diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index c04d5e38d6..2349728804 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,5 +1,3 @@ -Before writing an issue, please make sure you're talking about the native application (called Rocket.Chat+ in the App Store) and not the Cordova one (called Rocket.Chat in the App Store). If you are looking to open an issue to the Cordova application, go to this URL: https://github.com/RocketChat/Rocket.Chat.Cordova. - - Your Rocket.Chat app version: #### - Your Rocket.Chat server version: #### - Device (or Simulator) you're running with: #### diff --git a/.gitignore b/.gitignore index 3a7a925f02..bf5b79ee71 100644 --- a/.gitignore +++ b/.gitignore @@ -41,7 +41,7 @@ xcshareddata # you should judge for yourself, the pros and cons are mentioned at: # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control # -Pods/ +# Pods/ # Carthage # diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6da97eb53f..86855661e8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,48 +29,11 @@ _(NOTE: Steps 3 and 4 must be executed from project's directory)_ ``` git clone https://github.com/RocketChat/Rocket.Chat.iOS ``` -2. Install [Bundler](https://bundler.io) -``` -sudo gem install bundler -``` -To update _Bundler_ (when there is new version available) -``` -sudo gem update bundler -``` -3. Install all gem dependencies -``` -bundle install (sudo might be required in some cases) -``` -To update all gem dependencies (usually executed by maintainer) run -``` -bundle update -``` -To update pod's repository (in case of having those oudated compared to Podfile.lock and in case of `pod install` failure) -``` -bundle exec pod repo update -``` -4. Download library dependencies using the cocoapods dependency manager (and update the same way): -``` -bundle exec pod install -``` -5. Do NOT open the Xcode project directly, instead use the Rocket.Chat.xcworkspace file to open the Xcode workspace. -6. Build the project by ⌘ + R +2. Use the Rocket.Chat.xcworkspace file to open the Xcode workspace. +3. Build the project by ⌘ + R Also refer to [Guidelines](#project.pbxproj) for modifying files. -#### Alternative - -You can skip installing Bundler (not recommended) and just install [CocoaPods](https://cocoapods.org/) (note that you will need to install at least Ruby 2.2.3 for this to work). Make sure you have correct version of CocoaPods installed or you might be not able to build project properly. -``` -sudo gem install cocoapods -``` -Then you can call all the cocoapods actions without **bundle exe** command. - -To update cocoapods (not that often needed, you will be notified during `pod install` when new version is available) run. -``` -sudo gem update cocoapods -``` - ## Issues needing help Didn't found a bug or want a new feature not already reported? Check out [the issues with "help wanted"](https://github.com/RocketChat/Rocket.Chat.iOS/labels/help%20wanted) or other issues, for those no branch exists. diff --git a/Podfile b/Podfile index f68fd2163e..da211b4be9 100644 --- a/Podfile +++ b/Podfile @@ -1,6 +1,6 @@ source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '10.0' +platform :ios, '11.0' use_frameworks! inhibit_all_warnings! @@ -29,7 +29,7 @@ def shared_pods pod 'semver' # UI - pod 'SlackTextViewController', :git => 'https://github.com/rafaelks/SlackTextViewController.git' + pod 'RocketChatViewController', :git => 'https://github.com/RocketChat/RocketChatViewController' pod 'MobilePlayer', :git => 'https://github.com/RocketChat/RCiOSMobilePlayer' pod 'SimpleImageViewer', :git => 'https://github.com/cardoso/SimpleImageViewer.git' pod 'SwipeCellKit' @@ -51,12 +51,12 @@ def shared_pods pod 'OAuthSwift' pod '1PasswordExtension' + # DiffKit + diff_pods + # Debugging pod 'SwiftLint', :configurations => ['Debug'] pod 'FLEX', '~> 2.0', :configurations => ['Debug', 'Beta'] - - # Diffing - diff_pods end target 'Rocket.Chat.ShareExtension' do @@ -67,12 +67,10 @@ target 'Rocket.Chat.ShareExtension' do end target 'Rocket.Chat' do - # Shared pods shared_pods end target 'Rocket.ChatTests' do - # Shared pods shared_pods end diff --git a/Podfile.lock b/Podfile.lock index da04a73d5b..0163286d30 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -1,78 +1,91 @@ PODS: - 1PasswordExtension (1.8.5) - - Crashlytics (3.10.7): - - Fabric (~> 1.7.11) - - DifferenceKit/Core (0.5.3) - - Fabric (1.7.11) - - Firebase/Core (5.8.0): + - Crashlytics (3.11.1): + - Fabric (~> 1.8.1) + - DifferenceKit (0.7.2): + - DifferenceKit/Core (= 0.7.2) + - DifferenceKit/UIKitExtension (= 0.7.2) + - DifferenceKit/Core (0.7.2) + - DifferenceKit/UIKitExtension (0.7.2): + - DifferenceKit/Core + - Fabric (1.8.2) + - Firebase/Core (5.12.0): - Firebase/CoreOnly - - FirebaseAnalytics (= 5.1.2) - - Firebase/CoreOnly (5.8.0): - - FirebaseCore (= 5.1.3) - - FirebaseAnalytics (5.1.2): + - FirebaseAnalytics (= 5.3.0) + - Firebase/CoreOnly (5.12.0): + - FirebaseCore (= 5.1.7) + - FirebaseAnalytics (5.3.0): - FirebaseCore (~> 5.1) - - FirebaseInstanceID (~> 3.2) - - GoogleAppMeasurement (~> 5.1) - - GoogleUtilities/AppDelegateSwizzler (~> 5.2.0) - - GoogleUtilities/MethodSwizzler (~> 5.2.0) + - FirebaseInstanceID (~> 3.3) + - GoogleAppMeasurement (~> 5.3) + - GoogleUtilities/AppDelegateSwizzler (~> 5.2) + - GoogleUtilities/MethodSwizzler (~> 5.2) - GoogleUtilities/Network (~> 5.2) - "GoogleUtilities/NSData+zlib (~> 5.2)" - nanopb (~> 0.3) - - FirebaseCore (5.1.3): + - FirebaseCore (5.1.7): - GoogleUtilities/Logger (~> 5.2) - - FirebaseInstanceID (3.2.1): + - FirebaseInstanceID (3.3.0): - FirebaseCore (~> 5.1) - - GoogleUtilities/Environment (~> 5.2) + - GoogleUtilities/Environment (~> 5.3) + - GoogleUtilities/UserDefaults (~> 5.3) - FLAnimatedImage (1.0.12) - FLEX (2.4.0) - - GoogleAppMeasurement (5.1.2): - - GoogleUtilities/AppDelegateSwizzler (~> 5.2.0) - - GoogleUtilities/MethodSwizzler (~> 5.2.0) + - GoogleAppMeasurement (5.3.0): + - GoogleUtilities/AppDelegateSwizzler (~> 5.2) + - GoogleUtilities/MethodSwizzler (~> 5.2) - GoogleUtilities/Network (~> 5.2) - "GoogleUtilities/NSData+zlib (~> 5.2)" - nanopb (~> 0.3) - - GoogleUtilities/AppDelegateSwizzler (5.2.3): + - GoogleUtilities/AppDelegateSwizzler (5.3.4): - GoogleUtilities/Environment - GoogleUtilities/Logger - GoogleUtilities/Network - - GoogleUtilities/Environment (5.2.3) - - GoogleUtilities/Logger (5.2.3): + - GoogleUtilities/Environment (5.3.4) + - GoogleUtilities/Logger (5.3.4): - GoogleUtilities/Environment - - GoogleUtilities/MethodSwizzler (5.2.3): + - GoogleUtilities/MethodSwizzler (5.3.4): - GoogleUtilities/Logger - - GoogleUtilities/Network (5.2.3): + - GoogleUtilities/Network (5.3.4): - GoogleUtilities/Logger - "GoogleUtilities/NSData+zlib" - GoogleUtilities/Reachability - - "GoogleUtilities/NSData+zlib (5.2.3)" - - GoogleUtilities/Reachability (5.2.3): + - "GoogleUtilities/NSData+zlib (5.3.4)" + - GoogleUtilities/Reachability (5.3.4): + - GoogleUtilities/Logger + - GoogleUtilities/UserDefaults (5.3.4): - GoogleUtilities/Logger - MBProgressHUD (1.1.0) - MobilePlayer (1.2.0) - - nanopb (0.3.8): - - nanopb/decode (= 0.3.8) - - nanopb/encode (= 0.3.8) - - nanopb/decode (0.3.8) - - nanopb/encode (0.3.8) - - Nuke (7.3.2) - - Nuke-FLAnimatedImage-Plugin (5.0): + - nanopb (0.3.901): + - nanopb/decode (= 0.3.901) + - nanopb/encode (= 0.3.901) + - nanopb/decode (0.3.901) + - nanopb/encode (0.3.901) + - Nuke (7.5.1) + - Nuke-FLAnimatedImage-Plugin (6.0): - FLAnimatedImage (~> 1.0) - - Nuke (~> 7.0) + - Nuke (~> 7.5) - OAuthSwift (1.2.2) - RCMarkdownParser (3.0.6) - ReachabilitySwift (4.2.1) - - Realm (3.9.0): - - Realm/Headers (= 3.9.0) - - Realm/Headers (3.9.0) - - RealmSwift (3.9.0): - - Realm (= 3.9.0) + - Realm (3.11.1): + - Realm/Headers (= 3.11.1) + - Realm/Headers (3.11.1) + - RealmSwift (3.11.1): + - Realm (= 3.11.1) + - RocketChatViewController (0.1.0): + - RocketChatViewController/Composer (= 0.1.0) + - RocketChatViewController/ViewController (= 0.1.0) + - RocketChatViewController/Composer (0.1.0) + - RocketChatViewController/ViewController (0.1.0): + - DifferenceKit (~> 0.7.2) - semver (1.1.0) - SimpleImageViewer (1.2.0): - FLAnimatedImage - - SlackTextViewController (1.9.6) - Starscream (2.1.1) - SwiftLint (0.27.0) - - SwiftyJSON (4.1.0) + - SwiftyJSON (4.2.0) - SwipeCellKit (2.5.0) DEPENDENCIES: @@ -90,9 +103,9 @@ DEPENDENCIES: - RCMarkdownParser (from `https://github.com/RocketChat/RCMarkdownParser.git`) - ReachabilitySwift - RealmSwift + - RocketChatViewController (from `https://github.com/RocketChat/RocketChatViewController`) - semver - SimpleImageViewer (from `https://github.com/cardoso/SimpleImageViewer.git`) - - SlackTextViewController (from `https://github.com/rafaelks/SlackTextViewController.git`) - Starscream (~> 2) - SwiftLint - SwiftyJSON @@ -131,10 +144,10 @@ EXTERNAL SOURCES: :git: https://github.com/RocketChat/RCiOSMobilePlayer RCMarkdownParser: :git: https://github.com/RocketChat/RCMarkdownParser.git + RocketChatViewController: + :git: https://github.com/RocketChat/RocketChatViewController SimpleImageViewer: :git: https://github.com/cardoso/SimpleImageViewer.git - SlackTextViewController: - :git: https://github.com/rafaelks/SlackTextViewController.git CHECKOUT OPTIONS: MobilePlayer: @@ -143,44 +156,44 @@ CHECKOUT OPTIONS: RCMarkdownParser: :commit: c34d9ccef689c55b9eae69f3c65283da8d8b0c6c :git: https://github.com/RocketChat/RCMarkdownParser.git + RocketChatViewController: + :commit: 723f1a6857f8d49af11e582dbb7077a99c28cb78 + :git: https://github.com/RocketChat/RocketChatViewController SimpleImageViewer: :commit: 8222c338de0f285ca0c2d556c5d8dedd4a365b52 :git: https://github.com/cardoso/SimpleImageViewer.git - SlackTextViewController: - :commit: 944b7cc4de734638cdefdecb9c7d7846fc3ab252 - :git: https://github.com/rafaelks/SlackTextViewController.git SPEC CHECKSUMS: 1PasswordExtension: 0e95bdea64ec8ff2f4f693be5467a09fac42a83d - Crashlytics: ccaac42660eb9351b9960c0d66106b0bcf99f4fa - DifferenceKit: 2037137305c55a39ff729baa72697efa30b1052d - Fabric: f233c9492b3bbc1f04e3882986740f7988a58edb - Firebase: 25812f43e7a53b11ae2f0a5f4c6d12faeb1f7cd7 - FirebaseAnalytics: df15839e9c6ca6bd14d2e8ab6b0c672e6c49097e - FirebaseCore: 27bd80e5bfaaf9552a1f5cacb4c7e8bb925bab22 - FirebaseInstanceID: ea5af6920d0a4a29b40459d055bebe4a6c1333c4 + Crashlytics: ca7ab4bc304aa216bdc2e4c1a96389ee77252203 + DifferenceKit: 5179eaf0e76a1b9fbaeb93f4c1a82510be63ca65 + Fabric: d2b22f443ba195d8a7cc204da230977c72733b40 + Firebase: 9190018e296139d938b99521cde0c15a6e8d2946 + FirebaseAnalytics: 63202d2665de4e6adcbdce189135255d8b5962ba + FirebaseCore: 027d350adc039aa5483357c6f56556f117c5170e + FirebaseInstanceID: e2fa4cb35ef5558c200f7f0ad8a53e212215f93e FLAnimatedImage: 4a0b56255d9b05f18b6dd7ee06871be5d3b89e31 FLEX: bd1a39e55b56bb413b6f1b34b3c10a0dc44ef079 - GoogleAppMeasurement: fc4a4c3fe0144db9313cbf443ffe62e6b1d6268c - GoogleUtilities: 6f681e27050c5e130325e89fa0316dfca826f954 + GoogleAppMeasurement: 5029d78f2b438bd30ffb44e6c558b57c21622727 + GoogleUtilities: abb092d2c12e817fa3e0e7b274987dd72fb86ec3 MBProgressHUD: e7baa36a220447d8aeb12769bf0585582f3866d9 MobilePlayer: 069b13482499f14c25b6ce53f63a91e17975b073 - nanopb: 5601e6bca2dbf1ed831b519092ec110f66982ca3 - Nuke: a9a31bbd6c6723753ab024ef22057dcaaf046c1b - Nuke-FLAnimatedImage-Plugin: 6dfb9335ce298eaff9fdfed8d20d1bbfb2a6c326 + nanopb: 2901f78ea1b7b4015c860c2fdd1ea2fee1a18d48 + Nuke: 3814db501e55f17951451839c726ffd91641e9a5 + Nuke-FLAnimatedImage-Plugin: e4c39d13061a08ac0bdcb0cd7a23882f4a43f4a6 OAuthSwift: 27b34fe80b76b67cd8f45571e0be2432bc9f6de1 RCMarkdownParser: 518b616a4f48bb02247243544d4fd55c048288a4 ReachabilitySwift: 35720ffea59c1c76d15f885be77fd33e33985427 - Realm: 3d36f208bf3aff8335dc3298742140182bde4edb - RealmSwift: aa4d11917bfcfaa3ed51f219102a487ecd895447 + Realm: 037c5919b9ceb59d6beed5d3b031096856b119b3 + RealmSwift: c9580133e73ef40ed340401af2dbc9a5790dfea7 + RocketChatViewController: 00d436e393ac0bd0a62bc72d9a35a9043fc3f3a5 semver: 11ae3bc4a6036efbc86b5863ef5fa32c065c8bbd SimpleImageViewer: 6ed0d2acf7c166a5b4e795bccc7b9ea1b225ff9b - SlackTextViewController: b854e62c1c156336bc4fd409c6ca79b5773e8f9d Starscream: 142bd8ef24592d985daee9fa48c936070b85b15f SwiftLint: 3207c1faa2240bf8973b191820a116113cd11073 - SwiftyJSON: c29297daf073d2aa016295d5809cdd68045c39b3 + SwiftyJSON: c4bcba26dd9ec7a027fc8eade48e2c911f229e96 SwipeCellKit: d8f2617538ce3021cb0a11d1b93856a06a2f2e20 -PODFILE CHECKSUM: 6b8602cb3bfdb2d5969e91f6f161923d47884c5c +PODFILE CHECKSUM: 5d62982fe6d8cd234f28edafc23b27595439d854 COCOAPODS: 1.5.3 diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/Contents.json b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/Contents.json new file mode 100644 index 0000000000..8739f6c6be --- /dev/null +++ b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x", + "filename" : "onepassword-button-light.png" + }, + { + "idiom" : "universal", + "scale" : "2x", + "filename" : "onepassword-button-light@2x.png" + }, + { + "idiom" : "universal", + "scale" : "3x", + "filename" : "onepassword-button-light@3x.png" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/onepassword-button-light.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/onepassword-button-light.png new file mode 100644 index 0000000000..6f4b019ea5 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/onepassword-button-light.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/onepassword-button-light@2x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/onepassword-button-light@2x.png new file mode 100644 index 0000000000..2257425a68 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/onepassword-button-light@2x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/onepassword-button-light@3x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/onepassword-button-light@3x.png new file mode 100644 index 0000000000..95bf09fc90 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.imageset/onepassword-button-light@3x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.pdf new file mode 100644 index 0000000000..504d31c22b Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button-light.pdf differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/Contents.json b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/Contents.json new file mode 100644 index 0000000000..50b11e9b40 --- /dev/null +++ b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x", + "filename" : "onepassword-button.png" + }, + { + "idiom" : "universal", + "scale" : "2x", + "filename" : "onepassword-button@2x.png" + }, + { + "idiom" : "universal", + "scale" : "3x", + "filename" : "onepassword-button@3x.png" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/onepassword-button.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/onepassword-button.png new file mode 100644 index 0000000000..05d6cf999d Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/onepassword-button.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/onepassword-button@2x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/onepassword-button@2x.png new file mode 100644 index 0000000000..8de12de933 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/onepassword-button@2x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/onepassword-button@3x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/onepassword-button@3x.png new file mode 100644 index 0000000000..749ff2fe3f Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.imageset/onepassword-button@3x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.pdf new file mode 100644 index 0000000000..4f88b80093 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-button.pdf differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/Contents.json b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/Contents.json new file mode 100644 index 0000000000..84b28a5bd0 --- /dev/null +++ b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/Contents.json @@ -0,0 +1,33 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "1x", + "filename" : "onepassword-extension-light~compact.png" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "filename" : "onepassword-extension-light@2x~compact.png" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "filename" : "onepassword-extension-light@3x~compact.png" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "filename" : "onepassword-extension-light~regular.png" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "filename" : "onepassword-extension-light@2x~regular.png" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light@2x~compact.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light@2x~compact.png new file mode 100644 index 0000000000..6bcb6bba39 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light@2x~compact.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light@2x~regular.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light@2x~regular.png new file mode 100644 index 0000000000..80cf2647d8 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light@2x~regular.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light@3x~compact.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light@3x~compact.png new file mode 100644 index 0000000000..6e23d542d6 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light@3x~compact.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light~compact.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light~compact.png new file mode 100644 index 0000000000..267adcb537 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light~compact.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light~regular.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light~regular.png new file mode 100644 index 0000000000..a4d070329c Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light.imageset/onepassword-extension-light~regular.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light~compact.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light~compact.pdf new file mode 100644 index 0000000000..d749244e33 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light~compact.pdf differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light~regular.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light~regular.pdf new file mode 100644 index 0000000000..ebacc0051f Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension-light~regular.pdf differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/Contents.json b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/Contents.json new file mode 100644 index 0000000000..475ac081e4 --- /dev/null +++ b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/Contents.json @@ -0,0 +1,33 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "1x", + "filename" : "onepassword-extension~compact.png" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "filename" : "onepassword-extension@2x~compact.png" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "filename" : "onepassword-extension@3x~compact.png" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "filename" : "onepassword-extension~regular.png" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "filename" : "onepassword-extension@2x~regular.png" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension@2x~compact.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension@2x~compact.png new file mode 100644 index 0000000000..1fa632776e Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension@2x~compact.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension@2x~regular.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension@2x~regular.png new file mode 100644 index 0000000000..0e2dc61284 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension@2x~regular.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension@3x~compact.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension@3x~compact.png new file mode 100644 index 0000000000..fe7b3a5f18 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension@3x~compact.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension~compact.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension~compact.png new file mode 100644 index 0000000000..260b227a09 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension~compact.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension~regular.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension~regular.png new file mode 100644 index 0000000000..304e03f83d Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension.imageset/onepassword-extension~regular.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension~compact.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension~compact.pdf new file mode 100644 index 0000000000..83eb836dd3 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension~compact.pdf differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension~regular.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension~regular.pdf new file mode 100644 index 0000000000..e291d7acc4 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-extension~regular.pdf differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/Contents.json b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/Contents.json new file mode 100644 index 0000000000..73390e8edc --- /dev/null +++ b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x", + "filename" : "onepassword-navbar-light.png" + }, + { + "idiom" : "universal", + "scale" : "2x", + "filename" : "onepassword-navbar-light@2x.png" + }, + { + "idiom" : "universal", + "scale" : "3x", + "filename" : "onepassword-navbar-light@3x.png" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/onepassword-navbar-light.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/onepassword-navbar-light.png new file mode 100644 index 0000000000..2f67ddf32d Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/onepassword-navbar-light.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/onepassword-navbar-light@2x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/onepassword-navbar-light@2x.png new file mode 100644 index 0000000000..c592f7f3a9 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/onepassword-navbar-light@2x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/onepassword-navbar-light@3x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/onepassword-navbar-light@3x.png new file mode 100644 index 0000000000..2721b74c6a Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.imageset/onepassword-navbar-light@3x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.pdf new file mode 100644 index 0000000000..c7c1d52cbb Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar-light.pdf differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/Contents.json b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/Contents.json new file mode 100644 index 0000000000..f8cd9027ae --- /dev/null +++ b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x", + "filename" : "onepassword-navbar.png" + }, + { + "idiom" : "universal", + "scale" : "2x", + "filename" : "onepassword-navbar@2x.png" + }, + { + "idiom" : "universal", + "scale" : "3x", + "filename" : "onepassword-navbar@3x.png" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/onepassword-navbar.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/onepassword-navbar.png new file mode 100644 index 0000000000..d20bc7dfd2 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/onepassword-navbar.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/onepassword-navbar@2x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/onepassword-navbar@2x.png new file mode 100644 index 0000000000..346dc97f9f Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/onepassword-navbar@2x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/onepassword-navbar@3x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/onepassword-navbar@3x.png new file mode 100644 index 0000000000..24b64962a7 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.imageset/onepassword-navbar@3x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.pdf new file mode 100644 index 0000000000..a9bd33d258 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-navbar.pdf differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/Contents.json b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/Contents.json new file mode 100644 index 0000000000..56607e7af4 --- /dev/null +++ b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x", + "filename" : "onepassword-toolbar-light.png" + }, + { + "idiom" : "universal", + "scale" : "2x", + "filename" : "onepassword-toolbar-light@2x.png" + }, + { + "idiom" : "universal", + "scale" : "3x", + "filename" : "onepassword-toolbar-light@3x.png" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/onepassword-toolbar-light.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/onepassword-toolbar-light.png new file mode 100644 index 0000000000..38c71234d4 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/onepassword-toolbar-light.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/onepassword-toolbar-light@2x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/onepassword-toolbar-light@2x.png new file mode 100644 index 0000000000..9848373298 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/onepassword-toolbar-light@2x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/onepassword-toolbar-light@3x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/onepassword-toolbar-light@3x.png new file mode 100644 index 0000000000..3ec91b530d Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.imageset/onepassword-toolbar-light@3x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.pdf new file mode 100644 index 0000000000..5495bd6ae4 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar-light.pdf differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/Contents.json b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/Contents.json new file mode 100644 index 0000000000..af5f4f8f2c --- /dev/null +++ b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x", + "filename" : "onepassword-toolbar.png" + }, + { + "idiom" : "universal", + "scale" : "2x", + "filename" : "onepassword-toolbar@2x.png" + }, + { + "idiom" : "universal", + "scale" : "3x", + "filename" : "onepassword-toolbar@3x.png" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/onepassword-toolbar.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/onepassword-toolbar.png new file mode 100644 index 0000000000..27a3ca9e3b Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/onepassword-toolbar.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/onepassword-toolbar@2x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/onepassword-toolbar@2x.png new file mode 100644 index 0000000000..37b6601266 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/onepassword-toolbar@2x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/onepassword-toolbar@3x.png b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/onepassword-toolbar@3x.png new file mode 100644 index 0000000000..dbf308ace3 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.imageset/onepassword-toolbar@3x.png differ diff --git a/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.pdf b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.pdf new file mode 100644 index 0000000000..520eb98bc4 Binary files /dev/null and b/Pods/1PasswordExtension/1Password.xcassets/onepassword-toolbar.pdf differ diff --git a/Pods/1PasswordExtension/LICENSE.txt b/Pods/1PasswordExtension/LICENSE.txt new file mode 100644 index 0000000000..fbe2df3c89 --- /dev/null +++ b/Pods/1PasswordExtension/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2014 AgileBits Inc. + +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. \ No newline at end of file diff --git a/Pods/1PasswordExtension/OnePasswordExtension.h b/Pods/1PasswordExtension/OnePasswordExtension.h new file mode 100644 index 0000000000..25d63dc838 --- /dev/null +++ b/Pods/1PasswordExtension/OnePasswordExtension.h @@ -0,0 +1,210 @@ +// +// 1Password Extension +// +// Lovingly handcrafted by Dave Teare, Michael Fey, Rad Azzouz, and Roustem Karimov. +// Copyright (c) 2014 AgileBits. All rights reserved. +// + +#import +#import +#import + +#ifdef __IPHONE_8_0 +#import +#endif + +#if __has_feature(nullability) +NS_ASSUME_NONNULL_BEGIN +#else +#define nullable +#define __nullable +#define nonnull +#define __nonnull +#endif + +// Login Dictionary keys - Used to get or set the properties of a 1Password Login +#define AppExtensionURLStringKey @"url_string" +#define AppExtensionUsernameKey @"username" +#define AppExtensionPasswordKey @"password" +#define AppExtensionTOTPKey @"totp" +#define AppExtensionTitleKey @"login_title" +#define AppExtensionNotesKey @"notes" +#define AppExtensionSectionTitleKey @"section_title" +#define AppExtensionFieldsKey @"fields" +#define AppExtensionReturnedFieldsKey @"returned_fields" +#define AppExtensionOldPasswordKey @"old_password" +#define AppExtensionPasswordGeneratorOptionsKey @"password_generator_options" + +// Password Generator options - Used to set the 1Password Password Generator options when saving a new Login or when changing the password for for an existing Login +#define AppExtensionGeneratedPasswordMinLengthKey @"password_min_length" +#define AppExtensionGeneratedPasswordMaxLengthKey @"password_max_length" +#define AppExtensionGeneratedPasswordRequireDigitsKey @"password_require_digits" +#define AppExtensionGeneratedPasswordRequireSymbolsKey @"password_require_symbols" +#define AppExtensionGeneratedPasswordForbiddenCharactersKey @"password_forbidden_characters" + +// Errors codes +#define AppExtensionErrorDomain @"OnePasswordExtension" + +#define AppExtensionErrorCodeCancelledByUser 0 +#define AppExtensionErrorCodeAPINotAvailable 1 +#define AppExtensionErrorCodeFailedToContactExtension 2 +#define AppExtensionErrorCodeFailedToLoadItemProviderData 3 +#define AppExtensionErrorCodeCollectFieldsScriptFailed 4 +#define AppExtensionErrorCodeFillFieldsScriptFailed 5 +#define AppExtensionErrorCodeUnexpectedData 6 +#define AppExtensionErrorCodeFailedToObtainURLStringFromWebView 7 + +// Note to creators of libraries or frameworks: +// If you include this code within your library, then to prevent potential duplicate symbol +// conflicts for adopters of your library, you should rename the OnePasswordExtension class +// and associated typedefs. You might to so by adding your own project prefix, e.g., +// MyLibraryOnePasswordExtension. + +typedef void (^OnePasswordLoginDictionaryCompletionBlock)(NSDictionary * __nullable loginDictionary, NSError * __nullable error); +typedef void (^OnePasswordSuccessCompletionBlock)(BOOL success, NSError * __nullable error); +typedef void (^OnePasswordExtensionItemCompletionBlock)(NSExtensionItem * __nullable extensionItem, NSError * __nullable error); + +@interface OnePasswordExtension : NSObject + ++ (OnePasswordExtension *)sharedExtension; + +/*! + @discussion Determines if the 1Password Extension is available. Allows you to only show the 1Password login button to those + that can use it. Of course, you could leave the button enabled and educate users about the virtues of strong, unique + passwords instead :) + + @return isAppExtensionAvailable Returns YES if any app that supports the generic `org-appextension-feature-password-management` feature is installed on the device. + */ +#ifdef __IPHONE_8_0 +- (BOOL)isAppExtensionAvailable NS_EXTENSION_UNAVAILABLE_IOS("Not available in an extension. Check if org-appextension-feature-password-management:// URL can be opened by the app."); +#else +- (BOOL)isAppExtensionAvailable; +#endif + +/*! + Called from your login page, this method will find all available logins for the given URLString. + + @discussion 1Password will show all matching Login for the naked domain of the given URLString. For example if the user has an item in your 1Password vault with "subdomain1.domain.com” as the website and another one with "subdomain2.domain.com”, and the URLString is "https://domain.com", 1Password will show both items. + + However, if no matching login is found for "https://domain.com", the 1Password Extension will display the "Show all Logins" button so that the user can search among all the Logins in the vault. This is especially useful when the user has a login for "https://olddomain.com". + + After the user selects a login, it is stored into an NSDictionary and given to your completion handler. Use the `Login Dictionary keys` above to + extract the needed information and update your UI. The completion block is guaranteed to be called on the main thread. + + @param URLString For the matching Logins in the 1Password vault. + + @param viewController The view controller from which the 1Password Extension is invoked. Usually `self` + + @param sender The sender which triggers the share sheet to show. UIButton, UIBarButtonItem or UIView. Can also be nil on iPhone, but not on iPad. + + @param completion A completion block called with two parameters loginDictionary and error once completed. The loginDictionary reply parameter that contains the username, password and the One-Time Password if available. The error Reply parameter that is nil if the 1Password Extension has been successfully completed, or it contains error information about the completion failure. + */ +- (void)findLoginForURLString:(nonnull NSString *)URLString forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender completion:(nonnull OnePasswordLoginDictionaryCompletionBlock)completion; + +/*! + Create a new login within 1Password and allow the user to generate a new password before saving. + + @discussion The provided URLString should be unique to your app or service and be identical to what you pass into the find login method. + The completion block is guaranteed to be called on the main + thread. + + @param URLString For the new Login to be saved in 1Password. + + @param loginDetailsDictionary about the Login to be saved, including custom fields, are stored in an dictionary and given to the 1Password Extension. + + @param passwordGenerationOptions The Password generator options represented in a dictionary form. + + @param viewController The view controller from which the 1Password Extension is invoked. Usually `self` + + @param sender The sender which triggers the share sheet to show. UIButton, UIBarButtonItem or UIView. Can also be nil on iPhone, but not on iPad. + + @param completion A completion block which is called with type parameters loginDictionary and error. The loginDictionary reply parameter which contain all the information about the newly saved Login. Use the `Login Dictionary keys` above to extract the needed information and update your UI. For example, updating the UI with the newly generated password lets the user know their action was successful. The error reply parameter that is nil if the 1Password Extension has been successfully completed, or it contains error information about the completion failure. + */ +- (void)storeLoginForURLString:(nonnull NSString *)URLString loginDetails:(nullable NSDictionary *)loginDetailsDictionary passwordGenerationOptions:(nullable NSDictionary *)passwordGenerationOptions forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender completion:(nonnull OnePasswordLoginDictionaryCompletionBlock)completion; + +/*! + Change the password for an existing login within 1Password. + + @discussion The provided URLString should be unique to your app or service and be identical to what you pass into the find login method. The completion block is guaranteed to be called on the main thread. + + 1Password 6 and later: + The 1Password Extension will display all available the matching Logins for the given URL string. The user can choose which Login item to update. The "New Login" button will also be available at all times, in case the user wishes to to create a new Login instead, + + 1Password 5: + These are the three scenarios that are supported: + 1. A single matching Login is found: 1Password will enter edit mode for that Login and will update its password using the value for AppExtensionPasswordKey. + 2. More than a one matching Logins are found: 1Password will display a list of all matching Logins. The user must choose which one to update. Once in edit mode, the Login will be updated with the new password. + 3. No matching login is found: 1Password will create a new Login using the optional fields if available to populate its properties. + + @param URLString for the Login to be updated with a new password in 1Password. + + @param loginDetailsDictionary about the Login to be saved, including old password and the username, are stored in an dictionary and given to the 1Password Extension. + + @param passwordGenerationOptions The Password generator options epresented in a dictionary form. + + @param viewController The view controller from which the 1Password Extension is invoked. Usually `self` + + @param sender The sender which triggers the share sheet to show. UIButton, UIBarButtonItem or UIView. Can also be nil on iPhone, but not on iPad. + + @param completion A completion block which is called with type parameters loginDictionary and error. The loginDictionary reply parameter which contain all the information about the newly updated Login, including the newly generated and the old password. Use the `Login Dictionary keys` above to extract the needed information and update your UI. For example, updating the UI with the newly generated password lets the user know their action was successful. The error reply parameter that is nil if the 1Password Extension has been successfully completed, or it contains error information about the completion failure. + */ +- (void)changePasswordForLoginForURLString:(nonnull NSString *)URLString loginDetails:(nullable NSDictionary *)loginDetailsDictionary passwordGenerationOptions:(nullable NSDictionary *)passwordGenerationOptions forViewController:(UIViewController *)viewController sender:(nullable id)sender completion:(nonnull OnePasswordLoginDictionaryCompletionBlock)completion; + +/*! + Called from your web view controller, this method will show all the saved logins for the active page in the provided web + view, and automatically fill the HTML form fields. Supports both WKWebView and UIWebView. + + @discussion 1Password will show all matching Login for the naked domain of the current website. For example if the user has an item in your 1Password vault with "subdomain1.domain.com” as the website and another one with "subdomain2.domain.com”, and the current website is "https://domain.com", 1Password will show both items. + + However, if no matching login is found for "https://domain.com", the 1Password Extension will display the "New Login" button so that the user can create a new Login for the current website. + + @param webView The web view which displays the form to be filled. The active UIWebView Or WKWebView. Must not be nil. + + @param viewController The view controller from which the 1Password Extension is invoked. Usually `self` + + @param sender The sender which triggers the share sheet to show. UIButton, UIBarButtonItem or UIView. Can also be nil on iPhone, but not on iPad. + + @param yesOrNo Boolean flag. If YES is passed only matching Login items will be shown, otherwise the 1Password Extension will also display Credit Cards and Identities. + + @param completion Completion block called on completion with parameters success, and error. The success reply parameter that is YES if the 1Password Extension has been successfully completed or NO otherwise. The error reply parameter that is nil if the 1Password Extension has been successfully completed, or it contains error information about the completion failure. + */ +- (void)fillItemIntoWebView:(nonnull id)webView forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender showOnlyLogins:(BOOL)yesOrNo completion:(nonnull OnePasswordSuccessCompletionBlock)completion; + +/*! + Called in the UIActivityViewController completion block to find out whether or not the user selected the 1Password Extension activity. + + @param activityType or the bundle identidier of the selected activity in the share sheet. + + @return isOnePasswordExtensionActivityType Returns YES if the selected activity is the 1Password extension, NO otherwise. + */ +- (BOOL)isOnePasswordExtensionActivityType:(nullable NSString *)activityType; + +/*! + The returned NSExtensionItem can be used to create your own UIActivityViewController. Use `isOnePasswordExtensionActivityType:` and `fillReturnedItems:intoWebView:completion:` in the activity view controller completion block to process the result. The completion block is guaranteed to be called on the main thread. + + @param webView The web view which displays the form to be filled. The active UIWebView Or WKWebView. Must not be nil. + + @param completion Completion block called on completion with extensionItem and error. The extensionItem reply parameter that is contains all the info required by the 1Password extension if has been successfully completed or nil otherwise. The error reply parameter that is nil if the 1Password extension item has been successfully created, or it contains error information about the completion failure. + */ +- (void)createExtensionItemForWebView:(nonnull id)webView completion:(nonnull OnePasswordExtensionItemCompletionBlock)completion; + +/*! + Method used in the UIActivityViewController completion block to fill information into a web view. + + @param returnedItems Array which contains the selected activity in the share sheet. Empty array if the share sheet is cancelled by the user. + @param webView The web view which displays the form to be filled. The active UIWebView Or WKWebView. Must not be nil. + + @param completion Completion block called on completion with parameters success, and error. The success reply parameter that is YES if the 1Password Extension has been successfully completed or NO otherwise. The error reply parameter that is nil if the 1Password Extension has been successfully completed, or it contains error information about the completion failure. + */ +- (void)fillReturnedItems:(nullable NSArray *)returnedItems intoWebView:(nonnull id)webView completion:(nonnull OnePasswordSuccessCompletionBlock)completion; + +/*! + Deprecated in version 1.5 + @see Use fillItemIntoWebView:forViewController:sender:showOnlyLogins:completion: instead + */ +- (void)fillLoginIntoWebView:(nonnull id)webView forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender completion:(nonnull OnePasswordSuccessCompletionBlock)completion __attribute__((deprecated("Use fillItemIntoWebView:forViewController:sender:showOnlyLogins:completion: instead. Deprecated in version 1.5"))); +@end + +#if __has_feature(nullability) +NS_ASSUME_NONNULL_END +#endif diff --git a/Pods/1PasswordExtension/OnePasswordExtension.m b/Pods/1PasswordExtension/OnePasswordExtension.m new file mode 100644 index 0000000000..133f548428 --- /dev/null +++ b/Pods/1PasswordExtension/OnePasswordExtension.m @@ -0,0 +1,692 @@ +// +// 1Password Extension +// +// Lovingly handcrafted by Dave Teare, Michael Fey, Rad Azzouz, and Roustem Karimov. +// Copyright (c) 2014 AgileBits. All rights reserved. +// + +#import "OnePasswordExtension.h" + +// Version +#define VERSION_NUMBER @(185) +static NSString *const AppExtensionVersionNumberKey = @"version_number"; + +// Available App Extension Actions +static NSString *const kUTTypeAppExtensionFindLoginAction = @"org.appextension.find-login-action"; +static NSString *const kUTTypeAppExtensionSaveLoginAction = @"org.appextension.save-login-action"; +static NSString *const kUTTypeAppExtensionChangePasswordAction = @"org.appextension.change-password-action"; +static NSString *const kUTTypeAppExtensionFillWebViewAction = @"org.appextension.fill-webview-action"; +static NSString *const kUTTypeAppExtensionFillBrowserAction = @"org.appextension.fill-browser-action"; + +// WebView Dictionary keys +static NSString *const AppExtensionWebViewPageFillScript = @"fillScript"; +static NSString *const AppExtensionWebViewPageDetails = @"pageDetails"; + +@implementation OnePasswordExtension + +#pragma mark - Public Methods + ++ (OnePasswordExtension *)sharedExtension { + static dispatch_once_t onceToken; + static OnePasswordExtension *__sharedExtension; + + dispatch_once(&onceToken, ^{ + __sharedExtension = [OnePasswordExtension new]; + }); + + return __sharedExtension; +} + +- (BOOL)isAppExtensionAvailable { + if ([self isSystemAppExtensionAPIAvailable]) { + return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"org-appextension-feature-password-management://"]]; + } + + return NO; +} + +#pragma mark - Native app Login + +- (void)findLoginForURLString:(nonnull NSString *)URLString forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender completion:(nonnull OnePasswordLoginDictionaryCompletionBlock)completion { + NSAssert(URLString != nil, @"URLString must not be nil"); + NSAssert(viewController != nil, @"viewController must not be nil"); + + if (NO == [self isSystemAppExtensionAPIAvailable]) { + NSLog(@"Failed to findLoginForURLString, system API is not available"); + if (completion) { + completion(nil, [OnePasswordExtension systemAppExtensionAPINotAvailableError]); + } + + return; + } + +#ifdef __IPHONE_8_0 + NSDictionary *item = @{ AppExtensionVersionNumberKey: VERSION_NUMBER, AppExtensionURLStringKey: URLString }; + + UIActivityViewController *activityViewController = [self activityViewControllerForItem:item viewController:viewController sender:sender typeIdentifier:kUTTypeAppExtensionFindLoginAction]; + activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { + if (returnedItems.count == 0) { + NSError *error = nil; + if (activityError) { + NSLog(@"Failed to findLoginForURLString: %@", activityError); + error = [OnePasswordExtension failedToContactExtensionErrorWithActivityError:activityError]; + } + else { + error = [OnePasswordExtension extensionCancelledByUserError]; + } + + if (completion) { + completion(nil, error); + } + + return; + } + + [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *error) { + if (completion) { + completion(itemDictionary, error); + } + }]; + }; + + [viewController presentViewController:activityViewController animated:YES completion:nil]; +#endif +} + +#pragma mark - New User Registration + +- (void)storeLoginForURLString:(nonnull NSString *)URLString loginDetails:(nullable NSDictionary *)loginDetailsDictionary passwordGenerationOptions:(nullable NSDictionary *)passwordGenerationOptions forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender completion:(nonnull OnePasswordLoginDictionaryCompletionBlock)completion { + NSAssert(URLString != nil, @"URLString must not be nil"); + NSAssert(viewController != nil, @"viewController must not be nil"); + + if (NO == [self isSystemAppExtensionAPIAvailable]) { + NSLog(@"Failed to storeLoginForURLString, system API is not available"); + if (completion) { + completion(nil, [OnePasswordExtension systemAppExtensionAPINotAvailableError]); + } + + return; + } + + +#ifdef __IPHONE_8_0 + NSMutableDictionary *newLoginAttributesDict = [NSMutableDictionary new]; + newLoginAttributesDict[AppExtensionVersionNumberKey] = VERSION_NUMBER; + newLoginAttributesDict[AppExtensionURLStringKey] = URLString; + [newLoginAttributesDict addEntriesFromDictionary:loginDetailsDictionary]; + if (passwordGenerationOptions.count > 0) { + newLoginAttributesDict[AppExtensionPasswordGeneratorOptionsKey] = passwordGenerationOptions; + } + + UIActivityViewController *activityViewController = [self activityViewControllerForItem:newLoginAttributesDict viewController:viewController sender:sender typeIdentifier:kUTTypeAppExtensionSaveLoginAction]; + activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { + if (returnedItems.count == 0) { + NSError *error = nil; + if (activityError) { + NSLog(@"Failed to storeLoginForURLString: %@", activityError); + error = [OnePasswordExtension failedToContactExtensionErrorWithActivityError:activityError]; + } + else { + error = [OnePasswordExtension extensionCancelledByUserError]; + } + + if (completion) { + completion(nil, error); + } + + return; + } + + [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *error) { + if (completion) { + completion(itemDictionary, error); + } + }]; + }; + + [viewController presentViewController:activityViewController animated:YES completion:nil]; +#endif +} + +#pragma mark - Change Password + +- (void)changePasswordForLoginForURLString:(nonnull NSString *)URLString loginDetails:(nullable NSDictionary *)loginDetailsDictionary passwordGenerationOptions:(nullable NSDictionary *)passwordGenerationOptions forViewController:(UIViewController *)viewController sender:(nullable id)sender completion:(nonnull OnePasswordLoginDictionaryCompletionBlock)completion { + NSAssert(URLString != nil, @"URLString must not be nil"); + NSAssert(viewController != nil, @"viewController must not be nil"); + + if (NO == [self isSystemAppExtensionAPIAvailable]) { + NSLog(@"Failed to changePasswordForLoginWithUsername, system API is not available"); + if (completion) { + completion(nil, [OnePasswordExtension systemAppExtensionAPINotAvailableError]); + } + + return; + } + +#ifdef __IPHONE_8_0 + NSMutableDictionary *item = [NSMutableDictionary new]; + item[AppExtensionVersionNumberKey] = VERSION_NUMBER; + item[AppExtensionURLStringKey] = URLString; + [item addEntriesFromDictionary:loginDetailsDictionary]; + if (passwordGenerationOptions.count > 0) { + item[AppExtensionPasswordGeneratorOptionsKey] = passwordGenerationOptions; + } + + UIActivityViewController *activityViewController = [self activityViewControllerForItem:item viewController:viewController sender:sender typeIdentifier:kUTTypeAppExtensionChangePasswordAction]; + + activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { + if (returnedItems.count == 0) { + NSError *error = nil; + if (activityError) { + NSLog(@"Failed to changePasswordForLoginWithUsername: %@", activityError); + error = [OnePasswordExtension failedToContactExtensionErrorWithActivityError:activityError]; + } + else { + error = [OnePasswordExtension extensionCancelledByUserError]; + } + + if (completion) { + completion(nil, error); + } + + return; + } + + [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *error) { + if (completion) { + completion(itemDictionary, error); + } + }]; + }; + + [viewController presentViewController:activityViewController animated:YES completion:nil]; +#endif +} + +#pragma mark - Web View filling Support + +- (void)fillItemIntoWebView:(nonnull id)webView forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender showOnlyLogins:(BOOL)yesOrNo completion:(nonnull OnePasswordSuccessCompletionBlock)completion { + NSAssert(webView != nil, @"webView must not be nil"); + NSAssert(viewController != nil, @"viewController must not be nil"); + NSAssert([webView isKindOfClass:[UIWebView class]] || [webView isKindOfClass:[WKWebView class]], @"webView must be an instance of WKWebView or UIWebView."); + +#ifdef __IPHONE_8_0 + if ([webView isKindOfClass:[UIWebView class]]) { + [self fillItemIntoUIWebView:webView webViewController:viewController sender:(id)sender showOnlyLogins:yesOrNo completion:^(BOOL success, NSError *error) { + if (completion) { + completion(success, error); + } + }]; + } + #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 || ONE_PASSWORD_EXTENSION_ENABLE_WK_WEB_VIEW + else if ([webView isKindOfClass:[WKWebView class]]) { + [self fillItemIntoWKWebView:webView forViewController:viewController sender:(id)sender showOnlyLogins:yesOrNo completion:^(BOOL success, NSError *error) { + if (completion) { + completion(success, error); + } + }]; + } + #endif +#endif +} + +#pragma mark - Support for custom UIActivityViewControllers + +- (BOOL)isOnePasswordExtensionActivityType:(nullable NSString *)activityType { + return [@"com.agilebits.onepassword-ios.extension" isEqualToString:activityType] || [@"com.agilebits.beta.onepassword-ios.extension" isEqualToString:activityType]; +} + +- (void)createExtensionItemForWebView:(nonnull id)webView completion:(nonnull OnePasswordExtensionItemCompletionBlock)completion { + NSAssert(webView != nil, @"webView must not be nil"); + NSAssert([webView isKindOfClass:[UIWebView class]] || [webView isKindOfClass:[WKWebView class]], @"webView must be an instance of WKWebView or UIWebView."); + +#ifdef __IPHONE_8_0 + if ([webView isKindOfClass:[UIWebView class]]) { + UIWebView *uiWebView = (UIWebView *)webView; + NSString *collectedPageDetails = [uiWebView stringByEvaluatingJavaScriptFromString:OPWebViewCollectFieldsScript]; + + [self createExtensionItemForURLString:uiWebView.request.URL.absoluteString webPageDetails:collectedPageDetails completion:completion]; + } + #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 || ONE_PASSWORD_EXTENSION_ENABLE_WK_WEB_VIEW + else if ([webView isKindOfClass:[WKWebView class]]) { + WKWebView *wkWebView = (WKWebView *)webView; + [wkWebView evaluateJavaScript:OPWebViewCollectFieldsScript completionHandler:^(NSString *result, NSError *evaluateError) { + if (result == nil) { + NSLog(@"1Password Extension failed to collect web page fields: %@", evaluateError); + NSError *failedToCollectFieldsError = [OnePasswordExtension failedToCollectFieldsErrorWithUnderlyingError:evaluateError]; + if (completion) { + if ([NSThread isMainThread]) { + completion(nil, failedToCollectFieldsError); + } + else { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, failedToCollectFieldsError); + }); + } + } + + return; + } + + [self createExtensionItemForURLString:wkWebView.URL.absoluteString webPageDetails:result completion:completion]; + }]; + } + #endif +#endif +} + +- (void)fillReturnedItems:(nullable NSArray *)returnedItems intoWebView:(nonnull id)webView completion:(nonnull OnePasswordSuccessCompletionBlock)completion { + NSAssert(webView != nil, @"webView must not be nil"); + + if (returnedItems.count == 0) { + NSError *error = [OnePasswordExtension extensionCancelledByUserError]; + if (completion) { + completion(NO, error); + } + + return; + } + + [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *error) { + if (itemDictionary.count == 0) { + if (completion) { + completion(NO, error); + } + + return; + } + + NSString *fillScript = itemDictionary[AppExtensionWebViewPageFillScript]; + [self executeFillScript:fillScript inWebView:webView completion:^(BOOL success, NSError *executeFillScriptError) { + if (completion) { + completion(success, executeFillScriptError); + } + }]; + }]; +} + +#pragma mark - Private methods + +- (BOOL)isSystemAppExtensionAPIAvailable { +#ifdef __IPHONE_8_0 + return [NSExtensionItem class] != nil; +#else + return NO; +#endif +} + +- (void)findLoginIn1PasswordWithURLString:(nonnull NSString *)URLString collectedPageDetails:(nullable NSString *)collectedPageDetails forWebViewController:(nonnull UIViewController *)forViewController sender:(nullable id)sender withWebView:(nonnull id)webView showOnlyLogins:(BOOL)yesOrNo completion:(nonnull OnePasswordSuccessCompletionBlock)completion { + if ([URLString length] == 0) { + NSError *URLStringError = [OnePasswordExtension failedToObtainURLStringFromWebViewError]; + NSLog(@"Failed to findLoginIn1PasswordWithURLString: %@", URLStringError); + if (completion) { + completion(NO, URLStringError); + } + return; + } + + NSError *jsonError = nil; + NSData *data = [collectedPageDetails dataUsingEncoding:NSUTF8StringEncoding]; + NSDictionary *collectedPageDetailsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError]; + + if (collectedPageDetailsDictionary.count == 0) { + NSLog(@"Failed to parse JSON collected page details: %@", jsonError); + if (completion) { + completion(NO, jsonError); + } + return; + } + + NSDictionary *item = @{ AppExtensionVersionNumberKey : VERSION_NUMBER, AppExtensionURLStringKey : URLString, AppExtensionWebViewPageDetails : collectedPageDetailsDictionary }; + + NSString *typeIdentifier = yesOrNo ? kUTTypeAppExtensionFillWebViewAction : kUTTypeAppExtensionFillBrowserAction; + UIActivityViewController *activityViewController = [self activityViewControllerForItem:item viewController:forViewController sender:sender typeIdentifier:typeIdentifier]; + activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { + if (returnedItems.count == 0) { + NSError *error = nil; + if (activityError) { + NSLog(@"Failed to findLoginIn1PasswordWithURLString: %@", activityError); + error = [OnePasswordExtension failedToContactExtensionErrorWithActivityError:activityError]; + } + else { + error = [OnePasswordExtension extensionCancelledByUserError]; + } + + if (completion) { + completion(NO, error); + } + + return; + } + + [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *processExtensionItemError) { + if (itemDictionary.count == 0) { + if (completion) { + completion(NO, processExtensionItemError); + } + + return; + } + + NSString *fillScript = itemDictionary[AppExtensionWebViewPageFillScript]; + [self executeFillScript:fillScript inWebView:webView completion:^(BOOL success, NSError *executeFillScriptError) { + if (completion) { + completion(success, executeFillScriptError); + } + }]; + }]; + }; + + [forViewController presentViewController:activityViewController animated:YES completion:nil]; +} + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 || ONE_PASSWORD_EXTENSION_ENABLE_WK_WEB_VIEW +- (void)fillItemIntoWKWebView:(nonnull WKWebView *)webView forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender showOnlyLogins:(BOOL)yesOrNo completion:(nonnull OnePasswordSuccessCompletionBlock)completion { + [webView evaluateJavaScript:OPWebViewCollectFieldsScript completionHandler:^(NSString *result, NSError *error) { + if (result == nil) { + NSLog(@"1Password Extension failed to collect web page fields: %@", error); + if (completion) { + completion(NO,[OnePasswordExtension failedToCollectFieldsErrorWithUnderlyingError:error]); + } + + return; + } + + [self findLoginIn1PasswordWithURLString:webView.URL.absoluteString collectedPageDetails:result forWebViewController:viewController sender:sender withWebView:webView showOnlyLogins:yesOrNo completion:^(BOOL success, NSError *findLoginError) { + if (completion) { + completion(success, findLoginError); + } + }]; + }]; +} +#endif + +- (void)fillItemIntoUIWebView:(nonnull UIWebView *)webView webViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender showOnlyLogins:(BOOL)yesOrNo completion:(nonnull OnePasswordSuccessCompletionBlock)completion { + NSString *collectedPageDetails = [webView stringByEvaluatingJavaScriptFromString:OPWebViewCollectFieldsScript]; + [self findLoginIn1PasswordWithURLString:webView.request.URL.absoluteString collectedPageDetails:collectedPageDetails forWebViewController:viewController sender:sender withWebView:webView showOnlyLogins:yesOrNo completion:^(BOOL success, NSError *error) { + if (completion) { + completion(success, error); + } + }]; +} + +- (void)executeFillScript:(NSString * __nullable)fillScript inWebView:(nonnull id)webView completion:(nonnull OnePasswordSuccessCompletionBlock)completion { + + if (fillScript == nil) { + NSLog(@"Failed to executeFillScript, fillScript is missing"); + if (completion) { + completion(NO, [OnePasswordExtension failedToFillFieldsErrorWithLocalizedErrorMessage:NSLocalizedStringFromTable(@"Failed to fill web page because script is missing", @"OnePasswordExtension", @"1Password Extension Error Message") underlyingError:nil]); + } + + return; + } + + NSMutableString *scriptSource = [OPWebViewFillScript mutableCopy]; + [scriptSource appendFormat:@"(document, %@, undefined);", fillScript]; + +#ifdef __IPHONE_8_0 + if ([webView isKindOfClass:[UIWebView class]]) { + NSString *result = [((UIWebView *)webView) stringByEvaluatingJavaScriptFromString:scriptSource]; + BOOL success = (result != nil); + NSError *error = nil; + + if (!success) { + NSLog(@"Cannot executeFillScript, stringByEvaluatingJavaScriptFromString failed"); + error = [OnePasswordExtension failedToFillFieldsErrorWithLocalizedErrorMessage:NSLocalizedStringFromTable(@"Failed to fill web page because script could not be evaluated", @"OnePasswordExtension", @"1Password Extension Error Message") underlyingError:nil]; + } + + if (completion) { + completion(success, error); + } + } + + #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 || ONE_PASSWORD_EXTENSION_ENABLE_WK_WEB_VIEW + else if ([webView isKindOfClass:[WKWebView class]]) { + [((WKWebView *)webView) evaluateJavaScript:scriptSource completionHandler:^(NSString *result, NSError *evaluationError) { + BOOL success = (result != nil); + NSError *error = nil; + + if (!success) { + NSLog(@"Cannot executeFillScript, evaluateJavaScript failed: %@", evaluationError); + error = [OnePasswordExtension failedToFillFieldsErrorWithLocalizedErrorMessage:NSLocalizedStringFromTable(@"Failed to fill web page because script could not be evaluated", @"OnePasswordExtension", @"1Password Extension Error Message") underlyingError:error]; + } + + if (completion) { + completion(success, error); + } + }]; + } + #endif +#endif +} + +#ifdef __IPHONE_8_0 +- (void)processExtensionItem:(nullable NSExtensionItem *)extensionItem completion:(nonnull OnePasswordLoginDictionaryCompletionBlock)completion { + if (extensionItem.attachments.count == 0) { + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: @"Unexpected data returned by App Extension: extension item had no attachments." }; + NSError *error = [[NSError alloc] initWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeUnexpectedData userInfo:userInfo]; + if (completion) { + completion(nil, error); + } + return; + } + + NSItemProvider *itemProvider = extensionItem.attachments.firstObject; + if (NO == [itemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypePropertyList]) { + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: @"Unexpected data returned by App Extension: extension item attachment does not conform to kUTTypePropertyList type identifier" }; + NSError *error = [[NSError alloc] initWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeUnexpectedData userInfo:userInfo]; + if (completion) { + completion(nil, error); + } + return; + } + + + [itemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypePropertyList options:nil completionHandler:^(NSDictionary *itemDictionary, NSError *itemProviderError) { + NSError *error = nil; + if (itemDictionary.count == 0) { + NSLog(@"Failed to loadItemForTypeIdentifier: %@", itemProviderError); + error = [OnePasswordExtension failedToLoadItemProviderDataErrorWithUnderlyingError:itemProviderError]; + } + + if (completion) { + if ([NSThread isMainThread]) { + completion(itemDictionary, error); + } + else { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(itemDictionary, error); + }); + } + } + }]; +} + +- (UIActivityViewController *)activityViewControllerForItem:(nonnull NSDictionary *)item viewController:(nonnull UIViewController*)viewController sender:(nullable id)sender typeIdentifier:(nonnull NSString *)typeIdentifier { +#ifdef __IPHONE_8_0 + NSAssert(NO == (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && sender == nil), @"sender must not be nil on iPad."); + + NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithItem:item typeIdentifier:typeIdentifier]; + + NSExtensionItem *extensionItem = [[NSExtensionItem alloc] init]; + extensionItem.attachments = @[ itemProvider ]; + + UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:@[ extensionItem ] applicationActivities:nil]; + + if ([sender isKindOfClass:[UIBarButtonItem class]]) { + controller.popoverPresentationController.barButtonItem = sender; + } + else if ([sender isKindOfClass:[UIView class]]) { + controller.popoverPresentationController.sourceView = [sender superview]; + controller.popoverPresentationController.sourceRect = [sender frame]; + } + else { + NSLog(@"sender can be nil on iPhone"); + } + + return controller; +#else + return nil; +#endif +} + +#endif + +- (void)createExtensionItemForURLString:(nonnull NSString *)URLString webPageDetails:(nullable NSString *)webPageDetails completion:(nonnull OnePasswordExtensionItemCompletionBlock)completion { + NSError *jsonError = nil; + NSData *data = [webPageDetails dataUsingEncoding:NSUTF8StringEncoding]; + NSDictionary *webPageDetailsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError]; + + if (webPageDetailsDictionary.count == 0) { + NSLog(@"Failed to parse JSON collected page details: %@", jsonError); + if (completion) { + completion(nil, jsonError); + } + return; + } + + NSDictionary *item = @{ AppExtensionVersionNumberKey : VERSION_NUMBER, AppExtensionURLStringKey : URLString, AppExtensionWebViewPageDetails : webPageDetailsDictionary }; + + NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithItem:item typeIdentifier:kUTTypeAppExtensionFillBrowserAction]; + + NSExtensionItem *extensionItem = [[NSExtensionItem alloc] init]; + extensionItem.attachments = @[ itemProvider ]; + + if (completion) { + if ([NSThread isMainThread]) { + completion(extensionItem, nil); + } + else { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(extensionItem, nil); + }); + } + } +} + +#pragma mark - Errors + ++ (NSError *)systemAppExtensionAPINotAvailableError { + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : NSLocalizedStringFromTable(@"App Extension API is not available in this version of iOS", @"OnePasswordExtension", @"1Password Extension Error Message") }; + return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeAPINotAvailable userInfo:userInfo]; +} + + ++ (NSError *)extensionCancelledByUserError { + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : NSLocalizedStringFromTable(@"1Password Extension was cancelled by the user", @"OnePasswordExtension", @"1Password Extension Error Message") }; + return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeCancelledByUser userInfo:userInfo]; +} + ++ (NSError *)failedToContactExtensionErrorWithActivityError:(nullable NSError *)activityError { + NSMutableDictionary *userInfo = [NSMutableDictionary new]; + userInfo[NSLocalizedDescriptionKey] = NSLocalizedStringFromTable(@"Failed to contact the 1Password Extension", @"OnePasswordExtension", @"1Password Extension Error Message"); + if (activityError) { + userInfo[NSUnderlyingErrorKey] = activityError; + } + + return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeFailedToContactExtension userInfo:userInfo]; +} + ++ (NSError *)failedToCollectFieldsErrorWithUnderlyingError:(nullable NSError *)underlyingError { + NSMutableDictionary *userInfo = [NSMutableDictionary new]; + userInfo[NSLocalizedDescriptionKey] = NSLocalizedStringFromTable(@"Failed to execute script that collects web page information", @"OnePasswordExtension", @"1Password Extension Error Message"); + if (underlyingError) { + userInfo[NSUnderlyingErrorKey] = underlyingError; + } + + return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeCollectFieldsScriptFailed userInfo:userInfo]; +} + ++ (NSError *)failedToFillFieldsErrorWithLocalizedErrorMessage:(nullable NSString *)errorMessage underlyingError:(nullable NSError *)underlyingError { + NSMutableDictionary *userInfo = [NSMutableDictionary new]; + if (errorMessage) { + userInfo[NSLocalizedDescriptionKey] = errorMessage; + } + if (underlyingError) { + userInfo[NSUnderlyingErrorKey] = underlyingError; + } + + return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeFillFieldsScriptFailed userInfo:userInfo]; +} + ++ (NSError *)failedToLoadItemProviderDataErrorWithUnderlyingError:(nullable NSError *)underlyingError { + NSMutableDictionary *userInfo = [NSMutableDictionary new]; + userInfo[NSLocalizedDescriptionKey] = NSLocalizedStringFromTable(@"Failed to parse information returned by 1Password Extension", @"OnePasswordExtension", @"1Password Extension Error Message"); + if (underlyingError) { + userInfo[NSUnderlyingErrorKey] = underlyingError; + } + + return [[NSError alloc] initWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeFailedToLoadItemProviderData userInfo:userInfo]; +} + ++ (NSError *)failedToObtainURLStringFromWebViewError { + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : NSLocalizedStringFromTable(@"Failed to obtain URL String from web view. The web view must be loaded completely when calling the 1Password Extension", @"OnePasswordExtension", @"1Password Extension Error Message") }; + return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeFailedToObtainURLStringFromWebView userInfo:userInfo]; +} + +#pragma mark - WebView field collection and filling scripts + +static NSString *const OPWebViewCollectFieldsScript = @";(function(document, undefined) {\ +\ + document.addEventListener('input',function(b){!1!==b.isTrusted&&'input'===b.target.tagName.toLowerCase()&&(b.target.dataset['com.agilebits.onepassword.userEdited']='yes')},!0);\ +(function(b,a,c){a.FieldCollector=new function(){function f(d){return d?d.toString().toLowerCase():''}function e(d,b,a,e){e!==c&&e===a||null===a||a===c||(d[b]=a)}function k(d,b){var a=[];try{a=d.querySelectorAll(b)}catch(J){console.error('[COLLECT FIELDS] @ag_querySelectorAll Exception in selector \"'+b+'\"')}return a}function m(d){var a,c=[];if(d.labels&&d.labels.length&&0=a.cells.length)return null;d=r(a.cells[d.cellIndex]);return d=l(d)}function p(a){return a.options?(a=Array.prototype.slice.call(a.options).map(function(a){var d=a.text,d=d?f(d).replace(/\\s/mg,'').replace(/[~`!@$%^&*()\\-_+=:;'\"\\[\\]|\\\\,<.>\\/?]/mg,\ +''):null;return[d?d:null,a.value]}),{options:a}):null}function F(a){switch(f(a.type)){case 'checkbox':return a.checked?'✓':'';case 'hidden':a=a.value;if(!a||'number'!=typeof a.length)return'';254b.clientWidth||10>b.clientHeight)return!1;var n=b.getClientRects();if(0===n.length)return!1;for(var p=0;pf||0>m.right)return!1;if(0>k||k>f||0>a||a>e)return!1;for(c=b.ownerDocument.elementFromPoint(k+(c.right>window.innerWidth?(window.innerWidth-k)/2:c.width/2),a+(c.bottom>window.innerHeight?\ +(window.innerHeight-a)/2:c.height/2));c&&c!==b&&c!==document;){if(c.tagName&&'string'===typeof c.tagName&&'label'===c.tagName.toLowerCase()&&b.labels&&0 + + +## Just Give Me the Code (TL;DR) + +You might be looking at this 23 KB README and think integrating with 1Password is very complicated. Nothing could be further from the truth! + +If you're the type that just wants the code, here it is: + +* [OnePasswordExtension.h](https://raw.githubusercontent.com/AgileBits/onepassword-app-extension/master/OnePasswordExtension.h?token=110676__eyJzY29wZSI6IlJhd0Jsb2I6QWdpbGVCaXRzL29uZXBhc3N3b3JkLWFwcC1leHRlbnNpb24vbWFzdGVyL09uZVBhc3N3b3JkRXh0ZW5zaW9uLmgiLCJleHBpcmVzIjoxNDA3Mjg0MTMwfQ%3D%3D--3867c64b22a5923bead5948001ce2ff048892799) +* [OnePasswordExtension.m](https://raw.githubusercontent.com/AgileBits/onepassword-app-extension/master/OnePasswordExtension.m?token=110676__eyJzY29wZSI6IlJhd0Jsb2I6QWdpbGVCaXRzL29uZXBhc3N3b3JkLWFwcC1leHRlbnNpb24vbWFzdGVyL09uZVBhc3N3b3JkRXh0ZW5zaW9uLm0iLCJleHBpcmVzIjoxNDA3Mjg0MTA5fQ%3D%3D--05c6ea9c73d0afb9f30e53a31d81df00b7c02077) + +Simply include these two files in your project, add a button with a [1Password login image](https://github.com/AgileBits/onepassword-app-extension/tree/master/1Password.xcassets) on it to your view, set the button's action to call the appropriate `OnePasswordExtension` method, and you're all set! + + +## Running the Sample Apps + +Adding 1Password support to your app is easy. To demonstrate how it works, we have two sample apps for iOS that showcase all of the 1Password features. + + +### Step 1: Download the Source Code and Sample Apps + +To get started, download the [zip version](https://github.com/AgileBits/onepassword-app-extension/archive/master.zip) of the1Password App Extension API project or [clone it from GitHub](https://github.com/AgileBits/onepassword-app-extension). + +Inside the downloaded folder, you'll find the resources needed to integrate with 1Password, such as images and sample code. The sample code includes two apps from ACME Corporation: one that demonstrates how to integrate the 1Password Login and Registration features, as well as a web browser that showcases the web view Filling feature. + +The 1Password App Extension API is also available via CocoaPods, simply add `pod '1PasswordExtension', '~> 1.8.5'` (for the latest stable release) or `pod '1PasswordExtension', :git => 'https://github.com/AgileBits/onepassword-app-extension.git', :branch => 'master'` (for the latest nightly) to your Podfile, run `pod install` from your project directory and you're ready to go. + +The 1Password App Extension API is available via Carthage as well. Simply add `github "AgileBits/onepassword-extension" "add-framework-support"` to your Cartfile, then run `carthage update` and add it to your project. + +### Step 2: Install the Latest versions of 1Password & Xcode + +The sample project depends upon having the latest version of Xcode, as well as the latest version of 1Password installed on your iOS device. + + + +To install 1Password, you will need to download it from the [App Store](http://j.mp/1PasSITE). + +Let us know that you're an app developer and planning to add 1Password support by emailing us to [support+appex@agilebits.com](mailto:support+appex@agilebits.com). + + +### Step 3: Run the Apps + +Open `1Password Extension Demos` Xcode workspace from within the `Demos` folder with Xcode, and then select the `ACME` target and set it to run your iOS device: + + + +Since you will not have 1Password running within your iOS Simulator, it is important that you run on your device. + +If all goes well, The ACME app will launch and you'll be able to test the 1Password App Extension. The first time you attempt to access the 1Password extension you will need to enable it by tapping on the _More_ button in the share sheet and then enable the _1Password_ item in the _Activities_ list. If the 1Password icons are missing, it likely means you do not have 1Password installed. + +Back in Xcode you can change the scheme to ACME Browser to test the web view filling feature. + +## Integrating 1Password With Your App + +Once you've verified your setup by testing the sample applications, it is time to get your hands dirty and see exactly how to add 1Password into your app. + +Be forewarned, however, that there is not much code to get dirty with. If you were looking for an SDK to spend days of your life on, you'll be sorely disappointed. + + +### Add 1Password Files to Your Project + +Add the `OnePasswordExtension.h`, `OnePasswordExtension.m`, and `1Password.xcassets` to your project and import `OnePasswordExtension.h` in your view controller that implements the action for the 1Password button. + + + +### Use Case #1: Native App Login + +In this use case we'll learn how to enable your existing users to fill their credentials into your native app's login form. If your application is using a web view to login (i.e. OAuth), you'll want to follow the web view integration steps in [Use Case #4: Web View Filling](https://github.com/AgileBits/onepassword-app-extension#use-case-4-web-view-filling-support). + +The first step is to add a UIButton to your login page. Use an existing 1Password image from the _1Password.xcassets_ catalog so users recognize the button. + +You'll need to hide this button (or educate users on the benefits of strong, unique passwords) if no password manager is installed. You can use `isAppExtensionAvailable` to determine availability and hide the button if it isn't. For example: + +```objective-c +-(void)viewDidLoad { + [super viewDidLoad]; + [self.onepasswordSigninButton setHidden:![[OnePasswordExtension sharedExtension] isAppExtensionAvailable]]; +} +``` + +Note that `isAppExtensionAvailable` looks to see if any app is installed that supports the generic `org-appextension-feature-password-management` feature. Any application that supports password management actions can be used. + +**Important:** `isAppExtensionAvailable` uses `- [UIApplication canOpenURL:]`. Since iOS 9 it is recommended that you add the custom URL scheme, `org-appextension-feature-password-management`, in your target's `info.plist` as follows: + + + +For more information about URL schemes in iOS 9, please refer to the [Privacy and Your Apps session](https://developer.apple.com/videos/wwdc/2015/?id=703) from WWDC 2015 at around the the 9th minute mark. + +Next we need to wire up the action for this button to this method in your UIViewController: + +```objective-c +- (IBAction)findLoginFrom1Password:(id)sender { + [[OnePasswordExtension sharedExtension] findLoginForURLString:@"https://www.acme.com" forViewController:self sender:sender completion:^(NSDictionary *loginDictionary, NSError *error) { + if (loginDictionary.count == 0) { + if (error.code != AppExtensionErrorCodeCancelledByUser) { + NSLog(@"Error invoking 1Password App Extension for find login: %@", error); + } + return; + } + + self.usernameTextField.text = loginDictionary[AppExtensionUsernameKey]; + self.passwordTextField.text = loginDictionary[AppExtensionPasswordKey]; + }]; +} +``` + +This code is pretty straight forward: + +1. Provide a `URLString` that uniquely identifies your service. For example, if your app required a Twitter login, you would pass in `@"https://twitter.com"`. See [Best Practices](https://github.com/AgileBits/onepassword-app-extension#best-practices) for details. +2. Pass in the `UIViewController` that you want the share sheet to be presented upon. +3. Provide a completion block that will be called when the user finishes their selection. This block is guaranteed to be called on the main thread. +4. Extract the needed information from the login dictionary and update your UI elements. + + +### Use Case #2: New User Registration + +Allow your users to access 1Password directly from your registration page so they can generate strong, unique passwords. 1Password will also save the login for future use, allowing users to easily log into your app on their other devices. The newly saved login and generated password are returned to you so you can update your UI and complete the registration. + +Adding 1Password to your registration screen is very similar to adding 1Password to your login screen. In this case you'll wire the 1Password button to an action like this: + +```objective-c +- (IBAction)saveLoginTo1Password:(id)sender { + NSDictionary *newLoginDetails = @{ + AppExtensionTitleKey: @"ACME", + AppExtensionUsernameKey: self.usernameTextField.text ? : @"", + AppExtensionPasswordKey: self.passwordTextField.text ? : @"", + AppExtensionNotesKey: @"Saved with the ACME app", + AppExtensionSectionTitleKey: @"ACME Browser", + AppExtensionFieldsKey: @{ + @"firstname" : self.firstnameTextField.text ? : @"", + @"lastname" : self.lastnameTextField.text ? : @"" + // Add as many string fields as you please. + } + }; + + // The password generation options are optional, but are very handy in case you have strict rules about password lengths, symbols and digits. + NSDictionary *passwordGenerationOptions = @{ + // The minimum password length can be 4 or more. + AppExtensionGeneratedPasswordMinLengthKey: @(8), + + // The maximum password length can be 50 or less. + AppExtensionGeneratedPasswordMaxLengthKey: @(30), + + // If YES, the 1Password will guarantee that the generated password will contain at least one digit (number between 0 and 9). Passing NO will not exclude digits from the generated password. + AppExtensionGeneratedPasswordRequireDigitsKey: @(YES), + + // If YES, the 1Password will guarantee that the generated password will contain at least one symbol (See the list below). Passing NO will not exclude symbols from the generated password. + AppExtensionGeneratedPasswordRequireSymbolsKey: @(YES), + + // Here are all the symbols available in the the 1Password Password Generator: + // !@#$%^&*()_-+=|[]{}'\";.,>?/~` + // The string for AppExtensionGeneratedPasswordForbiddenCharactersKey should contain the symbols and characters that you wish 1Password to exclude from the generated password. + AppExtensionGeneratedPasswordForbiddenCharactersKey: @"!@#$%/0lIO" + }; + + [[OnePasswordExtension sharedExtension] storeLoginForURLString:@"https://www.acme.com" loginDetails:newLoginDetails passwordGenerationOptions:passwordGenerationOptions forViewController:self sender:sender completion:^(NSDictionary *loginDictionary, NSError *error) { + + if (loginDictionary.count == 0) { + if (error.code != AppExtensionErrorCodeCancelledByUser) { + NSLog(@"Failed to use 1Password App Extension to save a new Login: %@", error); + } + return; + } + + self.usernameTextField.text = loginDictionary[AppExtensionUsernameKey] ? : @""; + self.passwordTextField.text = loginDictionary[AppExtensionPasswordKey] ? : @""; + self.firstnameTextField.text = loginDictionary[AppExtensionReturnedFieldsKey][@"firstname"] ? : @""; + self.lastnameTextField.text = loginDictionary[AppExtensionReturnedFieldsKey][@"lastname"] ? : @""; + // retrieve any additional fields that were passed in newLoginDetails dictionary + }]; +} +``` + +You'll notice that we're passing a lot more information into 1Password than just the `URLString` key used in the sign in example. This is because at the end of the password generation process, 1Password will create a brand new login and save it. It's not possible for 1Password to ask your app for additional information later on, so we pass in everything we can before showing the password generator screen. + +An important thing to notice is that the `URLString` is set to the exact same value we used in the login scenario. This allows users to quickly find the login they saved for your app the next time they need to sign in. + +### Use Case #3: Change Password + +Allow your users to easily change passwords for saved logins in 1Password directly from your change password page. The updated login along with the old and the newly generated are returned to you so you can update your UI and complete the password change process. If no matching login is found in 1Password, the user will be prompted to save a new login instead. + +Adding 1Password to your change password screen is very similar to adding 1Password to your login and registration screens. In this case you'll wire the 1Password button to an action like this: + +```objective-c +- (IBAction)changePasswordIn1Password:(id)sender { + NSString *changedPassword = self.freshPasswordTextField.text ? : @""; + NSString *oldPassword = self.oldPasswordTextField.text ? : @""; + NSString *confirmationPassword = self.confirmPasswordTextField.text ? : @""; + + // Validate that the new password and the old password are not the same. + if (oldPassword.length > 0 && [oldPassword isEqualToString:changedPassword]) { + [self showChangePasswordFailedAlertWithMessage:@"The old and the new password must not be the same"]; + return; + } + + // Validate that the new and confirmation passwords match. + if (NO == [changedPassword isEqualToString:confirmationPassword]) { + [self showChangePasswordFailedAlertWithMessage:@"The new passwords and the confirmation password must match"]; + return; + } + + NSDictionary *loginDetails = @{ + AppExtensionTitleKey: @"ACME", // Optional, used for the third schenario only + AppExtensionUsernameKey: @"aUsername", // Optional, used for the third schenario only + AppExtensionPasswordKey: changedPassword, + AppExtensionOldPasswordKey: oldPassword, + AppExtensionNotesKey: @"Saved with the ACME app", // Optional, used for the third schenario only + }; + + // The password generation options are optional, but are very handy in case you have strict rules about password lengths, symbols and digits. + NSDictionary *passwordGenerationOptions = @{ + // The minimum password length can be 4 or more. + AppExtensionGeneratedPasswordMinLengthKey: @(8), + + // The maximum password length can be 50 or less. + AppExtensionGeneratedPasswordMaxLengthKey: @(30), + + // If YES, the 1Password will guarantee that the generated password will contain at least one digit (number between 0 and 9). Passing NO will not exclude digits from the generated password. + AppExtensionGeneratedPasswordRequireDigitsKey: @(YES), + + // If YES, the 1Password will guarantee that the generated password will contain at least one symbol (See the list below). Passing NO will not exclude symbols from the generated password. + AppExtensionGeneratedPasswordRequireSymbolsKey: @(YES), + + // Here are all the symbols available in the the 1Password Password Generator: + // !@#$%^&*()_-+=|[]{}'\";.,>?/~` + // The string for AppExtensionGeneratedPasswordForbiddenCharactersKey should contain the symbols and characters that you wish 1Password to exclude from the generated password. + AppExtensionGeneratedPasswordForbiddenCharactersKey: @"!@#$%/0lIO" + }; + + [[OnePasswordExtension sharedExtension] changePasswordForLoginForURLString:@"https://www.acme.com" loginDetails:loginDetails passwordGenerationOptions:passwordGenerationOptions forViewController:self sender:sender completion:^(NSDictionary *loginDictionary, NSError *error) { + if (loginDictionary.count == 0) { + if (error.code != AppExtensionErrorCodeCancelledByUser) { + NSLog(@"Error invoking 1Password App Extension for find login: %@", error); + } + return; + } + + self.oldPasswordTextField.text = loginDictionary[AppExtensionOldPasswordKey]; + self.freshPasswordTextField.text = loginDictionary[AppExtensionPasswordKey]; + self.confirmPasswordTextField.text = loginDictionary[AppExtensionPasswordKey]; + }]; +} +``` + +### Use Case #4: Web View Filling + +The 1Password App Extension is not limited to filling native UIs. With just a little bit of extra effort, users can fill `UIWebView`s and `WKWebView`s within your application as well. + +Simply add a button to your UI with its action assigned to this method in your web view's UIViewController: + +```objective-c +- (IBAction)fillUsing1Password:(id)sender { + [[OnePasswordExtension sharedExtension] fillItemIntoWebView:self.webView forViewController:self sender:sender showOnlyLogins:NO completion:^(BOOL success, NSError *error) { + if (!success) { + NSLog(@"Failed to fill into webview: <%@>", error); + } + }]; +} +``` + +1Password will take care of all the details of collecting information about the currently displayed page, allow the user to select the desired login, and then fill the web form details within the page. + +If you use a web view to login (i.e. OAuth) and you do not want other activities to show up in the share sheet and other item categories (Credit Cards and Identities) to show up in the 1Password Extension, you need to pass `YES` for `showOnlyLogins`. + +#### SFSafariViewController + +If your app uses `SFSafariViewController`, the 1Password App Extension will show up in the share sheet on devices running iOS 9.2 or later just like it does in Safari. No implementation is required. + +## Projects supporting iOS 7.1 and earlier + +If your project's Deployment Target is earlier than iOS 8.0, please make sure that you link the `MobileCoreServices` and the `WebKit` frameworks as follows: + + + +#### WKWebView support for projects with iOS 7.1 or earlier as the Deployment Target + +If the **Deployment Target** is `7.1` or earlier in your project or target and you are using `WKWebViews` (runtime checks for iOS 8 devices), you simply need to add `ONE_PASSWORD_EXTENSION_ENABLE_WK_WEB_VIEW=1` to your `Preprocessor Macros`. + + + +## Best Practices + +* Use the same `URLString` during Registration and Login. +* Ensure your `URLString` is set to your actual service so your users can easily find their logins within the main 1Password app. +* You should only ask for the login information of your own service or one specific to your app. Giving a URL for a service which you do not own or support may seriously break the customer's trust in your service/app. +* If you don't have a website for your app you should specify your bundle identifier as the `URLString`, like so: `app://bundleIdentifier` (e.g. `app://com.acme.awesome-app`). +* [Send us an icon](mailto:support+appex@agilebits.com) to use for our Rich Icon service so the user can see your lovely icon after creating new items. Please send an icon that is 1024x1024px. Make sure that you also include the URL string that you used, so we can associate it with the icon on our Rich Icons server. +* Use the icons provided in the `1Password.xcassets` asset catalog so users are familiar with what it will do. Contact us if you'd like additional sizes or have other special requirements. +* Enable users to set 1Password as their default browser for external web links. +* On your registration page, pre-validate fields before calling 1Password. For example, display a message if the username is not available so the user can fix it before calling the 1Password extension. + + +## References + +If you open up OnePasswordExtension.m and start poking around, you'll be interested in these references. + +* [Apple Extension Guide](https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/index.html#//apple_ref/doc/uid/TP40014214) +* [NSItemProvider](https://developer.apple.com/library/prerelease/ios/documentation/Foundation/Reference/NSItemProvider_Class/index.html#//apple_ref/doc/uid/TP40014351), [NSExtensionItem](https://developer.apple.com/library/prerelease/ios/documentation/Foundation/Reference/NSExtensionItem_Class/index.html#//apple_ref/doc/uid/TP40014375), and [UIActivityViewController](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIActivityViewController_Class/index.html#//apple_ref/doc/uid/TP40011976) class references. + + +## Contact Us + +Contact us, please! We'd love to hear from you about how you integrated 1Password within your app, how we can further improve things, and add your app to [apps that integrate with 1Password](https://blog.agilebits.com/1password-apps/). + +You can reach us at support+appex@agilebits.com, or if you prefer, [@1Password](https://twitter.com/1Password) on Twitter. + +You can also [subscribe to our 1Password App Extension Developers newsletter](https://blog.agilebits.com/1password-extension-developers-newsletter/). We’ll send you an occasional newsletter containing 1Password App Extension news, updates, and tricks, to help you realize the full potential of the 1Password Extension API in your iOS apps. diff --git a/Pods/Crashlytics/Crashlytics.framework/README b/Pods/Crashlytics/Crashlytics.framework/README new file mode 100644 index 0000000000..3ebf76719f --- /dev/null +++ b/Pods/Crashlytics/Crashlytics.framework/README @@ -0,0 +1 @@ +We've now combined all our supported platforms into a single podspec. As a result, we moved our submit script to a new location for Cocoapods projects: ${PODS_ROOT}/Crashlytics/submit. To avoid breaking functionality that references the old location of the submit, we've placed this dummy script that calls to the correct location, while providing a helpful warning if it is invoked. This bridge for backwards compatibility will be removed in a future release, so please heed the warning! diff --git a/Pods/Crashlytics/Crashlytics.framework/submit b/Pods/Crashlytics/Crashlytics.framework/submit new file mode 100755 index 0000000000..b7de4e377e --- /dev/null +++ b/Pods/Crashlytics/Crashlytics.framework/submit @@ -0,0 +1,6 @@ +if [[ -z $PODS_ROOT ]]; then +echo "error: The submit binary delivered by cocoapods is in a new location, under '$"{"PODS_ROOT"}"/Crashlytics/submit'. This script was put in place for backwards compatibility, but it relies on PODS_ROOT, which does not have a value in your current setup. Please update the path to the submit binary to fix this issue." +else +echo "warning: The submit script is now located at '$"{"PODS_ROOT"}"/Crashlytics/submit'. To remove this warning, update your path to point to this new location." +sh "${PODS_ROOT}/Crashlytics/submit" "$@" +fi diff --git a/Pods/Crashlytics/README.md b/Pods/Crashlytics/README.md new file mode 100644 index 0000000000..2715a06b7c --- /dev/null +++ b/Pods/Crashlytics/README.md @@ -0,0 +1,39 @@ +![Crashlytics Header](https://docs.fabric.io/ios/cocoapod-readmes/cocoapods-crashlytics-header.png) + +Part of [Google Fabric](https://get.fabric.io), [Crashlytics](http://try.crashlytics.com/) offers the most powerful, yet lightest weight crash reporting solution for iOS. Crashlytics also provides real-time analytics through [Answers](https://answers.io/) and app distributions to testers using [Beta](http://try.crashlytics.com/beta/). + +## Setup + +1. Visit [https://fabric.io/sign_up](https://fabric.io/sign_up) to create your Fabric account and to download Fabric.app. + +1. Open Fabric.app, login and select the Crashlytics SDK. + + ![Fabric Plugin](https://docs.fabric.io/ios/cocoapod-readmes/cocoapods-fabric-plugin.png) + +1. The Fabric app automatically detects when a project uses CocoaPods and gives you the option to install via the Podfile or Xcode. + + ![Fabric Installation Options](https://docs.fabric.io/ios/cocoapod-readmes/cocoapods-pod-installation-option.png) + +1. Select the Podfile option and follow the installation instructions to update your Podfile. **Note:** the Crashlytics Pod includes Answers. If you have Answers included as a separate Pod it should be removed from your Podfile to avoid duplicate symbol errors. + + ``` + pod 'Fabric' + pod 'Crashlytics' + ``` + +1. Run `pod install` + +1. Add a Run Script Build Phase and build your app. + + ![Fabric Run Script Build Phase](https://docs.fabric.io/ios/cocoapod-readmes/cocoapods-rsbp.png) + +1. Initialize the SDK by inserting code outlined in the Fabric.app. + +1. Run your app to finish the installation. + +## Resources + +* [Documentation](https://docs.fabric.io/apple/crashlytics/overview.html) +* [Forums](https://stackoverflow.com/questions/tagged/google-fabric) +* [Website](http://try.crashlytics.com/) +* Follow us on Twitter: [@fabric](https://twitter.com/fabric) and [@crashlytics](https://twitter.com/crashlytics) diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Crashlytics b/Pods/Crashlytics/iOS/Crashlytics.framework/Crashlytics new file mode 100755 index 0000000000..79eb5165e0 Binary files /dev/null and b/Pods/Crashlytics/iOS/Crashlytics.framework/Crashlytics differ diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/ANSCompatibility.h b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/ANSCompatibility.h new file mode 100644 index 0000000000..6ec011d93e --- /dev/null +++ b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/ANSCompatibility.h @@ -0,0 +1,31 @@ +// +// ANSCompatibility.h +// AnswersKit +// +// Copyright (c) 2015 Crashlytics, Inc. All rights reserved. +// + +#pragma once + +#if !__has_feature(nullability) +#define nonnull +#define nullable +#define _Nullable +#define _Nonnull +#endif + +#ifndef NS_ASSUME_NONNULL_BEGIN +#define NS_ASSUME_NONNULL_BEGIN +#endif + +#ifndef NS_ASSUME_NONNULL_END +#define NS_ASSUME_NONNULL_END +#endif + +#if __has_feature(objc_generics) +#define ANS_GENERIC_NSARRAY(type) NSArray +#define ANS_GENERIC_NSDICTIONARY(key_type,object_key) NSDictionary +#else +#define ANS_GENERIC_NSARRAY(type) NSArray +#define ANS_GENERIC_NSDICTIONARY(key_type,object_key) NSDictionary +#endif diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/Answers.h b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/Answers.h new file mode 100644 index 0000000000..8deacbee56 --- /dev/null +++ b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/Answers.h @@ -0,0 +1,210 @@ +// +// Answers.h +// Crashlytics +// +// Copyright (c) 2015 Crashlytics, Inc. All rights reserved. +// + +#import +#import "ANSCompatibility.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * This class exposes the Answers Events API, allowing you to track key + * user user actions and metrics in your app. + */ +@interface Answers : NSObject + +/** + * Log a Sign Up event to see users signing up for your app in real-time, understand how + * many users are signing up with different methods and their success rate signing up. + * + * @param signUpMethodOrNil The method by which a user logged in, e.g. Twitter or Digits. + * @param signUpSucceededOrNil The ultimate success or failure of the login + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logSignUpWithMethod:(nullable NSString *)signUpMethodOrNil + success:(nullable NSNumber *)signUpSucceededOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log an Log In event to see users logging into your app in real-time, understand how many + * users are logging in with different methods and their success rate logging into your app. + * + * @param loginMethodOrNil The method by which a user logged in, e.g. email, Twitter or Digits. + * @param loginSucceededOrNil The ultimate success or failure of the login + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logLoginWithMethod:(nullable NSString *)loginMethodOrNil + success:(nullable NSNumber *)loginSucceededOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log a Share event to see users sharing from your app in real-time, letting you + * understand what content they're sharing from the type or genre down to the specific id. + * + * @param shareMethodOrNil The method by which a user shared, e.g. email, Twitter, SMS. + * @param contentNameOrNil The human readable name for this piece of content. + * @param contentTypeOrNil The type of content shared. + * @param contentIdOrNil The unique identifier for this piece of content. Useful for finding the top shared item. + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logShareWithMethod:(nullable NSString *)shareMethodOrNil + contentName:(nullable NSString *)contentNameOrNil + contentType:(nullable NSString *)contentTypeOrNil + contentId:(nullable NSString *)contentIdOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log an Invite Event to track how users are inviting other users into + * your application. + * + * @param inviteMethodOrNil The method of invitation, e.g. GameCenter, Twitter, email. + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logInviteWithMethod:(nullable NSString *)inviteMethodOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log a Purchase event to see your revenue in real-time, understand how many users are making purchases, see which + * items are most popular, and track plenty of other important purchase-related metrics. + * + * @param itemPriceOrNil The purchased item's price. + * @param currencyOrNil The ISO4217 currency code. Example: USD + * @param purchaseSucceededOrNil Was the purchase successful or unsuccessful + * @param itemNameOrNil The human-readable form of the item's name. Example: + * @param itemTypeOrNil The type, or genre of the item. Example: Song + * @param itemIdOrNil The machine-readable, unique item identifier Example: SKU + * @param customAttributesOrNil A dictionary of custom attributes to associate with this purchase. + */ ++ (void)logPurchaseWithPrice:(nullable NSDecimalNumber *)itemPriceOrNil + currency:(nullable NSString *)currencyOrNil + success:(nullable NSNumber *)purchaseSucceededOrNil + itemName:(nullable NSString *)itemNameOrNil + itemType:(nullable NSString *)itemTypeOrNil + itemId:(nullable NSString *)itemIdOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log a Level Start Event to track where users are in your game. + * + * @param levelNameOrNil The level name + * @param customAttributesOrNil A dictionary of custom attributes to associate with this level start event. + */ ++ (void)logLevelStart:(nullable NSString *)levelNameOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log a Level End event to track how users are completing levels in your game. + * + * @param levelNameOrNil The name of the level completed, E.G. "1" or "Training" + * @param scoreOrNil The score the user completed the level with. + * @param levelCompletedSuccesfullyOrNil A boolean representing whether or not the level was completed successfully. + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logLevelEnd:(nullable NSString *)levelNameOrNil + score:(nullable NSNumber *)scoreOrNil + success:(nullable NSNumber *)levelCompletedSuccesfullyOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log an Add to Cart event to see users adding items to a shopping cart in real-time, understand how + * many users start the purchase flow, see which items are most popular, and track plenty of other important + * purchase-related metrics. + * + * @param itemPriceOrNil The purchased item's price. + * @param currencyOrNil The ISO4217 currency code. Example: USD + * @param itemNameOrNil The human-readable form of the item's name. Example: + * @param itemTypeOrNil The type, or genre of the item. Example: Song + * @param itemIdOrNil The machine-readable, unique item identifier Example: SKU + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logAddToCartWithPrice:(nullable NSDecimalNumber *)itemPriceOrNil + currency:(nullable NSString *)currencyOrNil + itemName:(nullable NSString *)itemNameOrNil + itemType:(nullable NSString *)itemTypeOrNil + itemId:(nullable NSString *)itemIdOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log a Start Checkout event to see users moving through the purchase funnel in real-time, understand how many + * users are doing this and how much they're spending per checkout, and see how it related to other important + * purchase-related metrics. + * + * @param totalPriceOrNil The total price of the cart. + * @param currencyOrNil The ISO4217 currency code. Example: USD + * @param itemCountOrNil The number of items in the cart. + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logStartCheckoutWithPrice:(nullable NSDecimalNumber *)totalPriceOrNil + currency:(nullable NSString *)currencyOrNil + itemCount:(nullable NSNumber *)itemCountOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log a Rating event to see users rating content within your app in real-time and understand what + * content is most engaging, from the type or genre down to the specific id. + * + * @param ratingOrNil The integer rating given by the user. + * @param contentNameOrNil The human readable name for this piece of content. + * @param contentTypeOrNil The type of content shared. + * @param contentIdOrNil The unique identifier for this piece of content. Useful for finding the top shared item. + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logRating:(nullable NSNumber *)ratingOrNil + contentName:(nullable NSString *)contentNameOrNil + contentType:(nullable NSString *)contentTypeOrNil + contentId:(nullable NSString *)contentIdOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log a Content View event to see users viewing content within your app in real-time and + * understand what content is most engaging, from the type or genre down to the specific id. + * + * @param contentNameOrNil The human readable name for this piece of content. + * @param contentTypeOrNil The type of content shared. + * @param contentIdOrNil The unique identifier for this piece of content. Useful for finding the top shared item. + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logContentViewWithName:(nullable NSString *)contentNameOrNil + contentType:(nullable NSString *)contentTypeOrNil + contentId:(nullable NSString *)contentIdOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log a Search event allows you to see users searching within your app in real-time and understand + * exactly what they're searching for. + * + * @param queryOrNil The user's query. + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. + */ ++ (void)logSearchWithQuery:(nullable NSString *)queryOrNil + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +/** + * Log a Custom Event to see user actions that are uniquely important for your app in real-time, to see how often + * they're performing these actions with breakdowns by different categories you add. Use a human-readable name for + * the name of the event, since this is how the event will appear in Answers. + * + * @param eventName The human-readable name for the event. + * @param customAttributesOrNil A dictionary of custom attributes to associate with this event. Attribute keys + * must be NSString and values must be NSNumber or NSString. + * @discussion How we treat NSNumbers: + * We will provide information about the distribution of values over time. + * + * How we treat NSStrings: + * NSStrings are used as categorical data, allowing comparison across different category values. + * Strings are limited to a maximum length of 100 characters, attributes over this length will be + * truncated. + * + * When tracking the Tweet views to better understand user engagement, sending the tweet's length + * and the type of media present in the tweet allows you to track how tweet length and the type of media influence + * engagement. + */ ++ (void)logCustomEventWithName:(NSString *)eventName + customAttributes:(nullable ANS_GENERIC_NSDICTIONARY(NSString *, id) *)customAttributesOrNil; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSAttributes.h b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSAttributes.h new file mode 100644 index 0000000000..1526b0dca6 --- /dev/null +++ b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSAttributes.h @@ -0,0 +1,33 @@ +// +// CLSAttributes.h +// Crashlytics +// +// Copyright (c) 2015 Crashlytics, Inc. All rights reserved. +// + +#pragma once + +#define CLS_DEPRECATED(x) __attribute__ ((deprecated(x))) + +#if !__has_feature(nullability) + #define nonnull + #define nullable + #define _Nullable + #define _Nonnull +#endif + +#ifndef NS_ASSUME_NONNULL_BEGIN + #define NS_ASSUME_NONNULL_BEGIN +#endif + +#ifndef NS_ASSUME_NONNULL_END + #define NS_ASSUME_NONNULL_END +#endif + +#if __has_feature(objc_generics) + #define CLS_GENERIC_NSARRAY(type) NSArray + #define CLS_GENERIC_NSDICTIONARY(key_type,object_key) NSDictionary +#else + #define CLS_GENERIC_NSARRAY(type) NSArray + #define CLS_GENERIC_NSDICTIONARY(key_type,object_key) NSDictionary +#endif diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSLogging.h b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSLogging.h new file mode 100644 index 0000000000..59590d546e --- /dev/null +++ b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSLogging.h @@ -0,0 +1,64 @@ +// +// CLSLogging.h +// Crashlytics +// +// Copyright (c) 2015 Crashlytics, Inc. All rights reserved. +// +#ifdef __OBJC__ +#import "CLSAttributes.h" +#import + +NS_ASSUME_NONNULL_BEGIN +#endif + + + +/** + * + * The CLS_LOG macro provides as easy way to gather more information in your log messages that are + * sent with your crash data. CLS_LOG prepends your custom log message with the function name and + * line number where the macro was used. If your app was built with the DEBUG preprocessor macro + * defined CLS_LOG uses the CLSNSLog function which forwards your log message to NSLog and CLSLog. + * If the DEBUG preprocessor macro is not defined CLS_LOG uses CLSLog only. + * + * Example output: + * -[AppDelegate login:] line 134 $ login start + * + * If you would like to change this macro, create a new header file, unset our define and then define + * your own version. Make sure this new header file is imported after the Crashlytics header file. + * + * #undef CLS_LOG + * #define CLS_LOG(__FORMAT__, ...) CLSNSLog... + * + **/ +#ifdef __OBJC__ +#ifdef DEBUG +#define CLS_LOG(__FORMAT__, ...) CLSNSLog((@"%s line %d $ " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) +#else +#define CLS_LOG(__FORMAT__, ...) CLSLog((@"%s line %d $ " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) +#endif +#endif + +/** + * + * Add logging that will be sent with your crash data. This logging will not show up in the system.log + * and will only be visible in your Crashlytics dashboard. + * + **/ + +#ifdef __OBJC__ +OBJC_EXTERN void CLSLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2); +OBJC_EXTERN void CLSLogv(NSString *format, va_list ap) NS_FORMAT_FUNCTION(1,0); + +/** + * + * Add logging that will be sent with your crash data. This logging will show up in the system.log + * and your Crashlytics dashboard. It is not recommended for Release builds. + * + **/ +OBJC_EXTERN void CLSNSLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2); +OBJC_EXTERN void CLSNSLogv(NSString *format, va_list ap) NS_FORMAT_FUNCTION(1,0); + + +NS_ASSUME_NONNULL_END +#endif diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSReport.h b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSReport.h new file mode 100644 index 0000000000..a8ff3b0b92 --- /dev/null +++ b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSReport.h @@ -0,0 +1,103 @@ +// +// CLSReport.h +// Crashlytics +// +// Copyright (c) 2015 Crashlytics, Inc. All rights reserved. +// + +#import +#import "CLSAttributes.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * The CLSCrashReport protocol is deprecated. See the CLSReport class and the CrashyticsDelegate changes for details. + **/ +@protocol CLSCrashReport + +@property (nonatomic, copy, readonly) NSString *identifier; +@property (nonatomic, copy, readonly) NSDictionary *customKeys; +@property (nonatomic, copy, readonly) NSString *bundleVersion; +@property (nonatomic, copy, readonly) NSString *bundleShortVersionString; +@property (nonatomic, readonly, nullable) NSDate *crashedOnDate; +@property (nonatomic, copy, readonly) NSString *OSVersion; +@property (nonatomic, copy, readonly) NSString *OSBuildVersion; + +@end + +/** + * The CLSReport exposes an interface to the phsyical report that Crashlytics has created. You can + * use this class to get information about the event, and can also set some values after the + * event has occurred. + **/ +@interface CLSReport : NSObject + +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; + +/** + * Returns the session identifier for the report. + **/ +@property (nonatomic, copy, readonly) NSString *identifier; + +/** + * Returns the custom key value data for the report. + **/ +@property (nonatomic, copy, readonly) NSDictionary *customKeys; + +/** + * Returns the CFBundleVersion of the application that generated the report. + **/ +@property (nonatomic, copy, readonly) NSString *bundleVersion; + +/** + * Returns the CFBundleShortVersionString of the application that generated the report. + **/ +@property (nonatomic, copy, readonly) NSString *bundleShortVersionString; + +/** + * Returns the date that the report was created. + **/ +@property (nonatomic, copy, readonly) NSDate *dateCreated; + +/** + * Returns the os version that the application crashed on. + **/ +@property (nonatomic, copy, readonly) NSString *OSVersion; + +/** + * Returns the os build version that the application crashed on. + **/ +@property (nonatomic, copy, readonly) NSString *OSBuildVersion; + +/** + * Returns YES if the report contains any crash information, otherwise returns NO. + **/ +@property (nonatomic, assign, readonly) BOOL isCrash; + +/** + * You can use this method to set, after the event, additional custom keys. The rules + * and semantics for this method are the same as those documented in Crashlytics.h. Be aware + * that the maximum size and count of custom keys is still enforced, and you can overwrite keys + * and/or cause excess keys to be deleted by using this method. + **/ +- (void)setObjectValue:(nullable id)value forKey:(NSString *)key; + +/** + * Record an application-specific user identifier. See Crashlytics.h for details. + **/ +@property (nonatomic, copy, nullable) NSString * userIdentifier; + +/** + * Record a user name. See Crashlytics.h for details. + **/ +@property (nonatomic, copy, nullable) NSString * userName; + +/** + * Record a user email. See Crashlytics.h for details. + **/ +@property (nonatomic, copy, nullable) NSString * userEmail; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSStackFrame.h b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSStackFrame.h new file mode 100644 index 0000000000..cdb5596ccb --- /dev/null +++ b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/CLSStackFrame.h @@ -0,0 +1,38 @@ +// +// CLSStackFrame.h +// Crashlytics +// +// Copyright 2015 Crashlytics, Inc. All rights reserved. +// + +#import +#import "CLSAttributes.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * + * This class is used in conjunction with -[Crashlytics recordCustomExceptionName:reason:frameArray:] to + * record information about non-ObjC/C++ exceptions. All information included here will be displayed + * in the Crashlytics UI, and can influence crash grouping. Be particularly careful with the use of the + * address property. If set, Crashlytics will attempt symbolication and could overwrite other properities + * in the process. + * + **/ +@interface CLSStackFrame : NSObject + ++ (instancetype)stackFrame; ++ (instancetype)stackFrameWithAddress:(NSUInteger)address; ++ (instancetype)stackFrameWithSymbol:(NSString *)symbol; + +@property (nonatomic, copy, nullable) NSString *symbol; +@property (nonatomic, copy, nullable) NSString *rawSymbol; +@property (nonatomic, copy, nullable) NSString *library; +@property (nonatomic, copy, nullable) NSString *fileName; +@property (nonatomic, assign) uint32_t lineNumber; +@property (nonatomic, assign) uint64_t offset; +@property (nonatomic, assign) uint64_t address; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/Crashlytics.h b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/Crashlytics.h new file mode 100644 index 0000000000..7104ca812c --- /dev/null +++ b/Pods/Crashlytics/iOS/Crashlytics.framework/Headers/Crashlytics.h @@ -0,0 +1,288 @@ +// +// Crashlytics.h +// Crashlytics +// +// Copyright (c) 2015 Crashlytics, Inc. All rights reserved. +// + +#import + +#import "CLSAttributes.h" +#import "CLSLogging.h" +#import "CLSReport.h" +#import "CLSStackFrame.h" +#import "Answers.h" + +NS_ASSUME_NONNULL_BEGIN + +@protocol CrashlyticsDelegate; + +/** + * Crashlytics. Handles configuration and initialization of Crashlytics. + * + * Note: The Crashlytics class cannot be subclassed. If this is causing you pain for + * testing, we suggest using either a wrapper class or a protocol extension. + */ +@interface Crashlytics : NSObject + +@property (nonatomic, readonly, copy) NSString *APIKey; +@property (nonatomic, readonly, copy) NSString *version; +@property (nonatomic, assign) BOOL debugMode; + +/** + * + * The delegate can be used to influence decisions on reporting and behavior, as well as reacting + * to previous crashes. + * + * Make certain that the delegate is setup before starting Crashlytics with startWithAPIKey:... or + * via +[Fabric with:...]. Failure to do will result in missing any delegate callbacks that occur + * synchronously during start. + * + **/ +@property (nonatomic, assign, nullable) id delegate; + +/** + * The recommended way to install Crashlytics into your application is to place a call to +startWithAPIKey: + * in your -application:didFinishLaunchingWithOptions: or -applicationDidFinishLaunching: + * method. + * + * Note: Starting with 3.0, the submission process has been significantly improved. The delay parameter + * is no longer required to throttle submissions on launch, performance will be great without it. + * + * @param apiKey The Crashlytics API Key for this app + * + * @return The singleton Crashlytics instance + */ ++ (Crashlytics *)startWithAPIKey:(NSString *)apiKey; ++ (Crashlytics *)startWithAPIKey:(NSString *)apiKey afterDelay:(NSTimeInterval)delay CLS_DEPRECATED("Crashlytics no longer needs or uses the delay parameter. Please use +startWithAPIKey: instead."); + +/** + * If you need the functionality provided by the CrashlyticsDelegate protocol, you can use + * these convenience methods to activate the framework and set the delegate in one call. + * + * @param apiKey The Crashlytics API Key for this app + * @param delegate A delegate object which conforms to CrashlyticsDelegate. + * + * @return The singleton Crashlytics instance + */ ++ (Crashlytics *)startWithAPIKey:(NSString *)apiKey delegate:(nullable id)delegate; ++ (Crashlytics *)startWithAPIKey:(NSString *)apiKey delegate:(nullable id)delegate afterDelay:(NSTimeInterval)delay CLS_DEPRECATED("Crashlytics no longer needs or uses the delay parameter. Please use +startWithAPIKey:delegate: instead."); + +/** + * Access the singleton Crashlytics instance. + * + * @return The singleton Crashlytics instance + */ ++ (Crashlytics *)sharedInstance; + +/** + * The easiest way to cause a crash - great for testing! + */ +- (void)crash; + +/** + * The easiest way to cause a crash with an exception - great for testing. + */ +- (void)throwException; + +/** + * Specify a user identifier which will be visible in the Crashlytics UI. + * + * Many of our customers have requested the ability to tie crashes to specific end-users of their + * application in order to facilitate responses to support requests or permit the ability to reach + * out for more information. We allow you to specify up to three separate values for display within + * the Crashlytics UI - but please be mindful of your end-user's privacy. + * + * We recommend specifying a user identifier - an arbitrary string that ties an end-user to a record + * in your system. This could be a database id, hash, or other value that is meaningless to a + * third-party observer but can be indexed and queried by you. + * + * Optionally, you may also specify the end-user's name or username, as well as email address if you + * do not have a system that works well with obscured identifiers. + * + * Pursuant to our EULA, this data is transferred securely throughout our system and we will not + * disseminate end-user data unless required to by law. That said, if you choose to provide end-user + * contact information, we strongly recommend that you disclose this in your application's privacy + * policy. Data privacy is of our utmost concern. + * + * @param identifier An arbitrary user identifier string which ties an end-user to a record in your system. + */ +- (void)setUserIdentifier:(nullable NSString *)identifier; + +/** + * Specify a user name which will be visible in the Crashlytics UI. + * Please be mindful of your end-user's privacy and see if setUserIdentifier: can fulfil your needs. + * @see setUserIdentifier: + * + * @param name An end user's name. + */ +- (void)setUserName:(nullable NSString *)name; + +/** + * Specify a user email which will be visible in the Crashlytics UI. + * Please be mindful of your end-user's privacy and see if setUserIdentifier: can fulfil your needs. + * + * @see setUserIdentifier: + * + * @param email An end user's email address. + */ +- (void)setUserEmail:(nullable NSString *)email; + ++ (void)setUserIdentifier:(nullable NSString *)identifier CLS_DEPRECATED("Please access this method via +sharedInstance"); ++ (void)setUserName:(nullable NSString *)name CLS_DEPRECATED("Please access this method via +sharedInstance"); ++ (void)setUserEmail:(nullable NSString *)email CLS_DEPRECATED("Please access this method via +sharedInstance"); + +/** + * Set a value for a for a key to be associated with your crash data which will be visible in the Crashlytics UI. + * When setting an object value, the object is converted to a string. This is typically done by calling + * -[NSObject description]. + * + * @param value The object to be associated with the key + * @param key The key with which to associate the value + */ +- (void)setObjectValue:(nullable id)value forKey:(NSString *)key; + +/** + * Set an int value for a key to be associated with your crash data which will be visible in the Crashlytics UI. + * + * @param value The integer value to be set + * @param key The key with which to associate the value + */ +- (void)setIntValue:(int)value forKey:(NSString *)key; + +/** + * Set an BOOL value for a key to be associated with your crash data which will be visible in the Crashlytics UI. + * + * @param value The BOOL value to be set + * @param key The key with which to associate the value + */ +- (void)setBoolValue:(BOOL)value forKey:(NSString *)key; + +/** + * Set an float value for a key to be associated with your crash data which will be visible in the Crashlytics UI. + * + * @param value The float value to be set + * @param key The key with which to associate the value + */ +- (void)setFloatValue:(float)value forKey:(NSString *)key; + ++ (void)setObjectValue:(nullable id)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance"); ++ (void)setIntValue:(int)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance"); ++ (void)setBoolValue:(BOOL)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance"); ++ (void)setFloatValue:(float)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance"); + +/** + * This method can be used to record a single exception structure in a report. This is particularly useful + * when your code interacts with non-native languages like Lua, C#, or Javascript. This call can be + * expensive and should only be used shortly before process termination. This API is not intended be to used + * to log NSException objects. All safely-reportable NSExceptions are automatically captured by + * Crashlytics. + * + * @param name The name of the custom exception + * @param reason The reason this exception occurred + * @param frameArray An array of CLSStackFrame objects + */ +- (void)recordCustomExceptionName:(NSString *)name reason:(nullable NSString *)reason frameArray:(CLS_GENERIC_NSARRAY(CLSStackFrame *) *)frameArray; + +/** + * + * This allows you to record a non-fatal event, described by an NSError object. These events will be grouped and + * displayed similarly to crashes. Keep in mind that this method can be expensive. Also, the total number of + * NSErrors that can be recorded during your app's life-cycle is limited by a fixed-size circular buffer. If the + * buffer is overrun, the oldest data is dropped. Errors are relayed to Crashlytics on a subsequent launch + * of your application. + * + * You can also use the -recordError:withAdditionalUserInfo: to include additional context not represented + * by the NSError instance itself. + * + **/ +- (void)recordError:(NSError *)error; +- (void)recordError:(NSError *)error withAdditionalUserInfo:(nullable CLS_GENERIC_NSDICTIONARY(NSString *, id) *)userInfo; + +- (void)logEvent:(NSString *)eventName CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:"); +- (void)logEvent:(NSString *)eventName attributes:(nullable NSDictionary *) attributes CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:"); ++ (void)logEvent:(NSString *)eventName CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:"); ++ (void)logEvent:(NSString *)eventName attributes:(nullable NSDictionary *) attributes CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:"); + +@end + +/** + * + * The CrashlyticsDelegate protocol provides a mechanism for your application to take + * action on events that occur in the Crashlytics crash reporting system. You can make + * use of these calls by assigning an object to the Crashlytics' delegate property directly, + * or through the convenience +startWithAPIKey:delegate: method. + * + */ +@protocol CrashlyticsDelegate +@optional + + +- (void)crashlyticsDidDetectCrashDuringPreviousExecution:(Crashlytics *)crashlytics CLS_DEPRECATED("Please refer to -crashlyticsDidDetectReportForLastExecution:"); +- (void)crashlytics:(Crashlytics *)crashlytics didDetectCrashDuringPreviousExecution:(id )crash CLS_DEPRECATED("Please refer to -crashlyticsDidDetectReportForLastExecution:"); + +/** + * + * Called when a Crashlytics instance has determined that the last execution of the + * application resulted in a saved report. This is called synchronously on Crashlytics + * initialization. Your delegate must invoke the completionHandler, but does not need to do so + * synchronously, or even on the main thread. Invoking completionHandler with NO will cause the + * detected report to be deleted and not submitted to Crashlytics. This is useful for + * implementing permission prompts, or other more-complex forms of logic around submitting crashes. + * + * Instead of using this method, you should try to make use of -crashlyticsDidDetectReportForLastExecution: + * if you can. + * + * @warning Failure to invoke the completionHandler will prevent submissions from being reported. Watch out. + * + * @warning Just implementing this delegate method will disable all forms of synchronous report submission. This can + * impact the reliability of reporting crashes very early in application launch. + * + * @param report The CLSReport object representing the last detected report + * @param completionHandler The completion handler to call when your logic has completed. + * + */ +- (void)crashlyticsDidDetectReportForLastExecution:(CLSReport *)report completionHandler:(void (^)(BOOL submit))completionHandler; + +/** + * + * Called when a Crashlytics instance has determined that the last execution of the + * application resulted in a saved report. This method differs from + * -crashlyticsDidDetectReportForLastExecution:completionHandler: in three important ways: + * + * - it is not called synchronously during initialization + * - it does not give you the ability to prevent the report from being submitted + * - the report object itself is immutable + * + * Thanks to these limitations, making use of this method does not impact reporting + * reliabilty in any way. + * + * @param report The read-only CLSReport object representing the last detected report + * + */ + +- (void)crashlyticsDidDetectReportForLastExecution:(CLSReport *)report; + +/** + * If your app is running on an OS that supports it (OS X 10.9+, iOS 7.0+), Crashlytics will submit + * most reports using out-of-process background networking operations. This results in a significant + * improvement in reliability of reporting, as well as power and performance wins for your users. + * If you don't want this functionality, you can disable by returning NO from this method. + * + * @warning Background submission is not supported for extensions on iOS or OS X. + * + * @param crashlytics The Crashlytics singleton instance + * + * @return Return NO if you don't want out-of-process background network operations. + * + */ +- (BOOL)crashlyticsCanUseBackgroundSessions:(Crashlytics *)crashlytics; + +@end + +/** + * `CrashlyticsKit` can be used as a parameter to `[Fabric with:@[CrashlyticsKit]];` in Objective-C. In Swift, use Crashlytics.sharedInstance() + */ +#define CrashlyticsKit [Crashlytics sharedInstance] + +NS_ASSUME_NONNULL_END diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Info.plist b/Pods/Crashlytics/iOS/Crashlytics.framework/Info.plist new file mode 100644 index 0000000000..bfa283150d Binary files /dev/null and b/Pods/Crashlytics/iOS/Crashlytics.framework/Info.plist differ diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/Modules/module.modulemap b/Pods/Crashlytics/iOS/Crashlytics.framework/Modules/module.modulemap new file mode 100644 index 0000000000..da0845e391 --- /dev/null +++ b/Pods/Crashlytics/iOS/Crashlytics.framework/Modules/module.modulemap @@ -0,0 +1,14 @@ +framework module Crashlytics { + header "Crashlytics.h" + header "Answers.h" + header "ANSCompatibility.h" + header "CLSLogging.h" + header "CLSReport.h" + header "CLSStackFrame.h" + header "CLSAttributes.h" + + export * + + link "z" + link "c++" +} diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/run b/Pods/Crashlytics/iOS/Crashlytics.framework/run new file mode 100755 index 0000000000..9058ea62c0 --- /dev/null +++ b/Pods/Crashlytics/iOS/Crashlytics.framework/run @@ -0,0 +1,28 @@ +#!/bin/sh + +# run +# +# Copyright (c) 2015 Crashlytics. All rights reserved. + +# Figure out where we're being called from +DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) + +# Quote path in case of spaces or special chars +DIR="\"${DIR}" + +PATH_SEP="/" +VALIDATE_COMMAND="uploadDSYM\" $@ validate run-script" +UPLOAD_COMMAND="uploadDSYM\" $@ run-script" + +# Ensure params are as expected, run in sync mode to validate +eval $DIR$PATH_SEP$VALIDATE_COMMAND +return_code=$? + +if [[ $return_code != 0 ]]; then + exit $return_code +fi + +# Verification passed, upload dSYM in background to prevent Xcode from waiting +# Note: Validation is performed again before upload. +# Output can still be found in Console.app +eval $DIR$PATH_SEP$UPLOAD_COMMAND > /dev/null 2>&1 & diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/submit b/Pods/Crashlytics/iOS/Crashlytics.framework/submit new file mode 100755 index 0000000000..3fda5cff1d Binary files /dev/null and b/Pods/Crashlytics/iOS/Crashlytics.framework/submit differ diff --git a/Pods/Crashlytics/iOS/Crashlytics.framework/uploadDSYM b/Pods/Crashlytics/iOS/Crashlytics.framework/uploadDSYM new file mode 100755 index 0000000000..8deb7c9c38 Binary files /dev/null and b/Pods/Crashlytics/iOS/Crashlytics.framework/uploadDSYM differ diff --git a/Pods/Crashlytics/submit b/Pods/Crashlytics/submit new file mode 100755 index 0000000000..3fda5cff1d Binary files /dev/null and b/Pods/Crashlytics/submit differ diff --git a/Pods/DifferenceKit/LICENSE b/Pods/DifferenceKit/LICENSE new file mode 100644 index 0000000000..d892df50e1 --- /dev/null +++ b/Pods/DifferenceKit/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2018 ra1028 + +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/DifferenceKit/README.md b/Pods/DifferenceKit/README.md new file mode 100644 index 0000000000..69b409064f --- /dev/null +++ b/Pods/DifferenceKit/README.md @@ -0,0 +1,335 @@ +

+ +

+

+A fast and flexible O(n) difference algorithm framework for Swift collection.
+The algorithm is optimized based on the Paul Heckel's algorithm. +

+ +

+Swift4 +Release +CocoaPods +Carthage +
+Build Status +Platform +Lincense +

+ +--- + +## Features +✅ Automate to calculate operations for batch-updates of UITableView, UICollectionView, NSTableView and NSCollectionView + +✅ **O(n)** difference algorithm optimized for performance in Swift + +✅ Supports both linear and sectioned collection + +✅ Supports calculating differences with best effort even if elements or section contains duplicates + +✅ Supports **all operations** for animated UI batch-updates including section reloads + +--- + +

+ +

+

+Sample app is imitated from DataSources 💾 +

+ +--- + +## Algorithm +The algorithm used in DifferenceKit is optimized based on the Paul Heckel's algorithm. +See also his paper ["A technique for isolating differences between files"](https://dl.acm.org/citation.cfm?id=359467) released in 1978. +[RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources) and [IGListKit](https://github.com/Instagram/IGListKit) are also implemented based on his algorithm. +This allows all types of differences to be computed in linear time **O(n)**. + +However, in `performBatchUpdates` of `UITableView` and `UICollectionView`, there are combinations of operations that cause crash when applied simultaneously. +To solve this problem, `DifferenceKit` takes an approach of split the set of differences at the minimal stages that can be perform batch-updates with no crashes. + +Implementation is [here](https://github.com/ra1028/DifferenceKit/blob/master/Sources/Algorithm.swift). + +--- + +## Documentation +⚠️ Since DifferenceKit is currently released in alpha version, updates may contain breaking changes. +See docs in [GitHub Pages](https://ra1028.github.io/DifferenceKit/). +Documentation is generated by [jazzy](https://github.com/realm/jazzy). + +--- + +## Getting Started +- [Example app](https://github.com/ra1028/DifferenceKit/blob/master/Examples) +- [Playground](https://github.com/ra1028/DifferenceKit/blob/master/DifferenceKit.playground/Contents.swift) + +### Example codes +The type of the element that to take the differences must be conform to the `Differentiable` protocol. +The `differenceIdentifier`'s type is determined generic by the associated type: +```swift +struct User: Differentiable { + let id: Int + let name: String + + var differenceIdentifier: Int { + return id + } + + func isContentEqual(to source: User) -> Bool { + return name == source.name + } +} +``` + +In the case of definition above, `id` uniquely identifies the element and get to know the user updated by comparing equality of `name` of the elements in source and target. + +There are default implementations of `Differentiable` for the types that conformed to `Equatable` or `Hashable`: +```swift +// If `Self` conform to `Hashable`. +var differenceIdentifier: Self { + return self +} + +// If `Self` conform to `Equatable`. +func isContentEqual(to source: Self) -> Bool { + return self == source +} +``` +So, you can simply: +```swift +extension String: Differentiable {} +``` + +Calculates the differences by creating `StagedChangeset` from two collections of elements conforming to `Differentiable`: +```swift +let source = [ + User(id: 0, name: "Vincent"), + User(id: 1, name: "Jules") +] +let target = [ + User(id: 1, name: "Jules"), + User(id: 0, name: "Vincent"), + User(id: 2, name: "Butch") +] + +let changeset = StagedChangeset(source: source, target: target) +``` + +If you want to include multiple types conformed to `Differentiable` in the collection, use `AnyDifferentiable`: +```swift +let source = [ + AnyDifferentiable("A"), + AnyDifferentiable(User(id: 0, name: "Vincent")) +] +``` + +In the case of sectioned collection, the section itself must have a unique identifier and be able to compare whether there is an update. +So each section must conform to `DifferentiableSection` protocol, but in most cases you can use `ArraySection` that general type conformed to it. +`ArraySection` requires a model conforming to `Differentiable` for differentiate from other sections: +```swift +enum Model: Differentiable { + case a, b, c +} + +let source: [ArraySection] = [ + ArraySection(model: .a, elements: ["A", "B"]), + ArraySection(model: .b, elements: ["C"]) +] +let target: [ArraySection] = [ + ArraySection(model: .c, elements: ["D", "E"]), + ArraySection(model: .a, elements: ["A"]), + ArraySection(model: .b, elements: ["B", "C"]) +] + +let changeset = StagedChangeset(source: source, target: target) +``` + +You can perform incremental updates on `UITableView` and `UICollectionView` using the created `StagedChangeset`. + +⚠️ **Don't forget** to **synchronously** update the data referenced by the data-source, with the data passed in the `setData` closure. The differences are applied in stages, and failing to do so is bound to create a crash: + +```swift +tableView.reload(using: changeset, with: .fade) { data in + dataSource.data = data +} +``` + +Batch-updates using too large amount of differences may adversely affect to performance. +Returning `true` with `interrupt` closure then falls back to `reloadData`: +```swift +collectionView.reload(using: changeset, interrupt: { $0.changeCount > 100 }) { data in + dataSource.data = data +} +``` + +--- + +## Comparison with Other Frameworks +Made a fair comparison as much as possible in features and performance with other **popular** and **awesome** frameworks. +This does **NOT** determine superiority or inferiority of the frameworks. I know that each framework has different benefits. +The frameworks and its version that compared is below. + +- [DifferenceKit](https://github.com/ra1028/DifferenceKit) - master +- [RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources) ([Differentiator](https://github.com/RxSwiftCommunity/RxDataSources/tree/master/Sources/Differentiator)) - 3.0.2 +- [FlexibleDiff](https://github.com/RACCommunity/FlexibleDiff) - 0.0.5 +- [IGListKit](https://github.com/Instagram/IGListKit) - 3.4.0 +- [ListDiff](https://github.com/lxcid/ListDiff) - 0.1.0 +- [DeepDiff](https://github.com/onmyway133/DeepDiff) - 1.2.0 +- [Differ](https://github.com/tonyarnold/Differ) ([Diff.swift](https://github.com/wokalski/Diff.swift)) - 1.2.3 +- [Dwifft](https://github.com/jflinter/Dwifft) - 0.8 + +### Features comparison +#### - Supported collection +| |Linear|Sectioned|Duplicate Element/Section| +|:------------|:----:|:-------:|:-----------------------:| +|DifferenceKit|✅ |✅ |✅ | +|RxDataSources|❌ |✅ |❌ | +|FlexibleDiff |✅ |✅ |✅ | +|IGListKit |✅ |❌ |✅ | +|ListDiff |✅ |❌ |✅ | +|DeepDiff |✅ |❌ |✅ | +|Differ |✅ |✅ |✅ | +|Dwifft |✅ |✅ |✅ | + +`Linear` means 1-dimensional collection. +`Sectioned` means 2-dimensional collection. + +#### - Supported element differences +| |Delete|Insert|Move|Reload |Move across sections| +|:------------|:----:|:----:|:--:|:------:|:------------------:| +|DifferenceKit|✅ |✅ |✅ |✅ |✅ | +|RxDataSources|✅ |✅ |✅ |✅ |✅ | +|FlexibleDiff |✅ |✅ |✅ |✅ |❌ | +|IGListKit |✅ |✅ |✅ |✅ |❌ | +|ListDiff |✅ |✅ |✅ |✅ |❌ | +|DeepDiff |✅ |✅ |✅ |✅ / ❌ |❌ | +|Differ |✅ |✅ |✅ |❌ |❌ | +|Dwifft |✅ |✅ |❌ |❌ |❌ | + +#### - Supported section differences +| |Delete|Insert|Move|Reload| +|:------------|:----:|:----:|:--:|:----:| +|DifferenceKit|✅ |✅ |✅ |✅ | +|RxDataSources|✅ |✅ |✅ |❌ | +|FlexibleDiff |✅ |✅ |✅ |✅ | +|IGListKit |❌ |❌ |❌ |❌ | +|ListDiff |❌ |❌ |❌ |❌ | +|DeepDiff |❌ |❌ |❌ |❌ | +|Differ |✅ |✅ |✅ |❌ | +|Dwifft |✅ |✅ |❌ |❌ | + +### Performance comparison +Performance was measured using `XCTestCase.measure` on iPhoneX simulator with `-O -whole-module-optimization`. +Use `Foundation.UUID` as an element. + +⚠️ If Move is included in the difference, performance may obviously decrease in some frameworks. +⚠️ *DeepDiff may had increased the processing speed by misuse of Hashable in algorithm.* + +#### - From 5,000 elements to 500 deleted and 500 inserted +| |Time(second)| +|:------------|:-----------| +|DifferenceKit|0.0022 | +|RxDataSources|0.0078 | +|FlexibleDiff |0.0168 | +|IGListKit |0.0412 | +|ListDiff |0.0388 | +|DeepDiff |0.0150 | +|Differ |0.3260 | +|Dwifft |33.600 | + +#### - From 10,000 elements to 1,000 deleted and 1,000 inserted +| |Time(second)| +|:------------|:-----------| +|DifferenceKit|0.0049 | +|RxDataSources|0.0143 | +|FlexibleDiff |0.0305 | +|IGListKit |0.0891 | +|ListDiff |0.0802 | +|DeepDiff |0.0300 | +|Differ |1.3450 | +|Dwifft |❌ | + +#### - From 100,000 elements to 10,000 deleted and 10,000 inserted +| |Time(second)| +|:------------|:-----------| +|DifferenceKit|0.057 | +|RxDataSources|0.179 | +|FlexibleDiff |0.356 | +|IGListKit |1.329 | +|ListDiff |1.026 | +|DeepDiff |0.334 | +|Differ |❌ | +|Dwifft |❌ | + +--- + +## Requirements +- Swift4.2+ +- iOS 9.0+ +- tvOS 9.0+ +- OS X 10.9+ +- watchOS 2.0+ (only algorithm) + +--- + +## Installation + +### [CocoaPods](https://cocoapods.org/) +To use only algorithm without extensions for UI, add the following: +```ruby +use_frameworks! + +target 'TargetName' do + pod 'DifferenceKit/Core' +end +``` + +#### iOS/tvOS +To use DifferenceKit with UIKit extension, add the following to your `Podfile`: +```ruby +target 'TargetName' do + pod 'DifferenceKit' +end +``` +or +```ruby +target 'TargetName' do + pod 'DifferenceKit/UIKitExtension' +end +``` + +#### macOS +To use DifferenceKit with AppKit extension, add the following to your `Podfile`: +```ruby +target 'TargetName' do + pod 'DifferenceKit/AppKitExtension' +end +``` + +### watchOS +There is no UI extension for watchOS. +You can use only the algorithm. + +### [Carthage](https://github.com/Carthage/Carthage) +Add the following to your `Cartfile`: +```ruby +github "ra1028/DifferenceKit" +``` +And run +```sh +carthage update +``` + +--- + +## Contribution +Welcome to fork and submit pull requests. +Before submitting pull request, please ensure you have passed the included tests. +If your pull request including new function, please write test cases for it. + +--- + +## License +DifferenceKit is released under the [MIT License](https://github.com/ra1028/DifferenceKit/blob/master/LICENSE). diff --git a/Pods/DifferenceKit/Sources/Algorithm.swift b/Pods/DifferenceKit/Sources/Algorithm.swift new file mode 100644 index 0000000000..e16f2d044b --- /dev/null +++ b/Pods/DifferenceKit/Sources/Algorithm.swift @@ -0,0 +1,642 @@ +public extension StagedChangeset where Collection: RangeReplaceableCollection, Collection.Element: Differentiable { + /// Creates a new `StagedChangeset` from the two collections. + /// + /// Calculate the differences between the collections using + /// the algorithm optimized based on the Paul Heckel's diff algorithm. + /// + /// - Note: This algorithm can compute the differences at high performance with O(n) complexity. + /// However, not always calculates the shortest differences. + /// + /// - Note: If the elements with the same identifier duplicated, the algorithm calculates + /// the moves at best effort, and rest of the duplicates as insertion or deletion. + /// + /// - Note: The data and changes each changeset contains are represents the middle of whole the changes. + /// Each changes are from the previous stage. + /// + /// - Parameters: + /// - source: A source collection to calculate differences. + /// - target: A target collection to calculate differences. + /// + /// - Complexity: O(n) + @inlinable + public init(source: Collection, target: Collection) { + self.init(source: source, target: target, section: 0) + } + + /// Creates a new `StagedChangeset` from the two collections. + /// + /// Calculate the differences between the collections using + /// the algorithm optimized based on the Paul Heckel's diff algorithm. + /// + /// - Note: This algorithm can compute the differences at high performance with O(n) complexity. + /// However, not always calculates the shortest differences. + /// + /// - Note: If the elements with the same identifier duplicated, the algorithm calculates + /// the moves at best effort, and rest of the duplicates as insertion or deletion. + /// + /// - Note: The data and changes each changeset contains are represents the middle of whole the changes. + /// Each changes are from the previous stage. + /// + /// - Parameters: + /// - source: A source collection to calculate differences. + /// - target: A target collection to calculate differences. + /// - section: An Int value to use as section index (or offset) of element. + /// + /// - Complexity: O(n) + @inlinable + public init(source: Collection, target: Collection, section: Int) { + let sourceElements = ContiguousArray(source) + let targetElements = ContiguousArray(target) + + // Returns the empty changesets if both are empty. + if sourceElements.isEmpty && targetElements.isEmpty { + self.init() + return + } + + // Returns the changesets that all deletions if source is not empty and target is empty + if !sourceElements.isEmpty && targetElements.isEmpty { + self.init([Changeset(data: target, elementDeleted: sourceElements.indices.map { ElementPath(element: $0, section: section) })]) + return + } + + // Returns the changesets that all insertions if source is empty and target is not empty + if sourceElements.isEmpty && !targetElements.isEmpty { + self.init([Changeset(data: target, elementInserted: targetElements.indices.map { ElementPath(element: $0, section: section) })]) + return + } + + var firstStageElements = ContiguousArray() + + let result = differentiate( + source: sourceElements, + target: targetElements, + trackTargetIndexAsUpdated: false, + mapIndex: { ElementPath(element: $0, section: section) }, + remainedInTarget: { firstStageElements.append($0) } + ) + + var changesets = ContiguousArray>() + + // The 1st stage changeset. + // - Includes: + // - element deletes + // - element updates + if !result.deleted.isEmpty || !result.updated.isEmpty { + changesets.append( + Changeset( + data: Collection(firstStageElements), + elementDeleted: result.deleted, + elementUpdated: result.updated + ) + ) + } + + // The 2st stage changeset. + // - Includes: + // - element inserts + // - element moves + if !result.inserted.isEmpty || !result.moved.isEmpty { + changesets.append( + Changeset( + data: target, + elementInserted: result.inserted, + elementMoved: result.moved + ) + ) + } + + // Set the target to `data` of the last stage. + if !changesets.isEmpty { + let index = changesets.index(before: changesets.endIndex) + changesets[index].data = target + } + + self.init(changesets) + } +} + +public extension StagedChangeset where Collection: RangeReplaceableCollection, Collection.Element: DifferentiableSection { + /// Creates a new `StagedChangeset` from the two sectioned collections. + /// + /// Calculate the differences between the collections using + /// the algorithm optimized based on the Paul Heckel's diff algorithm. + /// + /// - Note: This algorithm can compute the differences at high performance with O(n) complexity. + /// However, not always calculates the shortest differences. + /// + /// - Note: If the elements with the same identifier duplicated, the algorithm calculates + /// the moves at best effort, and rest of the duplicates as insertion or deletion. + /// + /// - Note: The data and changes each changeset contains are represents the middle of whole the changes. + /// Each changes are from the previous stage. + /// + /// - Parameters: + /// - source: A source sectioned collection to calculate differences. + /// - target: A target sectioned collection to calculate differences. + /// + /// - Complexity: O(n) + @inlinable + public init(source: Collection, target: Collection) { + typealias Section = Collection.Element + typealias SectionIdentifier = Collection.Element.DifferenceIdentifier + typealias Element = Collection.Element.Collection.Element + typealias ElementIdentifier = Collection.Element.Collection.Element.DifferenceIdentifier + + let sourceSections = ContiguousArray(source) + let targetSections = ContiguousArray(target) + + let contiguousSourceSections = ContiguousArray(sourceSections.map { ContiguousArray($0.elements) }) + let contiguousTargetSections = ContiguousArray(targetSections.map { ContiguousArray($0.elements) }) + + var firstStageSections = ContiguousArray
() + var secondStageSections = ContiguousArray
() + var thirdStageSections = ContiguousArray
() + + var sourceElementTraces = contiguousSourceSections.map { section in + ContiguousArray(repeating: Trace(), count: section.count) + } + var targetElementReferences = contiguousTargetSections.map { section in + ContiguousArray(repeating: nil, count: section.count) + } + + let flattenSourceCount = contiguousSourceSections.reduce(into: 0) { $0 += $1.count } + var flattenSourceIdentifiers = ContiguousArray() + var flattenSourceElementPaths = ContiguousArray() + + secondStageSections.reserveCapacity(contiguousTargetSections.count) + thirdStageSections.reserveCapacity(contiguousTargetSections.count) + + flattenSourceIdentifiers.reserveCapacity(flattenSourceCount) + flattenSourceElementPaths.reserveCapacity(flattenSourceCount) + + // Calculate the section differences. + + let sectionResult = differentiate( + source: sourceSections, + target: targetSections, + trackTargetIndexAsUpdated: true, + mapIndex: { $0 } + ) + + // Calculate the element differences. + + var elementDeleted = [ElementPath]() + var elementInserted = [ElementPath]() + var elementUpdated = [ElementPath]() + var elementMoved = [(source: ElementPath, target: ElementPath)]() + + for sourceSectionIndex in contiguousSourceSections.indices { + for sourceElementIndex in contiguousSourceSections[sourceSectionIndex].indices { + let sourceElementPath = ElementPath(element: sourceElementIndex, section: sourceSectionIndex) + let sourceElement = contiguousSourceSections[sourceElementPath] + flattenSourceIdentifiers.append(sourceElement.differenceIdentifier) + flattenSourceElementPaths.append(sourceElementPath) + } + } + + flattenSourceIdentifiers.withUnsafeBufferPointer { bufferPointer in + // The pointer and the table key are for optimization. + var sourceOccurrencesTable = [TableKey: Occurrence](minimumCapacity: flattenSourceCount * 2) + + // Record the index where the element was found in flatten source collection into occurrences table. + for flattenSourceIndex in flattenSourceIdentifiers.indices { + let pointer = bufferPointer.baseAddress!.advanced(by: flattenSourceIndex) + let key = TableKey(pointer: pointer) + + switch sourceOccurrencesTable[key] { + case .none: + sourceOccurrencesTable[key] = .unique(index: flattenSourceIndex) + + case .unique(let otherIndex)?: + let reference = IndicesReference([otherIndex, flattenSourceIndex]) + sourceOccurrencesTable[key] = .duplicate(reference: reference) + + case .duplicate(let reference)?: + reference.push(flattenSourceIndex) + } + } + + // Record the target index and the source index that the element having the same identifier. + for targetSectionIndex in contiguousTargetSections.indices { + let targetElements = contiguousTargetSections[targetSectionIndex] + + for targetElementIndex in targetElements.indices { + var targetIdentifier = targetElements[targetElementIndex].differenceIdentifier + let key = TableKey(pointer: &targetIdentifier) + + switch sourceOccurrencesTable[key] { + case .none: + break + + case .unique(let flattenSourceIndex)?: + let sourceElementPath = flattenSourceElementPaths[flattenSourceIndex] + let targetElementPath = ElementPath(element: targetElementIndex, section: targetSectionIndex) + + if case .none = sourceElementTraces[sourceElementPath].reference { + targetElementReferences[targetElementPath] = sourceElementPath + sourceElementTraces[sourceElementPath].reference = targetElementPath + } + + case .duplicate(let reference)?: + if let flattenSourceIndex = reference.next() { + let sourceElementPath = flattenSourceElementPaths[flattenSourceIndex] + let targetElementPath = ElementPath(element: targetElementIndex, section: targetSectionIndex) + targetElementReferences[targetElementPath] = sourceElementPath + sourceElementTraces[sourceElementPath].reference = targetElementPath + } + } + } + } + } + + // Record the element deletions. + for sourceSectionIndex in contiguousSourceSections.indices { + // Should not calculate the element deletions in the deleted section. + guard case .some = sectionResult.metadata.sourceTraces[sourceSectionIndex].reference else { + continue + } + + var offsetByDelete = 0 + var firstStageElements = ContiguousArray() + let sourceElements = contiguousSourceSections[sourceSectionIndex] + + for sourceElementIndex in sourceElements.indices { + let sourceElementPath = ElementPath(element: sourceElementIndex, section: sourceSectionIndex) + + sourceElementTraces[sourceElementPath].deleteOffset = offsetByDelete + + // If the element target section is recorded as insertion, record its element path as deletion. + if let targetElementPath = sourceElementTraces[sourceElementPath].reference, + case .some = sectionResult.metadata.targetReferences[targetElementPath.section] { + let targetElement = contiguousTargetSections[targetElementPath] + firstStageElements.append(targetElement) + continue + } + + elementDeleted.append(sourceElementPath) + sourceElementTraces[sourceElementPath].isTracked = true + offsetByDelete += 1 + } + + let firstStageSection = Section(source: sourceSections[sourceSectionIndex], elements: firstStageElements) + firstStageSections.append(firstStageSection) + } + + // Record the element updates/moves/insertions. + for targetSectionIndex in contiguousTargetSections.indices { + // Should not calculate the element updates/moves/insertions in the inserted section. + guard let sourceSectionIndex = sectionResult.metadata.targetReferences[targetSectionIndex] else { + secondStageSections.append(targetSections[targetSectionIndex]) + thirdStageSections.append(targetSections[targetSectionIndex]) + continue + } + + var untrackedSourceIndex: Int? = 0 + let targetElements = contiguousTargetSections[targetSectionIndex] + + let sectionDeleteOffset = sectionResult.metadata.sourceTraces[sourceSectionIndex].deleteOffset + + let secondStageSection = firstStageSections[sourceSectionIndex - sectionDeleteOffset] + secondStageSections.append(secondStageSection) + + var thirdStageElements = ContiguousArray() + thirdStageElements.reserveCapacity(targetElements.count) + + for targetElementIndex in targetElements.indices { + untrackedSourceIndex = untrackedSourceIndex.flatMap { index in + sourceElementTraces[sourceSectionIndex].suffix(from: index).index { !$0.isTracked } + } + + let targetElementPath = ElementPath(element: targetElementIndex, section: targetSectionIndex) + let targetElement = contiguousTargetSections[targetElementPath] + + // If the element source section is recorded as deletion, record its element path as insertion. + guard let sourceElementPath = targetElementReferences[targetElementPath], + let movedSourceSectionIndex = sectionResult.metadata.sourceTraces[sourceElementPath.section].reference else { + thirdStageElements.append(targetElement) + elementInserted.append(targetElementPath) + continue + } + + sourceElementTraces[sourceElementPath].isTracked = true + + let sourceElement = contiguousSourceSections[sourceElementPath] + thirdStageElements.append(targetElement) + + if !targetElement.isContentEqual(to: sourceElement) { + elementUpdated.append(sourceElementPath) + } + + if sourceElementPath.section != sourceSectionIndex || sourceElementPath.element != untrackedSourceIndex { + let deleteOffset = sourceElementTraces[sourceElementPath].deleteOffset + let moveSourceElementPath = ElementPath(element: sourceElementPath.element - deleteOffset, section: movedSourceSectionIndex) + elementMoved.append((source: moveSourceElementPath, target: targetElementPath)) + } + } + + let thirdStageSection = Section(source: secondStageSection, elements: thirdStageElements) + thirdStageSections.append(thirdStageSection) + } + + var changesets = ContiguousArray>() + + // The 1st stage changeset. + // - Includes: + // - section deletes + // - element deletes + // - element updates + if !sectionResult.deleted.isEmpty || !elementDeleted.isEmpty || !elementUpdated.isEmpty { + changesets.append( + Changeset( + data: Collection(firstStageSections), + sectionDeleted: sectionResult.deleted, + elementDeleted: elementDeleted, + elementUpdated: elementUpdated + ) + ) + } + + // The 2nd stage changeset. + // - Includes: + // - section inserts + // - section moves + if !sectionResult.inserted.isEmpty || !sectionResult.moved.isEmpty { + changesets.append( + Changeset( + data: Collection(secondStageSections), + sectionInserted: sectionResult.inserted, + sectionMoved: sectionResult.moved + ) + ) + } + + // The 3rd stage changeset. + // - Includes: + // - element inserts + // - element moves + if !elementInserted.isEmpty || !elementMoved.isEmpty { + changesets.append( + Changeset( + data: Collection(thirdStageSections), + elementInserted: elementInserted, + elementMoved: elementMoved + ) + ) + } + + // The 4th stage changeset. + // - Includes: + // - section updates + if !sectionResult.updated.isEmpty { + changesets.append( + Changeset( + data: target, + sectionUpdated: sectionResult.updated + ) + ) + } + + // Set the target to `data` of the last stage. + if !changesets.isEmpty { + let index = changesets.index(before: changesets.endIndex) + changesets[index].data = target + } + + self.init(changesets) + } +} + +/// The shared algorithm to calculate differences between two linear collections. +@inlinable +@discardableResult +internal func differentiate( + source: ContiguousArray, + target: ContiguousArray, + trackTargetIndexAsUpdated: Bool, + mapIndex: (Int) -> I, + remainedInTarget: ((E) -> Void)? = nil + ) -> DifferentiateResult { + var deleted = [I]() + var inserted = [I]() + var updated = [I]() + var moved = [(source: I, target: I)]() + + var sourceTraces = ContiguousArray>() + var targetReferences = ContiguousArray(repeating: nil, count: target.count) + var sourceIdentifiers = ContiguousArray() + + sourceIdentifiers.reserveCapacity(source.count) + sourceTraces.reserveCapacity(source.count) + + for sourceElement in source { + sourceTraces.append(Trace()) + sourceIdentifiers.append(sourceElement.differenceIdentifier) + } + + sourceIdentifiers.withUnsafeBufferPointer { bufferPointer in + // The pointer and the table key are for optimization. + var sourceOccurrencesTable = [TableKey: Occurrence](minimumCapacity: source.count * 2) + + // Record the index where the element was found in source collection into occurrences table. + for sourceIndex in sourceIdentifiers.indices { + let pointer = bufferPointer.baseAddress!.advanced(by: sourceIndex) + let key = TableKey(pointer: pointer) + + switch sourceOccurrencesTable[key] { + case .none: + sourceOccurrencesTable[key] = .unique(index: sourceIndex) + + case .unique(let otherIndex)?: + let reference = IndicesReference([otherIndex, sourceIndex]) + sourceOccurrencesTable[key] = .duplicate(reference: reference) + + case .duplicate(let reference)?: + reference.push(sourceIndex) + } + } + + // Record the target index and the source index that the element having the same identifier. + for targetIndex in target.indices { + var targetIdentifier = target[targetIndex].differenceIdentifier + let key = TableKey(pointer: &targetIdentifier) + + switch sourceOccurrencesTable[key] { + case .none: + break + + case .unique(let sourceIndex)?: + if case .none = sourceTraces[sourceIndex].reference { + targetReferences[targetIndex] = sourceIndex + sourceTraces[sourceIndex].reference = targetIndex + } + + case .duplicate(let reference)?: + if let sourceIndex = reference.next() { + targetReferences[targetIndex] = sourceIndex + sourceTraces[sourceIndex].reference = targetIndex + } + } + } + } + + var offsetByDelete = 0 + var untrackedSourceIndex: Int? = 0 + + // Record the deletions. + for sourceIndex in source.indices { + sourceTraces[sourceIndex].deleteOffset = offsetByDelete + + if let targetIndex = sourceTraces[sourceIndex].reference { + let targetElement = target[targetIndex] + remainedInTarget?(targetElement) + } else { + deleted.append(mapIndex(sourceIndex)) + sourceTraces[sourceIndex].isTracked = true + offsetByDelete += 1 + } + } + + // Record the updates/moves/insertions. + for targetIndex in target.indices { + untrackedSourceIndex = untrackedSourceIndex.flatMap { index in + sourceTraces.suffix(from: index).index { !$0.isTracked } + } + + if let sourceIndex = targetReferences[targetIndex] { + sourceTraces[sourceIndex].isTracked = true + + let sourceElement = source[sourceIndex] + let targetElement = target[targetIndex] + + if !targetElement.isContentEqual(to: sourceElement) { + updated.append(mapIndex(trackTargetIndexAsUpdated ? targetIndex : sourceIndex)) + } + + if sourceIndex != untrackedSourceIndex { + let deleteOffset = sourceTraces[sourceIndex].deleteOffset + moved.append((source: mapIndex(sourceIndex - deleteOffset), target: mapIndex(targetIndex))) + } + } else { + inserted.append(mapIndex(targetIndex)) + } + } + + return DifferentiateResult( + deleted: deleted, + inserted: inserted, + updated: updated, + moved: moved, + metadata: (sourceTraces: sourceTraces, targetReferences: targetReferences) + ) +} + +/// A set of changes and metadata as a result of calculating differences in linear collection. +@usableFromInline +internal struct DifferentiateResult { + @usableFromInline + internal typealias Metadata = (sourceTraces: ContiguousArray>, targetReferences: ContiguousArray) + @usableFromInline + internal let deleted: [Index] + @usableFromInline + internal let inserted: [Index] + @usableFromInline + internal let updated: [Index] + @usableFromInline + internal let moved: [(source: Index, target: Index)] + @usableFromInline + internal let metadata: Metadata + + @inlinable + internal init( + deleted: [Index] = [], + inserted: [Index] = [], + updated: [Index] = [], + moved: [(source: Index, target: Index)] = [], + metadata: Metadata + ) { + self.deleted = deleted + self.inserted = inserted + self.updated = updated + self.moved = moved + self.metadata = metadata + } +} + +/// A set of informations in middle of difference calculation. +@usableFromInline +internal struct Trace { + @usableFromInline + internal var reference: Index? + @usableFromInline + internal var deleteOffset = 0 + @usableFromInline + internal var isTracked = false + + @inlinable + init() {} +} + +/// The occurrences of element. +@usableFromInline +internal enum Occurrence { + case unique(index: Int) + case duplicate(reference: IndicesReference) +} + +/// A mutable reference to indices of elements. +@usableFromInline +internal final class IndicesReference { + @usableFromInline + internal var indices: ContiguousArray + @usableFromInline + internal var position = 0 + + @inlinable + internal init(_ indices: ContiguousArray) { + self.indices = indices + } + + @inlinable + internal func push(_ index: Int) { + indices.append(index) + } + + @inlinable + internal func next() -> Int? { + guard position < indices.endIndex else { + return nil + } + defer { position += 1 } + return indices[position] + } +} + +/// Dictionary key using UnsafePointer for performance optimization. +@usableFromInline +internal struct TableKey: Hashable { + @usableFromInline + internal let hashValue: Int + @usableFromInline + internal let pointer: UnsafePointer + + @inlinable + internal init(pointer: UnsafePointer) { + self.hashValue = pointer.pointee.hashValue + self.pointer = pointer + } + + @inlinable + internal static func == (lhs: TableKey, rhs: TableKey) -> Bool { + return lhs.hashValue == rhs.hashValue + && (lhs.pointer.distance(to: rhs.pointer) == 0 || lhs.pointer.pointee == rhs.pointer.pointee) + } +} + +internal extension MutableCollection where Element: MutableCollection, Index == Int, Element.Index == Int { + @inlinable + internal subscript(path: ElementPath) -> Element.Element { + get { return self[path.section][path.element] } + set { self[path.section][path.element] = newValue } + } +} diff --git a/Pods/DifferenceKit/Sources/AnyDifferentiable.swift b/Pods/DifferenceKit/Sources/AnyDifferentiable.swift new file mode 100644 index 0000000000..cded673cc2 --- /dev/null +++ b/Pods/DifferenceKit/Sources/AnyDifferentiable.swift @@ -0,0 +1,104 @@ +/// A type-erased differentiable value. +/// +/// The `AnyDifferentiable` type hides the specific underlying types. +/// Associated type `DifferenceIdentifier` is erased by `AnyHashable`. +/// The comparisons of whether has updated is forwards to an underlying differentiable value. +/// +/// You can store mixed-type elements in collection that require `Differentiable` conformance by +/// wrapping mixed-type elements in `AnyDifferentiable`: +/// +/// extension String: Differentiable {} +/// extension Int: Differentiable {} +/// +/// let source = [ +/// AnyDifferentiable("ABC"), +/// AnyDifferentiable(100) +/// ] +/// let target = [ +/// AnyDifferentiable("ABC"), +/// AnyDifferentiable(100), +/// AnyDifferentiable(200) +/// ] +/// +/// let changeset = StagedChangeset(source: source, target: target) +/// print(changeset.isEmpty) // prints "false" +public struct AnyDifferentiable: Differentiable { + /// The value wrapped by this instance. + @inlinable + public var base: Any { + return box.base + } + + /// A type-erased identifier value for difference calculation. + @inlinable + public var differenceIdentifier: AnyHashable { + return box.differenceIdentifier + } + + @usableFromInline + internal let box: AnyDifferentiableBox + + /// Creates a type-erased differentiable value that wraps the given instance. + /// + /// - Parameters: + /// - base: A differentiable value to wrap. + @inlinable + public init(_ base: D) { + box = DifferentiableBox(base) + } + + /// Indicate whether the content of `base` is equals to the content of the given source value. + /// + /// - Parameters: + /// - source: A source value to be compared. + /// + /// - Returns: A Boolean value indicating whether the content of `base` is equals + /// to the content of `base` of the given source value. + @inlinable + public func isContentEqual(to source: AnyDifferentiable) -> Bool { + return box.isContentEqual(to: source.box) + } +} + +extension AnyDifferentiable: CustomDebugStringConvertible { + public var debugDescription: String { + return "AnyDifferentiable(\(String(reflecting: base)))" + } +} + +@usableFromInline +internal protocol AnyDifferentiableBox { + var base: Any { get } + var differenceIdentifier: AnyHashable { get } + + func isContentEqual(to source: AnyDifferentiableBox) -> Bool +} + +@usableFromInline +internal struct DifferentiableBox: AnyDifferentiableBox { + @usableFromInline + internal let baseComponent: Base + + @inlinable + internal var base: Any { + return baseComponent + } + + @inlinable + internal var differenceIdentifier: AnyHashable { + return AnyHashable(baseComponent.differenceIdentifier) + } + + @inlinable + internal init(_ base: Base) { + baseComponent = base + } + + @inlinable + internal func isContentEqual(to source: AnyDifferentiableBox) -> Bool { + guard let sourceBase = source.base as? Base else { + return false + } + return baseComponent.isContentEqual(to: sourceBase) + } +} diff --git a/Pods/DifferenceKit/Sources/ArraySection.swift b/Pods/DifferenceKit/Sources/ArraySection.swift new file mode 100644 index 0000000000..9716706afe --- /dev/null +++ b/Pods/DifferenceKit/Sources/ArraySection.swift @@ -0,0 +1,73 @@ +/// A differentiable section with model and array of elements. +/// +/// Arrays are can not be identify each one and comparing whether has updated from other one. +/// ArraySection is a generic wrapper to hold a model to allow it. +public struct ArraySection: DifferentiableSection { + /// The model of section for differentiated with other section. + public var model: Model + /// The array of element in the section. + public var elements: [Element] + + /// An identifier value that of model for difference calculation. + @inlinable + public var differenceIdentifier: Model.DifferenceIdentifier { + return model.differenceIdentifier + } + + /// Creates a section with the model and the elements. + /// + /// - Parameters: + /// - model: A differentiable model of section. + /// - elements: The collection of element in the section. + @inlinable + public init(model: Model, elements: C) where C.Element == Element { + self.model = model + self.elements = Array(elements) + } + + /// Creates a new section reproducing the given source section with replacing the elements. + /// + /// - Parameters: + /// - source: A source section to reproduce. + /// - elements: The collection of elements for the new section. + @inlinable + public init(source: ArraySection, elements: C) where C.Element == Element { + self.init(model: source.model, elements: elements) + } + + /// Indicate whether the content of `self` is equals to the content of + /// the given source section. + /// + /// - Note: It's compared by the model of `self` and the specified section. + /// + /// - Parameters: + /// - source: A source section to compare. + /// + /// - Returns: A Boolean value indicating whether the content of `self` is equals + /// to the content of the given source section. + @inlinable + public func isContentEqual(to source: ArraySection) -> Bool { + return model.isContentEqual(to: source.model) + } +} + +extension ArraySection: Equatable where Model: Equatable, Element: Equatable { + public static func == (lhs: ArraySection, rhs: ArraySection) -> Bool { + return lhs.model == rhs.model && lhs.elements == rhs.elements + } +} + +extension ArraySection: CustomDebugStringConvertible { + public var debugDescription: String { + guard !elements.isEmpty else { + return "ArraySection(model: \(model), elements: [])" + } + + return """ + ArraySection( + model: \(model), + elements: \(elements) + ) + """ + } +} diff --git a/Pods/DifferenceKit/Sources/Changeset.swift b/Pods/DifferenceKit/Sources/Changeset.swift new file mode 100644 index 0000000000..6c3d74eebc --- /dev/null +++ b/Pods/DifferenceKit/Sources/Changeset.swift @@ -0,0 +1,157 @@ +/// A set of changes in the sectioned collection. +/// +/// Changes to the section of the linear collection should be empty. +/// +/// Notice that the value of the changes represents offsets of collection not index. +/// Since offsets are unordered, order is ignored when comparing two `Changeset`s. +public struct Changeset { + /// The collection after changed. + public var data: Collection + + /// The offsets of deleted sections. + public var sectionDeleted: [Int] + /// The offsets of inserted sections. + public var sectionInserted: [Int] + /// The offsets of updated sections. + public var sectionUpdated: [Int] + /// The pairs of source and target offset of moved sections. + public var sectionMoved: [(source: Int, target: Int)] + + /// The paths of deleted elements. + public var elementDeleted: [ElementPath] + /// The paths of inserted elements. + public var elementInserted: [ElementPath] + /// The paths of updated elements. + public var elementUpdated: [ElementPath] + /// The pairs of source and target path of moved elements. + public var elementMoved: [(source: ElementPath, target: ElementPath)] + + /// Creates a new `Changeset`. + /// + /// - Parameters: + /// - data: The collection after changed. + /// - sectionDeleted: The offsets of deleted sections. + /// - sectionInserted: The offsets of inserted sections. + /// - sectionUpdated: The offsets of updated sections. + /// - sectionMoved: The pairs of source and target offset of moved sections. + /// - elementDeleted: The paths of deleted elements. + /// - elementInserted: The paths of inserted elements. + /// - elementUpdated: The paths of updated elements. + /// - elementMoved: The pairs of source and target path of moved elements. + @inlinable + public init( + data: Collection, + sectionDeleted: [Int] = [], + sectionInserted: [Int] = [], + sectionUpdated: [Int] = [], + sectionMoved: [(source: Int, target: Int)] = [], + elementDeleted: [ElementPath] = [], + elementInserted: [ElementPath] = [], + elementUpdated: [ElementPath] = [], + elementMoved: [(source: ElementPath, target: ElementPath)] = [] + ) { + self.data = data + self.sectionDeleted = sectionDeleted + self.sectionInserted = sectionInserted + self.sectionUpdated = sectionUpdated + self.sectionMoved = sectionMoved + self.elementDeleted = elementDeleted + self.elementInserted = elementInserted + self.elementUpdated = elementUpdated + self.elementMoved = elementMoved + } +} + +public extension Changeset { + /// The number of section changes. + @inlinable + public var sectionChangeCount: Int { + return sectionDeleted.count + + sectionInserted.count + + sectionUpdated.count + + sectionMoved.count + } + + /// The number of element changes. + @inlinable + public var elementChangeCount: Int { + return elementDeleted.count + + elementInserted.count + + elementUpdated.count + + elementMoved.count + } + + /// The number of all changes. + @inlinable + public var changeCount: Int { + return sectionChangeCount + elementChangeCount + } + + /// A Boolean value indicating whether has section changes. + @inlinable + public var hasSectionChanges: Bool { + return sectionChangeCount > 0 + } + + /// A Boolean value indicating whether has element changes. + @inlinable + public var hasElementChanges: Bool { + return elementChangeCount > 0 + } + + /// A Boolean value indicating whether has changes. + @inlinable + public var hasChanges: Bool { + return changeCount > 0 + } +} + +extension Changeset: Equatable where Collection: Equatable { + public static func == (lhs: Changeset, rhs: Changeset) -> Bool { + return lhs.data == rhs.data + && Set(lhs.sectionDeleted) == Set(rhs.sectionDeleted) + && Set(lhs.sectionInserted) == Set(rhs.sectionInserted) + && Set(lhs.sectionUpdated) == Set(rhs.sectionUpdated) + && Set(lhs.sectionMoved.map(HashablePair.init)) == Set(rhs.sectionMoved.map(HashablePair.init)) + && Set(lhs.elementDeleted) == Set(rhs.elementDeleted) + && Set(lhs.elementInserted) == Set(rhs.elementInserted) + && Set(lhs.elementUpdated) == Set(rhs.elementUpdated) + && Set(lhs.elementMoved.map(HashablePair.init)) == Set(rhs.elementMoved.map(HashablePair.init)) + } +} + +extension Changeset: CustomDebugStringConvertible { + public var debugDescription: String { + guard !data.isEmpty || hasChanges else { + return "Changeset(data: [])" + } + + var description = """ + Changeset( + data: \(data.isEmpty ? "[]" : "[\n \(data.map { "\($0)" }.joined(separator: ",\n").split(separator: "\n").joined(separator: "\n "))\n ]") + """ + + func appendDescription(name: String, elements: [T]) { + guard !elements.isEmpty else { return } + + description += ",\n \(name): [\n \(elements.map { "\($0)" }.joined(separator: ",\n").split(separator: "\n").joined(separator: "\n "))\n ]" + } + + appendDescription(name: "sectionDeleted", elements: sectionDeleted) + appendDescription(name: "sectionInserted", elements: sectionInserted) + appendDescription(name: "sectionUpdated", elements: sectionUpdated) + appendDescription(name: "sectionMoved", elements: sectionMoved) + appendDescription(name: "elementDeleted", elements: elementDeleted) + appendDescription(name: "elementInserted", elements: elementInserted) + appendDescription(name: "elementUpdated", elements: elementUpdated) + appendDescription(name: "elementMoved", elements: elementMoved) + + description += "\n)" + return description + } +} + +private struct HashablePair: Hashable { + let first: H + let second: H +} diff --git a/Pods/DifferenceKit/Sources/ContentEquatable.swift b/Pods/DifferenceKit/Sources/ContentEquatable.swift new file mode 100644 index 0000000000..7ba853b3cf --- /dev/null +++ b/Pods/DifferenceKit/Sources/ContentEquatable.swift @@ -0,0 +1,52 @@ +/// Represents a value that can compare whether the content are equal. +public protocol ContentEquatable { + /// Indicate whether the content of `self` is equals to the content of + /// the given source value. + /// + /// - Parameters: + /// - source: A source value to be compared. + /// + /// - Returns: A Boolean value indicating whether the content of `self` is equals + /// to the content of the given source value. + func isContentEqual(to source: Self) -> Bool +} + +public extension ContentEquatable where Self: Equatable { + /// Indicate whether the content of `self` is equals to the content of the given source value. + /// Compared using `==` operator of `Equatable'. + /// + /// - Parameters: + /// - source: A source value to be compared. + /// + /// - Returns: A Boolean value indicating whether the content of `self` is equals + /// to the content of the given source value. + @inlinable + func isContentEqual(to source: Self) -> Bool { + return self == source + } +} + +extension Optional: ContentEquatable where Wrapped: ContentEquatable { + /// Indicate whether the content of `self` is equals to the content of the given source value. + /// Returns `true` if both values compared are nil. + /// The result of comparison between nil and non-nil values is `false`. + /// + /// - Parameters: + /// - source: An optional source value to be compared. + /// + /// - Returns: A Boolean value indicating whether the content of `self` is equals + /// to the content of the given source value. + @inlinable + public func isContentEqual(to source: Wrapped?) -> Bool { + switch (self, source) { + case let (lhs?, rhs?): + return lhs.isContentEqual(to: rhs) + + case (.none, .none): + return true + + case (.none, .some), (.some, .none): + return false + } + } +} diff --git a/Pods/DifferenceKit/Sources/Differentiable.swift b/Pods/DifferenceKit/Sources/Differentiable.swift new file mode 100644 index 0000000000..0610b24021 --- /dev/null +++ b/Pods/DifferenceKit/Sources/Differentiable.swift @@ -0,0 +1,16 @@ +/// Represents the value that identified for differentiate. +public protocol Differentiable: ContentEquatable { + /// A type representing the identifier. + associatedtype DifferenceIdentifier: Hashable + + /// An identifier value for difference calculation. + var differenceIdentifier: DifferenceIdentifier { get } +} + +public extension Differentiable where Self: Hashable { + /// The `self` value as an identifier for difference calculation. + @inlinable + var differenceIdentifier: Self { + return self + } +} diff --git a/Pods/DifferenceKit/Sources/DifferentiableSection.swift b/Pods/DifferenceKit/Sources/DifferentiableSection.swift new file mode 100644 index 0000000000..0c0ec1877e --- /dev/null +++ b/Pods/DifferenceKit/Sources/DifferentiableSection.swift @@ -0,0 +1,15 @@ +/// Represents the section of collection that can be identified and compared to whether has updated. +public protocol DifferentiableSection: Differentiable { + /// A type representing the elements in section. + associatedtype Collection: Swift.Collection where Collection.Element: Differentiable + + /// The collection of element in the section. + var elements: Collection { get } + + /// Creates a new section reproducing the given source section with replacing the elements. + /// + /// - Parameters: + /// - source: A source section to reproduce. + /// - elements: The collection of elements for the new section. + init(source: Self, elements: C) where C.Element == Collection.Element +} diff --git a/Pods/DifferenceKit/Sources/ElementPath.swift b/Pods/DifferenceKit/Sources/ElementPath.swift new file mode 100644 index 0000000000..bbcaffa38f --- /dev/null +++ b/Pods/DifferenceKit/Sources/ElementPath.swift @@ -0,0 +1,26 @@ +/// Represents the path to a specific element in a tree of nested collections. +/// +/// - Note: `Foundation.IndexPath` is disadvantageous in performance. +public struct ElementPath: Hashable { + /// The element index (or offset) of this path. + public var element: Int + /// The section index (or offset) of this path. + public var section: Int + + /// Creates a new `ElementPath`. + /// + /// - Parameters: + /// - element: The element index (or offset). + /// - section: The section index (or offset). + @inlinable + public init(element: Int, section: Int) { + self.element = element + self.section = section + } +} + +extension ElementPath: CustomDebugStringConvertible { + public var debugDescription: String { + return "[element: \(element), section: \(section)]" + } +} diff --git a/Pods/DifferenceKit/Sources/Extensions/UIKitExtension.swift b/Pods/DifferenceKit/Sources/Extensions/UIKitExtension.swift new file mode 100644 index 0000000000..5b038684f0 --- /dev/null +++ b/Pods/DifferenceKit/Sources/Extensions/UIKitExtension.swift @@ -0,0 +1,205 @@ +#if os(iOS) || os(tvOS) +import UIKit + +public extension UITableView { + /// Applies multiple animated updates in stages using `StagedChangeset`. + /// + /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. + /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. + /// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages. + /// + /// - Parameters: + /// - stagedChangeset: A staged set of changes. + /// - animation: An option to animate the updates. + /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated + /// updates should be stopped and performed reloadData. Default is nil. + /// - setData: A closure that takes the collection as a parameter. + /// The collection should be set to data-source of UITableView. + func reload( + using stagedChangeset: StagedChangeset, + with animation: @autoclosure () -> RowAnimation, + interrupt: ((Changeset) -> Bool)? = nil, + setData: (C) -> Void + ) { + reload( + using: stagedChangeset, + deleteSectionsAnimation: animation, + insertSectionsAnimation: animation, + reloadSectionsAnimation: animation, + deleteRowsAnimation: animation, + insertRowsAnimation: animation, + reloadRowsAnimation: animation, + interrupt: interrupt, + setData: setData + ) + } + + /// Applies multiple animated updates in stages using `StagedChangeset`. + /// + /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. + /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. + /// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages. + /// + /// - Parameters: + /// - stagedChangeset: A staged set of changes. + /// - deleteSectionsAnimation: An option to animate the section deletion. + /// - insertSectionsAnimation: An option to animate the section insertion. + /// - reloadSectionsAnimation: An option to animate the section reload. + /// - deleteRowsAnimation: An option to animate the row deletion. + /// - insertRowsAnimation: An option to animate the row insertion. + /// - reloadRowsAnimation: An option to animate the row reload. + /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated + /// updates should be stopped and performed reloadData. Default is nil. + /// - setData: A closure that takes the collection as a parameter. + /// The collection should be set to data-source of UITableView. + func reload( + using stagedChangeset: StagedChangeset, + deleteSectionsAnimation: @autoclosure () -> RowAnimation, + insertSectionsAnimation: @autoclosure () -> RowAnimation, + reloadSectionsAnimation: @autoclosure () -> RowAnimation, + deleteRowsAnimation: @autoclosure () -> RowAnimation, + insertRowsAnimation: @autoclosure () -> RowAnimation, + reloadRowsAnimation: @autoclosure () -> RowAnimation, + interrupt: ((Changeset) -> Bool)? = nil, + setData: (C) -> Void + ) { + if case .none = window, let data = stagedChangeset.last?.data { + setData(data) + return reloadData() + } + + let contentOffset = self.contentOffset + + for changeset in stagedChangeset { + if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data { + setData(data) + return reloadData() + } + + _performBatchUpdates { + setData(changeset.data) + + if !changeset.sectionDeleted.isEmpty { + deleteSections(IndexSet(changeset.sectionDeleted), with: deleteSectionsAnimation()) + } + + if !changeset.sectionInserted.isEmpty { + insertSections(IndexSet(changeset.sectionInserted), with: insertSectionsAnimation()) + } + + if !changeset.sectionUpdated.isEmpty { + reloadSections(IndexSet(changeset.sectionUpdated), with: reloadSectionsAnimation()) + } + + for (source, target) in changeset.sectionMoved { + moveSection(source, toSection: target) + } + + if !changeset.elementDeleted.isEmpty { + deleteRows(at: changeset.elementDeleted.map { IndexPath(row: $0.element, section: $0.section) }, with: deleteRowsAnimation()) + } + + if !changeset.elementInserted.isEmpty { + insertRows(at: changeset.elementInserted.map { IndexPath(row: $0.element, section: $0.section) }, with: insertRowsAnimation()) + } + + if !changeset.elementUpdated.isEmpty { + reloadRows(at: changeset.elementUpdated.map { IndexPath(row: $0.element, section: $0.section) }, with: reloadRowsAnimation()) + } + + for (source, target) in changeset.elementMoved { + moveRow(at: IndexPath(row: source.element, section: source.section), to: IndexPath(row: target.element, section: target.section)) + } + } + } + + if contentSize.height > bounds.size.height { + setContentOffset(contentOffset, animated: false) + } + } + + private func _performBatchUpdates(_ updates: () -> Void) { + if #available(iOS 11.0, tvOS 11.0, *) { + performBatchUpdates(updates) + } else { + beginUpdates() + updates() + endUpdates() + } + } +} + +public extension UICollectionView { + /// Applies multiple animated updates in stages using `StagedChangeset`. + /// + /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. + /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. + /// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages. + /// + /// - Parameters: + /// - stagedChangeset: A staged set of changes. + /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated + /// updates should be stopped and performed reloadData. Default is nil. + /// - setData: A closure that takes the collection as a parameter. + /// The collection should be set to data-source of UICollectionView. + func reload( + using stagedChangeset: StagedChangeset, + interrupt: ((Changeset) -> Bool)? = nil, + setData: (C) -> Void + ) { + if case .none = window, let data = stagedChangeset.last?.data { + setData(data) + return reloadData() + } + + let contentOffset = self.contentOffset + + for changeset in stagedChangeset { + if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data { + setData(data) + return reloadData() + } + + performBatchUpdates({ + setData(changeset.data) + + if !changeset.sectionDeleted.isEmpty { + deleteSections(IndexSet(changeset.sectionDeleted)) + } + + if !changeset.sectionInserted.isEmpty { + insertSections(IndexSet(changeset.sectionInserted)) + } + + if !changeset.sectionUpdated.isEmpty { + reloadSections(IndexSet(changeset.sectionUpdated)) + } + + for (source, target) in changeset.sectionMoved { + moveSection(source, toSection: target) + } + + if !changeset.elementDeleted.isEmpty { + deleteItems(at: changeset.elementDeleted.map { IndexPath(item: $0.element, section: $0.section) }) + } + + if !changeset.elementInserted.isEmpty { + insertItems(at: changeset.elementInserted.map { IndexPath(item: $0.element, section: $0.section) }) + } + + if !changeset.elementUpdated.isEmpty { + reloadItems(at: changeset.elementUpdated.map { IndexPath(item: $0.element, section: $0.section) }) + } + + for (source, target) in changeset.elementMoved { + moveItem(at: IndexPath(item: source.element, section: source.section), to: IndexPath(item: target.element, section: target.section)) + } + }) + } + + if contentSize.height > bounds.size.height { + setContentOffset(contentOffset, animated: false) + } + } +} +#endif diff --git a/Pods/DifferenceKit/Sources/StagedChangeset.swift b/Pods/DifferenceKit/Sources/StagedChangeset.swift new file mode 100644 index 0000000000..a917203fd6 --- /dev/null +++ b/Pods/DifferenceKit/Sources/StagedChangeset.swift @@ -0,0 +1,99 @@ +/// An ordered collection of `Changeset` as staged set of changes in the sectioned collection. +/// +/// The order is representing the stages of changesets. +/// +/// We know that there are combination of changes that crash when applied simultaneously +/// in batch-updates of UI such as UITableView or UICollectionView. +/// The `StagedChangeset` created from the two collection is split at the minimal stages +/// that can be perform batch-updates with no crashes. +/// +/// Example for calculating differences between the two linear collections. +/// +/// extension String: Differentiable {} +/// +/// let source = ["A", "B", "C"] +/// let target = ["B", "C", "D"] +/// +/// let changeset = StagedChangeset(source: source, target: target) +/// print(changeset.isEmpty) // prints "false" +/// +/// Example for calculating differences between the two sectioned collections. +/// +/// let source = [ +/// Section(model: "A", elements: ["😉"]), +/// ] +/// let target = [ +/// Section(model: "A", elements: ["😉, 😺"]), +/// Section(model: "B", elements: ["😪"]) +/// ] +/// +/// let changeset = StagedChangeset(source: sectionedSource, target: sectionedTarget) +/// print(changeset.isEmpty) // prints "false" +public struct StagedChangeset { + @usableFromInline + internal var changesets: ContiguousArray> + + /// Creates a new `StagedChangeset`. + /// + /// - Parameters: + /// - changesets: The collection of `Changeset`. + @inlinable + public init(_ changesets: C) where C.Element == Changeset { + self.changesets = ContiguousArray(changesets) + } +} + +extension StagedChangeset: RandomAccessCollection, RangeReplaceableCollection, MutableCollection { + @inlinable + public init() { + self.init([]) + } + + @inlinable + public var startIndex: Int { + return changesets.startIndex + } + + @inlinable + public var endIndex: Int { + return changesets.endIndex + } + + @inlinable + public func index(after i: Int) -> Int { + return changesets.index(after: i) + } + + @inlinable + public subscript(position: Int) -> Changeset { + get { return changesets[position] } + set { changesets[position] = newValue } + } + + @inlinable + public mutating func replaceSubrange(_ subrange: R, with newElements: C) where C.Element == Changeset, R.Bound == Int { + changesets.replaceSubrange(subrange, with: newElements) + } +} + +extension StagedChangeset: Equatable where Collection: Equatable { + @inlinable + public static func == (lhs: StagedChangeset, rhs: StagedChangeset) -> Bool { + return lhs.changesets == rhs.changesets + } +} + +extension StagedChangeset: ExpressibleByArrayLiteral { + @inlinable + public init(arrayLiteral elements: Changeset...) { + self.init(elements) + } +} + +extension StagedChangeset: CustomDebugStringConvertible { + public var debugDescription: String { + guard !isEmpty else { return "[]" } + + return "[\n\(map { " \($0.debugDescription.split(separator: "\n").joined(separator: "\n "))" }.joined(separator: ",\n"))\n]" + } +} diff --git a/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImage.h b/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImage.h new file mode 100644 index 0000000000..f056c3b9ef --- /dev/null +++ b/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImage.h @@ -0,0 +1,84 @@ +// +// FLAnimatedImage.h +// Flipboard +// +// Created by Raphael Schaad on 7/8/13. +// Copyright (c) 2013-2015 Flipboard. All rights reserved. +// + + +#import + +// Allow user classes conveniently just importing one header. +#import "FLAnimatedImageView.h" + + +#ifndef NS_DESIGNATED_INITIALIZER + #if __has_attribute(objc_designated_initializer) + #define NS_DESIGNATED_INITIALIZER __attribute((objc_designated_initializer)) + #else + #define NS_DESIGNATED_INITIALIZER + #endif +#endif + +extern const NSTimeInterval kFLAnimatedImageDelayTimeIntervalMinimum; + +// +// An `FLAnimatedImage`'s job is to deliver frames in a highly performant way and works in conjunction with `FLAnimatedImageView`. +// It subclasses `NSObject` and not `UIImage` because it's only an "image" in the sense that a sea lion is a lion. +// It tries to intelligently choose the frame cache size depending on the image and memory situation with the goal to lower CPU usage for smaller ones, lower memory usage for larger ones and always deliver frames for high performant play-back. +// Note: `posterImage`, `size`, `loopCount`, `delayTimes` and `frameCount` don't change after successful initialization. +// +@interface FLAnimatedImage : NSObject + +@property (nonatomic, strong, readonly) UIImage *posterImage; // Guaranteed to be loaded; usually equivalent to `-imageLazilyCachedAtIndex:0` +@property (nonatomic, assign, readonly) CGSize size; // The `.posterImage`'s `.size` + +@property (nonatomic, assign, readonly) NSUInteger loopCount; // 0 means repeating the animation indefinitely +@property (nonatomic, strong, readonly) NSDictionary *delayTimesForIndexes; // Of type `NSTimeInterval` boxed in `NSNumber`s +@property (nonatomic, assign, readonly) NSUInteger frameCount; // Number of valid frames; equal to `[.delayTimes count]` + +@property (nonatomic, assign, readonly) NSUInteger frameCacheSizeCurrent; // Current size of intelligently chosen buffer window; can range in the interval [1..frameCount] +@property (nonatomic, assign) NSUInteger frameCacheSizeMax; // Allow to cap the cache size; 0 means no specific limit (default) + +// Intended to be called from main thread synchronously; will return immediately. +// If the result isn't cached, will return `nil`; the caller should then pause playback, not increment frame counter and keep polling. +// After an initial loading time, depending on `frameCacheSize`, frames should be available immediately from the cache. +- (UIImage *)imageLazilyCachedAtIndex:(NSUInteger)index; + +// Pass either a `UIImage` or an `FLAnimatedImage` and get back its size ++ (CGSize)sizeForImage:(id)image; + +// On success, the initializers return an `FLAnimatedImage` with all fields initialized, on failure they return `nil` and an error will be logged. +- (instancetype)initWithAnimatedGIFData:(NSData *)data; +// Pass 0 for optimalFrameCacheSize to get the default, predrawing is enabled by default. +- (instancetype)initWithAnimatedGIFData:(NSData *)data optimalFrameCacheSize:(NSUInteger)optimalFrameCacheSize predrawingEnabled:(BOOL)isPredrawingEnabled NS_DESIGNATED_INITIALIZER; ++ (instancetype)animatedImageWithGIFData:(NSData *)data; + +@property (nonatomic, strong, readonly) NSData *data; // The data the receiver was initialized with; read-only + +@end + +typedef NS_ENUM(NSUInteger, FLLogLevel) { + FLLogLevelNone = 0, + FLLogLevelError, + FLLogLevelWarn, + FLLogLevelInfo, + FLLogLevelDebug, + FLLogLevelVerbose +}; + +@interface FLAnimatedImage (Logging) + ++ (void)setLogBlock:(void (^)(NSString *logString, FLLogLevel logLevel))logBlock logLevel:(FLLogLevel)logLevel; ++ (void)logStringFromBlock:(NSString *(^)(void))stringBlock withLevel:(FLLogLevel)level; + +@end + +#define FLLog(logLevel, format, ...) [FLAnimatedImage logStringFromBlock:^NSString *{ return [NSString stringWithFormat:(format), ## __VA_ARGS__]; } withLevel:(logLevel)] + +@interface FLWeakProxy : NSProxy + ++ (instancetype)weakProxyForObject:(id)targetObject; + +@end diff --git a/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImage.m b/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImage.m new file mode 100755 index 0000000000..3fdddc969b --- /dev/null +++ b/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImage.m @@ -0,0 +1,816 @@ +// +// FLAnimatedImage.m +// Flipboard +// +// Created by Raphael Schaad on 7/8/13. +// Copyright (c) 2013-2015 Flipboard. All rights reserved. +// + + +#import "FLAnimatedImage.h" +#import +#import + + +// From vm_param.h, define for iOS 8.0 or higher to build on device. +#ifndef BYTE_SIZE + #define BYTE_SIZE 8 // byte size in bits +#endif + +#define MEGABYTE (1024 * 1024) + +// This is how the fastest browsers do it as per 2012: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser-compatibility +const NSTimeInterval kFLAnimatedImageDelayTimeIntervalMinimum = 0.02; + +// An animated image's data size (dimensions * frameCount) category; its value is the max allowed memory (in MB). +// E.g.: A 100x200px GIF with 30 frames is ~2.3MB in our pixel format and would fall into the `FLAnimatedImageDataSizeCategoryAll` category. +typedef NS_ENUM(NSUInteger, FLAnimatedImageDataSizeCategory) { + FLAnimatedImageDataSizeCategoryAll = 10, // All frames permanently in memory (be nice to the CPU) + FLAnimatedImageDataSizeCategoryDefault = 75, // A frame cache of default size in memory (usually real-time performance and keeping low memory profile) + FLAnimatedImageDataSizeCategoryOnDemand = 250, // Only keep one frame at the time in memory (easier on memory, slowest performance) + FLAnimatedImageDataSizeCategoryUnsupported // Even for one frame too large, computer says no. +}; + +typedef NS_ENUM(NSUInteger, FLAnimatedImageFrameCacheSize) { + FLAnimatedImageFrameCacheSizeNoLimit = 0, // 0 means no specific limit + FLAnimatedImageFrameCacheSizeLowMemory = 1, // The minimum frame cache size; this will produce frames on-demand. + FLAnimatedImageFrameCacheSizeGrowAfterMemoryWarning = 2, // If we can produce the frames faster than we consume, one frame ahead will already result in a stutter-free playback. + FLAnimatedImageFrameCacheSizeDefault = 5 // Build up a comfy buffer window to cope with CPU hiccups etc. +}; + + +#if defined(DEBUG) && DEBUG +@protocol FLAnimatedImageDebugDelegate +@optional +- (void)debug_animatedImage:(FLAnimatedImage *)animatedImage didUpdateCachedFrames:(NSIndexSet *)indexesOfFramesInCache; +- (void)debug_animatedImage:(FLAnimatedImage *)animatedImage didRequestCachedFrame:(NSUInteger)index; +- (CGFloat)debug_animatedImagePredrawingSlowdownFactor:(FLAnimatedImage *)animatedImage; +@end +#endif + + +@interface FLAnimatedImage () + +@property (nonatomic, assign, readonly) NSUInteger frameCacheSizeOptimal; // The optimal number of frames to cache based on image size & number of frames; never changes +@property (nonatomic, assign, readonly, getter=isPredrawingEnabled) BOOL predrawingEnabled; // Enables predrawing of images to improve performance. +@property (nonatomic, assign) NSUInteger frameCacheSizeMaxInternal; // Allow to cap the cache size e.g. when memory warnings occur; 0 means no specific limit (default) +@property (nonatomic, assign) NSUInteger requestedFrameIndex; // Most recently requested frame index +@property (nonatomic, assign, readonly) NSUInteger posterImageFrameIndex; // Index of non-purgable poster image; never changes +@property (nonatomic, strong, readonly) NSMutableDictionary *cachedFramesForIndexes; +@property (nonatomic, strong, readonly) NSMutableIndexSet *cachedFrameIndexes; // Indexes of cached frames +@property (nonatomic, strong, readonly) NSMutableIndexSet *requestedFrameIndexes; // Indexes of frames that are currently produced in the background +@property (nonatomic, strong, readonly) NSIndexSet *allFramesIndexSet; // Default index set with the full range of indexes; never changes +@property (nonatomic, assign) NSUInteger memoryWarningCount; +@property (nonatomic, strong, readonly) dispatch_queue_t serialQueue; +@property (nonatomic, strong, readonly) __attribute__((NSObject)) CGImageSourceRef imageSource; + +// The weak proxy is used to break retain cycles with delayed actions from memory warnings. +// We are lying about the actual type here to gain static type checking and eliminate casts. +// The actual type of the object is `FLWeakProxy`. +@property (nonatomic, strong, readonly) FLAnimatedImage *weakProxy; + +#if defined(DEBUG) && DEBUG +@property (nonatomic, weak) id debug_delegate; +#endif + +@end + + +// For custom dispatching of memory warnings to avoid deallocation races since NSNotificationCenter doesn't retain objects it is notifying. +static NSHashTable *allAnimatedImagesWeak; + +@implementation FLAnimatedImage + +#pragma mark - Accessors +#pragma mark Public + +// This is the definite value the frame cache needs to size itself to. +- (NSUInteger)frameCacheSizeCurrent +{ + NSUInteger frameCacheSizeCurrent = self.frameCacheSizeOptimal; + + // If set, respect the caps. + if (self.frameCacheSizeMax > FLAnimatedImageFrameCacheSizeNoLimit) { + frameCacheSizeCurrent = MIN(frameCacheSizeCurrent, self.frameCacheSizeMax); + } + + if (self.frameCacheSizeMaxInternal > FLAnimatedImageFrameCacheSizeNoLimit) { + frameCacheSizeCurrent = MIN(frameCacheSizeCurrent, self.frameCacheSizeMaxInternal); + } + + return frameCacheSizeCurrent; +} + + +- (void)setFrameCacheSizeMax:(NSUInteger)frameCacheSizeMax +{ + if (_frameCacheSizeMax != frameCacheSizeMax) { + + // Remember whether the new cap will cause the current cache size to shrink; then we'll make sure to purge from the cache if needed. + BOOL willFrameCacheSizeShrink = (frameCacheSizeMax < self.frameCacheSizeCurrent); + + // Update the value + _frameCacheSizeMax = frameCacheSizeMax; + + if (willFrameCacheSizeShrink) { + [self purgeFrameCacheIfNeeded]; + } + } +} + + +#pragma mark Private + +- (void)setFrameCacheSizeMaxInternal:(NSUInteger)frameCacheSizeMaxInternal +{ + if (_frameCacheSizeMaxInternal != frameCacheSizeMaxInternal) { + + // Remember whether the new cap will cause the current cache size to shrink; then we'll make sure to purge from the cache if needed. + BOOL willFrameCacheSizeShrink = (frameCacheSizeMaxInternal < self.frameCacheSizeCurrent); + + // Update the value + _frameCacheSizeMaxInternal = frameCacheSizeMaxInternal; + + if (willFrameCacheSizeShrink) { + [self purgeFrameCacheIfNeeded]; + } + } +} + + +#pragma mark - Life Cycle + ++ (void)initialize +{ + if (self == [FLAnimatedImage class]) { + // UIKit memory warning notification handler shared by all of the instances + allAnimatedImagesWeak = [NSHashTable weakObjectsHashTable]; + + [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:nil usingBlock:^(NSNotification *note) { + // UIKit notifications are posted on the main thread. didReceiveMemoryWarning: is expecting the main run loop, and we don't lock on allAnimatedImagesWeak + NSAssert([NSThread isMainThread], @"Received memory warning on non-main thread"); + // Get a strong reference to all of the images. If an instance is returned in this array, it is still live and has not entered dealloc. + // Note that FLAnimatedImages can be created on any thread, so the hash table must be locked. + NSArray *images = nil; + @synchronized(allAnimatedImagesWeak) { + images = [[allAnimatedImagesWeak allObjects] copy]; + } + // Now issue notifications to all of the images while holding a strong reference to them + [images makeObjectsPerformSelector:@selector(didReceiveMemoryWarning:) withObject:note]; + }]; + } +} + + +- (instancetype)init +{ + FLAnimatedImage *animatedImage = [self initWithAnimatedGIFData:nil]; + if (!animatedImage) { + FLLog(FLLogLevelError, @"Use `-initWithAnimatedGIFData:` and supply the animated GIF data as an argument to initialize an object of type `FLAnimatedImage`."); + } + return animatedImage; +} + + +- (instancetype)initWithAnimatedGIFData:(NSData *)data +{ + return [self initWithAnimatedGIFData:data optimalFrameCacheSize:0 predrawingEnabled:YES]; +} + +- (instancetype)initWithAnimatedGIFData:(NSData *)data optimalFrameCacheSize:(NSUInteger)optimalFrameCacheSize predrawingEnabled:(BOOL)isPredrawingEnabled +{ + // Early return if no data supplied! + BOOL hasData = ([data length] > 0); + if (!hasData) { + FLLog(FLLogLevelError, @"No animated GIF data supplied."); + return nil; + } + + self = [super init]; + if (self) { + // Do one-time initializations of `readonly` properties directly to ivar to prevent implicit actions and avoid need for private `readwrite` property overrides. + + // Keep a strong reference to `data` and expose it read-only publicly. + // However, we will use the `_imageSource` as handler to the image data throughout our life cycle. + _data = data; + _predrawingEnabled = isPredrawingEnabled; + + // Initialize internal data structures + _cachedFramesForIndexes = [[NSMutableDictionary alloc] init]; + _cachedFrameIndexes = [[NSMutableIndexSet alloc] init]; + _requestedFrameIndexes = [[NSMutableIndexSet alloc] init]; + + // Note: We could leverage `CGImageSourceCreateWithURL` too to add a second initializer `-initWithAnimatedGIFContentsOfURL:`. + _imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, + (__bridge CFDictionaryRef)@{(NSString *)kCGImageSourceShouldCache: @NO}); + // Early return on failure! + if (!_imageSource) { + FLLog(FLLogLevelError, @"Failed to `CGImageSourceCreateWithData` for animated GIF data %@", data); + return nil; + } + + // Early return if not GIF! + CFStringRef imageSourceContainerType = CGImageSourceGetType(_imageSource); + BOOL isGIFData = UTTypeConformsTo(imageSourceContainerType, kUTTypeGIF); + if (!isGIFData) { + FLLog(FLLogLevelError, @"Supplied data is of type %@ and doesn't seem to be GIF data %@", imageSourceContainerType, data); + return nil; + } + + // Get `LoopCount` + // Note: 0 means repeating the animation indefinitely. + // Image properties example: + // { + // FileSize = 314446; + // "{GIF}" = { + // HasGlobalColorMap = 1; + // LoopCount = 0; + // }; + // } + NSDictionary *imageProperties = (__bridge_transfer NSDictionary *)CGImageSourceCopyProperties(_imageSource, NULL); + _loopCount = [[[imageProperties objectForKey:(id)kCGImagePropertyGIFDictionary] objectForKey:(id)kCGImagePropertyGIFLoopCount] unsignedIntegerValue]; + + // Iterate through frame images + size_t imageCount = CGImageSourceGetCount(_imageSource); + NSUInteger skippedFrameCount = 0; + NSMutableDictionary *delayTimesForIndexesMutable = [NSMutableDictionary dictionaryWithCapacity:imageCount]; + for (size_t i = 0; i < imageCount; i++) { + @autoreleasepool { + CGImageRef frameImageRef = CGImageSourceCreateImageAtIndex(_imageSource, i, NULL); + if (frameImageRef) { + UIImage *frameImage = [UIImage imageWithCGImage:frameImageRef]; + // Check for valid `frameImage` before parsing its properties as frames can be corrupted (and `frameImage` even `nil` when `frameImageRef` was valid). + if (frameImage) { + // Set poster image + if (!self.posterImage) { + _posterImage = frameImage; + // Set its size to proxy our size. + _size = _posterImage.size; + // Remember index of poster image so we never purge it; also add it to the cache. + _posterImageFrameIndex = i; + [self.cachedFramesForIndexes setObject:self.posterImage forKey:@(self.posterImageFrameIndex)]; + [self.cachedFrameIndexes addIndex:self.posterImageFrameIndex]; + } + + // Get `DelayTime` + // Note: It's not in (1/100) of a second like still falsely described in the documentation as per iOS 8 (rdar://19507384) but in seconds stored as `kCFNumberFloat32Type`. + // Frame properties example: + // { + // ColorModel = RGB; + // Depth = 8; + // PixelHeight = 960; + // PixelWidth = 640; + // "{GIF}" = { + // DelayTime = "0.4"; + // UnclampedDelayTime = "0.4"; + // }; + // } + + NSDictionary *frameProperties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(_imageSource, i, NULL); + NSDictionary *framePropertiesGIF = [frameProperties objectForKey:(id)kCGImagePropertyGIFDictionary]; + + // Try to use the unclamped delay time; fall back to the normal delay time. + NSNumber *delayTime = [framePropertiesGIF objectForKey:(id)kCGImagePropertyGIFUnclampedDelayTime]; + if (!delayTime) { + delayTime = [framePropertiesGIF objectForKey:(id)kCGImagePropertyGIFDelayTime]; + } + // If we don't get a delay time from the properties, fall back to `kDelayTimeIntervalDefault` or carry over the preceding frame's value. + const NSTimeInterval kDelayTimeIntervalDefault = 0.1; + if (!delayTime) { + if (i == 0) { + FLLog(FLLogLevelInfo, @"Falling back to default delay time for first frame %@ because none found in GIF properties %@", frameImage, frameProperties); + delayTime = @(kDelayTimeIntervalDefault); + } else { + FLLog(FLLogLevelInfo, @"Falling back to preceding delay time for frame %zu %@ because none found in GIF properties %@", i, frameImage, frameProperties); + delayTime = delayTimesForIndexesMutable[@(i - 1)]; + } + } + // Support frame delays as low as `kFLAnimatedImageDelayTimeIntervalMinimum`, with anything below being rounded up to `kDelayTimeIntervalDefault` for legacy compatibility. + // To support the minimum even when rounding errors occur, use an epsilon when comparing. We downcast to float because that's what we get for delayTime from ImageIO. + if ([delayTime floatValue] < ((float)kFLAnimatedImageDelayTimeIntervalMinimum - FLT_EPSILON)) { + FLLog(FLLogLevelInfo, @"Rounding frame %zu's `delayTime` from %f up to default %f (minimum supported: %f).", i, [delayTime floatValue], kDelayTimeIntervalDefault, kFLAnimatedImageDelayTimeIntervalMinimum); + delayTime = @(kDelayTimeIntervalDefault); + } + delayTimesForIndexesMutable[@(i)] = delayTime; + } else { + skippedFrameCount++; + FLLog(FLLogLevelInfo, @"Dropping frame %zu because valid `CGImageRef` %@ did result in `nil`-`UIImage`.", i, frameImageRef); + } + CFRelease(frameImageRef); + } else { + skippedFrameCount++; + FLLog(FLLogLevelInfo, @"Dropping frame %zu because failed to `CGImageSourceCreateImageAtIndex` with image source %@", i, _imageSource); + } + } + } + _delayTimesForIndexes = [delayTimesForIndexesMutable copy]; + _frameCount = imageCount; + + if (self.frameCount == 0) { + FLLog(FLLogLevelInfo, @"Failed to create any valid frames for GIF with properties %@", imageProperties); + return nil; + } else if (self.frameCount == 1) { + // Warn when we only have a single frame but return a valid GIF. + FLLog(FLLogLevelInfo, @"Created valid GIF but with only a single frame. Image properties: %@", imageProperties); + } else { + // We have multiple frames, rock on! + } + + // If no value is provided, select a default based on the GIF. + if (optimalFrameCacheSize == 0) { + // Calculate the optimal frame cache size: try choosing a larger buffer window depending on the predicted image size. + // It's only dependent on the image size & number of frames and never changes. + CGFloat animatedImageDataSize = CGImageGetBytesPerRow(self.posterImage.CGImage) * self.size.height * (self.frameCount - skippedFrameCount) / MEGABYTE; + if (animatedImageDataSize <= FLAnimatedImageDataSizeCategoryAll) { + _frameCacheSizeOptimal = self.frameCount; + } else if (animatedImageDataSize <= FLAnimatedImageDataSizeCategoryDefault) { + // This value doesn't depend on device memory much because if we're not keeping all frames in memory we will always be decoding 1 frame up ahead per 1 frame that gets played and at this point we might as well just keep a small buffer just large enough to keep from running out of frames. + _frameCacheSizeOptimal = FLAnimatedImageFrameCacheSizeDefault; + } else { + // The predicted size exceeds the limits to build up a cache and we go into low memory mode from the beginning. + _frameCacheSizeOptimal = FLAnimatedImageFrameCacheSizeLowMemory; + } + } else { + // Use the provided value. + _frameCacheSizeOptimal = optimalFrameCacheSize; + } + // In any case, cap the optimal cache size at the frame count. + _frameCacheSizeOptimal = MIN(_frameCacheSizeOptimal, self.frameCount); + + // Convenience/minor performance optimization; keep an index set handy with the full range to return in `-frameIndexesToCache`. + _allFramesIndexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, self.frameCount)]; + + // See the property declarations for descriptions. + _weakProxy = (id)[FLWeakProxy weakProxyForObject:self]; + + // Register this instance in the weak table for memory notifications. The NSHashTable will clean up after itself when we're gone. + // Note that FLAnimatedImages can be created on any thread, so the hash table must be locked. + @synchronized(allAnimatedImagesWeak) { + [allAnimatedImagesWeak addObject:self]; + } + } + return self; +} + + ++ (instancetype)animatedImageWithGIFData:(NSData *)data +{ + FLAnimatedImage *animatedImage = [[FLAnimatedImage alloc] initWithAnimatedGIFData:data]; + return animatedImage; +} + + +- (void)dealloc +{ + if (_weakProxy) { + [NSObject cancelPreviousPerformRequestsWithTarget:_weakProxy]; + } + + if (_imageSource) { + CFRelease(_imageSource); + } +} + + +#pragma mark - Public Methods + +// See header for more details. +// Note: both consumer and producer are throttled: consumer by frame timings and producer by the available memory (max buffer window size). +- (UIImage *)imageLazilyCachedAtIndex:(NSUInteger)index +{ + // Early return if the requested index is beyond bounds. + // Note: We're comparing an index with a count and need to bail on greater than or equal to. + if (index >= self.frameCount) { + FLLog(FLLogLevelWarn, @"Skipping requested frame %lu beyond bounds (total frame count: %lu) for animated image: %@", (unsigned long)index, (unsigned long)self.frameCount, self); + return nil; + } + + // Remember requested frame index, this influences what we should cache next. + self.requestedFrameIndex = index; +#if defined(DEBUG) && DEBUG + if ([self.debug_delegate respondsToSelector:@selector(debug_animatedImage:didRequestCachedFrame:)]) { + [self.debug_delegate debug_animatedImage:self didRequestCachedFrame:index]; + } +#endif + + // Quick check to avoid doing any work if we already have all possible frames cached, a common case. + if ([self.cachedFrameIndexes count] < self.frameCount) { + // If we have frames that should be cached but aren't and aren't requested yet, request them. + // Exclude existing cached frames, frames already requested, and specially cached poster image. + NSMutableIndexSet *frameIndexesToAddToCacheMutable = [self frameIndexesToCache]; + [frameIndexesToAddToCacheMutable removeIndexes:self.cachedFrameIndexes]; + [frameIndexesToAddToCacheMutable removeIndexes:self.requestedFrameIndexes]; + [frameIndexesToAddToCacheMutable removeIndex:self.posterImageFrameIndex]; + NSIndexSet *frameIndexesToAddToCache = [frameIndexesToAddToCacheMutable copy]; + + // Asynchronously add frames to our cache. + if ([frameIndexesToAddToCache count] > 0) { + [self addFrameIndexesToCache:frameIndexesToAddToCache]; + } + } + + // Get the specified image. + UIImage *image = self.cachedFramesForIndexes[@(index)]; + + // Purge if needed based on the current playhead position. + [self purgeFrameCacheIfNeeded]; + + return image; +} + + +// Only called once from `-imageLazilyCachedAtIndex` but factored into its own method for logical grouping. +- (void)addFrameIndexesToCache:(NSIndexSet *)frameIndexesToAddToCache +{ + // Order matters. First, iterate over the indexes starting from the requested frame index. + // Then, if there are any indexes before the requested frame index, do those. + NSRange firstRange = NSMakeRange(self.requestedFrameIndex, self.frameCount - self.requestedFrameIndex); + NSRange secondRange = NSMakeRange(0, self.requestedFrameIndex); + if (firstRange.length + secondRange.length != self.frameCount) { + FLLog(FLLogLevelWarn, @"Two-part frame cache range doesn't equal full range."); + } + + // Add to the requested list before we actually kick them off, so they don't get into the queue twice. + [self.requestedFrameIndexes addIndexes:frameIndexesToAddToCache]; + + // Lazily create dedicated isolation queue. + if (!self.serialQueue) { + _serialQueue = dispatch_queue_create("com.flipboard.framecachingqueue", DISPATCH_QUEUE_SERIAL); + } + + // Start streaming requested frames in the background into the cache. + // Avoid capturing self in the block as there's no reason to keep doing work if the animated image went away. + FLAnimatedImage * __weak weakSelf = self; + dispatch_async(self.serialQueue, ^{ + // Produce and cache next needed frame. + void (^frameRangeBlock)(NSRange, BOOL *) = ^(NSRange range, BOOL *stop) { + // Iterate through contiguous indexes; can be faster than `enumerateIndexesInRange:options:usingBlock:`. + for (NSUInteger i = range.location; i < NSMaxRange(range); i++) { +#if defined(DEBUG) && DEBUG + CFTimeInterval predrawBeginTime = CACurrentMediaTime(); +#endif + UIImage *image = [weakSelf imageAtIndex:i]; +#if defined(DEBUG) && DEBUG + CFTimeInterval predrawDuration = CACurrentMediaTime() - predrawBeginTime; + CFTimeInterval slowdownDuration = 0.0; + if ([self.debug_delegate respondsToSelector:@selector(debug_animatedImagePredrawingSlowdownFactor:)]) { + CGFloat predrawingSlowdownFactor = [self.debug_delegate debug_animatedImagePredrawingSlowdownFactor:self]; + slowdownDuration = predrawDuration * predrawingSlowdownFactor - predrawDuration; + [NSThread sleepForTimeInterval:slowdownDuration]; + } + FLLog(FLLogLevelVerbose, @"Predrew frame %lu in %f ms for animated image: %@", (unsigned long)i, (predrawDuration + slowdownDuration) * 1000, self); +#endif + // The results get returned one by one as soon as they're ready (and not in batch). + // The benefits of having the first frames as quick as possible outweigh building up a buffer to cope with potential hiccups when the CPU suddenly gets busy. + if (image && weakSelf) { + dispatch_async(dispatch_get_main_queue(), ^{ + weakSelf.cachedFramesForIndexes[@(i)] = image; + [weakSelf.cachedFrameIndexes addIndex:i]; + [weakSelf.requestedFrameIndexes removeIndex:i]; +#if defined(DEBUG) && DEBUG + if ([weakSelf.debug_delegate respondsToSelector:@selector(debug_animatedImage:didUpdateCachedFrames:)]) { + [weakSelf.debug_delegate debug_animatedImage:weakSelf didUpdateCachedFrames:weakSelf.cachedFrameIndexes]; + } +#endif + }); + } + } + }; + + [frameIndexesToAddToCache enumerateRangesInRange:firstRange options:0 usingBlock:frameRangeBlock]; + [frameIndexesToAddToCache enumerateRangesInRange:secondRange options:0 usingBlock:frameRangeBlock]; + }); +} + + ++ (CGSize)sizeForImage:(id)image +{ + CGSize imageSize = CGSizeZero; + + // Early return for nil + if (!image) { + return imageSize; + } + + if ([image isKindOfClass:[UIImage class]]) { + UIImage *uiImage = (UIImage *)image; + imageSize = uiImage.size; + } else if ([image isKindOfClass:[FLAnimatedImage class]]) { + FLAnimatedImage *animatedImage = (FLAnimatedImage *)image; + imageSize = animatedImage.size; + } else { + // Bear trap to capture bad images; we have seen crashers cropping up on iOS 7. + FLLog(FLLogLevelError, @"`image` isn't of expected types `UIImage` or `FLAnimatedImage`: %@", image); + } + + return imageSize; +} + + +#pragma mark - Private Methods +#pragma mark Frame Loading + +- (UIImage *)imageAtIndex:(NSUInteger)index +{ + // It's very important to use the cached `_imageSource` since the random access to a frame with `CGImageSourceCreateImageAtIndex` turns from an O(1) into an O(n) operation when re-initializing the image source every time. + CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_imageSource, index, NULL); + + // Early return for nil + if (!imageRef) { + return nil; + } + + UIImage *image = [UIImage imageWithCGImage:imageRef]; + CFRelease(imageRef); + + // Loading in the image object is only half the work, the displaying image view would still have to synchronosly wait and decode the image, so we go ahead and do that here on the background thread. + if (self.isPredrawingEnabled) { + image = [[self class] predrawnImageFromImage:image]; + } + + return image; +} + + +#pragma mark Frame Caching + +- (NSMutableIndexSet *)frameIndexesToCache +{ + NSMutableIndexSet *indexesToCache = nil; + // Quick check to avoid building the index set if the number of frames to cache equals the total frame count. + if (self.frameCacheSizeCurrent == self.frameCount) { + indexesToCache = [self.allFramesIndexSet mutableCopy]; + } else { + indexesToCache = [[NSMutableIndexSet alloc] init]; + + // Add indexes to the set in two separate blocks- the first starting from the requested frame index, up to the limit or the end. + // The second, if needed, the remaining number of frames beginning at index zero. + NSUInteger firstLength = MIN(self.frameCacheSizeCurrent, self.frameCount - self.requestedFrameIndex); + NSRange firstRange = NSMakeRange(self.requestedFrameIndex, firstLength); + [indexesToCache addIndexesInRange:firstRange]; + NSUInteger secondLength = self.frameCacheSizeCurrent - firstLength; + if (secondLength > 0) { + NSRange secondRange = NSMakeRange(0, secondLength); + [indexesToCache addIndexesInRange:secondRange]; + } + // Double check our math, before we add the poster image index which may increase it by one. + if ([indexesToCache count] != self.frameCacheSizeCurrent) { + FLLog(FLLogLevelWarn, @"Number of frames to cache doesn't equal expected cache size."); + } + + [indexesToCache addIndex:self.posterImageFrameIndex]; + } + + return indexesToCache; +} + + +- (void)purgeFrameCacheIfNeeded +{ + // Purge frames that are currently cached but don't need to be. + // But not if we're still under the number of frames to cache. + // This way, if all frames are allowed to be cached (the common case), we can skip all the `NSIndexSet` math below. + if ([self.cachedFrameIndexes count] > self.frameCacheSizeCurrent) { + NSMutableIndexSet *indexesToPurge = [self.cachedFrameIndexes mutableCopy]; + [indexesToPurge removeIndexes:[self frameIndexesToCache]]; + [indexesToPurge enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) { + // Iterate through contiguous indexes; can be faster than `enumerateIndexesInRange:options:usingBlock:`. + for (NSUInteger i = range.location; i < NSMaxRange(range); i++) { + [self.cachedFrameIndexes removeIndex:i]; + [self.cachedFramesForIndexes removeObjectForKey:@(i)]; + // Note: Don't `CGImageSourceRemoveCacheAtIndex` on the image source for frames that we don't want cached any longer to maintain O(1) time access. +#if defined(DEBUG) && DEBUG + if ([self.debug_delegate respondsToSelector:@selector(debug_animatedImage:didUpdateCachedFrames:)]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.debug_delegate debug_animatedImage:self didUpdateCachedFrames:self.cachedFrameIndexes]; + }); + } +#endif + } + }]; + } +} + + +- (void)growFrameCacheSizeAfterMemoryWarning:(NSNumber *)frameCacheSize +{ + self.frameCacheSizeMaxInternal = [frameCacheSize unsignedIntegerValue]; + FLLog(FLLogLevelDebug, @"Grew frame cache size max to %lu after memory warning for animated image: %@", (unsigned long)self.frameCacheSizeMaxInternal, self); + + // Schedule resetting the frame cache size max completely after a while. + const NSTimeInterval kResetDelay = 3.0; + [self.weakProxy performSelector:@selector(resetFrameCacheSizeMaxInternal) withObject:nil afterDelay:kResetDelay]; +} + + +- (void)resetFrameCacheSizeMaxInternal +{ + self.frameCacheSizeMaxInternal = FLAnimatedImageFrameCacheSizeNoLimit; + FLLog(FLLogLevelDebug, @"Reset frame cache size max (current frame cache size: %lu) for animated image: %@", (unsigned long)self.frameCacheSizeCurrent, self); +} + + +#pragma mark System Memory Warnings Notification Handler + +- (void)didReceiveMemoryWarning:(NSNotification *)notification +{ + self.memoryWarningCount++; + + // If we were about to grow larger, but got rapped on our knuckles by the system again, cancel. + [NSObject cancelPreviousPerformRequestsWithTarget:self.weakProxy selector:@selector(growFrameCacheSizeAfterMemoryWarning:) object:@(FLAnimatedImageFrameCacheSizeGrowAfterMemoryWarning)]; + [NSObject cancelPreviousPerformRequestsWithTarget:self.weakProxy selector:@selector(resetFrameCacheSizeMaxInternal) object:nil]; + + // Go down to the minimum and by that implicitly immediately purge from the cache if needed to not get jettisoned by the system and start producing frames on-demand. + FLLog(FLLogLevelDebug, @"Attempt setting frame cache size max to %lu (previous was %lu) after memory warning #%lu for animated image: %@", (unsigned long)FLAnimatedImageFrameCacheSizeLowMemory, (unsigned long)self.frameCacheSizeMaxInternal, (unsigned long)self.memoryWarningCount, self); + self.frameCacheSizeMaxInternal = FLAnimatedImageFrameCacheSizeLowMemory; + + // Schedule growing larger again after a while, but cap our attempts to prevent a periodic sawtooth wave (ramps upward and then sharply drops) of memory usage. + // + // [mem]^ (2) (5) (6) 1) Loading frames for the first time + // (*)| , , , 2) Mem warning #1; purge cache + // | /| (4)/| /| 3) Grow cache size a bit after a while, if no mem warning occurs + // | / | _/ | _/ | 4) Try to grow cache size back to optimum after a while, if no mem warning occurs + // |(1)/ |_/ |/ |__(7) 5) Mem warning #2; purge cache + // |__/ (3) 6) After repetition of (3) and (4), mem warning #3; purge cache + // +----------------------> 7) After 3 mem warnings, stay at minimum cache size + // [t] + // *) The mem high water mark before we get warned might change for every cycle. + // + const NSUInteger kGrowAttemptsMax = 2; + const NSTimeInterval kGrowDelay = 2.0; + if ((self.memoryWarningCount - 1) <= kGrowAttemptsMax) { + [self.weakProxy performSelector:@selector(growFrameCacheSizeAfterMemoryWarning:) withObject:@(FLAnimatedImageFrameCacheSizeGrowAfterMemoryWarning) afterDelay:kGrowDelay]; + } + + // Note: It's not possible to get the level of a memory warning with a public API: http://stackoverflow.com/questions/2915247/iphone-os-memory-warnings-what-do-the-different-levels-mean/2915477#2915477 +} + + +#pragma mark Image Decoding + +// Decodes the image's data and draws it off-screen fully in memory; it's thread-safe and hence can be called on a background thread. +// On success, the returned object is a new `UIImage` instance with the same content as the one passed in. +// On failure, the returned object is the unchanged passed in one; the data will not be predrawn in memory though and an error will be logged. +// First inspired by & good Karma to: https://gist.github.com/steipete/1144242 ++ (UIImage *)predrawnImageFromImage:(UIImage *)imageToPredraw +{ + // Always use a device RGB color space for simplicity and predictability what will be going on. + CGColorSpaceRef colorSpaceDeviceRGBRef = CGColorSpaceCreateDeviceRGB(); + // Early return on failure! + if (!colorSpaceDeviceRGBRef) { + FLLog(FLLogLevelError, @"Failed to `CGColorSpaceCreateDeviceRGB` for image %@", imageToPredraw); + return imageToPredraw; + } + + // Even when the image doesn't have transparency, we have to add the extra channel because Quartz doesn't support other pixel formats than 32 bpp/8 bpc for RGB: + // kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst, kCGImageAlphaPremultipliedLast + // (source: docs "Quartz 2D Programming Guide > Graphics Contexts > Table 2-1 Pixel formats supported for bitmap graphics contexts") + size_t numberOfComponents = CGColorSpaceGetNumberOfComponents(colorSpaceDeviceRGBRef) + 1; // 4: RGB + A + + // "In iOS 4.0 and later, and OS X v10.6 and later, you can pass NULL if you want Quartz to allocate memory for the bitmap." (source: docs) + void *data = NULL; + size_t width = imageToPredraw.size.width; + size_t height = imageToPredraw.size.height; + size_t bitsPerComponent = CHAR_BIT; + + size_t bitsPerPixel = (bitsPerComponent * numberOfComponents); + size_t bytesPerPixel = (bitsPerPixel / BYTE_SIZE); + size_t bytesPerRow = (bytesPerPixel * width); + + CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault; + + CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageToPredraw.CGImage); + // If the alpha info doesn't match to one of the supported formats (see above), pick a reasonable supported one. + // "For bitmaps created in iOS 3.2 and later, the drawing environment uses the premultiplied ARGB format to store the bitmap data." (source: docs) + if (alphaInfo == kCGImageAlphaNone || alphaInfo == kCGImageAlphaOnly) { + alphaInfo = kCGImageAlphaNoneSkipFirst; + } else if (alphaInfo == kCGImageAlphaFirst) { + alphaInfo = kCGImageAlphaPremultipliedFirst; + } else if (alphaInfo == kCGImageAlphaLast) { + alphaInfo = kCGImageAlphaPremultipliedLast; + } + // "The constants for specifying the alpha channel information are declared with the `CGImageAlphaInfo` type but can be passed to this parameter safely." (source: docs) + bitmapInfo |= alphaInfo; + + // Create our own graphics context to draw to; `UIGraphicsGetCurrentContext`/`UIGraphicsBeginImageContextWithOptions` doesn't create a new context but returns the current one which isn't thread-safe (e.g. main thread could use it at the same time). + // Note: It's not worth caching the bitmap context for multiple frames ("unique key" would be `width`, `height` and `hasAlpha`), it's ~50% slower. Time spent in libRIP's `CGSBlendBGRA8888toARGB8888` suddenly shoots up -- not sure why. + CGContextRef bitmapContextRef = CGBitmapContextCreate(data, width, height, bitsPerComponent, bytesPerRow, colorSpaceDeviceRGBRef, bitmapInfo); + CGColorSpaceRelease(colorSpaceDeviceRGBRef); + // Early return on failure! + if (!bitmapContextRef) { + FLLog(FLLogLevelError, @"Failed to `CGBitmapContextCreate` with color space %@ and parameters (width: %zu height: %zu bitsPerComponent: %zu bytesPerRow: %zu) for image %@", colorSpaceDeviceRGBRef, width, height, bitsPerComponent, bytesPerRow, imageToPredraw); + return imageToPredraw; + } + + // Draw image in bitmap context and create image by preserving receiver's properties. + CGContextDrawImage(bitmapContextRef, CGRectMake(0.0, 0.0, imageToPredraw.size.width, imageToPredraw.size.height), imageToPredraw.CGImage); + CGImageRef predrawnImageRef = CGBitmapContextCreateImage(bitmapContextRef); + UIImage *predrawnImage = [UIImage imageWithCGImage:predrawnImageRef scale:imageToPredraw.scale orientation:imageToPredraw.imageOrientation]; + CGImageRelease(predrawnImageRef); + CGContextRelease(bitmapContextRef); + + // Early return on failure! + if (!predrawnImage) { + FLLog(FLLogLevelError, @"Failed to `imageWithCGImage:scale:orientation:` with image ref %@ created with color space %@ and bitmap context %@ and properties and properties (scale: %f orientation: %ld) for image %@", predrawnImageRef, colorSpaceDeviceRGBRef, bitmapContextRef, imageToPredraw.scale, (long)imageToPredraw.imageOrientation, imageToPredraw); + return imageToPredraw; + } + + return predrawnImage; +} + + +#pragma mark - Description + +- (NSString *)description +{ + NSString *description = [super description]; + + description = [description stringByAppendingFormat:@" size=%@", NSStringFromCGSize(self.size)]; + description = [description stringByAppendingFormat:@" frameCount=%lu", (unsigned long)self.frameCount]; + + return description; +} + + +@end + +#pragma mark - Logging + +@implementation FLAnimatedImage (Logging) + +static void (^_logBlock)(NSString *logString, FLLogLevel logLevel) = nil; +static FLLogLevel _logLevel; + ++ (void)setLogBlock:(void (^)(NSString *logString, FLLogLevel logLevel))logBlock logLevel:(FLLogLevel)logLevel +{ + _logBlock = logBlock; + _logLevel = logLevel; +} + ++ (void)logStringFromBlock:(NSString *(^)(void))stringBlock withLevel:(FLLogLevel)level +{ + if (level <= _logLevel && _logBlock && stringBlock) { + _logBlock(stringBlock(), level); + } +} + +@end + + +#pragma mark - FLWeakProxy + +@interface FLWeakProxy () + +@property (nonatomic, weak) id target; + +@end + + +@implementation FLWeakProxy + +#pragma mark Life Cycle + +// This is the designated creation method of an `FLWeakProxy` and +// as a subclass of `NSProxy` it doesn't respond to or need `-init`. ++ (instancetype)weakProxyForObject:(id)targetObject +{ + FLWeakProxy *weakProxy = [FLWeakProxy alloc]; + weakProxy.target = targetObject; + return weakProxy; +} + + +#pragma mark Forwarding Messages + +- (id)forwardingTargetForSelector:(SEL)selector +{ + // Keep it lightweight: access the ivar directly + return _target; +} + + +#pragma mark - NSWeakProxy Method Overrides +#pragma mark Handling Unimplemented Methods + +- (void)forwardInvocation:(NSInvocation *)invocation +{ + // Fallback for when target is nil. Don't do anything, just return 0/NULL/nil. + // The method signature we've received to get here is just a dummy to keep `doesNotRecognizeSelector:` from firing. + // We can't really handle struct return types here because we don't know the length. + void *nullPointer = NULL; + [invocation setReturnValue:&nullPointer]; +} + + +- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector +{ + // We only get here if `forwardingTargetForSelector:` returns nil. + // In that case, our weak target has been reclaimed. Return a dummy method signature to keep `doesNotRecognizeSelector:` from firing. + // We'll emulate the Obj-c messaging nil behavior by setting the return value to nil in `forwardInvocation:`, but we'll assume that the return value is `sizeof(void *)`. + // Other libraries handle this situation by making use of a global method signature cache, but that seems heavier than necessary and has issues as well. + // See https://www.mikeash.com/pyblog/friday-qa-2010-02-26-futures.html and https://github.com/steipete/PSTDelegateProxy/issues/1 for examples of using a method signature cache. + return [NSObject instanceMethodSignatureForSelector:@selector(init)]; +} + + +@end diff --git a/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImageView.h b/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImageView.h new file mode 100644 index 0000000000..c0d527aa65 --- /dev/null +++ b/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImageView.h @@ -0,0 +1,36 @@ +// +// FLAnimatedImageView.h +// Flipboard +// +// Created by Raphael Schaad on 7/8/13. +// Copyright (c) 2013-2015 Flipboard. All rights reserved. +// + + +#import + +@class FLAnimatedImage; +@protocol FLAnimatedImageViewDebugDelegate; + + +// +// An `FLAnimatedImageView` can take an `FLAnimatedImage` and plays it automatically when in view hierarchy and stops when removed. +// The animation can also be controlled with the `UIImageView` methods `-start/stop/isAnimating`. +// It is a fully compatible `UIImageView` subclass and can be used as a drop-in component to work with existing code paths expecting to display a `UIImage`. +// Under the hood it uses a `CADisplayLink` for playback, which can be inspected with `currentFrame` & `currentFrameIndex`. +// +@interface FLAnimatedImageView : UIImageView + +// Setting `[UIImageView.image]` to a non-`nil` value clears out existing `animatedImage`. +// And vice versa, setting `animatedImage` will initially populate the `[UIImageView.image]` to its `posterImage` and then start animating and hold `currentFrame`. +@property (nonatomic, strong) FLAnimatedImage *animatedImage; +@property (nonatomic, copy) void(^loopCompletionBlock)(NSUInteger loopCountRemaining); + +@property (nonatomic, strong, readonly) UIImage *currentFrame; +@property (nonatomic, assign, readonly) NSUInteger currentFrameIndex; + +// The animation runloop mode. Enables playback during scrolling by allowing timer events (i.e. animation) with NSRunLoopCommonModes. +// To keep scrolling smooth on single-core devices such as iPhone 3GS/4 and iPod Touch 4th gen, the default run loop mode is NSDefaultRunLoopMode. Otherwise, the default is NSDefaultRunLoopMode. +@property (nonatomic, copy) NSString *runLoopMode; + +@end diff --git a/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImageView.m b/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImageView.m new file mode 100755 index 0000000000..ffbb658113 --- /dev/null +++ b/Pods/FLAnimatedImage/FLAnimatedImage/FLAnimatedImageView.m @@ -0,0 +1,437 @@ +// +// FLAnimatedImageView.h +// Flipboard +// +// Created by Raphael Schaad on 7/8/13. +// Copyright (c) 2013-2015 Flipboard. All rights reserved. +// + + +#import "FLAnimatedImageView.h" +#import "FLAnimatedImage.h" +#import + + +#if defined(DEBUG) && DEBUG +@protocol FLAnimatedImageViewDebugDelegate +@optional +- (void)debug_animatedImageView:(FLAnimatedImageView *)animatedImageView waitingForFrame:(NSUInteger)index duration:(NSTimeInterval)duration; +@end +#endif + + +@interface FLAnimatedImageView () + +// Override of public `readonly` properties as private `readwrite` +@property (nonatomic, strong, readwrite) UIImage *currentFrame; +@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex; + +@property (nonatomic, assign) NSUInteger loopCountdown; +@property (nonatomic, assign) NSTimeInterval accumulator; +@property (nonatomic, strong) CADisplayLink *displayLink; + +@property (nonatomic, assign) BOOL shouldAnimate; // Before checking this value, call `-updateShouldAnimate` whenever the animated image or visibility (window, superview, hidden, alpha) has changed. +@property (nonatomic, assign) BOOL needsDisplayWhenImageBecomesAvailable; + +#if defined(DEBUG) && DEBUG +@property (nonatomic, weak) id debug_delegate; +#endif + +@end + + +@implementation FLAnimatedImageView +@synthesize runLoopMode = _runLoopMode; + +#pragma mark - Initializers + +// -initWithImage: isn't documented as a designated initializer of UIImageView, but it actually seems to be. +// Using -initWithImage: doesn't call any of the other designated initializers. +- (instancetype)initWithImage:(UIImage *)image +{ + self = [super initWithImage:image]; + if (self) { + [self commonInit]; + } + return self; +} + +// -initWithImage:highlightedImage: also isn't documented as a designated initializer of UIImageView, but it doesn't call any other designated initializers. +- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage +{ + self = [super initWithImage:image highlightedImage:highlightedImage]; + if (self) { + [self commonInit]; + } + return self; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + [self commonInit]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if (self) { + [self commonInit]; + } + return self; +} + +- (void)commonInit +{ + self.runLoopMode = [[self class] defaultRunLoopMode]; +} + + +#pragma mark - Accessors +#pragma mark Public + +- (void)setAnimatedImage:(FLAnimatedImage *)animatedImage +{ + if (![_animatedImage isEqual:animatedImage]) { + if (animatedImage) { + // Clear out the image. + super.image = nil; + // Ensure disabled highlighting; it's not supported (see `-setHighlighted:`). + super.highlighted = NO; + // UIImageView seems to bypass some accessors when calculating its intrinsic content size, so this ensures its intrinsic content size comes from the animated image. + [self invalidateIntrinsicContentSize]; + } else { + // Stop animating before the animated image gets cleared out. + [self stopAnimating]; + } + + _animatedImage = animatedImage; + + self.currentFrame = animatedImage.posterImage; + self.currentFrameIndex = 0; + if (animatedImage.loopCount > 0) { + self.loopCountdown = animatedImage.loopCount; + } else { + self.loopCountdown = NSUIntegerMax; + } + self.accumulator = 0.0; + + // Start animating after the new animated image has been set. + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } + + [self.layer setNeedsDisplay]; + } +} + + +#pragma mark - Life Cycle + +- (void)dealloc +{ + // Removes the display link from all run loop modes. + [_displayLink invalidate]; +} + + +#pragma mark - UIView Method Overrides +#pragma mark Observing View-Related Changes + +- (void)didMoveToSuperview +{ + [super didMoveToSuperview]; + + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} + + +- (void)didMoveToWindow +{ + [super didMoveToWindow]; + + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} + +- (void)setAlpha:(CGFloat)alpha +{ + [super setAlpha:alpha]; + + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} + +- (void)setHidden:(BOOL)hidden +{ + [super setHidden:hidden]; + + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} + + +#pragma mark Auto Layout + +- (CGSize)intrinsicContentSize +{ + // Default to let UIImageView handle the sizing of its image, and anything else it might consider. + CGSize intrinsicContentSize = [super intrinsicContentSize]; + + // If we have have an animated image, use its image size. + // UIImageView's intrinsic content size seems to be the size of its image. The obvious approach, simply calling `-invalidateIntrinsicContentSize` when setting an animated image, results in UIImageView steadfastly returning `{UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric}` for its intrinsicContentSize. + // (Perhaps UIImageView bypasses its `-image` getter in its implementation of `-intrinsicContentSize`, as `-image` is not called after calling `-invalidateIntrinsicContentSize`.) + if (self.animatedImage) { + intrinsicContentSize = self.image.size; + } + + return intrinsicContentSize; +} + + +#pragma mark - UIImageView Method Overrides +#pragma mark Image Data + +- (UIImage *)image +{ + UIImage *image = nil; + if (self.animatedImage) { + // Initially set to the poster image. + image = self.currentFrame; + } else { + image = super.image; + } + return image; +} + + +- (void)setImage:(UIImage *)image +{ + if (image) { + // Clear out the animated image and implicitly pause animation playback. + self.animatedImage = nil; + } + + super.image = image; +} + + +#pragma mark Animating Images + +- (NSTimeInterval)frameDelayGreatestCommonDivisor +{ + // Presision is set to half of the `kFLAnimatedImageDelayTimeIntervalMinimum` in order to minimize frame dropping. + const NSTimeInterval kGreatestCommonDivisorPrecision = 2.0 / kFLAnimatedImageDelayTimeIntervalMinimum; + + NSArray *delays = self.animatedImage.delayTimesForIndexes.allValues; + + // Scales the frame delays by `kGreatestCommonDivisorPrecision` + // then converts it to an UInteger for in order to calculate the GCD. + NSUInteger scaledGCD = lrint([delays.firstObject floatValue] * kGreatestCommonDivisorPrecision); + for (NSNumber *value in delays) { + scaledGCD = gcd(lrint([value floatValue] * kGreatestCommonDivisorPrecision), scaledGCD); + } + + // Reverse to scale to get the value back into seconds. + return scaledGCD / kGreatestCommonDivisorPrecision; +} + + +static NSUInteger gcd(NSUInteger a, NSUInteger b) +{ + // http://en.wikipedia.org/wiki/Greatest_common_divisor + if (a < b) { + return gcd(b, a); + } else if (a == b) { + return b; + } + + while (true) { + NSUInteger remainder = a % b; + if (remainder == 0) { + return b; + } + a = b; + b = remainder; + } +} + + +- (void)startAnimating +{ + if (self.animatedImage) { + // Lazily create the display link. + if (!self.displayLink) { + // It is important to note the use of a weak proxy here to avoid a retain cycle. `-displayLinkWithTarget:selector:` + // will retain its target until it is invalidated. We use a weak proxy so that the image view will get deallocated + // independent of the display link's lifetime. Upon image view deallocation, we invalidate the display + // link which will lead to the deallocation of both the display link and the weak proxy. + FLWeakProxy *weakProxy = [FLWeakProxy weakProxyForObject:self]; + self.displayLink = [CADisplayLink displayLinkWithTarget:weakProxy selector:@selector(displayDidRefresh:)]; + + [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode]; + } + + // Note: The display link's `.frameInterval` value of 1 (default) means getting callbacks at the refresh rate of the display (~60Hz). + // Setting it to 2 divides the frame rate by 2 and hence calls back at every other display refresh. + const NSTimeInterval kDisplayRefreshRate = 60.0; // 60Hz + self.displayLink.frameInterval = MAX([self frameDelayGreatestCommonDivisor] * kDisplayRefreshRate, 1); + + self.displayLink.paused = NO; + } else { + [super startAnimating]; + } +} + +- (void)setRunLoopMode:(NSString *)runLoopMode +{ + if (![@[NSDefaultRunLoopMode, NSRunLoopCommonModes] containsObject:runLoopMode]) { + NSAssert(NO, @"Invalid run loop mode: %@", runLoopMode); + _runLoopMode = [[self class] defaultRunLoopMode]; + } else { + _runLoopMode = runLoopMode; + } +} + +- (void)stopAnimating +{ + if (self.animatedImage) { + self.displayLink.paused = YES; + } else { + [super stopAnimating]; + } +} + + +- (BOOL)isAnimating +{ + BOOL isAnimating = NO; + if (self.animatedImage) { + isAnimating = self.displayLink && !self.displayLink.isPaused; + } else { + isAnimating = [super isAnimating]; + } + return isAnimating; +} + + +#pragma mark Highlighted Image Unsupport + +- (void)setHighlighted:(BOOL)highlighted +{ + // Highlighted image is unsupported for animated images, but implementing it breaks the image view when embedded in a UICollectionViewCell. + if (!self.animatedImage) { + [super setHighlighted:highlighted]; + } +} + + +#pragma mark - Private Methods +#pragma mark Animation + +// Don't repeatedly check our window & superview in `-displayDidRefresh:` for performance reasons. +// Just update our cached value whenever the animated image or visibility (window, superview, hidden, alpha) is changed. +- (void)updateShouldAnimate +{ + BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alpha > 0.0; + self.shouldAnimate = self.animatedImage && isVisible; +} + + +- (void)displayDidRefresh:(CADisplayLink *)displayLink +{ + // If for some reason a wild call makes it through when we shouldn't be animating, bail. + // Early return! + if (!self.shouldAnimate) { + FLLog(FLLogLevelWarn, @"Trying to animate image when we shouldn't: %@", self); + return; + } + + NSNumber *delayTimeNumber = [self.animatedImage.delayTimesForIndexes objectForKey:@(self.currentFrameIndex)]; + // If we don't have a frame delay (e.g. corrupt frame), don't update the view but skip the playhead to the next frame (in else-block). + if (delayTimeNumber) { + NSTimeInterval delayTime = [delayTimeNumber floatValue]; + // If we have a nil image (e.g. waiting for frame), don't update the view nor playhead. + UIImage *image = [self.animatedImage imageLazilyCachedAtIndex:self.currentFrameIndex]; + if (image) { + FLLog(FLLogLevelVerbose, @"Showing frame %lu for animated image: %@", (unsigned long)self.currentFrameIndex, self.animatedImage); + self.currentFrame = image; + if (self.needsDisplayWhenImageBecomesAvailable) { + [self.layer setNeedsDisplay]; + self.needsDisplayWhenImageBecomesAvailable = NO; + } + + self.accumulator += displayLink.duration * displayLink.frameInterval; + + // While-loop first inspired by & good Karma to: https://github.com/ondalabs/OLImageView/blob/master/OLImageView.m + while (self.accumulator >= delayTime) { + self.accumulator -= delayTime; + self.currentFrameIndex++; + if (self.currentFrameIndex >= self.animatedImage.frameCount) { + // If we've looped the number of times that this animated image describes, stop looping. + self.loopCountdown--; + if (self.loopCompletionBlock) { + self.loopCompletionBlock(self.loopCountdown); + } + + if (self.loopCountdown == 0) { + [self stopAnimating]; + return; + } + self.currentFrameIndex = 0; + } + // Calling `-setNeedsDisplay` will just paint the current frame, not the new frame that we may have moved to. + // Instead, set `needsDisplayWhenImageBecomesAvailable` to `YES` -- this will paint the new image once loaded. + self.needsDisplayWhenImageBecomesAvailable = YES; + } + } else { + FLLog(FLLogLevelDebug, @"Waiting for frame %lu for animated image: %@", (unsigned long)self.currentFrameIndex, self.animatedImage); +#if defined(DEBUG) && DEBUG + if ([self.debug_delegate respondsToSelector:@selector(debug_animatedImageView:waitingForFrame:duration:)]) { + [self.debug_delegate debug_animatedImageView:self waitingForFrame:self.currentFrameIndex duration:(NSTimeInterval)displayLink.duration * displayLink.frameInterval]; + } +#endif + } + } else { + self.currentFrameIndex++; + } +} + ++ (NSString *)defaultRunLoopMode +{ + // Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations. + return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode; +} + + +#pragma mark - CALayerDelegate (Informal) +#pragma mark Providing the Layer's Content + +- (void)displayLayer:(CALayer *)layer +{ + layer.contents = (__bridge id)self.image.CGImage; +} + + +@end diff --git a/Pods/FLAnimatedImage/LICENSE b/Pods/FLAnimatedImage/LICENSE new file mode 100644 index 0000000000..632653f9aa --- /dev/null +++ b/Pods/FLAnimatedImage/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2016 Flipboard + +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/FLAnimatedImage/README.md b/Pods/FLAnimatedImage/README.md new file mode 100644 index 0000000000..384122cd09 --- /dev/null +++ b/Pods/FLAnimatedImage/README.md @@ -0,0 +1,103 @@ +FLAnimatedImage is a performant animated GIF engine for iOS: + +- Plays multiple GIFs simultaneously with a playback speed comparable to desktop browsers +- Honors variable frame delays +- Behaves gracefully under memory pressure +- Eliminates delays or blocking during the first playback loop +- Interprets the frame delays of fast GIFs the same way modern browsers do + +It's a well-tested [component that powers all GIFs in Flipboard](http://engineering.flipboard.com/2014/05/animated-gif/). To understand its behavior it comes with an interactive demo: + +![Flipboard playing multiple GIFs](https://github.com/Flipboard/FLAnimatedImage/raw/master/images/flanimatedimage-demo-player.gif) + +## Who is this for? + +- Apps that don't support animated GIFs yet +- Apps that already support animated GIFs but want a higher performance solution +- People who want to tinker with the code ([the corresponding blog post](http://engineering.flipboard.com/2014/05/animated-gif/) is a great place to start; also see the *To Do* section below) + +## Installation & Usage + +FLAnimatedImage is a well encapsulated drop-in component. Simply replace your `UIImageView` instances with instances of `FLAnimatedImageView` to get animated GIF support. There is no central cache or state to manage. + +If using CocoaPods, the quickest way to try it out is to type this on the command line: + +```shell +$ pod try FLAnimatedImage +``` + +To add it to your app, copy the two classes `FLAnimatedImage.h/.m` and `FLAnimatedImageView.h/.m` into your Xcode project or add via [CocoaPods](http://cocoapods.org) by adding this to your Podfile: + +```ruby +pod 'FLAnimatedImage', '~> 1.0' +``` + +If using [Carthage](https://github.com/Carthage/Carthage), add following line into your `Cartfile` + +``` +github "Flipboard/FLAnimatedImage" +``` + +In your code, `#import "FLAnimatedImage.h"`, create an image from an animated GIF, and setup the image view to display it: + +```objective-c +FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif"]]]; +FLAnimatedImageView *imageView = [[FLAnimatedImageView alloc] init]; +imageView.animatedImage = image; +imageView.frame = CGRectMake(0.0, 0.0, 100.0, 100.0); +[self.view addSubview:imageView]; +``` + +It's flexible to integrate in your custom image loading stack and backwards compatible to iOS 6. + +It uses ARC and the Apple frameworks `QuartzCore`, `ImageIO`, `MobileCoreServices`, and `CoreGraphics`. + +It is capable of fine-grained logging. A block can be set on `FLAnimatedImage` that's invoked when logging occurs with various log levels via the `+setLogBlock:logLevel:` method. For example: + +```objective-c +// Set up FLAnimatedImage logging. +[FLAnimatedImage setLogBlock:^(NSString *logString, FLLogLevel logLevel) { + // Using NSLog + NSLog(@"%@", logString); + + // ...or CocoaLumberjackLogger only logging warnings and errors + if (logLevel == FLLogLevelError) { + DDLogError(@"%@", logString); + } else if (logLevel == FLLogLevelWarn) { + DDLogWarn(@"%@", logString); + } +} logLevel:FLLogLevelWarn]; +``` + +Since FLAnimatedImage is licensed under MIT, it's compatible with the terms of using it for any app on the App Store. + +## To Do +- Support other animated image formats such as APNG or WebP (WebP support implemented [here](https://github.com/Flipboard/FLAnimatedImage/pull/86)) +- Integration into network libraries and image caches +- Investigate whether `FLAnimatedImage` should become a `UIImage` subclass +- Smarter buffering +- Bring demo app to iPhone + +This has successfully shipped to many people as is, but please do come with your questions, issues and pull requests! + +## Select apps using FLAnimatedImage +- [Dropbox](https://www.dropbox.com) +- [Medium](https://medium.com) +- [Facebook](https://facebook.com) +- [Pinterest](https://pinterest.com) +- [LiveBooth](http://www.liveboothapp.com) +- [Design Shots](https://itunes.apple.com/app/id792517951) +- [lWlVl Festival](http://lwlvl.com) +- [Close-up](http://closeu.pe) +- [Zip Code Finder](https://itunes.apple.com/app/id893031254) +- [getGIF](https://itunes.apple.com/app/id964784701) +- [Giffage](http://giffage.com) +- [Flipboard](https://flipboard.com) +- [Gifalicious](https://itunes.apple.com/us/app/gifalicious-see-your-gifs/id965346708?mt=8) +- [Slack](https://slack.com/) +- [Telegram](https://telegram.org/) +- [HashPhotos](https://itunes.apple.com/app/id685784609) +- [Ello](https://ello.co/) +- [Dumpert](http://dumpert.nl) + +If you're using FLAnimatedImage in your app please open a PR to add it to this list! diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputColorView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputColorView.h new file mode 100644 index 0000000000..ab3bd7b365 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputColorView.h @@ -0,0 +1,13 @@ +// +// FLEXArgumentInputColorView.h +// Flipboard +// +// Created by Ryan Olson on 6/30/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputView.h" + +@interface FLEXArgumentInputColorView : FLEXArgumentInputView + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputColorView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputColorView.m new file mode 100644 index 0000000000..af9ae46382 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputColorView.m @@ -0,0 +1,329 @@ +// +// FLEXArgumentInputColorView.m +// Flipboard +// +// Created by Ryan Olson on 6/30/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputColorView.h" +#import "FLEXUtility.h" +#import "FLEXRuntimeUtility.h" + +@protocol FLEXColorComponentInputViewDelegate; + +@interface FLEXColorComponentInputView : UIView + +@property (nonatomic, strong) UISlider *slider; +@property (nonatomic, strong) UILabel *valueLabel; + +@property (nonatomic, weak) id delegate; + +@end + +@protocol FLEXColorComponentInputViewDelegate + +- (void)colorComponentInputViewValueDidChange:(FLEXColorComponentInputView *)colorComponentInputView; + +@end + + +@implementation FLEXColorComponentInputView + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + self.slider = [[UISlider alloc] init]; + self.slider.backgroundColor = self.backgroundColor; + [self.slider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventValueChanged]; + [self addSubview:self.slider]; + + self.valueLabel = [[UILabel alloc] init]; + self.valueLabel.backgroundColor = self.backgroundColor; + self.valueLabel.font = [FLEXUtility defaultFontOfSize:14.0]; + self.valueLabel.textAlignment = NSTextAlignmentRight; + [self addSubview:self.valueLabel]; + + [self updateValueLabel]; + } + return self; +} + +- (void)setBackgroundColor:(UIColor *)backgroundColor +{ + [super setBackgroundColor:backgroundColor]; + self.slider.backgroundColor = backgroundColor; + self.valueLabel.backgroundColor = backgroundColor; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + const CGFloat kValueLabelWidth = 50.0; + + [self.slider sizeToFit]; + CGFloat sliderWidth = self.bounds.size.width - kValueLabelWidth; + self.slider.frame = CGRectMake(0, 0, sliderWidth, self.slider.frame.size.height); + + [self.valueLabel sizeToFit]; + CGFloat valueLabelOriginX = CGRectGetMaxX(self.slider.frame); + CGFloat valueLabelOriginY = FLEXFloor((self.slider.frame.size.height - self.valueLabel.frame.size.height) / 2.0); + self.valueLabel.frame = CGRectMake(valueLabelOriginX, valueLabelOriginY, kValueLabelWidth, self.valueLabel.frame.size.height); +} + +- (void)sliderChanged:(id)sender +{ + [self.delegate colorComponentInputViewValueDidChange:self]; + [self updateValueLabel]; +} + +- (void)updateValueLabel +{ + self.valueLabel.text = [NSString stringWithFormat:@"%.3f", self.slider.value]; +} + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGFloat height = [self.slider sizeThatFits:size].height; + return CGSizeMake(size.width, height); +} + +@end + +@interface FLEXColorPreviewBox : UIView + +@property (nonatomic, strong) UIColor *color; + +@property (nonatomic, strong) UIView *colorOverlayView; + +@end + +@implementation FLEXColorPreviewBox + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + self.layer.borderWidth = 1.0; + self.layer.borderColor = [[UIColor blackColor] CGColor]; + self.backgroundColor = [UIColor colorWithPatternImage:[[self class] backgroundPatternImage]]; + + self.colorOverlayView = [[UIView alloc] initWithFrame:self.bounds]; + self.colorOverlayView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + self.colorOverlayView.backgroundColor = [UIColor clearColor]; + [self addSubview:self.colorOverlayView]; + } + return self; +} + +- (void)setColor:(UIColor *)color +{ + self.colorOverlayView.backgroundColor = color; +} + +- (UIColor *)color +{ + return self.colorOverlayView.backgroundColor; +} + ++ (UIImage *)backgroundPatternImage +{ + const CGFloat kSquareDimension = 5.0; + CGSize squareSize = CGSizeMake(kSquareDimension, kSquareDimension); + CGSize imageSize = CGSizeMake(2.0 * kSquareDimension, 2.0 * kSquareDimension); + + UIGraphicsBeginImageContextWithOptions(imageSize, YES, [[UIScreen mainScreen] scale]); + + [[UIColor whiteColor] setFill]; + UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height)); + + [[UIColor grayColor] setFill]; + UIRectFill(CGRectMake(squareSize.width, 0, squareSize.width, squareSize.height)); + UIRectFill(CGRectMake(0, squareSize.height, squareSize.width, squareSize.height)); + + UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + + return image; +} + +@end + +@interface FLEXArgumentInputColorView () + +@property (nonatomic, strong) FLEXColorPreviewBox *colorPreviewBox; +@property (nonatomic, strong) UILabel *hexLabel; +@property (nonatomic, strong) FLEXColorComponentInputView *alphaInput; +@property (nonatomic, strong) FLEXColorComponentInputView *redInput; +@property (nonatomic, strong) FLEXColorComponentInputView *greenInput; +@property (nonatomic, strong) FLEXColorComponentInputView *blueInput; + +@end + +@implementation FLEXArgumentInputColorView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + self.colorPreviewBox = [[FLEXColorPreviewBox alloc] init]; + [self addSubview:self.colorPreviewBox]; + + self.hexLabel = [[UILabel alloc] init]; + self.hexLabel.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.9]; + self.hexLabel.textAlignment = NSTextAlignmentCenter; + self.hexLabel.font = [FLEXUtility defaultFontOfSize:12.0]; + [self addSubview:self.hexLabel]; + + self.alphaInput = [[FLEXColorComponentInputView alloc] init]; + self.alphaInput.slider.minimumTrackTintColor = [UIColor blackColor]; + self.alphaInput.delegate = self; + [self addSubview:self.alphaInput]; + + self.redInput = [[FLEXColorComponentInputView alloc] init]; + self.redInput.slider.minimumTrackTintColor = [UIColor redColor]; + self.redInput.delegate = self; + [self addSubview:self.redInput]; + + self.greenInput = [[FLEXColorComponentInputView alloc] init]; + self.greenInput.slider.minimumTrackTintColor = [UIColor greenColor]; + self.greenInput.delegate = self; + [self addSubview:self.greenInput]; + + self.blueInput = [[FLEXColorComponentInputView alloc] init]; + self.blueInput.slider.minimumTrackTintColor = [UIColor blueColor]; + self.blueInput.delegate = self; + [self addSubview:self.blueInput]; + } + return self; +} + +- (void)setBackgroundColor:(UIColor *)backgroundColor +{ + [super setBackgroundColor:backgroundColor]; + self.alphaInput.backgroundColor = backgroundColor; + self.redInput.backgroundColor = backgroundColor; + self.greenInput.backgroundColor = backgroundColor; + self.blueInput.backgroundColor = backgroundColor; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + CGFloat runningOriginY = 0; + CGSize constrainSize = CGSizeMake(self.bounds.size.width, CGFLOAT_MAX); + + self.colorPreviewBox.frame = CGRectMake(0, runningOriginY, self.bounds.size.width, [[self class] colorPreviewBoxHeight]); + runningOriginY = CGRectGetMaxY(self.colorPreviewBox.frame) + [[self class] inputViewVerticalPadding]; + + [self.hexLabel sizeToFit]; + const CGFloat kLabelVerticalOutsetAmount = 0.0; + const CGFloat kLabelHorizonalOutsetAmount = 2.0; + UIEdgeInsets labelOutset = UIEdgeInsetsMake(-kLabelVerticalOutsetAmount, -kLabelHorizonalOutsetAmount, -kLabelVerticalOutsetAmount, -kLabelHorizonalOutsetAmount); + self.hexLabel.frame = UIEdgeInsetsInsetRect(self.hexLabel.frame, labelOutset); + CGFloat hexLabelOriginX = self.colorPreviewBox.layer.borderWidth; + CGFloat hexLabelOriginY = CGRectGetMaxY(self.colorPreviewBox.frame) - self.colorPreviewBox.layer.borderWidth - self.hexLabel.frame.size.height; + self.hexLabel.frame = CGRectMake(hexLabelOriginX, hexLabelOriginY, self.hexLabel.frame.size.width, self.hexLabel.frame.size.height); + + NSArray *colorComponentInputViews = @[self.alphaInput, self.redInput, self.greenInput, self.blueInput]; + for (FLEXColorComponentInputView *inputView in colorComponentInputViews) { + CGSize fitSize = [inputView sizeThatFits:constrainSize]; + inputView.frame = CGRectMake(0, runningOriginY, fitSize.width, fitSize.height); + runningOriginY = CGRectGetMaxY(inputView.frame) + [[self class] inputViewVerticalPadding]; + } +} + +- (void)setInputValue:(id)inputValue +{ + if ([inputValue isKindOfClass:[UIColor class]]) { + [self updateWithColor:inputValue]; + } else if ([inputValue isKindOfClass:[NSValue class]]) { + const char *type = [inputValue objCType]; + if (strcmp(type, @encode(CGColorRef)) == 0) { + CGColorRef colorRef; + [inputValue getValue:&colorRef]; + UIColor *color = [[UIColor alloc] initWithCGColor:colorRef]; + [self updateWithColor:color]; + } + } +} + +- (id)inputValue +{ + return [UIColor colorWithRed:self.redInput.slider.value green:self.greenInput.slider.value blue:self.blueInput.slider.value alpha:self.alphaInput.slider.value]; +} + +- (void)colorComponentInputViewValueDidChange:(FLEXColorComponentInputView *)colorComponentInputView +{ + [self updateColorPreview]; +} + +- (void)updateWithColor:(UIColor *)color +{ + CGFloat red, green, blue, white, alpha; + if ([color getRed:&red green:&green blue:&blue alpha:&alpha]) { + self.alphaInput.slider.value = alpha; + [self.alphaInput updateValueLabel]; + self.redInput.slider.value = red; + [self.redInput updateValueLabel]; + self.greenInput.slider.value = green; + [self.greenInput updateValueLabel]; + self.blueInput.slider.value = blue; + [self.blueInput updateValueLabel]; + } else if ([color getWhite:&white alpha:&alpha]) { + self.alphaInput.slider.value = alpha; + [self.alphaInput updateValueLabel]; + self.redInput.slider.value = white; + [self.redInput updateValueLabel]; + self.greenInput.slider.value = white; + [self.greenInput updateValueLabel]; + self.blueInput.slider.value = white; + [self.blueInput updateValueLabel]; + } + [self updateColorPreview]; +} + +- (void)updateColorPreview +{ + self.colorPreviewBox.color = self.inputValue; + unsigned char redByte = self.redInput.slider.value * 255; + unsigned char greenByte = self.greenInput.slider.value * 255; + unsigned char blueByte = self.blueInput.slider.value * 255; + self.hexLabel.text = [NSString stringWithFormat:@"#%02X%02X%02X", redByte, greenByte, blueByte]; + [self setNeedsLayout]; +} + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGFloat height = 0; + height += [[self class] colorPreviewBoxHeight]; + height += [[self class] inputViewVerticalPadding]; + height += [self.alphaInput sizeThatFits:size].height; + height += [[self class] inputViewVerticalPadding]; + height += [self.redInput sizeThatFits:size].height; + height += [[self class] inputViewVerticalPadding]; + height += [self.greenInput sizeThatFits:size].height; + height += [[self class] inputViewVerticalPadding]; + height += [self.blueInput sizeThatFits:size].height; + return CGSizeMake(size.width, height); +} + ++ (CGFloat)inputViewVerticalPadding +{ + return 10.0; +} + ++ (CGFloat)colorPreviewBoxHeight +{ + return 40.0; +} + ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value +{ + return (type && (strcmp(type, @encode(CGColorRef)) == 0 || strcmp(type, FLEXEncodeClass(UIColor)) == 0)) || [value isKindOfClass:[UIColor class]]; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputDateView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputDateView.h new file mode 100644 index 0000000000..54e63a9744 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputDateView.h @@ -0,0 +1,13 @@ +// +// FLEXArgumentInputDataView.h +// Flipboard +// +// Created by Daniel Rodriguez Troitino on 2/14/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputView.h" + +@interface FLEXArgumentInputDateView : FLEXArgumentInputView + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputDateView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputDateView.m new file mode 100644 index 0000000000..0907d216be --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputDateView.m @@ -0,0 +1,63 @@ +// +// FLEXArgumentInputDataView.m +// Flipboard +// +// Created by Daniel Rodriguez Troitino on 2/14/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputDateView.h" +#import "FLEXRuntimeUtility.h" + +@interface FLEXArgumentInputDateView () + +@property (nonatomic, strong) UIDatePicker *datePicker; + +@end + +@implementation FLEXArgumentInputDateView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + self.datePicker = [[UIDatePicker alloc] init]; + self.datePicker.datePickerMode = UIDatePickerModeDateAndTime; + // Using UTC, because that's what the NSDate description prints + self.datePicker.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]; + self.datePicker.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; + [self addSubview:self.datePicker]; + } + return self; +} + +- (void)setInputValue:(id)inputValue +{ + if ([inputValue isKindOfClass:[NSDate class]]) { + self.datePicker.date = inputValue; + } +} + +- (id)inputValue +{ + return self.datePicker.date; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + self.datePicker.frame = self.bounds; +} + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGFloat height = [self.datePicker sizeThatFits:size].height; + return CGSizeMake(size.width, height); +} + ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value +{ + return (type && (strcmp(type, FLEXEncodeClass(NSDate)) == 0)) || [value isKindOfClass:[NSDate class]]; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontView.h new file mode 100644 index 0000000000..11847e604c --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontView.h @@ -0,0 +1,13 @@ +// +// FLEXArgumentInputFontView.h +// Flipboard +// +// Created by Ryan Olson on 6/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputView.h" + +@interface FLEXArgumentInputFontView : FLEXArgumentInputView + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontView.m new file mode 100644 index 0000000000..803b76fa74 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontView.m @@ -0,0 +1,121 @@ +// +// FLEXArgumentInputFontView.m +// Flipboard +// +// Created by Ryan Olson on 6/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputFontView.h" +#import "FLEXArgumentInputViewFactory.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXArgumentInputFontsPickerView.h" + +@interface FLEXArgumentInputFontView () + +@property (nonatomic, strong) FLEXArgumentInputView *fontNameInput; +@property (nonatomic, strong) FLEXArgumentInputView *pointSizeInput; + +@end + +@implementation FLEXArgumentInputFontView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + self.fontNameInput = [[FLEXArgumentInputFontsPickerView alloc] initWithArgumentTypeEncoding:FLEXEncodeClass(NSString)]; + self.fontNameInput.backgroundColor = self.backgroundColor; + self.fontNameInput.targetSize = FLEXArgumentInputViewSizeSmall; + self.fontNameInput.title = @"Font Name:"; + [self addSubview:self.fontNameInput]; + + self.pointSizeInput = [FLEXArgumentInputViewFactory argumentInputViewForTypeEncoding:@encode(CGFloat)]; + self.pointSizeInput.backgroundColor = self.backgroundColor; + self.pointSizeInput.targetSize = FLEXArgumentInputViewSizeSmall; + self.pointSizeInput.title = @"Point Size:"; + [self addSubview:self.pointSizeInput]; + } + return self; +} + +- (void)setBackgroundColor:(UIColor *)backgroundColor +{ + [super setBackgroundColor:backgroundColor]; + self.fontNameInput.backgroundColor = backgroundColor; + self.pointSizeInput.backgroundColor = backgroundColor; +} + +- (void)setInputValue:(id)inputValue +{ + if ([inputValue isKindOfClass:[UIFont class]]) { + UIFont *font = (UIFont *)inputValue; + self.fontNameInput.inputValue = font.fontName; + self.pointSizeInput.inputValue = @(font.pointSize); + } +} + +- (id)inputValue +{ + CGFloat pointSize = 0; + if ([self.pointSizeInput.inputValue isKindOfClass:[NSValue class]]) { + NSValue *pointSizeValue = (NSValue *)self.pointSizeInput.inputValue; + if (strcmp([pointSizeValue objCType], @encode(CGFloat)) == 0) { + [pointSizeValue getValue:&pointSize]; + } + } + return [UIFont fontWithName:self.fontNameInput.inputValue size:pointSize]; +} + +- (BOOL)inputViewIsFirstResponder +{ + return [self.fontNameInput inputViewIsFirstResponder] || [self.pointSizeInput inputViewIsFirstResponder]; +} + + +#pragma mark - Layout and Sizing + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + CGFloat runningOriginY = self.topInputFieldVerticalLayoutGuide; + + CGSize fontNameFitSize = [self.fontNameInput sizeThatFits:self.bounds.size]; + self.fontNameInput.frame = CGRectMake(0, runningOriginY, fontNameFitSize.width, fontNameFitSize.height); + runningOriginY = CGRectGetMaxY(self.fontNameInput.frame) + [[self class] verticalPaddingBetweenFields]; + + CGSize pointSizeFitSize = [self.pointSizeInput sizeThatFits:self.bounds.size]; + self.pointSizeInput.frame = CGRectMake(0, runningOriginY, pointSizeFitSize.width, pointSizeFitSize.height); +} + ++ (CGFloat)verticalPaddingBetweenFields +{ + return 10.0; +} + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGSize fitSize = [super sizeThatFits:size]; + + CGSize constrainSize = CGSizeMake(size.width, CGFLOAT_MAX); + + CGFloat height = fitSize.height; + height += [self.fontNameInput sizeThatFits:constrainSize].height; + height += [[self class] verticalPaddingBetweenFields]; + height += [self.pointSizeInput sizeThatFits:constrainSize].height; + + return CGSizeMake(fitSize.width, height); +} + + +#pragma mark - + ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value +{ + BOOL supported = type && strcmp(type, FLEXEncodeClass(UIFont)) == 0; + supported = supported || (value && [value isKindOfClass:[UIFont class]]); + return supported; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontsPickerView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontsPickerView.h new file mode 100644 index 0000000000..6912e6eb9c --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontsPickerView.h @@ -0,0 +1,12 @@ +// +// FLEXArgumentInputFontsPickerView.h +// UICatalog +// +// Created by 啟倫 陳 on 2014/7/27. +// Copyright (c) 2014年 f. All rights reserved. +// + +#import "FLEXArgumentInputTextView.h" + +@interface FLEXArgumentInputFontsPickerView : FLEXArgumentInputTextView +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontsPickerView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontsPickerView.m new file mode 100644 index 0000000000..421a078c0a --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputFontsPickerView.m @@ -0,0 +1,105 @@ +// +// FLEXArgumentInputFontsPickerView.m +// UICatalog +// +// Created by 啟倫 陳 on 2014/7/27. +// Copyright (c) 2014年 f. All rights reserved. +// + +#import "FLEXArgumentInputFontsPickerView.h" +#import "FLEXRuntimeUtility.h" + +@interface FLEXArgumentInputFontsPickerView () + +@property (nonatomic, strong) NSMutableArray *availableFonts; + +@end + + +@implementation FLEXArgumentInputFontsPickerView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + self.targetSize = FLEXArgumentInputViewSizeSmall; + [self createAvailableFonts]; + self.inputTextView.inputView = [self createFontsPicker]; + } + return self; +} + +- (void)setInputValue:(id)inputValue +{ + self.inputTextView.text = inputValue; + if ([self.availableFonts indexOfObject:inputValue] == NSNotFound) { + [self.availableFonts insertObject:inputValue atIndex:0]; + } + [(UIPickerView*)self.inputTextView.inputView selectRow:[self.availableFonts indexOfObject:inputValue] inComponent:0 animated:NO]; +} + +- (id)inputValue +{ + return [self.inputTextView.text length] > 0 ? [self.inputTextView.text copy] : nil; +} + +#pragma mark - private + +- (UIPickerView*)createFontsPicker +{ + UIPickerView *fontsPicker = [UIPickerView new]; + fontsPicker.dataSource = self; + fontsPicker.delegate = self; + fontsPicker.showsSelectionIndicator = YES; + return fontsPicker; +} + +- (void)createAvailableFonts +{ + NSMutableArray *unsortedFontsArray = [NSMutableArray array]; + for (NSString *eachFontFamily in [UIFont familyNames]) { + for (NSString *eachFontName in [UIFont fontNamesForFamilyName:eachFontFamily]) { + [unsortedFontsArray addObject:eachFontName]; + } + } + self.availableFonts = [NSMutableArray arrayWithArray:[unsortedFontsArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]]; +} + +#pragma mark - UIPickerViewDataSource + +- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView +{ + return 1; +} + +- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component +{ + return [self.availableFonts count]; +} + +#pragma mark - UIPickerViewDelegate + +- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view +{ + UILabel *fontLabel; + if (!view) { + fontLabel = [UILabel new]; + fontLabel.backgroundColor = [UIColor clearColor]; + fontLabel.textAlignment = NSTextAlignmentCenter; + } else { + fontLabel = (UILabel*)view; + } + UIFont *font = [UIFont fontWithName:self.availableFonts[row] size:15.0]; + NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; + NSAttributedString *attributesString = [[NSAttributedString alloc] initWithString:self.availableFonts[row] attributes:attributesDictionary]; + fontLabel.attributedText = attributesString; + [fontLabel sizeToFit]; + return fontLabel; +} + +- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component +{ + self.inputTextView.text = self.availableFonts[row]; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputJSONObjectView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputJSONObjectView.h new file mode 100644 index 0000000000..5776d3a65d --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputJSONObjectView.h @@ -0,0 +1,13 @@ +// +// FLEXArgumentInputJSONObjectView.h +// Flipboard +// +// Created by Ryan Olson on 6/15/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputTextView.h" + +@interface FLEXArgumentInputJSONObjectView : FLEXArgumentInputTextView + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputJSONObjectView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputJSONObjectView.m new file mode 100644 index 0000000000..32c11a6855 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputJSONObjectView.m @@ -0,0 +1,65 @@ +// +// FLEXArgumentInputJSONObjectView.m +// Flipboard +// +// Created by Ryan Olson on 6/15/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputJSONObjectView.h" +#import "FLEXRuntimeUtility.h" + +@implementation FLEXArgumentInputJSONObjectView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + // Start with the numbers and punctuation keyboard since quotes, curly braces, or + // square brackets are likely to be the first characters type for the JSON. + self.inputTextView.keyboardType = UIKeyboardTypeNumbersAndPunctuation; + self.targetSize = FLEXArgumentInputViewSizeLarge; + } + return self; +} + +- (void)setInputValue:(id)inputValue +{ + self.inputTextView.text = [FLEXRuntimeUtility editableJSONStringForObject:inputValue]; +} + +- (id)inputValue +{ + return [FLEXRuntimeUtility objectValueFromEditableJSONString:self.inputTextView.text]; +} + ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value +{ + // Must be object type. + BOOL supported = type && type[0] == '@'; + + if (supported) { + if (value) { + // If there's a current value, it must be serializable to JSON + supported = [FLEXRuntimeUtility editableJSONStringForObject:value] != nil; + } else { + // Otherwise, see if we have more type information than just 'id'. + // If we do, make sure the encoding is something serializable to JSON. + // Properties and ivars keep more detailed type encoding information than method arguments. + if (strcmp(type, @encode(id)) != 0) { + BOOL isJSONSerializableType = NO; + // Note: we can't use @encode(NSString) here because that drops the string information and just goes to @encode(id). + isJSONSerializableType = isJSONSerializableType || strcmp(type, FLEXEncodeClass(NSString)) == 0; + isJSONSerializableType = isJSONSerializableType || strcmp(type, FLEXEncodeClass(NSNumber)) == 0; + isJSONSerializableType = isJSONSerializableType || strcmp(type, FLEXEncodeClass(NSArray)) == 0; + isJSONSerializableType = isJSONSerializableType || strcmp(type, FLEXEncodeClass(NSDictionary)) == 0; + + supported = isJSONSerializableType; + } + } + } + + return supported; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNotSupportedView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNotSupportedView.h new file mode 100644 index 0000000000..77923efcba --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNotSupportedView.h @@ -0,0 +1,13 @@ +// +// FLEXArgumentInputNotSupportedView.h +// Flipboard +// +// Created by Ryan Olson on 6/18/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputTextView.h" + +@interface FLEXArgumentInputNotSupportedView : FLEXArgumentInputTextView + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNotSupportedView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNotSupportedView.m new file mode 100644 index 0000000000..b49457568f --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNotSupportedView.m @@ -0,0 +1,25 @@ +// +// FLEXArgumentInputNotSupportedView.m +// Flipboard +// +// Created by Ryan Olson on 6/18/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputNotSupportedView.h" + +@implementation FLEXArgumentInputNotSupportedView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + self.inputTextView.userInteractionEnabled = NO; + self.inputTextView.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1.0]; + self.inputTextView.text = @"nil"; + self.targetSize = FLEXArgumentInputViewSizeSmall; + } + return self; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNumberView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNumberView.h new file mode 100644 index 0000000000..754ea61367 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNumberView.h @@ -0,0 +1,13 @@ +// +// FLEXArgumentInputNumberView.h +// Flipboard +// +// Created by Ryan Olson on 6/15/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputTextView.h" + +@interface FLEXArgumentInputNumberView : FLEXArgumentInputTextView + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNumberView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNumberView.m new file mode 100644 index 0000000000..9b9d7bca5f --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputNumberView.m @@ -0,0 +1,57 @@ +// +// FLEXArgumentInputNumberView.m +// Flipboard +// +// Created by Ryan Olson on 6/15/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputNumberView.h" +#import "FLEXRuntimeUtility.h" + +@implementation FLEXArgumentInputNumberView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + self.inputTextView.keyboardType = UIKeyboardTypeNumbersAndPunctuation; + self.targetSize = FLEXArgumentInputViewSizeSmall; + } + return self; +} + +- (void)setInputValue:(id)inputValue +{ + if ([inputValue respondsToSelector:@selector(stringValue)]) { + self.inputTextView.text = [inputValue stringValue]; + } +} + +- (id)inputValue +{ + return [FLEXRuntimeUtility valueForNumberWithObjCType:[self.typeEncoding UTF8String] fromInputString:self.inputTextView.text]; +} + ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value +{ + static NSArray *primitiveTypes = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + primitiveTypes = @[@(@encode(char)), + @(@encode(int)), + @(@encode(short)), + @(@encode(long)), + @(@encode(long long)), + @(@encode(unsigned char)), + @(@encode(unsigned int)), + @(@encode(unsigned short)), + @(@encode(unsigned long)), + @(@encode(unsigned long long)), + @(@encode(float)), + @(@encode(double))]; + }); + return type && [primitiveTypes containsObject:@(type)]; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStringView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStringView.h new file mode 100644 index 0000000000..2c16b6cb1d --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStringView.h @@ -0,0 +1,13 @@ +// +// FLEXArgumentInputStringView.h +// Flipboard +// +// Created by Ryan Olson on 6/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputTextView.h" + +@interface FLEXArgumentInputStringView : FLEXArgumentInputTextView + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStringView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStringView.m new file mode 100644 index 0000000000..291fe091b5 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStringView.m @@ -0,0 +1,45 @@ +// +// FLEXArgumentInputStringView.m +// Flipboard +// +// Created by Ryan Olson on 6/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputStringView.h" +#import "FLEXRuntimeUtility.h" + +@implementation FLEXArgumentInputStringView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + self.targetSize = FLEXArgumentInputViewSizeLarge; + } + return self; +} + +- (void)setInputValue:(id)inputValue +{ + self.inputTextView.text = inputValue; +} + +- (id)inputValue +{ + // Interpret empty string as nil. We loose the ablitiy to set empty string as a string value, + // but we accept that tradeoff in exchange for not having to type quotes for every string. + return [self.inputTextView.text length] > 0 ? [self.inputTextView.text copy] : nil; +} + + +#pragma mark - + ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value +{ + BOOL supported = type && strcmp(type, FLEXEncodeClass(NSString)) == 0; + supported = supported || (value && [value isKindOfClass:[NSString class]]); + return supported; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStructView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStructView.h new file mode 100644 index 0000000000..3e3b6f946d --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStructView.h @@ -0,0 +1,13 @@ +// +// FLEXArgumentInputStructView.h +// Flipboard +// +// Created by Ryan Olson on 6/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputView.h" + +@interface FLEXArgumentInputStructView : FLEXArgumentInputView + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStructView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStructView.m new file mode 100644 index 0000000000..a66ccd8b32 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputStructView.m @@ -0,0 +1,210 @@ +// +// FLEXArgumentInputStructView.m +// Flipboard +// +// Created by Ryan Olson on 6/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputStructView.h" +#import "FLEXArgumentInputViewFactory.h" +#import "FLEXRuntimeUtility.h" + +@interface FLEXArgumentInputStructView () + +@property (nonatomic, strong) NSArray *argumentInputViews; + +@end + +@implementation FLEXArgumentInputStructView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + NSMutableArray *inputViews = [NSMutableArray array]; + NSArray *customTitles = [[self class] customFieldTitlesForTypeEncoding:typeEncoding]; + [FLEXRuntimeUtility enumerateTypesInStructEncoding:typeEncoding usingBlock:^(NSString *structName, const char *fieldTypeEncoding, NSString *prettyTypeEncoding, NSUInteger fieldIndex, NSUInteger fieldOffset) { + + FLEXArgumentInputView *inputView = [FLEXArgumentInputViewFactory argumentInputViewForTypeEncoding:fieldTypeEncoding]; + inputView.backgroundColor = self.backgroundColor; + inputView.targetSize = FLEXArgumentInputViewSizeSmall; + + if (fieldIndex < [customTitles count]) { + inputView.title = customTitles[fieldIndex]; + } else { + inputView.title = [NSString stringWithFormat:@"%@ field %lu (%@)", structName, (unsigned long)fieldIndex, prettyTypeEncoding]; + } + + [inputViews addObject:inputView]; + [self addSubview:inputView]; + }]; + self.argumentInputViews = inputViews; + } + return self; +} + + +#pragma mark - Superclass Overrides + +- (void)setBackgroundColor:(UIColor *)backgroundColor +{ + [super setBackgroundColor:backgroundColor]; + for (FLEXArgumentInputView *inputView in self.argumentInputViews) { + inputView.backgroundColor = backgroundColor; + } +} + +- (void)setInputValue:(id)inputValue +{ + if ([inputValue isKindOfClass:[NSValue class]]) { + const char *structTypeEncoding = [inputValue objCType]; + if (strcmp([self.typeEncoding UTF8String], structTypeEncoding) == 0) { + NSUInteger valueSize = 0; + @try { + // NSGetSizeAndAlignment barfs on type encoding for bitfields. + NSGetSizeAndAlignment(structTypeEncoding, &valueSize, NULL); + } @catch (NSException *exception) { } + + if (valueSize > 0) { + void *unboxedValue = malloc(valueSize); + [inputValue getValue:unboxedValue]; + [FLEXRuntimeUtility enumerateTypesInStructEncoding:structTypeEncoding usingBlock:^(NSString *structName, const char *fieldTypeEncoding, NSString *prettyTypeEncoding, NSUInteger fieldIndex, NSUInteger fieldOffset) { + + void *fieldPointer = unboxedValue + fieldOffset; + FLEXArgumentInputView *inputView = self.argumentInputViews[fieldIndex]; + + if (fieldTypeEncoding[0] == @encode(id)[0] || fieldTypeEncoding[0] == @encode(Class)[0]) { + inputView.inputValue = (__bridge id)fieldPointer; + } else { + NSValue *boxedField = [FLEXRuntimeUtility valueForPrimitivePointer:fieldPointer objCType:fieldTypeEncoding]; + inputView.inputValue = boxedField; + } + }]; + free(unboxedValue); + } + } + } +} + +- (id)inputValue +{ + NSValue *boxedStruct = nil; + const char *structTypeEncoding = [self.typeEncoding UTF8String]; + NSUInteger structSize = 0; + @try { + // NSGetSizeAndAlignment barfs on type encoding for bitfields. + NSGetSizeAndAlignment(structTypeEncoding, &structSize, NULL); + } @catch (NSException *exception) { } + + if (structSize > 0) { + void *unboxedStruct = malloc(structSize); + [FLEXRuntimeUtility enumerateTypesInStructEncoding:structTypeEncoding usingBlock:^(NSString *structName, const char *fieldTypeEncoding, NSString *prettyTypeEncoding, NSUInteger fieldIndex, NSUInteger fieldOffset) { + + void *fieldPointer = unboxedStruct + fieldOffset; + FLEXArgumentInputView *inputView = self.argumentInputViews[fieldIndex]; + + if (fieldTypeEncoding[0] == @encode(id)[0] || fieldTypeEncoding[0] == @encode(Class)[0]) { + // Object fields + memcpy(fieldPointer, (__bridge void *)inputView.inputValue, sizeof(id)); + } else { + // Boxed primitive/struct fields + id inputValue = inputView.inputValue; + if ([inputValue isKindOfClass:[NSValue class]] && strcmp([inputValue objCType], fieldTypeEncoding) == 0) { + [inputValue getValue:fieldPointer]; + } + } + }]; + + boxedStruct = [NSValue value:unboxedStruct withObjCType:structTypeEncoding]; + free(unboxedStruct); + } + + return boxedStruct; +} + +- (BOOL)inputViewIsFirstResponder +{ + BOOL isFirstResponder = NO; + for (FLEXArgumentInputView *inputView in self.argumentInputViews) { + if ([inputView inputViewIsFirstResponder]) { + isFirstResponder = YES; + break; + } + } + return isFirstResponder; +} + + +#pragma mark - Layout and Sizing + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + CGFloat runningOriginY = self.topInputFieldVerticalLayoutGuide; + + for (FLEXArgumentInputView *inputView in self.argumentInputViews) { + CGSize inputFitSize = [inputView sizeThatFits:self.bounds.size]; + inputView.frame = CGRectMake(0, runningOriginY, inputFitSize.width, inputFitSize.height); + runningOriginY = CGRectGetMaxY(inputView.frame) + [[self class] verticalPaddingBetweenFields]; + } +} + ++ (CGFloat)verticalPaddingBetweenFields +{ + return 10.0; +} + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGSize fitSize = [super sizeThatFits:size]; + + CGSize constrainSize = CGSizeMake(size.width, CGFLOAT_MAX); + CGFloat height = fitSize.height; + + for (FLEXArgumentInputView *inputView in self.argumentInputViews) { + height += [inputView sizeThatFits:constrainSize].height; + height += [[self class] verticalPaddingBetweenFields]; + } + + return CGSizeMake(fitSize.width, height); +} + + +#pragma mark - Class Helpers + ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value +{ + return type && type[0] == '{'; +} + ++ (NSArray *)customFieldTitlesForTypeEncoding:(const char *)typeEncoding +{ + NSArray *customTitles = nil; + if (strcmp(typeEncoding, @encode(CGRect)) == 0) { + customTitles = @[@"CGPoint origin", @"CGSize size"]; + } else if (strcmp(typeEncoding, @encode(CGPoint)) == 0) { + customTitles = @[@"CGFloat x", @"CGFloat y"]; + } else if (strcmp(typeEncoding, @encode(CGSize)) == 0) { + customTitles = @[@"CGFloat width", @"CGFloat height"]; + } else if (strcmp(typeEncoding, @encode(UIEdgeInsets)) == 0) { + customTitles = @[@"CGFloat top", @"CGFloat left", @"CGFloat bottom", @"CGFloat right"]; + } else if (strcmp(typeEncoding, @encode(UIOffset)) == 0) { + customTitles = @[@"CGFloat horizontal", @"CGFloat vertical"]; + } else if (strcmp(typeEncoding, @encode(NSRange)) == 0) { + customTitles = @[@"NSUInteger location", @"NSUInteger length"]; + } else if (strcmp(typeEncoding, @encode(CATransform3D)) == 0) { + customTitles = @[@"CGFloat m11", @"CGFloat m12", @"CGFloat m13", @"CGFloat m14", + @"CGFloat m21", @"CGFloat m22", @"CGFloat m23", @"CGFloat m24", + @"CGFloat m31", @"CGFloat m32", @"CGFloat m33", @"CGFloat m34", + @"CGFloat m41", @"CGFloat m42", @"CGFloat m43", @"CGFloat m44"]; + } else if (strcmp(typeEncoding, @encode(CGAffineTransform)) == 0) { + customTitles = @[@"CGFloat a", @"CGFloat b", + @"CGFloat c", @"CGFloat d", + @"CGFloat tx", @"CGFloat ty"]; + } + return customTitles; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputSwitchView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputSwitchView.h new file mode 100644 index 0000000000..973639df1d --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputSwitchView.h @@ -0,0 +1,13 @@ +// +// FLEXArgumentInputSwitchView.h +// Flipboard +// +// Created by Ryan Olson on 6/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputView.h" + +@interface FLEXArgumentInputSwitchView : FLEXArgumentInputView + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputSwitchView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputSwitchView.m new file mode 100644 index 0000000000..b5ee840a01 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputSwitchView.m @@ -0,0 +1,87 @@ +// +// FLEXArgumentInputSwitchView.m +// Flipboard +// +// Created by Ryan Olson on 6/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputSwitchView.h" + +@interface FLEXArgumentInputSwitchView () + +@property (nonatomic, strong) UISwitch *inputSwitch; + +@end + +@implementation FLEXArgumentInputSwitchView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + self.inputSwitch = [[UISwitch alloc] init]; + [self.inputSwitch addTarget:self action:@selector(switchValueDidChange:) forControlEvents:UIControlEventValueChanged]; + [self.inputSwitch sizeToFit]; + [self addSubview:self.inputSwitch]; + } + return self; +} + + +#pragma mark Input/Output + +- (void)setInputValue:(id)inputValue +{ + BOOL on = NO; + if ([inputValue isKindOfClass:[NSNumber class]]) { + NSNumber *number = (NSNumber *)inputValue; + on = [number boolValue]; + } else if ([inputValue isKindOfClass:[NSValue class]]) { + NSValue *value = (NSValue *)inputValue; + if (strcmp([value objCType], @encode(BOOL)) == 0) { + [value getValue:&on]; + } + } + self.inputSwitch.on = on; +} + +- (id)inputValue +{ + BOOL isOn = [self.inputSwitch isOn]; + NSValue *boxedBool = [NSValue value:&isOn withObjCType:@encode(BOOL)]; + return boxedBool; +} + +- (void)switchValueDidChange:(id)sender +{ + [self.delegate argumentInputViewValueDidChange:self]; +} + + +#pragma mark - Layout and Sizing + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + self.inputSwitch.frame = CGRectMake(0, self.topInputFieldVerticalLayoutGuide, self.inputSwitch.frame.size.width, self.inputSwitch.frame.size.height); +} + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGSize fitSize = [super sizeThatFits:size]; + fitSize.height += self.inputSwitch.frame.size.height; + return fitSize; +} + + +#pragma mark - Class Helpers + ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value +{ + // Only BOOLs. Current value is irrelevant. + return type && strcmp(type, @encode(BOOL)) == 0; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputTextView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputTextView.h new file mode 100644 index 0000000000..b76f1d4ba4 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputTextView.h @@ -0,0 +1,17 @@ +// +// FLEXArgumentInputTextView.h +// FLEXInjected +// +// Created by Ryan Olson on 6/15/14. +// +// + +#import "FLEXArgumentInputView.h" + +@interface FLEXArgumentInputTextView : FLEXArgumentInputView + +// For subclass eyes only + +@property (nonatomic, strong, readonly) UITextView *inputTextView; + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputTextView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputTextView.m new file mode 100644 index 0000000000..220f41c53d --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputTextView.m @@ -0,0 +1,121 @@ +// +// FLEXArgumentInputTextView.m +// FLEXInjected +// +// Created by Ryan Olson on 6/15/14. +// +// + +#import "FLEXArgumentInputTextView.h" +#import "FLEXUtility.h" + +@interface FLEXArgumentInputTextView () + +@property (nonatomic, strong) UITextView *inputTextView; +@property (nonatomic, readonly) NSUInteger numberOfInputLines; + +@end + +@implementation FLEXArgumentInputTextView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithArgumentTypeEncoding:typeEncoding]; + if (self) { + self.inputTextView = [[UITextView alloc] init]; + self.inputTextView.font = [[self class] inputFont]; + self.inputTextView.backgroundColor = [UIColor whiteColor]; + self.inputTextView.layer.borderColor = [[UIColor blackColor] CGColor]; + self.inputTextView.layer.borderWidth = 1.0; + self.inputTextView.autocapitalizationType = UITextAutocapitalizationTypeNone; + self.inputTextView.autocorrectionType = UITextAutocorrectionTypeNo; + self.inputTextView.delegate = self; + self.inputTextView.inputAccessoryView = [self createToolBar]; + [self addSubview:self.inputTextView]; + } + return self; +} + +#pragma mark - private + +- (UIToolbar*)createToolBar +{ + UIToolbar *toolBar = [UIToolbar new]; + [toolBar sizeToFit]; + UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; + UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(textViewDone)]; + toolBar.items = @[spaceItem, doneItem]; + return toolBar; +} + +- (void)textViewDone +{ + [self.inputTextView resignFirstResponder]; +} + + +#pragma mark - Text View Changes + +- (void)textViewDidChange:(UITextView *)textView +{ + [self.delegate argumentInputViewValueDidChange:self]; +} + + +#pragma mark - Superclass Overrides + +- (BOOL)inputViewIsFirstResponder +{ + return self.inputTextView.isFirstResponder; +} + + +#pragma mark - Layout and Sizing + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + self.inputTextView.frame = CGRectMake(0, self.topInputFieldVerticalLayoutGuide, self.bounds.size.width, [self inputTextViewHeight]); +} + +- (NSUInteger)numberOfInputLines +{ + NSUInteger numberOfInputLines = 0; + switch (self.targetSize) { + case FLEXArgumentInputViewSizeDefault: + numberOfInputLines = 2; + break; + + case FLEXArgumentInputViewSizeSmall: + numberOfInputLines = 1; + break; + + case FLEXArgumentInputViewSizeLarge: + numberOfInputLines = 8; + break; + } + return numberOfInputLines; +} + +- (CGFloat)inputTextViewHeight +{ + return ceil([[self class] inputFont].lineHeight * self.numberOfInputLines) + 16.0; +} + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGSize fitSize = [super sizeThatFits:size]; + fitSize.height += [self inputTextViewHeight]; + return fitSize; +} + + +#pragma mark - Class Helpers + ++ (UIFont *)inputFont +{ + return [FLEXUtility defaultFontOfSize:14.0]; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputView.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputView.h new file mode 100644 index 0000000000..3c14c3522a --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputView.h @@ -0,0 +1,60 @@ +// +// FLEXArgumentInputView.h +// Flipboard +// +// Created by Ryan Olson on 5/30/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +typedef NS_ENUM(NSUInteger, FLEXArgumentInputViewSize) { + FLEXArgumentInputViewSizeDefault = 0, + FLEXArgumentInputViewSizeSmall, + FLEXArgumentInputViewSizeLarge +}; + +@protocol FLEXArgumentInputViewDelegate; + +@interface FLEXArgumentInputView : UIView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding; + +/// The name of the field. Optional (can be nil). +@property (nonatomic, copy) NSString *title; + +/// To populate the filed with an initial value, set this property. +/// To reteive the value input by the user, access the property. +/// Primitive types and structs should/will be boxed in NSValue containers. +/// Concrete subclasses *must* override both the setter and getter for this property. +@property (nonatomic) id inputValue; + +/// Setting this value to large will make some argument input views increase the size of their input field(s). +/// Useful to increase the use of space if there is only one input view on screen (i.e. for property and ivar editing). +@property (nonatomic, assign) FLEXArgumentInputViewSize targetSize; + +/// Users of the input view can get delegate callbacks for incremental changes in user input. +@property (nonatomic, weak) id delegate; + +// Subclasses can override + +/// If the input view has one or more text views, returns YES when one of them is focused. +@property (nonatomic, readonly) BOOL inputViewIsFirstResponder; + +/// For subclasses to indicate that they can handle editing a field the give type and value. +/// Used by FLEXArgumentInputViewFactory to create appropriate input views. ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value; + +// For subclass eyes only + +@property (nonatomic, strong, readonly) UILabel *titleLabel; +@property (nonatomic, strong, readonly) NSString *typeEncoding; +@property (nonatomic, readonly) CGFloat topInputFieldVerticalLayoutGuide; + +@end + +@protocol FLEXArgumentInputViewDelegate + +- (void)argumentInputViewValueDidChange:(FLEXArgumentInputView *)argumentInputView; + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputView.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputView.m new file mode 100644 index 0000000000..2379e09173 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputView.m @@ -0,0 +1,137 @@ +// +// FLEXArgumentInputView.m +// Flipboard +// +// Created by Ryan Olson on 5/30/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArgumentInputView.h" +#import "FLEXUtility.h" + +@interface FLEXArgumentInputView () + +@property (nonatomic, strong) UILabel *titleLabel; +@property (nonatomic, strong) NSString *typeEncoding; + +@end + +@implementation FLEXArgumentInputView + +- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding +{ + self = [super initWithFrame:CGRectZero]; + if (self) { + self.typeEncoding = @(typeEncoding); + } + return self; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + if (self.showsTitle) { + CGSize constrainSize = CGSizeMake(self.bounds.size.width, CGFLOAT_MAX); + CGSize labelSize = [self.titleLabel sizeThatFits:constrainSize]; + self.titleLabel.frame = CGRectMake(0, 0, labelSize.width, labelSize.height); + } +} + +- (void)setBackgroundColor:(UIColor *)backgroundColor +{ + [super setBackgroundColor:backgroundColor]; + self.titleLabel.backgroundColor = backgroundColor; +} + +- (void)setTitle:(NSString *)title +{ + if (![_title isEqual:title]) { + _title = title; + self.titleLabel.text = title; + [self setNeedsLayout]; + } +} + +- (UILabel *)titleLabel +{ + if (!_titleLabel) { + _titleLabel = [[UILabel alloc] init]; + _titleLabel.font = [[self class] titleFont]; + _titleLabel.backgroundColor = self.backgroundColor; + _titleLabel.textColor = [UIColor colorWithWhite:0.3 alpha:1.0]; + _titleLabel.numberOfLines = 0; + [self addSubview:_titleLabel]; + } + return _titleLabel; +} + +- (BOOL)showsTitle +{ + return [self.title length] > 0; +} + +- (CGFloat)topInputFieldVerticalLayoutGuide +{ + CGFloat verticalLayoutGuide = 0; + if (self.showsTitle) { + CGFloat titleHeight = [self.titleLabel sizeThatFits:self.bounds.size].height; + verticalLayoutGuide = titleHeight + [[self class] titleBottomPadding]; + } + return verticalLayoutGuide; +} + + +#pragma mark - Subclasses Can Override + +- (BOOL)inputViewIsFirstResponder +{ + return NO; +} + +- (void)setInputValue:(id)inputValue +{ + // Subclasses should override. +} + +- (id)inputValue +{ + // Subclasses should override. + return nil; +} + ++ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value +{ + return NO; +} + + +#pragma mark - Class Helpers + ++ (UIFont *)titleFont +{ + return [FLEXUtility defaultFontOfSize:12.0]; +} + ++ (CGFloat)titleBottomPadding +{ + return 4.0; +} + + +#pragma mark - Sizing + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGFloat height = 0; + + if ([self.title length] > 0) { + CGSize constrainSize = CGSizeMake(size.width, CGFLOAT_MAX); + height += ceil([self.titleLabel sizeThatFits:constrainSize].height); + height += [[self class] titleBottomPadding]; + } + + return CGSizeMake(size.width, height); +} + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputViewFactory.h b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputViewFactory.h new file mode 100644 index 0000000000..0680903e42 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputViewFactory.h @@ -0,0 +1,25 @@ +// +// FLEXArgumentInputViewFactory.h +// FLEXInjected +// +// Created by Ryan Olson on 6/15/14. +// +// + +#import + +@class FLEXArgumentInputView; + +@interface FLEXArgumentInputViewFactory : NSObject + +/// Forwards to argumentInputViewForTypeEncoding:currentValue: with a nil currentValue. ++ (FLEXArgumentInputView *)argumentInputViewForTypeEncoding:(const char *)typeEncoding; + +/// The main factory method for making argument input view subclasses that are the best fit for the type. ++ (FLEXArgumentInputView *)argumentInputViewForTypeEncoding:(const char *)typeEncoding currentValue:(id)currentValue; + +/// A way to check if we should try editing a filed given its type encoding and value. +/// Useful when deciding whether to edit or explore a property, ivar, or NSUserDefaults value. ++ (BOOL)canEditFieldWithTypeEncoding:(const char *)typeEncoding currentValue:(id)currentValue; + +@end diff --git a/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputViewFactory.m b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputViewFactory.m new file mode 100644 index 0000000000..cbb6baecbc --- /dev/null +++ b/Pods/FLEX/Classes/Editing/ArgumentInputViews/FLEXArgumentInputViewFactory.m @@ -0,0 +1,72 @@ +// +// FLEXArgumentInputViewFactory.m +// FLEXInjected +// +// Created by Ryan Olson on 6/15/14. +// +// + +#import "FLEXArgumentInputViewFactory.h" +#import "FLEXArgumentInputView.h" +#import "FLEXArgumentInputJSONObjectView.h" +#import "FLEXArgumentInputNumberView.h" +#import "FLEXArgumentInputSwitchView.h" +#import "FLEXArgumentInputStructView.h" +#import "FLEXArgumentInputNotSupportedView.h" +#import "FLEXArgumentInputStringView.h" +#import "FLEXArgumentInputFontView.h" +#import "FLEXArgumentInputColorView.h" +#import "FLEXArgumentInputDateView.h" + +@implementation FLEXArgumentInputViewFactory + ++ (FLEXArgumentInputView *)argumentInputViewForTypeEncoding:(const char *)typeEncoding +{ + return [self argumentInputViewForTypeEncoding:typeEncoding currentValue:nil]; +} + ++ (FLEXArgumentInputView *)argumentInputViewForTypeEncoding:(const char *)typeEncoding currentValue:(id)currentValue +{ + Class subclass = [self argumentInputViewSubclassForTypeEncoding:typeEncoding currentValue:currentValue]; + if (!subclass) { + // Fall back to a FLEXArgumentInputNotSupportedView if we can't find a subclass that fits the type encoding. + // The unsupported view shows "nil" and does not allow user input. + subclass = [FLEXArgumentInputNotSupportedView class]; + } + return [[subclass alloc] initWithArgumentTypeEncoding:typeEncoding]; +} + ++ (Class)argumentInputViewSubclassForTypeEncoding:(const char *)typeEncoding currentValue:(id)currentValue +{ + Class argumentInputViewSubclass = nil; + + // Note that order is important here since multiple subclasses may support the same type. + // An example is the number subclass and the bool subclass for the type @encode(BOOL). + // Both work, but we'd prefer to use the bool subclass. + if ([FLEXArgumentInputColorView supportsObjCType:typeEncoding withCurrentValue:currentValue]) { + argumentInputViewSubclass = [FLEXArgumentInputColorView class]; + } else if ([FLEXArgumentInputFontView supportsObjCType:typeEncoding withCurrentValue:currentValue]) { + argumentInputViewSubclass = [FLEXArgumentInputFontView class]; + } else if ([FLEXArgumentInputStringView supportsObjCType:typeEncoding withCurrentValue:currentValue]) { + argumentInputViewSubclass = [FLEXArgumentInputStringView class]; + } else if ([FLEXArgumentInputStructView supportsObjCType:typeEncoding withCurrentValue:currentValue]) { + argumentInputViewSubclass = [FLEXArgumentInputStructView class]; + } else if ([FLEXArgumentInputSwitchView supportsObjCType:typeEncoding withCurrentValue:currentValue]) { + argumentInputViewSubclass = [FLEXArgumentInputSwitchView class]; + } else if ([FLEXArgumentInputDateView supportsObjCType:typeEncoding withCurrentValue:currentValue]) { + argumentInputViewSubclass = [FLEXArgumentInputDateView class]; + } else if ([FLEXArgumentInputNumberView supportsObjCType:typeEncoding withCurrentValue:currentValue]) { + argumentInputViewSubclass = [FLEXArgumentInputNumberView class]; + } else if ([FLEXArgumentInputJSONObjectView supportsObjCType:typeEncoding withCurrentValue:currentValue]) { + argumentInputViewSubclass = [FLEXArgumentInputJSONObjectView class]; + } + + return argumentInputViewSubclass; +} + ++ (BOOL)canEditFieldWithTypeEncoding:(const char *)typeEncoding currentValue:(id)currentValue +{ + return [self argumentInputViewSubclassForTypeEncoding:typeEncoding currentValue:currentValue] != nil; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXDefaultEditorViewController.h b/Pods/FLEX/Classes/Editing/FLEXDefaultEditorViewController.h new file mode 100644 index 0000000000..2e9e6c98f4 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXDefaultEditorViewController.h @@ -0,0 +1,17 @@ +// +// FLEXDefaultEditorViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/23/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXFieldEditorViewController.h" + +@interface FLEXDefaultEditorViewController : FLEXFieldEditorViewController + +- (id)initWithDefaults:(NSUserDefaults *)defaults key:(NSString *)key; + ++ (BOOL)canEditDefaultWithValue:(id)currentValue; + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXDefaultEditorViewController.m b/Pods/FLEX/Classes/Editing/FLEXDefaultEditorViewController.m new file mode 100644 index 0000000000..4d309dbb01 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXDefaultEditorViewController.m @@ -0,0 +1,72 @@ +// +// FLEXDefaultEditorViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/23/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXDefaultEditorViewController.h" +#import "FLEXFieldEditorView.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXArgumentInputView.h" +#import "FLEXArgumentInputViewFactory.h" + +@interface FLEXDefaultEditorViewController () + +@property (nonatomic, readonly) NSUserDefaults *defaults; +@property (nonatomic, strong) NSString *key; + +@end + +@implementation FLEXDefaultEditorViewController + +- (id)initWithDefaults:(NSUserDefaults *)defaults key:(NSString *)key +{ + self = [super initWithTarget:defaults]; + if (self) { + self.key = key; + self.title = @"Edit Default"; + } + return self; +} + +- (NSUserDefaults *)defaults +{ + return [self.target isKindOfClass:[NSUserDefaults class]] ? self.target : nil; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.fieldEditorView.fieldDescription = self.key; + + id currentValue = [self.defaults objectForKey:self.key]; + FLEXArgumentInputView *inputView = [FLEXArgumentInputViewFactory argumentInputViewForTypeEncoding:@encode(id) currentValue:currentValue]; + inputView.backgroundColor = self.view.backgroundColor; + inputView.inputValue = currentValue; + self.fieldEditorView.argumentInputViews = @[inputView]; +} + +- (void)actionButtonPressed:(id)sender +{ + [super actionButtonPressed:sender]; + + id value = self.firstInputView.inputValue; + if (value) { + [self.defaults setObject:value forKey:self.key]; + } else { + [self.defaults removeObjectForKey:self.key]; + } + [self.defaults synchronize]; + + self.firstInputView.inputValue = [self.defaults objectForKey:self.key]; +} + ++ (BOOL)canEditDefaultWithValue:(id)currentValue +{ + return [FLEXArgumentInputViewFactory canEditFieldWithTypeEncoding:@encode(id) currentValue:currentValue]; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXFieldEditorView.h b/Pods/FLEX/Classes/Editing/FLEXFieldEditorView.h new file mode 100644 index 0000000000..673abb6211 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXFieldEditorView.h @@ -0,0 +1,18 @@ +// +// FLEXFieldEditorView.h +// Flipboard +// +// Created by Ryan Olson on 5/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@interface FLEXFieldEditorView : UIView + +@property (nonatomic, copy) NSString *targetDescription; +@property (nonatomic, copy) NSString *fieldDescription; + +@property (nonatomic, strong) NSArray *argumentInputViews; + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXFieldEditorView.m b/Pods/FLEX/Classes/Editing/FLEXFieldEditorView.m new file mode 100644 index 0000000000..b9ac93a351 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXFieldEditorView.m @@ -0,0 +1,184 @@ +// +// FLEXFieldEditorView.m +// Flipboard +// +// Created by Ryan Olson on 5/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXFieldEditorView.h" +#import "FLEXArgumentInputView.h" +#import "FLEXUtility.h" + +@interface FLEXFieldEditorView () + +@property (nonatomic, strong) UILabel *targetDescriptionLabel; +@property (nonatomic, strong) UIView *targetDescriptionDivider; +@property (nonatomic, strong) UILabel *fieldDescriptionLabel; +@property (nonatomic, strong) UIView *fieldDescriptionDivider; + +@end + +@implementation FLEXFieldEditorView + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + self.targetDescriptionLabel = [[UILabel alloc] init]; + self.targetDescriptionLabel.numberOfLines = 0; + self.targetDescriptionLabel.font = [[self class] labelFont]; + [self addSubview:self.targetDescriptionLabel]; + + self.targetDescriptionDivider = [[self class] dividerView]; + [self addSubview:self.targetDescriptionDivider]; + + self.fieldDescriptionLabel = [[UILabel alloc] init]; + self.fieldDescriptionLabel.numberOfLines = 0; + self.fieldDescriptionLabel.font = [[self class] labelFont]; + [self addSubview:self.fieldDescriptionLabel]; + + self.fieldDescriptionDivider = [[self class] dividerView]; + [self addSubview:self.fieldDescriptionDivider]; + } + return self; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + CGFloat horizontalPadding = [[self class] horizontalPadding]; + CGFloat verticalPadding = [[self class] verticalPadding]; + CGFloat dividerLineHeight = [[self class] dividerLineHeight]; + + CGFloat originY = verticalPadding; + CGFloat originX = horizontalPadding; + CGFloat contentWidth = self.bounds.size.width - 2.0 * horizontalPadding; + CGSize constrainSize = CGSizeMake(contentWidth, CGFLOAT_MAX); + + CGSize instanceDescriptionSize = [self.targetDescriptionLabel sizeThatFits:constrainSize]; + self.targetDescriptionLabel.frame = CGRectMake(originX, originY, instanceDescriptionSize.width, instanceDescriptionSize.height); + originY = CGRectGetMaxY(self.targetDescriptionLabel.frame) + verticalPadding; + + self.targetDescriptionDivider.frame = CGRectMake(originX, originY, contentWidth, dividerLineHeight); + originY = CGRectGetMaxY(self.targetDescriptionDivider.frame) + verticalPadding; + + CGSize fieldDescriptionSize = [self.fieldDescriptionLabel sizeThatFits:constrainSize]; + self.fieldDescriptionLabel.frame = CGRectMake(originX, originY, fieldDescriptionSize.width, fieldDescriptionSize.height); + originY = CGRectGetMaxY(self.fieldDescriptionLabel.frame) + verticalPadding; + + self.fieldDescriptionDivider.frame = CGRectMake(originX, originY, contentWidth, dividerLineHeight); + originY = CGRectGetMaxY(self.fieldDescriptionDivider.frame) + verticalPadding; + + for (UIView *argumentInputView in self.argumentInputViews) { + CGSize inputViewSize = [argumentInputView sizeThatFits:constrainSize]; + argumentInputView.frame = CGRectMake(originX, originY, inputViewSize.width, inputViewSize.height); + originY = CGRectGetMaxY(argumentInputView.frame) + verticalPadding; + } +} + +- (void)setBackgroundColor:(UIColor *)backgroundColor +{ + [super setBackgroundColor:backgroundColor]; + self.targetDescriptionLabel.backgroundColor = backgroundColor; + self.fieldDescriptionLabel.backgroundColor = backgroundColor; +} + +- (void)setTargetDescription:(NSString *)targetDescription +{ + if (![_targetDescription isEqual:targetDescription]) { + _targetDescription = targetDescription; + self.targetDescriptionLabel.text = targetDescription; + [self setNeedsLayout]; + } +} + +- (void)setFieldDescription:(NSString *)fieldDescription +{ + if (![_fieldDescription isEqual:fieldDescription]) { + _fieldDescription = fieldDescription; + self.fieldDescriptionLabel.text = fieldDescription; + [self setNeedsLayout]; + } +} + +- (void)setArgumentInputViews:(NSArray *)argumentInputViews +{ + if (![_argumentInputViews isEqual:argumentInputViews]) { + + for (FLEXArgumentInputView *inputView in _argumentInputViews) { + [inputView removeFromSuperview]; + } + + _argumentInputViews = argumentInputViews; + + for (FLEXArgumentInputView *newInputView in argumentInputViews) { + [self addSubview:newInputView]; + } + + [self setNeedsLayout]; + } +} + ++ (UIView *)dividerView +{ + UIView *dividerView = [[UIView alloc] init]; + dividerView.backgroundColor = [self dividerColor]; + return dividerView; +} + ++ (UIColor *)dividerColor +{ + return [UIColor lightGrayColor]; +} + ++ (CGFloat)horizontalPadding +{ + return 10.0; +} + ++ (CGFloat)verticalPadding +{ + return 20.0; +} + ++ (UIFont *)labelFont +{ + return [FLEXUtility defaultFontOfSize:14.0]; +} + ++ (CGFloat)dividerLineHeight +{ + return 1.0; +} + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGFloat horizontalPadding = [[self class] horizontalPadding]; + CGFloat verticalPadding = [[self class] verticalPadding]; + CGFloat dividerLineHeight = [[self class] dividerLineHeight]; + + CGFloat height = 0; + CGFloat availableWidth = size.width - 2.0 * horizontalPadding; + CGSize constrainSize = CGSizeMake(availableWidth, CGFLOAT_MAX); + + height += verticalPadding; + height += ceil([self.targetDescriptionLabel sizeThatFits:constrainSize].height); + height += verticalPadding; + height += dividerLineHeight; + height += verticalPadding; + height += ceil([self.fieldDescriptionLabel sizeThatFits:constrainSize].height); + height += verticalPadding; + height += dividerLineHeight; + height += verticalPadding; + + for (FLEXArgumentInputView *inputView in self.argumentInputViews) { + height += [inputView sizeThatFits:constrainSize].height; + height += verticalPadding; + } + + return CGSizeMake(size.width, height); +} + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXFieldEditorViewController.h b/Pods/FLEX/Classes/Editing/FLEXFieldEditorViewController.h new file mode 100644 index 0000000000..13c011dc3a --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXFieldEditorViewController.h @@ -0,0 +1,28 @@ +// +// FLEXFieldEditorViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@class FLEXFieldEditorView; +@class FLEXArgumentInputView; + +@interface FLEXFieldEditorViewController : UIViewController + +- (id)initWithTarget:(id)target; + +// Convenience accessor since many subclasses only use one input view +@property (nonatomic, readonly) FLEXArgumentInputView *firstInputView; + +// For subclass use only. +@property (nonatomic, strong, readonly) id target; +@property (nonatomic, strong, readonly) FLEXFieldEditorView *fieldEditorView; +@property (nonatomic, strong, readonly) UIBarButtonItem *setterButton; +- (void)actionButtonPressed:(id)sender; +- (NSString *)titleForActionButton; + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXFieldEditorViewController.m b/Pods/FLEX/Classes/Editing/FLEXFieldEditorViewController.m new file mode 100644 index 0000000000..6ab029cd70 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXFieldEditorViewController.m @@ -0,0 +1,117 @@ +// +// FLEXFieldEditorViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXFieldEditorViewController.h" +#import "FLEXFieldEditorView.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXUtility.h" +#import "FLEXArgumentInputView.h" +#import "FLEXArgumentInputViewFactory.h" + +@interface FLEXFieldEditorViewController () + +@property (nonatomic, strong) UIScrollView *scrollView; + +@property (nonatomic, strong, readwrite) id target; +@property (nonatomic, strong, readwrite) FLEXFieldEditorView *fieldEditorView; +@property (nonatomic, strong, readwrite) UIBarButtonItem *setterButton; + +@end + +@implementation FLEXFieldEditorViewController + +- (id)initWithTarget:(id)target +{ + self = [super initWithNibName:nil bundle:nil]; + if (self) { + self.target = target; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; + } + return self; +} + +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (void)keyboardDidShow:(NSNotification *)notification +{ + CGRect keyboardRectInWindow = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; + CGSize keyboardSize = [self.view convertRect:keyboardRectInWindow fromView:nil].size; + UIEdgeInsets scrollInsets = self.scrollView.contentInset; + scrollInsets.bottom = keyboardSize.height; + self.scrollView.contentInset = scrollInsets; + self.scrollView.scrollIndicatorInsets = scrollInsets; + + // Find the active input view and scroll to make sure it's visible. + for (FLEXArgumentInputView *argumentInputView in self.fieldEditorView.argumentInputViews) { + if (argumentInputView.inputViewIsFirstResponder) { + CGRect scrollToVisibleRect = [self.scrollView convertRect:argumentInputView.bounds fromView:argumentInputView]; + [self.scrollView scrollRectToVisible:scrollToVisibleRect animated:YES]; + break; + } + } +} + +- (void)keyboardWillHide:(NSNotification *)notification +{ + UIEdgeInsets scrollInsets = self.scrollView.contentInset; + scrollInsets.bottom = 0.0; + self.scrollView.contentInset = scrollInsets; + self.scrollView.scrollIndicatorInsets = scrollInsets; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.view.backgroundColor = [FLEXUtility scrollViewGrayColor]; + + self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds]; + self.scrollView.backgroundColor = self.view.backgroundColor; + self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + self.scrollView.delegate = self; + [self.view addSubview:self.scrollView]; + + self.fieldEditorView = [[FLEXFieldEditorView alloc] init]; + self.fieldEditorView.backgroundColor = self.view.backgroundColor; + self.fieldEditorView.targetDescription = [NSString stringWithFormat:@"%@ %p", [self.target class], self.target]; + [self.scrollView addSubview:self.fieldEditorView]; + + self.setterButton = [[UIBarButtonItem alloc] initWithTitle:[self titleForActionButton] style:UIBarButtonItemStyleDone target:self action:@selector(actionButtonPressed:)]; + self.navigationItem.rightBarButtonItem = self.setterButton; +} + +- (void)viewWillLayoutSubviews +{ + CGSize constrainSize = CGSizeMake(self.scrollView.bounds.size.width, CGFLOAT_MAX); + CGSize fieldEditorSize = [self.fieldEditorView sizeThatFits:constrainSize]; + self.fieldEditorView.frame = CGRectMake(0, 0, fieldEditorSize.width, fieldEditorSize.height); + self.scrollView.contentSize = fieldEditorSize; +} + +- (FLEXArgumentInputView *)firstInputView +{ + return [[self.fieldEditorView argumentInputViews] firstObject]; +} + +- (void)actionButtonPressed:(id)sender +{ + // Subclasses can override + [self.fieldEditorView endEditing:YES]; +} + +- (NSString *)titleForActionButton +{ + // Subclasses can override. + return @"Set"; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXIvarEditorViewController.h b/Pods/FLEX/Classes/Editing/FLEXIvarEditorViewController.h new file mode 100644 index 0000000000..43f569828f --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXIvarEditorViewController.h @@ -0,0 +1,18 @@ +// +// FLEXIvarEditorViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/23/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXFieldEditorViewController.h" +#import + +@interface FLEXIvarEditorViewController : FLEXFieldEditorViewController + +- (id)initWithTarget:(id)target ivar:(Ivar)ivar; + ++ (BOOL)canEditIvar:(Ivar)ivar currentValue:(id)value; + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXIvarEditorViewController.m b/Pods/FLEX/Classes/Editing/FLEXIvarEditorViewController.m new file mode 100644 index 0000000000..da6fa5d37e --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXIvarEditorViewController.m @@ -0,0 +1,72 @@ +// +// FLEXIvarEditorViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/23/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXIvarEditorViewController.h" +#import "FLEXFieldEditorView.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXArgumentInputView.h" +#import "FLEXArgumentInputViewFactory.h" +#import "FLEXArgumentInputSwitchView.h" + +@interface FLEXIvarEditorViewController () + +@property (nonatomic, assign) Ivar ivar; + +@end + +@implementation FLEXIvarEditorViewController + +- (id)initWithTarget:(id)target ivar:(Ivar)ivar +{ + self = [super initWithTarget:target]; + if (self) { + self.ivar = ivar; + self.title = @"Instance Variable"; + } + return self; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.fieldEditorView.fieldDescription = [FLEXRuntimeUtility prettyNameForIvar:self.ivar]; + + FLEXArgumentInputView *inputView = [FLEXArgumentInputViewFactory argumentInputViewForTypeEncoding:ivar_getTypeEncoding(self.ivar)]; + inputView.backgroundColor = self.view.backgroundColor; + inputView.inputValue = [FLEXRuntimeUtility valueForIvar:self.ivar onObject:self.target]; + inputView.delegate = self; + self.fieldEditorView.argumentInputViews = @[inputView]; + + // Don't show a "set" button for switches. Set the ivar when the switch toggles. + if ([inputView isKindOfClass:[FLEXArgumentInputSwitchView class]]) { + self.navigationItem.rightBarButtonItem = nil; + } +} + +- (void)actionButtonPressed:(id)sender +{ + [super actionButtonPressed:sender]; + + [FLEXRuntimeUtility setValue:self.firstInputView.inputValue forIvar:self.ivar onObject:self.target]; + self.firstInputView.inputValue = [FLEXRuntimeUtility valueForIvar:self.ivar onObject:self.target]; +} + +- (void)argumentInputViewValueDidChange:(FLEXArgumentInputView *)argumentInputView +{ + if ([argumentInputView isKindOfClass:[FLEXArgumentInputSwitchView class]]) { + [self actionButtonPressed:nil]; + } +} + ++ (BOOL)canEditIvar:(Ivar)ivar currentValue:(id)value +{ + return [FLEXArgumentInputViewFactory canEditFieldWithTypeEncoding:ivar_getTypeEncoding(ivar) currentValue:value]; +} + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXMethodCallingViewController.h b/Pods/FLEX/Classes/Editing/FLEXMethodCallingViewController.h new file mode 100644 index 0000000000..66e73607da --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXMethodCallingViewController.h @@ -0,0 +1,16 @@ +// +// FLEXMethodCallingViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/23/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXFieldEditorViewController.h" +#import + +@interface FLEXMethodCallingViewController : FLEXFieldEditorViewController + +- (id)initWithTarget:(id)target method:(Method)method; + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXMethodCallingViewController.m b/Pods/FLEX/Classes/Editing/FLEXMethodCallingViewController.m new file mode 100644 index 0000000000..2c6506ba4a --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXMethodCallingViewController.m @@ -0,0 +1,100 @@ +// +// FLEXMethodCallingViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/23/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXMethodCallingViewController.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXFieldEditorView.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXObjectExplorerViewController.h" +#import "FLEXArgumentInputView.h" +#import "FLEXArgumentInputViewFactory.h" + +@interface FLEXMethodCallingViewController () + +@property (nonatomic, assign) Method method; + +@end + +@implementation FLEXMethodCallingViewController + +- (id)initWithTarget:(id)target method:(Method)method +{ + self = [super initWithTarget:target]; + if (self) { + self.method = method; + self.title = [self isClassMethod] ? @"Class Method" : @"Method"; + } + return self; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.fieldEditorView.fieldDescription = [FLEXRuntimeUtility prettyNameForMethod:self.method isClassMethod:[self isClassMethod]]; + + NSArray *methodComponents = [FLEXRuntimeUtility prettyArgumentComponentsForMethod:self.method]; + NSMutableArray *argumentInputViews = [NSMutableArray array]; + unsigned int argumentIndex = kFLEXNumberOfImplicitArgs; + for (NSString *methodComponent in methodComponents) { + char *argumentTypeEncoding = method_copyArgumentType(self.method, argumentIndex); + FLEXArgumentInputView *inputView = [FLEXArgumentInputViewFactory argumentInputViewForTypeEncoding:argumentTypeEncoding]; + free(argumentTypeEncoding); + + inputView.backgroundColor = self.view.backgroundColor; + inputView.title = methodComponent; + [argumentInputViews addObject:inputView]; + argumentIndex++; + } + self.fieldEditorView.argumentInputViews = argumentInputViews; +} + +- (BOOL)isClassMethod +{ + return self.target && self.target == [self.target class]; +} + +- (NSString *)titleForActionButton +{ + return @"Call"; +} + +- (void)actionButtonPressed:(id)sender +{ + [super actionButtonPressed:sender]; + + NSMutableArray *arguments = [NSMutableArray array]; + for (FLEXArgumentInputView *inputView in self.fieldEditorView.argumentInputViews) { + id argumentValue = inputView.inputValue; + if (!argumentValue) { + // Use NSNulls as placeholders in the array. They will be interpreted as nil arguments. + argumentValue = [NSNull null]; + } + [arguments addObject:argumentValue]; + } + + NSError *error = nil; + id returnedObject = [FLEXRuntimeUtility performSelector:method_getName(self.method) onObject:self.target withArguments:arguments error:&error]; + + if (error) { + NSString *title = @"Method Call Failed"; + NSString *message = [error localizedDescription]; + UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; + [alert show]; + } else if (returnedObject) { + // For non-nil (or void) return types, push an explorer view controller to display the returned object + FLEXObjectExplorerViewController *explorerViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:returnedObject]; + [self.navigationController pushViewController:explorerViewController animated:YES]; + } else { + // If we didn't get a returned object but the method call succeeded, + // pop this view controller off the stack to indicate that the call went through. + [self.navigationController popViewControllerAnimated:YES]; + } +} + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXPropertyEditorViewController.h b/Pods/FLEX/Classes/Editing/FLEXPropertyEditorViewController.h new file mode 100644 index 0000000000..8d42c8e282 --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXPropertyEditorViewController.h @@ -0,0 +1,18 @@ +// +// FLEXPropertyEditorViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/20/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXFieldEditorViewController.h" +#import + +@interface FLEXPropertyEditorViewController : FLEXFieldEditorViewController + +- (id)initWithTarget:(id)target property:(objc_property_t)property; + ++ (BOOL)canEditProperty:(objc_property_t)property currentValue:(id)value; + +@end diff --git a/Pods/FLEX/Classes/Editing/FLEXPropertyEditorViewController.m b/Pods/FLEX/Classes/Editing/FLEXPropertyEditorViewController.m new file mode 100644 index 0000000000..4b09d8304a --- /dev/null +++ b/Pods/FLEX/Classes/Editing/FLEXPropertyEditorViewController.m @@ -0,0 +1,94 @@ +// +// FLEXPropertyEditorViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/20/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXPropertyEditorViewController.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXFieldEditorView.h" +#import "FLEXArgumentInputView.h" +#import "FLEXArgumentInputViewFactory.h" +#import "FLEXArgumentInputSwitchView.h" + +@interface FLEXPropertyEditorViewController () + +@property (nonatomic, assign) objc_property_t property; + +@end + +@implementation FLEXPropertyEditorViewController + +- (id)initWithTarget:(id)target property:(objc_property_t)property +{ + self = [super initWithTarget:target]; + if (self) { + self.property = property; + self.title = @"Property"; + } + return self; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.fieldEditorView.fieldDescription = [FLEXRuntimeUtility fullDescriptionForProperty:self.property]; + id currentValue = [FLEXRuntimeUtility valueForProperty:self.property onObject:self.target]; + self.setterButton.enabled = [[self class] canEditProperty:self.property currentValue:currentValue]; + + const char *typeEncoding = [[FLEXRuntimeUtility typeEncodingForProperty:self.property] UTF8String]; + FLEXArgumentInputView *inputView = [FLEXArgumentInputViewFactory argumentInputViewForTypeEncoding:typeEncoding]; + inputView.backgroundColor = self.view.backgroundColor; + inputView.inputValue = [FLEXRuntimeUtility valueForProperty:self.property onObject:self.target]; + inputView.delegate = self; + self.fieldEditorView.argumentInputViews = @[inputView]; + + // Don't show a "set" button for switches - just call the setter immediately after the switch toggles. + if ([inputView isKindOfClass:[FLEXArgumentInputSwitchView class]]) { + self.navigationItem.rightBarButtonItem = nil; + } +} + +- (void)actionButtonPressed:(id)sender +{ + [super actionButtonPressed:sender]; + + id userInputObject = self.firstInputView.inputValue; + NSArray *arguments = userInputObject ? @[userInputObject] : nil; + SEL setterSelector = [FLEXRuntimeUtility setterSelectorForProperty:self.property]; + NSError *error = nil; + [FLEXRuntimeUtility performSelector:setterSelector onObject:self.target withArguments:arguments error:&error]; + if (error) { + NSString *title = @"Property Setter Failed"; + NSString *message = [error localizedDescription]; + UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; + [alert show]; + self.firstInputView.inputValue = [FLEXRuntimeUtility valueForProperty:self.property onObject:self.target]; + } else { + // If the setter was called without error, pop the view controller to indicate that and make the user's life easier. + // Don't do this for simulated taps on the action button (i.e. from switch/BOOL editors). The experience is weird there. + if (sender) { + [self.navigationController popViewControllerAnimated:YES]; + } + } +} + +- (void)argumentInputViewValueDidChange:(FLEXArgumentInputView *)argumentInputView +{ + if ([argumentInputView isKindOfClass:[FLEXArgumentInputSwitchView class]]) { + [self actionButtonPressed:nil]; + } +} + ++ (BOOL)canEditProperty:(objc_property_t)property currentValue:(id)value +{ + const char *typeEncoding = [[FLEXRuntimeUtility typeEncodingForProperty:property] UTF8String]; + BOOL canEditType = [FLEXArgumentInputViewFactory canEditFieldWithTypeEncoding:typeEncoding currentValue:value]; + BOOL isReadonly = [FLEXRuntimeUtility isReadonlyProperty:property]; + return canEditType && !isReadonly; +} + +@end diff --git a/Pods/FLEX/Classes/ExplorerInterface/FLEXExplorerViewController.h b/Pods/FLEX/Classes/ExplorerInterface/FLEXExplorerViewController.h new file mode 100644 index 0000000000..0e41b7b112 --- /dev/null +++ b/Pods/FLEX/Classes/ExplorerInterface/FLEXExplorerViewController.h @@ -0,0 +1,37 @@ +// +// FLEXExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 4/4/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@protocol FLEXExplorerViewControllerDelegate; + +@interface FLEXExplorerViewController : UIViewController + +@property (nonatomic, weak) id delegate; + +- (BOOL)shouldReceiveTouchAtWindowPoint:(CGPoint)pointInWindowCoordinates; +- (BOOL)wantsWindowToBecomeKey; + +// Keyboard shortcut helpers + +- (void)toggleSelectTool; +- (void)toggleMoveTool; +- (void)toggleViewsTool; +- (void)toggleMenuTool; +- (void)handleDownArrowKeyPressed; +- (void)handleUpArrowKeyPressed; +- (void)handleRightArrowKeyPressed; +- (void)handleLeftArrowKeyPressed; + +@end + +@protocol FLEXExplorerViewControllerDelegate + +- (void)explorerViewControllerDidFinish:(FLEXExplorerViewController *)explorerViewController; + +@end diff --git a/Pods/FLEX/Classes/ExplorerInterface/FLEXExplorerViewController.m b/Pods/FLEX/Classes/ExplorerInterface/FLEXExplorerViewController.m new file mode 100644 index 0000000000..980d6fd859 --- /dev/null +++ b/Pods/FLEX/Classes/ExplorerInterface/FLEXExplorerViewController.m @@ -0,0 +1,908 @@ +// +// FLEXExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 4/4/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXExplorerViewController.h" +#import "FLEXExplorerToolbar.h" +#import "FLEXToolbarItem.h" +#import "FLEXUtility.h" +#import "FLEXHierarchyTableViewController.h" +#import "FLEXGlobalsTableViewController.h" +#import "FLEXObjectExplorerViewController.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXNetworkHistoryTableViewController.h" + +typedef NS_ENUM(NSUInteger, FLEXExplorerMode) { + FLEXExplorerModeDefault, + FLEXExplorerModeSelect, + FLEXExplorerModeMove +}; + +@interface FLEXExplorerViewController () + +@property (nonatomic, strong) FLEXExplorerToolbar *explorerToolbar; + +/// Tracks the currently active tool/mode +@property (nonatomic, assign) FLEXExplorerMode currentMode; + +/// Gesture recognizer for dragging a view in move mode +@property (nonatomic, strong) UIPanGestureRecognizer *movePanGR; + +/// Gesture recognizer for showing additional details on the selected view +@property (nonatomic, strong) UITapGestureRecognizer *detailsTapGR; + +/// Only valid while a move pan gesture is in progress. +@property (nonatomic, assign) CGRect selectedViewFrameBeforeDragging; + +/// Only valid while a toolbar drag pan gesture is in progress. +@property (nonatomic, assign) CGRect toolbarFrameBeforeDragging; + +/// Borders of all the visible views in the hierarchy at the selection point. +/// The keys are NSValues with the correponding view (nonretained). +@property (nonatomic, strong) NSDictionary *outlineViewsForVisibleViews; + +/// The actual views at the selection point with the deepest view last. +@property (nonatomic, strong) NSArray *viewsAtTapPoint; + +/// The view that we're currently highlighting with an overlay and displaying details for. +@property (nonatomic, strong) UIView *selectedView; + +/// A colored transparent overlay to indicate that the view is selected. +@property (nonatomic, strong) UIView *selectedViewOverlay; + +/// Tracked so we can restore the key window after dismissing a modal. +/// We need to become key after modal presentation so we can correctly capture intput. +/// If we're just showing the toolbar, we want the main app's window to remain key so that we don't interfere with input, status bar, etc. +@property (nonatomic, strong) UIWindow *previousKeyWindow; + +/// Similar to the previousKeyWindow property above, we need to track status bar styling if +/// the app doesn't use view controller based status bar management. When we present a modal, +/// we want to change the status bar style to UIStausBarStyleDefault. Before changing, we stash +/// the current style. On dismissal, we return the staus bar to the style that the app was using previously. +@property (nonatomic, assign) UIStatusBarStyle previousStatusBarStyle; + +/// All views that we're KVOing. Used to help us clean up properly. +@property (nonatomic, strong) NSMutableSet *observedViews; + +@end + +@implementation FLEXExplorerViewController + +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil +{ + self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; + if (self) { + self.observedViews = [NSMutableSet set]; + } + return self; +} + +-(void)dealloc +{ + for (UIView *view in _observedViews) { + [self stopObservingView:view]; + } +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + // Toolbar + self.explorerToolbar = [[FLEXExplorerToolbar alloc] init]; + CGSize toolbarSize = [self.explorerToolbar sizeThatFits:self.view.bounds.size]; + // Start the toolbar off below any bars that may be at the top of the view. + CGFloat toolbarOriginY = 100.0; + self.explorerToolbar.frame = CGRectMake(0.0, toolbarOriginY, toolbarSize.width, toolbarSize.height); + self.explorerToolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin; + [self.view addSubview:self.explorerToolbar]; + [self setupToolbarActions]; + [self setupToolbarGestures]; + + // View selection + UITapGestureRecognizer *selectionTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSelectionTap:)]; + [self.view addGestureRecognizer:selectionTapGR]; + + // View moving + self.movePanGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleMovePan:)]; + self.movePanGR.enabled = self.currentMode == FLEXExplorerModeMove; + [self.view addGestureRecognizer:self.movePanGR]; +} + +- (void)viewWillAppear:(BOOL)animated +{ + [super viewWillAppear:animated]; + + [self updateButtonStates]; +} + + +#pragma mark - Rotation + +- (UIViewController *)viewControllerForRotationAndOrientation +{ + UIWindow *window = self.previousKeyWindow ?: [[UIApplication sharedApplication] keyWindow]; + UIViewController *viewController = window.rootViewController; + NSString *viewControllerSelectorString = [@[@"_vie", @"wContro", @"llerFor", @"Supported", @"Interface", @"Orientations"] componentsJoinedByString:@""]; + SEL viewControllerSelector = NSSelectorFromString(viewControllerSelectorString); + if ([viewController respondsToSelector:viewControllerSelector]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + viewController = [viewController performSelector:viewControllerSelector]; +#pragma clang diagnostic pop + } + return viewController; +} + +- (UIInterfaceOrientationMask)supportedInterfaceOrientations +{ + UIViewController *viewControllerToAsk = [self viewControllerForRotationAndOrientation]; + UIInterfaceOrientationMask supportedOrientations = [FLEXUtility infoPlistSupportedInterfaceOrientationsMask]; + if (viewControllerToAsk && viewControllerToAsk != self) { + supportedOrientations = [viewControllerToAsk supportedInterfaceOrientations]; + } + + // The UIViewController docs state that this method must not return zero. + // If we weren't able to get a valid value for the supported interface orientations, default to all supported. + if (supportedOrientations == 0) { + supportedOrientations = UIInterfaceOrientationMaskAll; + } + + return supportedOrientations; +} + +- (BOOL)shouldAutorotate +{ + UIViewController *viewControllerToAsk = [self viewControllerForRotationAndOrientation]; + BOOL shouldAutorotate = YES; + if (viewControllerToAsk && viewControllerToAsk != self) { + shouldAutorotate = [viewControllerToAsk shouldAutorotate]; + } + return shouldAutorotate; +} + +- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration +{ + for (UIView *outlineView in [self.outlineViewsForVisibleViews allValues]) { + outlineView.hidden = YES; + } + self.selectedViewOverlay.hidden = YES; +} + +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation +{ + for (UIView *view in self.viewsAtTapPoint) { + NSValue *key = [NSValue valueWithNonretainedObject:view]; + UIView *outlineView = self.outlineViewsForVisibleViews[key]; + outlineView.frame = [self frameInLocalCoordinatesForView:view]; + if (self.currentMode == FLEXExplorerModeSelect) { + outlineView.hidden = NO; + } + } + + if (self.selectedView) { + self.selectedViewOverlay.frame = [self frameInLocalCoordinatesForView:self.selectedView]; + self.selectedViewOverlay.hidden = NO; + } +} + + +#pragma mark - Setter Overrides + +- (void)setSelectedView:(UIView *)selectedView +{ + if (![_selectedView isEqual:selectedView]) { + if (![self.viewsAtTapPoint containsObject:_selectedView]) { + [self stopObservingView:_selectedView]; + } + + _selectedView = selectedView; + + [self beginObservingView:selectedView]; + + // Update the toolbar and selected overlay + self.explorerToolbar.selectedViewDescription = [FLEXUtility descriptionForView:selectedView includingFrame:YES]; + self.explorerToolbar.selectedViewOverlayColor = [FLEXUtility consistentRandomColorForObject:selectedView];; + + if (selectedView) { + if (!self.selectedViewOverlay) { + self.selectedViewOverlay = [[UIView alloc] init]; + [self.view addSubview:self.selectedViewOverlay]; + self.selectedViewOverlay.layer.borderWidth = 1.0; + } + UIColor *outlineColor = [FLEXUtility consistentRandomColorForObject:selectedView]; + self.selectedViewOverlay.backgroundColor = [outlineColor colorWithAlphaComponent:0.2]; + self.selectedViewOverlay.layer.borderColor = [outlineColor CGColor]; + self.selectedViewOverlay.frame = [self.view convertRect:selectedView.bounds fromView:selectedView]; + + // Make sure the selected overlay is in front of all the other subviews except the toolbar, which should always stay on top. + [self.view bringSubviewToFront:self.selectedViewOverlay]; + [self.view bringSubviewToFront:self.explorerToolbar]; + } else { + [self.selectedViewOverlay removeFromSuperview]; + self.selectedViewOverlay = nil; + } + + // Some of the button states depend on whether we have a selected view. + [self updateButtonStates]; + } +} + +- (void)setViewsAtTapPoint:(NSArray *)viewsAtTapPoint +{ + if (![_viewsAtTapPoint isEqual:viewsAtTapPoint]) { + for (UIView *view in _viewsAtTapPoint) { + if (view != self.selectedView) { + [self stopObservingView:view]; + } + } + + _viewsAtTapPoint = viewsAtTapPoint; + + for (UIView *view in viewsAtTapPoint) { + [self beginObservingView:view]; + } + } +} + +- (void)setCurrentMode:(FLEXExplorerMode)currentMode +{ + if (_currentMode != currentMode) { + _currentMode = currentMode; + switch (currentMode) { + case FLEXExplorerModeDefault: + [self removeAndClearOutlineViews]; + self.viewsAtTapPoint = nil; + self.selectedView = nil; + break; + + case FLEXExplorerModeSelect: + // Make sure the outline views are unhidden in case we came from the move mode. + for (id key in self.outlineViewsForVisibleViews) { + UIView *outlineView = self.outlineViewsForVisibleViews[key]; + outlineView.hidden = NO; + } + break; + + case FLEXExplorerModeMove: + // Hide all the outline views to focus on the selected view, which is the only one that will move. + for (id key in self.outlineViewsForVisibleViews) { + UIView *outlineView = self.outlineViewsForVisibleViews[key]; + outlineView.hidden = YES; + } + break; + } + self.movePanGR.enabled = currentMode == FLEXExplorerModeMove; + [self updateButtonStates]; + } +} + + +#pragma mark - View Tracking + +- (void)beginObservingView:(UIView *)view +{ + // Bail if we're already observing this view or if there's nothing to observe. + if (!view || [self.observedViews containsObject:view]) { + return; + } + + for (NSString *keyPath in [[self class] viewKeyPathsToTrack]) { + [view addObserver:self forKeyPath:keyPath options:0 context:NULL]; + } + + [self.observedViews addObject:view]; +} + +- (void)stopObservingView:(UIView *)view +{ + if (!view) { + return; + } + + for (NSString *keyPath in [[self class] viewKeyPathsToTrack]) { + [view removeObserver:self forKeyPath:keyPath]; + } + + [self.observedViews removeObject:view]; +} + ++ (NSArray *)viewKeyPathsToTrack +{ + static NSArray *trackedViewKeyPaths = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSString *frameKeyPath = NSStringFromSelector(@selector(frame)); + trackedViewKeyPaths = @[frameKeyPath]; + }); + return trackedViewKeyPaths; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context +{ + [self updateOverlayAndDescriptionForObjectIfNeeded:object]; +} + +- (void)updateOverlayAndDescriptionForObjectIfNeeded:(id)object +{ + NSUInteger indexOfView = [self.viewsAtTapPoint indexOfObject:object]; + if (indexOfView != NSNotFound) { + UIView *view = self.viewsAtTapPoint[indexOfView]; + NSValue *key = [NSValue valueWithNonretainedObject:view]; + UIView *outline = self.outlineViewsForVisibleViews[key]; + if (outline) { + outline.frame = [self frameInLocalCoordinatesForView:view]; + } + } + if (object == self.selectedView) { + // Update the selected view description since we show the frame value there. + self.explorerToolbar.selectedViewDescription = [FLEXUtility descriptionForView:self.selectedView includingFrame:YES]; + CGRect selectedViewOutlineFrame = [self frameInLocalCoordinatesForView:self.selectedView]; + self.selectedViewOverlay.frame = selectedViewOutlineFrame; + } +} + +- (CGRect)frameInLocalCoordinatesForView:(UIView *)view +{ + // First convert to window coordinates since the view may be in a different window than our view. + CGRect frameInWindow = [view convertRect:view.bounds toView:nil]; + // Then convert from the window to our view's coordinate space. + return [self.view convertRect:frameInWindow fromView:nil]; +} + + +#pragma mark - Toolbar Buttons + +- (void)setupToolbarActions +{ + [self.explorerToolbar.selectItem addTarget:self action:@selector(selectButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; + [self.explorerToolbar.hierarchyItem addTarget:self action:@selector(hierarchyButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; + [self.explorerToolbar.moveItem addTarget:self action:@selector(moveButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; + [self.explorerToolbar.globalsItem addTarget:self action:@selector(globalsButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; + [self.explorerToolbar.closeItem addTarget:self action:@selector(closeButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; +} + +- (void)selectButtonTapped:(FLEXToolbarItem *)sender +{ + [self toggleSelectTool]; +} + +- (void)hierarchyButtonTapped:(FLEXToolbarItem *)sender +{ + [self toggleViewsTool]; +} + +- (NSArray *)allViewsInHierarchy +{ + NSMutableArray *allViews = [NSMutableArray array]; + NSArray *windows = [FLEXUtility allWindows]; + for (UIWindow *window in windows) { + if (window != self.view.window) { + [allViews addObject:window]; + [allViews addObjectsFromArray:[self allRecursiveSubviewsInView:window]]; + } + } + return allViews; +} + +- (UIWindow *)statusWindow +{ + NSString *statusBarString = [NSString stringWithFormat:@"%@arWindow", @"_statusB"]; + return [[UIApplication sharedApplication] valueForKey:statusBarString]; +} + +- (void)moveButtonTapped:(FLEXToolbarItem *)sender +{ + [self toggleMoveTool]; +} + +- (void)globalsButtonTapped:(FLEXToolbarItem *)sender +{ + [self toggleMenuTool]; +} + +- (void)closeButtonTapped:(FLEXToolbarItem *)sender +{ + self.currentMode = FLEXExplorerModeDefault; + [self.delegate explorerViewControllerDidFinish:self]; +} + +- (void)updateButtonStates +{ + // Move and details only active when an object is selected. + BOOL hasSelectedObject = self.selectedView != nil; + self.explorerToolbar.moveItem.enabled = hasSelectedObject; + self.explorerToolbar.selectItem.selected = self.currentMode == FLEXExplorerModeSelect; + self.explorerToolbar.moveItem.selected = self.currentMode == FLEXExplorerModeMove; +} + + +#pragma mark - Toolbar Dragging + +- (void)setupToolbarGestures +{ + // Pan gesture for dragging. + UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleToolbarPanGesture:)]; + [self.explorerToolbar.dragHandle addGestureRecognizer:panGR]; + + // Tap gesture for hinting. + UITapGestureRecognizer *hintTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleToolbarHintTapGesture:)]; + [self.explorerToolbar.dragHandle addGestureRecognizer:hintTapGR]; + + // Tap gesture for showing additional details + self.detailsTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleToolbarDetailsTapGesture:)]; + [self.explorerToolbar.selectedViewDescriptionContainer addGestureRecognizer:self.detailsTapGR]; +} + +- (void)handleToolbarPanGesture:(UIPanGestureRecognizer *)panGR +{ + switch (panGR.state) { + case UIGestureRecognizerStateBegan: + self.toolbarFrameBeforeDragging = self.explorerToolbar.frame; + [self updateToolbarPostionWithDragGesture:panGR]; + break; + + case UIGestureRecognizerStateChanged: + case UIGestureRecognizerStateEnded: + [self updateToolbarPostionWithDragGesture:panGR]; + break; + + default: + break; + } +} + +- (void)updateToolbarPostionWithDragGesture:(UIPanGestureRecognizer *)panGR +{ + CGPoint translation = [panGR translationInView:self.view]; + CGRect newToolbarFrame = self.toolbarFrameBeforeDragging; + newToolbarFrame.origin.y += translation.y; + + CGFloat maxY = CGRectGetMaxY(self.view.bounds) - newToolbarFrame.size.height; + if (newToolbarFrame.origin.y < 0.0) { + newToolbarFrame.origin.y = 0.0; + } else if (newToolbarFrame.origin.y > maxY) { + newToolbarFrame.origin.y = maxY; + } + + self.explorerToolbar.frame = newToolbarFrame; +} + +- (void)handleToolbarHintTapGesture:(UITapGestureRecognizer *)tapGR +{ + // Bounce the toolbar to indicate that it is draggable. + // TODO: make it bouncier. + if (tapGR.state == UIGestureRecognizerStateRecognized) { + CGRect originalToolbarFrame = self.explorerToolbar.frame; + const NSTimeInterval kHalfwayDuration = 0.2; + const CGFloat kVerticalOffset = 30.0; + [UIView animateWithDuration:kHalfwayDuration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{ + CGRect newToolbarFrame = self.explorerToolbar.frame; + newToolbarFrame.origin.y += kVerticalOffset; + self.explorerToolbar.frame = newToolbarFrame; + } completion:^(BOOL finished) { + [UIView animateWithDuration:kHalfwayDuration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{ + self.explorerToolbar.frame = originalToolbarFrame; + } completion:nil]; + }]; + } +} + +- (void)handleToolbarDetailsTapGesture:(UITapGestureRecognizer *)tapGR +{ + if (tapGR.state == UIGestureRecognizerStateRecognized && self.selectedView) { + FLEXObjectExplorerViewController *selectedViewExplorer = [FLEXObjectExplorerFactory explorerViewControllerForObject:self.selectedView]; + selectedViewExplorer.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selectedViewExplorerFinished:)]; + UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:selectedViewExplorer]; + [self makeKeyAndPresentViewController:navigationController animated:YES completion:nil]; + } +} + + +#pragma mark - View Selection + +- (void)handleSelectionTap:(UITapGestureRecognizer *)tapGR +{ + // Only if we're in selection mode + if (self.currentMode == FLEXExplorerModeSelect && tapGR.state == UIGestureRecognizerStateRecognized) { + // Note that [tapGR locationInView:nil] is broken in iOS 8, so we have to do a two step conversion to window coordinates. + // Thanks to @lascorbe for finding this: https://github.com/Flipboard/FLEX/pull/31 + CGPoint tapPointInView = [tapGR locationInView:self.view]; + CGPoint tapPointInWindow = [self.view convertPoint:tapPointInView toView:nil]; + [self updateOutlineViewsForSelectionPoint:tapPointInWindow]; + } +} + +- (void)updateOutlineViewsForSelectionPoint:(CGPoint)selectionPointInWindow +{ + [self removeAndClearOutlineViews]; + + // Include hidden views in the "viewsAtTapPoint" array so we can show them in the hierarchy list. + self.viewsAtTapPoint = [self viewsAtPoint:selectionPointInWindow skipHiddenViews:NO]; + + // For outlined views and the selected view, only use visible views. + // Outlining hidden views adds clutter and makes the selection behavior confusing. + NSArray *visibleViewsAtTapPoint = [self viewsAtPoint:selectionPointInWindow skipHiddenViews:YES]; + NSMutableDictionary *newOutlineViewsForVisibleViews = [NSMutableDictionary dictionary]; + for (UIView *view in visibleViewsAtTapPoint) { + UIView *outlineView = [self outlineViewForView:view]; + [self.view addSubview:outlineView]; + NSValue *key = [NSValue valueWithNonretainedObject:view]; + [newOutlineViewsForVisibleViews setObject:outlineView forKey:key]; + } + self.outlineViewsForVisibleViews = newOutlineViewsForVisibleViews; + self.selectedView = [self viewForSelectionAtPoint:selectionPointInWindow]; + + // Make sure the explorer toolbar doesn't end up behind the newly added outline views. + [self.view bringSubviewToFront:self.explorerToolbar]; + + [self updateButtonStates]; +} + +- (UIView *)outlineViewForView:(UIView *)view +{ + CGRect outlineFrame = [self frameInLocalCoordinatesForView:view]; + UIView *outlineView = [[UIView alloc] initWithFrame:outlineFrame]; + outlineView.backgroundColor = [UIColor clearColor]; + outlineView.layer.borderColor = [[FLEXUtility consistentRandomColorForObject:view] CGColor]; + outlineView.layer.borderWidth = 1.0; + return outlineView; +} + +- (void)removeAndClearOutlineViews +{ + for (id key in self.outlineViewsForVisibleViews) { + UIView *outlineView = self.outlineViewsForVisibleViews[key]; + [outlineView removeFromSuperview]; + } + self.outlineViewsForVisibleViews = nil; +} + +- (NSArray *)viewsAtPoint:(CGPoint)tapPointInWindow skipHiddenViews:(BOOL)skipHidden +{ + NSMutableArray *views = [NSMutableArray array]; + for (UIWindow *window in [FLEXUtility allWindows]) { + // Don't include the explorer's own window or subviews. + if (window != self.view.window && [window pointInside:tapPointInWindow withEvent:nil]) { + [views addObject:window]; + [views addObjectsFromArray:[self recursiveSubviewsAtPoint:tapPointInWindow inView:window skipHiddenViews:skipHidden]]; + } + } + return views; +} + +- (UIView *)viewForSelectionAtPoint:(CGPoint)tapPointInWindow +{ + // Select in the window that would handle the touch, but don't just use the result of hitTest:withEvent: so we can still select views with interaction disabled. + // Default to the the application's key window if none of the windows want the touch. + UIWindow *windowForSelection = [[UIApplication sharedApplication] keyWindow]; + for (UIWindow *window in [[FLEXUtility allWindows] reverseObjectEnumerator]) { + // Ignore the explorer's own window. + if (window != self.view.window) { + if ([window hitTest:tapPointInWindow withEvent:nil]) { + windowForSelection = window; + break; + } + } + } + + // Select the deepest visible view at the tap point. This generally corresponds to what the user wants to select. + return [[self recursiveSubviewsAtPoint:tapPointInWindow inView:windowForSelection skipHiddenViews:YES] lastObject]; +} + +- (NSArray *)recursiveSubviewsAtPoint:(CGPoint)pointInView inView:(UIView *)view skipHiddenViews:(BOOL)skipHidden +{ + NSMutableArray *subviewsAtPoint = [NSMutableArray array]; + for (UIView *subview in view.subviews) { + BOOL isHidden = subview.hidden || subview.alpha < 0.01; + if (skipHidden && isHidden) { + continue; + } + + BOOL subviewContainsPoint = CGRectContainsPoint(subview.frame, pointInView); + if (subviewContainsPoint) { + [subviewsAtPoint addObject:subview]; + } + + // If this view doesn't clip to its bounds, we need to check its subviews even if it doesn't contain the selection point. + // They may be visible and contain the selection point. + if (subviewContainsPoint || !subview.clipsToBounds) { + CGPoint pointInSubview = [view convertPoint:pointInView toView:subview]; + [subviewsAtPoint addObjectsFromArray:[self recursiveSubviewsAtPoint:pointInSubview inView:subview skipHiddenViews:skipHidden]]; + } + } + return subviewsAtPoint; +} + +- (NSArray *)allRecursiveSubviewsInView:(UIView *)view +{ + NSMutableArray *subviews = [NSMutableArray array]; + for (UIView *subview in view.subviews) { + [subviews addObject:subview]; + [subviews addObjectsFromArray:[self allRecursiveSubviewsInView:subview]]; + } + return subviews; +} + +- (NSDictionary *)hierarchyDepthsForViews:(NSArray *)views +{ + NSMutableDictionary *hierarchyDepths = [NSMutableDictionary dictionary]; + for (UIView *view in views) { + NSInteger depth = 0; + UIView *tryView = view; + while (tryView.superview) { + tryView = tryView.superview; + depth++; + } + [hierarchyDepths setObject:@(depth) forKey:[NSValue valueWithNonretainedObject:view]]; + } + return hierarchyDepths; +} + + +#pragma mark - Selected View Moving + +- (void)handleMovePan:(UIPanGestureRecognizer *)movePanGR +{ + switch (movePanGR.state) { + case UIGestureRecognizerStateBegan: + self.selectedViewFrameBeforeDragging = self.selectedView.frame; + [self updateSelectedViewPositionWithDragGesture:movePanGR]; + break; + + case UIGestureRecognizerStateChanged: + case UIGestureRecognizerStateEnded: + [self updateSelectedViewPositionWithDragGesture:movePanGR]; + break; + + default: + break; + } +} + +- (void)updateSelectedViewPositionWithDragGesture:(UIPanGestureRecognizer *)movePanGR +{ + CGPoint translation = [movePanGR translationInView:self.selectedView.superview]; + CGRect newSelectedViewFrame = self.selectedViewFrameBeforeDragging; + newSelectedViewFrame.origin.x = FLEXFloor(newSelectedViewFrame.origin.x + translation.x); + newSelectedViewFrame.origin.y = FLEXFloor(newSelectedViewFrame.origin.y + translation.y); + self.selectedView.frame = newSelectedViewFrame; +} + + +#pragma mark - Touch Handling + +- (BOOL)shouldReceiveTouchAtWindowPoint:(CGPoint)pointInWindowCoordinates +{ + BOOL shouldReceiveTouch = NO; + + CGPoint pointInLocalCoordinates = [self.view convertPoint:pointInWindowCoordinates fromView:nil]; + + // Always if it's on the toolbar + if (CGRectContainsPoint(self.explorerToolbar.frame, pointInLocalCoordinates)) { + shouldReceiveTouch = YES; + } + + // Always if we're in selection mode + if (!shouldReceiveTouch && self.currentMode == FLEXExplorerModeSelect) { + shouldReceiveTouch = YES; + } + + // Always in move mode too + if (!shouldReceiveTouch && self.currentMode == FLEXExplorerModeMove) { + shouldReceiveTouch = YES; + } + + // Always if we have a modal presented + if (!shouldReceiveTouch && self.presentedViewController) { + shouldReceiveTouch = YES; + } + + return shouldReceiveTouch; +} + + +#pragma mark - FLEXHierarchyTableViewControllerDelegate + +- (void)hierarchyViewController:(FLEXHierarchyTableViewController *)hierarchyViewController didFinishWithSelectedView:(UIView *)selectedView +{ + // Note that we need to wait until the view controller is dismissed to calculated the frame of the outline view. + // Otherwise the coordinate conversion doesn't give the correct result. + [self resignKeyAndDismissViewControllerAnimated:YES completion:^{ + // If the selected view is outside of the tap point array (selected from "Full Hierarchy"), + // then clear out the tap point array and remove all the outline views. + if (![self.viewsAtTapPoint containsObject:selectedView]) { + self.viewsAtTapPoint = nil; + [self removeAndClearOutlineViews]; + } + + // If we now have a selected view and we didn't have one previously, go to "select" mode. + if (self.currentMode == FLEXExplorerModeDefault && selectedView) { + self.currentMode = FLEXExplorerModeSelect; + } + + // The selected view setter will also update the selected view overlay appropriately. + self.selectedView = selectedView; + }]; +} + + +#pragma mark - FLEXGlobalsViewControllerDelegate + +- (void)globalsViewControllerDidFinish:(FLEXGlobalsTableViewController *)globalsViewController +{ + [self resignKeyAndDismissViewControllerAnimated:YES completion:nil]; +} + + +#pragma mark - FLEXObjectExplorerViewController Done Action + +- (void)selectedViewExplorerFinished:(id)sender +{ + [self resignKeyAndDismissViewControllerAnimated:YES completion:nil]; +} + + +#pragma mark - Modal Presentation and Window Management + +- (void)makeKeyAndPresentViewController:(UIViewController *)viewController animated:(BOOL)animated completion:(void (^)(void))completion +{ + // Save the current key window so we can restore it following dismissal. + self.previousKeyWindow = [[UIApplication sharedApplication] keyWindow]; + + // Make our window key to correctly handle input. + [self.view.window makeKeyWindow]; + + // Move the status bar on top of FLEX so we can get scroll to top behavior for taps. + [[self statusWindow] setWindowLevel:self.view.window.windowLevel + 1.0]; + + // If this app doesn't use view controller based status bar management and we're on iOS 7+, + // make sure the status bar style is UIStatusBarStyleDefault. We don't actully have to check + // for view controller based management because the global methods no-op if that is turned on. + self.previousStatusBarStyle = [[UIApplication sharedApplication] statusBarStyle]; + [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault]; + + // Show the view controller. + [self presentViewController:viewController animated:animated completion:completion]; +} + +- (void)resignKeyAndDismissViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion +{ + UIWindow *previousKeyWindow = self.previousKeyWindow; + self.previousKeyWindow = nil; + [previousKeyWindow makeKeyWindow]; + [[previousKeyWindow rootViewController] setNeedsStatusBarAppearanceUpdate]; + + // Restore the status bar window's normal window level. + // We want it above FLEX while a modal is presented for scroll to top, but below FLEX otherwise for exploration. + [[self statusWindow] setWindowLevel:UIWindowLevelStatusBar]; + + // Restore the stauts bar style if the app is using global status bar management. + [[UIApplication sharedApplication] setStatusBarStyle:self.previousStatusBarStyle]; + + [self dismissViewControllerAnimated:animated completion:completion]; +} + +- (BOOL)wantsWindowToBecomeKey +{ + return self.previousKeyWindow != nil; +} + +#pragma mark - Keyboard Shortcut Helpers + +- (void)toggleSelectTool +{ + if (self.currentMode == FLEXExplorerModeSelect) { + self.currentMode = FLEXExplorerModeDefault; + } else { + self.currentMode = FLEXExplorerModeSelect; + } +} + +- (void)toggleMoveTool +{ + if (self.currentMode == FLEXExplorerModeMove) { + self.currentMode = FLEXExplorerModeDefault; + } else { + self.currentMode = FLEXExplorerModeMove; + } +} + +- (void)toggleViewsTool +{ + BOOL viewsModalShown = [[self presentedViewController] isKindOfClass:[UINavigationController class]]; + viewsModalShown = viewsModalShown && [[[(UINavigationController *)[self presentedViewController] viewControllers] firstObject] isKindOfClass:[FLEXHierarchyTableViewController class]]; + if (viewsModalShown) { + [self resignKeyAndDismissViewControllerAnimated:YES completion:nil]; + } else { + void (^presentBlock)() = ^{ + NSArray *allViews = [self allViewsInHierarchy]; + NSDictionary *depthsForViews = [self hierarchyDepthsForViews:allViews]; + FLEXHierarchyTableViewController *hierarchyTVC = [[FLEXHierarchyTableViewController alloc] initWithViews:allViews viewsAtTap:self.viewsAtTapPoint selectedView:self.selectedView depths:depthsForViews]; + hierarchyTVC.delegate = self; + UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:hierarchyTVC]; + [self makeKeyAndPresentViewController:navigationController animated:YES completion:nil]; + }; + + if (self.presentedViewController) { + [self resignKeyAndDismissViewControllerAnimated:NO completion:presentBlock]; + } else { + presentBlock(); + } + } +} + +- (void)toggleMenuTool +{ + BOOL menuModalShown = [[self presentedViewController] isKindOfClass:[UINavigationController class]]; + menuModalShown = menuModalShown && [[[(UINavigationController *)[self presentedViewController] viewControllers] firstObject] isKindOfClass:[FLEXGlobalsTableViewController class]]; + if (menuModalShown) { + [self resignKeyAndDismissViewControllerAnimated:YES completion:nil]; + } else { + void (^presentBlock)() = ^{ + FLEXGlobalsTableViewController *globalsViewController = [[FLEXGlobalsTableViewController alloc] init]; + globalsViewController.delegate = self; + [FLEXGlobalsTableViewController setApplicationWindow:[[UIApplication sharedApplication] keyWindow]]; + UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:globalsViewController]; + [self makeKeyAndPresentViewController:navigationController animated:YES completion:nil]; + }; + + if (self.presentedViewController) { + [self resignKeyAndDismissViewControllerAnimated:NO completion:presentBlock]; + } else { + presentBlock(); + } + } +} + +- (void)handleDownArrowKeyPressed +{ + if (self.currentMode == FLEXExplorerModeMove) { + CGRect frame = self.selectedView.frame; + frame.origin.y += 1.0 / [[UIScreen mainScreen] scale]; + self.selectedView.frame = frame; + } else if (self.currentMode == FLEXExplorerModeSelect && [self.viewsAtTapPoint count] > 0) { + NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView]; + if (selectedViewIndex > 0) { + self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex - 1]; + } + } +} + +- (void)handleUpArrowKeyPressed +{ + if (self.currentMode == FLEXExplorerModeMove) { + CGRect frame = self.selectedView.frame; + frame.origin.y -= 1.0 / [[UIScreen mainScreen] scale]; + self.selectedView.frame = frame; + } else if (self.currentMode == FLEXExplorerModeSelect && [self.viewsAtTapPoint count] > 0) { + NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView]; + if (selectedViewIndex < [self.viewsAtTapPoint count] - 1) { + self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex + 1]; + } + } +} + +- (void)handleRightArrowKeyPressed +{ + if (self.currentMode == FLEXExplorerModeMove) { + CGRect frame = self.selectedView.frame; + frame.origin.x += 1.0 / [[UIScreen mainScreen] scale]; + self.selectedView.frame = frame; + } +} + +- (void)handleLeftArrowKeyPressed +{ + if (self.currentMode == FLEXExplorerModeMove) { + CGRect frame = self.selectedView.frame; + frame.origin.x -= 1.0 / [[UIScreen mainScreen] scale]; + self.selectedView.frame = frame; + } +} + +@end diff --git a/Pods/FLEX/Classes/ExplorerInterface/FLEXWindow.h b/Pods/FLEX/Classes/ExplorerInterface/FLEXWindow.h new file mode 100644 index 0000000000..8643c630fc --- /dev/null +++ b/Pods/FLEX/Classes/ExplorerInterface/FLEXWindow.h @@ -0,0 +1,24 @@ +// +// FLEXWindow.h +// Flipboard +// +// Created by Ryan Olson on 4/13/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@protocol FLEXWindowEventDelegate; + +@interface FLEXWindow : UIWindow + +@property (nonatomic, weak) id eventDelegate; + +@end + +@protocol FLEXWindowEventDelegate + +- (BOOL)shouldHandleTouchAtPoint:(CGPoint)pointInWindow; +- (BOOL)canBecomeKeyWindow; + +@end diff --git a/Pods/FLEX/Classes/ExplorerInterface/FLEXWindow.m b/Pods/FLEX/Classes/ExplorerInterface/FLEXWindow.m new file mode 100644 index 0000000000..1923a5c80f --- /dev/null +++ b/Pods/FLEX/Classes/ExplorerInterface/FLEXWindow.m @@ -0,0 +1,67 @@ +// +// FLEXWindow.m +// Flipboard +// +// Created by Ryan Olson on 4/13/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXWindow.h" +#import + +@implementation FLEXWindow + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + self.backgroundColor = [UIColor clearColor]; + // Some apps have windows at UIWindowLevelStatusBar + n. + // If we make the window level too high, we block out UIAlertViews. + // There's a balance between staying above the app's windows and staying below alerts. + // UIWindowLevelStatusBar + 100 seems to hit that balance. + self.windowLevel = UIWindowLevelStatusBar + 100.0; + } + return self; +} + +- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event +{ + BOOL pointInside = NO; + if ([self.eventDelegate shouldHandleTouchAtPoint:point]) { + pointInside = [super pointInside:point withEvent:event]; + } + return pointInside; +} + +- (BOOL)shouldAffectStatusBarAppearance +{ + return [self isKeyWindow]; +} + +- (BOOL)canBecomeKeyWindow +{ + return [self.eventDelegate canBecomeKeyWindow]; +} + ++ (void)initialize +{ + // This adds a method (superclass override) at runtime which gives us the status bar behavior we want. + // The FLEX window is intended to be an overlay that generally doesn't affect the app underneath. + // Most of the time, we want the app's main window(s) to be in control of status bar behavior. + // Done at runtime with an obfuscated selector because it is private API. But you shoudn't ship this to the App Store anyways... + NSString *canAffectSelectorString = [@[@"_can", @"Affect", @"Status", @"Bar", @"Appearance"] componentsJoinedByString:@""]; + SEL canAffectSelector = NSSelectorFromString(canAffectSelectorString); + Method shouldAffectMethod = class_getInstanceMethod(self, @selector(shouldAffectStatusBarAppearance)); + IMP canAffectImplementation = method_getImplementation(shouldAffectMethod); + class_addMethod(self, canAffectSelector, canAffectImplementation, method_getTypeEncoding(shouldAffectMethod)); + + // One more... + NSString *canBecomeKeySelectorString = [NSString stringWithFormat:@"_%@", NSStringFromSelector(@selector(canBecomeKeyWindow))]; + SEL canBecomeKeySelector = NSSelectorFromString(canBecomeKeySelectorString); + Method canBecomeKeyMethod = class_getInstanceMethod(self, @selector(canBecomeKeyWindow)); + IMP canBecomeKeyImplementation = method_getImplementation(canBecomeKeyMethod); + class_addMethod(self, canBecomeKeySelector, canBecomeKeyImplementation, method_getTypeEncoding(canBecomeKeyMethod)); +} + +@end diff --git a/Pods/FLEX/Classes/FLEX.h b/Pods/FLEX/Classes/FLEX.h new file mode 100644 index 0000000000..bb6cd2f14e --- /dev/null +++ b/Pods/FLEX/Classes/FLEX.h @@ -0,0 +1,9 @@ +// +// FLEX.h +// FLEX +// +// Created by Eric Horacek on 7/18/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import diff --git a/Pods/FLEX/Classes/FLEXManager.h b/Pods/FLEX/Classes/FLEXManager.h new file mode 100644 index 0000000000..613c341dd2 --- /dev/null +++ b/Pods/FLEX/Classes/FLEXManager.h @@ -0,0 +1,70 @@ +// +// FLEXManager.h +// Flipboard +// +// Created by Ryan Olson on 4/4/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import +#import + +@interface FLEXManager : NSObject + ++ (instancetype)sharedManager; + +@property (nonatomic, readonly) BOOL isHidden; + +- (void)showExplorer; +- (void)hideExplorer; +- (void)toggleExplorer; + +#pragma mark - Network Debugging + +/// If this property is set to YES, FLEX will swizzle NSURLConnection*Delegate and NSURLSession*Delegate methods +/// on classes that conform to the protocols. This allows you to view network activity history from the main FLEX menu. +/// Full responses are kept temporarily in a size-limited cache and may be pruned under memory pressure. +@property (nonatomic, assign, getter=isNetworkDebuggingEnabled) BOOL networkDebuggingEnabled; + +/// Defaults to 25 MB if never set. Values set here are presisted across launches of the app. +/// The response cache uses an NSCache, so it may purge prior to hitting the limit when the app is under memory pressure. +@property (nonatomic, assign) NSUInteger networkResponseCacheByteLimit; + +#pragma mark - Keyboard Shortcuts + +/// Simulator keyboard shortcuts are enabled by default. +/// The shortcuts will not fire when there is an active text field, text view, or other responder accepting key input. +/// You can disable keyboard shortcuts if you have existing keyboard shortcuts that conflict with FLEX, or if you like doing things the hard way ;) +/// Keyboard shortcuts are always disabled (and support is compiled out) in non-simulator builds +@property (nonatomic, assign) BOOL simulatorShortcutsEnabled; + +/// Adds an action to run when the specified key & modifier combination is pressed +/// @param key A single character string matching a key on the keyboard +/// @param modifiers Modifier keys such as shift, command, or alt/option +/// @param action The block to run on the main thread when the key & modifier combination is recognized. +/// @param description Shown the the keyboard shortcut help menu, which is accessed via the '?' key. +/// @note The action block will be retained for the duration of the application. You may want to use weak references. +/// @note FLEX registers several default keyboard shortcuts. Use the '?' key to see a list of shortcuts. +- (void)registerSimulatorShortcutWithKey:(NSString *)key modifiers:(UIKeyModifierFlags)modifiers action:(dispatch_block_t)action description:(NSString *)description; + +#pragma mark - Extensions + +/// Adds an entry at the bottom of the list of Global State items. Call this method before this view controller is displayed. +/// @param entryName The string to be displayed in the cell. +/// @param objectFutureBlock When you tap on the row, information about the object returned by this block will be displayed. +/// Passing a block that returns an object allows you to display information about an object whose actual pointer may change at runtime (e.g. +currentUser) +/// @note This method must be called from the main thread. +/// The objectFutureBlock will be invoked from the main thread and may return nil. +/// @note The passed block will be copied and retain for the duration of the application, you may want to use __weak references. +- (void)registerGlobalEntryWithName:(NSString *)entryName objectFutureBlock:(id (^)(void))objectFutureBlock; + +/// Adds an entry at the bottom of the list of Global State items. Call this method before this view controller is displayed. +/// @param entryName The string to be displayed in the cell. +/// @param viewControllerFutureBlock When you tap on the row, view controller returned by this block will be pushed on the navigation controller stack. +/// @note This method must be called from the main thread. +/// The viewControllerFutureBlock will be invoked from the main thread and may not return nil. +/// @note The passed block will be copied and retain for the duration of the application, you may want to use __weak references. +- (void)registerGlobalEntryWithName:(NSString *)entryName + viewControllerFutureBlock:(UIViewController * (^)(void))viewControllerFutureBlock; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXDatabaseManager.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXDatabaseManager.h new file mode 100644 index 0000000000..20de90e24b --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXDatabaseManager.h @@ -0,0 +1,26 @@ +// +// PTDatabaseManager.h +// Derived from: +// +// FMDatabase.h +// FMDB( https://github.com/ccgus/fmdb ) +// +// Created by Peng Tao on 15/11/23. +// +// Licensed to Flying Meat Inc. under one or more contributor license agreements. +// See the LICENSE file distributed with this work for the terms under +// which Flying Meat Inc. licenses this file to you. + +#import + +@protocol FLEXDatabaseManager + +@required +- (instancetype)initWithPath:(NSString*)path; + +- (BOOL)open; +- (NSArray *)queryAllTables; +- (NSArray *)queryAllColumnsWithTableName:(NSString *)tableName; +- (NSArray *)queryAllDataWithTableName:(NSString *)tableName; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXMultiColumnTableView.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXMultiColumnTableView.h new file mode 100644 index 0000000000..fca6cc874c --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXMultiColumnTableView.h @@ -0,0 +1,48 @@ +// +// PTMultiColumnTableView.h +// PTMultiColumnTableViewDemo +// +// Created by Peng Tao on 15/11/16. +// Copyright © 2015年 Peng Tao. All rights reserved. +// + +#import +#import "FLEXTableColumnHeader.h" + +@class FLEXMultiColumnTableView; + +@protocol FLEXMultiColumnTableViewDelegate + +@required +- (void)multiColumnTableView:(FLEXMultiColumnTableView *)tableView didTapLabelWithText:(NSString *)text; +- (void)multiColumnTableView:(FLEXMultiColumnTableView *)tableView didTapHeaderWithText:(NSString *)text sortType:(FLEXTableColumnHeaderSortType)sortType; + +@end + +@protocol FLEXMultiColumnTableViewDataSource + +@required + +- (NSInteger)numberOfColumnsInTableView:(FLEXMultiColumnTableView *)tableView; +- (NSInteger)numberOfRowsInTableView:(FLEXMultiColumnTableView *)tableView; +- (NSString *)columnNameInColumn:(NSInteger)column; +- (NSString *)rowNameInRow:(NSInteger)row; +- (NSString *)contentAtColumn:(NSInteger)column row:(NSInteger)row; +- (NSArray *)contentAtRow:(NSInteger)row; + +- (CGFloat)multiColumnTableView:(FLEXMultiColumnTableView *)tableView widthForContentCellInColumn:(NSInteger)column; +- (CGFloat)multiColumnTableView:(FLEXMultiColumnTableView *)tableView heightForContentCellInRow:(NSInteger)row; +- (CGFloat)heightForTopHeaderInTableView:(FLEXMultiColumnTableView *)tableView; +- (CGFloat)widthForLeftHeaderInTableView:(FLEXMultiColumnTableView *)tableView; + +@end + + +@interface FLEXMultiColumnTableView : UIView + +@property (nonatomic, weak) iddataSource; +@property (nonatomic, weak) iddelegate; + +- (void)reloadData; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXMultiColumnTableView.m b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXMultiColumnTableView.m new file mode 100644 index 0000000000..916791429b --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXMultiColumnTableView.m @@ -0,0 +1,341 @@ +// +// PTMultiColumnTableView.m +// PTMultiColumnTableViewDemo +// +// Created by Peng Tao on 15/11/16. +// Copyright © 2015年 Peng Tao. All rights reserved. +// + +#import "FLEXMultiColumnTableView.h" +#import "FLEXTableContentCell.h" +#import "FLEXTableLeftCell.h" + +@interface FLEXMultiColumnTableView () + + +@property (nonatomic, strong) UIScrollView *contentScrollView; +@property (nonatomic, strong) UIScrollView *headerScrollView; +@property (nonatomic, strong) UITableView *leftTableView; +@property (nonatomic, strong) UITableView *contentTableView; +@property (nonatomic, strong) UIView *leftHeader; + +@property (nonatomic, strong) NSDictionary *sortStatusDict; +@property (nonatomic, strong) NSArray *rowData; +@end + +static const CGFloat kColumnMargin = 1; + +@implementation FLEXMultiColumnTableView + + +- (instancetype)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + [self loadUI]; + } + return self; +} + +- (void)didMoveToSuperview +{ + [super didMoveToSuperview]; + [self reloadData]; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + CGFloat width = self.frame.size.width; + CGFloat height = self.frame.size.height; + CGFloat topheaderHeight = [self topHeaderHeight]; + CGFloat leftHeaderWidth = [self leftHeaderWidth]; + + CGFloat contentWidth = 0.0; + NSInteger rowsCount = [self numberOfColumns]; + for (int i = 0; i < rowsCount; i++) { + contentWidth += [self contentWidthForColumn:i]; + } + + self.leftTableView.frame = CGRectMake(0, topheaderHeight, leftHeaderWidth, height - topheaderHeight); + self.headerScrollView.frame = CGRectMake(leftHeaderWidth, 0, width - leftHeaderWidth, topheaderHeight); + self.headerScrollView.contentSize = CGSizeMake( self.contentTableView.frame.size.width, self.headerScrollView.frame.size.height); + self.contentTableView.frame = CGRectMake(0, 0, contentWidth + [self numberOfColumns] * [self columnMargin] , height - topheaderHeight); + self.contentScrollView.frame = CGRectMake(leftHeaderWidth, topheaderHeight, width - leftHeaderWidth, height - topheaderHeight); + self.contentScrollView.contentSize = self.contentTableView.frame.size; + self.leftHeader.frame = CGRectMake(0, 0, [self leftHeaderWidth], [self topHeaderHeight]); +} + + +- (void)loadUI +{ + [self loadHeaderScrollView]; + [self loadContentScrollView]; + [self loadLeftView]; +} + +- (void)reloadData +{ + [self loadLeftViewData]; + [self loadContentData]; + [self loadHeaderData]; +} + +#pragma mark - UI + +- (void)loadHeaderScrollView +{ + UIScrollView *headerScrollView = [[UIScrollView alloc] init]; + headerScrollView.delegate = self; + self.headerScrollView = headerScrollView; + self.headerScrollView.backgroundColor = [UIColor colorWithWhite:0.803 alpha:0.850]; + + [self addSubview:headerScrollView]; +} + +- (void)loadContentScrollView +{ + + UIScrollView *scrollView = [[UIScrollView alloc] init]; + scrollView.bounces = NO; + scrollView.delegate = self; + + UITableView *tableView = [[UITableView alloc] init]; + tableView.delegate = self; + tableView.dataSource = self; + tableView.separatorStyle = UITableViewCellSeparatorStyleNone; + + [self addSubview:scrollView]; + [scrollView addSubview:tableView]; + + self.contentScrollView = scrollView; + self.contentTableView = tableView; + +} + +- (void)loadLeftView +{ + UITableView *leftTableView = [[UITableView alloc] init]; + leftTableView.delegate = self; + leftTableView.dataSource = self; + leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone; + self.leftTableView = leftTableView; + [self addSubview:leftTableView]; + + UIView *leftHeader = [[UIView alloc] init]; + leftHeader.backgroundColor = [UIColor colorWithWhite:0.950 alpha:0.668]; + self.leftHeader = leftHeader; + [self addSubview:leftHeader]; + +} + + +#pragma mark - Data + +- (void)loadHeaderData +{ + NSArray *subviews = self.headerScrollView.subviews; + + for (UIView *subview in subviews) { + [subview removeFromSuperview]; + } + CGFloat x = 0.0; + CGFloat w = 0.0; + for (int i = 0; i < [self numberOfColumns] ; i++) { + w = [self contentWidthForColumn:i] + [self columnMargin]; + + FLEXTableColumnHeader *cell = [[FLEXTableColumnHeader alloc] initWithFrame:CGRectMake(x, 0, w, [self topHeaderHeight] - 1)]; + cell.label.text = [self columnTitleForColumn:i]; + [self.headerScrollView addSubview:cell]; + + FLEXTableColumnHeaderSortType type = [self.sortStatusDict[[self columnTitleForColumn:i]] integerValue]; + [cell changeSortStatusWithType:type]; + + UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self + action:@selector(contentHeaderTap:)]; + [cell addGestureRecognizer:gesture]; + cell.userInteractionEnabled = YES; + + x = x + w; + } +} + +- (void)contentHeaderTap:(UIGestureRecognizer *)gesture +{ + FLEXTableColumnHeader *header = (FLEXTableColumnHeader *)gesture.view; + NSString *string = header.label.text; + FLEXTableColumnHeaderSortType currentType = [self.sortStatusDict[string] integerValue]; + FLEXTableColumnHeaderSortType newType ; + + switch (currentType) { + case FLEXTableColumnHeaderSortTypeNone: + newType = FLEXTableColumnHeaderSortTypeAsc; + break; + case FLEXTableColumnHeaderSortTypeAsc: + newType = FLEXTableColumnHeaderSortTypeDesc; + break; + case FLEXTableColumnHeaderSortTypeDesc: + newType = FLEXTableColumnHeaderSortTypeAsc; + break; + } + + self.sortStatusDict = @{header.label.text : @(newType)}; + [header changeSortStatusWithType:newType]; + [self.delegate multiColumnTableView:self didTapHeaderWithText:string sortType:newType]; + +} + +- (void)loadContentData +{ + [self.contentTableView reloadData]; +} + +- (void)loadLeftViewData +{ + [self.leftTableView reloadData]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView + cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + UIColor *backgroundColor = [UIColor whiteColor]; + if (indexPath.row % 2 != 0) { + backgroundColor = [UIColor colorWithWhite:0.950 alpha:0.750]; + } + + if (tableView != self.leftTableView) { + self.rowData = [self.dataSource contentAtRow:indexPath.row]; + FLEXTableContentCell *cell = [FLEXTableContentCell cellWithTableView:tableView + columnNumber:[self numberOfColumns]]; + cell.contentView.backgroundColor = backgroundColor; + cell.delegate = self; + + for (int i = 0 ; i < cell.labels.count; i++) { + + UILabel *label = cell.labels[i]; + label.textColor = [UIColor blackColor]; + + NSString *content = [NSString stringWithFormat:@"%@",self.rowData[i]]; + if ([content isEqualToString:@""]) { + label.textColor = [UIColor lightGrayColor]; + content = @"NULL"; + } + label.text = content; + label.backgroundColor = backgroundColor; + } + return cell; + } + else { + FLEXTableLeftCell *cell = [FLEXTableLeftCell cellWithTableView:tableView]; + cell.contentView.backgroundColor = backgroundColor; + cell.titlelabel.text = [self rowTitleForRow:indexPath.row]; + return cell; + } +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return [self.dataSource numberOfRowsInTableView:self]; +} + + +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath +{ + return [self.dataSource multiColumnTableView:self heightForContentCellInRow:indexPath.row]; +} + + +- (void)scrollViewDidScroll:(UIScrollView *)scrollView +{ + if (scrollView == self.contentScrollView) { + self.headerScrollView.contentOffset = scrollView.contentOffset; + } + else if (scrollView == self.headerScrollView) { + self.contentScrollView.contentOffset = scrollView.contentOffset; + } + else if (scrollView == self.leftTableView) { + self.contentTableView.contentOffset = scrollView.contentOffset; + } + else if (scrollView == self.contentTableView) { + self.leftTableView.contentOffset = scrollView.contentOffset; + } +} + +#pragma mark - +#pragma mark UITableView Delegate + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + if (tableView == self.leftTableView) { + [self.contentTableView selectRowAtIndexPath:indexPath + animated:NO + scrollPosition:UITableViewScrollPositionNone]; + } + else if (tableView == self.contentTableView) { + [self.leftTableView selectRowAtIndexPath:indexPath + animated:NO + scrollPosition:UITableViewScrollPositionNone]; + } +} + +#pragma mark - +#pragma mark DataSource Accessor + +- (NSInteger)numberOfrows +{ + return [self.dataSource numberOfRowsInTableView:self]; +} + +- (NSInteger)numberOfColumns +{ + return [self.dataSource numberOfColumnsInTableView:self]; +} + +- (NSString *)columnTitleForColumn:(NSInteger)column +{ + return [self.dataSource columnNameInColumn:column]; +} + +- (NSString *)rowTitleForRow:(NSInteger)row +{ + return [self.dataSource rowNameInRow:row]; +} + +- (NSString *)contentAtColumn:(NSInteger)column row:(NSInteger)row; +{ + return [self.dataSource contentAtColumn:column row:row]; +} + +- (CGFloat)contentWidthForColumn:(NSInteger)column +{ + return [self.dataSource multiColumnTableView:self widthForContentCellInColumn:column]; +} + +- (CGFloat)contentHeightForRow:(NSInteger)row +{ + return [self.dataSource multiColumnTableView:self heightForContentCellInRow:row]; +} + +- (CGFloat)topHeaderHeight +{ + return [self.dataSource heightForTopHeaderInTableView:self]; +} + +- (CGFloat)leftHeaderWidth +{ + return [self.dataSource widthForLeftHeaderInTableView:self]; +} + +- (CGFloat)columnMargin +{ + return kColumnMargin; +} + + +- (void)tableContentCell:(FLEXTableContentCell *)tableView labelDidTapWithText:(NSString *)text +{ + [self.delegate multiColumnTableView:self didTapLabelWithText:text]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXRealmDatabaseManager.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXRealmDatabaseManager.h new file mode 100644 index 0000000000..44c78fb3e2 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXRealmDatabaseManager.h @@ -0,0 +1,14 @@ +// +// FLEXRealmDatabaseManager.h +// FLEX +// +// Created by Tim Oliver on 28/01/2016. +// Copyright © 2016 Realm. All rights reserved. +// + +#import +#import "FLEXDatabaseManager.h" + +@interface FLEXRealmDatabaseManager : NSObject + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXRealmDatabaseManager.m b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXRealmDatabaseManager.m new file mode 100644 index 0000000000..f239a4192c --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXRealmDatabaseManager.m @@ -0,0 +1,114 @@ +// +// FLEXRealmDatabaseManager.m +// FLEX +// +// Created by Tim Oliver on 28/01/2016. +// Copyright © 2016 Realm. All rights reserved. +// + +#import "FLEXRealmDatabaseManager.h" + +#if __has_include() +#import +#import +#else +#import "FLEXRealmDefines.h" +#endif + +@interface FLEXRealmDatabaseManager () + +@property (nonatomic, copy) NSString *path; +@property (nonatomic, strong) id realm; + +@end + +//#endif + +@implementation FLEXRealmDatabaseManager + +- (instancetype)initWithPath:(NSString*)aPath +{ + Class realmClass = NSClassFromString(@"RLMRealm"); + if (realmClass == nil) { + return nil; + } + + self = [super init]; + + if (self) { + _path = aPath; + } + return self; +} + +- (BOOL)open +{ + Class realmClass = NSClassFromString(@"RLMRealm"); + Class configurationClass = NSClassFromString(@"RLMRealmConfiguration"); + + if (realmClass == nil || configurationClass == nil) { + return NO; + } + + NSError *error = nil; + id configuration = [[configurationClass alloc] init]; + [(RLMRealmConfiguration *)configuration setFileURL:[NSURL fileURLWithPath:self.path]]; + self.realm = [realmClass realmWithConfiguration:configuration error:&error]; + return (error == nil); +} + +- (NSArray *)queryAllTables +{ + NSMutableArray *allTables = [NSMutableArray array]; + RLMSchema *schema = [self.realm schema]; + + for (RLMObjectSchema *objectSchema in schema.objectSchema) { + if (objectSchema.className == nil) { + continue; + } + + NSDictionary *dictionary = @{@"name":objectSchema.className}; + [allTables addObject:dictionary]; + } + + return allTables; +} + +- (NSArray *)queryAllColumnsWithTableName:(NSString *)tableName +{ + RLMObjectSchema *objectSchema = [[self.realm schema] schemaForClassName:tableName]; + if (objectSchema == nil) { + return nil; + } + + NSMutableArray *columnNames = [NSMutableArray array]; + for (RLMProperty *property in objectSchema.properties) { + [columnNames addObject:property.name]; + } + + return columnNames; +} + +- (NSArray *)queryAllDataWithTableName:(NSString *)tableName +{ + RLMObjectSchema *objectSchema = [[self.realm schema] schemaForClassName:tableName]; + RLMResults *results = [self.realm allObjects:tableName]; + if (results.count == 0 || objectSchema == nil) { + return nil; + } + + NSMutableArray *allDataEntries = [NSMutableArray array]; + for (RLMObject *result in results) { + NSMutableDictionary *entry = [NSMutableDictionary dictionary]; + for (RLMProperty *property in objectSchema.properties) { + id value = [result valueForKey:property.name]; + entry[property.name] = (value) ? (value) : [NSNull null]; + } + + [allDataEntries addObject:entry]; + } + + return allDataEntries; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXRealmDefines.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXRealmDefines.h new file mode 100644 index 0000000000..2afbaab8e8 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXRealmDefines.h @@ -0,0 +1,46 @@ +// +// Realm.h +// FLEX +// +// Created by Tim Oliver on 16/02/2016. +// Copyright © 2016 Realm. All rights reserved. +// + +#if __has_include() +#else + +@class RLMObject, RLMResults, RLMRealm, RLMRealmConfiguration, RLMSchema, RLMObjectSchema, RLMProperty; + +@interface RLMRealmConfiguration : NSObject +@property (nonatomic, copy) NSURL *fileURL; +@end + +@interface RLMRealm : NSObject +@property (nonatomic, readonly) RLMSchema *schema; ++ (RLMRealm *)realmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error; +- (RLMResults *)allObjects:(NSString *)className; +@end + +@interface RLMSchema : NSObject +@property (nonatomic, readonly) NSArray *objectSchema; +- (RLMObjectSchema *)schemaForClassName:(NSString *)className; +@end + +@interface RLMObjectSchema : NSObject +@property (nonatomic, readonly) NSString *className; +@property (nonatomic, readonly) NSArray *properties; +@end + +@interface RLMProperty : NSString +@property (nonatomic, readonly) NSString *name; +@end + +@interface RLMResults : NSObject +@property (nonatomic, readonly) NSInteger count; +@end + +@interface RLMObject : NSObject + +@end + +#endif \ No newline at end of file diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXSQLiteDatabaseManager.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXSQLiteDatabaseManager.h new file mode 100644 index 0000000000..9ab461bbaa --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXSQLiteDatabaseManager.h @@ -0,0 +1,19 @@ +// +// PTDatabaseManager.h +// Derived from: +// +// FMDatabase.h +// FMDB( https://github.com/ccgus/fmdb ) +// +// Created by Peng Tao on 15/11/23. +// +// Licensed to Flying Meat Inc. under one or more contributor license agreements. +// See the LICENSE file distributed with this work for the terms under +// which Flying Meat Inc. licenses this file to you. + +#import +#import "FLEXDatabaseManager.h" + +@interface FLEXSQLiteDatabaseManager : NSObject + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXSQLiteDatabaseManager.m b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXSQLiteDatabaseManager.m new file mode 100644 index 0000000000..2ddbce125f --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXSQLiteDatabaseManager.m @@ -0,0 +1,190 @@ +// +// PTDatabaseManager.m +// PTDatabaseReader +// +// Created by Peng Tao on 15/11/23. +// Copyright © 2015年 Peng Tao. All rights reserved. +// + +#import "FLEXSQLiteDatabaseManager.h" +#import + + +static NSString *const QUERY_TABLENAMES_SQL = @"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"; + +@implementation FLEXSQLiteDatabaseManager +{ + sqlite3* _db; + NSString* _databasePath; +} + +- (instancetype)initWithPath:(NSString*)aPath +{ + self = [super init]; + + if (self) { + _databasePath = [aPath copy]; + } + return self; +} + +- (BOOL)open { + if (_db) { + return YES; + } + int err = sqlite3_open([_databasePath UTF8String], &_db); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + return YES; +} + +- (BOOL)close { + if (!_db) { + return YES; + } + + int rc; + BOOL retry; + BOOL triedFinalizingOpenStatements = NO; + + do { + retry = NO; + rc = sqlite3_close(_db); + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { + if (!triedFinalizingOpenStatements) { + triedFinalizingOpenStatements = YES; + sqlite3_stmt *pStmt; + while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) { + NSLog(@"Closing leaked statement"); + sqlite3_finalize(pStmt); + retry = YES; + } + } + } + else if (SQLITE_OK != rc) { + NSLog(@"error closing!: %d", rc); + } + } + while (retry); + + _db = nil; + return YES; +} + + +- (NSArray *)queryAllTables +{ + return [self executeQuery:QUERY_TABLENAMES_SQL]; +} + +- (NSArray *)queryAllColumnsWithTableName:(NSString *)tableName +{ + NSString *sql = [NSString stringWithFormat:@"PRAGMA table_info('%@')",tableName]; + NSArray *resultArray = [self executeQuery:sql]; + NSMutableArray *array = [NSMutableArray array]; + for (NSDictionary *dict in resultArray) { + [array addObject:dict[@"name"]]; + } + return array; +} + +- (NSArray *)queryAllDataWithTableName:(NSString *)tableName +{ + NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@",tableName]; + return [self executeQuery:sql]; +} + +#pragma mark - +#pragma mark - Private + +- (NSArray *)executeQuery:(NSString *)sql +{ + [self open]; + NSMutableArray *resultArray = [NSMutableArray array]; + sqlite3_stmt *pstmt; + if (sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pstmt, 0) == SQLITE_OK) { + while (sqlite3_step(pstmt) == SQLITE_ROW) { + NSUInteger num_cols = (NSUInteger)sqlite3_data_count(pstmt); + if (num_cols > 0) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; + + int columnCount = sqlite3_column_count(pstmt); + + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + + NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name(pstmt, columnIdx)]; + id objectValue = [self objectForColumnIndex:columnIdx stmt:pstmt]; + [dict setObject:objectValue forKey:columnName]; + } + [resultArray addObject:dict]; + } + } + } + [self close]; + return resultArray; +} + + +- (id)objectForColumnIndex:(int)columnIdx stmt:(sqlite3_stmt*)stmt { + int columnType = sqlite3_column_type(stmt, columnIdx); + + id returnValue = nil; + + if (columnType == SQLITE_INTEGER) { + returnValue = [NSNumber numberWithLongLong:sqlite3_column_int64(stmt, columnIdx)]; + } + else if (columnType == SQLITE_FLOAT) { + returnValue = [NSNumber numberWithDouble:sqlite3_column_double(stmt, columnIdx)]; + } + else if (columnType == SQLITE_BLOB) { + returnValue = [self dataForColumnIndex:columnIdx stmt:stmt]; + } + else { + //default to a string for everything else + returnValue = [self stringForColumnIndex:columnIdx stmt:stmt]; + } + + if (returnValue == nil) { + returnValue = [NSNull null]; + } + + return returnValue; +} + +- (NSString *)stringForColumnIndex:(int)columnIdx stmt:(sqlite3_stmt *)stmt { + + if (sqlite3_column_type(stmt, columnIdx) == SQLITE_NULL || (columnIdx < 0)) { + return nil; + } + + const char *c = (const char *)sqlite3_column_text(stmt, columnIdx); + + if (!c) { + // null row. + return nil; + } + + return [NSString stringWithUTF8String:c]; +} + +- (NSData *)dataForColumnIndex:(int)columnIdx stmt:(sqlite3_stmt *)stmt{ + + if (sqlite3_column_type(stmt, columnIdx) == SQLITE_NULL || (columnIdx < 0)) { + return nil; + } + + const char *dataBuffer = sqlite3_column_blob(stmt, columnIdx); + int dataSize = sqlite3_column_bytes(stmt, columnIdx); + + if (dataBuffer == NULL) { + return nil; + } + + return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize]; +} + + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableColumnHeader.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableColumnHeader.h new file mode 100644 index 0000000000..bded1e26cf --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableColumnHeader.h @@ -0,0 +1,24 @@ +// +// FLEXTableContentHeaderCell.h +// UICatalog +// +// Created by Peng Tao on 15/11/26. +// Copyright © 2015年 f. All rights reserved. +// + +#import + +typedef NS_ENUM(NSUInteger, FLEXTableColumnHeaderSortType) { + FLEXTableColumnHeaderSortTypeNone = 0, + FLEXTableColumnHeaderSortTypeAsc, + FLEXTableColumnHeaderSortTypeDesc, +}; + +@interface FLEXTableColumnHeader : UIView + +@property (nonatomic, strong) UILabel *label; + +- (void)changeSortStatusWithType:(FLEXTableColumnHeaderSortType)type; + +@end + diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableColumnHeader.m b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableColumnHeader.m new file mode 100644 index 0000000000..591cdd9b6b --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableColumnHeader.m @@ -0,0 +1,60 @@ +// +// FLEXTableContentHeaderCell.m +// UICatalog +// +// Created by Peng Tao on 15/11/26. +// Copyright © 2015年 f. All rights reserved. +// + +#import "FLEXTableColumnHeader.h" + +@implementation FLEXTableColumnHeader +{ + UILabel *_arrowLabel; +} + + +- (instancetype)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + self.backgroundColor = [UIColor whiteColor]; + + UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, frame.size.width - 25, frame.size.height)]; + label.font = [UIFont systemFontOfSize:13.0]; + [self addSubview:label]; + self.label = label; + + + _arrowLabel = [[UILabel alloc] initWithFrame:CGRectMake(frame.size.width - 20, 0, 20, frame.size.height)]; + _arrowLabel.font = [UIFont systemFontOfSize:13.0]; + [self addSubview:_arrowLabel]; + + UIView *line = [[UIView alloc] initWithFrame:CGRectMake(frame.size.width - 1, 2, 1, frame.size.height - 4)]; + line.backgroundColor = [UIColor colorWithWhite:0.803 alpha:0.850]; + [self addSubview:line]; + + } + return self; +} + +- (void)changeSortStatusWithType:(FLEXTableColumnHeaderSortType)type +{ + switch (type) { + case FLEXTableColumnHeaderSortTypeNone: + _arrowLabel.text = @""; + break; + case FLEXTableColumnHeaderSortTypeAsc: + _arrowLabel.text = @"⬆️"; + break; + case FLEXTableColumnHeaderSortTypeDesc: + _arrowLabel.text = @"⬇️"; + break; + } +} + + + + + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentCell.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentCell.h new file mode 100644 index 0000000000..b95a28c60e --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentCell.h @@ -0,0 +1,27 @@ +// +// FLEXTableContentCell.h +// UICatalog +// +// Created by Peng Tao on 15/11/24. +// Copyright © 2015年 f. All rights reserved. +// + +#import + +@class FLEXTableContentCell; +@protocol FLEXTableContentCellDelegate + +@optional +- (void)tableContentCell:(FLEXTableContentCell *)tableView labelDidTapWithText:(NSString *)text; + +@end + +@interface FLEXTableContentCell : UITableViewCell + +@property (nonatomic, strong)NSArray *labels; + +@property (nonatomic, weak) iddelegate; + ++ (instancetype)cellWithTableView:(UITableView *)tableView columnNumber:(NSInteger)number; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentCell.m b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentCell.m new file mode 100644 index 0000000000..b3aaaaf9d8 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentCell.m @@ -0,0 +1,66 @@ +// +// FLEXTableContentCell.m +// UICatalog +// +// Created by Peng Tao on 15/11/24. +// Copyright © 2015年 f. All rights reserved. +// + +#import "FLEXTableContentCell.h" +#import "FLEXMultiColumnTableView.h" + +@interface FLEXTableContentCell () + +@end + +@implementation FLEXTableContentCell + ++ (instancetype)cellWithTableView:(UITableView *)tableView columnNumber:(NSInteger)number; +{ + static NSString *identifier = @"FLEXTableContentCell"; + FLEXTableContentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; + if (!cell) { + cell = [[FLEXTableContentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; + NSMutableArray *labels = [NSMutableArray array]; + for (int i = 0; i < number ; i++) { + UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero]; + label.backgroundColor = [UIColor whiteColor]; + label.font = [UIFont systemFontOfSize:13.0]; + label.textAlignment = NSTextAlignmentLeft; + label.backgroundColor = [UIColor greenColor]; + [labels addObject:label]; + + UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:cell + action:@selector(labelDidTap:)]; + [label addGestureRecognizer:gesture]; + label.userInteractionEnabled = YES; + + [cell.contentView addSubview:label]; + cell.contentView.backgroundColor = [UIColor whiteColor]; + } + cell.labels = labels; + } + return cell; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + CGFloat labelWidth = self.contentView.frame.size.width / self.labels.count; + CGFloat labelHeight = self.contentView.frame.size.height; + for (int i = 0; i < self.labels.count; i++) { + UILabel *label = self.labels[i]; + label.frame = CGRectMake(labelWidth * i + 5, 0, (labelWidth - 10), labelHeight); + } +} + + +- (void)labelDidTap:(UIGestureRecognizer *)gesture +{ + UILabel *label = (UILabel *)gesture.view; + if ([self.delegate respondsToSelector:@selector(tableContentCell:labelDidTapWithText:)]) { + [self.delegate tableContentCell:self labelDidTapWithText:label.text]; + } +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentViewController.h new file mode 100644 index 0000000000..9bb481c10b --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentViewController.h @@ -0,0 +1,16 @@ +// +// PTTableContentViewController.h +// PTDatabaseReader +// +// Created by Peng Tao on 15/11/23. +// Copyright © 2015年 Peng Tao. All rights reserved. +// + +#import + +@interface FLEXTableContentViewController : UIViewController + +@property (nonatomic, strong) NSArray *columnsArray; +@property (nonatomic, strong) NSArray *contentsArray; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentViewController.m new file mode 100644 index 0000000000..5651a0a8ae --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableContentViewController.m @@ -0,0 +1,184 @@ +// +// PTTableContentViewController.m +// PTDatabaseReader +// +// Created by Peng Tao on 15/11/23. +// Copyright © 2015年 Peng Tao. All rights reserved. +// + +#import "FLEXTableContentViewController.h" +#import "FLEXMultiColumnTableView.h" +#import "FLEXWebViewController.h" + + +@interface FLEXTableContentViewController () + +@property (nonatomic, strong)FLEXMultiColumnTableView *multiColumView; + +@end + +@implementation FLEXTableContentViewController + +- (instancetype)init +{ + self = [super init]; + if (self) { + + CGRect rectStatus = [UIApplication sharedApplication].statusBarFrame; + CGFloat y = 64; + if (rectStatus.size.height == 0) { + y = 32; + } + _multiColumView = [[FLEXMultiColumnTableView alloc] initWithFrame: + CGRectMake(0, y, self.view.frame.size.width, self.view.frame.size.height - y)]; + + _multiColumView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + _multiColumView.backgroundColor = [UIColor whiteColor]; + _multiColumView.dataSource = self; + _multiColumView.delegate = self; + self.automaticallyAdjustsScrollViewInsets = NO; + + + [self.view addSubview:_multiColumView]; + } + return self; +} + +- (void)viewWillAppear:(BOOL)animated +{ + [super viewWillAppear:animated]; + [self.multiColumView reloadData]; + +} + +#pragma mark - +#pragma mark MultiColumnTableView DataSource + +- (NSInteger)numberOfColumnsInTableView:(FLEXMultiColumnTableView *)tableView +{ + return self.columnsArray.count; +} +- (NSInteger)numberOfRowsInTableView:(FLEXMultiColumnTableView *)tableView +{ + return self.contentsArray.count; +} + + +- (NSString *)columnNameInColumn:(NSInteger)column +{ + return self.columnsArray[column]; +} + + +- (NSString *)rowNameInRow:(NSInteger)row +{ + return [NSString stringWithFormat:@"%ld",(long)row]; +} + +- (NSString *)contentAtColumn:(NSInteger)column row:(NSInteger)row +{ + if (self.contentsArray.count > row) { + NSDictionary *dic = self.contentsArray[row]; + if (self.contentsArray.count > column) { + return [NSString stringWithFormat:@"%@",[dic objectForKey:self.columnsArray[column]]]; + } + } + return @""; +} + +- (NSArray *)contentAtRow:(NSInteger)row +{ + NSMutableArray *result = [NSMutableArray array]; + if (self.contentsArray.count > row) { + NSDictionary *dic = self.contentsArray[row]; + for (int i = 0; i < self.columnsArray.count; i ++) { + [result addObject:dic[self.columnsArray[i]]]; + } + return result; + } + return nil; +} + +- (CGFloat)multiColumnTableView:(FLEXMultiColumnTableView *)tableView + heightForContentCellInRow:(NSInteger)row +{ + return 40; +} + +- (CGFloat)multiColumnTableView:(FLEXMultiColumnTableView *)tableView + widthForContentCellInColumn:(NSInteger)column +{ + return 120; +} + +- (CGFloat)heightForTopHeaderInTableView:(FLEXMultiColumnTableView *)tableView +{ + return 40; +} + +- (CGFloat)widthForLeftHeaderInTableView:(FLEXMultiColumnTableView *)tableView +{ + NSString *str = [NSString stringWithFormat:@"%lu",(unsigned long)self.contentsArray.count]; + NSDictionary *attrs = @{@"NSFontAttributeName":[UIFont systemFontOfSize:17.0]}; + CGSize size = [str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 14) + options:NSStringDrawingUsesLineFragmentOrigin + attributes:attrs context:nil].size; + return size.width + 20; +} + +#pragma mark - +#pragma mark MultiColumnTableView Delegate + + +- (void)multiColumnTableView:(FLEXMultiColumnTableView *)tableView didTapLabelWithText:(NSString *)text +{ + FLEXWebViewController * detailViewController = [[FLEXWebViewController alloc] initWithText:text]; + [self.navigationController pushViewController:detailViewController animated:YES]; +} + +- (void)multiColumnTableView:(FLEXMultiColumnTableView *)tableView didTapHeaderWithText:(NSString *)text sortType:(FLEXTableColumnHeaderSortType)sortType +{ + + NSArray *sortContentData = [self.contentsArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { + + if ([obj1 objectForKey:text] == [NSNull null]) { + return NSOrderedAscending; + } + if ([obj2 objectForKey:text] == [NSNull null]) { + return NSOrderedDescending; + } + NSComparisonResult result = [[obj1 objectForKey:text] compare:[obj2 objectForKey:text]]; + + return result; + }]; + if (sortType == FLEXTableColumnHeaderSortTypeDesc) { + NSEnumerator *contentReverseEvumerator = [sortContentData reverseObjectEnumerator]; + sortContentData = [NSArray arrayWithArray:[contentReverseEvumerator allObjects]]; + } + + self.contentsArray = sortContentData; + [self.multiColumView reloadData]; +} + +#pragma mark - +#pragma mark About Transition + +- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection + withTransitionCoordinator:(id )coordinator +{ + [super willTransitionToTraitCollection:newCollection + withTransitionCoordinator:coordinator]; + [coordinator animateAlongsideTransition:^(id context) { + if (newCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact) { + + _multiColumView.frame = CGRectMake(0, 32, self.view.frame.size.width, self.view.frame.size.height - 32); + } + else { + _multiColumView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64); + } + [self.view setNeedsLayout]; + } completion:nil]; +} + + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableLeftCell.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableLeftCell.h new file mode 100644 index 0000000000..3ec4a01920 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableLeftCell.h @@ -0,0 +1,17 @@ +// +// FLEXTableLeftCell.h +// UICatalog +// +// Created by Peng Tao on 15/11/24. +// Copyright © 2015年 f. All rights reserved. +// + +#import + +@interface FLEXTableLeftCell : UITableViewCell + +@property (nonatomic, strong) UILabel *titlelabel; + ++ (instancetype)cellWithTableView:(UITableView *)tableView; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableLeftCell.m b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableLeftCell.m new file mode 100644 index 0000000000..a1a73e5cad --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableLeftCell.m @@ -0,0 +1,35 @@ +// +// FLEXTableLeftCell.m +// UICatalog +// +// Created by Peng Tao on 15/11/24. +// Copyright © 2015年 f. All rights reserved. +// + +#import "FLEXTableLeftCell.h" + +@implementation FLEXTableLeftCell + ++ (instancetype)cellWithTableView:(UITableView *)tableView +{ + static NSString *identifier = @"FLEXTableLeftCell"; + FLEXTableLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; + + if (!cell) { + cell = [[FLEXTableLeftCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; + UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectZero]; + textLabel.textAlignment = NSTextAlignmentCenter; + textLabel.font = [UIFont systemFontOfSize:13.0]; + textLabel.backgroundColor = [UIColor clearColor]; + [cell.contentView addSubview:textLabel]; + cell.titlelabel = textLabel; + } + return cell; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + self.titlelabel.frame = self.contentView.frame; +} +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableListViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableListViewController.h new file mode 100644 index 0000000000..0a63316459 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableListViewController.h @@ -0,0 +1,16 @@ +// +// PTTableListViewController.h +// PTDatabaseReader +// +// Created by Peng Tao on 15/11/23. +// Copyright © 2015年 Peng Tao. All rights reserved. +// + +#import + +@interface FLEXTableListViewController : UITableViewController + ++ (BOOL)supportsExtension:(NSString *)extension; +- (instancetype)initWithPath:(NSString *)path; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableListViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableListViewController.m new file mode 100644 index 0000000000..5b64446489 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/DatabaseBrowser/FLEXTableListViewController.m @@ -0,0 +1,136 @@ +// +// PTTableListViewController.m +// PTDatabaseReader +// +// Created by Peng Tao on 15/11/23. +// Copyright © 2015年 Peng Tao. All rights reserved. +// + +#import "FLEXTableListViewController.h" + +#import "FLEXDatabaseManager.h" +#import "FLEXSQLiteDatabaseManager.h" +#import "FLEXRealmDatabaseManager.h" + +#import "FLEXTableContentViewController.h" + +@interface FLEXTableListViewController () +{ + id _dbm; + NSString *_databasePath; +} + +@property (nonatomic, strong) NSArray *tables; + ++ (NSArray *)supportedSQLiteExtensions; ++ (NSArray *)supportedRealmExtensions; + +@end + +@implementation FLEXTableListViewController + +- (instancetype)initWithPath:(NSString *)path +{ + self = [super initWithStyle:UITableViewStyleGrouped]; + if (self) { + _databasePath = [path copy]; + _dbm = [self databaseManagerForFileAtPath:_databasePath]; + [_dbm open]; + [self getAllTables]; + } + return self; +} + +- (id)databaseManagerForFileAtPath:(NSString *)path +{ + NSString *pathExtension = path.pathExtension.lowercaseString; + + NSArray *sqliteExtensions = [FLEXTableListViewController supportedSQLiteExtensions]; + if ([sqliteExtensions indexOfObject:pathExtension] != NSNotFound) { + return [[FLEXSQLiteDatabaseManager alloc] initWithPath:path]; + } + + NSArray *realmExtensions = [FLEXTableListViewController supportedRealmExtensions]; + if (realmExtensions != nil && [realmExtensions indexOfObject:pathExtension] != NSNotFound) { + return [[FLEXRealmDatabaseManager alloc] initWithPath:path]; + } + + return nil; +} + +- (void)getAllTables +{ + NSArray *resultArray = [_dbm queryAllTables]; + NSMutableArray *array = [NSMutableArray array]; + for (NSDictionary *dict in resultArray) { + [array addObject:dict[@"name"]]; + } + self.tables = array; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return self.tables.count; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FLEXTableListViewControllerCell"]; + if (!cell) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault + reuseIdentifier:@"FLEXTableListViewControllerCell"]; + } + cell.textLabel.text = self.tables[indexPath.row]; + return cell; +} + + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXTableContentViewController *contentViewController = [[FLEXTableContentViewController alloc] init]; + + contentViewController.contentsArray = [_dbm queryAllDataWithTableName:self.tables[indexPath.row]]; + contentViewController.columnsArray = [_dbm queryAllColumnsWithTableName:self.tables[indexPath.row]]; + + contentViewController.title = self.tables[indexPath.row]; + [self.navigationController pushViewController:contentViewController animated:YES]; +} + + +- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section +{ + return [NSString stringWithFormat:@"%lu tables", (unsigned long)self.tables.count]; +} + ++ (BOOL)supportsExtension:(NSString *)extension +{ + extension = extension.lowercaseString; + + NSArray *sqliteExtensions = [FLEXTableListViewController supportedSQLiteExtensions]; + if (sqliteExtensions.count > 0 && [sqliteExtensions indexOfObject:extension] != NSNotFound) { + return YES; + } + + NSArray *realmExtensions = [FLEXTableListViewController supportedRealmExtensions]; + if (realmExtensions.count > 0 && [realmExtensions indexOfObject:extension] != NSNotFound) { + return YES; + } + + return NO; +} + ++ (NSArray *)supportedSQLiteExtensions +{ + return @[@"db", @"sqlite", @"sqlite3"]; +} + ++ (NSArray *)supportedRealmExtensions +{ + if (NSClassFromString(@"RLMRealm") == nil) { + return nil; + } + + return @[@"realm"]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXClassesTableViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXClassesTableViewController.h new file mode 100644 index 0000000000..0c00cc2185 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXClassesTableViewController.h @@ -0,0 +1,15 @@ +// +// FLEXClassesTableViewController.h +// Flipboard +// +// Created by Ryan Olson on 2014-05-03. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@interface FLEXClassesTableViewController : UITableViewController + +@property (nonatomic, copy) NSString *binaryImageName; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXClassesTableViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXClassesTableViewController.m new file mode 100644 index 0000000000..80e3fa4314 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXClassesTableViewController.m @@ -0,0 +1,140 @@ +// +// FLEXClassesTableViewController.m +// Flipboard +// +// Created by Ryan Olson on 2014-05-03. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXClassesTableViewController.h" +#import "FLEXObjectExplorerViewController.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXUtility.h" +#import + +@interface FLEXClassesTableViewController () + +@property (nonatomic, strong) NSArray *classNames; +@property (nonatomic, strong) NSArray *filteredClassNames; +@property (nonatomic, strong) UISearchBar *searchBar; + +@end + +@implementation FLEXClassesTableViewController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.searchBar = [[UISearchBar alloc] init]; + self.searchBar.placeholder = [FLEXUtility searchBarPlaceholderText]; + self.searchBar.delegate = self; + [self.searchBar sizeToFit]; + self.tableView.tableHeaderView = self.searchBar; +} + +- (void)setBinaryImageName:(NSString *)binaryImageName +{ + if (![_binaryImageName isEqual:binaryImageName]) { + _binaryImageName = binaryImageName; + [self loadClassNames]; + [self updateTitle]; + } +} + +- (void)setClassNames:(NSArray *)classNames +{ + _classNames = classNames; + self.filteredClassNames = classNames; +} + +- (void)loadClassNames +{ + unsigned int classNamesCount = 0; + const char **classNames = objc_copyClassNamesForImage([self.binaryImageName UTF8String], &classNamesCount); + if (classNames) { + NSMutableArray *classNameStrings = [NSMutableArray array]; + for (unsigned int i = 0; i < classNamesCount; i++) { + const char *className = classNames[i]; + NSString *classNameString = [NSString stringWithUTF8String:className]; + [classNameStrings addObject:classNameString]; + } + + self.classNames = [classNameStrings sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; + + free(classNames); + } +} + +- (void)updateTitle +{ + NSString *shortImageName = self.binaryImageName.lastPathComponent; + self.title = [NSString stringWithFormat:@"%@ Classes (%lu)", shortImageName, (unsigned long)[self.filteredClassNames count]]; +} + + +#pragma mark - Search + +- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText +{ + if ([searchText length] > 0) { + NSPredicate *searchPreidcate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchText]; + self.filteredClassNames = [self.classNames filteredArrayUsingPredicate:searchPreidcate]; + } else { + self.filteredClassNames = self.classNames; + } + [self updateTitle]; + [self.tableView reloadData]; +} + +- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar +{ + [searchBar resignFirstResponder]; +} + +- (void)scrollViewDidScroll:(UIScrollView *)scrollView +{ + // Dismiss the keyboard when interacting with filtered results. + [self.searchBar endEditing:YES]; +} + + +#pragma mark - Table View Data Source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return [self.filteredClassNames count]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *CellIdentifier = @"Cell"; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; + if (!cell) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; + cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + cell.textLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + } + + cell.textLabel.text = self.filteredClassNames[indexPath.row]; + + return cell; +} + + +#pragma mark - Table View Delegate + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + NSString *className = self.filteredClassNames[indexPath.row]; + Class selectedClass = objc_getClass([className UTF8String]); + FLEXObjectExplorerViewController *objectExplorer = [FLEXObjectExplorerFactory explorerViewControllerForObject:selectedClass]; + [self.navigationController pushViewController:objectExplorer animated:YES]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXCookiesTableViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXCookiesTableViewController.h new file mode 100644 index 0000000000..09c5865159 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXCookiesTableViewController.h @@ -0,0 +1,13 @@ +// +// FLEXCookiesTableViewController.h +// FLEX +// +// Created by Rich Robinson on 19/10/2015. +// Copyright © 2015 Flipboard. All rights reserved. +// + +#import + +@interface FLEXCookiesTableViewController : UITableViewController + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXCookiesTableViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXCookiesTableViewController.m new file mode 100644 index 0000000000..d7e87ce28a --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXCookiesTableViewController.m @@ -0,0 +1,71 @@ +// +// FLEXCookiesTableViewController.m +// FLEX +// +// Created by Rich Robinson on 19/10/2015. +// Copyright © 2015 Flipboard. All rights reserved. +// + +#import "FLEXCookiesTableViewController.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXUtility.h" + +@interface FLEXCookiesTableViewController () + +@property (nonatomic, strong) NSArray *cookies; + +@end + +@implementation FLEXCookiesTableViewController + +- (id)initWithStyle:(UITableViewStyle)style { + self = [super initWithStyle:style]; + + if (self) { + self.title = @"Cookies"; + + NSSortDescriptor *nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]; + _cookies =[[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies sortedArrayUsingDescriptors:@[nameSortDescriptor]]; + } + + return self; +} + +- (NSHTTPCookie *)cookieForRowAtIndexPath:(NSIndexPath *)indexPath { + return self.cookies[indexPath.row]; +} + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + return self.cookies.count; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + static NSString *CellIdentifier = @"Cell"; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; + if (!cell) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; + cell.textLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + cell.detailTextLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + cell.detailTextLabel.textColor = [UIColor grayColor]; + cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + } + + NSHTTPCookie *cookie = [self cookieForRowAtIndexPath:indexPath]; + cell.textLabel.text = [NSString stringWithFormat:@"%@ (%@)", cookie.name, cookie.value]; + cell.detailTextLabel.text = cookie.domain; + + return cell; +} + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { + NSHTTPCookie *cookie = [self cookieForRowAtIndexPath:indexPath]; + UIViewController *cookieViewController = (UIViewController *)[FLEXObjectExplorerFactory explorerViewControllerForObject:cookie]; + + [self.navigationController pushViewController:cookieViewController animated:YES]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserFileOperationController.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserFileOperationController.h new file mode 100644 index 0000000000..79ff1144d5 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserFileOperationController.h @@ -0,0 +1,33 @@ +// +// FLEXFileBrowserFileOperationController.h +// Flipboard +// +// Created by Daniel Rodriguez Troitino on 2/13/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import + +@protocol FLEXFileBrowserFileOperationController; + +@protocol FLEXFileBrowserFileOperationControllerDelegate + +- (void)fileOperationControllerDidDismiss:(id)controller; + +@end + +@protocol FLEXFileBrowserFileOperationController + +@property (nonatomic, weak) id delegate; + +- (instancetype)initWithPath:(NSString *)path; + +- (void)show; + +@end + +@interface FLEXFileBrowserFileDeleteOperationController : NSObject +@end + +@interface FLEXFileBrowserFileRenameOperationController : NSObject +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserFileOperationController.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserFileOperationController.m new file mode 100644 index 0000000000..4ed48f9a87 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserFileOperationController.m @@ -0,0 +1,142 @@ +// +// FLEXFileBrowserFileOperationController.m +// Flipboard +// +// Created by Daniel Rodriguez Troitino on 2/13/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import "FLEXFileBrowserFileOperationController.h" +#import + +@interface FLEXFileBrowserFileDeleteOperationController () + +@property (nonatomic, copy, readonly) NSString *path; + +- (instancetype)initWithPath:(NSString *)path NS_DESIGNATED_INITIALIZER; + +@end + +@implementation FLEXFileBrowserFileDeleteOperationController + +@synthesize delegate = _delegate; + +- (instancetype)init +{ + return [self initWithPath:nil]; +} + +- (instancetype)initWithPath:(NSString *)path +{ + self = [super init]; + if (self) { + _path = path; + } + + return self; +} + +- (void)show +{ + BOOL isDirectory = NO; + BOOL stillExists = [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]; + + if (stillExists) { + UIAlertView *deleteWarning = [[UIAlertView alloc] + initWithTitle:[NSString stringWithFormat:@"Delete %@?", self.path.lastPathComponent] + message:[NSString stringWithFormat:@"The %@ will be deleted. This operation cannot be undone", isDirectory ? @"directory" : @"file"] + delegate:self + cancelButtonTitle:@"Cancel" + otherButtonTitles:@"Delete", nil]; + [deleteWarning show]; + } else { + [[[UIAlertView alloc] initWithTitle:@"File Removed" message:@"The file at the specified path no longer exists." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; + } +} + +#pragma mark - UIAlertViewDelegate + +- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex +{ + if (buttonIndex == alertView.cancelButtonIndex) { + // Nothing, just cancel + } else if (buttonIndex == alertView.firstOtherButtonIndex) { + [[NSFileManager defaultManager] removeItemAtPath:self.path error:NULL]; + } +} + +- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex +{ + [self.delegate fileOperationControllerDidDismiss:self]; +} + +@end + +@interface FLEXFileBrowserFileRenameOperationController () + +@property (nonatomic, copy, readonly) NSString *path; + +- (instancetype)initWithPath:(NSString *)path NS_DESIGNATED_INITIALIZER; + +@end + +@implementation FLEXFileBrowserFileRenameOperationController + +@synthesize delegate = _delegate; + +- (instancetype)init +{ + return [self initWithPath:nil]; +} + +- (instancetype)initWithPath:(NSString *)path +{ + self = [super init]; + if (self) { + _path = path; + } + + return self; +} + +- (void)show +{ + BOOL isDirectory = NO; + BOOL stillExists = [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]; + + if (stillExists) { + UIAlertView *renameDialog = [[UIAlertView alloc] + initWithTitle:[NSString stringWithFormat:@"Rename %@?", self.path.lastPathComponent] + message:nil + delegate:self + cancelButtonTitle:@"Cancel" + otherButtonTitles:@"Rename", nil]; + renameDialog.alertViewStyle = UIAlertViewStylePlainTextInput; + UITextField *textField = [renameDialog textFieldAtIndex:0]; + textField.placeholder = @"New file name"; + textField.text = self.path.lastPathComponent; + [renameDialog show]; + } else { + [[[UIAlertView alloc] initWithTitle:@"File Removed" message:@"The file at the specified path no longer exists." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; + } +} + +#pragma mark - UIAlertViewDelegate + +- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex +{ + if (buttonIndex == alertView.cancelButtonIndex) { + // Nothing, just cancel + } else if (buttonIndex == alertView.firstOtherButtonIndex) { + NSString *newFileName = [alertView textFieldAtIndex:0].text; + NSString *newPath = [[self.path stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFileName]; + [[NSFileManager defaultManager] moveItemAtPath:self.path toPath:newPath error:NULL]; + } +} + +- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex +{ + [self.delegate fileOperationControllerDidDismiss:self]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserSearchOperation.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserSearchOperation.h new file mode 100644 index 0000000000..24b7fa93d6 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserSearchOperation.h @@ -0,0 +1,25 @@ +// +// FLEXFileBrowserSearchOperation.h +// UICatalog +// +// Created by 啟倫 陳 on 2014/8/4. +// Copyright (c) 2014年 f. All rights reserved. +// + +#import + +@protocol FLEXFileBrowserSearchOperationDelegate; + +@interface FLEXFileBrowserSearchOperation : NSOperation + +@property (nonatomic, weak) id delegate; + +- (id)initWithPath:(NSString *)currentPath searchString:(NSString *)searchString; + +@end + +@protocol FLEXFileBrowserSearchOperationDelegate + +- (void)fileBrowserSearchOperationResult:(NSArray *)searchResult size:(uint64_t)size; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserSearchOperation.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserSearchOperation.m new file mode 100644 index 0000000000..1b99f43968 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserSearchOperation.m @@ -0,0 +1,123 @@ +// +// FLEXFileBrowserSearchOperation.m +// UICatalog +// +// Created by 啟倫 陳 on 2014/8/4. +// Copyright (c) 2014年 f. All rights reserved. +// + +#import "FLEXFileBrowserSearchOperation.h" + +@implementation NSMutableArray (FLEXStack) + +- (void)flex_push:(id)anObject +{ + [self addObject:anObject]; +} + +- (id)flex_pop +{ + id anObject = [self lastObject]; + [self removeLastObject]; + return anObject; +} + +@end + +@interface FLEXFileBrowserSearchOperation () + +@property (nonatomic, strong) NSString *path; +@property (nonatomic, strong) NSString *searchString; + +@end + +@implementation FLEXFileBrowserSearchOperation + +#pragma mark - private + +- (uint64_t)totalSizeAtPath:(NSString *)path +{ + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSDictionary *attributes = [fileManager attributesOfItemAtPath:path error:NULL]; + uint64_t totalSize = [attributes fileSize]; + + for (NSString *fileName in [fileManager enumeratorAtPath:path]) { + attributes = [fileManager attributesOfItemAtPath:[path stringByAppendingPathComponent:fileName] error:NULL]; + totalSize += [attributes fileSize]; + } + return totalSize; +} + +#pragma mark - instance method + +- (id)initWithPath:(NSString *)currentPath searchString:(NSString *)searchString +{ + self = [super init]; + if (self) { + self.path = currentPath; + self.searchString = searchString; + } + return self; +} + +#pragma mark - methods to override + +- (void)main +{ + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSMutableArray *searchPaths = [NSMutableArray array]; + NSMutableDictionary *sizeMapping = [NSMutableDictionary dictionary]; + uint64_t totalSize = 0; + NSMutableArray *stack = [NSMutableArray array]; + [stack flex_push:self.path]; + + //recursive found all match searchString paths, and precomputing there size + while ([stack count]) { + NSString *currentPath = [stack flex_pop]; + NSArray *directoryPath = [fileManager contentsOfDirectoryAtPath:currentPath error:nil]; + + for (NSString *subPath in directoryPath) { + NSString *fullPath = [currentPath stringByAppendingPathComponent:subPath]; + + if ([[subPath lowercaseString] rangeOfString:[self.searchString lowercaseString]].location != NSNotFound) { + [searchPaths addObject:fullPath]; + if (!sizeMapping[fullPath]) { + uint64_t fullPathSize = [self totalSizeAtPath:fullPath]; + totalSize += fullPathSize; + [sizeMapping setObject:@(fullPathSize) forKey:fullPath]; + } + } + BOOL isDirectory; + if ([fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory] && isDirectory) { + [stack flex_push:fullPath]; + } + + if ([self isCancelled]) { + return; + } + } + } + + //sort + NSArray *sortedArray = [searchPaths sortedArrayUsingComparator:^NSComparisonResult(NSString *path1, NSString *path2) { + uint64_t pathSize1 = [sizeMapping[path1] unsignedLongLongValue]; + uint64_t pathSize2 = [sizeMapping[path2] unsignedLongLongValue]; + if (pathSize1 < pathSize2) { + return NSOrderedAscending; + } else if (pathSize1 > pathSize2) { + return NSOrderedDescending; + } else { + return NSOrderedSame; + } + }]; + + if ([self isCancelled]) { + return; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [self.delegate fileBrowserSearchOperationResult:sortedArray size:totalSize]; + }); +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserTableViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserTableViewController.h new file mode 100644 index 0000000000..7454e9df21 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserTableViewController.h @@ -0,0 +1,17 @@ +// +// FLEXFileBrowserTableViewController.h +// Flipboard +// +// Created by Ryan Olson on 6/9/14. +// Based on previous work by Evan Doll +// + +#import + +#import "FLEXFileBrowserSearchOperation.h" + +@interface FLEXFileBrowserTableViewController : UITableViewController + +- (id)initWithPath:(NSString *)path; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserTableViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserTableViewController.m new file mode 100644 index 0000000000..6508bde4b5 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXFileBrowserTableViewController.m @@ -0,0 +1,351 @@ +// +// FLEXFileBrowserTableViewController.m +// Flipboard +// +// Created by Ryan Olson on 6/9/14. +// +// + +#import "FLEXFileBrowserTableViewController.h" +#import "FLEXFileBrowserFileOperationController.h" +#import "FLEXUtility.h" +#import "FLEXWebViewController.h" +#import "FLEXImagePreviewViewController.h" +#import "FLEXTableListViewController.h" + +@interface FLEXFileBrowserTableViewCell : UITableViewCell +@end + +@interface FLEXFileBrowserTableViewController () + +@property (nonatomic, copy) NSString *path; +@property (nonatomic, copy) NSArray *childPaths; +@property (nonatomic, strong) NSArray *searchPaths; +@property (nonatomic, strong) NSNumber *recursiveSize; +@property (nonatomic, strong) NSNumber *searchPathsSize; +@property (nonatomic, strong) UISearchController *searchController; +@property (nonatomic) NSOperationQueue *operationQueue; +@property (nonatomic, strong) UIDocumentInteractionController *documentController; +@property (nonatomic, strong) id fileOperationController; + +@end + +@implementation FLEXFileBrowserTableViewController + +- (id)initWithStyle:(UITableViewStyle)style +{ + return [self initWithPath:NSHomeDirectory()]; +} + +- (id)initWithPath:(NSString *)path +{ + self = [super initWithStyle:UITableViewStyleGrouped]; + if (self) { + self.path = path; + self.title = [path lastPathComponent]; + self.operationQueue = [NSOperationQueue new]; + + self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; + self.searchController.searchResultsUpdater = self; + self.searchController.delegate = self; + self.searchController.dimsBackgroundDuringPresentation = NO; + self.tableView.tableHeaderView = self.searchController.searchBar; + + //computing path size + FLEXFileBrowserTableViewController *__weak weakSelf = self; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSDictionary *attributes = [fileManager attributesOfItemAtPath:path error:NULL]; + uint64_t totalSize = [attributes fileSize]; + + for (NSString *fileName in [fileManager enumeratorAtPath:path]) { + attributes = [fileManager attributesOfItemAtPath:[path stringByAppendingPathComponent:fileName] error:NULL]; + totalSize += [attributes fileSize]; + + // Bail if the interested view controller has gone away. + if (!weakSelf) { + return; + } + } + + dispatch_async(dispatch_get_main_queue(), ^{ + FLEXFileBrowserTableViewController *__strong strongSelf = weakSelf; + strongSelf.recursiveSize = @(totalSize); + [strongSelf.tableView reloadData]; + }); + }); + + [self reloadChildPaths]; + } + return self; +} + +#pragma mark - UIViewController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + UIMenuItem *renameMenuItem = [[UIMenuItem alloc] initWithTitle:@"Rename" action:@selector(fileBrowserRename:)]; + UIMenuItem *deleteMenuItem = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(fileBrowserDelete:)]; + [UIMenuController sharedMenuController].menuItems = @[renameMenuItem, deleteMenuItem]; +} + +#pragma mark - FLEXFileBrowserSearchOperationDelegate + +- (void)fileBrowserSearchOperationResult:(NSArray *)searchResult size:(uint64_t)size +{ + self.searchPaths = searchResult; + self.searchPathsSize = @(size); + [self.tableView reloadData]; +} + +#pragma mark - UISearchResultsUpdating + +- (void)updateSearchResultsForSearchController:(UISearchController *)searchController +{ + [self reloadDisplayedPaths]; +} + +#pragma mark - UISearchControllerDelegate + +- (void)willDismissSearchController:(UISearchController *)searchController +{ + [self.operationQueue cancelAllOperations]; + [self reloadChildPaths]; + [self.tableView reloadData]; +} + + +#pragma mark - Table view data source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return self.searchController.isActive ? [self.searchPaths count] : [self.childPaths count]; +} + +- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section +{ + BOOL isSearchActive = self.searchController.isActive; + NSNumber *currentSize = isSearchActive ? self.searchPathsSize : self.recursiveSize; + NSArray *currentPaths = isSearchActive ? self.searchPaths : self.childPaths; + + NSString *sizeString = nil; + if (!currentSize) { + sizeString = @"Computing size…"; + } else { + sizeString = [NSByteCountFormatter stringFromByteCount:[currentSize longLongValue] countStyle:NSByteCountFormatterCountStyleFile]; + } + + return [NSString stringWithFormat:@"%lu files (%@)", (unsigned long)[currentPaths count], sizeString]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + NSString *fullPath = [self filePathAtIndexPath:indexPath]; + NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fullPath error:NULL]; + BOOL isDirectory = [[attributes fileType] isEqual:NSFileTypeDirectory]; + NSString *subtitle = nil; + if (isDirectory) { + NSUInteger count = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:fullPath error:NULL] count]; + subtitle = [NSString stringWithFormat:@"%lu file%@", (unsigned long)count, (count == 1 ? @"" : @"s")]; + } else { + NSString *sizeString = [NSByteCountFormatter stringFromByteCount:[attributes fileSize] countStyle:NSByteCountFormatterCountStyleFile]; + subtitle = [NSString stringWithFormat:@"%@ - %@", sizeString, [attributes fileModificationDate]]; + } + + static NSString *textCellIdentifier = @"textCell"; + static NSString *imageCellIdentifier = @"imageCell"; + UITableViewCell *cell = nil; + + // Separate image and text only cells because otherwise the separator lines get out-of-whack on image cells reused with text only. + BOOL showImagePreview = [FLEXUtility isImagePathExtension:[fullPath pathExtension]]; + NSString *cellIdentifier = showImagePreview ? imageCellIdentifier : textCellIdentifier; + + if (!cell) { + cell = [[FLEXFileBrowserTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; + cell.textLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + cell.detailTextLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + cell.detailTextLabel.textColor = [UIColor grayColor]; + cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + } + NSString *cellTitle = [fullPath lastPathComponent]; + cell.textLabel.text = cellTitle; + cell.detailTextLabel.text = subtitle; + + if (showImagePreview) { + cell.imageView.contentMode = UIViewContentModeScaleAspectFit; + cell.imageView.image = [UIImage imageWithContentsOfFile:fullPath]; + } + + return cell; +} + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + NSString *fullPath = [self filePathAtIndexPath:indexPath]; + NSString *subpath = [fullPath lastPathComponent]; + NSString *pathExtension = [subpath pathExtension]; + + BOOL isDirectory = NO; + BOOL stillExists = [[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDirectory]; + if (stillExists) { + UIViewController *drillInViewController = nil; + if (isDirectory) { + drillInViewController = [[[self class] alloc] initWithPath:fullPath]; + } else if ([FLEXUtility isImagePathExtension:pathExtension]) { + UIImage *image = [UIImage imageWithContentsOfFile:fullPath]; + drillInViewController = [[FLEXImagePreviewViewController alloc] initWithImage:image]; + } else { + // Special case keyed archives, json, and plists to get more readable data. + NSString *prettyString = nil; + if ([pathExtension isEqual:@"archive"] || [pathExtension isEqual:@"coded"]) { + prettyString = [[NSKeyedUnarchiver unarchiveObjectWithFile:fullPath] description]; + } else if ([pathExtension isEqualToString:@"json"]) { + prettyString = [FLEXUtility prettyJSONStringFromData:[NSData dataWithContentsOfFile:fullPath]]; + } else if ([pathExtension isEqualToString:@"plist"]) { + NSData *fileData = [NSData dataWithContentsOfFile:fullPath]; + prettyString = [[NSPropertyListSerialization propertyListWithData:fileData options:0 format:NULL error:NULL] description]; + } + + if ([prettyString length] > 0) { + drillInViewController = [[FLEXWebViewController alloc] initWithText:prettyString]; + } else if ([FLEXWebViewController supportsPathExtension:pathExtension]) { + drillInViewController = [[FLEXWebViewController alloc] initWithURL:[NSURL fileURLWithPath:fullPath]]; + } else if ([FLEXTableListViewController supportsExtension:subpath.pathExtension]) { + drillInViewController = [[FLEXTableListViewController alloc] initWithPath:fullPath]; + } + else { + NSString *fileString = [NSString stringWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:NULL]; + if ([fileString length] > 0) { + drillInViewController = [[FLEXWebViewController alloc] initWithText:fileString]; + } + } + } + + if (drillInViewController) { + drillInViewController.title = [subpath lastPathComponent]; + [self.navigationController pushViewController:drillInViewController animated:YES]; + } else { + [self openFileController:fullPath]; + [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; + } + } else { + [[[UIAlertView alloc] initWithTitle:@"File Removed" message:@"The file at the specified path no longer exists." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; + [self reloadDisplayedPaths]; + } +} + +- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath +{ + return YES; +} + +- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + return action == @selector(fileBrowserDelete:) || action == @selector(fileBrowserRename:); +} + +- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + // Empty, but has to exist for the menu to show + // The table view only calls this method for actions in the UIResponderStandardEditActions informal protocol. + // Since our actions are outside of that protocol, we need to manually handle the action forwarding from the cells. +} + +#pragma mark - FLEXFileBrowserFileOperationControllerDelegate + +- (void)fileOperationControllerDidDismiss:(id)controller +{ + [self reloadDisplayedPaths]; +} + +- (void)openFileController:(NSString *)fullPath +{ + UIDocumentInteractionController *controller = [UIDocumentInteractionController new]; + controller.URL = [[NSURL alloc] initFileURLWithPath:fullPath]; + + [controller presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES]; + self.documentController = controller; +} + +- (void)fileBrowserRename:(UITableViewCell *)sender +{ + NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; + NSString *fullPath = [self filePathAtIndexPath:indexPath]; + + self.fileOperationController = [[FLEXFileBrowserFileRenameOperationController alloc] initWithPath:fullPath]; + self.fileOperationController.delegate = self; + [self.fileOperationController show]; +} + +- (void)fileBrowserDelete:(UITableViewCell *)sender +{ + NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; + NSString *fullPath = [self filePathAtIndexPath:indexPath]; + + self.fileOperationController = [[FLEXFileBrowserFileDeleteOperationController alloc] initWithPath:fullPath]; + self.fileOperationController.delegate = self; + [self.fileOperationController show]; +} + +- (void)reloadDisplayedPaths +{ + if (self.searchController.isActive) { + [self reloadSearchPaths]; + } else { + [self reloadChildPaths]; + } + [self.tableView reloadData]; +} + +- (void)reloadChildPaths +{ + NSMutableArray *childPaths = [NSMutableArray array]; + NSArray *subpaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.path error:NULL]; + for (NSString *subpath in subpaths) { + [childPaths addObject:[self.path stringByAppendingPathComponent:subpath]]; + } + self.childPaths = childPaths; +} + +- (void)reloadSearchPaths +{ + self.searchPaths = nil; + self.searchPathsSize = nil; + + //clear pre search request and start a new one + [self.operationQueue cancelAllOperations]; + FLEXFileBrowserSearchOperation *newOperation = [[FLEXFileBrowserSearchOperation alloc] initWithPath:self.path searchString:self.searchController.searchBar.text]; + newOperation.delegate = self; + [self.operationQueue addOperation:newOperation]; +} + +- (NSString *)filePathAtIndexPath:(NSIndexPath *)indexPath +{ + return self.searchController.isActive ? self.searchPaths[indexPath.row] : self.childPaths[indexPath.row]; +} + +@end + + +@implementation FLEXFileBrowserTableViewCell + +- (void)fileBrowserRename:(UIMenuController *)sender +{ + id target = [self.nextResponder targetForAction:_cmd withSender:sender]; + [[UIApplication sharedApplication] sendAction:_cmd to:target from:self forEvent:nil]; +} + +- (void)fileBrowserDelete:(UIMenuController *)sender +{ + id target = [self.nextResponder targetForAction:_cmd withSender:sender]; + [[UIApplication sharedApplication] sendAction:_cmd to:target from:self forEvent:nil]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXGlobalsTableViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXGlobalsTableViewController.h new file mode 100644 index 0000000000..a2fbe358e4 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXGlobalsTableViewController.h @@ -0,0 +1,27 @@ +// +// FLEXGlobalsTableViewController.h +// Flipboard +// +// Created by Ryan Olson on 2014-05-03. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@protocol FLEXGlobalsTableViewControllerDelegate; + +@interface FLEXGlobalsTableViewController : UITableViewController + +@property (nonatomic, weak) id delegate; + +/// We pretend that one of the app's windows is still the key window, even though the explorer window may have become key. +/// We want to display debug state about the application, not about this tool. ++ (void)setApplicationWindow:(UIWindow *)applicationWindow; + +@end + +@protocol FLEXGlobalsTableViewControllerDelegate + +- (void)globalsViewControllerDidFinish:(FLEXGlobalsTableViewController *)globalsViewController; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXGlobalsTableViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXGlobalsTableViewController.m new file mode 100644 index 0000000000..2986643d96 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXGlobalsTableViewController.m @@ -0,0 +1,306 @@ +// +// FLEXGlobalsTableViewController.m +// Flipboard +// +// Created by Ryan Olson on 2014-05-03. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXGlobalsTableViewController.h" +#import "FLEXUtility.h" +#import "FLEXLibrariesTableViewController.h" +#import "FLEXClassesTableViewController.h" +#import "FLEXObjectExplorerViewController.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXLiveObjectsTableViewController.h" +#import "FLEXFileBrowserTableViewController.h" +#import "FLEXCookiesTableViewController.h" +#import "FLEXGlobalsTableViewControllerEntry.h" +#import "FLEXManager+Private.h" +#import "FLEXSystemLogTableViewController.h" +#import "FLEXNetworkHistoryTableViewController.h" + +static __weak UIWindow *s_applicationWindow = nil; + +typedef NS_ENUM(NSUInteger, FLEXGlobalsRow) { + FLEXGlobalsRowNetworkHistory, + FLEXGlobalsRowSystemLog, + FLEXGlobalsRowLiveObjects, + FLEXGlobalsRowFileBrowser, + FLEXGlobalsCookies, + FLEXGlobalsRowSystemLibraries, + FLEXGlobalsRowAppClasses, + FLEXGlobalsRowAppDelegate, + FLEXGlobalsRowRootViewController, + FLEXGlobalsRowUserDefaults, + FLEXGlobalsRowApplication, + FLEXGlobalsRowKeyWindow, + FLEXGlobalsRowMainScreen, + FLEXGlobalsRowCurrentDevice, + FLEXGlobalsRowCount +}; + +@interface FLEXGlobalsTableViewController () + +/// [FLEXGlobalsTableViewControllerEntry *] +@property (nonatomic, readonly, copy) NSArray *entries; + +@end + +@implementation FLEXGlobalsTableViewController + +/// [FLEXGlobalsTableViewControllerEntry *] ++ (NSArray *)defaultGlobalEntries +{ + NSMutableArray *defaultGlobalEntries = [NSMutableArray array]; + + for (FLEXGlobalsRow defaultRowIndex = 0; defaultRowIndex < FLEXGlobalsRowCount; defaultRowIndex++) { + FLEXGlobalsTableViewControllerEntryNameFuture titleFuture = nil; + FLEXGlobalsTableViewControllerViewControllerFuture viewControllerFuture = nil; + + switch (defaultRowIndex) { + case FLEXGlobalsRowAppClasses: + titleFuture = ^NSString *{ + return [NSString stringWithFormat:@"📕 %@ Classes", [FLEXUtility applicationName]]; + }; + viewControllerFuture = ^UIViewController *{ + FLEXClassesTableViewController *classesViewController = [[FLEXClassesTableViewController alloc] init]; + classesViewController.binaryImageName = [FLEXUtility applicationImageName]; + + return classesViewController; + }; + break; + + case FLEXGlobalsRowSystemLibraries: { + NSString *titleString = @"📚 System Libraries"; + titleFuture = ^NSString *{ + return titleString; + }; + viewControllerFuture = ^UIViewController *{ + FLEXLibrariesTableViewController *librariesViewController = [[FLEXLibrariesTableViewController alloc] init]; + librariesViewController.title = titleString; + + return librariesViewController; + }; + break; + } + + case FLEXGlobalsRowLiveObjects: + titleFuture = ^NSString *{ + return @"💩 Heap Objects"; + }; + viewControllerFuture = ^UIViewController *{ + return [[FLEXLiveObjectsTableViewController alloc] init]; + }; + + break; + + case FLEXGlobalsRowAppDelegate: + titleFuture = ^NSString *{ + return [NSString stringWithFormat:@"👉 %@", [[[UIApplication sharedApplication] delegate] class]]; + }; + viewControllerFuture = ^UIViewController *{ + id appDelegate = [[UIApplication sharedApplication] delegate]; + return [FLEXObjectExplorerFactory explorerViewControllerForObject:appDelegate]; + }; + break; + + case FLEXGlobalsRowRootViewController: + titleFuture = ^NSString *{ + return [NSString stringWithFormat:@"🌴 %@", [[s_applicationWindow rootViewController] class]]; + }; + viewControllerFuture = ^UIViewController *{ + UIViewController *rootViewController = [s_applicationWindow rootViewController]; + return [FLEXObjectExplorerFactory explorerViewControllerForObject:rootViewController]; + }; + break; + + case FLEXGlobalsRowUserDefaults: + titleFuture = ^NSString *{ + return @"🚶 +[NSUserDefaults standardUserDefaults]"; + }; + viewControllerFuture = ^UIViewController *{ + NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults]; + return [FLEXObjectExplorerFactory explorerViewControllerForObject:standardUserDefaults]; + }; + break; + + case FLEXGlobalsRowApplication: + titleFuture = ^NSString *{ + return @"💾 +[UIApplication sharedApplication]"; + }; + viewControllerFuture = ^UIViewController *{ + UIApplication *sharedApplication = [UIApplication sharedApplication]; + return [FLEXObjectExplorerFactory explorerViewControllerForObject:sharedApplication]; + }; + break; + + case FLEXGlobalsRowKeyWindow: + titleFuture = ^NSString *{ + return @"🔑 -[UIApplication keyWindow]"; + }; + viewControllerFuture = ^UIViewController *{ + return [FLEXObjectExplorerFactory explorerViewControllerForObject:s_applicationWindow]; + }; + break; + + case FLEXGlobalsRowMainScreen: + titleFuture = ^NSString *{ + return @"💻 +[UIScreen mainScreen]"; + }; + viewControllerFuture = ^UIViewController *{ + UIScreen *mainScreen = [UIScreen mainScreen]; + return [FLEXObjectExplorerFactory explorerViewControllerForObject:mainScreen]; + }; + break; + + case FLEXGlobalsRowCurrentDevice: + titleFuture = ^NSString *{ + return @"📱 +[UIDevice currentDevice]"; + }; + viewControllerFuture = ^UIViewController *{ + UIDevice *currentDevice = [UIDevice currentDevice]; + return [FLEXObjectExplorerFactory explorerViewControllerForObject:currentDevice]; + }; + break; + + case FLEXGlobalsCookies: + titleFuture = ^NSString *{ + return @"🍪 Cookies"; + }; + viewControllerFuture = ^UIViewController *{ + return [[FLEXCookiesTableViewController alloc] init]; + }; + break; + + case FLEXGlobalsRowFileBrowser: + titleFuture = ^NSString *{ + return @"📁 File Browser"; + }; + viewControllerFuture = ^UIViewController *{ + return [[FLEXFileBrowserTableViewController alloc] init]; + }; + break; + + case FLEXGlobalsRowSystemLog: + titleFuture = ^{ + return @"⚠️ System Log"; + }; + viewControllerFuture = ^{ + return [[FLEXSystemLogTableViewController alloc] init]; + }; + break; + + case FLEXGlobalsRowNetworkHistory: + titleFuture = ^{ + return @"📡 Network History"; + }; + viewControllerFuture = ^{ + return [[FLEXNetworkHistoryTableViewController alloc] init]; + }; + break; + case FLEXGlobalsRowCount: + break; + } + + NSParameterAssert(titleFuture); + NSParameterAssert(viewControllerFuture); + + [defaultGlobalEntries addObject:[FLEXGlobalsTableViewControllerEntry entryWithNameFuture:titleFuture viewControllerFuture:viewControllerFuture]]; + } + + return defaultGlobalEntries; +} + +- (id)initWithStyle:(UITableViewStyle)style +{ + self = [super initWithStyle:style]; + if (self) { + self.title = @"💪 FLEX"; + _entries = [[[self class] defaultGlobalEntries] arrayByAddingObjectsFromArray:[FLEXManager sharedManager].userGlobalEntries]; + } + return self; +} + +#pragma mark - Public + ++ (void)setApplicationWindow:(UIWindow *)applicationWindow +{ + s_applicationWindow = applicationWindow; +} + +#pragma mark - UIViewController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donePressed:)]; +} + +#pragma mark - + +- (void)donePressed:(id)sender +{ + [self.delegate globalsViewControllerDidFinish:self]; +} + +#pragma mark - Table Data Helpers + +- (FLEXGlobalsTableViewControllerEntry *)globalEntryAtIndexPath:(NSIndexPath *)indexPath +{ + return self.entries[indexPath.row]; +} + +- (NSString *)titleForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXGlobalsTableViewControllerEntry *entry = [self globalEntryAtIndexPath:indexPath]; + + return entry.entryNameFuture(); +} + +- (UIViewController *)viewControllerToPushForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXGlobalsTableViewControllerEntry *entry = [self globalEntryAtIndexPath:indexPath]; + + return entry.viewControllerFuture(); +} + +#pragma mark - Table View Data Source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return [self.entries count]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *CellIdentifier = @"Cell"; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; + if (!cell) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; + cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + cell.textLabel.font = [FLEXUtility defaultFontOfSize:14.0]; + } + + cell.textLabel.text = [self titleForRowAtIndexPath:indexPath]; + + return cell; +} + + +#pragma mark - Table View Delegate + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + UIViewController *viewControllerToPush = [self viewControllerToPushForRowAtIndexPath:indexPath]; + + [self.navigationController pushViewController:viewControllerToPush animated:YES]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXInstancesTableViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXInstancesTableViewController.h new file mode 100644 index 0000000000..b8e6d8f4ab --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXInstancesTableViewController.h @@ -0,0 +1,16 @@ +// +// FLEXInstancesTableViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@interface FLEXInstancesTableViewController : UITableViewController + ++ (instancetype)instancesTableViewControllerForClassName:(NSString *)className; ++ (instancetype)instancesTableViewControllerForInstancesReferencingObject:(id)object; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXInstancesTableViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXInstancesTableViewController.m new file mode 100644 index 0000000000..b802dce521 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXInstancesTableViewController.m @@ -0,0 +1,130 @@ +// +// FLEXInstancesTableViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXInstancesTableViewController.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXObjectExplorerViewController.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXUtility.h" +#import "FLEXHeapEnumerator.h" +#import + + +@interface FLEXInstancesTableViewController () + +@property (nonatomic, strong) NSArray *instances; +@property (nonatomic, strong) NSArray *fieldNames; + +@end + +@implementation FLEXInstancesTableViewController + ++ (instancetype)instancesTableViewControllerForClassName:(NSString *)className +{ + const char *classNameCString = [className UTF8String]; + NSMutableArray *instances = [NSMutableArray array]; + [FLEXHeapEnumerator enumerateLiveObjectsUsingBlock:^(__unsafe_unretained id object, __unsafe_unretained Class actualClass) { + if (strcmp(classNameCString, class_getName(actualClass)) == 0) { + // Note: objects of certain classes crash when retain is called. It is up to the user to avoid tapping into instance lists for these classes. + // Ex. OS_dispatch_queue_specific_queue + // In the future, we could provide some kind of warning for classes that are known to be problematic. + if (malloc_size((__bridge const void *)(object)) > 0) { + [instances addObject:object]; + } + } + }]; + FLEXInstancesTableViewController *instancesViewController = [[self alloc] init]; + instancesViewController.instances = instances; + instancesViewController.title = [NSString stringWithFormat:@"%@ (%lu)", className, (unsigned long)[instances count]]; + return instancesViewController; +} + ++ (instancetype)instancesTableViewControllerForInstancesReferencingObject:(id)object +{ + NSMutableArray *instances = [NSMutableArray array]; + NSMutableArray *fieldNames = [NSMutableArray array]; + [FLEXHeapEnumerator enumerateLiveObjectsUsingBlock:^(__unsafe_unretained id tryObject, __unsafe_unretained Class actualClass) { + // Get all the ivars on the object. Start with the class and and travel up the inheritance chain. + // Once we find a match, record it and move on to the next object. There's no reason to find multiple matches within the same object. + Class tryClass = actualClass; + while (tryClass) { + unsigned int ivarCount = 0; + Ivar *ivars = class_copyIvarList(tryClass, &ivarCount); + for (unsigned int ivarIndex = 0; ivarIndex < ivarCount; ivarIndex++) { + Ivar ivar = ivars[ivarIndex]; + const char *typeEncoding = ivar_getTypeEncoding(ivar); + if (typeEncoding[0] == @encode(id)[0] || typeEncoding[0] == @encode(Class)[0]) { + ptrdiff_t offset = ivar_getOffset(ivar); + uintptr_t *fieldPointer = (__bridge void *)tryObject + offset; + if (*fieldPointer == (uintptr_t)(__bridge void *)object) { + [instances addObject:tryObject]; + [fieldNames addObject:@(ivar_getName(ivar))]; + return; + } + } + } + tryClass = class_getSuperclass(tryClass); + } + }]; + FLEXInstancesTableViewController *instancesViewController = [[self alloc] init]; + instancesViewController.instances = instances; + instancesViewController.fieldNames = fieldNames; + instancesViewController.title = [NSString stringWithFormat:@"Referencing %@ %p", NSStringFromClass(object_getClass(object)), object]; + return instancesViewController; +} + + +#pragma mark - Table View Data Source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return [self.instances count]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *CellIdentifier = @"Cell"; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; + if (!cell) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; + cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + UIFont *cellFont = [FLEXUtility defaultTableViewCellLabelFont]; + cell.textLabel.font = cellFont; + cell.detailTextLabel.font = cellFont; + cell.detailTextLabel.textColor = [UIColor grayColor]; + } + + id instance = self.instances[indexPath.row]; + NSString *title = nil; + if ((NSInteger)[self.fieldNames count] > indexPath.row) { + title = [NSString stringWithFormat:@"%@ %@", NSStringFromClass(object_getClass(instance)), self.fieldNames[indexPath.row]]; + } else { + title = [NSString stringWithFormat:@"%@ %p", NSStringFromClass(object_getClass(instance)), instance]; + } + cell.textLabel.text = title; + cell.detailTextLabel.text = [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:instance]; + + return cell; +} + + +#pragma mark - Table View Delegate + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + id instance = self.instances[indexPath.row]; + FLEXObjectExplorerViewController *drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:instance]; + [self.navigationController pushViewController:drillInViewController animated:YES]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLibrariesTableViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLibrariesTableViewController.h new file mode 100644 index 0000000000..a67783ca24 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLibrariesTableViewController.h @@ -0,0 +1,13 @@ +// +// FLEXLibrariesTableViewController.h +// Flipboard +// +// Created by Ryan Olson on 2014-05-02. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@interface FLEXLibrariesTableViewController : UITableViewController + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLibrariesTableViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLibrariesTableViewController.m new file mode 100644 index 0000000000..849238e3bc --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLibrariesTableViewController.m @@ -0,0 +1,177 @@ +// +// FLEXLibrariesTableViewController.m +// Flipboard +// +// Created by Ryan Olson on 2014-05-02. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXLibrariesTableViewController.h" +#import "FLEXUtility.h" +#import "FLEXClassesTableViewController.h" +#import "FLEXClassExplorerViewController.h" +#import + +@interface FLEXLibrariesTableViewController () + +@property (nonatomic, strong) NSArray *imageNames; +@property (nonatomic, strong) NSArray *filteredImageNames; + +@property (nonatomic, strong) UISearchBar *searchBar; +@property (nonatomic, strong) Class foundClass; + +@end + +@implementation FLEXLibrariesTableViewController + +- (id)initWithStyle:(UITableViewStyle)style +{ + self = [super initWithStyle:style]; + if (self) { + [self loadImageNames]; + } + return self; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.searchBar = [[UISearchBar alloc] init]; + self.searchBar.delegate = self; + self.searchBar.placeholder = [FLEXUtility searchBarPlaceholderText]; + [self.searchBar sizeToFit]; + self.tableView.tableHeaderView = self.searchBar; +} + + +#pragma mark - Binary Images + +- (void)loadImageNames +{ + unsigned int imageNamesCount = 0; + const char **imageNames = objc_copyImageNames(&imageNamesCount); + if (imageNames) { + NSMutableArray *imageNameStrings = [NSMutableArray array]; + NSString *appImageName = [FLEXUtility applicationImageName]; + for (unsigned int i = 0; i < imageNamesCount; i++) { + const char *imageName = imageNames[i]; + NSString *imageNameString = [NSString stringWithUTF8String:imageName]; + // Skip the app's image. We're just showing system libraries and frameworks. + if (![imageNameString isEqual:appImageName]) { + [imageNameStrings addObject:imageNameString]; + } + } + + // Sort alphabetically + self.imageNames = [imageNameStrings sortedArrayWithOptions:0 usingComparator:^NSComparisonResult(NSString *name1, NSString *name2) { + NSString *shortName1 = [self shortNameForImageName:name1]; + NSString *shortName2 = [self shortNameForImageName:name2]; + return [shortName1 caseInsensitiveCompare:shortName2]; + }]; + + free(imageNames); + } +} + +- (NSString *)shortNameForImageName:(NSString *)imageName +{ + NSArray *components = [imageName componentsSeparatedByString:@"/"]; + if (components.count >= 2) { + return [NSString stringWithFormat:@"%@/%@", components[components.count - 2], components[components.count - 1]]; + } + return imageName.lastPathComponent; +} + +- (void)setImageNames:(NSArray *)imageNames +{ + if (![_imageNames isEqual:imageNames]) { + _imageNames = imageNames; + self.filteredImageNames = imageNames; + } +} + + +#pragma mark - Filtering + +- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText +{ + if ([searchText length] > 0) { + NSPredicate *searchPreidcate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) { + BOOL matches = NO; + NSString *shortName = [self shortNameForImageName:evaluatedObject]; + if ([shortName rangeOfString:searchText options:NSCaseInsensitiveSearch].length > 0) { + matches = YES; + } + return matches; + }]; + self.filteredImageNames = [self.imageNames filteredArrayUsingPredicate:searchPreidcate]; + } else { + self.filteredImageNames = self.imageNames; + } + + self.foundClass = NSClassFromString(searchText); + [self.tableView reloadData]; +} + +- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar +{ + [searchBar resignFirstResponder]; +} + + +#pragma mark - Table View Data Source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return self.filteredImageNames.count + (self.foundClass ? 1 : 0); +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *cellIdentifier = @"Cell"; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; + if (!cell) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; + cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + cell.textLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + } + + NSString *executablePath; + if (self.foundClass) { + if (indexPath.row == 0) { + cell.textLabel.text = [NSString stringWithFormat:@"Class \"%@\"", self.searchBar.text]; + return cell; + } else { + executablePath = self.filteredImageNames[indexPath.row-1]; + } + } else { + executablePath = self.filteredImageNames[indexPath.row]; + } + + cell.textLabel.text = [self shortNameForImageName:executablePath]; + return cell; +} + + +#pragma mark - Table View Delegate + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + if (indexPath.row == 0 && self.foundClass) { + FLEXClassExplorerViewController *objectExplorer = [FLEXClassExplorerViewController new]; + objectExplorer.object = self.foundClass; + [self.navigationController pushViewController:objectExplorer animated:YES]; + } else { + FLEXClassesTableViewController *classesViewController = [[FLEXClassesTableViewController alloc] init]; + classesViewController.binaryImageName = self.filteredImageNames[self.foundClass ? indexPath.row-1 : indexPath.row]; + [self.navigationController pushViewController:classesViewController animated:YES]; + } +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLiveObjectsTableViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLiveObjectsTableViewController.h new file mode 100644 index 0000000000..bf7a8d7fdf --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLiveObjectsTableViewController.h @@ -0,0 +1,13 @@ +// +// FLEXLiveObjectsTableViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@interface FLEXLiveObjectsTableViewController : UITableViewController + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLiveObjectsTableViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLiveObjectsTableViewController.m new file mode 100644 index 0000000000..e414b9c629 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXLiveObjectsTableViewController.m @@ -0,0 +1,208 @@ +// +// FLEXLiveObjectsTableViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXLiveObjectsTableViewController.h" +#import "FLEXHeapEnumerator.h" +#import "FLEXInstancesTableViewController.h" +#import "FLEXUtility.h" +#import + +static const NSInteger kFLEXLiveObjectsSortAlphabeticallyIndex = 0; +static const NSInteger kFLEXLiveObjectsSortByCountIndex = 1; + +@interface FLEXLiveObjectsTableViewController () + +@property (nonatomic, strong) NSDictionary *instanceCountsForClassNames; +@property (nonatomic, readonly) NSArray *allClassNames; +@property (nonatomic, strong) NSArray *filteredClassNames; +@property (nonatomic, strong) UISearchBar *searchBar; + +@end + +@implementation FLEXLiveObjectsTableViewController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.searchBar = [[UISearchBar alloc] init]; + self.searchBar.placeholder = [FLEXUtility searchBarPlaceholderText]; + self.searchBar.delegate = self; + self.searchBar.showsScopeBar = YES; + self.searchBar.scopeButtonTitles = @[@"Sort Alphabetically", @"Sort by Count"]; + [self.searchBar sizeToFit]; + self.tableView.tableHeaderView = self.searchBar; + + self.refreshControl = [[UIRefreshControl alloc] init]; + [self.refreshControl addTarget:self action:@selector(refreshControlDidRefresh:) forControlEvents:UIControlEventValueChanged]; + + [self reloadTableData]; +} + +- (NSArray *)allClassNames +{ + return [self.instanceCountsForClassNames allKeys]; +} + +- (void)reloadTableData +{ + // Set up a CFMutableDictionary with class pointer keys and NSUInteger values. + // We abuse CFMutableDictionary a little to have primitive keys through judicious casting, but it gets the job done. + // The dictionary is intialized with a 0 count for each class so that it doesn't have to expand during enumeration. + // While it might be a little cleaner to populate an NSMutableDictionary with class name string keys to NSNumber counts, + // we choose the CF/primitives approach because it lets us enumerate the objects in the heap without allocating any memory during enumeration. + // The alternative of creating one NSString/NSNumber per object on the heap ends up polluting the count of live objects quite a bit. + unsigned int classCount = 0; + Class *classes = objc_copyClassList(&classCount); + CFMutableDictionaryRef mutableCountsForClasses = CFDictionaryCreateMutable(NULL, classCount, NULL, NULL); + for (unsigned int i = 0; i < classCount; i++) { + CFDictionarySetValue(mutableCountsForClasses, (__bridge const void *)classes[i], (const void *)0); + } + + // Enumerate all objects on the heap to build the counts of instances for each class. + [FLEXHeapEnumerator enumerateLiveObjectsUsingBlock:^(__unsafe_unretained id object, __unsafe_unretained Class actualClass) { + NSUInteger instanceCount = (NSUInteger)CFDictionaryGetValue(mutableCountsForClasses, (__bridge const void *)actualClass); + instanceCount++; + CFDictionarySetValue(mutableCountsForClasses, (__bridge const void *)actualClass, (const void *)instanceCount); + }]; + + // Convert our CF primitive dictionary into a nicer mapping of class name strings to counts that we will use as the table's model. + NSMutableDictionary *mutableCountsForClassNames = [NSMutableDictionary dictionary]; + for (unsigned int i = 0; i < classCount; i++) { + Class class = classes[i]; + NSUInteger instanceCount = (NSUInteger)CFDictionaryGetValue(mutableCountsForClasses, (__bridge const void *)(class)); + if (instanceCount > 0) { + NSString *className = @(class_getName(class)); + [mutableCountsForClassNames setObject:@(instanceCount) forKey:className]; + } + } + free(classes); + + self.instanceCountsForClassNames = mutableCountsForClassNames; + + [self updateTableDataForSearchFilter]; +} + +- (void)refreshControlDidRefresh:(id)sender +{ + [self reloadTableData]; + [self.refreshControl endRefreshing]; +} + +- (void)updateTitle +{ + NSString *title = @"Live Objects"; + + NSUInteger totalCount = 0; + for (NSString *className in self.allClassNames) { + totalCount += [self.instanceCountsForClassNames[className] unsignedIntegerValue]; + } + NSUInteger filteredCount = 0; + for (NSString *className in self.filteredClassNames) { + filteredCount += [self.instanceCountsForClassNames[className] unsignedIntegerValue]; + } + + if (filteredCount == totalCount) { + // Unfiltered + title = [title stringByAppendingFormat:@" (%lu)", (unsigned long)totalCount]; + } else { + title = [title stringByAppendingFormat:@" (filtered, %lu)", (unsigned long)filteredCount]; + } + + self.title = title; +} + + +#pragma mark - Search + +- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText +{ + [self updateTableDataForSearchFilter]; +} + +- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar +{ + [searchBar resignFirstResponder]; +} + +- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope +{ + [self updateTableDataForSearchFilter]; +} + +- (void)scrollViewDidScroll:(UIScrollView *)scrollView +{ + // Dismiss the keyboard when interacting with filtered results. + [self.searchBar endEditing:YES]; +} + +- (void)updateTableDataForSearchFilter +{ + if ([self.searchBar.text length] > 0) { + NSPredicate *searchPreidcate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", self.searchBar.text]; + self.filteredClassNames = [self.allClassNames filteredArrayUsingPredicate:searchPreidcate]; + } else { + self.filteredClassNames = self.allClassNames; + } + + if (self.searchBar.selectedScopeButtonIndex == kFLEXLiveObjectsSortAlphabeticallyIndex) { + self.filteredClassNames = [self.filteredClassNames sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; + } else if (self.searchBar.selectedScopeButtonIndex == kFLEXLiveObjectsSortByCountIndex) { + self.filteredClassNames = [self.filteredClassNames sortedArrayUsingComparator:^NSComparisonResult(NSString *className1, NSString *className2) { + NSNumber *count1 = self.instanceCountsForClassNames[className1]; + NSNumber *count2 = self.instanceCountsForClassNames[className2]; + // Reversed for descending counts. + return [count2 compare:count1]; + }]; + } + + [self updateTitle]; + [self.tableView reloadData]; +} + + +#pragma mark - Table view data source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return [self.filteredClassNames count]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *CellIdentifier = @"Cell"; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; + if (!cell) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; + cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + cell.textLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + } + + NSString *className = self.filteredClassNames[indexPath.row]; + NSNumber *count = self.instanceCountsForClassNames[className]; + cell.textLabel.text = [NSString stringWithFormat:@"%@ (%ld)", className, (long)[count integerValue]]; + + return cell; +} + + +#pragma mark - Table view delegate + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + NSString *className = self.filteredClassNames[indexPath.row]; + FLEXInstancesTableViewController *instancesViewController = [FLEXInstancesTableViewController instancesTableViewControllerForClassName:className]; + [self.navigationController pushViewController:instancesViewController animated:YES]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXWebViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXWebViewController.h new file mode 100644 index 0000000000..86c73dcb92 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXWebViewController.h @@ -0,0 +1,18 @@ +// +// FLEXWebViewController.m +// Flipboard +// +// Created by Ryan Olson on 6/10/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@interface FLEXWebViewController : UIViewController + +- (id)initWithURL:(NSURL *)url; +- (id)initWithText:(NSString *)text; + ++ (BOOL)supportsPathExtension:(NSString *)extension; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/FLEXWebViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXWebViewController.m new file mode 100644 index 0000000000..51fdc7fe8b --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/FLEXWebViewController.m @@ -0,0 +1,127 @@ +// +// FLEXWebViewController.m +// Flipboard +// +// Created by Ryan Olson on 6/10/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXWebViewController.h" +#import "FLEXUtility.h" + +@interface FLEXWebViewController () + +@property (nonatomic, strong) UIWebView *webView; +@property (nonatomic, strong) NSString *originalText; + +@end + +@implementation FLEXWebViewController + +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil +{ + self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; + if (self) { + self.webView = [[UIWebView alloc] init]; + self.webView.delegate = self; + self.webView.dataDetectorTypes = UIDataDetectorTypeLink; + self.webView.scalesPageToFit = YES; + } + return self; +} + +- (id)initWithText:(NSString *)text +{ + self = [self initWithNibName:nil bundle:nil]; + if (self) { + self.originalText = text; + NSString *htmlString = [NSString stringWithFormat:@"
%@
", [FLEXUtility stringByEscapingHTMLEntitiesInString:text]]; + [self.webView loadHTMLString:htmlString baseURL:nil]; + } + return self; +} + +- (id)initWithURL:(NSURL *)url +{ + self = [self initWithNibName:nil bundle:nil]; + if (self) { + NSURLRequest *request = [NSURLRequest requestWithURL:url]; + [self.webView loadRequest:request]; + } + return self; +} + +- (void)dealloc +{ + // UIWebView's delegate is assign so we need to clear it manually. + if (_webView.delegate == self) { + _webView.delegate = nil; + } +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + [self.view addSubview:self.webView]; + self.webView.frame = self.view.bounds; + self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + + if ([self.originalText length] > 0) { + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Copy" style:UIBarButtonItemStylePlain target:self action:@selector(copyButtonTapped:)]; + } +} + +- (void)copyButtonTapped:(id)sender +{ + [[UIPasteboard generalPasteboard] setString:self.originalText]; +} + + +#pragma mark - UIWebView Delegate + +- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType +{ + BOOL shouldStart = NO; + if (navigationType == UIWebViewNavigationTypeOther) { + // Allow the initial load + shouldStart = YES; + } else { + // For clicked links, push another web view controller onto the navigation stack so that hitting the back button works as expected. + // Don't allow the current web view do handle the navigation. + FLEXWebViewController *webVC = [[[self class] alloc] initWithURL:[request URL]]; + webVC.title = [[request URL] absoluteString]; + [self.navigationController pushViewController:webVC animated:YES]; + } + return shouldStart; +} + + +#pragma mark - Class Helpers + ++ (BOOL)supportsPathExtension:(NSString *)extension +{ + BOOL supported = NO; + NSSet *supportedExtensions = [self webViewSupportedPathExtensions]; + if ([supportedExtensions containsObject:[extension lowercaseString]]) { + supported = YES; + } + return supported; +} + ++ (NSSet *)webViewSupportedPathExtensions +{ + static NSSet *pathExtenstions = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // Note that this is not exhaustive, but all these extensions should work well in the web view. + // See https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/CreatingContentforSafarioniPhone/CreatingContentforSafarioniPhone.html#//apple_ref/doc/uid/TP40006482-SW7 + pathExtenstions = [NSSet setWithArray:@[@"jpg", @"jpeg", @"png", @"gif", @"pdf", @"svg", @"tiff", @"3gp", @"3gpp", @"3g2", + @"3gp2", @"aiff", @"aif", @"aifc", @"cdda", @"amr", @"mp3", @"swa", @"mp4", @"mpeg", + @"mpg", @"mp3", @"wav", @"bwf", @"m4a", @"m4b", @"m4p", @"mov", @"qt", @"mqv", @"m4v"]]; + + }); + return pathExtenstions; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogMessage.h b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogMessage.h new file mode 100644 index 0000000000..32d041931f --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogMessage.h @@ -0,0 +1,21 @@ +// +// FLEXSystemLogMessage.h +// UICatalog +// +// Created by Ryan Olson on 1/25/15. +// Copyright (c) 2015 f. All rights reserved. +// + +#import +#import + +@interface FLEXSystemLogMessage : NSObject + ++ (instancetype)logMessageFromASLMessage:(aslmsg)aslMessage; + +@property (nonatomic, strong) NSDate *date; +@property (nonatomic, copy) NSString *sender; +@property (nonatomic, copy) NSString *messageText; +@property (nonatomic, assign) long long messageID; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogMessage.m b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogMessage.m new file mode 100644 index 0000000000..785b61997a --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogMessage.m @@ -0,0 +1,55 @@ +// +// FLEXSystemLogMessage.m +// UICatalog +// +// Created by Ryan Olson on 1/25/15. +// Copyright (c) 2015 f. All rights reserved. +// + +#import "FLEXSystemLogMessage.h" + +@implementation FLEXSystemLogMessage + ++(instancetype)logMessageFromASLMessage:(aslmsg)aslMessage +{ + FLEXSystemLogMessage *logMessage = [[FLEXSystemLogMessage alloc] init]; + + const char *timestamp = asl_get(aslMessage, ASL_KEY_TIME); + if (timestamp) { + NSTimeInterval timeInterval = [@(timestamp) integerValue]; + const char *nanoseconds = asl_get(aslMessage, ASL_KEY_TIME_NSEC); + if (nanoseconds) { + timeInterval += [@(nanoseconds) doubleValue] / NSEC_PER_SEC; + } + logMessage.date = [NSDate dateWithTimeIntervalSince1970:timeInterval]; + } + + const char *sender = asl_get(aslMessage, ASL_KEY_SENDER); + if (sender) { + logMessage.sender = @(sender); + } + + const char *messageText = asl_get(aslMessage, ASL_KEY_MSG); + if (messageText) { + logMessage.messageText = @(messageText); + } + + const char *messageID = asl_get(aslMessage, ASL_KEY_MSG_ID); + if (messageID) { + logMessage.messageID = [@(messageID) longLongValue]; + } + + return logMessage; +} + +- (BOOL)isEqual:(id)object +{ + return [object isKindOfClass:[FLEXSystemLogMessage class]] && self.messageID == [object messageID]; +} + +- (NSUInteger)hash +{ + return (NSUInteger)self.messageID; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewCell.h b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewCell.h new file mode 100644 index 0000000000..eff562ab37 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewCell.h @@ -0,0 +1,23 @@ +// +// FLEXSystemLogTableViewCell.h +// UICatalog +// +// Created by Ryan Olson on 1/25/15. +// Copyright (c) 2015 f. All rights reserved. +// + +#import + +@class FLEXSystemLogMessage; + +extern NSString *const kFLEXSystemLogTableViewCellIdentifier; + +@interface FLEXSystemLogTableViewCell : UITableViewCell + +@property (nonatomic, strong) FLEXSystemLogMessage *logMessage; +@property (nonatomic, copy) NSString *highlightedText; + ++ (NSString *)displayedTextForLogMessage:(FLEXSystemLogMessage *)logMessage; ++ (CGFloat)preferredHeightForLogMessage:(FLEXSystemLogMessage *)logMessage inWidth:(CGFloat)width; + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewCell.m b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewCell.m new file mode 100644 index 0000000000..dbeb62fde6 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewCell.m @@ -0,0 +1,128 @@ +// +// FLEXSystemLogTableViewCell.m +// UICatalog +// +// Created by Ryan Olson on 1/25/15. +// Copyright (c) 2015 f. All rights reserved. +// + +#import "FLEXSystemLogTableViewCell.h" +#import "FLEXSystemLogMessage.h" + +NSString *const kFLEXSystemLogTableViewCellIdentifier = @"FLEXSystemLogTableViewCellIdentifier"; + +@interface FLEXSystemLogTableViewCell () + +@property (nonatomic, strong) UILabel *logMessageLabel; +@property (nonatomic, strong) NSAttributedString *logMessageAttributedText; + +@end + +@implementation FLEXSystemLogTableViewCell + +- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier +{ + self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; + if (self) { + self.logMessageLabel = [[UILabel alloc] init]; + self.logMessageLabel.numberOfLines = 0; + self.separatorInset = UIEdgeInsetsZero; + self.selectionStyle = UITableViewCellSelectionStyleNone; + [self.contentView addSubview:self.logMessageLabel]; + } + return self; +} + +- (void)setLogMessage:(FLEXSystemLogMessage *)logMessage +{ + if (![_logMessage isEqual:logMessage]) { + _logMessage = logMessage; + self.logMessageAttributedText = nil; + [self setNeedsLayout]; + } +} + +- (void)setHighlightedText:(NSString *)highlightedText +{ + if (![_highlightedText isEqual:highlightedText]) { + _highlightedText = highlightedText; + self.logMessageAttributedText = nil; + [self setNeedsLayout]; + } +} + +- (NSAttributedString *)logMessageAttributedText +{ + if (!_logMessageAttributedText) { + _logMessageAttributedText = [[self class] attributedTextForLogMessage:self.logMessage highlightedText:self.highlightedText]; + } + return _logMessageAttributedText; +} + +static const UIEdgeInsets kFLEXLogMessageCellInsets = {10.0, 10.0, 10.0, 10.0}; + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + self.logMessageLabel.attributedText = self.logMessageAttributedText; + self.logMessageLabel.frame = UIEdgeInsetsInsetRect(self.contentView.bounds, kFLEXLogMessageCellInsets); +} + +#pragma mark - Stateless helpers + ++ (NSAttributedString *)attributedTextForLogMessage:(FLEXSystemLogMessage *)logMessage highlightedText:(NSString *)highlightedText +{ + NSString *text = [self displayedTextForLogMessage:logMessage]; + NSDictionary *attributes = @{ NSFontAttributeName : [UIFont fontWithName:@"CourierNewPSMT" size:12.0] }; + NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes]; + + if ([highlightedText length] > 0) { + NSMutableAttributedString *mutableAttributedText = [attributedText mutableCopy]; + NSMutableDictionary *highlightAttributes = [@{ NSBackgroundColorAttributeName : [UIColor yellowColor] } mutableCopy]; + [highlightAttributes addEntriesFromDictionary:attributes]; + + NSRange remainingSearchRange = NSMakeRange(0, text.length); + while (remainingSearchRange.location < text.length) { + remainingSearchRange.length = text.length - remainingSearchRange.location; + NSRange foundRange = [text rangeOfString:highlightedText options:NSCaseInsensitiveSearch range:remainingSearchRange]; + if (foundRange.location != NSNotFound) { + remainingSearchRange.location = foundRange.location + foundRange.length; + [mutableAttributedText setAttributes:highlightAttributes range:foundRange]; + } else { + break; + } + } + attributedText = mutableAttributedText; + } + + return attributedText; +} + ++ (NSString *)displayedTextForLogMessage:(FLEXSystemLogMessage *)logMessage +{ + return [NSString stringWithFormat:@"%@: %@", [self logTimeStringFromDate:logMessage.date], logMessage.messageText]; +} + ++ (CGFloat)preferredHeightForLogMessage:(FLEXSystemLogMessage *)logMessage inWidth:(CGFloat)width +{ + UIEdgeInsets insets = kFLEXLogMessageCellInsets; + CGFloat availableWidth = width - insets.left - insets.right; + NSAttributedString *attributedLogText = [self attributedTextForLogMessage:logMessage highlightedText:nil]; + CGSize labelSize = [attributedLogText boundingRectWithSize:CGSizeMake(availableWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size; + return labelSize.height + insets.top + insets.bottom; +} + ++ (NSString *)logTimeStringFromDate:(NSDate *)date +{ + static NSDateFormatter *formatter = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + formatter = [[NSDateFormatter alloc] init]; + formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS"; + }); + + return [formatter stringFromDate:date]; +} + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewController.h b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewController.h new file mode 100644 index 0000000000..ca9f52195b --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewController.h @@ -0,0 +1,13 @@ +// +// FLEXSystemLogTableViewController.h +// UICatalog +// +// Created by Ryan Olson on 1/19/15. +// Copyright (c) 2015 f. All rights reserved. +// + +#import + +@interface FLEXSystemLogTableViewController : UITableViewController + +@end diff --git a/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewController.m b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewController.m new file mode 100644 index 0000000000..b1e5b65390 --- /dev/null +++ b/Pods/FLEX/Classes/GlobalStateExplorers/SystemLog/FLEXSystemLogTableViewController.m @@ -0,0 +1,192 @@ +// +// FLEXSystemLogTableViewController.m +// UICatalog +// +// Created by Ryan Olson on 1/19/15. +// Copyright (c) 2015 f. All rights reserved. +// + +#import "FLEXSystemLogTableViewController.h" +#import "FLEXUtility.h" +#import "FLEXSystemLogMessage.h" +#import "FLEXSystemLogTableViewCell.h" +#import + +@interface FLEXSystemLogTableViewController () + +@property (nonatomic, strong) UISearchController *searchController; +@property (nonatomic, copy) NSArray *logMessages; +@property (nonatomic, copy) NSArray *filteredLogMessages; +@property (nonatomic, strong) NSTimer *logUpdateTimer; + +@end + +@implementation FLEXSystemLogTableViewController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + [self.tableView registerClass:[FLEXSystemLogTableViewCell class] forCellReuseIdentifier:kFLEXSystemLogTableViewCellIdentifier]; + self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; + self.title = @"Loading..."; + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@" ⬇︎ " style:UIBarButtonItemStylePlain target:self action:@selector(scrollToLastRow)]; + + self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; + self.searchController.delegate = self; + self.searchController.searchResultsUpdater = self; + self.searchController.dimsBackgroundDuringPresentation = NO; + self.tableView.tableHeaderView = self.searchController.searchBar; + + [self updateLogMessages]; +} + +- (void)viewWillAppear:(BOOL)animated +{ + [super viewWillAppear:animated]; + + NSTimeInterval updateInterval = 1.0; + +#if TARGET_IPHONE_SIMULATOR + // Querrying the ASL is much slower in the simulator. We need a longer polling interval to keep things repsonsive. + updateInterval = 5.0; +#endif + + self.logUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:updateInterval target:self selector:@selector(updateLogMessages) userInfo:nil repeats:YES]; +} + +- (void)viewWillDisappear:(BOOL)animated +{ + [super viewWillDisappear:animated]; + + [self.logUpdateTimer invalidate]; +} + +- (void)updateLogMessages +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + NSArray *logMessages = [[self class] allLogMessagesForCurrentProcess]; + dispatch_async(dispatch_get_main_queue(), ^{ + self.title = @"System Log"; + self.logMessages = logMessages; + + // "Follow" the log as new messages stream in if we were previously near the bottom. + BOOL wasNearBottom = self.tableView.contentOffset.y >= self.tableView.contentSize.height - self.tableView.frame.size.height - 100.0; + [self.tableView reloadData]; + if (wasNearBottom) { + [self scrollToLastRow]; + } + }); + }); +} + +- (void)scrollToLastRow +{ + NSInteger numberOfRows = [self.tableView numberOfRowsInSection:0]; + if (numberOfRows > 0) { + NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:numberOfRows - 1 inSection:0]; + [self.tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; + } +} + +#pragma mark - Table view data source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return self.searchController.isActive ? [self.filteredLogMessages count] : [self.logMessages count]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXSystemLogTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXSystemLogTableViewCellIdentifier forIndexPath:indexPath]; + cell.logMessage = [self logMessageAtIndexPath:indexPath]; + cell.highlightedText = self.searchController.searchBar.text; + + if (indexPath.row % 2 == 0) { + cell.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0]; + } else { + cell.backgroundColor = [UIColor whiteColor]; + } + + return cell; +} + +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXSystemLogMessage *logMessage = [self logMessageAtIndexPath:indexPath]; + return [FLEXSystemLogTableViewCell preferredHeightForLogMessage:logMessage inWidth:self.tableView.bounds.size.width]; +} + +#pragma mark - Copy on long press + +- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath +{ + return YES; +} + +- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + return action == @selector(copy:); +} + +- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + if (action == @selector(copy:)) { + FLEXSystemLogMessage *logMessage = [self logMessageAtIndexPath:indexPath]; + NSString *stringToCopy = [FLEXSystemLogTableViewCell displayedTextForLogMessage:logMessage] ?: @""; + [[UIPasteboard generalPasteboard] setString:stringToCopy]; + } +} + +- (FLEXSystemLogMessage *)logMessageAtIndexPath:(NSIndexPath *)indexPath +{ + return self.searchController.isActive ? self.filteredLogMessages[indexPath.row] : self.logMessages[indexPath.row]; +} + +#pragma mark - UISearchResultsUpdating + +- (void)updateSearchResultsForSearchController:(UISearchController *)searchController +{ + NSString *searchString = searchController.searchBar.text; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + NSArray *filteredLogMessages = [self.logMessages filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(FLEXSystemLogMessage *logMessage, NSDictionary *bindings) { + NSString *displayedText = [FLEXSystemLogTableViewCell displayedTextForLogMessage:logMessage]; + return [displayedText rangeOfString:searchString options:NSCaseInsensitiveSearch].length > 0; + }]]; + dispatch_async(dispatch_get_main_queue(), ^{ + if ([searchController.searchBar.text isEqual:searchString]) { + self.filteredLogMessages = filteredLogMessages; + [self.tableView reloadData]; + } + }); + }); +} + +#pragma mark - Log Message Fetching + ++ (NSArray *)allLogMessagesForCurrentProcess +{ + asl_object_t query = asl_new(ASL_TYPE_QUERY); + + // Filter for messages from the current process. Note that this appears to happen by default on device, but is required in the simulator. + NSString *pidString = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]]; + asl_set_query(query, ASL_KEY_PID, [pidString UTF8String], ASL_QUERY_OP_EQUAL); + + aslresponse response = asl_search(NULL, query); + aslmsg aslMessage = NULL; + + NSMutableArray *logMessages = [NSMutableArray array]; + while ((aslMessage = asl_next(response))) { + [logMessages addObject:[FLEXSystemLogMessage logMessageFromASLMessage:aslMessage]]; + } + asl_release(response); + + return logMessages; +} + +@end diff --git a/Pods/FLEX/Classes/Manager/FLEXManager+Private.h b/Pods/FLEX/Classes/Manager/FLEXManager+Private.h new file mode 100644 index 0000000000..e5a25bcc18 --- /dev/null +++ b/Pods/FLEX/Classes/Manager/FLEXManager+Private.h @@ -0,0 +1,16 @@ +// +// FLEXManager+Private.h +// PebbleApp +// +// Created by Javier Soto on 7/26/14. +// Copyright (c) 2014 Pebble Technology. All rights reserved. +// + +#import "FLEXManager.h" + +@interface FLEXManager () + +/// An array of FLEXGlobalsTableViewControllerEntry objects that have been registered by the user. +@property (nonatomic, readonly, strong) NSArray *userGlobalEntries; + +@end diff --git a/Pods/FLEX/Classes/Manager/FLEXManager.m b/Pods/FLEX/Classes/Manager/FLEXManager.m new file mode 100644 index 0000000000..e8d66fe818 --- /dev/null +++ b/Pods/FLEX/Classes/Manager/FLEXManager.m @@ -0,0 +1,360 @@ +// +// FLEXManager.m +// Flipboard +// +// Created by Ryan Olson on 4/4/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXManager.h" +#import "FLEXExplorerViewController.h" +#import "FLEXWindow.h" +#import "FLEXGlobalsTableViewControllerEntry.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXObjectExplorerViewController.h" +#import "FLEXNetworkObserver.h" +#import "FLEXNetworkRecorder.h" +#import "FLEXKeyboardShortcutManager.h" +#import "FLEXFileBrowserTableViewController.h" +#import "FLEXNetworkHistoryTableViewController.h" +#import "FLEXKeyboardHelpViewController.h" + +@interface FLEXManager () + +@property (nonatomic, strong) FLEXWindow *explorerWindow; +@property (nonatomic, strong) FLEXExplorerViewController *explorerViewController; + +@property (nonatomic, readonly, strong) NSMutableArray *userGlobalEntries; + +@end + +@implementation FLEXManager + ++ (instancetype)sharedManager +{ + static FLEXManager *sharedManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedManager = [[[self class] alloc] init]; + }); + return sharedManager; +} + +- (instancetype)init +{ + self = [super init]; + if (self) { + _userGlobalEntries = [[NSMutableArray alloc] init]; + } + return self; +} + +- (FLEXWindow *)explorerWindow +{ + NSAssert([NSThread isMainThread], @"You must use %@ from the main thread only.", NSStringFromClass([self class])); + + if (!_explorerWindow) { + _explorerWindow = [[FLEXWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; + _explorerWindow.eventDelegate = self; + _explorerWindow.rootViewController = self.explorerViewController; + } + + return _explorerWindow; +} + +- (FLEXExplorerViewController *)explorerViewController +{ + if (!_explorerViewController) { + _explorerViewController = [[FLEXExplorerViewController alloc] init]; + _explorerViewController.delegate = self; + } + + return _explorerViewController; +} + +- (void)showExplorer +{ + self.explorerWindow.hidden = NO; +} + +- (void)hideExplorer +{ + self.explorerWindow.hidden = YES; +} + +- (void)toggleExplorer { + if (self.explorerWindow.isHidden) { + [self showExplorer]; + } else { + [self hideExplorer]; + } +} + +- (BOOL)isHidden +{ + return self.explorerWindow.isHidden; +} + +- (BOOL)isNetworkDebuggingEnabled +{ + return [FLEXNetworkObserver isEnabled]; +} + +- (void)setNetworkDebuggingEnabled:(BOOL)networkDebuggingEnabled +{ + [FLEXNetworkObserver setEnabled:networkDebuggingEnabled]; +} + +- (NSUInteger)networkResponseCacheByteLimit +{ + return [[FLEXNetworkRecorder defaultRecorder] responseCacheByteLimit]; +} + +- (void)setNetworkResponseCacheByteLimit:(NSUInteger)networkResponseCacheByteLimit +{ + [[FLEXNetworkRecorder defaultRecorder] setResponseCacheByteLimit:networkResponseCacheByteLimit]; +} + +#pragma mark - FLEXWindowEventDelegate + +- (BOOL)shouldHandleTouchAtPoint:(CGPoint)pointInWindow +{ + // Ask the explorer view controller + return [self.explorerViewController shouldReceiveTouchAtWindowPoint:pointInWindow]; +} + +- (BOOL)canBecomeKeyWindow +{ + // Only when the explorer view controller wants it because it needs to accept key input & affect the status bar. + return [self.explorerViewController wantsWindowToBecomeKey]; +} + + +#pragma mark - FLEXExplorerViewControllerDelegate + +- (void)explorerViewControllerDidFinish:(FLEXExplorerViewController *)explorerViewController +{ + [self hideExplorer]; +} + +#pragma mark - Simulator Shortcuts + +- (void)registerSimulatorShortcutWithKey:(NSString *)key modifiers:(UIKeyModifierFlags)modifiers action:(dispatch_block_t)action description:(NSString *)description +{ +# if TARGET_OS_SIMULATOR + [[FLEXKeyboardShortcutManager sharedManager] registerSimulatorShortcutWithKey:key modifiers:modifiers action:action description:description]; +#endif +} + +- (void)setSimulatorShortcutsEnabled:(BOOL)simulatorShortcutsEnabled +{ +# if TARGET_OS_SIMULATOR + [[FLEXKeyboardShortcutManager sharedManager] setEnabled:simulatorShortcutsEnabled]; +#endif +} + +- (BOOL)simulatorShortcutsEnabled +{ +# if TARGET_OS_SIMULATOR + return [[FLEXKeyboardShortcutManager sharedManager] isEnabled]; +#else + return NO; +#endif +} + +- (void)registerDefaultSimulatorShortcuts +{ + [self registerSimulatorShortcutWithKey:@"f" modifiers:0 action:^{ + [self toggleExplorer]; + } description:@"Toggle FLEX toolbar"]; + + [self registerSimulatorShortcutWithKey:@"g" modifiers:0 action:^{ + [self showExplorerIfNeeded]; + [self.explorerViewController toggleMenuTool]; + } description:@"Toggle FLEX globals menu"]; + + [self registerSimulatorShortcutWithKey:@"v" modifiers:0 action:^{ + [self showExplorerIfNeeded]; + [self.explorerViewController toggleViewsTool]; + } description:@"Toggle view hierarchy menu"]; + + [self registerSimulatorShortcutWithKey:@"s" modifiers:0 action:^{ + [self showExplorerIfNeeded]; + [self.explorerViewController toggleSelectTool]; + } description:@"Toggle select tool"]; + + [self registerSimulatorShortcutWithKey:@"m" modifiers:0 action:^{ + [self showExplorerIfNeeded]; + [self.explorerViewController toggleMoveTool]; + } description:@"Toggle move tool"]; + + [self registerSimulatorShortcutWithKey:@"n" modifiers:0 action:^{ + [self toggleTopViewControllerOfClass:[FLEXNetworkHistoryTableViewController class]]; + } description:@"Toggle network history view"]; + + [self registerSimulatorShortcutWithKey:UIKeyInputDownArrow modifiers:0 action:^{ + if ([self isHidden]) { + [self tryScrollDown]; + } else { + [self.explorerViewController handleDownArrowKeyPressed]; + } + } description:@"Cycle view selection\n\t\tMove view down\n\t\tScroll down"]; + + [self registerSimulatorShortcutWithKey:UIKeyInputUpArrow modifiers:0 action:^{ + if ([self isHidden]) { + [self tryScrollUp]; + } else { + [self.explorerViewController handleUpArrowKeyPressed]; + } + } description:@"Cycle view selection\n\t\tMove view up\n\t\tScroll up"]; + + [self registerSimulatorShortcutWithKey:UIKeyInputRightArrow modifiers:0 action:^{ + if (![self isHidden]) { + [self.explorerViewController handleRightArrowKeyPressed]; + } + } description:@"Move selected view right"]; + + [self registerSimulatorShortcutWithKey:UIKeyInputLeftArrow modifiers:0 action:^{ + if ([self isHidden]) { + [self tryGoBack]; + } else { + [self.explorerViewController handleLeftArrowKeyPressed]; + } + } description:@"Move selected view left"]; + + [self registerSimulatorShortcutWithKey:@"?" modifiers:0 action:^{ + [self toggleTopViewControllerOfClass:[FLEXKeyboardHelpViewController class]]; + } description:@"Toggle (this) help menu"]; + + [self registerSimulatorShortcutWithKey:UIKeyInputEscape modifiers:0 action:^{ + [[[self topViewController] presentingViewController] dismissViewControllerAnimated:YES completion:nil]; + } description:@"End editing text\n\t\tDismiss top view controller"]; + + [self registerSimulatorShortcutWithKey:@"o" modifiers:UIKeyModifierCommand|UIKeyModifierShift action:^{ + [self toggleTopViewControllerOfClass:[FLEXFileBrowserTableViewController class]]; + } description:@"Toggle file browser menu"]; +} + ++ (void)load +{ + dispatch_async(dispatch_get_main_queue(), ^{ + [[[self class] sharedManager] registerDefaultSimulatorShortcuts]; + }); +} + +#pragma mark - Extensions + +- (void)registerGlobalEntryWithName:(NSString *)entryName objectFutureBlock:(id (^)(void))objectFutureBlock +{ + NSParameterAssert(entryName); + NSParameterAssert(objectFutureBlock); + NSAssert([NSThread isMainThread], @"This method must be called from the main thread."); + + entryName = entryName.copy; + FLEXGlobalsTableViewControllerEntry *entry = [FLEXGlobalsTableViewControllerEntry entryWithNameFuture:^NSString *{ + return entryName; + } viewControllerFuture:^UIViewController *{ + return [FLEXObjectExplorerFactory explorerViewControllerForObject:objectFutureBlock()]; + }]; + + [self.userGlobalEntries addObject:entry]; +} + +- (void)registerGlobalEntryWithName:(NSString *)entryName viewControllerFutureBlock:(UIViewController * (^)(void))viewControllerFutureBlock +{ + NSParameterAssert(entryName); + NSParameterAssert(viewControllerFutureBlock); + NSAssert([NSThread isMainThread], @"This method must be called from the main thread."); + + entryName = entryName.copy; + FLEXGlobalsTableViewControllerEntry *entry = [FLEXGlobalsTableViewControllerEntry entryWithNameFuture:^NSString *{ + return entryName; + } viewControllerFuture:^UIViewController *{ + UIViewController *viewController = viewControllerFutureBlock(); + NSCAssert(viewController, @"'%@' entry returned nil viewController. viewControllerFutureBlock should never return nil.", entryName); + return viewController; + }]; + + [self.userGlobalEntries addObject:entry]; +} + +- (void)tryScrollDown +{ + UIScrollView *firstScrollView = [self firstScrollView]; + CGPoint contentOffset = [firstScrollView contentOffset]; + CGFloat distance = floor(firstScrollView.frame.size.height / 2.0); + CGFloat maxContentOffsetY = firstScrollView.contentSize.height + firstScrollView.contentInset.bottom - firstScrollView.frame.size.height; + distance = MIN(maxContentOffsetY - firstScrollView.contentOffset.y, distance); + contentOffset.y += distance; + [firstScrollView setContentOffset:contentOffset animated:YES]; +} + +- (void)tryScrollUp +{ + UIScrollView *firstScrollView = [self firstScrollView]; + CGPoint contentOffset = [firstScrollView contentOffset]; + CGFloat distance = floor(firstScrollView.frame.size.height / 2.0); + CGFloat minContentOffsetY = -firstScrollView.contentInset.top; + distance = MIN(firstScrollView.contentOffset.y - minContentOffsetY, distance); + contentOffset.y -= distance; + [firstScrollView setContentOffset:contentOffset animated:YES]; +} + +- (UIScrollView *)firstScrollView +{ + NSMutableArray *views = [[[[UIApplication sharedApplication] keyWindow] subviews] mutableCopy]; + UIScrollView *scrollView = nil; + while ([views count] > 0) { + UIView *view = [views firstObject]; + [views removeObjectAtIndex:0]; + if ([view isKindOfClass:[UIScrollView class]]) { + scrollView = (UIScrollView *)view; + break; + } else { + [views addObjectsFromArray:[view subviews]]; + } + } + return scrollView; +} + +- (void)tryGoBack +{ + UINavigationController *navigationController = nil; + UIViewController *topViewController = [self topViewController]; + if ([topViewController isKindOfClass:[UINavigationController class]]) { + navigationController = (UINavigationController *)topViewController; + } else { + navigationController = topViewController.navigationController; + } + [navigationController popViewControllerAnimated:YES]; +} + +- (UIViewController *)topViewController +{ + UIViewController *topViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController]; + while ([topViewController presentedViewController]) { + topViewController = [topViewController presentedViewController]; + } + return topViewController; +} + +- (void)toggleTopViewControllerOfClass:(Class)class +{ + UIViewController *topViewController = [self topViewController]; + if ([topViewController isKindOfClass:[UINavigationController class]] && [[[(UINavigationController *)topViewController viewControllers] firstObject] isKindOfClass:[class class]]) { + [[topViewController presentingViewController] dismissViewControllerAnimated:YES completion:nil]; + } else { + id viewController = [[class alloc] init]; + UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; + [topViewController presentViewController:navigationController animated:YES completion:nil]; + } +} + +- (void)showExplorerIfNeeded +{ + if ([self isHidden]) { + [self showExplorer]; + } +} + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkCurlLogger.h b/Pods/FLEX/Classes/Network/FLEXNetworkCurlLogger.h new file mode 100644 index 0000000000..6fb7eb63cc --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkCurlLogger.h @@ -0,0 +1,19 @@ +// +// FLEXCurlLogger.h +// +// +// Created by Ji Pei on 07/27/16 +// + +#import + +@interface FLEXNetworkCurlLogger : NSObject + +/** + * Generates a cURL command equivalent to the given request. + * + * @param request The request to be translated + */ ++ (NSString *)curlCommandString:(NSURLRequest *)request; + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkCurlLogger.m b/Pods/FLEX/Classes/Network/FLEXNetworkCurlLogger.m new file mode 100644 index 0000000000..742d3a5f21 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkCurlLogger.m @@ -0,0 +1,42 @@ +// +// FLEXCurlLogger.m +// +// +// Created by Ji Pei on 07/27/16 +// + +#import "FLEXNetworkCurlLogger.h" + +@implementation FLEXNetworkCurlLogger + ++ (NSString *)curlCommandString:(NSURLRequest *)request { + __block NSMutableString *curlCommandString = [NSMutableString stringWithFormat:@"curl -v -X %@ ", request.HTTPMethod]; + + [curlCommandString appendFormat:@"\'%@\' ", request.URL.absoluteString]; + + [request.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *val, BOOL *stop) { + [curlCommandString appendFormat:@"-H \'%@: %@\' ", key, val]; + }]; + + NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL]; + if (cookies) { + [curlCommandString appendFormat:@"-H \'Cookie:"]; + for (NSHTTPCookie *cookie in cookies) { + [curlCommandString appendFormat:@" %@=%@;", cookie.name, cookie.value]; + } + [curlCommandString appendFormat:@"\' "]; + } + + if (request.HTTPBody) { + if ([request.allHTTPHeaderFields[@"Content-Length"] intValue] < 1024) { + [curlCommandString appendFormat:@"-d \'%@\'", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]]; + } else { + [curlCommandString appendFormat:@"[TOO MUCH DATA TO INCLUDE]"]; + } + } + + return curlCommandString; +} + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkHistoryTableViewController.h b/Pods/FLEX/Classes/Network/FLEXNetworkHistoryTableViewController.h new file mode 100644 index 0000000000..b114515e67 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkHistoryTableViewController.h @@ -0,0 +1,13 @@ +// +// FLEXNetworkHistoryTableViewController.h +// Flipboard +// +// Created by Ryan Olson on 2/8/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import + +@interface FLEXNetworkHistoryTableViewController : UITableViewController + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkHistoryTableViewController.m b/Pods/FLEX/Classes/Network/FLEXNetworkHistoryTableViewController.m new file mode 100644 index 0000000000..040fa44591 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkHistoryTableViewController.m @@ -0,0 +1,360 @@ +// +// FLEXNetworkHistoryTableViewController.m +// Flipboard +// +// Created by Ryan Olson on 2/8/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import "FLEXNetworkHistoryTableViewController.h" +#import "FLEXNetworkTransaction.h" +#import "FLEXNetworkTransactionTableViewCell.h" +#import "FLEXNetworkRecorder.h" +#import "FLEXNetworkTransactionDetailTableViewController.h" +#import "FLEXNetworkObserver.h" +#import "FLEXNetworkSettingsTableViewController.h" + +@interface FLEXNetworkHistoryTableViewController () + +/// Backing model +@property (nonatomic, copy) NSArray *networkTransactions; +@property (nonatomic, assign) long long bytesReceived; +@property (nonatomic, copy) NSArray *filteredNetworkTransactions; +@property (nonatomic, assign) long long filteredBytesReceived; + +@property (nonatomic, assign) BOOL rowInsertInProgress; +@property (nonatomic, assign) BOOL isPresentingSearch; + +@property (nonatomic, strong) UISearchController *searchController; + +@end + +@implementation FLEXNetworkHistoryTableViewController + +- (instancetype)initWithStyle:(UITableViewStyle)style +{ + self = [super initWithStyle:style]; + if (self) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNewTransactionRecordedNotification:) name:kFLEXNetworkRecorderNewTransactionNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTransactionUpdatedNotification:) name:kFLEXNetworkRecorderTransactionUpdatedNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTransactionsClearedNotification:) name:kFLEXNetworkRecorderTransactionsClearedNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkObserverEnabledStateChangedNotification:) name:kFLEXNetworkObserverEnabledStateChangedNotification object:nil]; + self.title = @"📡 Network"; + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(settingsButtonTapped:)]; + } + return self; +} + +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + [self.tableView registerClass:[FLEXNetworkTransactionTableViewCell class] forCellReuseIdentifier:kFLEXNetworkTransactionCellIdentifier]; + self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; + self.tableView.rowHeight = [FLEXNetworkTransactionTableViewCell preferredCellHeight]; + + self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; + self.searchController.delegate = self; + self.searchController.searchResultsUpdater = self; + self.searchController.dimsBackgroundDuringPresentation = NO; + self.tableView.tableHeaderView = self.searchController.searchBar; + + [self updateTransactions]; +} + +- (void)settingsButtonTapped:(id)sender +{ + FLEXNetworkSettingsTableViewController *settingsViewController = [[FLEXNetworkSettingsTableViewController alloc] init]; + settingsViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(settingsViewControllerDoneTapped:)]; + settingsViewController.title = @"Network Debugging Settings"; + UINavigationController *wrapperNavigationController = [[UINavigationController alloc] initWithRootViewController:settingsViewController]; + [self presentViewController:wrapperNavigationController animated:YES completion:nil]; +} + +- (void)settingsViewControllerDoneTapped:(id)sender +{ + [self dismissViewControllerAnimated:YES completion:nil]; +} + +- (void)updateTransactions +{ + self.networkTransactions = [[FLEXNetworkRecorder defaultRecorder] networkTransactions]; +} + +- (void)setNetworkTransactions:(NSArray *)networkTransactions +{ + if (![_networkTransactions isEqual:networkTransactions]) { + _networkTransactions = networkTransactions; + [self updateBytesReceived]; + [self updateFilteredBytesReceived]; + } +} + +- (void)updateBytesReceived +{ + long long bytesReceived = 0; + for (FLEXNetworkTransaction *transaction in self.networkTransactions) { + bytesReceived += transaction.receivedDataLength; + } + self.bytesReceived = bytesReceived; + [self updateFirstSectionHeader]; +} + +- (void)setFilteredNetworkTransactions:(NSArray *)filteredNetworkTransactions +{ + if (![_filteredNetworkTransactions isEqual:filteredNetworkTransactions]) { + _filteredNetworkTransactions = filteredNetworkTransactions; + [self updateFilteredBytesReceived]; + } +} + +- (void)updateFilteredBytesReceived +{ + long long filteredBytesReceived = 0; + for (FLEXNetworkTransaction *transaction in self.filteredNetworkTransactions) { + filteredBytesReceived += transaction.receivedDataLength; + } + self.filteredBytesReceived = filteredBytesReceived; + [self updateFirstSectionHeader]; +} + +- (void)updateFirstSectionHeader +{ + UIView *view = [self.tableView headerViewForSection:0]; + if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) { + UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view; + headerView.textLabel.text = [self headerText]; + [headerView setNeedsLayout]; + } +} + +- (NSString *)headerText +{ + NSString *headerText = nil; + if ([FLEXNetworkObserver isEnabled]) { + long long bytesReceived = 0; + NSInteger totalRequests = 0; + if (self.searchController.isActive) { + bytesReceived = self.filteredBytesReceived; + totalRequests = [self.filteredNetworkTransactions count]; + } else { + bytesReceived = self.bytesReceived; + totalRequests = [self.networkTransactions count]; + } + NSString *byteCountText = [NSByteCountFormatter stringFromByteCount:bytesReceived countStyle:NSByteCountFormatterCountStyleBinary]; + NSString *requestsText = totalRequests == 1 ? @"Request" : @"Requests"; + headerText = [NSString stringWithFormat:@"%ld %@ (%@ received)", (long)totalRequests, requestsText, byteCountText]; + } else { + headerText = @"⚠️ Debugging Disabled (Enable in Settings)"; + } + return headerText; +} + +#pragma mark - Notification Handlers + +- (void)handleNewTransactionRecordedNotification:(NSNotification *)notification +{ + [self tryUpdateTransactions]; +} + +- (void)tryUpdateTransactions +{ + // Let the previous row insert animation finish before starting a new one to avoid stomping. + // We'll try calling the method again when the insertion completes, and we properly no-op if there haven't been changes. + if (self.rowInsertInProgress) { + return; + } + + if (self.searchController.isActive) { + [self updateTransactions]; + [self updateSearchResults]; + return; + } + + NSInteger existingRowCount = [self.networkTransactions count]; + [self updateTransactions]; + NSInteger newRowCount = [self.networkTransactions count]; + NSInteger addedRowCount = newRowCount - existingRowCount; + + if (addedRowCount != 0 && !self.isPresentingSearch) { + // Insert animation if we're at the top. + if (self.tableView.contentOffset.y <= 0.0 && addedRowCount > 0) { + [CATransaction begin]; + + self.rowInsertInProgress = YES; + [CATransaction setCompletionBlock:^{ + self.rowInsertInProgress = NO; + [self tryUpdateTransactions]; + }]; + + NSMutableArray *indexPathsToReload = [NSMutableArray array]; + for (NSInteger row = 0; row < addedRowCount; row++) { + [indexPathsToReload addObject:[NSIndexPath indexPathForRow:row inSection:0]]; + } + [self.tableView insertRowsAtIndexPaths:indexPathsToReload withRowAnimation:UITableViewRowAnimationAutomatic]; + + [CATransaction commit]; + } else { + // Maintain the user's position if they've scrolled down. + CGSize existingContentSize = self.tableView.contentSize; + [self.tableView reloadData]; + CGFloat contentHeightChange = self.tableView.contentSize.height - existingContentSize.height; + self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, self.tableView.contentOffset.y + contentHeightChange); + } + } +} + +- (void)handleTransactionUpdatedNotification:(NSNotification *)notification +{ + [self updateBytesReceived]; + [self updateFilteredBytesReceived]; + + FLEXNetworkTransaction *transaction = notification.userInfo[kFLEXNetworkRecorderUserInfoTransactionKey]; + + // Update both the main table view and search table view if needed. + for (FLEXNetworkTransactionTableViewCell *cell in [self.tableView visibleCells]) { + if ([cell.transaction isEqual:transaction]) { + // Using -[UITableView reloadRowsAtIndexPaths:withRowAnimation:] is overkill here and kicks off a lot of + // work that can make the table view somewhat unresponseive when lots of updates are streaming in. + // We just need to tell the cell that it needs to re-layout. + [cell setNeedsLayout]; + break; + } + } + [self updateFirstSectionHeader]; +} + +- (void)handleTransactionsClearedNotification:(NSNotification *)notification +{ + [self updateTransactions]; + [self.tableView reloadData]; +} + +- (void)handleNetworkObserverEnabledStateChangedNotification:(NSNotification *)notification +{ + // Update the header, which displays a warning when network debugging is disabled + [self updateFirstSectionHeader]; +} + +#pragma mark - Table view data source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return self.searchController.isActive ? [self.filteredNetworkTransactions count] : [self.networkTransactions count]; +} + +- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section +{ + return [self headerText]; +} + +- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section +{ + if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) { + UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view; + headerView.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:14.0]; + headerView.textLabel.textColor = [UIColor whiteColor]; + headerView.contentView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:1.0]; + } +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXNetworkTransactionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXNetworkTransactionCellIdentifier forIndexPath:indexPath]; + cell.transaction = [self transactionAtIndexPath:indexPath inTableView:tableView]; + + // Since we insert from the top, assign background colors bottom up to keep them consistent for each transaction. + NSInteger totalRows = [tableView numberOfRowsInSection:indexPath.section]; + if ((totalRows - indexPath.row) % 2 == 0) { + cell.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0]; + } else { + cell.backgroundColor = [UIColor whiteColor]; + } + + return cell; +} + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXNetworkTransactionDetailTableViewController *detailViewController = [[FLEXNetworkTransactionDetailTableViewController alloc] init]; + detailViewController.transaction = [self transactionAtIndexPath:indexPath inTableView:tableView]; + [self.navigationController pushViewController:detailViewController animated:YES]; +} + +#pragma mark - Menu Actions + +- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath +{ + return YES; +} + +- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + return action == @selector(copy:); +} + +- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + if (action == @selector(copy:)) { + FLEXNetworkTransaction *transaction = [self transactionAtIndexPath:indexPath inTableView:tableView]; + NSString *requestURLString = transaction.request.URL.absoluteString ?: @""; + [[UIPasteboard generalPasteboard] setString:requestURLString]; + } +} + +- (FLEXNetworkTransaction *)transactionAtIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView +{ + return self.searchController.isActive ? self.filteredNetworkTransactions[indexPath.row] : self.networkTransactions[indexPath.row]; +} + +#pragma mark - UISearchResultsUpdating + +- (void)updateSearchResultsForSearchController:(UISearchController *)searchController +{ + [self updateSearchResults]; +} + +- (void)updateSearchResults +{ + NSString *searchString = self.searchController.searchBar.text; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + NSArray *filteredNetworkTransactions = [self.networkTransactions filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(FLEXNetworkTransaction *transaction, NSDictionary *bindings) { + return [[transaction.request.URL absoluteString] rangeOfString:searchString options:NSCaseInsensitiveSearch].length > 0; + }]]; + dispatch_async(dispatch_get_main_queue(), ^{ + if ([self.searchController.searchBar.text isEqual:searchString]) { + self.filteredNetworkTransactions = filteredNetworkTransactions; + [self.tableView reloadData]; + } + }); + }); +} + +#pragma mark - UISearchControllerDelegate + +- (void)willPresentSearchController:(UISearchController *)searchController +{ + self.isPresentingSearch = YES; +} + +- (void)didPresentSearchController:(UISearchController *)searchController +{ + self.isPresentingSearch = NO; +} + +- (void)willDismissSearchController:(UISearchController *)searchController +{ + [self.tableView reloadData]; +} + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkRecorder.h b/Pods/FLEX/Classes/Network/FLEXNetworkRecorder.h new file mode 100644 index 0000000000..1f075bf5c3 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkRecorder.h @@ -0,0 +1,63 @@ +// +// FLEXNetworkRecorder.h +// Flipboard +// +// Created by Ryan Olson on 2/4/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import + +// Notifications posted when the record is updated +extern NSString *const kFLEXNetworkRecorderNewTransactionNotification; +extern NSString *const kFLEXNetworkRecorderTransactionUpdatedNotification; +extern NSString *const kFLEXNetworkRecorderUserInfoTransactionKey; +extern NSString *const kFLEXNetworkRecorderTransactionsClearedNotification; + +@class FLEXNetworkTransaction; + +@interface FLEXNetworkRecorder : NSObject + +/// In general, it only makes sense to have one recorder for the entire application. ++ (instancetype)defaultRecorder; + +/// Defaults to 25 MB if never set. Values set here are presisted across launches of the app. +@property (nonatomic, assign) NSUInteger responseCacheByteLimit; + +/// If NO, the recorder not cache will not cache response for content types with an "image", "video", or "audio" prefix. +@property (nonatomic, assign) BOOL shouldCacheMediaResponses; + +// Accessing recorded network activity + +/// Array of FLEXNetworkTransaction objects ordered by start time with the newest first. +- (NSArray *)networkTransactions; + +/// The full response data IFF it hasn't been purged due to memory pressure. +- (NSData *)cachedResponseBodyForTransaction:(FLEXNetworkTransaction *)transaction; + +/// Dumps all network transactions and cached response bodies. +- (void)clearRecordedActivity; + + +// Recording network activity + +/// Call when app is about to send HTTP request. +- (void)recordRequestWillBeSentWithRequestID:(NSString *)requestID request:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse; + +/// Call when HTTP response is available. +- (void)recordResponseReceivedWithRequestID:(NSString *)requestID response:(NSURLResponse *)response; + +/// Call when data chunk is received over the network. +- (void)recordDataReceivedWithRequestID:(NSString *)requestID dataLength:(int64_t)dataLength; + +/// Call when HTTP request has finished loading. +- (void)recordLoadingFinishedWithRequestID:(NSString *)requestID responseBody:(NSData *)responseBody; + +/// Call when HTTP request has failed to load. +- (void)recordLoadingFailedWithRequestID:(NSString *)requestID error:(NSError *)error; + +/// Call to set the request mechanism anytime after recordRequestWillBeSent... has been called. +/// This string can be set to anything useful about the API used to make the request. +- (void)recordMechanism:(NSString *)mechanism forRequestID:(NSString *)requestID; + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkRecorder.m b/Pods/FLEX/Classes/Network/FLEXNetworkRecorder.m new file mode 100644 index 0000000000..a36bf32479 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkRecorder.m @@ -0,0 +1,262 @@ +// +// FLEXNetworkRecorder.m +// Flipboard +// +// Created by Ryan Olson on 2/4/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import "FLEXNetworkRecorder.h" +#import "FLEXNetworkCurlLogger.h" +#import "FLEXNetworkTransaction.h" +#import "FLEXUtility.h" +#import "FLEXResources.h" + +NSString *const kFLEXNetworkRecorderNewTransactionNotification = @"kFLEXNetworkRecorderNewTransactionNotification"; +NSString *const kFLEXNetworkRecorderTransactionUpdatedNotification = @"kFLEXNetworkRecorderTransactionUpdatedNotification"; +NSString *const kFLEXNetworkRecorderUserInfoTransactionKey = @"transaction"; +NSString *const kFLEXNetworkRecorderTransactionsClearedNotification = @"kFLEXNetworkRecorderTransactionsClearedNotification"; + +NSString *const kFLEXNetworkRecorderResponseCacheLimitDefaultsKey = @"com.flex.responseCacheLimit"; + +@interface FLEXNetworkRecorder () + +@property (nonatomic, strong) NSCache *responseCache; +@property (nonatomic, strong) NSMutableArray *orderedTransactions; +@property (nonatomic, strong) NSMutableDictionary *networkTransactionsForRequestIdentifiers; +@property (nonatomic, strong) dispatch_queue_t queue; + +@end + +@implementation FLEXNetworkRecorder + +- (instancetype)init +{ + self = [super init]; + if (self) { + self.responseCache = [[NSCache alloc] init]; + NSUInteger responseCacheLimit = [[[NSUserDefaults standardUserDefaults] objectForKey:kFLEXNetworkRecorderResponseCacheLimitDefaultsKey] unsignedIntegerValue]; + if (responseCacheLimit) { + [self.responseCache setTotalCostLimit:responseCacheLimit]; + } else { + // Default to 25 MB max. The cache will purge earlier if there is memory pressure. + [self.responseCache setTotalCostLimit:25 * 1024 * 1024]; + } + self.orderedTransactions = [NSMutableArray array]; + self.networkTransactionsForRequestIdentifiers = [NSMutableDictionary dictionary]; + + // Serial queue used because we use mutable objects that are not thread safe + self.queue = dispatch_queue_create("com.flex.FLEXNetworkRecorder", DISPATCH_QUEUE_SERIAL); + } + return self; +} + ++ (instancetype)defaultRecorder +{ + static FLEXNetworkRecorder *defaultRecorder = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + defaultRecorder = [[[self class] alloc] init]; + }); + return defaultRecorder; +} + +#pragma mark - Public Data Access + +- (NSUInteger)responseCacheByteLimit +{ + return [self.responseCache totalCostLimit]; +} + +- (void)setResponseCacheByteLimit:(NSUInteger)responseCacheByteLimit +{ + [self.responseCache setTotalCostLimit:responseCacheByteLimit]; + [[NSUserDefaults standardUserDefaults] setObject:@(responseCacheByteLimit) forKey:kFLEXNetworkRecorderResponseCacheLimitDefaultsKey]; +} + +- (NSArray *)networkTransactions +{ + __block NSArray *transactions = nil; + dispatch_sync(self.queue, ^{ + transactions = [self.orderedTransactions copy]; + }); + return transactions; +} + +- (NSData *)cachedResponseBodyForTransaction:(FLEXNetworkTransaction *)transaction +{ + return [self.responseCache objectForKey:transaction.requestID]; +} + +- (void)clearRecordedActivity +{ + dispatch_async(self.queue, ^{ + [self.responseCache removeAllObjects]; + [self.orderedTransactions removeAllObjects]; + [self.networkTransactionsForRequestIdentifiers removeAllObjects]; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkRecorderTransactionsClearedNotification object:self]; + }); + }); +} + +#pragma mark - Network Events + +- (void)recordRequestWillBeSentWithRequestID:(NSString *)requestID request:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse +{ + NSDate *startDate = [NSDate date]; + + if (redirectResponse) { + [self recordResponseReceivedWithRequestID:requestID response:redirectResponse]; + [self recordLoadingFinishedWithRequestID:requestID responseBody:nil]; + } + + dispatch_async(self.queue, ^{ + FLEXNetworkTransaction *transaction = [[FLEXNetworkTransaction alloc] init]; + transaction.requestID = requestID; + transaction.request = request; + transaction.startTime = startDate; + + [self.orderedTransactions insertObject:transaction atIndex:0]; + [self.networkTransactionsForRequestIdentifiers setObject:transaction forKey:requestID]; + transaction.transactionState = FLEXNetworkTransactionStateAwaitingResponse; + + [self postNewTransactionNotificationWithTransaction:transaction]; + }); +} + +- (void)recordResponseReceivedWithRequestID:(NSString *)requestID response:(NSURLResponse *)response +{ + NSDate *responseDate = [NSDate date]; + + dispatch_async(self.queue, ^{ + FLEXNetworkTransaction *transaction = self.networkTransactionsForRequestIdentifiers[requestID]; + if (!transaction) { + return; + } + transaction.response = response; + transaction.transactionState = FLEXNetworkTransactionStateReceivingData; + transaction.latency = -[transaction.startTime timeIntervalSinceDate:responseDate]; + + [self postUpdateNotificationForTransaction:transaction]; + }); +} + +- (void)recordDataReceivedWithRequestID:(NSString *)requestID dataLength:(int64_t)dataLength +{ + dispatch_async(self.queue, ^{ + FLEXNetworkTransaction *transaction = self.networkTransactionsForRequestIdentifiers[requestID]; + if (!transaction) { + return; + } + transaction.receivedDataLength += dataLength; + + [self postUpdateNotificationForTransaction:transaction]; + }); +} + +- (void)recordLoadingFinishedWithRequestID:(NSString *)requestID responseBody:(NSData *)responseBody +{ + NSDate *finishedDate = [NSDate date]; + + dispatch_async(self.queue, ^{ + FLEXNetworkTransaction *transaction = self.networkTransactionsForRequestIdentifiers[requestID]; + if (!transaction) { + return; + } + transaction.transactionState = FLEXNetworkTransactionStateFinished; + transaction.duration = -[transaction.startTime timeIntervalSinceDate:finishedDate]; + + BOOL shouldCache = [responseBody length] > 0; + if (!self.shouldCacheMediaResponses) { + NSArray *ignoredMIMETypePrefixes = @[ @"audio", @"image", @"video" ]; + for (NSString *ignoredPrefix in ignoredMIMETypePrefixes) { + shouldCache = shouldCache && ![transaction.response.MIMEType hasPrefix:ignoredPrefix]; + } + } + + if (shouldCache) { + [self.responseCache setObject:responseBody forKey:requestID cost:[responseBody length]]; + } + + NSString *mimeType = transaction.response.MIMEType; + if ([mimeType hasPrefix:@"image/"] && [responseBody length] > 0) { + // Thumbnail image previews on a separate background queue + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + NSInteger maxPixelDimension = [[UIScreen mainScreen] scale] * 32.0; + transaction.responseThumbnail = [FLEXUtility thumbnailedImageWithMaxPixelDimension:maxPixelDimension fromImageData:responseBody]; + [self postUpdateNotificationForTransaction:transaction]; + }); + } else if ([mimeType isEqual:@"application/json"]) { + transaction.responseThumbnail = [FLEXResources jsonIcon]; + } else if ([mimeType isEqual:@"text/plain"]){ + transaction.responseThumbnail = [FLEXResources textPlainIcon]; + } else if ([mimeType isEqual:@"text/html"]) { + transaction.responseThumbnail = [FLEXResources htmlIcon]; + } else if ([mimeType isEqual:@"application/x-plist"]) { + transaction.responseThumbnail = [FLEXResources plistIcon]; + } else if ([mimeType isEqual:@"application/octet-stream"] || [mimeType isEqual:@"application/binary"]) { + transaction.responseThumbnail = [FLEXResources binaryIcon]; + } else if ([mimeType rangeOfString:@"javascript"].length > 0) { + transaction.responseThumbnail = [FLEXResources jsIcon]; + } else if ([mimeType rangeOfString:@"xml"].length > 0) { + transaction.responseThumbnail = [FLEXResources xmlIcon]; + } else if ([mimeType hasPrefix:@"audio"]) { + transaction.responseThumbnail = [FLEXResources audioIcon]; + } else if ([mimeType hasPrefix:@"video"]) { + transaction.responseThumbnail = [FLEXResources videoIcon]; + } else if ([mimeType hasPrefix:@"text"]) { + transaction.responseThumbnail = [FLEXResources textIcon]; + } + + [self postUpdateNotificationForTransaction:transaction]; + }); +} + +- (void)recordLoadingFailedWithRequestID:(NSString *)requestID error:(NSError *)error +{ + dispatch_async(self.queue, ^{ + FLEXNetworkTransaction *transaction = self.networkTransactionsForRequestIdentifiers[requestID]; + if (!transaction) { + return; + } + transaction.transactionState = FLEXNetworkTransactionStateFailed; + transaction.duration = -[transaction.startTime timeIntervalSinceNow]; + transaction.error = error; + + [self postUpdateNotificationForTransaction:transaction]; + }); +} + +- (void)recordMechanism:(NSString *)mechanism forRequestID:(NSString *)requestID +{ + dispatch_async(self.queue, ^{ + FLEXNetworkTransaction *transaction = self.networkTransactionsForRequestIdentifiers[requestID]; + if (!transaction) { + return; + } + transaction.requestMechanism = mechanism; + + [self postUpdateNotificationForTransaction:transaction]; + }); +} + +#pragma mark Notification Posting + +- (void)postNewTransactionNotificationWithTransaction:(FLEXNetworkTransaction *)transaction +{ + dispatch_async(dispatch_get_main_queue(), ^{ + NSDictionary *userInfo = @{ kFLEXNetworkRecorderUserInfoTransactionKey : transaction }; + [[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkRecorderNewTransactionNotification object:self userInfo:userInfo]; + }); +} + +- (void)postUpdateNotificationForTransaction:(FLEXNetworkTransaction *)transaction +{ + dispatch_async(dispatch_get_main_queue(), ^{ + NSDictionary *userInfo = @{ kFLEXNetworkRecorderUserInfoTransactionKey : transaction }; + [[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkRecorderTransactionUpdatedNotification object:self userInfo:userInfo]; + }); +} + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkSettingsTableViewController.h b/Pods/FLEX/Classes/Network/FLEXNetworkSettingsTableViewController.h new file mode 100644 index 0000000000..331a2d8d70 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkSettingsTableViewController.h @@ -0,0 +1,13 @@ +// +// FLEXNetworkSettingsTableViewController.h +// FLEXInjected +// +// Created by Ryan Olson on 2/20/15. +// +// + +#import + +@interface FLEXNetworkSettingsTableViewController : UITableViewController + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkSettingsTableViewController.m b/Pods/FLEX/Classes/Network/FLEXNetworkSettingsTableViewController.m new file mode 100644 index 0000000000..3586c5de49 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkSettingsTableViewController.m @@ -0,0 +1,186 @@ +// +// FLEXNetworkSettingsTableViewController.m +// FLEXInjected +// +// Created by Ryan Olson on 2/20/15. +// +// + +#import "FLEXNetworkSettingsTableViewController.h" +#import "FLEXNetworkObserver.h" +#import "FLEXNetworkRecorder.h" +#import "FLEXUtility.h" + +@interface FLEXNetworkSettingsTableViewController () + +@property (nonatomic, copy) NSArray *cells; + +@property (nonatomic, strong) UITableViewCell *cacheLimitCell; + +@end + +@implementation FLEXNetworkSettingsTableViewController + +- (instancetype)initWithStyle:(UITableViewStyle)style +{ + self = [super initWithStyle:UITableViewStyleGrouped]; + if (self) { + + } + return self; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + NSMutableArray *mutableCells = [NSMutableArray array]; + + UITableViewCell *networkDebuggingCell = [self switchCellWithTitle:@"Network Debugging" toggleAction:@selector(networkDebuggingToggled:) isOn:[FLEXNetworkObserver isEnabled]]; + [mutableCells addObject:networkDebuggingCell]; + + UITableViewCell *cacheMediaResponsesCell = [self switchCellWithTitle:@"Cache Media Responses" toggleAction:@selector(cacheMediaResponsesToggled:) isOn:NO]; + [mutableCells addObject:cacheMediaResponsesCell]; + + NSUInteger currentCacheLimit = [[FLEXNetworkRecorder defaultRecorder] responseCacheByteLimit]; + const NSUInteger fiftyMega = 50 * 1024 * 1024; + NSString *cacheLimitTitle = [self titleForCacheLimitCellWithValue:currentCacheLimit]; + self.cacheLimitCell = [self sliderCellWithTitle:cacheLimitTitle changedAction:@selector(cacheLimitAdjusted:) minimum:0.0 maximum:fiftyMega initialValue:currentCacheLimit]; + [mutableCells addObject:self.cacheLimitCell]; + + UITableViewCell *clearRecordedRequestsCell = [self buttonCellWithTitle:@"❌ Clear Recorded Requests" touchUpAction:@selector(clearRequestsTapped:) isDestructive:YES]; + [mutableCells addObject:clearRecordedRequestsCell]; + + self.cells = mutableCells; +} + +#pragma mark - Settings Actions + +- (void)networkDebuggingToggled:(UISwitch *)sender +{ + [FLEXNetworkObserver setEnabled:sender.isOn]; +} + +- (void)cacheMediaResponsesToggled:(UISwitch *)sender +{ + [[FLEXNetworkRecorder defaultRecorder] setShouldCacheMediaResponses:sender.isOn]; +} + +- (void)cacheLimitAdjusted:(UISlider *)sender +{ + [[FLEXNetworkRecorder defaultRecorder] setResponseCacheByteLimit:sender.value]; + self.cacheLimitCell.textLabel.text = [self titleForCacheLimitCellWithValue:sender.value]; +} + +- (void)clearRequestsTapped:(UIButton *)sender +{ + UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Clear Recorded Requests" otherButtonTitles:nil]; + [actionSheet showInView:self.view]; +} + +#pragma mark - Table view data source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return [self.cells count]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + return self.cells[indexPath.row]; +} + +#pragma mark - UIActionSheetDelegate + +- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex +{ + if (buttonIndex != actionSheet.cancelButtonIndex) { + [[FLEXNetworkRecorder defaultRecorder] clearRecordedActivity]; + } +} + +#pragma mark - Helpers + +- (UITableViewCell *)switchCellWithTitle:(NSString *)title toggleAction:(SEL)toggleAction isOn:(BOOL)isOn +{ + UITableViewCell *cell = [[UITableViewCell alloc] init]; + cell.selectionStyle = UITableViewCellSelectionStyleNone; + cell.textLabel.text = title; + cell.textLabel.font = [[self class] cellTitleFont]; + + UISwitch *theSwitch = [[UISwitch alloc] init]; + theSwitch.on = isOn; + [theSwitch addTarget:self action:toggleAction forControlEvents:UIControlEventValueChanged]; + + CGFloat switchOriginY = round((cell.contentView.frame.size.height - theSwitch.frame.size.height) / 2.0); + CGFloat switchOriginX = CGRectGetMaxX(cell.contentView.frame) - theSwitch.frame.size.width - self.tableView.separatorInset.left; + theSwitch.frame = CGRectMake(switchOriginX, switchOriginY, theSwitch.frame.size.width, theSwitch.frame.size.height); + theSwitch.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin; + [cell.contentView addSubview:theSwitch]; + + return cell; +} + +- (UITableViewCell *)buttonCellWithTitle:(NSString *)title touchUpAction:(SEL)action isDestructive:(BOOL)isDestructive +{ + UITableViewCell *buttonCell = [[UITableViewCell alloc] init]; + buttonCell.selectionStyle = UITableViewCellSelectionStyleNone; + + UIButton *actionButton = [UIButton buttonWithType:UIButtonTypeSystem]; + [actionButton setTitle:title forState:UIControlStateNormal]; + if (isDestructive) { + actionButton.tintColor = [UIColor redColor]; + } + actionButton.titleLabel.font = [[self class] cellTitleFont];; + [actionButton addTarget:self action:@selector(clearRequestsTapped:) forControlEvents:UIControlEventTouchUpInside]; + + [buttonCell.contentView addSubview:actionButton]; + actionButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + actionButton.frame = buttonCell.contentView.frame; + actionButton.contentEdgeInsets = UIEdgeInsetsMake(0.0, self.tableView.separatorInset.left, 0.0, self.tableView.separatorInset.left); + actionButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; + + return buttonCell; +} + +- (NSString *)titleForCacheLimitCellWithValue:(long long)cacheLimit +{ + NSInteger limitInMB = round(cacheLimit / (1024 * 1024)); + return [NSString stringWithFormat:@"Cache Limit (%ld MB)", (long)limitInMB]; +} + +- (UITableViewCell *)sliderCellWithTitle:(NSString *)title changedAction:(SEL)changedAction minimum:(CGFloat)minimum maximum:(CGFloat)maximum initialValue:(CGFloat)initialValue +{ + UITableViewCell *sliderCell = [[UITableViewCell alloc] init]; + sliderCell.selectionStyle = UITableViewCellSelectionStyleNone; + sliderCell.textLabel.text = title; + sliderCell.textLabel.font = [[self class] cellTitleFont]; + + UISlider *slider = [[UISlider alloc] init]; + slider.minimumValue = minimum; + slider.maximumValue = maximum; + slider.value = initialValue; + [slider addTarget:self action:changedAction forControlEvents:UIControlEventValueChanged]; + [slider sizeToFit]; + + CGFloat sliderWidth = round(sliderCell.contentView.frame.size.width * 2.0 / 5.0); + CGFloat sliderOriginY = round((sliderCell.contentView.frame.size.height - slider.frame.size.height) / 2.0); + CGFloat sliderOriginX = CGRectGetMaxX(sliderCell.contentView.frame) - sliderWidth - self.tableView.separatorInset.left; + slider.frame = CGRectMake(sliderOriginX, sliderOriginY, sliderWidth, slider.frame.size.height); + slider.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin; + [sliderCell.contentView addSubview:slider]; + + return sliderCell; +} + ++ (UIFont *)cellTitleFont +{ + return [FLEXUtility defaultFontOfSize:14.0]; +} + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkTransaction.h b/Pods/FLEX/Classes/Network/FLEXNetworkTransaction.h new file mode 100644 index 0000000000..8c9d000067 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkTransaction.h @@ -0,0 +1,44 @@ +// +// FLEXNetworkTransaction.h +// Flipboard +// +// Created by Ryan Olson on 2/8/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import +#import "UIKit/UIKit.h" + +typedef NS_ENUM(NSInteger, FLEXNetworkTransactionState) { + FLEXNetworkTransactionStateUnstarted, + FLEXNetworkTransactionStateAwaitingResponse, + FLEXNetworkTransactionStateReceivingData, + FLEXNetworkTransactionStateFinished, + FLEXNetworkTransactionStateFailed +}; + +@interface FLEXNetworkTransaction : NSObject + +@property (nonatomic, copy) NSString *requestID; + +@property (nonatomic, strong) NSURLRequest *request; +@property (nonatomic, strong) NSURLResponse *response; +@property (nonatomic, copy) NSString *requestMechanism; +@property (nonatomic, assign) FLEXNetworkTransactionState transactionState; +@property (nonatomic, strong) NSError *error; + +@property (nonatomic, strong) NSDate *startTime; +@property (nonatomic, assign) NSTimeInterval latency; +@property (nonatomic, assign) NSTimeInterval duration; + +@property (nonatomic, assign) int64_t receivedDataLength; + +/// Only applicable for image downloads. A small thumbnail to preview the full response. +@property (nonatomic, strong) UIImage *responseThumbnail; + +/// Populated lazily. Handles both normal HTTPBody data and HTTPBodyStreams. +@property (nonatomic, strong, readonly) NSData *cachedRequestBody; + ++ (NSString *)readableStringFromTransactionState:(FLEXNetworkTransactionState)state; + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkTransaction.m b/Pods/FLEX/Classes/Network/FLEXNetworkTransaction.m new file mode 100644 index 0000000000..87a9892497 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkTransaction.m @@ -0,0 +1,80 @@ +// +// FLEXNetworkTransaction.m +// Flipboard +// +// Created by Ryan Olson on 2/8/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import "FLEXNetworkTransaction.h" + +@interface FLEXNetworkTransaction () + +@property (nonatomic, strong, readwrite) NSData *cachedRequestBody; + +@end + +@implementation FLEXNetworkTransaction + +- (NSString *)description +{ + NSString *description = [super description]; + + description = [description stringByAppendingFormat:@" id = %@;", self.requestID]; + description = [description stringByAppendingFormat:@" url = %@;", self.request.URL]; + description = [description stringByAppendingFormat:@" duration = %f;", self.duration]; + description = [description stringByAppendingFormat:@" receivedDataLength = %lld", self.receivedDataLength]; + + return description; +} + +- (NSData *)cachedRequestBody { + if (!_cachedRequestBody) { + if (self.request.HTTPBody != nil) { + _cachedRequestBody = self.request.HTTPBody; + } else if ([self.request.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { + NSInputStream *bodyStream = [self.request.HTTPBodyStream copy]; + const NSUInteger bufferSize = 1024; + uint8_t buffer[bufferSize]; + NSMutableData *data = [NSMutableData data]; + [bodyStream open]; + NSInteger readBytes = 0; + do { + readBytes = [bodyStream read:buffer maxLength:bufferSize]; + [data appendBytes:buffer length:readBytes]; + } while (readBytes > 0); + [bodyStream close]; + _cachedRequestBody = data; + } + } + return _cachedRequestBody; +} + ++ (NSString *)readableStringFromTransactionState:(FLEXNetworkTransactionState)state +{ + NSString *readableString = nil; + switch (state) { + case FLEXNetworkTransactionStateUnstarted: + readableString = @"Unstarted"; + break; + + case FLEXNetworkTransactionStateAwaitingResponse: + readableString = @"Awaiting Response"; + break; + + case FLEXNetworkTransactionStateReceivingData: + readableString = @"Receiving Data"; + break; + + case FLEXNetworkTransactionStateFinished: + readableString = @"Finished"; + break; + + case FLEXNetworkTransactionStateFailed: + readableString = @"Failed"; + break; + } + return readableString; +} + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkTransactionDetailTableViewController.h b/Pods/FLEX/Classes/Network/FLEXNetworkTransactionDetailTableViewController.h new file mode 100644 index 0000000000..2e065faf8b --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkTransactionDetailTableViewController.h @@ -0,0 +1,17 @@ +// +// FLEXNetworkTransactionDetailTableViewController.h +// Flipboard +// +// Created by Ryan Olson on 2/10/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import + +@class FLEXNetworkTransaction; + +@interface FLEXNetworkTransactionDetailTableViewController : UITableViewController + +@property (nonatomic, strong) FLEXNetworkTransaction *transaction; + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkTransactionDetailTableViewController.m b/Pods/FLEX/Classes/Network/FLEXNetworkTransactionDetailTableViewController.m new file mode 100644 index 0000000000..57ee4e79eb --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkTransactionDetailTableViewController.m @@ -0,0 +1,465 @@ +// +// FLEXNetworkTransactionDetailTableViewController.m +// Flipboard +// +// Created by Ryan Olson on 2/10/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import "FLEXNetworkTransactionDetailTableViewController.h" +#import "FLEXNetworkCurlLogger.h" +#import "FLEXNetworkRecorder.h" +#import "FLEXNetworkTransaction.h" +#import "FLEXWebViewController.h" +#import "FLEXImagePreviewViewController.h" +#import "FLEXMultilineTableViewCell.h" +#import "FLEXUtility.h" + +@interface FLEXNetworkDetailSection : NSObject + +@property (nonatomic, copy) NSString *title; +@property (nonatomic, copy) NSArray *rows; + +@end + +@implementation FLEXNetworkDetailSection + +@end + +typedef UIViewController *(^FLEXNetworkDetailRowSelectionFuture)(void); + +@interface FLEXNetworkDetailRow : NSObject + +@property (nonatomic, copy) NSString *title; +@property (nonatomic, copy) NSString *detailText; +@property (nonatomic, copy) FLEXNetworkDetailRowSelectionFuture selectionFuture; + +@end + +@implementation FLEXNetworkDetailRow + +@end + +@interface FLEXNetworkTransactionDetailTableViewController () + +@property (nonatomic, copy) NSArray *sections; + +@end + +@implementation FLEXNetworkTransactionDetailTableViewController + +- (instancetype)initWithStyle:(UITableViewStyle)style +{ + // Force grouped style + self = [super initWithStyle:UITableViewStyleGrouped]; + if (self) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTransactionUpdatedNotification:) name:kFLEXNetworkRecorderTransactionUpdatedNotification object:nil]; + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Copy curl" style:UIBarButtonItemStylePlain target:self action:@selector(copyButtonPressed:)]; + } + return self; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + [self.tableView registerClass:[FLEXMultilineTableViewCell class] forCellReuseIdentifier:kFLEXMultilineTableViewCellIdentifier]; +} + +- (void)setTransaction:(FLEXNetworkTransaction *)transaction +{ + if (![_transaction isEqual:transaction]) { + _transaction = transaction; + self.title = [transaction.request.URL lastPathComponent]; + [self rebuildTableSections]; + } +} + +- (void)setSections:(NSArray *)sections +{ + if (![_sections isEqual:sections]) { + _sections = [sections copy]; + [self.tableView reloadData]; + } +} + +- (void)rebuildTableSections +{ + NSMutableArray *sections = [NSMutableArray array]; + + FLEXNetworkDetailSection *generalSection = [[self class] generalSectionForTransaction:self.transaction]; + if ([generalSection.rows count] > 0) { + [sections addObject:generalSection]; + } + FLEXNetworkDetailSection *requestHeadersSection = [[self class] requestHeadersSectionForTransaction:self.transaction]; + if ([requestHeadersSection.rows count] > 0) { + [sections addObject:requestHeadersSection]; + } + FLEXNetworkDetailSection *queryParametersSection = [[self class] queryParametersSectionForTransaction:self.transaction]; + if ([queryParametersSection.rows count] > 0) { + [sections addObject:queryParametersSection]; + } + FLEXNetworkDetailSection *postBodySection = [[self class] postBodySectionForTransaction:self.transaction]; + if ([postBodySection.rows count] > 0) { + [sections addObject:postBodySection]; + } + FLEXNetworkDetailSection *responseHeadersSection = [[self class] responseHeadersSectionForTransaction:self.transaction]; + if ([responseHeadersSection.rows count] > 0) { + [sections addObject:responseHeadersSection]; + } + + self.sections = sections; +} + +- (void)handleTransactionUpdatedNotification:(NSNotification *)notification +{ + FLEXNetworkTransaction *transaction = [[notification userInfo] objectForKey:kFLEXNetworkRecorderUserInfoTransactionKey]; + if (transaction == self.transaction) { + [self rebuildTableSections]; + } +} + +- (void)copyButtonPressed:(id)sender +{ + [[UIPasteboard generalPasteboard] setString:[FLEXNetworkCurlLogger curlCommandString:_transaction.request]]; +} + +#pragma mark - Table view data source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return [self.sections count]; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + FLEXNetworkDetailSection *sectionModel = self.sections[section]; + return [sectionModel.rows count]; +} + +- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section +{ + FLEXNetworkDetailSection *sectionModel = self.sections[section]; + return sectionModel.title; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXMultilineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXMultilineTableViewCellIdentifier forIndexPath:indexPath]; + + FLEXNetworkDetailRow *rowModel = [self rowModelAtIndexPath:indexPath]; + + cell.textLabel.attributedText = [[self class] attributedTextForRow:rowModel]; + cell.accessoryType = rowModel.selectionFuture ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone; + cell.selectionStyle = rowModel.selectionFuture ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone; + + return cell; +} + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXNetworkDetailRow *rowModel = [self rowModelAtIndexPath:indexPath]; + + UIViewController *viewControllerToPush = nil; + if (rowModel.selectionFuture) { + viewControllerToPush = rowModel.selectionFuture(); + } + + if (viewControllerToPush) { + [self.navigationController pushViewController:viewControllerToPush animated:YES]; + } + + [tableView deselectRowAtIndexPath:indexPath animated:YES]; +} + +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXNetworkDetailRow *row = [self rowModelAtIndexPath:indexPath]; + NSAttributedString *attributedText = [[self class] attributedTextForRow:row]; + BOOL showsAccessory = row.selectionFuture != nil; + return [FLEXMultilineTableViewCell preferredHeightWithAttributedText:attributedText inTableViewWidth:self.tableView.bounds.size.width style:UITableViewStyleGrouped showsAccessory:showsAccessory]; +} + +- (FLEXNetworkDetailRow *)rowModelAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXNetworkDetailSection *sectionModel = self.sections[indexPath.section]; + return sectionModel.rows[indexPath.row]; +} + +#pragma mark - Cell Copying + +- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath +{ + return YES; +} + +- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + return action == @selector(copy:); +} + +- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + if (action == @selector(copy:)) { + FLEXNetworkDetailRow *row = [self rowModelAtIndexPath:indexPath]; + [[UIPasteboard generalPasteboard] setString:row.detailText]; + } +} + +#pragma mark - View Configuration + ++ (NSAttributedString *)attributedTextForRow:(FLEXNetworkDetailRow *)row +{ + NSDictionary *titleAttributes = @{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Medium" size:12.0], + NSForegroundColorAttributeName : [UIColor colorWithWhite:0.5 alpha:1.0] }; + NSDictionary *detailAttributes = @{ NSFontAttributeName : [FLEXUtility defaultTableViewCellLabelFont], + NSForegroundColorAttributeName : [UIColor blackColor] }; + + NSString *title = [NSString stringWithFormat:@"%@: ", row.title]; + NSString *detailText = row.detailText ?: @""; + NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init]; + [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:title attributes:titleAttributes]]; + [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:detailText attributes:detailAttributes]]; + + return attributedText; +} + +#pragma mark - Table Data Generation + ++ (FLEXNetworkDetailSection *)generalSectionForTransaction:(FLEXNetworkTransaction *)transaction +{ + NSMutableArray *rows = [NSMutableArray array]; + + FLEXNetworkDetailRow *requestURLRow = [[FLEXNetworkDetailRow alloc] init]; + requestURLRow.title = @"Request URL"; + NSURL *url = transaction.request.URL; + requestURLRow.detailText = url.absoluteString; + requestURLRow.selectionFuture = ^{ + UIViewController *urlWebViewController = [[FLEXWebViewController alloc] initWithURL:url]; + urlWebViewController.title = url.absoluteString; + return urlWebViewController; + }; + [rows addObject:requestURLRow]; + + FLEXNetworkDetailRow *requestMethodRow = [[FLEXNetworkDetailRow alloc] init]; + requestMethodRow.title = @"Request Method"; + requestMethodRow.detailText = transaction.request.HTTPMethod; + [rows addObject:requestMethodRow]; + + if ([transaction.cachedRequestBody length] > 0) { + FLEXNetworkDetailRow *postBodySizeRow = [[FLEXNetworkDetailRow alloc] init]; + postBodySizeRow.title = @"Request Body Size"; + postBodySizeRow.detailText = [NSByteCountFormatter stringFromByteCount:[transaction.cachedRequestBody length] countStyle:NSByteCountFormatterCountStyleBinary]; + [rows addObject:postBodySizeRow]; + + FLEXNetworkDetailRow *postBodyRow = [[FLEXNetworkDetailRow alloc] init]; + postBodyRow.title = @"Request Body"; + postBodyRow.detailText = @"tap to view"; + postBodyRow.selectionFuture = ^{ + NSString *contentType = [transaction.request valueForHTTPHeaderField:@"Content-Type"]; + UIViewController *detailViewController = [self detailViewControllerForMIMEType:contentType data:[self postBodyDataForTransaction:transaction]]; + if (detailViewController) { + detailViewController.title = @"Request Body"; + } else { + NSString *alertMessage = [NSString stringWithFormat:@"FLEX does not have a viewer for request body data with MIME type: %@", [transaction.request valueForHTTPHeaderField:@"Content-Type"]]; + [[[UIAlertView alloc] initWithTitle:@"Can't View Body Data" message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; + } + return detailViewController; + }; + [rows addObject:postBodyRow]; + } + + NSString *statusCodeString = [FLEXUtility statusCodeStringFromURLResponse:transaction.response]; + if ([statusCodeString length] > 0) { + FLEXNetworkDetailRow *statusCodeRow = [[FLEXNetworkDetailRow alloc] init]; + statusCodeRow.title = @"Status Code"; + statusCodeRow.detailText = statusCodeString; + [rows addObject:statusCodeRow]; + } + + if (transaction.error) { + FLEXNetworkDetailRow *errorRow = [[FLEXNetworkDetailRow alloc] init]; + errorRow.title = @"Error"; + errorRow.detailText = transaction.error.localizedDescription; + [rows addObject:errorRow]; + } + + FLEXNetworkDetailRow *responseBodyRow = [[FLEXNetworkDetailRow alloc] init]; + responseBodyRow.title = @"Response Body"; + NSData *responseData = [[FLEXNetworkRecorder defaultRecorder] cachedResponseBodyForTransaction:transaction]; + if ([responseData length] > 0) { + responseBodyRow.detailText = @"tap to view"; + // Avoid a long lived strong reference to the response data in case we need to purge it from the cache. + __weak NSData *weakResponseData = responseData; + responseBodyRow.selectionFuture = ^{ + UIViewController *responseBodyDetailViewController = nil; + NSData *strongResponseData = weakResponseData; + if (strongResponseData) { + responseBodyDetailViewController = [self detailViewControllerForMIMEType:transaction.response.MIMEType data:strongResponseData]; + if (!responseBodyDetailViewController) { + NSString *alertMessage = [NSString stringWithFormat:@"FLEX does not have a viewer for responses with MIME type: %@", transaction.response.MIMEType]; + [[[UIAlertView alloc] initWithTitle:@"Can't View Response" message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; + } + responseBodyDetailViewController.title = @"Response"; + } else { + NSString *alertMessage = @"The response has been purged from the cache"; + [[[UIAlertView alloc] initWithTitle:@"Can't View Response" message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; + } + return responseBodyDetailViewController; + }; + } else { + BOOL emptyResponse = transaction.receivedDataLength == 0; + responseBodyRow.detailText = emptyResponse ? @"empty" : @"not in cache"; + } + [rows addObject:responseBodyRow]; + + FLEXNetworkDetailRow *responseSizeRow = [[FLEXNetworkDetailRow alloc] init]; + responseSizeRow.title = @"Response Size"; + responseSizeRow.detailText = [NSByteCountFormatter stringFromByteCount:transaction.receivedDataLength countStyle:NSByteCountFormatterCountStyleBinary]; + [rows addObject:responseSizeRow]; + + FLEXNetworkDetailRow *mimeTypeRow = [[FLEXNetworkDetailRow alloc] init]; + mimeTypeRow.title = @"MIME Type"; + mimeTypeRow.detailText = transaction.response.MIMEType; + [rows addObject:mimeTypeRow]; + + FLEXNetworkDetailRow *mechanismRow = [[FLEXNetworkDetailRow alloc] init]; + mechanismRow.title = @"Mechanism"; + mechanismRow.detailText = transaction.requestMechanism; + [rows addObject:mechanismRow]; + + NSDateFormatter *startTimeFormatter = [[NSDateFormatter alloc] init]; + startTimeFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS"; + + FLEXNetworkDetailRow *localStartTimeRow = [[FLEXNetworkDetailRow alloc] init]; + localStartTimeRow.title = [NSString stringWithFormat:@"Start Time (%@)", [[NSTimeZone localTimeZone] abbreviationForDate:transaction.startTime]]; + localStartTimeRow.detailText = [startTimeFormatter stringFromDate:transaction.startTime]; + [rows addObject:localStartTimeRow]; + + startTimeFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; + + FLEXNetworkDetailRow *utcStartTimeRow = [[FLEXNetworkDetailRow alloc] init]; + utcStartTimeRow.title = @"Start Time (UTC)"; + utcStartTimeRow.detailText = [startTimeFormatter stringFromDate:transaction.startTime]; + [rows addObject:utcStartTimeRow]; + + FLEXNetworkDetailRow *unixStartTime = [[FLEXNetworkDetailRow alloc] init]; + unixStartTime.title = @"Unix Start Time"; + unixStartTime.detailText = [NSString stringWithFormat:@"%f", [transaction.startTime timeIntervalSince1970]]; + [rows addObject:unixStartTime]; + + FLEXNetworkDetailRow *durationRow = [[FLEXNetworkDetailRow alloc] init]; + durationRow.title = @"Total Duration"; + durationRow.detailText = [FLEXUtility stringFromRequestDuration:transaction.duration]; + [rows addObject:durationRow]; + + FLEXNetworkDetailRow *latencyRow = [[FLEXNetworkDetailRow alloc] init]; + latencyRow.title = @"Latency"; + latencyRow.detailText = [FLEXUtility stringFromRequestDuration:transaction.latency]; + [rows addObject:latencyRow]; + + FLEXNetworkDetailSection *generalSection = [[FLEXNetworkDetailSection alloc] init]; + generalSection.title = @"General"; + generalSection.rows = rows; + + return generalSection; +} + ++ (FLEXNetworkDetailSection *)requestHeadersSectionForTransaction:(FLEXNetworkTransaction *)transaction +{ + FLEXNetworkDetailSection *requestHeadersSection = [[FLEXNetworkDetailSection alloc] init]; + requestHeadersSection.title = @"Request Headers"; + requestHeadersSection.rows = [self networkDetailRowsFromDictionary:transaction.request.allHTTPHeaderFields]; + + return requestHeadersSection; +} + ++ (FLEXNetworkDetailSection *)postBodySectionForTransaction:(FLEXNetworkTransaction *)transaction +{ + FLEXNetworkDetailSection *postBodySection = [[FLEXNetworkDetailSection alloc] init]; + postBodySection.title = @"Request Body Parameters"; + if ([transaction.cachedRequestBody length] > 0) { + NSString *contentType = [transaction.request valueForHTTPHeaderField:@"Content-Type"]; + if ([contentType hasPrefix:@"application/x-www-form-urlencoded"]) { + NSString *bodyString = [[NSString alloc] initWithData:[self postBodyDataForTransaction:transaction] encoding:NSUTF8StringEncoding]; + postBodySection.rows = [self networkDetailRowsFromDictionary:[FLEXUtility dictionaryFromQuery:bodyString]]; + } + } + return postBodySection; +} + ++ (FLEXNetworkDetailSection *)queryParametersSectionForTransaction:(FLEXNetworkTransaction *)transaction +{ + NSDictionary *queryDictionary = [FLEXUtility dictionaryFromQuery:transaction.request.URL.query]; + FLEXNetworkDetailSection *querySection = [[FLEXNetworkDetailSection alloc] init]; + querySection.title = @"Query Parameters"; + querySection.rows = [self networkDetailRowsFromDictionary:queryDictionary]; + + return querySection; +} + ++ (FLEXNetworkDetailSection *)responseHeadersSectionForTransaction:(FLEXNetworkTransaction *)transaction +{ + FLEXNetworkDetailSection *responseHeadersSection = [[FLEXNetworkDetailSection alloc] init]; + responseHeadersSection.title = @"Response Headers"; + if ([transaction.response isKindOfClass:[NSHTTPURLResponse class]]) { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)transaction.response; + responseHeadersSection.rows = [self networkDetailRowsFromDictionary:httpResponse.allHeaderFields]; + } + return responseHeadersSection; +} + ++ (NSArray *)networkDetailRowsFromDictionary:(NSDictionary *)dictionary +{ + NSMutableArray *rows = [NSMutableArray arrayWithCapacity:[dictionary count]]; + NSArray *sortedKeys = [[dictionary allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; + for (NSString *key in sortedKeys) { + NSString *value = dictionary[key]; + FLEXNetworkDetailRow *row = [[FLEXNetworkDetailRow alloc] init]; + row.title = key; + row.detailText = [value description]; + [rows addObject:row]; + } + return [rows copy]; +} + ++ (UIViewController *)detailViewControllerForMIMEType:(NSString *)mimeType data:(NSData *)data +{ + // FIXME (RKO): Don't rely on UTF8 string encoding + UIViewController *detailViewController = nil; + if ([FLEXUtility isValidJSONData:data]) { + NSString *prettyJSON = [FLEXUtility prettyJSONStringFromData:data]; + if ([prettyJSON length] > 0) { + detailViewController = [[FLEXWebViewController alloc] initWithText:prettyJSON]; + } + } else if ([mimeType hasPrefix:@"image/"]) { + UIImage *image = [UIImage imageWithData:data]; + detailViewController = [[FLEXImagePreviewViewController alloc] initWithImage:image]; + } else if ([mimeType isEqual:@"application/x-plist"]) { + id propertyList = [NSPropertyListSerialization propertyListWithData:data options:0 format:NULL error:NULL]; + detailViewController = [[FLEXWebViewController alloc] initWithText:[propertyList description]]; + } + + // Fall back to trying to show the response as text + if (!detailViewController) { + NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + if ([text length] > 0) { + detailViewController = [[FLEXWebViewController alloc] initWithText:text]; + } + } + return detailViewController; +} + ++ (NSData *)postBodyDataForTransaction:(FLEXNetworkTransaction *)transaction +{ + NSData *bodyData = transaction.cachedRequestBody; + if ([bodyData length] > 0) { + NSString *contentEncoding = [transaction.request valueForHTTPHeaderField:@"Content-Encoding"]; + if ([contentEncoding rangeOfString:@"deflate" options:NSCaseInsensitiveSearch].length > 0 || [contentEncoding rangeOfString:@"gzip" options:NSCaseInsensitiveSearch].length > 0) { + bodyData = [FLEXUtility inflatedDataFromCompressedData:bodyData]; + } + } + return bodyData; +} + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkTransactionTableViewCell.h b/Pods/FLEX/Classes/Network/FLEXNetworkTransactionTableViewCell.h new file mode 100644 index 0000000000..385573da95 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkTransactionTableViewCell.h @@ -0,0 +1,21 @@ +// +// FLEXNetworkTransactionTableViewCell.h +// Flipboard +// +// Created by Ryan Olson on 2/8/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import + +extern NSString *const kFLEXNetworkTransactionCellIdentifier; + +@class FLEXNetworkTransaction; + +@interface FLEXNetworkTransactionTableViewCell : UITableViewCell + +@property (nonatomic, strong) FLEXNetworkTransaction *transaction; + ++ (CGFloat)preferredCellHeight; + +@end diff --git a/Pods/FLEX/Classes/Network/FLEXNetworkTransactionTableViewCell.m b/Pods/FLEX/Classes/Network/FLEXNetworkTransactionTableViewCell.m new file mode 100644 index 0000000000..3037989332 --- /dev/null +++ b/Pods/FLEX/Classes/Network/FLEXNetworkTransactionTableViewCell.m @@ -0,0 +1,180 @@ +// +// FLEXNetworkTransactionTableViewCell.m +// Flipboard +// +// Created by Ryan Olson on 2/8/15. +// Copyright (c) 2015 Flipboard. All rights reserved. +// + +#import "FLEXNetworkTransactionTableViewCell.h" +#import "FLEXNetworkTransaction.h" +#import "FLEXUtility.h" +#import "FLEXResources.h" + +NSString *const kFLEXNetworkTransactionCellIdentifier = @"kFLEXNetworkTransactionCellIdentifier"; + +@interface FLEXNetworkTransactionTableViewCell () + +@property (nonatomic, strong) UIImageView *thumbnailImageView; +@property (nonatomic, strong) UILabel *nameLabel; +@property (nonatomic, strong) UILabel *pathLabel; +@property (nonatomic, strong) UILabel *transactionDetailsLabel; + +@end + +@implementation FLEXNetworkTransactionTableViewCell + +- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier +{ + self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; + if (self) { + self.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + + self.nameLabel = [[UILabel alloc] init]; + self.nameLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + [self.contentView addSubview:self.nameLabel]; + + self.pathLabel = [[UILabel alloc] init]; + self.pathLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + self.pathLabel.textColor = [UIColor colorWithWhite:0.4 alpha:1.0]; + [self.contentView addSubview:self.pathLabel]; + + self.thumbnailImageView = [[UIImageView alloc] init]; + self.thumbnailImageView.layer.borderColor = [[UIColor blackColor] CGColor]; + self.thumbnailImageView.layer.borderWidth = 1.0; + self.thumbnailImageView.contentMode = UIViewContentModeScaleAspectFit; + [self.contentView addSubview:self.thumbnailImageView]; + + self.transactionDetailsLabel = [[UILabel alloc] init]; + self.transactionDetailsLabel.font = [FLEXUtility defaultFontOfSize:10.0]; + self.transactionDetailsLabel.textColor = [UIColor colorWithWhite:0.65 alpha:1.0]; + [self.contentView addSubview:self.transactionDetailsLabel]; + } + return self; +} + +- (void)setTransaction:(FLEXNetworkTransaction *)transaction +{ + if (_transaction != transaction) { + _transaction = transaction; + [self setNeedsLayout]; + } +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + const CGFloat kVerticalPadding = 8.0; + const CGFloat kLeftPadding = 10.0; + const CGFloat kImageDimension = 32.0; + + CGFloat thumbnailOriginY = round((self.contentView.bounds.size.height - kImageDimension) / 2.0); + self.thumbnailImageView.frame = CGRectMake(kLeftPadding, thumbnailOriginY, kImageDimension, kImageDimension); + self.thumbnailImageView.image = self.transaction.responseThumbnail; + + CGFloat textOriginX = CGRectGetMaxX(self.thumbnailImageView.frame) + kLeftPadding; + CGFloat availableTextWidth = self.contentView.bounds.size.width - textOriginX; + + self.nameLabel.text = [self nameLabelText]; + CGSize nameLabelPreferredSize = [self.nameLabel sizeThatFits:CGSizeMake(availableTextWidth, CGFLOAT_MAX)]; + self.nameLabel.frame = CGRectMake(textOriginX, kVerticalPadding, availableTextWidth, nameLabelPreferredSize.height); + self.nameLabel.textColor = self.transaction.error ? [UIColor redColor] : [UIColor blackColor]; + + self.pathLabel.text = [self pathLabelText]; + CGSize pathLabelPreferredSize = [self.pathLabel sizeThatFits:CGSizeMake(availableTextWidth, CGFLOAT_MAX)]; + CGFloat pathLabelOriginY = ceil((self.contentView.bounds.size.height - pathLabelPreferredSize.height) / 2.0); + self.pathLabel.frame = CGRectMake(textOriginX, pathLabelOriginY, availableTextWidth, pathLabelPreferredSize.height); + + self.transactionDetailsLabel.text = [self transactionDetailsLabelText]; + CGSize transactionLabelPreferredSize = [self.transactionDetailsLabel sizeThatFits:CGSizeMake(availableTextWidth, CGFLOAT_MAX)]; + CGFloat transactionDetailsOriginX = textOriginX; + CGFloat transactionDetailsLabelOriginY = CGRectGetMaxY(self.contentView.bounds) - kVerticalPadding - transactionLabelPreferredSize.height; + CGFloat transactionDetailsLabelWidth = self.contentView.bounds.size.width - transactionDetailsOriginX; + self.transactionDetailsLabel.frame = CGRectMake(transactionDetailsOriginX, transactionDetailsLabelOriginY, transactionDetailsLabelWidth, transactionLabelPreferredSize.height); +} + +- (NSString *)nameLabelText +{ + NSURL *url = self.transaction.request.URL; + NSString *name = [url lastPathComponent]; + if ([name length] == 0) { + name = @"/"; + } + NSString *query = [url query]; + if (query) { + name = [name stringByAppendingFormat:@"?%@", query]; + } + return name; +} + +- (NSString *)pathLabelText +{ + NSURL *url = self.transaction.request.URL; + NSMutableArray *mutablePathComponents = [[url pathComponents] mutableCopy]; + if ([mutablePathComponents count] > 0) { + [mutablePathComponents removeLastObject]; + } + NSString *path = [url host]; + for (NSString *pathComponent in mutablePathComponents) { + path = [path stringByAppendingPathComponent:pathComponent]; + } + return path; +} + +- (NSString *)transactionDetailsLabelText +{ + NSMutableArray *detailComponents = [NSMutableArray array]; + + NSString *timestamp = [[self class] timestampStringFromRequestDate:self.transaction.startTime]; + if ([timestamp length] > 0) { + [detailComponents addObject:timestamp]; + } + + // Omit method for GET (assumed as default) + NSString *httpMethod = self.transaction.request.HTTPMethod; + if ([httpMethod length] > 0) { + [detailComponents addObject:httpMethod]; + } + + if (self.transaction.transactionState == FLEXNetworkTransactionStateFinished || self.transaction.transactionState == FLEXNetworkTransactionStateFailed) { + NSString *statusCodeString = [FLEXUtility statusCodeStringFromURLResponse:self.transaction.response]; + if ([statusCodeString length] > 0) { + [detailComponents addObject:statusCodeString]; + } + + if (self.transaction.receivedDataLength > 0) { + NSString *responseSize = [NSByteCountFormatter stringFromByteCount:self.transaction.receivedDataLength countStyle:NSByteCountFormatterCountStyleBinary]; + [detailComponents addObject:responseSize]; + } + + NSString *totalDuration = [FLEXUtility stringFromRequestDuration:self.transaction.duration]; + NSString *latency = [FLEXUtility stringFromRequestDuration:self.transaction.latency]; + NSString *duration = [NSString stringWithFormat:@"%@ (%@)", totalDuration, latency]; + [detailComponents addObject:duration]; + } else { + // Unstarted, Awaiting Response, Receiving Data, etc. + NSString *state = [FLEXNetworkTransaction readableStringFromTransactionState:self.transaction.transactionState]; + [detailComponents addObject:state]; + } + + return [detailComponents componentsJoinedByString:@" ・ "]; +} + ++ (NSString *)timestampStringFromRequestDate:(NSDate *)date +{ + static NSDateFormatter *dateFormatter = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + dateFormatter = [[NSDateFormatter alloc] init]; + dateFormatter.dateFormat = @"HH:mm:ss"; + }); + return [dateFormatter stringFromDate:date]; +} + ++ (CGFloat)preferredCellHeight +{ + return 65.0; +} + +@end diff --git a/Pods/FLEX/Classes/Network/PonyDebugger/FLEXNetworkObserver.h b/Pods/FLEX/Classes/Network/PonyDebugger/FLEXNetworkObserver.h new file mode 100644 index 0000000000..6e8c1d3bba --- /dev/null +++ b/Pods/FLEX/Classes/Network/PonyDebugger/FLEXNetworkObserver.h @@ -0,0 +1,29 @@ +// +// FLEXNetworkObserver.h +// Derived from: +// +// PDAFNetworkDomainController.h +// PonyDebugger +// +// Created by Mike Lewis on 2/27/12. +// +// Licensed to Square, Inc. under one or more contributor license agreements. +// See the LICENSE file distributed with this work for the terms under +// which Square, Inc. licenses this file to you. +// + +#import + +extern NSString *const kFLEXNetworkObserverEnabledStateChangedNotification; + +/// This class swizzles NSURLConnection and NSURLSession delegate methods to observe events in the URL loading system. +/// High level network events are sent to the default FLEXNetworkRecorder instance which maintains the request history and caches response bodies. +@interface FLEXNetworkObserver : NSObject + +/// Swizzling occurs when the observer is enabled for the first time. +/// This reduces the impact of FLEX if network debugging is not desired. +/// NOTE: this setting persists between launches of the app. ++ (void)setEnabled:(BOOL)enabled; ++ (BOOL)isEnabled; + +@end diff --git a/Pods/FLEX/Classes/Network/PonyDebugger/FLEXNetworkObserver.m b/Pods/FLEX/Classes/Network/PonyDebugger/FLEXNetworkObserver.m new file mode 100644 index 0000000000..637beacc5f --- /dev/null +++ b/Pods/FLEX/Classes/Network/PonyDebugger/FLEXNetworkObserver.m @@ -0,0 +1,1122 @@ +// +// FLEXNetworkObserver.m +// Derived from: +// +// PDAFNetworkDomainController.m +// PonyDebugger +// +// Created by Mike Lewis on 2/27/12. +// +// Licensed to Square, Inc. under one or more contributor license agreements. +// See the LICENSE file distributed with this work for the terms under +// which Square, Inc. licenses this file to you. +// + +#import "FLEXNetworkObserver.h" +#import "FLEXNetworkRecorder.h" +#import "FLEXUtility.h" + +#import +#import +#import + +NSString *const kFLEXNetworkObserverEnabledStateChangedNotification = @"kFLEXNetworkObserverEnabledStateChangedNotification"; +static NSString *const kFLEXNetworkObserverEnabledDefaultsKey = @"com.flex.FLEXNetworkObserver.enableOnLaunch"; + +typedef void (^NSURLSessionAsyncCompletion)(id fileURLOrData, NSURLResponse *response, NSError *error); + +@interface FLEXInternalRequestState : NSObject + +@property (nonatomic, copy) NSURLRequest *request; +@property (nonatomic, strong) NSMutableData *dataAccumulator; + +@end + +@implementation FLEXInternalRequestState + +@end + +@interface FLEXNetworkObserver (NSURLConnectionHelpers) + +- (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id )delegate; +- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id )delegate; + +- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id )delegate; + +- (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id )delegate; +- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id )delegate; + +- (void)connectionWillCancel:(NSURLConnection *)connection; + +@end + + +@interface FLEXNetworkObserver (NSURLSessionTaskHelpers) + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id )delegate; +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id )delegate; +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id )delegate; +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id )delegate; +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id )delegate; +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id )delegate; +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id )delegate; + +- (void)URLSessionTaskWillResume:(NSURLSessionTask *)task; + +@end + +@interface FLEXNetworkObserver () + +@property (nonatomic, strong) NSMutableDictionary *requestStatesForRequestIDs; +@property (nonatomic, strong) dispatch_queue_t queue; + +@end + +@implementation FLEXNetworkObserver + +#pragma mark - Public Methods + ++ (void)setEnabled:(BOOL)enabled +{ + BOOL previouslyEnabled = [self isEnabled]; + + [[NSUserDefaults standardUserDefaults] setBool:enabled forKey:kFLEXNetworkObserverEnabledDefaultsKey]; + + if (enabled) { + // Inject if needed. This injection is protected with a dispatch_once, so we're ok calling it multiple times. + // By doing the injection lazily, we keep the impact of the tool lower when this feature isn't enabled. + [self injectIntoAllNSURLConnectionDelegateClasses]; + } + + if (previouslyEnabled != enabled) { + [[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkObserverEnabledStateChangedNotification object:self]; + } +} + ++ (BOOL)isEnabled +{ + return [[[NSUserDefaults standardUserDefaults] objectForKey:kFLEXNetworkObserverEnabledDefaultsKey] boolValue]; +} + ++ (void)load +{ + // We don't want to do the swizzling from +load because not all the classes may be loaded at this point. + dispatch_async(dispatch_get_main_queue(), ^{ + if ([self isEnabled]) { + [self injectIntoAllNSURLConnectionDelegateClasses]; + } + }); +} + +#pragma mark - Statics + ++ (instancetype)sharedObserver +{ + static FLEXNetworkObserver *sharedObserver = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedObserver = [[[self class] alloc] init]; + }); + return sharedObserver; +} + ++ (NSString *)nextRequestID +{ + return [[NSUUID UUID] UUIDString]; +} + +#pragma mark Delegate Injection Convenience Methods + +/// All swizzled delegate methods should make use of this guard. +/// This will prevent duplicated sniffing when the original implementation calls up to a superclass implementation which we've also swizzled. +/// The superclass implementation (and implementations in classes above that) will be executed without inteference if called from the original implementation. ++ (void)sniffWithoutDuplicationForObject:(NSObject *)object selector:(SEL)selector sniffingBlock:(void (^)(void))sniffingBlock originalImplementationBlock:(void (^)(void))originalImplementationBlock +{ + // If we don't have an object to detect nested calls on, just run the original implmentation and bail. + // This case can happen if someone besides the URL loading system calls the delegate methods directly. + // See https://github.com/Flipboard/FLEX/issues/61 for an example. + if (!object) { + originalImplementationBlock(); + return; + } + + const void *key = selector; + + // Don't run the sniffing block if we're inside a nested call + if (!objc_getAssociatedObject(object, key)) { + sniffingBlock(); + } + + // Mark that we're calling through to the original so we can detect nested calls + objc_setAssociatedObject(object, key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + originalImplementationBlock(); + objc_setAssociatedObject(object, key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - Delegate Injection + ++ (void)injectIntoAllNSURLConnectionDelegateClasses +{ + // Only allow swizzling once. + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // Swizzle any classes that implement one of these selectors. + const SEL selectors[] = { + @selector(connectionDidFinishLoading:), + @selector(connection:willSendRequest:redirectResponse:), + @selector(connection:didReceiveResponse:), + @selector(connection:didReceiveData:), + @selector(connection:didFailWithError:), + @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:), + @selector(URLSession:dataTask:didReceiveData:), + @selector(URLSession:dataTask:didReceiveResponse:completionHandler:), + @selector(URLSession:task:didCompleteWithError:), + @selector(URLSession:dataTask:didBecomeDownloadTask:delegate:), + @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:), + @selector(URLSession:downloadTask:didFinishDownloadingToURL:) + }; + + const int numSelectors = sizeof(selectors) / sizeof(SEL); + + Class *classes = NULL; + int numClasses = objc_getClassList(NULL, 0); + + if (numClasses > 0) { + classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses); + numClasses = objc_getClassList(classes, numClasses); + for (NSInteger classIndex = 0; classIndex < numClasses; ++classIndex) { + Class class = classes[classIndex]; + + if (class == [FLEXNetworkObserver class]) { + continue; + } + + // Use the runtime API rather than the methods on NSObject to avoid sending messages to + // classes we're not interested in swizzling. Otherwise we hit +initialize on all classes. + // NOTE: calling class_getInstanceMethod() DOES send +initialize to the class. That's why we iterate through the method list. + unsigned int methodCount = 0; + Method *methods = class_copyMethodList(class, &methodCount); + BOOL matchingSelectorFound = NO; + for (unsigned int methodIndex = 0; methodIndex < methodCount; methodIndex++) { + for (int selectorIndex = 0; selectorIndex < numSelectors; ++selectorIndex) { + if (method_getName(methods[methodIndex]) == selectors[selectorIndex]) { + [self injectIntoDelegateClass:class]; + matchingSelectorFound = YES; + break; + } + } + if (matchingSelectorFound) { + break; + } + } + free(methods); + } + + free(classes); + } + + [self injectIntoNSURLConnectionCancel]; + [self injectIntoNSURLSessionTaskResume]; + + [self injectIntoNSURLConnectionAsynchronousClassMethod]; + [self injectIntoNSURLConnectionSynchronousClassMethod]; + + [self injectIntoNSURLSessionAsyncDataAndDownloadTaskMethods]; + [self injectIntoNSURLSessionAsyncUploadTaskMethods]; + }); +} + ++ (void)injectIntoDelegateClass:(Class)cls +{ + // Connections + [self injectWillSendRequestIntoDelegateClass:cls]; + [self injectDidReceiveDataIntoDelegateClass:cls]; + [self injectDidReceiveResponseIntoDelegateClass:cls]; + [self injectDidFinishLoadingIntoDelegateClass:cls]; + [self injectDidFailWithErrorIntoDelegateClass:cls]; + + // Sessions + [self injectTaskWillPerformHTTPRedirectionIntoDelegateClass:cls]; + [self injectTaskDidReceiveDataIntoDelegateClass:cls]; + [self injectTaskDidReceiveResponseIntoDelegateClass:cls]; + [self injectTaskDidCompleteWithErrorIntoDelegateClass:cls]; + [self injectRespondsToSelectorIntoDelegateClass:cls]; + + // Data tasks + [self injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:cls]; + + // Download tasks + [self injectDownloadTaskDidWriteDataIntoDelegateClass:cls]; + [self injectDownloadTaskDidFinishDownloadingIntoDelegateClass:cls]; +} + ++ (void)injectIntoNSURLConnectionCancel +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class class = [NSURLConnection class]; + SEL selector = @selector(cancel); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + Method originalCancel = class_getInstanceMethod(class, selector); + + void (^swizzleBlock)(NSURLConnection *) = ^(NSURLConnection *slf) { + [[FLEXNetworkObserver sharedObserver] connectionWillCancel:slf]; + ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector); + }; + + IMP implementation = imp_implementationWithBlock(swizzleBlock); + class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalCancel)); + Method newCancel = class_getInstanceMethod(class, swizzledSelector); + method_exchangeImplementations(originalCancel, newCancel); + }); +} + ++ (void)injectIntoNSURLSessionTaskResume +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // In iOS 7 resume lives in __NSCFLocalSessionTask + // In iOS 8 resume lives in NSURLSessionTask + // In iOS 9 resume lives in __NSCFURLSessionTask + Class class = Nil; + if (![[NSProcessInfo processInfo] respondsToSelector:@selector(operatingSystemVersion)]) { + class = NSClassFromString([@[@"__", @"NSC", @"FLocalS", @"ession", @"Task"] componentsJoinedByString:@""]); + } else if ([[NSProcessInfo processInfo] operatingSystemVersion].majorVersion < 9) { + class = [NSURLSessionTask class]; + } else { + class = NSClassFromString([@[@"__", @"NSC", @"FURLS", @"ession", @"Task"] componentsJoinedByString:@""]); + } + SEL selector = @selector(resume); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Method originalResume = class_getInstanceMethod(class, selector); + + void (^swizzleBlock)(NSURLSessionTask *) = ^(NSURLSessionTask *slf) { + [[FLEXNetworkObserver sharedObserver] URLSessionTaskWillResume:slf]; + ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector); + }; + + IMP implementation = imp_implementationWithBlock(swizzleBlock); + class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalResume)); + Method newResume = class_getInstanceMethod(class, swizzledSelector); + method_exchangeImplementations(originalResume, newResume); + }); +} + ++ (void)injectIntoNSURLConnectionAsynchronousClassMethod +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class class = objc_getMetaClass(class_getName([NSURLConnection class])); + SEL selector = @selector(sendAsynchronousRequest:queue:completionHandler:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + typedef void (^NSURLConnectionAsyncCompletion)(NSURLResponse* response, NSData* data, NSError* connectionError); + + void (^asyncSwizzleBlock)(Class, NSURLRequest *, NSOperationQueue *, NSURLConnectionAsyncCompletion) = ^(Class slf, NSURLRequest *request, NSOperationQueue *queue, NSURLConnectionAsyncCompletion completion) { + if ([FLEXNetworkObserver isEnabled]) { + NSString *requestID = [self nextRequestID]; + [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:nil]; + NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class]; + [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID]; + NSURLConnectionAsyncCompletion completionWrapper = ^(NSURLResponse *response, NSData *data, NSError *connectionError) { + [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response]; + [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]]; + if (connectionError) { + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:connectionError]; + } else { + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data]; + } + + // Call through to the original completion handler + if (completion) { + completion(response, data, connectionError); + } + }; + ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, queue, completionWrapper); + } else { + ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, queue, completion); + } + }; + + [FLEXUtility replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncSwizzleBlock swizzledSelector:swizzledSelector]; + }); +} + ++ (void)injectIntoNSURLConnectionSynchronousClassMethod +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class class = objc_getMetaClass(class_getName([NSURLConnection class])); + SEL selector = @selector(sendSynchronousRequest:returningResponse:error:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + NSData *(^syncSwizzleBlock)(Class, NSURLRequest *, NSURLResponse **, NSError **) = ^NSData *(Class slf, NSURLRequest *request, NSURLResponse **response, NSError **error) { + NSData *data = nil; + if ([FLEXNetworkObserver isEnabled]) { + NSString *requestID = [self nextRequestID]; + [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:nil]; + NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class]; + [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID]; + NSError *temporaryError = nil; + NSURLResponse *temporaryResponse = nil; + data = ((id(*)(id, SEL, id, NSURLResponse **, NSError **))objc_msgSend)(slf, swizzledSelector, request, &temporaryResponse, &temporaryError); + [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:temporaryResponse]; + [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]]; + if (temporaryError) { + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:temporaryError]; + } else { + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data]; + } + if (error) { + *error = temporaryError; + } + if (response) { + *response = temporaryResponse; + } + } else { + data = ((id(*)(id, SEL, id, NSURLResponse **, NSError **))objc_msgSend)(slf, swizzledSelector, request, response, error); + } + + return data; + }; + + [FLEXUtility replaceImplementationOfKnownSelector:selector onClass:class withBlock:syncSwizzleBlock swizzledSelector:swizzledSelector]; + }); +} + ++ (void)injectIntoNSURLSessionAsyncDataAndDownloadTaskMethods +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class class = [NSURLSession class]; + + // The method signatures here are close enough that we can use the same logic to inject into all of them. + const SEL selectors[] = { + @selector(dataTaskWithRequest:completionHandler:), + @selector(dataTaskWithURL:completionHandler:), + @selector(downloadTaskWithRequest:completionHandler:), + @selector(downloadTaskWithResumeData:completionHandler:), + @selector(downloadTaskWithURL:completionHandler:) + }; + + const int numSelectors = sizeof(selectors) / sizeof(SEL); + + for (int selectorIndex = 0; selectorIndex < numSelectors; selectorIndex++) { + SEL selector = selectors[selectorIndex]; + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + if ([FLEXUtility instanceRespondsButDoesNotImplementSelector:selector class:class]) { + // iOS 7 does not implement these methods on NSURLSession. We actually want to + // swizzle __NSCFURLSession, which we can get from the class of the shared session + class = [[NSURLSession sharedSession] class]; + } + + NSURLSessionTask *(^asyncDataOrDownloadSwizzleBlock)(Class, id, NSURLSessionAsyncCompletion) = ^NSURLSessionTask *(Class slf, id argument, NSURLSessionAsyncCompletion completion) { + NSURLSessionTask *task = nil; + // If completion block was not provided sender expect to receive delegated methods or does not + // interested in callback at all. In this case we should just call original method implementation + // with nil completion block. + if ([FLEXNetworkObserver isEnabled] && completion) { + NSString *requestID = [self nextRequestID]; + NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class]; + NSURLSessionAsyncCompletion completionWrapper = [self asyncCompletionWrapperForRequestID:requestID mechanism:mechanism completion:completion]; + task = ((id(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, argument, completionWrapper); + [self setRequestID:requestID forConnectionOrTask:task]; + } else { + task = ((id(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, argument, completion); + } + return task; + }; + + [FLEXUtility replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncDataOrDownloadSwizzleBlock swizzledSelector:swizzledSelector]; + } + }); +} + ++ (void)injectIntoNSURLSessionAsyncUploadTaskMethods +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class class = [NSURLSession class]; + + // The method signatures here are close enough that we can use the same logic to inject into both of them. + // Note that they have 3 arguments, so we can't easily combine with the data and download method above. + const SEL selectors[] = { + @selector(uploadTaskWithRequest:fromData:completionHandler:), + @selector(uploadTaskWithRequest:fromFile:completionHandler:) + }; + + const int numSelectors = sizeof(selectors) / sizeof(SEL); + + for (int selectorIndex = 0; selectorIndex < numSelectors; selectorIndex++) { + SEL selector = selectors[selectorIndex]; + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + if ([FLEXUtility instanceRespondsButDoesNotImplementSelector:selector class:class]) { + // iOS 7 does not implement these methods on NSURLSession. We actually want to + // swizzle __NSCFURLSession, which we can get from the class of the shared session + class = [[NSURLSession sharedSession] class]; + } + + NSURLSessionUploadTask *(^asyncUploadTaskSwizzleBlock)(Class, NSURLRequest *, id, NSURLSessionAsyncCompletion) = ^NSURLSessionUploadTask *(Class slf, NSURLRequest *request, id argument, NSURLSessionAsyncCompletion completion) { + NSURLSessionUploadTask *task = nil; + if ([FLEXNetworkObserver isEnabled]) { + NSString *requestID = [self nextRequestID]; + NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class]; + NSURLSessionAsyncCompletion completionWrapper = [self asyncCompletionWrapperForRequestID:requestID mechanism:mechanism completion:completion]; + task = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, argument, completionWrapper); + [self setRequestID:requestID forConnectionOrTask:task]; + } else { + task = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, argument, completion); + } + return task; + }; + + [FLEXUtility replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncUploadTaskSwizzleBlock swizzledSelector:swizzledSelector]; + } + }); +} + ++ (NSString *)mechansimFromClassMethod:(SEL)selector onClass:(Class)class +{ + return [NSString stringWithFormat:@"+[%@ %@]", NSStringFromClass(class), NSStringFromSelector(selector)]; +} + ++ (NSURLSessionAsyncCompletion)asyncCompletionWrapperForRequestID:(NSString *)requestID mechanism:(NSString *)mechanism completion:(NSURLSessionAsyncCompletion)completion +{ + NSURLSessionAsyncCompletion completionWrapper = ^(id fileURLOrData, NSURLResponse *response, NSError *error) { + [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID]; + [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response]; + NSData *data = nil; + if ([fileURLOrData isKindOfClass:[NSURL class]]) { + data = [NSData dataWithContentsOfURL:fileURLOrData]; + } else if ([fileURLOrData isKindOfClass:[NSData class]]) { + data = fileURLOrData; + } + [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]]; + if (error) { + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error]; + } else { + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data]; + } + + // Call through to the original completion handler + if (completion) { + completion(fileURLOrData, response, error); + } + }; + return completionWrapper; +} + ++ (void)injectWillSendRequestIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(connection:willSendRequest:redirectResponse:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLConnectionDataDelegate); + if (!protocol) { + protocol = @protocol(NSURLConnectionDelegate); + } + + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response); + + NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) { + [[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf]; + return request; + }; + + NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) { + __block NSURLRequest *returnValue = nil; + [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{ + undefinedBlock(slf, connection, request, response); + } originalImplementationBlock:^{ + returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response); + }]; + return returnValue; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; +} + ++ (void)injectDidReceiveResponseIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(connection:didReceiveResponse:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLConnectionDataDelegate); + if (!protocol) { + protocol = @protocol(NSURLConnectionDelegate); + } + + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLConnectionDidReceiveResponseBlock)(id slf, NSURLConnection *connection, NSURLResponse *response); + + NSURLConnectionDidReceiveResponseBlock undefinedBlock = ^(id slf, NSURLConnection *connection, NSURLResponse *response) { + [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveResponse:response delegate:slf]; + }; + + NSURLConnectionDidReceiveResponseBlock implementationBlock = ^(id slf, NSURLConnection *connection, NSURLResponse *response) { + [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{ + undefinedBlock(slf, connection, response); + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, response); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; +} + ++ (void)injectDidReceiveDataIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(connection:didReceiveData:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLConnectionDataDelegate); + if (!protocol) { + protocol = @protocol(NSURLConnectionDelegate); + } + + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLConnectionDidReceiveDataBlock)(id slf, NSURLConnection *connection, NSData *data); + + NSURLConnectionDidReceiveDataBlock undefinedBlock = ^(id slf, NSURLConnection *connection, NSData *data) { + [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveData:data delegate:slf]; + }; + + NSURLConnectionDidReceiveDataBlock implementationBlock = ^(id slf, NSURLConnection *connection, NSData *data) { + [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{ + undefinedBlock(slf, connection, data); + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, data); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; +} + ++ (void)injectDidFinishLoadingIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(connectionDidFinishLoading:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLConnectionDataDelegate); + if (!protocol) { + protocol = @protocol(NSURLConnectionDelegate); + } + + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLConnectionDidFinishLoadingBlock)(id slf, NSURLConnection *connection); + + NSURLConnectionDidFinishLoadingBlock undefinedBlock = ^(id slf, NSURLConnection *connection) { + [[FLEXNetworkObserver sharedObserver] connectionDidFinishLoading:connection delegate:slf]; + }; + + NSURLConnectionDidFinishLoadingBlock implementationBlock = ^(id slf, NSURLConnection *connection) { + [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{ + undefinedBlock(slf, connection); + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSelector, connection); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; +} + ++ (void)injectDidFailWithErrorIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(connection:didFailWithError:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLConnectionDelegate); + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLConnectionDidFailWithErrorBlock)(id slf, NSURLConnection *connection, NSError *error); + + NSURLConnectionDidFailWithErrorBlock undefinedBlock = ^(id slf, NSURLConnection *connection, NSError *error) { + [[FLEXNetworkObserver sharedObserver] connection:connection didFailWithError:error delegate:slf]; + }; + + NSURLConnectionDidFailWithErrorBlock implementationBlock = ^(id slf, NSURLConnection *connection, NSError *error) { + [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{ + undefinedBlock(slf, connection, error); + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, error); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; +} + ++ (void)injectTaskWillPerformHTTPRedirectionIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLSessionTaskDelegate); + + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLSessionWillPerformHTTPRedirectionBlock)(id slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)); + + NSURLSessionWillPerformHTTPRedirectionBlock undefinedBlock = ^(id slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) { + [[FLEXNetworkObserver sharedObserver] URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler delegate:slf]; + completionHandler(newRequest); + }; + + NSURLSessionWillPerformHTTPRedirectionBlock implementationBlock = ^(id slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) { + [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{ + [[FLEXNetworkObserver sharedObserver] URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler delegate:slf]; + } originalImplementationBlock:^{ + ((id(*)(id, SEL, id, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, task, response, newRequest, completionHandler); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; + +} + ++ (void)injectTaskDidReceiveDataIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(URLSession:dataTask:didReceiveData:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLSessionDataDelegate); + + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLSessionDidReceiveDataBlock)(id slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data); + + NSURLSessionDidReceiveDataBlock undefinedBlock = ^(id slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) { + [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveData:data delegate:slf]; + }; + + NSURLSessionDidReceiveDataBlock implementationBlock = ^(id slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) { + [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{ + undefinedBlock(slf, session, dataTask, data); + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, data); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; + +} + ++ (void)injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(URLSession:dataTask:didBecomeDownloadTask:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLSessionDataDelegate); + + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLSessionDidBecomeDownloadTaskBlock)(id slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask); + + NSURLSessionDidBecomeDownloadTaskBlock undefinedBlock = ^(id slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) { + [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didBecomeDownloadTask:downloadTask delegate:slf]; + }; + + NSURLSessionDidBecomeDownloadTaskBlock implementationBlock = ^(id slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) { + [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{ + undefinedBlock(slf, session, dataTask, downloadTask); + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, downloadTask); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; +} + ++ (void)injectTaskDidReceiveResponseIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(URLSession:dataTask:didReceiveResponse:completionHandler:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLSessionDataDelegate); + + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLSessionDidReceiveResponseBlock)(id slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)); + + NSURLSessionDidReceiveResponseBlock undefinedBlock = ^(id slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) { + [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler delegate:slf]; + completionHandler(NSURLSessionResponseAllow); + }; + + NSURLSessionDidReceiveResponseBlock implementationBlock = ^(id slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) { + [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{ + [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler delegate:slf]; + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, dataTask, response, completionHandler); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; + +} + ++ (void)injectTaskDidCompleteWithErrorIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(URLSession:task:didCompleteWithError:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLSessionTaskDelegate); + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id slf, NSURLSession *session, NSURLSessionTask *task, NSError *error); + + NSURLSessionTaskDidCompleteWithErrorBlock undefinedBlock = ^(id slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) { + [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didCompleteWithError:error delegate:slf]; + }; + + NSURLSessionTaskDidCompleteWithErrorBlock implementationBlock = ^(id slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) { + [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{ + undefinedBlock(slf, session, task, error); + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, error); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; +} + +// Used for overriding AFNetworking behavior ++ (void)injectRespondsToSelectorIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(respondsToSelector:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + //Protocol *protocol = @protocol(NSURLSessionTaskDelegate); + Method method = class_getInstanceMethod(cls, selector); + struct objc_method_description methodDescription = *method_getDescription(method); + + BOOL (^undefinedBlock)(id , SEL) = ^(id slf, SEL sel) { + return YES; + }; + + BOOL (^implementationBlock)(id , SEL) = ^(id slf, SEL sel) { + if (sel == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) { + return undefinedBlock(slf, sel); + } + return ((BOOL(*)(id, SEL, SEL))objc_msgSend)(slf, swizzledSelector, sel); + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; +} + + ++ (void)injectDownloadTaskDidFinishDownloadingIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(URLSession:downloadTask:didFinishDownloadingToURL:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLSessionDownloadDelegate); + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLSessionDownloadTaskDidFinishDownloadingBlock)(id slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location); + + NSURLSessionDownloadTaskDidFinishDownloadingBlock undefinedBlock = ^(id slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) { + NSData *data = [NSData dataWithContentsOfFile:location.relativePath]; + [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didFinishDownloadingToURL:location data:data delegate:slf]; + }; + + NSURLSessionDownloadTaskDidFinishDownloadingBlock implementationBlock = ^(id slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) { + [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{ + undefinedBlock(slf, session, task, location); + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, location); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; +} + ++ (void)injectDownloadTaskDidWriteDataIntoDelegateClass:(Class)cls +{ + SEL selector = @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:); + SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector]; + + Protocol *protocol = @protocol(NSURLSessionDownloadDelegate); + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + + typedef void (^NSURLSessionDownloadTaskDidWriteDataBlock)(id slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); + + NSURLSessionDownloadTaskDidWriteDataBlock undefinedBlock = ^(id slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) { + [[FLEXNetworkObserver sharedObserver] URLSession:session downloadTask:task didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite delegate:slf]; + }; + + NSURLSessionDownloadTaskDidWriteDataBlock implementationBlock = ^(id slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) { + [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{ + undefinedBlock(slf, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } originalImplementationBlock:^{ + ((void(*)(id, SEL, id, id, int64_t, int64_t, int64_t))objc_msgSend)(slf, swizzledSelector, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + }]; + }; + + [FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock]; + +} + +static char const * const kFLEXRequestIDKey = "kFLEXRequestIDKey"; + ++ (NSString *)requestIDForConnectionOrTask:(id)connectionOrTask +{ + NSString *requestID = objc_getAssociatedObject(connectionOrTask, kFLEXRequestIDKey); + if (!requestID) { + requestID = [self nextRequestID]; + [self setRequestID:requestID forConnectionOrTask:connectionOrTask]; + } + return requestID; +} + ++ (void)setRequestID:(NSString *)requestID forConnectionOrTask:(id)connectionOrTask +{ + objc_setAssociatedObject(connectionOrTask, kFLEXRequestIDKey, requestID, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - Initialization + +- (id)init +{ + self = [super init]; + if (self) { + self.requestStatesForRequestIDs = [[NSMutableDictionary alloc] init]; + self.queue = dispatch_queue_create("com.flex.FLEXNetworkObserver", DISPATCH_QUEUE_SERIAL); + } + return self; +} + +#pragma mark - Private Methods + +- (void)performBlock:(dispatch_block_t)block +{ + if ([[self class] isEnabled]) { + dispatch_async(_queue, block); + } +} + +- (FLEXInternalRequestState *)requestStateForRequestID:(NSString *)requestID +{ + FLEXInternalRequestState *requestState = self.requestStatesForRequestIDs[requestID]; + if (!requestState) { + requestState = [[FLEXInternalRequestState alloc] init]; + [self.requestStatesForRequestIDs setObject:requestState forKey:requestID]; + } + return requestState; +} + +- (void)removeRequestStateForRequestID:(NSString *)requestID +{ + [self.requestStatesForRequestIDs removeObjectForKey:requestID]; +} + +@end + + +@implementation FLEXNetworkObserver (NSURLConnectionHelpers) + +- (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id)delegate +{ + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:connection]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + requestState.request = request; + [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:response]; + NSString *mechanism = [NSString stringWithFormat:@"NSURLConnection (delegate: %@)", [delegate class]]; + [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID]; + }]; +} + +- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id)delegate +{ + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:connection]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + + NSMutableData *dataAccumulator = nil; + if (response.expectedContentLength < 0) { + dataAccumulator = [[NSMutableData alloc] init]; + } else { + dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength]; + } + requestState.dataAccumulator = dataAccumulator; + + [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response]; + }]; +} + +- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id)delegate +{ + // Just to be safe since we're doing this async + data = [data copy]; + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:connection]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + [requestState.dataAccumulator appendData:data]; + [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:data.length]; + }]; +} + +- (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id)delegate +{ + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:connection]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:requestState.dataAccumulator]; + [self removeRequestStateForRequestID:requestID]; + }]; +} + +- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id)delegate +{ + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:connection]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + + // Cancellations can occur prior to the willSendRequest:... NSURLConnection delegate call. + // These are pretty common and clutter up the logs. Only record the failure if the recorder already knows about the request through willSendRequest:... + if (requestState.request) { + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error]; + } + + [self removeRequestStateForRequestID:requestID]; + }]; +} + +- (void)connectionWillCancel:(NSURLConnection *)connection +{ + [self performBlock:^{ + // Mimic the behavior of NSURLSession which is to create an error on cancellation. + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"cancelled" }; + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; + [self connection:connection didFailWithError:error delegate:nil]; + }]; +} + +@end + + +@implementation FLEXNetworkObserver (NSURLSessionTaskHelpers) + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id)delegate +{ + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:task]; + [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:response]; + }]; +} + +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id)delegate +{ + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + + NSMutableData *dataAccumulator = nil; + if (response.expectedContentLength < 0) { + dataAccumulator = [[NSMutableData alloc] init]; + } else { + dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength]; + } + requestState.dataAccumulator = dataAccumulator; + + NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDataTask (delegate: %@)", [delegate class]]; + [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestID:requestID]; + + [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response]; + }]; +} + +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id)delegate +{ + [self performBlock:^{ + // By setting the request ID of the download task to match the data task, + // it can pick up where the data task left off. + NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask]; + [[self class] setRequestID:requestID forConnectionOrTask:downloadTask]; + }]; +} + +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id)delegate +{ + // Just to be safe since we're doing this async + data = [data copy]; + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + + [requestState.dataAccumulator appendData:data]; + + [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:data.length]; + }]; +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id)delegate +{ + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:task]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + + if (error) { + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error]; + } else { + [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:requestState.dataAccumulator]; + } + + [self removeRequestStateForRequestID:requestID]; + }]; +} + +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id)delegate +{ + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:downloadTask]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + + if (!requestState.dataAccumulator) { + NSUInteger unsignedBytesExpectedToWrite = totalBytesExpectedToWrite > 0 ? (NSUInteger)totalBytesExpectedToWrite : 0; + requestState.dataAccumulator = [[NSMutableData alloc] initWithCapacity:unsignedBytesExpectedToWrite]; + [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:downloadTask.response]; + + NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDownloadTask (delegate: %@)", [delegate class]]; + [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestID:requestID]; + } + + [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:bytesWritten]; + }]; +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id)delegate +{ + data = [data copy]; + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:downloadTask]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + [requestState.dataAccumulator appendData:data]; + }]; +} + +- (void)URLSessionTaskWillResume:(NSURLSessionTask *)task +{ + // Since resume can be called multiple times on the same task, only treat the first resume as + // the equivalent to connection:willSendRequest:... + [self performBlock:^{ + NSString *requestID = [[self class] requestIDForConnectionOrTask:task]; + FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID]; + if (!requestState.request) { + requestState.request = task.currentRequest; + + [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:task.currentRequest redirectResponse:nil]; + } + }]; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXArrayExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXArrayExplorerViewController.h new file mode 100644 index 0000000000..761ee06352 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXArrayExplorerViewController.h @@ -0,0 +1,13 @@ +// +// FLEXArrayExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/15/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" + +@interface FLEXArrayExplorerViewController : FLEXObjectExplorerViewController + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXArrayExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXArrayExplorerViewController.m new file mode 100644 index 0000000000..ed1b1eb6f7 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXArrayExplorerViewController.m @@ -0,0 +1,78 @@ +// +// FLEXArrayExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/15/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXArrayExplorerViewController.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXObjectExplorerFactory.h" + +@interface FLEXArrayExplorerViewController () + +@property (nonatomic, readonly) NSArray *array; + +@end + +@implementation FLEXArrayExplorerViewController + +- (NSArray *)array +{ + return [self.object isKindOfClass:[NSArray class]] ? self.object : nil; +} + + +#pragma mark - Superclass Overrides + +- (NSString *)customSectionTitle +{ + return @"Array Indices"; +} + +- (NSArray *)customSectionRowCookies +{ + // Use index numbers as the row cookies + NSMutableArray *cookies = [NSMutableArray arrayWithCapacity:[self.array count]]; + for (NSUInteger i = 0; i < [self.array count]; i++) { + [cookies addObject:@(i)]; + } + return cookies; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + return [rowCookie description]; +} + +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie +{ + return [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:[self detailObjectForRowCookie:rowCookie]]; +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + return YES; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + return [FLEXObjectExplorerFactory explorerViewControllerForObject:[self detailObjectForRowCookie:rowCookie]]; +} + +- (BOOL)shouldShowDescription +{ + return NO; +} + + +#pragma mark - Helpers + +- (id)detailObjectForRowCookie:(id)rowCookie +{ + NSUInteger index = [rowCookie unsignedIntegerValue]; + return self.array[index]; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXClassExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXClassExplorerViewController.h new file mode 100644 index 0000000000..9bb36ce664 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXClassExplorerViewController.h @@ -0,0 +1,13 @@ +// +// FLEXClassExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 6/18/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" + +@interface FLEXClassExplorerViewController : FLEXObjectExplorerViewController + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXClassExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXClassExplorerViewController.m new file mode 100644 index 0000000000..561f1289fc --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXClassExplorerViewController.m @@ -0,0 +1,132 @@ +// +// FLEXClassExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 6/18/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXClassExplorerViewController.h" +#import "FLEXMethodCallingViewController.h" +#import "FLEXInstancesTableViewController.h" + +typedef NS_ENUM(NSUInteger, FLEXClassExplorerRow) { + FLEXClassExplorerRowNew, + FLEXClassExplorerRowAlloc, + FLEXClassExplorerRowLiveInstances +}; + +@interface FLEXClassExplorerViewController () + +@property (nonatomic, readonly) Class theClass; + +@end + +@implementation FLEXClassExplorerViewController + +- (Class)theClass +{ + Class theClass = Nil; + if (class_isMetaClass(object_getClass(self.object))) { + theClass = self.object; + } + return theClass; +} + +#pragma mark - Superclass Overrides + +- (NSArray *)possibleExplorerSections +{ + // Move class methods to between our custom section and the properties section since + // we are more interested in the class sections than in the instance level sections. + NSMutableArray *mutableSections = [[super possibleExplorerSections] mutableCopy]; + [mutableSections removeObject:@(FLEXObjectExplorerSectionClassMethods)]; + [mutableSections insertObject:@(FLEXObjectExplorerSectionClassMethods) atIndex:[mutableSections indexOfObject:@(FLEXObjectExplorerSectionProperties)]]; + return mutableSections; +} + +- (NSString *)customSectionTitle +{ + return @"Shortcuts"; +} + +- (NSArray *)customSectionRowCookies +{ + NSMutableArray *cookies = [NSMutableArray array]; + if ([self.theClass respondsToSelector:@selector(new)]) { + [cookies addObject:@(FLEXClassExplorerRowNew)]; + } + if ([self.theClass respondsToSelector:@selector(alloc)]) { + [cookies addObject:@(FLEXClassExplorerRowAlloc)]; + } + [cookies addObject:@(FLEXClassExplorerRowLiveInstances)]; + return cookies; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + NSString *title = nil; + FLEXClassExplorerRow row = [rowCookie unsignedIntegerValue]; + switch (row) { + case FLEXClassExplorerRowNew: + title = @"+ (id)new"; + break; + + case FLEXClassExplorerRowAlloc: + title = @"+ (id)alloc"; + break; + + case FLEXClassExplorerRowLiveInstances: + title = @"Live Instances"; + break; + } + return title; +} + +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie +{ + return nil; +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + return YES; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + UIViewController *drillInViewController = nil; + FLEXClassExplorerRow row = [rowCookie unsignedIntegerValue]; + switch (row) { + case FLEXClassExplorerRowNew: + drillInViewController = [[FLEXMethodCallingViewController alloc] initWithTarget:self.theClass method:class_getClassMethod(self.theClass, @selector(new))]; + break; + + case FLEXClassExplorerRowAlloc: + drillInViewController = [[FLEXMethodCallingViewController alloc] initWithTarget:self.theClass method:class_getClassMethod(self.theClass, @selector(alloc))]; + break; + + case FLEXClassExplorerRowLiveInstances: + drillInViewController = [FLEXInstancesTableViewController instancesTableViewControllerForClassName:NSStringFromClass(self.theClass)]; + break; + } + return drillInViewController; +} + +- (BOOL)shouldShowDescription +{ + // Redundant with our title. + return NO; +} + +- (BOOL)canCallInstanceMethods +{ + return NO; +} + +- (BOOL)canHaveInstanceState +{ + return NO; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXDefaultsExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXDefaultsExplorerViewController.h new file mode 100644 index 0000000000..8ed698b707 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXDefaultsExplorerViewController.h @@ -0,0 +1,13 @@ +// +// FLEXDefaultsExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/23/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" + +@interface FLEXDefaultsExplorerViewController : FLEXObjectExplorerViewController + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXDefaultsExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXDefaultsExplorerViewController.m new file mode 100644 index 0000000000..c3c26f2987 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXDefaultsExplorerViewController.m @@ -0,0 +1,73 @@ +// +// FLEXDefaultsExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/23/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXDefaultsExplorerViewController.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXDefaultEditorViewController.h" + +@interface FLEXDefaultsExplorerViewController () + +@property (nonatomic, readonly) NSUserDefaults *defaults; + +@end + +@implementation FLEXDefaultsExplorerViewController + +- (NSUserDefaults *)defaults +{ + return [self.object isKindOfClass:[NSUserDefaults class]] ? self.object : nil; +} + + +#pragma mark - Superclass Overrides + +- (NSString *)customSectionTitle +{ + return @"Defaults"; +} + +- (NSArray *)customSectionRowCookies +{ + return [[[self.defaults dictionaryRepresentation] allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + return rowCookie; +} + +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie +{ + return [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:[self.defaults objectForKey:rowCookie]]; +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + return YES; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + UIViewController *drillInViewController = nil; + NSString *key = rowCookie; + id drillInObject = [self.defaults objectForKey:key]; + if ([FLEXDefaultEditorViewController canEditDefaultWithValue:drillInObject]) { + drillInViewController = [[FLEXDefaultEditorViewController alloc] initWithDefaults:self.defaults key:key]; + } else { + drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:drillInObject]; + } + return drillInViewController; +} + +- (BOOL)shouldShowDescription +{ + return NO; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXDictionaryExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXDictionaryExplorerViewController.h new file mode 100644 index 0000000000..77b9c80cfe --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXDictionaryExplorerViewController.h @@ -0,0 +1,13 @@ +// +// FLEXDictionaryExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" + +@interface FLEXDictionaryExplorerViewController : FLEXObjectExplorerViewController + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXDictionaryExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXDictionaryExplorerViewController.m new file mode 100644 index 0000000000..253ae65de6 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXDictionaryExplorerViewController.m @@ -0,0 +1,64 @@ +// +// FLEXDictionaryExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXDictionaryExplorerViewController.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXObjectExplorerFactory.h" + +@interface FLEXDictionaryExplorerViewController () + +@property (nonatomic, readonly) NSDictionary *dictionary; + +@end + +@implementation FLEXDictionaryExplorerViewController + +- (NSDictionary *)dictionary +{ + return [self.object isKindOfClass:[NSDictionary class]] ? self.object : nil; +} + + +#pragma mark - Superclass Overrides + +- (NSString *)customSectionTitle +{ + return @"Dictionary Objects"; +} + +- (NSArray *)customSectionRowCookies +{ + return [self.dictionary allKeys]; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + return [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:rowCookie]; +} + +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie +{ + return [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:self.dictionary[rowCookie]]; +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + return YES; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + return [FLEXObjectExplorerFactory explorerViewControllerForObject:self.dictionary[rowCookie]]; +} + +- (BOOL)shouldShowDescription +{ + return NO; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXGlobalsTableViewControllerEntry.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXGlobalsTableViewControllerEntry.h new file mode 100644 index 0000000000..c82827a11c --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXGlobalsTableViewControllerEntry.h @@ -0,0 +1,22 @@ +// +// FLEXGlobalsTableViewControllerEntry.h +// UICatalog +// +// Created by Javier Soto on 7/26/14. +// Copyright (c) 2014 f. All rights reserved. +// + +#import +#import + +typedef NSString *(^FLEXGlobalsTableViewControllerEntryNameFuture)(void); +typedef UIViewController *(^FLEXGlobalsTableViewControllerViewControllerFuture)(void); + +@interface FLEXGlobalsTableViewControllerEntry : NSObject + +@property (nonatomic, readonly, copy) FLEXGlobalsTableViewControllerEntryNameFuture entryNameFuture; +@property (nonatomic, readonly, copy) FLEXGlobalsTableViewControllerViewControllerFuture viewControllerFuture; + ++ (instancetype)entryWithNameFuture:(FLEXGlobalsTableViewControllerEntryNameFuture)nameFuture viewControllerFuture:(FLEXGlobalsTableViewControllerViewControllerFuture)viewControllerFuture; + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXGlobalsTableViewControllerEntry.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXGlobalsTableViewControllerEntry.m new file mode 100644 index 0000000000..0a9306b72d --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXGlobalsTableViewControllerEntry.m @@ -0,0 +1,25 @@ +// +// FLEXGlobalsTableViewControllerEntry.m +// UICatalog +// +// Created by Javier Soto on 7/26/14. +// Copyright (c) 2014 f. All rights reserved. +// + +#import "FLEXGlobalsTableViewControllerEntry.h" + +@implementation FLEXGlobalsTableViewControllerEntry + ++ (instancetype)entryWithNameFuture:(FLEXGlobalsTableViewControllerEntryNameFuture)nameFuture viewControllerFuture:(FLEXGlobalsTableViewControllerViewControllerFuture)viewControllerFuture +{ + NSParameterAssert(nameFuture); + NSParameterAssert(viewControllerFuture); + + FLEXGlobalsTableViewControllerEntry *entry = [[self alloc] init]; + entry->_entryNameFuture = [nameFuture copy]; + entry->_viewControllerFuture = [viewControllerFuture copy]; + + return entry; +} + +@end \ No newline at end of file diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXImageExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXImageExplorerViewController.h new file mode 100644 index 0000000000..ea8cf5e37e --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXImageExplorerViewController.h @@ -0,0 +1,13 @@ +// +// FLEXImageExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 6/12/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" + +@interface FLEXImageExplorerViewController : FLEXObjectExplorerViewController + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXImageExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXImageExplorerViewController.m new file mode 100644 index 0000000000..d529181bbe --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXImageExplorerViewController.m @@ -0,0 +1,69 @@ +// +// FLEXImageExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 6/12/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXImageExplorerViewController.h" +#import "FLEXImagePreviewViewController.h" + +typedef NS_ENUM(NSUInteger, FLEXImageExplorerRow) { + FLEXImageExplorerRowImage +}; + +@interface FLEXImageExplorerViewController () + +@property (nonatomic, readonly) UIImage *image; + +@end + +@implementation FLEXImageExplorerViewController + +- (UIImage *)image +{ + return [self.object isKindOfClass:[UIImage class]] ? self.object : nil; +} + +#pragma mark - Superclass Overrides + +- (NSString *)customSectionTitle +{ + return @"Shortcuts"; +} + +- (NSArray *)customSectionRowCookies +{ + return @[@(FLEXImageExplorerRowImage)]; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + NSString *title = nil; + if ([rowCookie isEqual:@(FLEXImageExplorerRowImage)]) { + title = @"Show Image"; + } + return title; +} + +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie +{ + return nil; +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + return YES; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + UIViewController *drillInViewController = nil; + if ([rowCookie isEqual:@(FLEXImageExplorerRowImage)]) { + drillInViewController = [[FLEXImagePreviewViewController alloc] initWithImage:self.image]; + } + return drillInViewController; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXLayerExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXLayerExplorerViewController.h new file mode 100644 index 0000000000..f9a157cb74 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXLayerExplorerViewController.h @@ -0,0 +1,13 @@ +// +// FLEXLayerExplorerViewController.h +// UICatalog +// +// Created by Ryan Olson on 12/14/14. +// Copyright (c) 2014 f. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" + +@interface FLEXLayerExplorerViewController : FLEXObjectExplorerViewController + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXLayerExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXLayerExplorerViewController.m new file mode 100644 index 0000000000..e55184e00f --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXLayerExplorerViewController.m @@ -0,0 +1,92 @@ +// +// FLEXLayerExplorerViewController.m +// UICatalog +// +// Created by Ryan Olson on 12/14/14. +// Copyright (c) 2014 f. All rights reserved. +// + +#import "FLEXLayerExplorerViewController.h" +#import "FLEXImagePreviewViewController.h" + +typedef NS_ENUM(NSUInteger, FLEXLayerExplorerRow) { + FLEXLayerExplorerRowPreview +}; + +@interface FLEXLayerExplorerViewController () + +@property (nonatomic, readonly) CALayer *layerToExplore; + +@end + +@implementation FLEXLayerExplorerViewController + +- (CALayer *)layerToExplore +{ + return [self.object isKindOfClass:[CALayer class]] ? self.object : nil; +} + +#pragma mark - Superclass Overrides + +- (NSString *)customSectionTitle +{ + return @"Shortcuts"; +} + +- (NSArray *)customSectionRowCookies +{ + return @[@(FLEXLayerExplorerRowPreview)]; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + NSString *title = nil; + + if ([rowCookie isKindOfClass:[NSNumber class]]) { + FLEXLayerExplorerRow row = [rowCookie unsignedIntegerValue]; + switch (row) { + case FLEXLayerExplorerRowPreview: + title = @"Preview Image"; + break; + } + } + + return title; +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + return YES; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + UIViewController *drillInViewController = nil; + + if ([rowCookie isKindOfClass:[NSNumber class]]) { + FLEXLayerExplorerRow row = [rowCookie unsignedIntegerValue]; + switch (row) { + case FLEXLayerExplorerRowPreview: + drillInViewController = [[self class] imagePreviewViewControllerForLayer:self.layerToExplore]; + break; + } + } + + return drillInViewController; +} + ++ (UIViewController *)imagePreviewViewControllerForLayer:(CALayer *)layer +{ + UIViewController *imagePreviewViewController = nil; + if (!CGRectIsEmpty(layer.bounds)) { + UIGraphicsBeginImageContextWithOptions(layer.bounds.size, NO, 0.0); + CGContextRef imageContext = UIGraphicsGetCurrentContext(); + [layer renderInContext:imageContext]; + UIImage *previewImage = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + imagePreviewViewController = [[FLEXImagePreviewViewController alloc] initWithImage:previewImage]; + } + return imagePreviewViewController; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerFactory.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerFactory.h new file mode 100644 index 0000000000..0115670553 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerFactory.h @@ -0,0 +1,17 @@ +// +// FLEXObjectExplorerFactory.h +// Flipboard +// +// Created by Ryan Olson on 5/15/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@class FLEXObjectExplorerViewController; + +@interface FLEXObjectExplorerFactory : NSObject + ++ (FLEXObjectExplorerViewController *)explorerViewControllerForObject:(id)object; + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerFactory.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerFactory.m new file mode 100644 index 0000000000..05dd666785 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerFactory.m @@ -0,0 +1,65 @@ +// +// FLEXObjectExplorerFactory.m +// Flipboard +// +// Created by Ryan Olson on 5/15/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerFactory.h" +#import "FLEXObjectExplorerViewController.h" +#import "FLEXArrayExplorerViewController.h" +#import "FLEXSetExplorerViewController.h" +#import "FLEXDictionaryExplorerViewController.h" +#import "FLEXDefaultsExplorerViewController.h" +#import "FLEXViewControllerExplorerViewController.h" +#import "FLEXViewExplorerViewController.h" +#import "FLEXImageExplorerViewController.h" +#import "FLEXClassExplorerViewController.h" +#import "FLEXLayerExplorerViewController.h" +#import + +@implementation FLEXObjectExplorerFactory + ++ (FLEXObjectExplorerViewController *)explorerViewControllerForObject:(id)object +{ + // Bail for nil object. We can't explore nil. + if (!object) { + return nil; + } + + static NSDictionary *explorerSubclassesForObjectTypeStrings = nil; + static dispatch_once_t once; + dispatch_once(&once, ^{ + explorerSubclassesForObjectTypeStrings = @{NSStringFromClass([NSArray class]) : [FLEXArrayExplorerViewController class], + NSStringFromClass([NSSet class]) : [FLEXSetExplorerViewController class], + NSStringFromClass([NSDictionary class]) : [FLEXDictionaryExplorerViewController class], + NSStringFromClass([NSUserDefaults class]) : [FLEXDefaultsExplorerViewController class], + NSStringFromClass([UIViewController class]) : [FLEXViewControllerExplorerViewController class], + NSStringFromClass([UIView class]) : [FLEXViewExplorerViewController class], + NSStringFromClass([UIImage class]) : [FLEXImageExplorerViewController class], + NSStringFromClass([CALayer class]) : [FLEXLayerExplorerViewController class]}; + }); + + Class explorerClass = nil; + BOOL objectIsClass = class_isMetaClass(object_getClass(object)); + if (objectIsClass) { + explorerClass = [FLEXClassExplorerViewController class]; + } else { + explorerClass = [FLEXObjectExplorerViewController class]; + for (NSString *objectTypeString in explorerSubclassesForObjectTypeStrings) { + Class objectClass = NSClassFromString(objectTypeString); + if ([object isKindOfClass:objectClass]) { + explorerClass = explorerSubclassesForObjectTypeStrings[objectTypeString]; + break; + } + } + } + + FLEXObjectExplorerViewController *explorerViewController = [[explorerClass alloc] init]; + explorerViewController.object = object; + + return explorerViewController; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerViewController.h new file mode 100644 index 0000000000..781a85924a --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerViewController.h @@ -0,0 +1,51 @@ +// +// FLEXObjectExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 2014-05-03. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +typedef NS_ENUM(NSUInteger, FLEXObjectExplorerSection) { + FLEXObjectExplorerSectionDescription, + FLEXObjectExplorerSectionCustom, + FLEXObjectExplorerSectionProperties, + FLEXObjectExplorerSectionIvars, + FLEXObjectExplorerSectionMethods, + FLEXObjectExplorerSectionClassMethods, + FLEXObjectExplorerSectionSuperclasses, + FLEXObjectExplorerSectionReferencingInstances +}; + +@interface FLEXObjectExplorerViewController : UITableViewController + +@property (nonatomic, strong) id object; + +// Sublasses can override the methods below to provide data in a custom section. +// The subclass should provide an array of "row cookies" to allow retreival of individual row data later on. +// The objects in the rowCookies array will be used to call the row title, subtitle, etc methods to consturct the rows. +// The cookies approach is used here because we may filter the visible rows based on the search text entered by the user. +- (NSString *)customSectionTitle; +- (NSArray *)customSectionRowCookies; +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie; +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie; +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie; +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie; + +// More subclass configuration hooks. + +/// Whether to allow showing/drilling in to current values for ivars and properties. Defalut is YES. +- (BOOL)canHaveInstanceState; + +/// Whether to allow drilling in to method calling interfaces for instance methods. Default is YES. +- (BOOL)canCallInstanceMethods; + +/// If the custom section data makes the description redundant, subclasses can choose to hide it. Default is YES. +- (BOOL)shouldShowDescription; + +/// Subclasses can reorder/change which sections can display directly by overriding this method. +- (NSArray *)possibleExplorerSections; + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerViewController.m new file mode 100644 index 0000000000..a01953b9f9 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXObjectExplorerViewController.m @@ -0,0 +1,1033 @@ +// +// FLEXObjectExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 2014-05-03. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" +#import "FLEXUtility.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXMultilineTableViewCell.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXPropertyEditorViewController.h" +#import "FLEXIvarEditorViewController.h" +#import "FLEXMethodCallingViewController.h" +#import "FLEXInstancesTableViewController.h" +#import + +// Convenience boxes to keep runtime properties, ivars, and methods in foundation collections. +@interface FLEXPropertyBox : NSObject +@property (nonatomic, assign) objc_property_t property; +@end +@implementation FLEXPropertyBox +@end + +@interface FLEXIvarBox : NSObject +@property (nonatomic, assign) Ivar ivar; +@end +@implementation FLEXIvarBox +@end + +@interface FLEXMethodBox : NSObject +@property (nonatomic, assign) Method method; +@end +@implementation FLEXMethodBox +@end + +static const NSInteger kFLEXObjectExplorerScopeNoInheritanceIndex = 0; +static const NSInteger kFLEXObjectExplorerScopeIncludeInheritanceIndex = 1; + +@interface FLEXObjectExplorerViewController () + +@property (nonatomic, strong) NSArray *properties; +@property (nonatomic, strong) NSArray *inheritedProperties; +@property (nonatomic, strong) NSArray *filteredProperties; + +@property (nonatomic, strong) NSArray *ivars; +@property (nonatomic, strong) NSArray *inheritedIvars; +@property (nonatomic, strong) NSArray *filteredIvars; + +@property (nonatomic, strong) NSArray *methods; +@property (nonatomic, strong) NSArray *inheritedMethods; +@property (nonatomic, strong) NSArray *filteredMethods; + +@property (nonatomic, strong) NSArray *classMethods; +@property (nonatomic, strong) NSArray *inheritedClassMethods; +@property (nonatomic, strong) NSArray *filteredClassMethods; + +@property (nonatomic, strong) NSArray *superclasses; +@property (nonatomic, strong) NSArray *filteredSuperclasses; + +@property (nonatomic, strong) NSArray *cachedCustomSectionRowCookies; +@property (nonatomic, strong) NSIndexSet *customSectionVisibleIndexes; + +@property (nonatomic, strong) UISearchBar *searchBar; +@property (nonatomic, strong) NSString *filterText; +@property (nonatomic, assign) BOOL includeInheritance; + +@end + +@implementation FLEXObjectExplorerViewController + +- (id)initWithStyle:(UITableViewStyle)style +{ + // Force grouped style + return [super initWithStyle:UITableViewStyleGrouped]; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.searchBar = [[UISearchBar alloc] init]; + self.searchBar.placeholder = [FLEXUtility searchBarPlaceholderText]; + self.searchBar.delegate = self; + self.searchBar.showsScopeBar = YES; + self.searchBar.scopeButtonTitles = @[@"No Inheritance", @"Include Inheritance"]; + [self.searchBar sizeToFit]; + self.tableView.tableHeaderView = self.searchBar; + + self.refreshControl = [[UIRefreshControl alloc] init]; + [self.refreshControl addTarget:self action:@selector(refreshControlDidRefresh:) forControlEvents:UIControlEventValueChanged]; +} + +- (void)viewWillAppear:(BOOL)animated +{ + [super viewWillAppear:animated]; + + // Reload the entire table view rather than just the visible cells because the filtered rows + // may have changed (i.e. a change in the description row that causes it to get filtered out). + [self updateTableData]; +} + +- (void)scrollViewDidScroll:(UIScrollView *)scrollView +{ + [self.searchBar endEditing:YES]; +} + +- (void)refreshControlDidRefresh:(id)sender +{ + [self updateTableData]; + [self.refreshControl endRefreshing]; +} + + +#pragma mark - Search + +- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText +{ + self.filterText = searchText; +} + +- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar +{ + [searchBar resignFirstResponder]; +} + +- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope +{ + if (selectedScope == kFLEXObjectExplorerScopeIncludeInheritanceIndex) { + self.includeInheritance = YES; + } else if (selectedScope == kFLEXObjectExplorerScopeNoInheritanceIndex) { + self.includeInheritance = NO; + } +} + + +#pragma mark - Setter overrides + +- (void)setObject:(id)object +{ + _object = object; + // Use [object class] here rather than object_getClass because we don't want to show the KVO prefix for observed objects. + self.title = [[object class] description]; + [self updateTableData]; +} + +- (void)setIncludeInheritance:(BOOL)includeInheritance +{ + if (_includeInheritance != includeInheritance) { + _includeInheritance = includeInheritance; + [self updateDisplayedData]; + } +} + +- (void)setFilterText:(NSString *)filterText +{ + if (_filterText != filterText || ![_filterText isEqual:filterText]) { + _filterText = filterText; + [self updateDisplayedData]; + } +} + + +#pragma mark - Reloading + +- (void)updateTableData +{ + [self updateCustomData]; + [self updateProperties]; + [self updateIvars]; + [self updateMethods]; + [self updateClassMethods]; + [self updateSuperclasses]; + [self updateDisplayedData]; +} + +- (void)updateDisplayedData +{ + [self updateFilteredCustomData]; + [self updateFilteredProperties]; + [self updateFilteredIvars]; + [self updateFilteredMethods]; + [self updateFilteredClassMethods]; + [self updateFilteredSuperclasses]; + + if (self.isViewLoaded) { + [self.tableView reloadData]; + } +} + +- (BOOL)shouldShowDescription +{ + BOOL showDescription = YES; + + // Not if it's empty or nil. + NSString *descripition = [FLEXUtility safeDescriptionForObject:self.object]; + if (showDescription) { + showDescription = [descripition length] > 0; + } + + // Not if we have filter text that doesn't match the desctiption. + if (showDescription && [self.filterText length] > 0) { + showDescription = [descripition rangeOfString:self.filterText options:NSCaseInsensitiveSearch].length > 0; + } + + return showDescription; +} + + +#pragma mark - Properties + +- (void)updateProperties +{ + Class class = [self.object class]; + self.properties = [[self class] propertiesForClass:class]; + self.inheritedProperties = [[self class] inheritedPropertiesForClass:class]; +} + ++ (NSArray *)propertiesForClass:(Class)class +{ + NSMutableArray *boxedProperties = [NSMutableArray array]; + unsigned int propertyCount = 0; + objc_property_t *propertyList = class_copyPropertyList(class, &propertyCount); + if (propertyList) { + for (unsigned int i = 0; i < propertyCount; i++) { + FLEXPropertyBox *propertyBox = [[FLEXPropertyBox alloc] init]; + propertyBox.property = propertyList[i]; + [boxedProperties addObject:propertyBox]; + } + free(propertyList); + } + return boxedProperties; +} + ++ (NSArray *)inheritedPropertiesForClass:(Class)class +{ + NSMutableArray *inheritedProperties = [NSMutableArray array]; + while ((class = [class superclass])) { + [inheritedProperties addObjectsFromArray:[self propertiesForClass:class]]; + } + return inheritedProperties; +} + +- (void)updateFilteredProperties +{ + NSArray *candidateProperties = self.properties; + if (self.includeInheritance) { + candidateProperties = [candidateProperties arrayByAddingObjectsFromArray:self.inheritedProperties]; + } + + NSArray *unsortedFilteredProperties = nil; + if ([self.filterText length] > 0) { + NSMutableArray *mutableUnsortedFilteredProperties = [NSMutableArray array]; + for (FLEXPropertyBox *propertyBox in candidateProperties) { + NSString *prettyName = [FLEXRuntimeUtility prettyNameForProperty:propertyBox.property]; + if ([prettyName rangeOfString:self.filterText options:NSCaseInsensitiveSearch].location != NSNotFound) { + [mutableUnsortedFilteredProperties addObject:propertyBox]; + } + } + unsortedFilteredProperties = mutableUnsortedFilteredProperties; + } else { + unsortedFilteredProperties = candidateProperties; + } + + self.filteredProperties = [unsortedFilteredProperties sortedArrayUsingComparator:^NSComparisonResult(FLEXPropertyBox *propertyBox1, FLEXPropertyBox *propertyBox2) { + NSString *name1 = [NSString stringWithUTF8String:property_getName(propertyBox1.property)]; + NSString *name2 = [NSString stringWithUTF8String:property_getName(propertyBox2.property)]; + return [name1 caseInsensitiveCompare:name2]; + }]; +} + +- (NSString *)titleForPropertyAtIndex:(NSInteger)index +{ + FLEXPropertyBox *propertyBox = self.filteredProperties[index]; + return [FLEXRuntimeUtility prettyNameForProperty:propertyBox.property]; +} + +- (id)valueForPropertyAtIndex:(NSInteger)index +{ + id value = nil; + if ([self canHaveInstanceState]) { + FLEXPropertyBox *propertyBox = self.filteredProperties[index]; + value = [FLEXRuntimeUtility valueForProperty:propertyBox.property onObject:self.object]; + } + return value; +} + + +#pragma mark - Ivars + +- (void)updateIvars +{ + Class class = [self.object class]; + self.ivars = [[self class] ivarsForClass:class]; + self.inheritedIvars = [[self class] inheritedIvarsForClass:class]; +} + ++ (NSArray *)ivarsForClass:(Class)class +{ + NSMutableArray *boxedIvars = [NSMutableArray array]; + unsigned int ivarCount = 0; + Ivar *ivarList = class_copyIvarList(class, &ivarCount); + if (ivarList) { + for (unsigned int i = 0; i < ivarCount; i++) { + FLEXIvarBox *ivarBox = [[FLEXIvarBox alloc] init]; + ivarBox.ivar = ivarList[i]; + [boxedIvars addObject:ivarBox]; + } + free(ivarList); + } + return boxedIvars; +} + ++ (NSArray *)inheritedIvarsForClass:(Class)class +{ + NSMutableArray *inheritedIvars = [NSMutableArray array]; + while ((class = [class superclass])) { + [inheritedIvars addObjectsFromArray:[self ivarsForClass:class]]; + } + return inheritedIvars; +} + +- (void)updateFilteredIvars +{ + NSArray *candidateIvars = self.ivars; + if (self.includeInheritance) { + candidateIvars = [candidateIvars arrayByAddingObjectsFromArray:self.inheritedIvars]; + } + + NSArray *unsortedFilteredIvars = nil; + if ([self.filterText length] > 0) { + NSMutableArray *mutableUnsortedFilteredIvars = [NSMutableArray array]; + for (FLEXIvarBox *ivarBox in candidateIvars) { + NSString *prettyName = [FLEXRuntimeUtility prettyNameForIvar:ivarBox.ivar]; + if ([prettyName rangeOfString:self.filterText options:NSCaseInsensitiveSearch].location != NSNotFound) { + [mutableUnsortedFilteredIvars addObject:ivarBox]; + } + } + unsortedFilteredIvars = mutableUnsortedFilteredIvars; + } else { + unsortedFilteredIvars = candidateIvars; + } + + self.filteredIvars = [unsortedFilteredIvars sortedArrayUsingComparator:^NSComparisonResult(FLEXIvarBox *ivarBox1, FLEXIvarBox *ivarBox2) { + NSString *name1 = [NSString stringWithUTF8String:ivar_getName(ivarBox1.ivar)]; + NSString *name2 = [NSString stringWithUTF8String:ivar_getName(ivarBox2.ivar)]; + return [name1 caseInsensitiveCompare:name2]; + }]; +} + +- (NSString *)titleForIvarAtIndex:(NSInteger)index +{ + FLEXIvarBox *ivarBox = self.filteredIvars[index]; + return [FLEXRuntimeUtility prettyNameForIvar:ivarBox.ivar]; +} + +- (id)valueForIvarAtIndex:(NSInteger)index +{ + id value = nil; + if ([self canHaveInstanceState]) { + FLEXIvarBox *ivarBox = self.filteredIvars[index]; + value = [FLEXRuntimeUtility valueForIvar:ivarBox.ivar onObject:self.object]; + } + return value; +} + + +#pragma mark - Methods + +- (void)updateMethods +{ + Class class = [self.object class]; + self.methods = [[self class] methodsForClass:class]; + self.inheritedMethods = [[self class] inheritedMethodsForClass:class]; +} + +- (void)updateFilteredMethods +{ + self.filteredMethods = [self filteredMethodsFromMethods:self.methods inheritedMethods:self.inheritedMethods areClassMethods:NO]; +} + +- (void)updateClassMethods +{ + const char *className = [NSStringFromClass([self.object class]) UTF8String]; + Class metaClass = objc_getMetaClass(className); + self.classMethods = [[self class] methodsForClass:metaClass]; + self.inheritedClassMethods = [[self class] inheritedMethodsForClass:metaClass]; +} + +- (void)updateFilteredClassMethods +{ + self.filteredClassMethods = [self filteredMethodsFromMethods:self.classMethods inheritedMethods:self.inheritedClassMethods areClassMethods:YES]; +} + ++ (NSArray *)methodsForClass:(Class)class +{ + NSMutableArray *boxedMethods = [NSMutableArray array]; + unsigned int methodCount = 0; + Method *methodList = class_copyMethodList(class, &methodCount); + if (methodList) { + for (unsigned int i = 0; i < methodCount; i++) { + FLEXMethodBox *methodBox = [[FLEXMethodBox alloc] init]; + methodBox.method = methodList[i]; + [boxedMethods addObject:methodBox]; + } + free(methodList); + } + return boxedMethods; +} + ++ (NSArray *)inheritedMethodsForClass:(Class)class +{ + NSMutableArray *inheritedMethods = [NSMutableArray array]; + while ((class = [class superclass])) { + [inheritedMethods addObjectsFromArray:[self methodsForClass:class]]; + } + return inheritedMethods; +} + +- (NSArray *)filteredMethodsFromMethods:(NSArray *)methods inheritedMethods:(NSArray *)inheritedMethods areClassMethods:(BOOL)areClassMethods +{ + NSArray *candidateMethods = methods; + if (self.includeInheritance) { + candidateMethods = [candidateMethods arrayByAddingObjectsFromArray:inheritedMethods]; + } + + NSArray *unsortedFilteredMethods = nil; + if ([self.filterText length] > 0) { + NSMutableArray *mutableUnsortedFilteredMethods = [NSMutableArray array]; + for (FLEXMethodBox *methodBox in candidateMethods) { + NSString *prettyName = [FLEXRuntimeUtility prettyNameForMethod:methodBox.method isClassMethod:areClassMethods]; + if ([prettyName rangeOfString:self.filterText options:NSCaseInsensitiveSearch].location != NSNotFound) { + [mutableUnsortedFilteredMethods addObject:methodBox]; + } + } + unsortedFilteredMethods = mutableUnsortedFilteredMethods; + } else { + unsortedFilteredMethods = candidateMethods; + } + + NSArray *sortedFilteredMethods = [unsortedFilteredMethods sortedArrayUsingComparator:^NSComparisonResult(FLEXMethodBox *methodBox1, FLEXMethodBox *methodBox2) { + NSString *name1 = NSStringFromSelector(method_getName(methodBox1.method)); + NSString *name2 = NSStringFromSelector(method_getName(methodBox2.method)); + return [name1 caseInsensitiveCompare:name2]; + }]; + + return sortedFilteredMethods; +} + +- (NSString *)titleForMethodAtIndex:(NSInteger)index +{ + FLEXMethodBox *methodBox = self.filteredMethods[index]; + return [FLEXRuntimeUtility prettyNameForMethod:methodBox.method isClassMethod:NO]; +} + +- (NSString *)titleForClassMethodAtIndex:(NSInteger)index +{ + FLEXMethodBox *classMethodBox = self.filteredClassMethods[index]; + return [FLEXRuntimeUtility prettyNameForMethod:classMethodBox.method isClassMethod:YES]; +} + + +#pragma mark - Superclasses + ++ (NSArray *)superclassesForClass:(Class)class +{ + NSMutableArray *superClasses = [NSMutableArray array]; + while ((class = [class superclass])) { + [superClasses addObject:class]; + } + return superClasses; +} + +- (void)updateSuperclasses +{ + self.superclasses = [[self class] superclassesForClass:[self.object class]]; +} + +- (void)updateFilteredSuperclasses +{ + if ([self.filterText length] > 0) { + NSMutableArray *filteredSuperclasses = [NSMutableArray array]; + for (Class superclass in self.superclasses) { + if ([NSStringFromClass(superclass) rangeOfString:self.filterText options:NSCaseInsensitiveSearch].length > 0) { + [filteredSuperclasses addObject:superclass]; + } + } + self.filteredSuperclasses = filteredSuperclasses; + } else { + self.filteredSuperclasses = self.superclasses; + } +} + + +#pragma mark - Table View Data Helpers + +- (NSArray *)possibleExplorerSections +{ + static NSArray *possibleSections = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + possibleSections = @[@(FLEXObjectExplorerSectionDescription), + @(FLEXObjectExplorerSectionCustom), + @(FLEXObjectExplorerSectionProperties), + @(FLEXObjectExplorerSectionIvars), + @(FLEXObjectExplorerSectionMethods), + @(FLEXObjectExplorerSectionClassMethods), + @(FLEXObjectExplorerSectionSuperclasses), + @(FLEXObjectExplorerSectionReferencingInstances)]; + }); + return possibleSections; +} + +- (NSArray *)visibleExplorerSections +{ + NSMutableArray *visibleSections = [NSMutableArray array]; + + for (NSNumber *possibleSection in [self possibleExplorerSections]) { + FLEXObjectExplorerSection explorerSection = [possibleSection unsignedIntegerValue]; + if ([self numberOfRowsForExplorerSection:explorerSection] > 0) { + [visibleSections addObject:possibleSection]; + } + } + + return visibleSections; +} + +- (NSString *)sectionTitleWithBaseName:(NSString *)baseName totalCount:(NSUInteger)totalCount filteredCount:(NSUInteger)filteredCount +{ + NSString *sectionTitle = nil; + if (totalCount == filteredCount) { + sectionTitle = [baseName stringByAppendingFormat:@" (%lu)", (unsigned long)totalCount]; + } else { + sectionTitle = [baseName stringByAppendingFormat:@" (%lu of %lu)", (unsigned long)filteredCount, (unsigned long)totalCount]; + } + return sectionTitle; +} + +- (FLEXObjectExplorerSection)explorerSectionAtIndex:(NSInteger)sectionIndex +{ + return [[[self visibleExplorerSections] objectAtIndex:sectionIndex] unsignedIntegerValue]; +} + +- (NSInteger)numberOfRowsForExplorerSection:(FLEXObjectExplorerSection)section +{ + NSInteger numberOfRows = 0; + switch (section) { + case FLEXObjectExplorerSectionDescription: + numberOfRows = [self shouldShowDescription] ? 1 : 0; + break; + + case FLEXObjectExplorerSectionCustom: + numberOfRows = [self.customSectionVisibleIndexes count]; + break; + + case FLEXObjectExplorerSectionProperties: + numberOfRows = [self.filteredProperties count]; + break; + + case FLEXObjectExplorerSectionIvars: + numberOfRows = [self.filteredIvars count]; + break; + + case FLEXObjectExplorerSectionMethods: + numberOfRows = [self.filteredMethods count]; + break; + + case FLEXObjectExplorerSectionClassMethods: + numberOfRows = [self.filteredClassMethods count]; + break; + + case FLEXObjectExplorerSectionSuperclasses: + numberOfRows = [self.filteredSuperclasses count]; + break; + + case FLEXObjectExplorerSectionReferencingInstances: + // Hide this section if there is fliter text since there's nothing searchable (only 1 row, always the same). + numberOfRows = [self.filterText length] == 0 ? 1 : 0; + break; + } + return numberOfRows; +} + +- (NSString *)titleForRow:(NSInteger)row inExplorerSection:(FLEXObjectExplorerSection)section +{ + NSString *title = nil; + switch (section) { + case FLEXObjectExplorerSectionDescription: + title = [FLEXUtility safeDescriptionForObject:self.object]; + break; + + case FLEXObjectExplorerSectionCustom: + title = [self customSectionTitleForRowCookie:[self customSectionRowCookieForVisibleRow:row]]; + break; + + case FLEXObjectExplorerSectionProperties: + title = [self titleForPropertyAtIndex:row]; + break; + + case FLEXObjectExplorerSectionIvars: + title = [self titleForIvarAtIndex:row]; + break; + + case FLEXObjectExplorerSectionMethods: + title = [self titleForMethodAtIndex:row]; + break; + + case FLEXObjectExplorerSectionClassMethods: + title = [self titleForClassMethodAtIndex:row]; + break; + + case FLEXObjectExplorerSectionSuperclasses: + title = NSStringFromClass(self.filteredSuperclasses[row]); + break; + + case FLEXObjectExplorerSectionReferencingInstances: + title = @"Other objects with ivars referencing this object"; + break; + } + return title; +} + +- (NSString *)subtitleForRow:(NSInteger)row inExplorerSection:(FLEXObjectExplorerSection)section +{ + NSString *subtitle = nil; + switch (section) { + case FLEXObjectExplorerSectionDescription: + break; + + case FLEXObjectExplorerSectionCustom: + subtitle = [self customSectionSubtitleForRowCookie:[self customSectionRowCookieForVisibleRow:row]]; + break; + + case FLEXObjectExplorerSectionProperties: + subtitle = [self canHaveInstanceState] ? [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:[self valueForPropertyAtIndex:row]] : nil; + break; + + case FLEXObjectExplorerSectionIvars: + subtitle = [self canHaveInstanceState] ? [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:[self valueForIvarAtIndex:row]] : nil; + break; + + case FLEXObjectExplorerSectionMethods: + break; + + case FLEXObjectExplorerSectionClassMethods: + break; + + case FLEXObjectExplorerSectionSuperclasses: + break; + + case FLEXObjectExplorerSectionReferencingInstances: + break; + } + return subtitle; +} + +- (BOOL)canDrillInToRow:(NSInteger)row inExplorerSection:(FLEXObjectExplorerSection)section +{ + BOOL canDrillIn = NO; + switch (section) { + case FLEXObjectExplorerSectionDescription: + break; + + case FLEXObjectExplorerSectionCustom: + canDrillIn = [self customSectionCanDrillIntoRowWithCookie:[self customSectionRowCookieForVisibleRow:row]]; + break; + + case FLEXObjectExplorerSectionProperties: { + if ([self canHaveInstanceState]) { + FLEXPropertyBox *propertyBox = self.filteredProperties[row]; + objc_property_t property = propertyBox.property; + id currentValue = [self valueForPropertyAtIndex:row]; + BOOL canEdit = [FLEXPropertyEditorViewController canEditProperty:property currentValue:currentValue]; + BOOL canExplore = currentValue != nil; + canDrillIn = canEdit || canExplore; + } + } break; + + case FLEXObjectExplorerSectionIvars: { + if ([self canHaveInstanceState]) { + FLEXIvarBox *ivarBox = self.filteredIvars[row]; + Ivar ivar = ivarBox.ivar; + id currentValue = [self valueForIvarAtIndex:row]; + BOOL canEdit = [FLEXIvarEditorViewController canEditIvar:ivar currentValue:currentValue]; + BOOL canExplore = currentValue != nil; + canDrillIn = canEdit || canExplore; + } + } break; + + case FLEXObjectExplorerSectionMethods: + canDrillIn = [self canCallInstanceMethods]; + break; + + case FLEXObjectExplorerSectionClassMethods: + canDrillIn = YES; + break; + + case FLEXObjectExplorerSectionSuperclasses: + canDrillIn = YES; + break; + + case FLEXObjectExplorerSectionReferencingInstances: + canDrillIn = YES; + break; + } + return canDrillIn; +} + +- (BOOL)canCopyRow:(NSInteger)row inExplorerSection:(FLEXObjectExplorerSection)section +{ + BOOL canCopy = NO; + + switch (section) { + case FLEXObjectExplorerSectionDescription: + canCopy = YES; + break; + + default: + break; + } + return canCopy; +} + +- (NSString *)titleForExplorerSection:(FLEXObjectExplorerSection)section +{ + NSString *title = nil; + switch (section) { + case FLEXObjectExplorerSectionDescription: { + title = @"Description"; + } break; + + case FLEXObjectExplorerSectionCustom: { + title = [self customSectionTitle]; + } break; + + case FLEXObjectExplorerSectionProperties: { + NSUInteger totalCount = [self.properties count]; + if (self.includeInheritance) { + totalCount += [self.inheritedProperties count]; + } + title = [self sectionTitleWithBaseName:@"Properties" totalCount:totalCount filteredCount:[self.filteredProperties count]]; + } break; + + case FLEXObjectExplorerSectionIvars: { + NSUInteger totalCount = [self.ivars count]; + if (self.includeInheritance) { + totalCount += [self.inheritedIvars count]; + } + title = [self sectionTitleWithBaseName:@"Ivars" totalCount:totalCount filteredCount:[self.filteredIvars count]]; + } break; + + case FLEXObjectExplorerSectionMethods: { + NSUInteger totalCount = [self.methods count]; + if (self.includeInheritance) { + totalCount += [self.inheritedMethods count]; + } + title = [self sectionTitleWithBaseName:@"Methods" totalCount:totalCount filteredCount:[self.filteredMethods count]]; + } break; + + case FLEXObjectExplorerSectionClassMethods: { + NSUInteger totalCount = [self.classMethods count]; + if (self.includeInheritance) { + totalCount += [self.inheritedClassMethods count]; + } + title = [self sectionTitleWithBaseName:@"Class Methods" totalCount:totalCount filteredCount:[self.filteredClassMethods count]]; + } break; + + case FLEXObjectExplorerSectionSuperclasses: { + title = [self sectionTitleWithBaseName:@"Superclasses" totalCount:[self.superclasses count] filteredCount:[self.filteredSuperclasses count]]; + } break; + + case FLEXObjectExplorerSectionReferencingInstances: { + title = @"Object Graph"; + } break; + } + return title; +} + +- (UIViewController *)drillInViewControllerForRow:(NSUInteger)row inExplorerSection:(FLEXObjectExplorerSection)section +{ + UIViewController *viewController = nil; + switch (section) { + case FLEXObjectExplorerSectionDescription: + break; + + case FLEXObjectExplorerSectionCustom: + viewController = [self customSectionDrillInViewControllerForRowCookie:[self customSectionRowCookieForVisibleRow:row]]; + break; + + case FLEXObjectExplorerSectionProperties: { + FLEXPropertyBox *propertyBox = self.filteredProperties[row]; + objc_property_t property = propertyBox.property; + id currentValue = [self valueForPropertyAtIndex:row]; + if ([FLEXPropertyEditorViewController canEditProperty:property currentValue:currentValue]) { + viewController = [[FLEXPropertyEditorViewController alloc] initWithTarget:self.object property:property]; + } else if (currentValue) { + viewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:currentValue]; + } + } break; + + case FLEXObjectExplorerSectionIvars: { + FLEXIvarBox *ivarBox = self.filteredIvars[row]; + Ivar ivar = ivarBox.ivar; + id currentValue = [self valueForIvarAtIndex:row]; + if ([FLEXIvarEditorViewController canEditIvar:ivar currentValue:currentValue]) { + viewController = [[FLEXIvarEditorViewController alloc] initWithTarget:self.object ivar:ivar]; + } else if (currentValue) { + viewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:currentValue]; + } + } break; + + case FLEXObjectExplorerSectionMethods: { + FLEXMethodBox *methodBox = self.filteredMethods[row]; + Method method = methodBox.method; + viewController = [[FLEXMethodCallingViewController alloc] initWithTarget:self.object method:method]; + } break; + + case FLEXObjectExplorerSectionClassMethods: { + FLEXMethodBox *methodBox = self.filteredClassMethods[row]; + Method method = methodBox.method; + viewController = [[FLEXMethodCallingViewController alloc] initWithTarget:[self.object class] method:method]; + } break; + + case FLEXObjectExplorerSectionSuperclasses: { + Class superclass = self.filteredSuperclasses[row]; + viewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:superclass]; + } break; + + case FLEXObjectExplorerSectionReferencingInstances: { + viewController = [FLEXInstancesTableViewController instancesTableViewControllerForInstancesReferencingObject:self.object]; + } break; + } + return viewController; +} + + +#pragma mark - Table View Data Source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return [[self visibleExplorerSections] count]; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + FLEXObjectExplorerSection explorerSection = [self explorerSectionAtIndex:section]; + return [self numberOfRowsForExplorerSection:explorerSection]; +} + +- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section +{ + FLEXObjectExplorerSection explorerSection = [self explorerSectionAtIndex:section]; + return [self titleForExplorerSection:explorerSection]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXObjectExplorerSection explorerSection = [self explorerSectionAtIndex:indexPath.section]; + + BOOL useDescriptionCell = explorerSection == FLEXObjectExplorerSectionDescription; + NSString *cellIdentifier = useDescriptionCell ? kFLEXMultilineTableViewCellIdentifier : @"cell"; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; + if (!cell) { + if (useDescriptionCell) { + cell = [[FLEXMultilineTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; + cell.textLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + } else { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; + UIFont *cellFont = [FLEXUtility defaultTableViewCellLabelFont]; + cell.textLabel.font = cellFont; + cell.detailTextLabel.font = cellFont; + cell.detailTextLabel.textColor = [UIColor grayColor]; + } + } + + cell.textLabel.text = [self titleForRow:indexPath.row inExplorerSection:explorerSection]; + cell.detailTextLabel.text = [self subtitleForRow:indexPath.row inExplorerSection:explorerSection]; + cell.accessoryType = [self canDrillInToRow:indexPath.row inExplorerSection:explorerSection] ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone; + + return cell; +} + +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXObjectExplorerSection explorerSection = [self explorerSectionAtIndex:indexPath.section]; + CGFloat height = self.tableView.rowHeight; + if (explorerSection == FLEXObjectExplorerSectionDescription) { + NSString *text = [self titleForRow:indexPath.row inExplorerSection:explorerSection]; + NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{ NSFontAttributeName : [FLEXUtility defaultTableViewCellLabelFont] }]; + CGFloat preferredHeight = [FLEXMultilineTableViewCell preferredHeightWithAttributedText:attributedText inTableViewWidth:self.tableView.frame.size.width style:tableView.style showsAccessory:NO]; + height = MAX(height, preferredHeight); + } + return height; +} + + +#pragma mark - Table View Delegate + +- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXObjectExplorerSection explorerSection = [self explorerSectionAtIndex:indexPath.section]; + return [self canDrillInToRow:indexPath.row inExplorerSection:explorerSection]; +} + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXObjectExplorerSection explorerSection = [self explorerSectionAtIndex:indexPath.section]; + UIViewController *detailViewController = [self drillInViewControllerForRow:indexPath.row inExplorerSection:explorerSection]; + if (detailViewController) { + [self.navigationController pushViewController:detailViewController animated:YES]; + } else { + [tableView deselectRowAtIndexPath:indexPath animated:YES]; + } +} + +- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath +{ + FLEXObjectExplorerSection explorerSection = [self explorerSectionAtIndex:indexPath.section]; + BOOL canCopy = [self canCopyRow:indexPath.row inExplorerSection:explorerSection]; + return canCopy; +} + +- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + BOOL canPerformAction = NO; + + if (action == @selector(copy:)) { + FLEXObjectExplorerSection explorerSection = [self explorerSectionAtIndex:indexPath.section]; + BOOL canCopy = [self canCopyRow:indexPath.row inExplorerSection:explorerSection]; + canPerformAction = canCopy; + } + + return canPerformAction; +} + +- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender +{ + if (action == @selector(copy:)) { + FLEXObjectExplorerSection explorerSection = [self explorerSectionAtIndex:indexPath.section]; + NSString *stringToCopy = @""; + + NSString *title = [self titleForRow:indexPath.row inExplorerSection:explorerSection]; + if ([title length] > 0) { + stringToCopy = [stringToCopy stringByAppendingString:title]; + } + + NSString *subtitle = [self subtitleForRow:indexPath.row inExplorerSection:explorerSection]; + if ([subtitle length] > 0) { + if ([stringToCopy length] > 0) { + stringToCopy = [stringToCopy stringByAppendingString:@"\n\n"]; + } + stringToCopy = [stringToCopy stringByAppendingString:subtitle]; + } + + [[UIPasteboard generalPasteboard] setString:stringToCopy]; + } +} + + +#pragma mark - Custom Section + +- (void)updateCustomData +{ + self.cachedCustomSectionRowCookies = [self customSectionRowCookies]; +} + +- (void)updateFilteredCustomData +{ + NSIndexSet *filteredIndexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [self.cachedCustomSectionRowCookies count])]; + if ([self.filterText length] > 0) { + filteredIndexSet = [filteredIndexSet indexesPassingTest:^BOOL(NSUInteger index, BOOL *stop) { + BOOL matches = NO; + NSString *rowTitle = [self customSectionTitleForRowCookie:self.cachedCustomSectionRowCookies[index]]; + if ([rowTitle rangeOfString:self.filterText options:NSCaseInsensitiveSearch].location != NSNotFound) { + matches = YES; + } + return matches; + }]; + } + self.customSectionVisibleIndexes = filteredIndexSet; +} + +- (id)customSectionRowCookieForVisibleRow:(NSUInteger)row +{ + return [[self.cachedCustomSectionRowCookies objectsAtIndexes:self.customSectionVisibleIndexes] objectAtIndex:row]; +} + + +#pragma mark - Subclasses Can Override + +- (NSString *)customSectionTitle +{ + return nil; +} + +- (NSArray *)customSectionRowCookies +{ + return nil; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + return nil; +} + +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie +{ + return nil; +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + return NO; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + return nil; +} + +- (BOOL)canHaveInstanceState +{ + return YES; +} + +- (BOOL)canCallInstanceMethods +{ + return YES; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXSetExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXSetExplorerViewController.h new file mode 100644 index 0000000000..7e43870398 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXSetExplorerViewController.h @@ -0,0 +1,13 @@ +// +// FLEXSetExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 5/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" + +@interface FLEXSetExplorerViewController : FLEXObjectExplorerViewController + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXSetExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXSetExplorerViewController.m new file mode 100644 index 0000000000..f6e5fd12ef --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXSetExplorerViewController.m @@ -0,0 +1,64 @@ +// +// FLEXSetExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 5/16/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXSetExplorerViewController.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXObjectExplorerFactory.h" + +@interface FLEXSetExplorerViewController () + +@property (nonatomic, readonly) NSSet *set; + +@end + +@implementation FLEXSetExplorerViewController + +- (NSSet *)set +{ + return [self.object isKindOfClass:[NSSet class]] ? self.object : nil; +} + + +#pragma mark - Superclass Overrides + +- (NSString *)customSectionTitle +{ + return @"Set Objects"; +} + +- (NSArray *)customSectionRowCookies +{ + return [self.set allObjects]; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + return [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:rowCookie]; +} + +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie +{ + return nil; +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + return YES; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + return [FLEXObjectExplorerFactory explorerViewControllerForObject:rowCookie]; +} + +- (BOOL)shouldShowDescription +{ + return NO; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXViewControllerExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXViewControllerExplorerViewController.h new file mode 100644 index 0000000000..7b7ed7574f --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXViewControllerExplorerViewController.h @@ -0,0 +1,13 @@ +// +// FLEXViewControllerExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 6/11/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" + +@interface FLEXViewControllerExplorerViewController : FLEXObjectExplorerViewController + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXViewControllerExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXViewControllerExplorerViewController.m new file mode 100644 index 0000000000..a9e590029f --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXViewControllerExplorerViewController.m @@ -0,0 +1,96 @@ +// +// FLEXViewControllerExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 6/11/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXViewControllerExplorerViewController.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXObjectExplorerFactory.h" + +typedef NS_ENUM(NSUInteger, FLEXViewControllerExplorerRow) { + FLEXViewControllerExplorerRowPush, + FLEXViewControllerExplorerRowView +}; + +@interface FLEXViewControllerExplorerViewController () + +@property (nonatomic, readonly) UIViewController *viewController; + +@end + +@implementation FLEXViewControllerExplorerViewController + +- (UIViewController *)viewController +{ + return [self.object isKindOfClass:[UIViewController class]] ? self.object : nil; +} + +- (BOOL)canPushViewController +{ + // Only show the "Push View Controller" option if it's not already part of the hierarchy to avoid really disrupting the app. + return self.viewController.view.window == nil; +} + + +#pragma mark - Superclass Overrides + +- (NSString *)customSectionTitle +{ + return @"Shortcuts"; +} + +- (NSArray *)customSectionRowCookies +{ + NSArray *rowCookies = @[@(FLEXViewControllerExplorerRowView)]; + if ([self canPushViewController]) { + rowCookies = [@[@(FLEXViewControllerExplorerRowPush)] arrayByAddingObjectsFromArray:rowCookies]; + } + return rowCookies; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + NSString *title = nil; + if ([rowCookie isEqual:@(FLEXViewControllerExplorerRowPush)]) { + title = @"Push View Controller"; + } else if ([rowCookie isEqual:@(FLEXViewControllerExplorerRowView)]) { + title = @"@property UIView *view"; + } + return title; +} + +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie +{ + NSString *subtitle = nil; + if ([rowCookie isEqual:@(FLEXViewControllerExplorerRowView)]) { + subtitle = [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:self.viewController.view]; + } + return subtitle; +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + BOOL canDrillIn = NO; + if ([rowCookie isEqual:@(FLEXViewControllerExplorerRowPush)]) { + canDrillIn = [self canPushViewController]; + }else if ([rowCookie isEqual:@(FLEXViewControllerExplorerRowView)]) { + canDrillIn = self.viewController.view != nil; + } + return canDrillIn; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + UIViewController *drillInViewController = nil; + if ([rowCookie isEqual:@(FLEXViewControllerExplorerRowPush)]) { + drillInViewController = self.viewController; + } else if ([rowCookie isEqual:@(FLEXViewControllerExplorerRowView)]) { + drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:self.viewController.view]; + } + return drillInViewController; +} + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXViewExplorerViewController.h b/Pods/FLEX/Classes/ObjectExplorers/FLEXViewExplorerViewController.h new file mode 100644 index 0000000000..241ff1d8a1 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXViewExplorerViewController.h @@ -0,0 +1,13 @@ +// +// FLEXViewExplorerViewController.h +// Flipboard +// +// Created by Ryan Olson on 6/11/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXObjectExplorerViewController.h" + +@interface FLEXViewExplorerViewController : FLEXObjectExplorerViewController + +@end diff --git a/Pods/FLEX/Classes/ObjectExplorers/FLEXViewExplorerViewController.m b/Pods/FLEX/Classes/ObjectExplorers/FLEXViewExplorerViewController.m new file mode 100644 index 0000000000..fe9ccc9041 --- /dev/null +++ b/Pods/FLEX/Classes/ObjectExplorers/FLEXViewExplorerViewController.m @@ -0,0 +1,217 @@ +// +// FLEXViewExplorerViewController.m +// Flipboard +// +// Created by Ryan Olson on 6/11/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXViewExplorerViewController.h" +#import "FLEXRuntimeUtility.h" +#import "FLEXUtility.h" +#import "FLEXObjectExplorerFactory.h" +#import "FLEXImagePreviewViewController.h" +#import "FLEXPropertyEditorViewController.h" + +typedef NS_ENUM(NSUInteger, FLEXViewExplorerRow) { + FLEXViewExplorerRowViewController, + FLEXViewExplorerRowPreview, + FLEXViewExplorerRowViewControllerForAncestor +}; + +@interface FLEXViewExplorerViewController () + +// Don't clash with UIViewController's view property +@property (nonatomic, readonly) UIView *viewToExplore; + +@end + +@implementation FLEXViewExplorerViewController + +- (UIView *)viewToExplore +{ + return [self.object isKindOfClass:[UIView class]] ? self.object : nil; +} + + +#pragma mark - Superclass Overrides + +- (NSString *)customSectionTitle +{ + return @"Shortcuts"; +} + +- (NSArray *)customSectionRowCookies +{ + NSMutableArray *rowCookies = [NSMutableArray array]; + + if ([FLEXUtility viewControllerForView:self.viewToExplore]) { + [rowCookies addObject:@(FLEXViewExplorerRowViewController)]; + }else{ + [rowCookies addObject:@(FLEXViewExplorerRowViewControllerForAncestor)]; + } + + [rowCookies addObject:@(FLEXViewExplorerRowPreview)]; + [rowCookies addObjectsFromArray:[self shortcutPropertyNames]]; + + return rowCookies; +} + +- (NSArray *)shortcutPropertyNames +{ + NSArray *propertyNames = @[@"frame", @"bounds", @"center", @"transform", @"backgroundColor", @"alpha", @"opaque", @"hidden", @"clipsToBounds", @"userInteractionEnabled", @"layer"]; + + if ([self.viewToExplore isKindOfClass:[UILabel class]]) { + propertyNames = [@[@"text", @"font", @"textColor"] arrayByAddingObjectsFromArray:propertyNames]; + } + + return propertyNames; +} + +- (NSString *)customSectionTitleForRowCookie:(id)rowCookie +{ + NSString *title = nil; + + if ([rowCookie isKindOfClass:[NSNumber class]]) { + FLEXViewExplorerRow row = [rowCookie unsignedIntegerValue]; + switch (row) { + case FLEXViewExplorerRowViewController: + title = @"View Controller"; + break; + + case FLEXViewExplorerRowPreview: + title = @"Preview Image"; + break; + + case FLEXViewExplorerRowViewControllerForAncestor: + title = @"View Controller For Ancestor"; + break; + } + } else if ([rowCookie isKindOfClass:[NSString class]]) { + objc_property_t property = [self viewPropertyForName:rowCookie]; + if (property) { + NSString *prettyPropertyName = [FLEXRuntimeUtility prettyNameForProperty:property]; + // Since we're outside of the "properties" section, prepend @property for clarity. + title = [NSString stringWithFormat:@"@property %@", prettyPropertyName]; + } + } + + return title; +} + +- (NSString *)customSectionSubtitleForRowCookie:(id)rowCookie +{ + NSString *subtitle = nil; + + if ([rowCookie isKindOfClass:[NSNumber class]]) { + FLEXViewExplorerRow row = [rowCookie unsignedIntegerValue]; + switch (row) { + case FLEXViewExplorerRowViewController: + subtitle = [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:[FLEXUtility viewControllerForView:self.viewToExplore]]; + break; + + case FLEXViewExplorerRowPreview: + break; + + case FLEXViewExplorerRowViewControllerForAncestor: + subtitle = [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:[FLEXUtility viewControllerForAncestralView:self.viewToExplore]]; + break; + } + } else if ([rowCookie isKindOfClass:[NSString class]]) { + objc_property_t property = [self viewPropertyForName:rowCookie]; + if (property) { + id value = [FLEXRuntimeUtility valueForProperty:property onObject:self.viewToExplore]; + subtitle = [FLEXRuntimeUtility descriptionForIvarOrPropertyValue:value]; + } + } + + return subtitle; +} + +- (objc_property_t)viewPropertyForName:(NSString *)propertyName +{ + return class_getProperty([self.viewToExplore class], [propertyName UTF8String]); +} + +- (BOOL)customSectionCanDrillIntoRowWithCookie:(id)rowCookie +{ + return YES; +} + +- (UIViewController *)customSectionDrillInViewControllerForRowCookie:(id)rowCookie +{ + UIViewController *drillInViewController = nil; + + if ([rowCookie isKindOfClass:[NSNumber class]]) { + FLEXViewExplorerRow row = [rowCookie unsignedIntegerValue]; + switch (row) { + case FLEXViewExplorerRowViewController: + drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:[FLEXUtility viewControllerForView:self.viewToExplore]]; + break; + + case FLEXViewExplorerRowPreview: + drillInViewController = [[self class] imagePreviewViewControllerForView:self.viewToExplore]; + break; + + case FLEXViewExplorerRowViewControllerForAncestor: + drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:[FLEXUtility viewControllerForAncestralView:self.viewToExplore]]; + break; + } + } else if ([rowCookie isKindOfClass:[NSString class]]) { + objc_property_t property = [self viewPropertyForName:rowCookie]; + if (property) { + id currentValue = [FLEXRuntimeUtility valueForProperty:property onObject:self.viewToExplore]; + if ([FLEXPropertyEditorViewController canEditProperty:property currentValue:currentValue]) { + drillInViewController = [[FLEXPropertyEditorViewController alloc] initWithTarget:self.object property:property]; + } else { + drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:currentValue]; + } + } + } + + return drillInViewController; +} + ++ (UIViewController *)imagePreviewViewControllerForView:(UIView *)view +{ + UIViewController *imagePreviewViewController = nil; + if (!CGRectIsEmpty(view.bounds)) { + CGSize viewSize = view.bounds.size; + UIGraphicsBeginImageContextWithOptions(viewSize, NO, 0.0); + [view drawViewHierarchyInRect:CGRectMake(0, 0, viewSize.width, viewSize.height) afterScreenUpdates:YES]; + UIImage *previewImage = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + imagePreviewViewController = [[FLEXImagePreviewViewController alloc] initWithImage:previewImage]; + } + return imagePreviewViewController; +} + + +#pragma mark - Runtime Adjustment + ++ (void)initialize +{ + // A quirk of UIView: a lot of the "@property"s are not actually properties from the perspective of the runtime. + // We add these properties to the class at runtime if they haven't been added yet. + // This way, we can use our property editor to access and change them. + // The property attributes match the declared attributes in UIView.h + NSDictionary *frameAttributes = @{kFLEXUtilityAttributeTypeEncoding : @(@encode(CGRect)), kFLEXUtilityAttributeNonAtomic : @""}; + [FLEXRuntimeUtility tryAddPropertyWithName:"frame" attributes:frameAttributes toClass:[UIView class]]; + + NSDictionary *alphaAttributes = @{kFLEXUtilityAttributeTypeEncoding : @(@encode(CGFloat)), kFLEXUtilityAttributeNonAtomic : @""}; + [FLEXRuntimeUtility tryAddPropertyWithName:"alpha" attributes:alphaAttributes toClass:[UIView class]]; + + NSDictionary *clipsAttributes = @{kFLEXUtilityAttributeTypeEncoding : @(@encode(BOOL)), kFLEXUtilityAttributeNonAtomic : @""}; + [FLEXRuntimeUtility tryAddPropertyWithName:"clipsToBounds" attributes:clipsAttributes toClass:[UIView class]]; + + NSDictionary *opaqueAttributes = @{kFLEXUtilityAttributeTypeEncoding : @(@encode(BOOL)), kFLEXUtilityAttributeNonAtomic : @"", kFLEXUtilityAttributeCustomGetter : @"isOpaque"}; + [FLEXRuntimeUtility tryAddPropertyWithName:"opaque" attributes:opaqueAttributes toClass:[UIView class]]; + + NSDictionary *hiddenAttributes = @{kFLEXUtilityAttributeTypeEncoding : @(@encode(BOOL)), kFLEXUtilityAttributeNonAtomic : @"", kFLEXUtilityAttributeCustomGetter : @"isHidden"}; + [FLEXRuntimeUtility tryAddPropertyWithName:"hidden" attributes:hiddenAttributes toClass:[UIView class]]; + + NSDictionary *backgroundColorAttributes = @{kFLEXUtilityAttributeTypeEncoding : @(FLEXEncodeClass(UIColor)), kFLEXUtilityAttributeNonAtomic : @"", kFLEXUtilityAttributeCopy : @""}; + [FLEXRuntimeUtility tryAddPropertyWithName:"backgroundColor" attributes:backgroundColorAttributes toClass:[UIView class]]; +} + +@end diff --git a/Pods/FLEX/Classes/Toolbar/FLEXExplorerToolbar.h b/Pods/FLEX/Classes/Toolbar/FLEXExplorerToolbar.h new file mode 100644 index 0000000000..f6de0c798e --- /dev/null +++ b/Pods/FLEX/Classes/Toolbar/FLEXExplorerToolbar.h @@ -0,0 +1,49 @@ +// +// FLEXExplorerToolbar.h +// Flipboard +// +// Created by Ryan Olson on 4/4/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@class FLEXToolbarItem; + +@interface FLEXExplorerToolbar : UIView + +/// Toolbar item for selecting views. +/// Users of the toolbar can configure the enabled/selected state and event targets/actions. +@property (nonatomic, strong, readonly) FLEXToolbarItem *selectItem; + +/// Toolbar item for presenting a list with the view hierarchy. +/// Users of the toolbar can configure the enabled state and event targets/actions. +@property (nonatomic, strong, readonly) FLEXToolbarItem *hierarchyItem; + +/// Toolbar item for moving views. +/// Users of the toolbar can configure the enabled/selected state and event targets/actions. +@property (nonatomic, strong, readonly) FLEXToolbarItem *moveItem; + +/// Toolbar item for inspecting details of the selected view. +/// Users of the toolbar can configure the enabled state and event targets/actions. +@property (nonatomic, strong, readonly) FLEXToolbarItem *globalsItem; + +/// Toolbar item for hiding the explorer. +/// Users of the toolbar can configure the event targets/actions. +@property (nonatomic, strong, readonly) FLEXToolbarItem *closeItem; + +/// A view for moving the entire toolbar. +/// Users of the toolbar can attach a pan gesture recognizer to decide how to reposition the toolbar. +@property (nonatomic, strong, readonly) UIView *dragHandle; + +/// A color matching the overlay on color on the selected view. +@property (nonatomic, strong) UIColor *selectedViewOverlayColor; + +/// Description text for the selected view displayed below the toolbar items. +@property (nonatomic, copy) NSString *selectedViewDescription; + +/// Area where details of the selected view are shown +/// Users of the toolbar can attach a tap gesture recognizer to show additional details. +@property (nonatomic, strong, readonly) UIView *selectedViewDescriptionContainer; + +@end diff --git a/Pods/FLEX/Classes/Toolbar/FLEXExplorerToolbar.m b/Pods/FLEX/Classes/Toolbar/FLEXExplorerToolbar.m new file mode 100644 index 0000000000..c257101ec3 --- /dev/null +++ b/Pods/FLEX/Classes/Toolbar/FLEXExplorerToolbar.m @@ -0,0 +1,226 @@ +// +// FLEXExplorerToolbar.m +// Flipboard +// +// Created by Ryan Olson on 4/4/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXExplorerToolbar.h" +#import "FLEXToolbarItem.h" +#import "FLEXResources.h" +#import "FLEXUtility.h" + +@interface FLEXExplorerToolbar () + +@property (nonatomic, strong, readwrite) FLEXToolbarItem *selectItem; +@property (nonatomic, strong, readwrite) FLEXToolbarItem *moveItem; +@property (nonatomic, strong, readwrite) FLEXToolbarItem *globalsItem; +@property (nonatomic, strong, readwrite) FLEXToolbarItem *closeItem; +@property (nonatomic, strong, readwrite) FLEXToolbarItem *hierarchyItem; +@property (nonatomic, strong, readwrite) UIView *dragHandle; + +@property (nonatomic, strong) UIImageView *dragHandleImageView; + +@property (nonatomic, strong) NSArray *toolbarItems; + +@property (nonatomic, strong) UIView *selectedViewDescriptionContainer; +@property (nonatomic, strong) UIView *selectedViewColorIndicator; +@property (nonatomic, strong) UILabel *selectedViewDescriptionLabel; + +@end + +@implementation FLEXExplorerToolbar + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + NSMutableArray *toolbarItems = [NSMutableArray array]; + + self.dragHandle = [[UIView alloc] init]; + self.dragHandle.backgroundColor = [FLEXToolbarItem defaultBackgroundColor]; + [self addSubview:self.dragHandle]; + + UIImage *dragHandle = [FLEXResources dragHandle]; + self.dragHandleImageView = [[UIImageView alloc] initWithImage:dragHandle]; + [self.dragHandle addSubview:self.dragHandleImageView]; + + UIImage *globalsIcon = [FLEXResources globeIcon]; + self.globalsItem = [FLEXToolbarItem toolbarItemWithTitle:@"menu" image:globalsIcon]; + [self addSubview:self.globalsItem]; + [toolbarItems addObject:self.globalsItem]; + + UIImage *listIcon = [FLEXResources listIcon]; + self.hierarchyItem = [FLEXToolbarItem toolbarItemWithTitle:@"views" image:listIcon]; + [self addSubview:self.hierarchyItem]; + [toolbarItems addObject:self.hierarchyItem]; + + UIImage *selectIcon = [FLEXResources selectIcon]; + self.selectItem = [FLEXToolbarItem toolbarItemWithTitle:@"select" image:selectIcon]; + [self addSubview:self.selectItem]; + [toolbarItems addObject:self.selectItem]; + + UIImage *moveIcon = [FLEXResources moveIcon]; + self.moveItem = [FLEXToolbarItem toolbarItemWithTitle:@"move" image:moveIcon]; + [self addSubview:self.moveItem]; + [toolbarItems addObject:self.moveItem]; + + UIImage *closeIcon = [FLEXResources closeIcon]; + self.closeItem = [FLEXToolbarItem toolbarItemWithTitle:@"close" image:closeIcon]; + [self addSubview:self.closeItem]; + [toolbarItems addObject:self.closeItem]; + + self.toolbarItems = toolbarItems; + self.backgroundColor = [UIColor clearColor]; + + self.selectedViewDescriptionContainer = [[UIView alloc] init]; + self.selectedViewDescriptionContainer.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.95]; + self.selectedViewDescriptionContainer.hidden = YES; + [self addSubview:self.selectedViewDescriptionContainer]; + + self.selectedViewColorIndicator = [[UIView alloc] init]; + self.selectedViewColorIndicator.backgroundColor = [UIColor redColor]; + [self.selectedViewDescriptionContainer addSubview:self.selectedViewColorIndicator]; + + self.selectedViewDescriptionLabel = [[UILabel alloc] init]; + self.selectedViewDescriptionLabel.backgroundColor = [UIColor clearColor]; + self.selectedViewDescriptionLabel.font = [[self class] descriptionLabelFont]; + [self.selectedViewDescriptionContainer addSubview:self.selectedViewDescriptionLabel]; + } + return self; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + // Drag Handle + const CGFloat kToolbarItemHeight = [[self class] toolbarItemHeight]; + self.dragHandle.frame = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, [[self class] dragHandleWidth], kToolbarItemHeight); + CGRect dragHandleImageFrame = self.dragHandleImageView.frame; + dragHandleImageFrame.origin.x = FLEXFloor((self.dragHandle.frame.size.width - dragHandleImageFrame.size.width) / 2.0); + dragHandleImageFrame.origin.y = FLEXFloor((self.dragHandle.frame.size.height - dragHandleImageFrame.size.height) / 2.0); + self.dragHandleImageView.frame = dragHandleImageFrame; + + + // Toolbar Items + CGFloat originX = CGRectGetMaxX(self.dragHandle.frame); + CGFloat originY = self.bounds.origin.y; + CGFloat height = kToolbarItemHeight; + CGFloat width = FLEXFloor((CGRectGetMaxX(self.bounds) - originX) / [self.toolbarItems count]); + for (UIView *toolbarItem in self.toolbarItems) { + toolbarItem.frame = CGRectMake(originX, originY, width, height); + originX = CGRectGetMaxX(toolbarItem.frame); + } + + // Make sure the last toolbar item goes to the edge to account for any accumulated rounding effects. + UIView *lastToolbarItem = [self.toolbarItems lastObject]; + CGRect lastToolbarItemFrame = lastToolbarItem.frame; + lastToolbarItemFrame.size.width = CGRectGetMaxX(self.bounds) - lastToolbarItemFrame.origin.x; + lastToolbarItem.frame = lastToolbarItemFrame; + + const CGFloat kSelectedViewColorDiameter = [[self class] selectedViewColorIndicatorDiameter]; + const CGFloat kDescriptionLabelHeight = [[self class] descriptionLabelHeight]; + const CGFloat kHorizontalPadding = [[self class] horizontalPadding]; + const CGFloat kDescriptionVerticalPadding = [[self class] descriptionVerticalPadding]; + const CGFloat kDescriptionContainerHeight = [[self class] descriptionContainerHeight]; + + CGRect descriptionContainerFrame = CGRectZero; + descriptionContainerFrame.size.height = kDescriptionContainerHeight; + descriptionContainerFrame.origin.y = CGRectGetMaxY(self.bounds) - kDescriptionContainerHeight; + descriptionContainerFrame.size.width = self.bounds.size.width; + self.selectedViewDescriptionContainer.frame = descriptionContainerFrame; + + // Selected View Color + CGRect selectedViewColorFrame = CGRectZero; + selectedViewColorFrame.size.width = kSelectedViewColorDiameter; + selectedViewColorFrame.size.height = kSelectedViewColorDiameter; + selectedViewColorFrame.origin.x = kHorizontalPadding; + selectedViewColorFrame.origin.y = FLEXFloor((kDescriptionContainerHeight - kSelectedViewColorDiameter) / 2.0); + self.selectedViewColorIndicator.frame = selectedViewColorFrame; + self.selectedViewColorIndicator.layer.cornerRadius = ceil(selectedViewColorFrame.size.height / 2.0); + + // Selected View Description + CGRect descriptionLabelFrame = CGRectZero; + CGFloat descriptionOriginX = CGRectGetMaxX(selectedViewColorFrame) + kHorizontalPadding; + descriptionLabelFrame.size.height = kDescriptionLabelHeight; + descriptionLabelFrame.origin.x = descriptionOriginX; + descriptionLabelFrame.origin.y = kDescriptionVerticalPadding; + descriptionLabelFrame.size.width = CGRectGetMaxX(self.selectedViewDescriptionContainer.bounds) - kHorizontalPadding - descriptionOriginX; + self.selectedViewDescriptionLabel.frame = descriptionLabelFrame; +} + + +#pragma mark - Setter Overrides + +- (void)setSelectedViewOverlayColor:(UIColor *)selectedViewOverlayColor +{ + if (![_selectedViewOverlayColor isEqual:selectedViewOverlayColor]) { + _selectedViewOverlayColor = selectedViewOverlayColor; + self.selectedViewColorIndicator.backgroundColor = selectedViewOverlayColor; + } +} + +- (void)setSelectedViewDescription:(NSString *)selectedViewDescription +{ + if (![_selectedViewDescription isEqual:selectedViewDescription]) { + _selectedViewDescription = selectedViewDescription; + self.selectedViewDescriptionLabel.text = selectedViewDescription; + BOOL showDescription = [selectedViewDescription length] > 0; + self.selectedViewDescriptionContainer.hidden = !showDescription; + } +} + + +#pragma mark - Sizing Convenience Methods + ++ (UIFont *)descriptionLabelFont +{ + return [UIFont systemFontOfSize:12.0]; +} + ++ (CGFloat)toolbarItemHeight +{ + return 44.0; +} + ++ (CGFloat)dragHandleWidth +{ + return 30.0; +} + ++ (CGFloat)descriptionLabelHeight +{ + return ceil([[self descriptionLabelFont] lineHeight]); +} + ++ (CGFloat)descriptionVerticalPadding +{ + return 2.0; +} + ++ (CGFloat)descriptionContainerHeight +{ + return [self descriptionVerticalPadding] * 2.0 + [self descriptionLabelHeight]; +} + ++ (CGFloat)selectedViewColorIndicatorDiameter +{ + return ceil([self descriptionLabelHeight] / 2.0); +} + ++ (CGFloat)horizontalPadding +{ + return 11.0; +} + +- (CGSize)sizeThatFits:(CGSize)size +{ + CGFloat height = 0.0; + height += [[self class] toolbarItemHeight]; + height += [[self class] descriptionContainerHeight]; + return CGSizeMake(size.width, height); +} + +@end diff --git a/Pods/FLEX/Classes/Toolbar/FLEXToolbarItem.h b/Pods/FLEX/Classes/Toolbar/FLEXToolbarItem.h new file mode 100644 index 0000000000..9c297e0bb4 --- /dev/null +++ b/Pods/FLEX/Classes/Toolbar/FLEXToolbarItem.h @@ -0,0 +1,17 @@ +// +// FLEXToolbarItem.h +// Flipboard +// +// Created by Ryan Olson on 4/4/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@interface FLEXToolbarItem : UIButton + ++ (instancetype)toolbarItemWithTitle:(NSString *)title image:(UIImage *)image; + ++ (UIColor *)defaultBackgroundColor; + +@end diff --git a/Pods/FLEX/Classes/Toolbar/FLEXToolbarItem.m b/Pods/FLEX/Classes/Toolbar/FLEXToolbarItem.m new file mode 100644 index 0000000000..734f7f8e33 --- /dev/null +++ b/Pods/FLEX/Classes/Toolbar/FLEXToolbarItem.m @@ -0,0 +1,133 @@ +// +// FLEXToolbarItem.m +// Flipboard +// +// Created by Ryan Olson on 4/4/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXToolbarItem.h" +#import "FLEXUtility.h" + +@interface FLEXToolbarItem () + +@property (nonatomic, copy) NSAttributedString *attributedTitle; +@property (nonatomic, strong) UIImage *image; + +@end + +@implementation FLEXToolbarItem + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + self.backgroundColor = [[self class] defaultBackgroundColor]; + [self setTitleColor:[[self class] defaultTitleColor] forState:UIControlStateNormal]; + [self setTitleColor:[[self class] disabledTitleColor] forState:UIControlStateDisabled]; + } + return self; +} + ++ (instancetype)toolbarItemWithTitle:(NSString *)title image:(UIImage *)image +{ + FLEXToolbarItem *toolbarItem = [self buttonWithType:UIButtonTypeCustom]; + NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:title attributes:[self titleAttributes]]; + toolbarItem.attributedTitle = attributedTitle; + toolbarItem.image = image; + [toolbarItem setAttributedTitle:attributedTitle forState:UIControlStateNormal]; + [toolbarItem setImage:image forState:UIControlStateNormal]; + return toolbarItem; +} + + +#pragma mark - Display Defaults + ++ (NSDictionary *)titleAttributes +{ + return @{NSFontAttributeName : [FLEXUtility defaultFontOfSize:12.0]}; +} + ++ (UIColor *)defaultTitleColor +{ + return [UIColor blackColor]; +} + ++ (UIColor *)disabledTitleColor +{ + return [UIColor colorWithWhite:121.0/255.0 alpha:1.0]; +} + ++ (UIColor *)highlightedBackgroundColor +{ + return [UIColor colorWithWhite:0.9 alpha:1.0]; +} + ++ (UIColor *)selectedBackgroundColor +{ + return [UIColor colorWithRed:199.0/255.0 green:199.0/255.0 blue:255.0/255.0 alpha:1.0]; +} + ++ (UIColor *)defaultBackgroundColor +{ + return [UIColor colorWithWhite:1.0 alpha:0.95]; +} + ++ (CGFloat)topMargin +{ + return 2.0; +} + + +#pragma mark - State Changes + +- (void)setHighlighted:(BOOL)highlighted +{ + [super setHighlighted:highlighted]; + [self updateBackgroundColor]; +} + +- (void)setSelected:(BOOL)selected +{ + [super setSelected:selected]; + [self updateBackgroundColor]; +} + +- (void)updateBackgroundColor +{ + if (self.highlighted) { + self.backgroundColor = [[self class] highlightedBackgroundColor]; + } else if (self.selected) { + self.backgroundColor = [[self class] selectedBackgroundColor]; + } else { + self.backgroundColor = [[self class] defaultBackgroundColor]; + } +} + + +#pragma mark - UIButton Layout Overrides + +- (CGRect)titleRectForContentRect:(CGRect)contentRect +{ + // Bottom aligned and centered. + CGRect titleRect = CGRectZero; + CGSize titleSize = [self.attributedTitle boundingRectWithSize:contentRect.size options:0 context:nil].size; + titleSize = CGSizeMake(ceil(titleSize.width), ceil(titleSize.height)); + titleRect.size = titleSize; + titleRect.origin.y = contentRect.origin.y + CGRectGetMaxY(contentRect) - titleSize.height; + titleRect.origin.x = contentRect.origin.x + FLEXFloor((contentRect.size.width - titleSize.width) / 2.0); + return titleRect; +} + +- (CGRect)imageRectForContentRect:(CGRect)contentRect +{ + CGSize imageSize = self.image.size; + CGRect titleRect = [self titleRectForContentRect:contentRect]; + CGFloat availableHeight = contentRect.size.height - titleRect.size.height - [[self class] topMargin]; + CGFloat originY = [[self class] topMargin] + FLEXFloor((availableHeight - imageSize.height) / 2.0); + CGFloat originX = FLEXFloor((contentRect.size.width - imageSize.width) / 2.0); + CGRect imageRect = CGRectMake(originX, originY, imageSize.width, imageSize.height); + return imageRect; +} + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXHeapEnumerator.h b/Pods/FLEX/Classes/Utility/FLEXHeapEnumerator.h new file mode 100644 index 0000000000..87109f024a --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXHeapEnumerator.h @@ -0,0 +1,17 @@ +// +// FLEXHeapEnumerator.h +// Flipboard +// +// Created by Ryan Olson on 5/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +typedef void (^flex_object_enumeration_block_t)(__unsafe_unretained id object, __unsafe_unretained Class actualClass); + +@interface FLEXHeapEnumerator : NSObject + ++ (void)enumerateLiveObjectsUsingBlock:(flex_object_enumeration_block_t)block; + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXHeapEnumerator.m b/Pods/FLEX/Classes/Utility/FLEXHeapEnumerator.m new file mode 100644 index 0000000000..53c3accd27 --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXHeapEnumerator.m @@ -0,0 +1,96 @@ +// +// FLEXHeapEnumerator.m +// Flipboard +// +// Created by Ryan Olson on 5/28/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXHeapEnumerator.h" +#import +#import +#import + +static CFMutableSetRef registeredClasses; + +// Mimics the objective-c object stucture for checking if a range of memory is an object. +typedef struct { + Class isa; +} flex_maybe_object_t; + +@implementation FLEXHeapEnumerator + +static void range_callback(task_t task, void *context, unsigned type, vm_range_t *ranges, unsigned rangeCount) +{ + flex_object_enumeration_block_t block = (__bridge flex_object_enumeration_block_t)context; + if (!block) { + return; + } + + for (unsigned int i = 0; i < rangeCount; i++) { + vm_range_t range = ranges[i]; + flex_maybe_object_t *tryObject = (flex_maybe_object_t *)range.address; + Class tryClass = NULL; +#ifdef __arm64__ + // See http://www.sealiesoftware.com/blog/archive/2013/09/24/objc_explain_Non-pointer_isa.html + extern uint64_t objc_debug_isa_class_mask WEAK_IMPORT_ATTRIBUTE; + tryClass = (__bridge Class)((void *)((uint64_t)tryObject->isa & objc_debug_isa_class_mask)); +#else + tryClass = tryObject->isa; +#endif + // If the class pointer matches one in our set of class pointers from the runtime, then we should have an object. + if (CFSetContainsValue(registeredClasses, (__bridge const void *)(tryClass))) { + block((__bridge id)tryObject, tryClass); + } + } +} + +static kern_return_t reader(__unused task_t remote_task, vm_address_t remote_address, __unused vm_size_t size, void **local_memory) +{ + *local_memory = (void *)remote_address; + return KERN_SUCCESS; +} + ++ (void)enumerateLiveObjectsUsingBlock:(flex_object_enumeration_block_t)block +{ + if (!block) { + return; + } + + // Refresh the class list on every call in case classes are added to the runtime. + [self updateRegisteredClasses]; + + // Inspired by: + // http://llvm.org/svn/llvm-project/lldb/tags/RELEASE_34/final/examples/darwin/heap_find/heap/heap_find.cpp + // https://gist.github.com/samdmarshall/17f4e66b5e2e579fd396 + + vm_address_t *zones = NULL; + unsigned int zoneCount = 0; + kern_return_t result = malloc_get_all_zones(TASK_NULL, reader, &zones, &zoneCount); + + if (result == KERN_SUCCESS) { + for (unsigned int i = 0; i < zoneCount; i++) { + malloc_zone_t *zone = (malloc_zone_t *)zones[i]; + if (zone->introspect && zone->introspect->enumerator) { + zone->introspect->enumerator(TASK_NULL, (__bridge void *)block, MALLOC_PTR_IN_USE_RANGE_TYPE, (vm_address_t)zone, reader, &range_callback); + } + } + } +} + ++ (void)updateRegisteredClasses +{ + if (!registeredClasses) { + registeredClasses = CFSetCreateMutable(NULL, 0, NULL); + } else { + CFSetRemoveAllValues(registeredClasses); + } + unsigned int count = 0; + Class *classes = objc_copyClassList(&count); + for (unsigned int i = 0; i < count; i++) { + CFSetAddValue(registeredClasses, (__bridge const void *)(classes[i])); + } + free(classes); +} + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXKeyboardHelpViewController.h b/Pods/FLEX/Classes/Utility/FLEXKeyboardHelpViewController.h new file mode 100644 index 0000000000..e688c85fae --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXKeyboardHelpViewController.h @@ -0,0 +1,13 @@ +// +// FLEXKeyboardHelpViewController.h +// UICatalog +// +// Created by Ryan Olson on 9/19/15. +// Copyright © 2015 f. All rights reserved. +// + +#import + +@interface FLEXKeyboardHelpViewController : UIViewController + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXKeyboardHelpViewController.m b/Pods/FLEX/Classes/Utility/FLEXKeyboardHelpViewController.m new file mode 100644 index 0000000000..5282b3467c --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXKeyboardHelpViewController.m @@ -0,0 +1,44 @@ +// +// FLEXKeyboardHelpViewController.m +// UICatalog +// +// Created by Ryan Olson on 9/19/15. +// Copyright © 2015 f. All rights reserved. +// + +#import "FLEXKeyboardHelpViewController.h" +#import "FLEXKeyboardShortcutManager.h" + +@interface FLEXKeyboardHelpViewController () + +@property (nonatomic, strong) UITextView *textView; + +@end + +@implementation FLEXKeyboardHelpViewController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.textView = [[UITextView alloc] initWithFrame:self.view.bounds]; + self.textView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + [self.view addSubview:self.textView]; +#if TARGET_OS_SIMULATOR + self.textView.text = [[FLEXKeyboardShortcutManager sharedManager] keyboardShortcutsDescription]; +#endif + self.textView.backgroundColor = [UIColor blackColor]; + self.textView.textColor = [UIColor whiteColor]; + self.textView.font = [UIFont boldSystemFontOfSize:14.0]; + self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque; + + self.title = @"Simulator Shortcuts"; + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donePressed:)]; +} + +- (void)donePressed:(id)sender +{ + [self.presentingViewController dismissViewControllerAnimated:YES completion:nil]; +} + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXKeyboardShortcutManager.h b/Pods/FLEX/Classes/Utility/FLEXKeyboardShortcutManager.h new file mode 100644 index 0000000000..732a8cbf5b --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXKeyboardShortcutManager.h @@ -0,0 +1,24 @@ +// +// FLEXKeyboardShortcutManager.h +// FLEX +// +// Created by Ryan Olson on 9/19/15. +// Copyright © 2015 Flipboard. All rights reserved. +// + +#import + +#if TARGET_OS_SIMULATOR + +@interface FLEXKeyboardShortcutManager : NSObject + ++ (instancetype)sharedManager; + +- (void)registerSimulatorShortcutWithKey:(NSString *)key modifiers:(UIKeyModifierFlags)modifiers action:(dispatch_block_t)action description:(NSString *)description; +- (NSString *)keyboardShortcutsDescription; + +@property (nonatomic, assign, getter=isEnabled) BOOL enabled; + +@end + +#endif diff --git a/Pods/FLEX/Classes/Utility/FLEXKeyboardShortcutManager.m b/Pods/FLEX/Classes/Utility/FLEXKeyboardShortcutManager.m new file mode 100644 index 0000000000..b55138e76e --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXKeyboardShortcutManager.m @@ -0,0 +1,306 @@ +// +// FLEXKeyboardShortcutManager.m +// FLEX +// +// Created by Ryan Olson on 9/19/15. +// Copyright © 2015 Flipboard. All rights reserved. +// + +#import "FLEXKeyboardShortcutManager.h" +#import "FLEXUtility.h" +#import +#import + +#if TARGET_OS_SIMULATOR + +@interface UIEvent (UIPhysicalKeyboardEvent) + +@property (nonatomic, strong) NSString *_modifiedInput; +@property (nonatomic, strong) NSString *_unmodifiedInput; +@property (nonatomic, assign) UIKeyModifierFlags _modifierFlags; +@property (nonatomic, assign) BOOL _isKeyDown; +@property (nonatomic, assign) long _keyCode; + +@end + +@interface FLEXKeyInput : NSObject + +@property (nonatomic, copy, readonly) NSString *key; +@property (nonatomic, assign, readonly) UIKeyModifierFlags flags; +@property (nonatomic, copy, readonly) NSString *helpDescription; + +@end + +@implementation FLEXKeyInput + +- (BOOL)isEqual:(id)object +{ + BOOL isEqual = NO; + if ([object isKindOfClass:[FLEXKeyInput class]]) { + FLEXKeyInput *keyCommand = (FLEXKeyInput *)object; + BOOL equalKeys = self.key == keyCommand.key || [self.key isEqual:keyCommand.key]; + BOOL equalFlags = self.flags == keyCommand.flags; + isEqual = equalKeys && equalFlags; + } + return isEqual; +} + +- (NSUInteger)hash +{ + return [self.key hash] ^ self.flags; +} + +- (id)copyWithZone:(NSZone *)zone +{ + return [[self class] keyInputForKey:self.key flags:self.flags helpDescription:self.helpDescription]; +} + +- (NSString *)description +{ + NSDictionary *keyMappings = @{ UIKeyInputUpArrow : @"↑", + UIKeyInputDownArrow : @"↓", + UIKeyInputLeftArrow : @"←", + UIKeyInputRightArrow : @"→", + UIKeyInputEscape : @"␛", + @" " : @"␠"}; + + NSString *prettyKey = nil; + if (self.key && keyMappings[self.key]) { + prettyKey = keyMappings[self.key]; + } else { + prettyKey = [self.key uppercaseString]; + } + + NSString *prettyFlags = @""; + if (self.flags & UIKeyModifierControl) { + prettyFlags = [prettyFlags stringByAppendingString:@"⌃"]; + } + if (self.flags & UIKeyModifierAlternate) { + prettyFlags = [prettyFlags stringByAppendingString:@"⌥"]; + } + if (self.flags & UIKeyModifierShift) { + prettyFlags = [prettyFlags stringByAppendingString:@"⇧"]; + } + if (self.flags & UIKeyModifierCommand) { + prettyFlags = [prettyFlags stringByAppendingString:@"⌘"]; + } + + // Fudging to get easy columns with tabs + if ([prettyFlags length] < 2) { + prettyKey = [prettyKey stringByAppendingString:@"\t"]; + } + + return [NSString stringWithFormat:@"%@%@\t%@", prettyFlags, prettyKey, self.helpDescription]; +} + ++ (instancetype)keyInputForKey:(NSString *)key flags:(UIKeyModifierFlags)flags +{ + return [self keyInputForKey:key flags:flags helpDescription:nil]; +} + ++ (instancetype)keyInputForKey:(NSString *)key flags:(UIKeyModifierFlags)flags helpDescription:(NSString *)helpDescription +{ + FLEXKeyInput *keyInput = [[self alloc] init]; + if (keyInput) { + keyInput->_key = key; + keyInput->_flags = flags; + keyInput->_helpDescription = helpDescription; + } + return keyInput; +} + +@end + +@interface FLEXKeyboardShortcutManager () + +@property (nonatomic, strong) NSMutableDictionary *actionsForKeyInputs; + +@property (nonatomic, assign, getter=isPressingShift) BOOL pressingShift; +@property (nonatomic, assign, getter=isPressingCommand) BOOL pressingCommand; +@property (nonatomic, assign, getter=isPressingControl) BOOL pressingControl; + +@end + +@implementation FLEXKeyboardShortcutManager + ++ (instancetype)sharedManager +{ + static FLEXKeyboardShortcutManager *sharedManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedManager = [[[self class] alloc] init]; + }); + return sharedManager; +} + ++ (void)load +{ + SEL originalKeyEventSelector = NSSelectorFromString(@"handleKeyUIEvent:"); + SEL swizzledKeyEventSelector = [FLEXUtility swizzledSelectorForSelector:originalKeyEventSelector]; + + void (^handleKeyUIEventSwizzleBlock)(UIApplication *, UIEvent *) = ^(UIApplication *slf, UIEvent *event) { + + [[[self class] sharedManager] handleKeyboardEvent:event]; + + ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledKeyEventSelector, event); + }; + + [FLEXUtility replaceImplementationOfKnownSelector:originalKeyEventSelector onClass:[UIApplication class] withBlock:handleKeyUIEventSwizzleBlock swizzledSelector:swizzledKeyEventSelector]; + + if ([[UITouch class] instancesRespondToSelector:@selector(maximumPossibleForce)]) { + SEL originalSendEventSelector = NSSelectorFromString(@"sendEvent:"); + SEL swizzledSendEventSelector = [FLEXUtility swizzledSelectorForSelector:originalSendEventSelector]; + + void (^sendEventSwizzleBlock)(UIApplication *, UIEvent *) = ^(UIApplication *slf, UIEvent *event) { + if (event.type == UIEventTypeTouches) { + FLEXKeyboardShortcutManager *keyboardManager = [FLEXKeyboardShortcutManager sharedManager]; + NSInteger pressureLevel = 0; + if (keyboardManager.isPressingShift) { + pressureLevel++; + } + if (keyboardManager.isPressingCommand) { + pressureLevel++; + } + if (keyboardManager.isPressingControl) { + pressureLevel++; + } + if (pressureLevel > 0) { + for (UITouch *touch in [event allTouches]) { + double adjustedPressureLevel = pressureLevel * 20 * touch.maximumPossibleForce; + [touch setValue:@(adjustedPressureLevel) forKey:@"_pressure"]; + } + } + } + + ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSendEventSelector, event); + }; + + [FLEXUtility replaceImplementationOfKnownSelector:originalSendEventSelector onClass:[UIApplication class] withBlock:sendEventSwizzleBlock swizzledSelector:swizzledSendEventSelector]; + + SEL originalSupportsTouchPressureSelector = NSSelectorFromString(@"_supportsForceTouch"); + SEL swizzledSupportsTouchPressureSelector = [FLEXUtility swizzledSelectorForSelector:originalSupportsTouchPressureSelector]; + + BOOL (^supportsTouchPressureSwizzleBlock)(UIDevice *) = ^BOOL(UIDevice *slf) { + return YES; + }; + + [FLEXUtility replaceImplementationOfKnownSelector:originalSupportsTouchPressureSelector onClass:[UIDevice class] withBlock:supportsTouchPressureSwizzleBlock swizzledSelector:swizzledSupportsTouchPressureSelector]; + } +} + +- (instancetype)init +{ + self = [super init]; + + if (self) { + _actionsForKeyInputs = [NSMutableDictionary dictionary]; + _enabled = YES; + } + + return self; +} + +- (void)registerSimulatorShortcutWithKey:(NSString *)key modifiers:(UIKeyModifierFlags)modifiers action:(dispatch_block_t)action description:(NSString *)description +{ + FLEXKeyInput *keyInput = [FLEXKeyInput keyInputForKey:key flags:modifiers helpDescription:description]; + [self.actionsForKeyInputs setObject:action forKey:keyInput]; +} + +static const long kFLEXControlKeyCode = 0xe0; +static const long kFLEXShiftKeyCode = 0xe1; +static const long kFLEXCommandKeyCode = 0xe3; + +- (void)handleKeyboardEvent:(UIEvent *)event +{ + if (!self.enabled) { + return; + } + + NSString *modifiedInput = nil; + NSString *unmodifiedInput = nil; + UIKeyModifierFlags flags = 0; + BOOL isKeyDown = NO; + + if ([event respondsToSelector:@selector(_modifiedInput)]) { + modifiedInput = [event _modifiedInput]; + } + + if ([event respondsToSelector:@selector(_unmodifiedInput)]) { + unmodifiedInput = [event _unmodifiedInput]; + } + + if ([event respondsToSelector:@selector(_modifierFlags)]) { + flags = [event _modifierFlags]; + } + + if ([event respondsToSelector:@selector(_isKeyDown)]) { + isKeyDown = [event _isKeyDown]; + } + + BOOL interactionEnabled = ![[UIApplication sharedApplication] isIgnoringInteractionEvents]; + BOOL hasFirstResponder = NO; + if (isKeyDown && [modifiedInput length] > 0 && interactionEnabled) { + UIResponder *firstResponder = nil; + for (UIWindow *window in [FLEXUtility allWindows]) { + firstResponder = [window valueForKey:@"firstResponder"]; + if (firstResponder) { + hasFirstResponder = YES; + break; + } + } + + // Ignore key commands (except escape) when there's an active responder + if (firstResponder) { + if ([unmodifiedInput isEqual:UIKeyInputEscape]) { + [firstResponder resignFirstResponder]; + } + } else { + FLEXKeyInput *exactMatch = [FLEXKeyInput keyInputForKey:unmodifiedInput flags:flags]; + + dispatch_block_t actionBlock = self.actionsForKeyInputs[exactMatch]; + + if (!actionBlock) { + FLEXKeyInput *shiftMatch = [FLEXKeyInput keyInputForKey:modifiedInput flags:flags&(!UIKeyModifierShift)]; + actionBlock = self.actionsForKeyInputs[shiftMatch]; + } + + if (!actionBlock) { + FLEXKeyInput *capitalMatch = [FLEXKeyInput keyInputForKey:[unmodifiedInput uppercaseString] flags:flags]; + actionBlock = self.actionsForKeyInputs[capitalMatch]; + } + + if (actionBlock) { + actionBlock(); + } + } + } + + // Calling _keyCode on events from the simulator keyboard will crash. + // It is only safe to call _keyCode when there's not an active responder. + if (!hasFirstResponder && [event respondsToSelector:@selector(_keyCode)]) { + long keyCode = [event _keyCode]; + if (keyCode == kFLEXControlKeyCode) { + self.pressingControl = isKeyDown; + } else if (keyCode == kFLEXCommandKeyCode) { + self.pressingCommand = isKeyDown; + } else if (keyCode == kFLEXShiftKeyCode) { + self.pressingShift = isKeyDown; + } + } +} + +- (NSString *)keyboardShortcutsDescription +{ + NSMutableString *description = [NSMutableString string]; + NSArray *keyInputs = [[self.actionsForKeyInputs allKeys] sortedArrayUsingComparator:^NSComparisonResult(FLEXKeyInput *_Nonnull input1, FLEXKeyInput *_Nonnull input2) { + return [input1.key caseInsensitiveCompare:input2.key]; + }]; + for (FLEXKeyInput *keyInput in keyInputs) { + [description appendFormat:@"%@\n", keyInput]; + } + return [description copy]; +} + +@end + +#endif diff --git a/Pods/FLEX/Classes/Utility/FLEXMultilineTableViewCell.h b/Pods/FLEX/Classes/Utility/FLEXMultilineTableViewCell.h new file mode 100644 index 0000000000..b462df952f --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXMultilineTableViewCell.h @@ -0,0 +1,17 @@ +// +// FLEXMultilineTableViewCell.h +// UICatalog +// +// Created by Ryan Olson on 2/13/15. +// Copyright (c) 2015 f. All rights reserved. +// + +#import + +extern NSString *const kFLEXMultilineTableViewCellIdentifier; + +@interface FLEXMultilineTableViewCell : UITableViewCell + ++ (CGFloat)preferredHeightWithAttributedText:(NSAttributedString *)attributedText inTableViewWidth:(CGFloat)tableViewWidth style:(UITableViewStyle)style showsAccessory:(BOOL)showsAccessory; + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXMultilineTableViewCell.m b/Pods/FLEX/Classes/Utility/FLEXMultilineTableViewCell.m new file mode 100644 index 0000000000..de9b647ae6 --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXMultilineTableViewCell.m @@ -0,0 +1,55 @@ +// +// FLEXMultilineTableViewCell.m +// UICatalog +// +// Created by Ryan Olson on 2/13/15. +// Copyright (c) 2015 f. All rights reserved. +// + +#import "FLEXMultilineTableViewCell.h" + +NSString *const kFLEXMultilineTableViewCellIdentifier = @"kFLEXMultilineTableViewCellIdentifier"; + +@implementation FLEXMultilineTableViewCell + +- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier +{ + self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; + if (self) { + self.textLabel.numberOfLines = 0; + } + return self; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + self.textLabel.frame = UIEdgeInsetsInsetRect(self.contentView.bounds, [[self class] labelInsets]); +} + ++ (UIEdgeInsets)labelInsets +{ + return UIEdgeInsetsMake(10.0, 15.0, 10.0, 15.0); +} + ++ (CGFloat)preferredHeightWithAttributedText:(NSAttributedString *)attributedText inTableViewWidth:(CGFloat)tableViewWidth style:(UITableViewStyle)style showsAccessory:(BOOL)showsAccessory +{ + CGFloat labelWidth = tableViewWidth; + + // Content view inset due to accessory view observed on iOS 8.1 iPhone 6. + if (showsAccessory) { + labelWidth -= 34.0; + } + + UIEdgeInsets labelInsets = [self labelInsets]; + labelWidth -= (labelInsets.left + labelInsets.right); + + CGSize constrainSize = CGSizeMake(labelWidth, CGFLOAT_MAX); + CGFloat preferredLabelHeight = ceil([attributedText boundingRectWithSize:constrainSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height); + CGFloat preferredCellHeight = preferredLabelHeight + labelInsets.top + labelInsets.bottom + 1.0; + + return preferredCellHeight; +} + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXResources.h b/Pods/FLEX/Classes/Utility/FLEXResources.h new file mode 100644 index 0000000000..58f7dc305b --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXResources.h @@ -0,0 +1,33 @@ +// +// FLEXResources.h +// FLEX +// +// Created by Ryan Olson on 6/8/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import +#import + +@interface FLEXResources : NSObject + ++ (UIImage *)closeIcon; ++ (UIImage *)dragHandle; ++ (UIImage *)globeIcon; ++ (UIImage *)hierarchyIndentPattern; ++ (UIImage *)listIcon; ++ (UIImage *)moveIcon; ++ (UIImage *)selectIcon; + ++ (UIImage *)jsonIcon; ++ (UIImage *)textPlainIcon; ++ (UIImage *)htmlIcon; ++ (UIImage *)audioIcon; ++ (UIImage *)jsIcon; ++ (UIImage *)plistIcon; ++ (UIImage *)textIcon; ++ (UIImage *)videoIcon; ++ (UIImage *)xmlIcon; ++ (UIImage *)binaryIcon; + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXResources.m b/Pods/FLEX/Classes/Utility/FLEXResources.m new file mode 100644 index 0000000000..7916d581a7 --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXResources.m @@ -0,0 +1,167 @@ +// +// FLEXResources.m +// FLEX +// +// Created by Ryan Olson on 6/8/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXResources.h" + +static const u_int8_t FLEXCloseIcon[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x0f, 0x08, 0x06, 0x00, 0x00, 0x00, 0x3b, 0xd6, 0x95, 0x4a, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0xf4, 0x69, 0xff, 0xfb, 0xdd, 0xe7, 0x39, 0xe7, 0xbe, 0x79, 0xbf, 0xef, 0x7c, 0xf7, 0xfd, 0xbe, 0x7b, 0xee, 0xc9, 0x39, 0x00, 0x9a, 0xb6, 0x02, 0xb9, 0x3c, 0x17, 0xd7, 0x02, 0xc8, 0x93, 0x15, 0x2a, 0xe2, 0x23, 0x82, 0xf9, 0x13, 0x52, 0xd3, 0xf8, 0x8c, 0x07, 0x80, 0x83, 0x01, 0x70, 0xc0, 0x0d, 0x48, 0x81, 0xb0, 0x40, 0x1e, 0x14, 0x17, 0x17, 0x03, 0xff, 0x79, 0xbd, 0xbd, 0x09, 0x18, 0x65, 0xbc, 0xe6, 0x48, 0xc5, 0xfa, 0x4f, 0xb7, 0x7f, 0x37, 0x68, 0x8b, 0xc4, 0x05, 0x42, 0x00, 0x2c, 0x0e, 0x99, 0x33, 0x44, 0x05, 0xc2, 0x3c, 0x84, 0x0f, 0x01, 0x90, 0x1c, 0xa1, 0x5c, 0x51, 0x08, 0x40, 0x6b, 0x46, 0xbc, 0xc5, 0xb4, 0x42, 0x39, 0x85, 0x3b, 0x10, 0xd6, 0x55, 0x20, 0x81, 0x08, 0x7f, 0xa2, 0x70, 0x96, 0x0a, 0xd3, 0x91, 0x7a, 0xd0, 0xcd, 0xe8, 0xc7, 0x96, 0x2a, 0x9f, 0xc4, 0xf8, 0x10, 0x00, 0xba, 0x17, 0x80, 0x1a, 0x4b, 0x20, 0x50, 0x64, 0x01, 0x70, 0x42, 0x11, 0xcf, 0x2f, 0x12, 0x66, 0xa1, 0x38, 0x1c, 0x11, 0xc2, 0x4e, 0x32, 0x91, 0x54, 0x86, 0xf0, 0x2a, 0x84, 0xfd, 0x85, 0x12, 0x01, 0xe2, 0x38, 0xd7, 0x11, 0x1e, 0x91, 0x97, 0x37, 0x15, 0x61, 0x4d, 0x04, 0xc1, 0x36, 0xe3, 0x6f, 0x71, 0xb2, 0xfe, 0x86, 0x05, 0x82, 0x8c, 0xa1, 0x98, 0x02, 0x41, 0xd6, 0x10, 0xee, 0xcf, 0x85, 0x1a, 0x0a, 0x6a, 0xa1, 0xd2, 0x02, 0x79, 0xae, 0x60, 0x86, 0xea, 0xc7, 0xff, 0xb3, 0xcb, 0xcb, 0x55, 0xa2, 0x7a, 0xa9, 0x2e, 0x33, 0xd4, 0xb3, 0x24, 0x8a, 0xc8, 0x78, 0x74, 0xd7, 0x45, 0x75, 0xdb, 0x90, 0x33, 0x35, 0x9a, 0xc2, 0x2c, 0x84, 0xf7, 0xcb, 0x32, 0xc6, 0xc5, 0x22, 0xac, 0x83, 0xf0, 0x51, 0x29, 0x95, 0x71, 0x3f, 0x6e, 0x91, 0x28, 0x23, 0x93, 0x10, 0xa6, 0xfc, 0xdb, 0x84, 0x05, 0x21, 0xa8, 0x96, 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 0x54, 0x24, 0x52, 0x3c, 0xaa, 0x1b, 0x71, 0x33, 0x5b, 0x30, 0x86, 0x9a, 0xaf, 0x48, 0x33, 0xf1, 0x4c, 0x5e, 0x18, 0x47, 0xd5, 0x84, 0xd2, 0xf3, 0x1e, 0x62, 0x20, 0x04, 0x42, 0x81, 0x0f, 0x4a, 0xd4, 0x32, 0x60, 0x2a, 0x64, 0x83, 0xb4, 0xa5, 0xab, 0xae, 0x0b, 0xfd, 0xea, 0xb7, 0x84, 0x83, 0x00, 0x14, 0x90, 0x05, 0x62, 0x70, 0x1c, 0x60, 0x06, 0x47, 0xa4, 0xa8, 0x2c, 0x32, 0xd4, 0x27, 0x40, 0x31, 0xfc, 0x09, 0x32, 0xe4, 0x53, 0x30, 0x34, 0x2e, 0x58, 0x65, 0x15, 0x43, 0x11, 0xe2, 0x3f, 0x0f, 0xb1, 0xfd, 0x63, 0x1d, 0x21, 0x53, 0x65, 0x2d, 0x52, 0x8d, 0xc8, 0x81, 0x27, 0xe8, 0x09, 0x79, 0xa4, 0x21, 0xe9, 0x4f, 0xfa, 0x92, 0x31, 0xa8, 0x0f, 0x44, 0xcd, 0x85, 0xf4, 0x22, 0xbd, 0x07, 0xc7, 0xf1, 0x35, 0x07, 0x75, 0xd2, 0xc3, 0xe8, 0xa1, 0xf4, 0x48, 0x7a, 0x38, 0xdd, 0x6e, 0x90, 0x01, 0x21, 0x52, 0x9d, 0x8b, 0x9a, 0x02, 0xa4, 0xff, 0xc2, 0x45, 0x23, 0x9b, 0x18, 0x65, 0xa7, 0x40, 0xbd, 0x6c, 0x30, 0x87, 0xaf, 0xf1, 0x68, 0x4f, 0x68, 0xad, 0xb4, 0x47, 0xb4, 0x1b, 0xb4, 0x36, 0xda, 0x1d, 0x48, 0x86, 0x3f, 0x54, 0x51, 0x06, 0x32, 0x9d, 0x22, 0x5d, 0xa0, 0x18, 0x54, 0x30, 0x14, 0x79, 0x2c, 0xb4, 0xa1, 0x68, 0xfd, 0x55, 0x11,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0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9c, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78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x5e, 0x56, 0xaa, 0x89, 0x96, 0x40, 0x24, 0xd2, 0x87, 0x83, 0x3c, 0xe9, 0x5b, 0x31, 0x0a, 0x38, 0xe2, 0xcc, 0x61, 0xab, 0x61, 0x2d, 0xf1, 0x9e, 0x30, 0xc3, 0x73, 0x38, 0x81, 0x49, 0x95, 0xa5, 0x2b, 0x15, 0xba, 0xbf, 0x42, 0x25, 0xcf, 0xac, 0x7e, 0x18, 0x61, 0x83, 0xd5, 0x38, 0x91, 0x33, 0xf9, 0x6e, 0x38, 0xeb, 0x3f, 0x4d, 0x76, 0xc4, 0xe8, 0xc0, 0x5a, 0x77, 0x44, 0x1a, 0x17, 0x5f, 0xbb, 0x45, 0x24, 0x4f, 0x74, 0xeb, 0xfc, 0x94, 0x7a, 0x2f, 0x56, 0x67, 0xcd, 0x09, 0xe4, 0x1f, 0xf6, 0xf7, 0xdf, 0x1e, 0xca, 0xd4, 0xbd, 0xd6, 0xb3, 0x30, 0x96, 0xb3, 0x16, 0x1b, 0x77, 0x65, 0x37, 0xc2, 0x4e, 0x38, 0xbd, 0x01, 0xa7, 0x78, 0x6a, 0x4b, 0x16, 0xe1, 0xee, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXCloseIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x1e, 0x08, 0x06, 0x00, 0x00, 0x00, 0x3b, 0x30, 0xae, 0xa2, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0xf4, 0x69, 0xff, 0xfb, 0xdd, 0xe7, 0x39, 0xe7, 0xbe, 0x79, 0xbf, 0xef, 0x7c, 0xf7, 0xfd, 0xbe, 0x7b, 0xee, 0xc9, 0x39, 0x00, 0x9a, 0xb6, 0x02, 0xb9, 0x3c, 0x17, 0xd7, 0x02, 0xc8, 0x93, 0x15, 0x2a, 0xe2, 0x23, 0x82, 0xf9, 0x13, 0x52, 0xd3, 0xf8, 0x8c, 0x07, 0x80, 0x83, 0x01, 0x70, 0xc0, 0x0d, 0x48, 0x81, 0xb0, 0x40, 0x1e, 0x14, 0x17, 0x17, 0x03, 0xff, 0x79, 0xbd, 0xbd, 0x09, 0x18, 0x65, 0xbc, 0xe6, 0x48, 0xc5, 0xfa, 0x4f, 0xb7, 0x7f, 0x37, 0x68, 0x8b, 0xc4, 0x05, 0x42, 0x00, 0x2c, 0x0e, 0x99, 0x33, 0x44, 0x05, 0xc2, 0x3c, 0x84, 0x0f, 0x01, 0x90, 0x1c, 0xa1, 0x5c, 0x51, 0x08, 0x40, 0x6b, 0x46, 0xbc, 0xc5, 0xb4, 0x42, 0x39, 0x85, 0x3b, 0x10, 0xd6, 0x55, 0x20, 0x81, 0x08, 0x7f, 0xa2, 0x70, 0x96, 0x0a, 0xd3, 0x91, 0x7a, 0xd0, 0xcd, 0xe8, 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0xf8, 0x2c, 0x89, 0x38, 0x6a, 0x10, 0x97, 0x8b, 0x0b, 0xc2, 0x12, 0x10, 0x8f, 0x34, 0xe0, 0xd9, 0x99, 0xd2, 0xf0, 0x28, 0x84, 0xd1, 0xbb, 0xc2, 0x77, 0x16, 0x4b, 0x12, 0x53, 0x10, 0x46, 0x3a, 0xf1, 0xfa, 0x22, 0x69, 0xf2, 0x38, 0x84, 0x39, 0x08, 0x37, 0x17, 0xe4, 0x24, 0x50, 0x1a, 0xa8, 0x38, 0x57, 0x8b, 0x25, 0x21, 0x14, 0xaf, 0xf2, 0x51, 0x28, 0xe3, 0x29, 0xcd, 0x96, 0x88, 0xef, 0xc8, 0x54, 0x84, 0x53, 0x39, 0x22, 0x1f, 0x82, 0x95, 0x57, 0x80, 0x90, 0x2a, 0x3e, 0x61, 0x2e, 0x14, 0xa8, 0x9e, 0xa5, 0x8f, 0x78, 0xb7, 0x42, 0x49, 0x62, 0x24, 0xe2, 0xd1, 0x58, 0x22, 0x46, 0x24, 0x0e, 0x0d, 0x43, 0x18, 0x3d, 0x97, 0x98, 0x20, 0x96, 0x25, 0x0d, 0xe8, 0x21, 0x24, 0xf2, 0xc2, 0x60, 0x2a, 0x0e, 0xe5, 0x5f, 0x2c, 0xcf, 0x55, 0xcd, 0x6f, 0xa4, 0x93, 0x28, 0x17, 0xe7, 0x46, 0x50, 0xbc, 0x39, 0xc2, 0xdb, 0x0a, 0x8a, 0x12, 0x06, 0xc7, 0x9e, 0x29, 0x54, 0x24, 0x52, 0x3c, 0xaa, 0x1b, 0x71, 0x33, 0x5b, 0x30, 0x86, 0x9a, 0xaf, 0x48, 0x33, 0xf1, 0x4c, 0x5e, 0x18, 0x47, 0xd5, 0x84, 0xd2, 0xf3, 0x1e, 0x62, 0x20, 0x04, 0x42, 0x81, 0x0f, 0x4a, 0xd4, 0x32, 0x60, 0x2a, 0x64, 0x83, 0xb4, 0xa5, 0xab, 0xae, 0x0b, 0xfd, 0xea, 0xb7, 0x84,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, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9c, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x39, 0x30, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20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xd3, 0xdd, 0x35, 0x8f, 0x90, 0xc7, 0xb7, 0x0b, 0xd3, 0x2f, 0x2d, 0x82, 0x9f, 0x12, 0x04, 0x6b, 0x9b, 0x50, 0xcf, 0xad, 0x4d, 0x79, 0xe1, 0x5b, 0xe0, 0x1a, 0xd4, 0xae, 0x29, 0xa8, 0x64, 0xc0, 0xc2, 0x43, 0x50, 0x16, 0xbe, 0x05, 0xda, 0xc2, 0x57, 0xe7, 0x89, 0x6d, 0x86, 0x0f, 0x76, 0x69, 0xf9, 0x3c, 0x96, 0x1e, 0x37, 0x3a, 0x78, 0xcf, 0x79, 0xcb, 0x56, 0x7b, 0xa1, 0xd2, 0xd5, 0x21, 0x38, 0x0b, 0x0d, 0xc1, 0x2d, 0xd0, 0xed, 0x3f, 0x20, 0x16, 0xa8, 0x6c, 0xa5, 0xc7, 0x77, 0xda, 0xa6, 0x8c, 0x10, 0x13, 0x73, 0x49, 0x22, 0x22, 0x40, 0xc7, 0xd2, 0x81, 0x4d, 0xea, 0x6e, 0x0d, 0x5c, 0x43, 0x70, 0x66, 0xd2, 0x8d, 0xbd, 0x51, 0xce, 0xb4, 0xe1, 0x74, 0xa7, 0x56, 0x78, 0xbd, 0xfa, 0x1c, 0x9b, 0xa0, 0x92, 0x89, 0x05, 0x0e, 0xe6, 0xf0, 0x5e, 0x8d, 0xca, 0xad, 0x95, 0x0a, 0x54, 0xc6, 0x15, 0x3c, 0xc3, 0x11, 0x1f, 0x91, 0xed, 0x15, 0x98, 0x1e, 0x67, 0xf0, 0x0a, 0x3e, 0x3a, 0x60, 0xb6, 0x52, 0x2b, 0x1c, 0xcc, 0x7b, 0xfe, 0xb4, 0xfd, 0x00, 0xb3, 0x4a, 0x9f, 0x54, 0x63, 0x5e, 0xe3, 0x04, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXDragHandle[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x26, 0x08, 0x06, 0x00, 0x00, 0x00, 0xfd, 0x5c, 0x0a, 0xf0, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0xf4, 0x69, 0xff, 0xfb, 0xdd, 0xe7, 0x39, 0xe7, 0xbe, 0x79, 0xbf, 0xef, 0x7c, 0xf7, 0xfd, 0xbe, 0x7b, 0xee, 0xc9, 0x39, 0x00, 0x9a, 0xb6, 0x02, 0xb9, 0x3c, 0x17, 0xd7, 0x02, 0xc8, 0x93, 0x15, 0x2a, 0xe2, 0x23, 0x82, 0xf9, 0x13, 0x52, 0xd3, 0xf8, 0x8c, 0x07, 0x80, 0x83, 0x01, 0x70, 0xc0, 0x0d, 0x48, 0x81, 0xb0, 0x40, 0x1e, 0x14, 0x17, 0x17, 0x03, 0xff, 0x79, 0xbd, 0xbd, 0x09, 0x18, 0x65, 0xbc, 0xe6, 0x48, 0xc5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, 0xe0, 0xb3, 0xa2, 0xaf, 0xaf, 0x77, 0x63, 0x5f, 0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9e, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x38, 0x32, 0x38, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x36, 0x36, 0x38, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0x8a, 0x6f, 0x99, 0x54, 0x00, 0x00, 0x00, 0x4b, 0x49, 0x44, 0x41, 0x54, 0x38, 0x11, 0x63, 0x60, 0x60, 0x60, 0xd8, 0x0a, 0xc4, 0xff, 0x09, 0xe0, 0xad, 0x4c, 0x40, 0x05, 0xc4, 0x00, 0x90, 0x41, 0x34, 0x00, 0xa3, 0x6e, 0xa4, 0x4e, 0xa0, 0x8e, 0x86, 0xe3, 0x68, 0x38, 0x22, 0xe7, 0xf5, 0x81, 0xce, 0xd7, 0x9b, 0x80, 0xd1, 0xf1, 0x97, 0x00, 0xde, 0xc4, 0x02, 0x54, 0xc0, 0x0a, 0xc4, 0x84, 0xca, 0x20, 0x56, 0x46, 0xa0, 0x22, 0x10, 0x20, 0xa4, 0xf0, 0x1f, 0x44, 0x19, 0x91, 0xe4, 0xc8, 0x73, 0x23, 0x00, 0x28, 0x34, 0x66, 0xcc, 0x96, 0x10, 0xe2, 0x94, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXDragHandle2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x4c, 0x08, 0x06, 0x00, 0x00, 0x00, 0x6d, 0x54, 0x97, 0x97, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0xf4, 0x69, 0xff, 0xfb, 0xdd, 0xe7, 0x39, 0xe7, 0xbe, 0x79, 0xbf, 0xef, 0x7c, 0xf7, 0xfd, 0xbe, 0x7b, 0xee, 0xc9, 0x39, 0x00, 0x9a, 0xb6, 0x02, 0xb9, 0x3c, 0x17, 0xd7, 0x02, 0xc8, 0x93, 0x15, 0x2a, 0xe2, 0x23, 0x82, 0xf9, 0x13, 0x52, 0xd3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x45, 0x75, 0xdb, 0x90, 0x33, 0x35, 0x9a, 0xc2, 0x2c, 0x84, 0xf7, 0xcb, 0x32, 0xc6, 0xc5, 0x22, 0xac, 0x83, 0xf0, 0x51, 0x29, 0x95, 0x71, 0x3f, 0x6e, 0x91, 0x28, 0x23, 0x93, 0x10, 0xa6, 0xfc, 0xdb, 0x84, 0x05, 0x21, 0xa8, 0x96, 0xc0, 0x43, 0xf8, 0x8d, 0x48, 0x10, 0x1a, 0x8d, 0xb0, 0x11, 0x00, 0xce, 0x54, 0xe6, 0x24, 0x05, 0x0d, 0x60, 0x6b, 0x81, 0x02, 0x21, 0x95, 0x3f, 0x1e, 0x2c, 0x2d, 0x8c, 0x4a, 0x1c, 0xc0, 0xc9, 0x8a, 0xa9, 0xf1, 0x03, 0xf1, 0xf1, 0x6c, 0x59, 0xee, 0x38, 0x6a, 0x7e, 0xa0, 0x38, 0xf8, 0x2c, 0x89, 0x38, 0x6a, 0x10, 0x97, 0x8b, 0x0b, 0xc2, 0x12, 0x10, 0x8f, 0x34, 0xe0, 0xd9, 0x99, 0xd2, 0xf0, 0x28, 0x84, 0xd1, 0xbb, 0xc2, 0x77, 0x16, 0x4b, 0x12, 0x53, 0x10, 0x46, 0x3a, 0xf1, 0xfa, 0x22, 0x69, 0xf2, 0x38, 0x84, 0x39, 0x08, 0x37, 0x17, 0xe4, 0x24, 0x50, 0x1a, 0xa8, 0x38, 0x57, 0x8b, 0x25, 0x21, 0x14, 0xaf, 0xf2, 0x51, 0x28, 0xe3, 0x29, 0xcd, 0x96, 0x88, 0xef, 0xc8, 0x54, 0x84, 0x53, 0x39, 0x22, 0x1f, 0x82, 0x95, 0x57, 0x80, 0x90, 0x2a, 0x3e, 0x61, 0x2e, 0x14, 0xa8, 0x9e, 0xa5, 0x8f, 0x78, 0xb7, 0x42, 0x49, 0x62, 0x24, 0xe2, 0xd1, 0x58, 0x22, 0x46, 0x24, 0x0e, 0x0d, 0x43, 0x18, 0x3d, 0x97, 0x98, 0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 0x27, 0x06, 0x02, 0xee, 0xea, 0x3a, 0xd4, 0x10, 0x43, 0x5d, 0x05, 0x99, 0xae, 0x2e, 0x2a, 0x80, 0xb1, 0x14, 0x68, 0x6b, 0xf2, 0xbe, 0xaf, 0xef, 0xb5, 0x31, 0x00, 0xa3, 0x01, 0xe0, 0xb3, 0xa2, 0xaf, 0xaf, 0x77, 0x63, 0x5f, 0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9e, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x38, 0x32, 0x38, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x36, 0x36, 0x38, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0x8a, 0x6f, 0x99, 0x54, 0x00, 0x00, 0x00, 0x7c, 0x49, 0x44, 0x41, 0x54, 0x58, 0x09, 0xed, 0xd5, 0xc1, 0x09, 0xc0, 0x30, 0x0c, 0x43, 0x51, 0xd3, 0xed, 0xba, 0xff, 0x08, 0x19, 0xa4, 0x8d, 0x0f, 0xe9, 0x5d, 0x8d, 0x74, 0xca, 0x0f, 0xf8, 0x68, 0x61, 0x93, 0x07, 0xae, 0xaa, 0xba, 0x67, 0x8d, 0x59, 0xcf, 0x66, 0x75, 0x46, 0x67, 0x59, 0xc2, 0xd6, 0x30, 0xe3, 0xea, 0x44, 0xf7, 0xb3, 0xaf, 0xec, 0x1e, 0xf0, 0xc4, 0x3c, 0xfb, 0xa7, 0x38, 0x50, 0xe3, 0xf0, 0x38, 0x8a, 0x38, 0xfc, 0x7d, 0x0a, 0xbe, 0x13, 0x70, 0x1c, 0x9a, 0xc0, 0xc2, 0x38, 0xc4, 0x61, 0x80, 0x95, 0x1c, 0x89, 0x43, 0x1c, 0xca, 0x68, 0x02, 0x0d, 0x38, 0xc4, 0x61, 0x80, 0x95, 0x1c, 0x89, 0x43, 0x1c, 0xca, 0x68, 0x02, 0x0d, 0x38, 0xc4, 0x61, 0x80, 0x95, 0x1c, 0x89, 0x43, 0x1c, 0xca, 0x68, 0x02, 0x0d, 0x38, 0xdc, 0x73, 0xf8, 0x02, 0x86, 0x61, 0x32, 0xdb, 0x80, 0xa1, 0x94, 0xde, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXGlobeIcon[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x12, 0x08, 0x06, 0x00, 0x00, 0x00, 0x56, 0xce, 0x8e, 0x57, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08,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0x16, 0x4b, 0x12, 0x53, 0x10, 0x46, 0x3a, 0xf1, 0xfa, 0x22, 0x69, 0xf2, 0x38, 0x84, 0x39, 0x08, 0x37, 0x17, 0xe4, 0x24, 0x50, 0x1a, 0xa8, 0x38, 0x57, 0x8b, 0x25, 0x21, 0x14, 0xaf, 0xf2, 0x51, 0x28, 0xe3, 0x29, 0xcd, 0x96, 0x88, 0xef, 0xc8, 0x54, 0x84, 0x53, 0x39, 0x22, 0x1f, 0x82, 0x95, 0x57, 0x80, 0x90, 0x2a, 0x3e, 0x61, 0x2e, 0x14, 0xa8, 0x9e, 0xa5, 0x8f, 0x78, 0xb7, 0x42, 0x49, 0x62, 0x24, 0xe2, 0xd1, 0x58, 0x22, 0x46, 0x24, 0x0e, 0x0d, 0x43, 0x18, 0x3d, 0x97, 0x98, 0x20, 0x96, 0x25, 0x0d, 0xe8, 0x21, 0x24, 0xf2, 0xc2, 0x60, 0x2a, 0x0e, 0xe5, 0x5f, 0x2c, 0xcf, 0x55, 0xcd, 0x6f, 0xa4, 0x93, 0x28, 0x17, 0xe7, 0x46, 0x50, 0xbc, 0x39, 0xc2, 0xdb, 0x0a, 0x8a, 0x12, 0x06, 0xc7, 0x9e, 0x29, 0x54, 0x24, 0x52, 0x3c, 0xaa, 0x1b, 0x71, 0x33, 0x5b, 0x30, 0x86, 0x9a, 0xaf, 0x48, 0x33, 0xf1, 0x4c, 0x5e, 0x18, 0x47, 0xd5, 0x84, 0xd2, 0xf3, 0x1e, 0x62, 0x20, 0x04, 0x42, 0x81, 0x0f, 0x4a, 0xd4, 0x32, 0x60, 0x2a, 0x64, 0x83, 0xb4, 0xa5, 0xab, 0xae, 0x0b, 0xfd, 0xea, 0xb7, 0x84, 0x83, 0x00, 0x14, 0x90, 0x05, 0x62, 0x70, 0x1c, 0x60, 0x06, 0x47, 0xa4, 0xa8, 0x2c, 0x32, 0xd4, 0x27, 0x40, 0x31, 0xfc, 0x09, 0x32, 0xe4, 0x53, 0x30, 0x34, 0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63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x39, 0x30, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c,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x25, 0x5b, 0xe2, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXGlobeIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x24, 0x08, 0x06, 0x00, 0x00, 0x00, 0xe1, 0x00, 0x98, 0x98, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0xf4, 0x69, 0xff, 0xfb, 0xdd, 0xe7, 0x39, 0xe7, 0xbe, 0x79, 0xbf, 0xef, 0x7c, 0xf7, 0xfd, 0xbe, 0x7b, 0xee, 0xc9, 0x39, 0x00, 0x9a, 0xb6, 0x02, 0xb9, 0x3c, 0x17, 0xd7, 0x02, 0xc8, 0x93, 0x15, 0x2a, 0xe2, 0x23, 0x82, 0xf9, 0x13, 0x52, 0xd3, 0xf8, 0x8c, 0x07, 0x80, 0x83, 0x01, 0x70, 0xc0, 0x0d, 0x48, 0x81, 0xb0, 0x40, 0x1e, 0x14, 0x17, 0x17, 0x03, 0xff, 0x79, 0xbd, 0xbd, 0x09, 0x18, 0x65, 0xbc, 0xe6, 0x48, 0xc5, 0xfa, 0x4f, 0xb7, 0x7f, 0x37, 0x68, 0x8b, 0xc4, 0x05, 0x42, 0x00, 0x2c, 0x0e, 0x99, 0x33, 0x44, 0x05, 0xc2, 0x3c, 0x84, 0x0f, 0x01, 0x90, 0x1c, 0xa1, 0x5c, 0x51, 0x08, 0x40, 0x6b, 0x46, 0xbc, 0xc5, 0xb4, 0x42, 0x39, 0x85, 0x3b, 0x10, 0xd6, 0x55, 0x20, 0x81, 0x08, 0x7f, 0xa2, 0x70, 0x96, 0x0a, 0xd3, 0x91, 0x7a, 0xd0, 0xcd, 0xe8, 0xc7, 0x96, 0x2a, 0x9f, 0xc4, 0xf8, 0x10, 0x00, 0xba, 0x17, 0x80, 0x1a, 0x4b, 0x20, 0x50, 0x64, 0x01, 0x70, 0x42, 0x11, 0xcf, 0x2f, 0x12, 0x66, 0xa1, 0x38, 0x1c, 0x11, 0xc2, 0x4e, 0x32, 0x91, 0x54, 0x86, 0xf0, 0x2a, 0x84, 0xfd, 0x85, 0x12, 0x01, 0xe2, 0x38, 0xd7, 0x11, 0x1e, 0x91, 0x97, 0x37, 0x15, 0x61, 0x4d, 0x04, 0xc1, 0x36, 0xe3, 0x6f, 0x71, 0xb2, 0xfe, 0x86, 0x05, 0x82, 0x8c, 0xa1, 0x98, 0x02, 0x41, 0xd6, 0x10, 0xee, 0xcf, 0x85, 0x1a, 0x0a, 0x6a, 0xa1, 0xd2, 0x02, 0x79, 0xae, 0x60, 0x86, 0xea, 0xc7, 0xff, 0xb3, 0xcb, 0xcb, 0x55, 0xa2, 0x7a, 0xa9, 0x2e, 0x33, 0xd4, 0xb3, 0x24, 0x8a, 0xc8, 0x78, 0x74, 0xd7, 0x45, 0x75, 0xdb, 0x90, 0x33, 0x35, 0x9a, 0xc2, 0x2c, 0x84, 0xf7, 0xcb, 0x32, 0xc6, 0xc5, 0x22, 0xac, 0x83, 0xf0, 0x51, 0x29, 0x95, 0x71, 0x3f, 0x6e, 0x91, 0x28, 0x23, 0x93, 0x10, 0xa6, 0xfc, 0xdb, 0x84, 0x05, 0x21, 0xa8, 0x96, 0xc0, 0x43, 0xf8, 0x8d, 0x48, 0x10, 0x1a, 0x8d, 0xb0, 0x11, 0x00, 0xce, 0x54, 0xe6, 0x24, 0x05, 0x0d, 0x60, 0x6b, 0x81, 0x02, 0x21, 0x95, 0x3f, 0x1e, 0x2c, 0x2d, 0x8c, 0x4a, 0x1c, 0xc0, 0xc9, 0x8a, 0xa9, 0xf1, 0x03, 0xf1, 0xf1, 0x6c, 0x59, 0xee, 0x38, 0x6a, 0x7e, 0xa0, 0x38, 0xf8, 0x2c, 0x89, 0x38, 0x6a, 0x10, 0x97, 0x8b, 0x0b, 0xc2, 0x12, 0x10, 0x8f, 0x34, 0xe0, 0xd9, 0x99, 0xd2, 0xf0, 0x28, 0x84, 0xd1, 0xbb, 0xc2, 0x77, 0x16, 0x4b, 0x12, 0x53, 0x10, 0x46, 0x3a, 0xf1, 0xfa, 0x22, 0x69, 0xf2, 0x38, 0x84, 0x39, 0x08, 0x37, 0x17, 0xe4, 0x24, 0x50, 0x1a, 0xa8, 0x38, 0x57, 0x8b, 0x25, 0x21, 0x14, 0xaf, 0xf2, 0x51, 0x28, 0xe3, 0x29, 0xcd, 0x96, 0x88, 0xef, 0xc8, 0x54, 0x84, 0x53, 0x39, 0x22, 0x1f, 0x82, 0x95, 0x57, 0x80, 0x90, 0x2a, 0x3e, 0x61, 0x2e, 0x14, 0xa8, 0x9e, 0xa5, 0x8f, 0x78, 0xb7, 0x42, 0x49, 0x62, 0x24, 0xe2, 0xd1, 0x58, 0x22, 0x46, 0x24, 0x0e, 0x0d, 0x43, 0x18, 0x3d, 0x97, 0x98, 0x20, 0x96, 0x25, 0x0d, 0xe8, 0x21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a, 0xd4, 0x10, 0x43, 0x5d, 0x05, 0x99, 0xae, 0x2e, 0x2a, 0x80, 0xb1, 0x14, 0x68, 0x6b, 0xf2, 0xbe, 0xaf, 0xef, 0xb5, 0x31, 0x00, 0xa3, 0x01, 0xe0, 0xb3, 0xa2, 0xaf, 0xaf, 0x77, 0x63, 0x5f, 0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9c, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x39, 0x30, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xc1, 0xe2, 0xd2, 0xc6, 0x00, 0x00, 0x03, 0x7e, 0x49, 0x44, 0x41, 0x54, 0x58, 0x09, 0xcd, 0x98, 0x3d, 0x6b, 0x54, 0x51, 0x10, 0x86, 0x8d, 0xb1, 0xf3, 0x83, 0xac, 0x60, 0x61, 0x20, 0x58, 0x88, 0x1f, 0xa8, 0x9d, 0x85, 0x85, 0x58, 0x2e, 0x04, 0x4c, 0x61, 0x6a, 0x05, 0x7f, 0x84, 0x56, 0x0a, 0xd9, 0x3f, 0xa0, 0x90, 0xfc, 0x80, 0xfc, 0x00, 0x3b, 0x85, 0xa4, 0x31, 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, 0x90, 0x21, 0x21, 0x5e, 0x29, 0xae, 0xca, 0xaa, 0x30, 0x25, 0x34, 0x05, 0xd6, 0xf1, 0x78, 0x60, 0x0d, 0x2c, 0xc4, 0x58, 0x37, 0x05, 0x38, 0x70, 0x9d, 0x83, 0xa6, 0x36, 0x3d, 0xba, 0x12, 0x6e, 0x5f, 0x7c, 0xa6, 0x5c, 0xd0, 0xf7, 0x9f, 0x2d, 0x3b, 0x21, 0xec, 0xca, 0x3f, 0x1b, 0xe2, 0xe4, 0xec, 0xbe, 0x5e, 0x1c, 0x09, 0xd4, 0xa0, 0x56, 0xcf, 0x84, 0x83, 0x6b, 0x5e, 0x58, 0x13, 0x7c, 0xb5, 0x3a, 0x69, 0x72, 0xe1, 0x6c, 0x3b, 0xf4, 0xe4, 0x2b, 0x15, 0x1f, 0xdb, 0xa5, 0xc1, 0x36, 0xce, 0x9a, 0xfc, 0x7c, 0xa9, 0xd4, 0x05, 0xde, 0x65, 0xca, 0xfe, 0xa5, 0xf7, 0x46, 0xfe, 0x39, 0x61, 0x46, 0xd8, 0xfa, 0x39, 0x90, 0xdd, 0x51, 0xfe, 0x02, 0x89, 0x7c, 0xcc, 0xd6, 0x15, 0x10, 0x0a, 0x4d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXHierarchyIndentPattern[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0xf9, 0x3c, 0x0f, 0xcd, 0x00, 0x00, 0x0a, 0x41, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0x9d, 0x96, 0x77, 0x54, 0x53, 0xd9, 0x16, 0x87, 0xcf, 0xbd, 0x37, 0xbd, 0xd0, 0x12, 0x22, 0x20, 0x25, 0xf4, 0x1a, 0x7a, 0x09, 0x20, 0xd2, 0x3b, 0x48, 0x15, 0x04, 0x51, 0x89, 0x49, 0x80, 0x50, 0x02, 0x86, 0x84, 0x26, 0x76, 0x44, 0x05, 0x46, 0x14, 0x11, 0x29, 0x56, 0x64, 0x54, 0xc0, 0x01, 0x47, 0x87, 0x22, 0x63, 0x45, 0x14, 0x0b, 0x83, 0x82, 0x62, 0xd7, 0x09, 0xf2, 0x10, 0x50, 0xc6, 0xc1, 0x51, 0x44, 0x45, 0xe5, 0xdd, 0x8c, 0x6b, 0x09, 0xef, 0xad, 0x35, 0xf3, 0xde, 0x9a, 0xfd, 0xc7, 0x59, 0xdf, 0xd9, 0xe7, 0xb7, 0xd7, 0xd9, 0x67, 0xef, 0x7d, 0xd7, 0xba, 0x00, 0x50, 0xfc, 0x82, 0x04, 0xc2, 0x74, 0x58, 0x01, 0x80, 0x34, 0xa1, 0x58, 0x14, 0xee, 0xeb, 0xc1, 0x5c, 0x12, 0x13, 0xcb, 0xc4, 0xf7, 0x02, 0x18, 0x10, 0x01, 0x0e, 0x58, 0x01, 0xc0, 0xe1, 0x66, 0x66, 0x04, 0x47, 0xf8, 0x44, 0x02, 0xd4, 0xfc, 0xbd, 0x3d, 0x99, 0x99, 0xa8, 0x48, 0xc6, 0xb3, 0xf6, 0xee, 0x2e, 0x80, 0x64, 0xbb, 0xdb, 0x2c, 0xbf, 0x50, 0x26, 0x73, 0xd6, 0xff, 0x7f, 0x91, 0x22, 0x37, 0x43, 0x24, 0x06, 0x00, 0x0a, 0x45, 0xd5, 0x36, 0x3c, 0x7e, 0x26, 0x17, 0xe5, 0x02, 0x94, 0x53, 0xb3, 0xc5, 0x19, 0x32, 0xff, 0x04, 0xca, 0xf4, 0x95, 0x29, 0x32, 0x86, 0x31, 0x32, 0x16, 0xa1,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 0x4c, 0x41, 0x22, 0x53, 0xe6, 0xf6, 0x0c, 0x8f, 0x64, 0x72, 0x25, 0xa2, 0x2c, 0x19, 0xa3, 0xdf, 0x84, 0x6c, 0xc1, 0x02, 0x12, 0x90, 0x07, 0x74, 0xa0, 0x0a, 0x34, 0x81, 0x2e, 0x30, 0x02, 0x2c, 0x60, 0x0d, 0x1c, 0x80, 0x33, 0x70, 0x03, 0xde, 0x20, 0x00, 0x84, 0x80, 0x48, 0x10, 0x03, 0x96, 0x03, 0x2e, 0x48, 0x02, 0x69, 0x40, 0x04, 0xb2, 0x41, 0x3e, 0xd8, 0x00, 0x0a, 0x41, 0x31, 0xd8, 0x01, 0x76, 0x83, 0x6a, 0x70, 0x00, 0xd4, 0x81, 0x7a, 0xd0, 0x04, 0x4e, 0x82, 0x36, 0x70, 0x06, 0x5c, 0x04, 0x57, 0xc0, 0x0d, 0x70, 0x0b, 0x0c, 0x80, 0x47, 0x40, 0x0a, 0x86, 0xc1, 0x4b, 0x30, 0x01, 0xde, 0x81, 0x69, 0x08, 0x82, 0xf0, 0x10, 0x15, 0xa2, 0x41, 0xaa, 0x90, 0x16, 0xa4, 0x0f, 0x99, 0x42, 0xd6, 0x10, 0x1b, 0x5a, 0x08, 0x79, 0x43, 0x41, 0x50, 0x38, 0x14, 0x03, 0xc5, 0x43, 0x89, 0x90, 0x10, 0x92, 0x40, 0xf9, 0xd0, 0x26, 0xa8, 0x18, 0x2a, 0x83, 0xaa, 0xa1, 0x43, 0x50, 0x3d, 0xf4, 0x23, 0x74, 0x1a, 0xba, 0x08, 0x5d, 0x83, 0xfa, 0xa0, 0x07, 0xd0, 0x20, 0x34, 0x06, 0xfd, 0x01, 0x7d, 0x84, 0x11, 0x98, 0x02, 0xd3, 0x61, 0x0d, 0xd8, 0x00, 0xb6, 0x80, 0xd9, 0xb0, 0x3b, 0x1c, 0x08, 0x47, 0xc2, 0xcb, 0xe0, 0x44, 0x78, 0x15, 0x9c, 0x07, 0x17, 0xc0, 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0x96, 0x20, 0x24, 0x6c, 0x24, 0x54, 0x10, 0x1a, 0x08, 0xe7, 0x08, 0xfd, 0x84, 0x11, 0xc2, 0x34, 0x51, 0x81, 0xa8, 0x4f, 0x74, 0x22, 0x86, 0x10, 0x79, 0xc4, 0x5c, 0x62, 0x29, 0xb1, 0x8e, 0xd8, 0x41, 0xbc, 0x49, 0x1c, 0x26, 0x4e, 0x93, 0x14, 0x49, 0x86, 0x24, 0x17, 0x52, 0x24, 0x29, 0x99, 0xb4, 0x81, 0x54, 0x49, 0x6a, 0x22, 0x5d, 0x26, 0x3d, 0x26, 0xbd, 0x21, 0x93, 0xc9, 0x3a, 0x64, 0x47, 0x72, 0x18, 0x59, 0x40, 0x5e, 0x4f, 0xae, 0x24, 0x9f, 0x20, 0x5f, 0x25, 0x0f, 0x92, 0x3f, 0x50, 0x94, 0x28, 0x26, 0x14, 0x4f, 0x4a, 0x1c, 0x45, 0x42, 0xd9, 0x4e, 0x39, 0x4a, 0xb9, 0x40, 0x79, 0x40, 0x79, 0x43, 0xa5, 0x52, 0x0d, 0xa8, 0x6e, 0xd4, 0x58, 0xaa, 0x98, 0xba, 0x9d, 0x5a, 0x4f, 0xbd, 0x44, 0x7d, 0x4a, 0x7d, 0x2f, 0x47, 0x93, 0x33, 0x97, 0xf3, 0x97, 0xe3, 0xc9, 0xad, 0x93, 0xab, 0x91, 0x6b, 0x95, 0xeb, 0x97, 0x7b, 0x25, 0x4f, 0x94, 0xd7, 0x97, 0x77, 0x97, 0x5f, 0x2e, 0x9f, 0x27, 0x5f, 0x21, 0x7f, 0x4a, 0xfe, 0xa6, 0xfc, 0xb8, 0x02, 0x51, 0xc1, 0x40, 0xc1, 0x53, 0x81, 0xa3, 0xb0, 0x56, 0xa1, 0x46, 0xe1, 0xb4, 0xc2, 0x3d, 0x85, 0x49, 0x45, 0x9a, 0xa2, 0x95, 0x62, 0x88, 0x62, 0x9a, 0x62, 0x89, 0x62, 0x83, 0xe2, 0x35, 0xc5, 0x51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0x91, 0xe9, 0xec, 0x4f, 0xf8, 0x4f, 0x95, 0x9f, 0x8d, 0x3f, 0x77, 0x7c, 0x09, 0xfc, 0xf2, 0x78, 0x26, 0x6d, 0x66, 0xe6, 0xdf, 0xf7, 0x84, 0xf3, 0xfb, 0x32, 0x3a, 0x59, 0x7e, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x03, 0xa4, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x34, 0x2d, 0x30, 0x35, 0x2d, 0x30, 0x32, 0x54, 0x31, 0x31, 0x3a, 0x30, 0x35, 0x3a, 0x35, 0x35, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xc0, 0x10, 0xf8, 0x70, 0x00, 0x00, 0x00, 0x10, 0x49, 0x44, 0x41, 0x54, 0x08, 0x1d, 0x63, 0x60, 0x60, 0x60, 0xf8, 0x0f, 0xc4, 0x70, 0x00, 0x00, 0x0d, 0x04, 0x01, 0x00, 0x65, 0x59, 0x09, 0xe8, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXHierarchyIndentPattern2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0xe3, 0x00, 0xef, 0x43, 0x00, 0x00, 0x0a, 0x41, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0x9d, 0x96, 0x77, 0x54, 0x53, 0xd9, 0x16, 0x87, 0xcf, 0xbd, 0x37, 0xbd, 0xd0, 0x12, 0x22, 0x20, 0x25, 0xf4, 0x1a, 0x7a, 0x09, 0x20, 0xd2, 0x3b, 0x48, 0x15, 0x04, 0x51, 0x89, 0x49, 0x80, 0x50, 0x02, 0x86, 0x84, 0x26, 0x76, 0x44, 0x05, 0x46, 0x14, 0x11, 0x29, 0x56, 0x64, 0x54, 0xc0, 0x01, 0x47, 0x87, 0x22, 0x63, 0x45, 0x14, 0x0b, 0x83, 0x82, 0x62, 0x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0x41, 0x3e, 0xd8, 0x00, 0x0a, 0x41, 0x31, 0xd8, 0x01, 0x76, 0x83, 0x6a, 0x70, 0x00, 0xd4, 0x81, 0x7a, 0xd0, 0x04, 0x4e, 0x82, 0x36, 0x70, 0x06, 0x5c, 0x04, 0x57, 0xc0, 0x0d, 0x70, 0x0b, 0x0c, 0x80, 0x47, 0x40, 0x0a, 0x86, 0xc1, 0x4b, 0x30, 0x01, 0xde, 0x81, 0x69, 0x08, 0x82, 0xf0, 0x10, 0x15, 0xa2, 0x41, 0xaa, 0x90, 0x16, 0xa4, 0x0f, 0x99, 0x42, 0xd6, 0x10, 0x1b, 0x5a, 0x08, 0x79, 0x43, 0x41, 0x50, 0x38, 0x14, 0x03, 0xc5, 0x43, 0x89, 0x90, 0x10, 0x92, 0x40, 0xf9, 0xd0, 0x26, 0xa8, 0x18, 0x2a, 0x83, 0xaa, 0xa1, 0x43, 0x50, 0x3d, 0xf4, 0x23, 0x74, 0x1a, 0xba, 0x08, 0x5d, 0x83, 0xfa, 0xa0, 0x07, 0xd0, 0x20, 0x34, 0x06, 0xfd, 0x01, 0x7d, 0x84, 0x11, 0x98, 0x02, 0xd3, 0x61, 0x0d, 0xd8, 0x00, 0xb6, 0x80, 0xd9, 0xb0, 0x3b, 0x1c, 0x08, 0x47, 0xc2, 0xcb, 0xe0, 0x44, 0x78, 0x15, 0x9c, 0x07, 0x17, 0xc0, 0xdb, 0xe1, 0x4a, 0xb8, 0x16, 0x3e, 0x0e, 0xb7, 0xc2, 0x17, 0xe1, 0x1b, 0xf0, 0x00, 0x2c, 0x85, 0x5f, 0xc2, 0x93, 0x08, 0x40, 0xc8, 0x08, 0x03, 0xd1, 0x46, 0x58, 0x08, 0x1b, 0xf1, 0x44, 0x42, 0x90, 0x58, 0x24, 0x01, 0x11, 0x21, 0x6b, 0x91, 0x22, 0xa4, 0x02, 0xa9, 0x45, 0x9a, 0x90, 0x0e, 0xa4, 0x1b, 0xb9, 0x8d, 0x48, 0x91, 0x71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54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x34, 0x2d, 0x30, 0x35, 0x2d, 0x30, 0x32, 0x54, 0x31, 0x31, 0x3a, 0x30, 0x35, 0x3a, 0x30, 0x36, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x38, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0x90, 0x7a, 0xe1, 0x8d, 0x00, 0x00, 0x00, 0x12, 0x49, 0x44, 0x41, 0x54, 0x08, 0x1d, 0x63, 0x60, 0x60, 0x60, 0xf8, 0x0f, 0xc5, 0x40, 0x0a, 0x13, 0x00, 0x00, 0x35, 0xeb, 0x01, 0xff, 0x0f, 0x5e, 0xbc, 0xf4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXListIcon[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x0f, 0x08, 0x06, 0x00, 0x00, 0x00, 0xe4, 0x98, 0xef, 0x55, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0xf4, 0x69, 0xff, 0xfb, 0xdd, 0xe7, 0x39, 0xe7, 0xbe, 0x79, 0xbf, 0xef, 0x7c, 0xf7, 0xfd, 0xbe, 0x7b, 0xee, 0xc9, 0x39, 0x00, 0x9a, 0xb6, 0x02, 0xb9, 0x3c, 0x17, 0xd7, 0x02, 0xc8, 0x93, 0x15, 0x2a, 0xe2, 0x23, 0x82, 0xf9, 0x13, 0x52, 0x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 0x45, 0x75, 0xdb, 0x90, 0x33, 0x35, 0x9a, 0xc2, 0x2c, 0x84, 0xf7, 0xcb, 0x32, 0xc6, 0xc5, 0x22, 0xac, 0x83, 0xf0, 0x51, 0x29, 0x95, 0x71, 0x3f, 0x6e, 0x91, 0x28, 0x23, 0x93, 0x10, 0xa6, 0xfc, 0xdb, 0x84, 0x05, 0x21, 0xa8, 0x96, 0xc0, 0x43, 0xf8, 0x8d, 0x48, 0x10, 0x1a, 0x8d, 0xb0, 0x11, 0x00, 0xce, 0x54, 0xe6, 0x24, 0x05, 0x0d, 0x60, 0x6b, 0x81, 0x02, 0x21, 0x95, 0x3f, 0x1e, 0x2c, 0x2d, 0x8c, 0x4a, 0x1c, 0xc0, 0xc9, 0x8a, 0xa9, 0xf1, 0x03, 0xf1, 0xf1, 0x6c, 0x59, 0xee, 0x38, 0x6a, 0x7e, 0xa0, 0x38, 0xf8, 0x2c, 0x89, 0x38, 0x6a, 0x10, 0x97, 0x8b, 0x0b, 0xc2, 0x12, 0x10, 0x8f, 0x34, 0xe0, 0xd9, 0x99, 0xd2, 0xf0, 0x28, 0x84, 0xd1, 0xbb, 0xc2, 0x77, 0x16, 0x4b, 0x12, 0x53, 0x10, 0x46, 0x3a, 0xf1, 0xfa, 0x22, 0x69, 0xf2, 0x38, 0x84, 0x39, 0x08, 0x37, 0x17, 0xe4, 0x24, 0x50, 0x1a, 0xa8, 0x38, 0x57, 0x8b, 0x25, 0x21, 0x14, 0xaf, 0xf2, 0x51, 0x28, 0xe3, 0x29, 0xcd, 0x96, 0x88, 0xef, 0xc8, 0x54, 0x84, 0x53, 0x39, 0x22, 0x1f, 0x82, 0x95, 0x57, 0x80, 0x90, 0x2a, 0x3e, 0x61, 0x2e, 0x14, 0xa8, 0x9e, 0xa5, 0x8f, 0x78, 0xb7, 0x42, 0x49, 0x62, 0x24, 0xe2, 0xd1, 0x58, 0x22, 0x46, 0x24, 0x0e, 0x0d, 0x43, 0x18, 0x3d, 0x97, 0x98,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e, 0x27, 0x06, 0x02, 0xee, 0xea, 0x3a, 0xd4, 0x10, 0x43, 0x5d, 0x05, 0x99, 0xae, 0x2e, 0x2a, 0x80, 0xb1, 0x14, 0x68, 0x6b, 0xf2, 0xbe, 0xaf, 0xef, 0xb5, 0x31, 0x00, 0xa3, 0x01, 0xe0, 0xb3, 0xa2, 0xaf, 0xaf, 0x77, 0x63, 0x5f, 0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9c, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x39, 0x30, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xc1, 0xe2, 0xd2, 0xc6, 0x00, 0x00, 0x00, 0x65, 0x49, 0x44, 0x41, 0x54, 0x38, 0x11, 0x63, 0x60, 0x60, 0x60, 0x68, 0x05, 0xe2, 0x9f, 0x40, 0xfc, 0x9f, 0x42, 0x0c, 0x32, 0xa3, 0x95, 0x11, 0x48, 0x7c, 0x06, 0x62, 0x1e, 0x20, 0xa6, 0x06, 0xf8, 0xc2, 0x0c, 0x34, 0x05, 0x64, 0x98, 0x39, 0x10, 0x83, 0xd8, 0x94, 0x80, 0x5f, 0x40, 0xcd, 0xfd, 0x94, 0x18, 0x30, 0x84, 0xf5, 0x36, 0x03, 0xdd, 0xfe, 0x0d, 0x88, 0xff, 0x52, 0x88, 0x41, 0x66, 0x34, 0xd3, 0x24, 0x96, 0xf9, 0x81, 0x26, 0x53, 0x23, 0x96, 0x7f, 0x03, 0xcd, 0x99, 0x04, 0x72, 0x21, 0x08, 0x80, 0x68, 0x18, 0x1b, 0x2c, 0x40, 0x06, 0x01, 0xcb, 0x18, 0x64, 0x68, 0xa5, 0xb7, 0x96, 0x11, 0x16, 0xcb, 0x00, 0xa6, 0x38, 0x45, 0xd2, 0xe0, 0x92, 0x71, 0xfa, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXListIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1e, 0x08, 0x06, 0x00, 0x00, 0x00, 0x5e, 0xdd, 0x5c, 0xdd, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5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x25, 0x21, 0x14, 0xaf, 0xf2, 0x51, 0x28, 0xe3, 0x29, 0xcd, 0x96, 0x88, 0xef, 0xc8, 0x54, 0x84, 0x53, 0x39, 0x22, 0x1f, 0x82, 0x95, 0x57, 0x80, 0x90, 0x2a, 0x3e, 0x61, 0x2e, 0x14, 0xa8, 0x9e, 0xa5, 0x8f, 0x78, 0xb7, 0x42, 0x49, 0x62, 0x24, 0xe2, 0xd1, 0x58, 0x22, 0x46, 0x24, 0x0e, 0x0d, 0x43, 0x18, 0x3d, 0x97, 0x98, 0x20, 0x96, 0x25, 0x0d, 0xe8, 0x21, 0x24, 0xf2, 0xc2, 0x60, 0x2a, 0x0e, 0xe5, 0x5f, 0x2c, 0xcf, 0x55, 0xcd, 0x6f, 0xa4, 0x93, 0x28, 0x17, 0xe7, 0x46, 0x50, 0xbc, 0x39, 0xc2, 0xdb, 0x0a, 0x8a, 0x12, 0x06, 0xc7, 0x9e, 0x29, 0x54, 0x24, 0x52, 0x3c, 0xaa, 0x1b, 0x71, 0x33, 0x5b, 0x30, 0x86, 0x9a, 0xaf, 0x48, 0x33, 0xf1, 0x4c, 0x5e, 0x18, 0x47, 0xd5, 0x84, 0xd2, 0xf3, 0x1e, 0x62, 0x20, 0x04, 0x42, 0x81, 0x0f, 0x4a, 0xd4, 0x32, 0x60, 0x2a, 0x64, 0x83, 0xb4, 0xa5, 0xab, 0xae, 0x0b, 0xfd, 0xea, 0xb7, 0x84, 0x83, 0x00, 0x14, 0x90, 0x05, 0x62, 0x70, 0x1c, 0x60, 0x06, 0x47, 0xa4, 0xa8, 0x2c, 0x32, 0xd4, 0x27, 0x40, 0x31, 0xfc, 0x09, 0x32, 0xe4, 0x53, 0x30, 0x34, 0x2e, 0x58, 0x65, 0x15, 0x43, 0x11, 0xe2, 0x3f, 0x0f, 0xb1, 0xfd, 0x63, 0x1d, 0x21, 0x53, 0x65, 0x2d, 0x52, 0x8d, 0xc8, 0x81, 0x27, 0xe8, 0x09, 0x79, 0xa4,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x3b, 0x00, 0xd8, 0xa9, 0x68, 0xef, 0x70, 0x05, 0x80, 0xc9, 0xe9, 0x3f, 0x73, 0xa9, 0x3c, 0xb0, 0xfe, 0x73, 0x22, 0xc2, 0xd8, 0x40, 0xa3, 0xe8, 0x7f, 0xe0, 0xfe, 0x73, 0x19, 0x65, 0x40, 0x7b, 0x08, 0xd8, 0x11, 0x08, 0x90, 0x34, 0x0f, 0x20, 0xa6, 0x11, 0x60, 0x13, 0x6a, 0x56, 0x08, 0xb3, 0xd0, 0x9d, 0xda, 0x7e, 0x27, 0x06, 0x02, 0xee, 0xea, 0x3a, 0xd4, 0x10, 0x43, 0x5d, 0x05, 0x99, 0xae, 0x2e, 0x2a, 0x80, 0xb1, 0x14, 0x68, 0x6b, 0xf2, 0xbe, 0xaf, 0xef, 0xb5, 0x31, 0x00, 0xa3, 0x01, 0xe0, 0xb3, 0xa2, 0xaf, 0xaf, 0x77, 0x63, 0x5f, 0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9c, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x39, 0x30, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xc1, 0xe2, 0xd2, 0xc6, 0x00, 0x00, 0x00, 0x94, 0x49, 0x44, 0x41, 0x54, 0x58, 0x09, 0xed, 0x96, 0xc1, 0x09, 0x80, 0x30, 0x14, 0x43, 0xbf, 0x0a, 0x6e, 0xe0, 0xc1, 0x5d, 0x1c, 0xb0, 0x13, 0x38, 0xa2, 0x8e, 0xa1, 0x89, 0x87, 0xd2, 0x7a, 0xfc, 0x5e, 0x22, 0x44, 0x08, 0xf4, 0x0b, 0xc2, 0x23, 0x8d, 0x4d, 0x23, 0x22, 0x66, 0xa8, 0x40, 0x07, 0x74, 0x89, 0x88, 0x2c, 0x64, 0x22, 0xdb, 0xb3, 0x50, 0x01, 0x7b, 0x73, 0x94, 0x01, 0x80, 0xa4, 0x5d, 0x49, 0x2a, 0xf8, 0x9c, 0xa3, 0x20, 0x54, 0x87, 0x34, 0x61, 0x5a, 0xa0, 0xad, 0x7b, 0xab, 0x33, 0xec, 0x44, 0x61, 0x10, 0xa5, 0x7f, 0x12, 0x1d, 0xbf, 0x4c, 0x62, 0x07, 0xec, 0x40, 0xce, 0x01, 0xf9, 0x63, 0x86, 0x67, 0xe0, 0xbb, 0x03, 0x55, 0x66, 0x77, 0x71, 0x2e, 0x74, 0xcd, 0x57, 0xee, 0xe2, 0x64, 0xbe, 0x79, 0x05, 0xac, 0x17, 0xd6, 0xc6, 0x50, 0x2f, 0xed, 0x80, 0x1d, 0xf8, 0xa5, 0x03, 0xee, 0x62, 0x6c, 0x5b, 0xb6, 0xdb, 0xdd, 0xc5, 0x9f, 0x33, 0xef, 0x2e, 0x4e, 0xe6, 0xaf, 0x76, 0xf1, 0x0d, 0xa7, 0xae, 0x59, 0xeb, 0x22, 0xc6, 0xba, 0x58, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXMoveIcon[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x15, 0x08, 0x06, 0x00, 0x00, 0x00, 0xa9, 0x17, 0xa5, 0x96, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0xf4, 0x69, 0xff, 0xfb, 0xdd, 0xe7, 0x39, 0xe7, 0xbe, 0x79, 0xbf, 0xef, 0x7c, 0xf7, 0xfd, 0xbe, 0x7b, 0xee, 0xc9, 0x39, 0x00, 0x9a, 0xb6, 0x02, 0xb9, 0x3c, 0x17, 0xd7, 0x02, 0xc8, 0x93, 0x15, 0x2a, 0xe2, 0x23, 0x82, 0xf9, 0x13, 0x52, 0xd3, 0xf8, 0x8c, 0x07, 0x80, 0x83, 0x01, 0x70, 0xc0, 0x0d, 0x48, 0x81, 0xb0, 0x40, 0x1e, 0x14, 0x17, 0x17, 0x03, 0xff, 0x79, 0xbd, 0xbd, 0x09, 0x18, 0x65, 0xbc, 0xe6, 0x48, 0xc5, 0xfa, 0x4f, 0xb7, 0x7f, 0x37, 0x68, 0x8b, 0xc4, 0x05, 0x42, 0x00, 0x2c, 0x0e, 0x99, 0x33, 0x44, 0x05, 0xc2, 0x3c, 0x84, 0x0f, 0x01, 0x90, 0x1c, 0xa1, 0x5c, 0x51, 0x08, 0x40, 0x6b, 0x46, 0xbc, 0xc5, 0xb4, 0x42, 0x39, 0x85, 0x3b, 0x10, 0xd6, 0x55, 0x20, 0x81, 0x08, 0x7f, 0xa2, 0x70, 0x96, 0x0a, 0xd3, 0x91, 0x7a, 0xd0, 0xcd, 0xe8, 0xc7, 0x96, 0x2a, 0x9f, 0xc4, 0xf8, 0x10, 0x00, 0xba, 0x17, 0x80, 0x1a, 0x4b, 0x20, 0x50, 0x64, 0x01, 0x70, 0x42, 0x11, 0xcf, 0x2f, 0x12, 0x66, 0xa1, 0x38, 0x1c, 0x11, 0xc2, 0x4e, 0x32, 0x91, 0x54, 0x86, 0xf0, 0x2a, 0x84, 0xfd, 0x85, 0x12, 0x01, 0xe2, 0x38, 0xd7, 0x11, 0x1e, 0x91, 0x97, 0x37, 0x15, 0x61, 0x4d, 0x04, 0xc1, 0x36, 0xe3, 0x6f, 0x71, 0xb2, 0xfe, 0x86, 0x05, 0x82, 0x8c, 0xa1, 0x98, 0x02, 0x41, 0xd6, 0x10, 0xee, 0xcf, 0x85, 0x1a, 0x0a, 0x6a, 0xa1, 0xd2, 0x02, 0x79, 0xae, 0x60, 0x86, 0xea, 0xc7, 0xff, 0xb3, 0xcb, 0xcb, 0x55, 0xa2, 0x7a, 0xa9, 0x2e, 0x33, 0xd4, 0xb3, 0x24, 0x8a, 0xc8, 0x78, 0x74, 0xd7, 0x45, 0x75, 0xdb, 0x90, 0x33, 0x35, 0x9a, 0xc2, 0x2c, 0x84, 0xf7, 0xcb, 0x32, 0xc6, 0xc5, 0x22, 0xac, 0x83, 0xf0, 0x51, 0x29, 0x95, 0x71, 0x3f, 0x6e, 0x91, 0x28, 0x23, 0x93, 0x10, 0xa6, 0xfc, 0xdb, 0x84, 0x05, 0x21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7, 0x9e, 0x29, 0x54, 0x24, 0x52, 0x3c, 0xaa, 0x1b, 0x71, 0x33, 0x5b, 0x30, 0x86, 0x9a, 0xaf, 0x48, 0x33, 0xf1, 0x4c, 0x5e, 0x18, 0x47, 0xd5, 0x84, 0xd2, 0xf3, 0x1e, 0x62, 0x20, 0x04, 0x42, 0x81, 0x0f, 0x4a, 0xd4, 0x32, 0x60, 0x2a, 0x64, 0x83, 0xb4, 0xa5, 0xab, 0xae, 0x0b, 0xfd, 0xea, 0xb7, 0x84, 0x83, 0x00, 0x14, 0x90, 0x05, 0x62, 0x70, 0x1c, 0x60, 0x06, 0x47, 0xa4, 0xa8, 0x2c, 0x32, 0xd4, 0x27, 0x40, 0x31, 0xfc, 0x09, 0x32, 0xe4, 0x53, 0x30, 0x34, 0x2e, 0x58, 0x65, 0x15, 0x43, 0x11, 0xe2, 0x3f, 0x0f, 0xb1, 0xfd, 0x63, 0x1d, 0x21, 0x53, 0x65, 0x2d, 0x52, 0x8d, 0xc8, 0x81, 0x27, 0xe8, 0x09, 0x79, 0xa4, 0x21, 0xe9, 0x4f, 0xfa, 0x92, 0x31, 0xa8, 0x0f, 0x44, 0xcd, 0x85, 0xf4, 0x22, 0xbd, 0x07, 0xc7, 0xf1, 0x35, 0x07, 0x75, 0xd2, 0xc3, 0xe8, 0xa1, 0xf4, 0x48, 0x7a, 0x38, 0xdd, 0x6e, 0x90, 0x01, 0x21, 0x52, 0x9d, 0x8b, 0x9a, 0x02, 0xa4, 0xff, 0xc2, 0x45, 0x23, 0x9b, 0x18, 0x65, 0xa7, 0x40, 0xbd, 0x6c, 0x30, 0x87, 0xaf, 0xf1, 0x68, 0x4f, 0x68, 0xad, 0xb4, 0x47, 0xb4, 0x1b, 0xb4, 0x36, 0xda, 0x1d, 0x48, 0x86, 0x3f, 0x54, 0x51, 0x06, 0x32, 0x9d, 0x22, 0x5d, 0xa0, 0x18, 0x54, 0x30, 0x14, 0x79, 0x2c, 0xb4, 0xa1, 0x68, 0x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, 0x63, 0x5f, 0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9c, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x39, 0x30, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xc1, 0xe2, 0xd2, 0xc6, 0x00, 0x00, 0x01, 0x2f, 0x49, 0x44, 0x41, 0x54, 0x38, 0x11, 0xb5, 0x95, 0x31, 0x4e, 0x03, 0x41, 0x0c, 0x45, 0x87, 0x40, 0xfa, 0x88, 0x13, 0xa4, 0xa1, 0xe2, 0x0e, 0x88, 0x94, 0xd4, 0x1c, 0x21, 0x1d, 0x07, 0x80, 0x33, 0x40, 0x49, 0x41, 0xc7, 0x11, 0xe8, 0x22, 0xa1, 0x54, 0x41, 0x94, 0xf4, 0x14, 0x11, 0x12, 0xe4, 0x04, 0x5c, 0x00, 0x09, 0x78, 0x4f, 0x9a, 0x41, 0x93, 0xdd, 0xcd, 0x32, 0xcb, 0x86, 0x2f, 0x7d, 0xd9, 0xe3, 0xb1, 0x7f, 0x2c, 0xaf, 0x47, 0x09, 0xa1, 0x0c, 0xfb, 0xa4, 0xcd, 0xa0, 0x76, 0x2b, 0x18, 0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0xa6, 0xf5, 0x6c, 0xbc, 0xd6, 0x21, 0xb1, 0x22, 0xf8, 0x52, 0x14, 0xab, 0x72, 0xed, 0x05, 0x15, 0x29, 0x55, 0x92, 0xfc, 0xaa, 0xb9, 0xa8, 0xe7, 0xde, 0x18, 0xa2, 0xb0, 0x80, 0x0a, 0x6b, 0x3d, 0x6f, 0x05, 0x9d, 0xfe, 0xa3, 0xbe, 0x01, 0xe4, 0xf1, 0x5c, 0xce, 0x72, 0x04, 0x22, 0xd7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXMoveIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x2a, 0x08, 0x06, 0x00, 0x00, 0x00, 0xc5, 0xc3, 0xc9, 0x5b, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0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xef, 0xc8, 0x54, 0x84, 0x53, 0x39, 0x22, 0x1f, 0x82, 0x95, 0x57, 0x80, 0x90, 0x2a, 0x3e, 0x61, 0x2e, 0x14, 0xa8, 0x9e, 0xa5, 0x8f, 0x78, 0xb7, 0x42, 0x49, 0x62, 0x24, 0xe2, 0xd1, 0x58, 0x22, 0x46, 0x24, 0x0e, 0x0d, 0x43, 0x18, 0x3d, 0x97, 0x98, 0x20, 0x96, 0x25, 0x0d, 0xe8, 0x21, 0x24, 0xf2, 0xc2, 0x60, 0x2a, 0x0e, 0xe5, 0x5f, 0x2c, 0xcf, 0x55, 0xcd, 0x6f, 0xa4, 0x93, 0x28, 0x17, 0xe7, 0x46, 0x50, 0xbc, 0x39, 0xc2, 0xdb, 0x0a, 0x8a, 0x12, 0x06, 0xc7, 0x9e, 0x29, 0x54, 0x24, 0x52, 0x3c, 0xaa, 0x1b, 0x71, 0x33, 0x5b, 0x30, 0x86, 0x9a, 0xaf, 0x48, 0x33, 0xf1, 0x4c, 0x5e, 0x18, 0x47, 0xd5, 0x84, 0xd2, 0xf3, 0x1e, 0x62, 0x20, 0x04, 0x42, 0x81, 0x0f, 0x4a, 0xd4, 0x32, 0x60, 0x2a, 0x64, 0x83, 0xb4, 0xa5, 0xab, 0xae, 0x0b, 0xfd, 0xea, 0xb7, 0x84, 0x83, 0x00, 0x14, 0x90, 0x05, 0x62, 0x70, 0x1c, 0x60, 0x06, 0x47, 0xa4, 0xa8, 0x2c, 0x32, 0xd4, 0x27, 0x40, 0x31, 0xfc, 0x09, 0x32, 0xe4, 0x53, 0x30, 0x34, 0x2e, 0x58, 0x65, 0x15, 0x43, 0x11, 0xe2, 0x3f, 0x0f, 0xb1, 0xfd, 0x63, 0x1d, 0x21, 0x53, 0x65, 0x2d, 0x52, 0x8d, 0xc8, 0x81, 0x27, 0xe8, 0x09, 0x79, 0xa4, 0x21, 0xe9, 0x4f, 0xfa, 0x92, 0x31, 0xa8, 0x0f, 0x44, 0xcd, 0x85, 0x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 0x73, 0xa9, 0x3c, 0xb0, 0xfe, 0x73, 0x22, 0xc2, 0xd8, 0x40, 0xa3, 0xe8, 0x7f, 0xe0, 0xfe, 0x73, 0x19, 0x65, 0x40, 0x7b, 0x08, 0xd8, 0x11, 0x08, 0x90, 0x34, 0x0f, 0x20, 0xa6, 0x11, 0x60, 0x13, 0x6a, 0x56, 0x08, 0xb3, 0xd0, 0x9d, 0xda, 0x7e, 0x27, 0x06, 0x02, 0xee, 0xea, 0x3a, 0xd4, 0x10, 0x43, 0x5d, 0x05, 0x99, 0xae, 0x2e, 0x2a, 0x80, 0xb1, 0x14, 0x68, 0x6b, 0xf2, 0xbe, 0xaf, 0xef, 0xb5, 0x31, 0x00, 0xa3, 0x01, 0xe0, 0xb3, 0xa2, 0xaf, 0xaf, 0x77, 0x63, 0x5f, 0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9c, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x39, 0x30, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xc1, 0xe2, 0xd2, 0xc6, 0x00, 0x00, 0x02, 0x26, 0x49, 0x44, 0x41, 0x54, 0x58, 0x09, 0xd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0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXSelectIcon[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x11, 0x08, 0x06, 0x00, 0x00, 0x00, 0xed, 0xc8, 0x9d, 0x9f, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0xf4, 0x69, 0xff, 0xfb, 0xdd, 0xe7, 0x39, 0xe7, 0xbe, 0x79, 0xbf, 0xef, 0x7c, 0xf7, 0xfd, 0xbe, 0x7b, 0xee, 0xc9, 0x39, 0x00, 0x9a, 0xb6, 0x02, 0xb9, 0x3c, 0x17, 0xd7, 0x02, 0xc8, 0x93, 0x15, 0x2a, 0xe2, 0x23, 0x82, 0xf9, 0x13, 0x52, 0xd3, 0xf8, 0x8c, 0x07, 0x80, 0x83, 0x01, 0x70, 0xc0, 0x0d, 0x48, 0x81,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xcb, 0x32, 0xc6, 0xc5, 0x22, 0xac, 0x83, 0xf0, 0x51, 0x29, 0x95, 0x71, 0x3f, 0x6e, 0x91, 0x28, 0x23, 0x93, 0x10, 0xa6, 0xfc, 0xdb, 0x84, 0x05, 0x21, 0xa8, 0x96, 0xc0, 0x43, 0xf8, 0x8d, 0x48, 0x10, 0x1a, 0x8d, 0xb0, 0x11, 0x00, 0xce, 0x54, 0xe6, 0x24, 0x05, 0x0d, 0x60, 0x6b, 0x81, 0x02, 0x21, 0x95, 0x3f, 0x1e, 0x2c, 0x2d, 0x8c, 0x4a, 0x1c, 0xc0, 0xc9, 0x8a, 0xa9, 0xf1, 0x03, 0xf1, 0xf1, 0x6c, 0x59, 0xee, 0x38, 0x6a, 0x7e, 0xa0, 0x38, 0xf8, 0x2c, 0x89, 0x38, 0x6a, 0x10, 0x97, 0x8b, 0x0b, 0xc2, 0x12, 0x10, 0x8f, 0x34, 0xe0, 0xd9, 0x99, 0xd2, 0xf0, 0x28, 0x84, 0xd1, 0xbb, 0xc2, 0x77, 0x16, 0x4b, 0x12, 0x53, 0x10, 0x46, 0x3a, 0xf1, 0xfa, 0x22, 0x69, 0xf2, 0x38, 0x84, 0x39, 0x08, 0x37, 0x17, 0xe4, 0x24, 0x50, 0x1a, 0xa8, 0x38, 0x57, 0x8b, 0x25, 0x21, 0x14, 0xaf, 0xf2, 0x51, 0x28, 0xe3, 0x29, 0xcd, 0x96, 0x88, 0xef, 0xc8, 0x54, 0x84, 0x53, 0x39, 0x22, 0x1f, 0x82, 0x95, 0x57, 0x80, 0x90, 0x2a, 0x3e, 0x61, 0x2e, 0x14, 0xa8, 0x9e, 0xa5, 0x8f, 0x78, 0xb7, 0x42, 0x49, 0x62, 0x24, 0xe2, 0xd1, 0x58, 0x22, 0x46, 0x24, 0x0e, 0x0d, 0x43, 0x18, 0x3d, 0x97, 0x98, 0x20, 0x96, 0x25, 0x0d, 0xe8, 0x21, 0x24, 0xf2, 0xc2, 0x60, 0x2a, 0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x99, 0xae, 0x2e, 0x2a, 0x80, 0xb1, 0x14, 0x68, 0x6b, 0xf2, 0xbe, 0xaf, 0xef, 0xb5, 0x31, 0x00, 0xa3, 0x01, 0xe0, 0xb3, 0xa2, 0xaf, 0xaf, 0x77, 0x63, 0x5f, 0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9c, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x39, 0x30, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xc1, 0xe2, 0xd2, 0xc6, 0x00, 0x00, 0x00, 0xf4, 0x49, 0x44, 0x41, 0x54, 0x28, 0x15, 0x95, 0x92, 0xc1, 0x0a, 0x01, 0x61, 0x14, 0x85, 0x27, 0x45, 0x64, 0xa3, 0x94, 0x2c, 0xac, 0xa4, 0x44, 0x51, 0x16, 0xd6, 0xf6, 0xca, 0xc6, 0x23, 0x78, 0x02, 0x25, 0x2f, 0x61, 0xc9, 0xc6, 0xde, 0x0b, 0xd8, 0x51, 0xbc, 0x82, 0xc8, 0x4e, 0xa1, 0xa4, 0xac, 0x94, 0x6c, 0x88, 0x14, 0xdf, 0xd5, 0xdc, 0xfa, 0x1b, 0x33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 0x17, 0xaf, 0x54, 0x62, 0xf7, 0x88, 0x7e, 0xaa, 0x27, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXSelectIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x22, 0x08, 0x06, 0x00, 0x00, 0x00, 0x4c, 0x7d, 0xb9, 0x49, 0x00, 0x00, 0x0c, 0x45, 0x69, 0x43, 0x43, 0x50, 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x48, 0x0d, 0xad, 0x57, 0x77, 0x58, 0x53, 0xd7, 0x1b, 0xfe, 0xee, 0x48, 0x02, 0x21, 0x09, 0x23, 0x10, 0x01, 0x19, 0x61, 0x2f, 0x51, 0xf6, 0x94, 0xbd, 0x05, 0x05, 0x99, 0x42, 0x1d, 0x84, 0x24, 0x90, 0x30, 0x62, 0x08, 0x04, 0x15, 0xf7, 0x28, 0xad, 0x60, 0x1d, 0xa8, 0x38, 0x70, 0x54, 0xb4, 0x2a, 0xe2, 0xaa, 0x03, 0x90, 0x3a, 0x10, 0x71, 0x5b, 0x14, 0xb7, 0x75, 0x14, 0xb5, 0x28, 0x28, 0xb5, 0x38, 0x70, 0xa1, 0xf2, 0x3b, 0x37, 0x0c, 0xfb, 0xf4, 0x69, 0xff, 0xfb, 0xdd, 0xe7, 0x39, 0xe7, 0xbe, 0x79, 0xbf, 0xef, 0x7c, 0xf7, 0xfd, 0xbe, 0x7b, 0xee, 0xc9, 0x39, 0x00, 0x9a, 0xb6, 0x02, 0xb9, 0x3c, 0x17, 0xd7, 0x02, 0xc8, 0x93, 0x15, 0x2a, 0xe2, 0x23, 0x82, 0xf9, 0x13, 0x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0xd7, 0x45, 0x75, 0xdb, 0x90, 0x33, 0x35, 0x9a, 0xc2, 0x2c, 0x84, 0xf7, 0xcb, 0x32, 0xc6, 0xc5, 0x22, 0xac, 0x83, 0xf0, 0x51, 0x29, 0x95, 0x71, 0x3f, 0x6e, 0x91, 0x28, 0x23, 0x93, 0x10, 0xa6, 0xfc, 0xdb, 0x84, 0x05, 0x21, 0xa8, 0x96, 0xc0, 0x43, 0xf8, 0x8d, 0x48, 0x10, 0x1a, 0x8d, 0xb0, 0x11, 0x00, 0xce, 0x54, 0xe6, 0x24, 0x05, 0x0d, 0x60, 0x6b, 0x81, 0x02, 0x21, 0x95, 0x3f, 0x1e, 0x2c, 0x2d, 0x8c, 0x4a, 0x1c, 0xc0, 0xc9, 0x8a, 0xa9, 0xf1, 0x03, 0xf1, 0xf1, 0x6c, 0x59, 0xee, 0x38, 0x6a, 0x7e, 0xa0, 0x38, 0xf8, 0x2c, 0x89, 0x38, 0x6a, 0x10, 0x97, 0x8b, 0x0b, 0xc2, 0x12, 0x10, 0x8f, 0x34, 0xe0, 0xd9, 0x99, 0xd2, 0xf0, 0x28, 0x84, 0xd1, 0xbb, 0xc2, 0x77, 0x16, 0x4b, 0x12, 0x53, 0x10, 0x46, 0x3a, 0xf1, 0xfa, 0x22, 0x69, 0xf2, 0x38, 0x84, 0x39, 0x08, 0x37, 0x17, 0xe4, 0x24, 0x50, 0x1a, 0xa8, 0x38, 0x57, 0x8b, 0x25, 0x21, 0x14, 0xaf, 0xf2, 0x51, 0x28, 0xe3, 0x29, 0xcd, 0x96, 0x88, 0xef, 0xc8, 0x54, 0x84, 0x53, 0x39, 0x22, 0x1f, 0x82, 0x95, 0x57, 0x80, 0x90, 0x2a, 0x3e, 0x61, 0x2e, 0x14, 0xa8, 0x9e, 0xa5, 0x8f, 0x78, 0xb7, 0x42, 0x49, 0x62, 0x24, 0xe2, 0xd1, 0x58, 0x22, 0x46, 0x24, 0x0e, 0x0d, 0x43, 0x18, 0x3d, 0x97,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, 0x7e, 0x27, 0x06, 0x02, 0xee, 0xea, 0x3a, 0xd4, 0x10, 0x43, 0x5d, 0x05, 0x99, 0xae, 0x2e, 0x2a, 0x80, 0xb1, 0x14, 0x68, 0x6b, 0xf2, 0xbe, 0xaf, 0xef, 0xb5, 0x31, 0x00, 0xa3, 0x01, 0xe0, 0xb3, 0xa2, 0xaf, 0xaf, 0x77, 0x63, 0x5f, 0xdf, 0xe7, 0x6d, 0x68, 0xaf, 0x7e, 0x07, 0xa0, 0x31, 0xbf, 0xff, 0xac, 0x47, 0x79, 0x53, 0x67, 0xc8, 0x1f, 0xd1, 0x7e, 0x1e, 0xe0, 0x7c, 0xcb, 0x92, 0x79, 0xd4, 0xfd, 0xef, 0xd7, 0xff, 0x00, 0x53, 0x9d, 0x6a, 0xc0, 0x3e, 0x1f, 0x78, 0xfa, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01, 0x49, 0x52, 0x24, 0xf0, 0x00, 0x00, 0x01, 0x9c, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x39, 0x30, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xc1, 0xe2, 0xd2, 0xc6, 0x00, 0x00, 0x02, 0x01, 0x49, 0x44, 0x41, 0x54, 0x48, 0x0d, 0xbd, 0x96, 0xcf, 0x2b, 0x05, 0x51, 0x14, 0xc7, 0x1f, 0x3d, 0xf2, 0x33, 0x0b, 0x85, 0x52, 0xb6, 0x42, 0xc4, 0x42, 0xd6, 0x96, 0x8a, 0x12, 0x0b, 0xca, 0x1f, 0x41, 0x42, 0xb1, 0x61, 0x85, 0x35, 0x29, 0x85, 0x94, 0x8d, 0x62, 0x69, 0x23, 0x24,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0x10, 0x4a, 0x3d, 0x39, 0x49, 0x2f, 0x33, 0xb8, 0x7b, 0x8d, 0x34, 0xf1, 0x88, 0xb6, 0xdf, 0x12, 0x55, 0x41, 0xdf, 0xad, 0x11, 0xab, 0x39, 0xea, 0xf7, 0xe9, 0xb3, 0x3a, 0x11, 0x2c, 0x26, 0x8a, 0xac, 0xe0, 0x53, 0x2d, 0x51, 0x4d, 0xc4, 0xc8, 0x7f, 0xa8, 0x10, 0xaf, 0x9f, 0xa0, 0x2f, 0xa5, 0xc9, 0x91, 0x70, 0x20, 0x65, 0xd4, 0x6f, 0x40, 0x37, 0x4d, 0x2f, 0x48, 0xaf, 0x6f, 0x7e, 0xc3, 0xc2, 0x6d, 0x8d, 0xf9, 0x40, 0x65, 0xca, 0x23, 0x31, 0x79, 0xf7, 0xcb, 0x48, 0x9f, 0x4c, 0xbd, 0xd5, 0x94, 0xa6, 0x3b, 0xa2, 0x38, 0x89, 0x93, 0x48, 0x9e, 0x4a, 0xa6, 0x52, 0x60, 0xf1, 0x1f, 0x65, 0x5c, 0x9e, 0x8b, 0x0f, 0xbf, 0xa0, 0x23, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXJSONIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x03, 0xa8, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x30, 0x39, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x32, 0x3a, 0x32, 0x33, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0x03, 0x64, 0xa2, 0xe8, 0x00, 0x00, 0x06, 0x37, 0x49, 0x44, 0x41, 0x54, 0x68, 0x05, 0xed, 0x59, 0x7b, 0x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x8b, 0x4d, 0x4d, 0x4d, 0xb8, 0x65, 0x1b, 0x1a, 0x1a, 0x6a, 0x6a, 0x6a, 0x10, 0xb3, 0x35, 0x6b, 0xd6, 0xb0, 0xd0, 0xb2, 0x2f, 0x2e, 0x57, 0x0c, 0xd0, 0xa1, 0xa1, 0xa1, 0x6a, 0xfe, 0x74, 0x1a, 0x99, 0xc1, 0x98, 0xce, 0x37, 0xc4, 0xd1, 0x8d, 0x81, 0xc5, 0xa3, 0x80, 0xdf, 0x50, 0xba, 0x1b, 0xff, 0x1d, 0x80, 0xfe, 0x63, 0x0e, 0x37, 0x25, 0xfa, 0x09, 0x1a, 0x36, 0xae, 0xfa, 0xd8, 0xd8, 0xd8, 0xe5, 0xcb, 0x97, 0x1b, 0x0a, 0x98, 0xe8, 0xcd, 0xfa, 0x0e, 0x88, 0xd6, 0x28, 0x58, 0x9e, 0x80, 0x7b, 0x40, 0xb0, 0x45, 0x36, 0x8a, 0x73, 0x38, 0x60, 0x63, 0xc0, 0x84, 0xc3, 0x1d, 0x19, 0x10, 0x1e, 0x52, 0x1b, 0x05, 0x3a, 0x32, 0x60, 0x63, 0xc0, 0x84, 0xc3, 0x5f, 0xf8, 0x0c, 0xfc, 0x0d, 0x80, 0x98, 0xbd, 0xed, 0xf7, 0x50, 0xda, 0x08, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXTextPlainIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x03, 0xa8, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x30, 0x39, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x32, 0x3a, 0x34, 0x33, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e,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xd9, 0x13, 0x09, 0x04, 0x1a, 0xcc, 0x60, 0x30, 0xdc, 0x9d, 0x1b, 0x12, 0x54, 0x09, 0x88, 0xf0, 0xa7, 0x10, 0xec, 0xe1, 0xe5, 0x87, 0x27, 0xa2, 0x1c, 0x1f, 0x1f, 0xdf, 0xde, 0xde, 0x2e, 0x2f, 0x2f, 0xc7, 0x0b, 0xe5, 0xad, 0xa0, 0x1f, 0xb6, 0x41, 0x8e, 0x93, 0x93, 0x93, 0x1f, 0x86, 0xf5, 0x01, 0xc5, 0x0b, 0x0e, 0x6f, 0x2e, 0x9e, 0x32, 0x74, 0x0e, 0x0f, 0xf3, 0x5e, 0x6d, 0xf9, 0x15, 0xc0, 0x47, 0x08, 0xbe, 0x2e, 0xf1, 0x9a, 0x24, 0x61, 0xa0, 0x71, 0x31, 0xd1, 0x79, 0x21, 0xbd, 0x57, 0x5b, 0xf9, 0x7f, 0xa1, 0xc7, 0x2e, 0x07, 0x7f, 0x96, 0x3d, 0xb6, 0x3f, 0xa2, 0xed, 0xcb, 0x01, 0x88, 0x4e, 0x19, 0x65, 0x01, 0xb9, 0x02, 0x94, 0x13, 0x2a, 0x5a, 0x9d, 0x5c, 0x01, 0xd1, 0x29, 0xa3, 0x2c, 0xf0, 0x1f, 0x15, 0xdc, 0xd7, 0x70, 0xbb, 0x15, 0xe8, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXHTMLIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x03, 0xa8, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x30, 0x39, 0x54, 0x32, 0x33, 0x3a, 0x30, 0x32, 0x3a, 0x39, 0x35, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d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, 0x1e, 0x80, 0x97, 0x97, 0x57, 0x48, 0x48, 0x08, 0x34, 0x6a, 0x34, 0x1a, 0x06, 0xbd, 0x5d, 0x5d, 0x5d, 0xa9, 0xa9, 0xa9, 0x65, 0x65, 0x65, 0x0c, 0x3c, 0x0c, 0x4b, 0x9e, 0x9e, 0x9e, 0xd1, 0xd1, 0xd1, 0x41, 0x41, 0x41, 0xe0, 0x59, 0x5f, 0x5f, 0x67, 0xe0, 0x34, 0x5f, 0x62, 0xf3, 0x45, 0x6a, 0x68, 0x68, 0x08, 0x62, 0x22, 0x91, 0x88, 0x81, 0xb9, 0xa5, 0xa5, 0x05, 0x3c, 0x09, 0x09, 0x09, 0x0c, 0x3c, 0x56, 0x97, 0x06, 0x07, 0x07, 0xa1, 0x04, 0x45, 0xb0, 0xca, 0x49, 0x31, 0x58, 0xaf, 0x00, 0x34, 0x52, 0xa3, 0xad, 0xad, 0x2d, 0x32, 0x32, 0x12, 0xd9, 0xca, 0xce, 0xce, 0x56, 0x2a, 0x95, 0x14, 0x8e, 0x36, 0x9b, 0x98, 0x98, 0xc0, 0x54, 0xab, 0xd5, 0xf6, 0xee, 0x8f, 0x81, 0x81, 0x01, 0xd2, 0xd0, 0xd8, 0x3c, 0x39, 0x39, 0x39, 0x89, 0x89, 0x89, 0x8d, 0x8d, 0x8d, 0xe9, 0xe9, 0xe9, 0x90, 0xad, 0xac, 0xac, 0xac, 0xad, 0xad, 0x95, 0x48, 0x24, 0x59, 0x59, 0x59, 0xfd, 0xfd, 0x7b, 0x6f, 0xf2, 0x38, 0x0d, 0x2a, 0x14, 0x06, 0x82, 0x54, 0x00, 0x66, 0x9c, 0x9d, 0x9d, 0x29, 0x63, 0x75, 0x75, 0x75, 0x44, 0x64, 0x78, 0x78, 0x98, 0x02, 0xe9, 0x44, 0x43, 0x43, 0x03, 0x18, 0x96, 0x97, 0x99, 0xde, 0x32, 0x44, 0x45, 0x45, 0xd1, 0xed, 0x3a, 0xbc, 0x02, 0x19, 0x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00, 0x8e, 0x70, 0x91, 0x59, 0xa7, 0xf5, 0x16, 0x62, 0x96, 0x3f, 0xf2, 0x55, 0x3e, 0x80, 0xa3, 0x2e, 0x01, 0x5f, 0x01, 0xbe, 0x02, 0x1c, 0x33, 0xc0, 0xb7, 0x10, 0xc7, 0x04, 0x72, 0x16, 0xe7, 0x2b, 0xc0, 0x39, 0x85, 0x1c, 0x15, 0x1c, 0xfb, 0x0a, 0xfc, 0x0d, 0x0a, 0x08, 0x48, 0x44, 0xec, 0xf6, 0xcb, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXAudioIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x04, 0x24, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x64, 0x63, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x70, 0x75, 0x72, 0x6c, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x64, 0x63, 0x2f, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x31, 0x2e, 0x31, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x42, 0x61, 0x67, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x32, 0x31, 0x54, 0x32, 0x30, 0x3a, 0x30, 0x32, 0x3a, 0x32, 0x39, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 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f6, 0x4b, 0x82, 0x0b, 0x39, 0x76, 0x1f, 0x62, 0x4e, 0xe4, 0x2b, 0xd9, 0xff, 0xf3, 0x04, 0x89, 0x9f, 0x45, 0x48, 0x62, 0xc2, 0xa9, 0xba, 0x9c, 0xd8, 0x35, 0x80, 0x2e, 0x59, 0x7f, 0xcd, 0x4e, 0xeb, 0x20, 0xfe, 0x35, 0xa5, 0xec, 0x41, 0x2a, 0x3b, 0x80, 0x1e, 0x94, 0x33, 0x20, 0x43, 0x76, 0x0b, 0x0c, 0x88, 0x9a, 0x7b, 0x78, 0x89, 0xdd, 0x02, 0x3d, 0x28, 0x67, 0x40, 0x86, 0xec, 0x16, 0x18, 0x10, 0x35, 0xf7, 0xf0, 0x12, 0xbb, 0x05, 0x7a, 0x50, 0xce, 0x80, 0x0c, 0xfd, 0x0b, 0xbe, 0x35, 0x47, 0x3f, 0x08, 0xc9, 0x3b, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXJSIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x04, 0x24, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x64, 0x63, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x70, 0x75, 0x72, 0x6c, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x64, 0x63, 0x2f, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x31, 0x2e, 0x31, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x42, 0x61, 0x67, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x32, 0x31, 0x54, 0x32, 0x30, 0x3a, 0x30, 0x32, 0x3a, 0x38, 0x38, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0x0e, 0x0a, 0xaa, 0x03, 0x00, 0x00, 0x05, 0x39, 0x49, 0x44, 0x41, 0x54, 0x68, 0x05, 0xed, 0x58, 0x7d, 0x48, 0x5b, 0x57, 0x14, 0xcf, 0x8b, 0x2f, 0x31, 0xd1, 0x1a, 0x4d, 0xb4, 0x06, 0xc7, 0xfc, 0x88, 0x55, 0x59, 0x97, 0x5a, 0xf1, 0xb3, 0x43, 0x83, 0xba, 0x32, 0x97, 0x0d, 0x3a, 0x0b, 0x2b, 0x08, 0x75, 0x65, 0x82, 0x8c, 0xc1, 0xdc, 0x1f, 0xab, 0x48, 0xdd, 0x64, 0x62, 0x19, 0x6e, 0x73, 0xc2, 0xa6, 0x83, 0x6e, 0x38, 0x46, 0xff, 0x28, 0xc3, 0x75, 0x6b, 0x51, 0x36, 0x54, 0x56, 0x23, 0x88, 0x3a, 0x3b, 0xa1, 0x22, 0xd4, 0xd8, 0xc9, 0x28, 0x9b, 0x1f, 0x0c, 0xad, 0x4c, 0xa3, 0xb5, 0x89, 0x71, 0xd1, 0x7c, 0xb8, 0x63, 0x9f, 0xb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x4a, 0x4a, 0xca, 0xec, 0xec, 0xec, 0xda, 0xda, 0x9a, 0x4a, 0xa5, 0x4a, 0x4e, 0x4e, 0x96, 0x4a, 0x09, 0x9c, 0x2b, 0x42, 0x16, 0x02, 0x02, 0x7a, 0x7a, 0x7a, 0x26, 0x26, 0x26, 0xd4, 0x6a, 0x35, 0xec, 0xa1, 0xcc, 0xcb, 0xb5, 0xa8, 0xa8, 0x88, 0x2b, 0xe0, 0xd8, 0xd3, 0x0b, 0x3c, 0xe9, 0xe9, 0xe9, 0x5c, 0x3f, 0x19, 0x9b, 0xf7, 0xfe, 0xc5, 0x4e, 0x64, 0xde, 0xb2, 0x2c, 0x9b, 0xaa, 0xaa, 0x2a, 0xf6, 0x56, 0x08, 0x0c, 0x02, 0x3f, 0xe6, 0x96, 0x97, 0x97, 0x61, 0x3f, 0x81, 0xc5, 0xa3, 0x54, 0x2a, 0xf3, 0xf2, 0xf2, 0x72, 0x72, 0x72, 0x58, 0x31, 0x21, 0x30, 0x08, 0x08, 0x08, 0x01, 0x4b, 0x3f, 0x29, 0x42, 0xf1, 0x1e, 0xf0, 0x93, 0x1e, 0xff, 0x96, 0x20, 0x00, 0xbf, 0x86, 0x78, 0x11, 0x84, 0x0e, 0xe0, 0xd5, 0x0f, 0x7f, 0xb6, 0xd0, 0x01, 0xfc, 0x1a, 0xe2, 0x45, 0x38, 0xf2, 0x1d, 0xf8, 0x0f, 0x1c, 0x65, 0x73, 0xb3, 0xdd, 0xbe, 0x50, 0xc7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXPlistIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x04, 0x24, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x64, 0x63, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x70, 0x75, 0x72, 0x6c, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x64, 0x63, 0x2f, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x31, 0x2e, 0x31, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x42, 0x61, 0x67, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x32, 0x31, 0x54, 0x32, 0x30, 0x3a, 0x30, 0x32, 0x3a, 0x33, 0x35, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xc8, 0x4f, 0xd5, 0xc2, 0x00, 0x00, 0x06, 0xa8, 0x49, 0x44, 0x41, 0x54, 0x68, 0x05, 0xed, 0x58, 0x7b, 0x4c, 0x53, 0x57, 0x18, 0xb7, 0xef, 0x77, 0x91, 0x87, 0x82, 0x20, 0x68, 0x01, 0xd1, 0xf8, 0x20, 0x6e, 0x09, 0xd1, 0x44, 0xc1, 0xcc, 0xa0, 0xce, 0x4c, 0x0d, 0xfc, 0xb7, 0x11, 0xa6, 0x93, 0xb0,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, 0x0f, 0x7b, 0x3c, 0x70, 0xd0, 0xa5, 0xfc, 0x34, 0x4e, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXTextIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x04, 0x24, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x64, 0x63, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x70, 0x75, 0x72, 0x6c, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x64, 0x63, 0x2f, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x31, 0x2e, 0x31, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x42, 0x61, 0x67, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x32, 0x31, 0x54, 0x32, 0x30, 0x3a, 0x30, 0x32, 0x3a, 0x38, 0x33, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0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, 0x99, 0x10, 0x67, 0x86, 0x4f, 0xfc, 0x9c, 0xe1, 0x4a, 0x13, 0x14, 0x14, 0x64, 0x58, 0x45, 0x43, 0x80, 0x49, 0x1a, 0xdb, 0x0c, 0xcb, 0xc6, 0xdf, 0xdf, 0x9f, 0xb4, 0xd4, 0x24, 0xde, 0xbc, 0x04, 0x4c, 0x9a, 0xfb, 0xf8, 0x00, 0x5e, 0x57, 0x89, 0x8f, 0x1f, 0x16, 0x7f, 0x8f, 0x42, 0x02, 0xfc, 0x6b, 0xf5, 0x3c, 0x48, 0xa1, 0x03, 0xcf, 0x53, 0x57, 0xfe, 0x56, 0x85, 0x0e, 0xf0, 0xaf, 0xd5, 0xf3, 0x20, 0x85, 0x0e, 0x3c, 0x4f, 0x5d, 0xf9, 0x5b, 0x15, 0x3a, 0xc0, 0xbf, 0x56, 0xcf, 0x83, 0xfc, 0x17, 0xab, 0x70, 0xa9, 0x05, 0xf0, 0x5c, 0xd1, 0x77, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXVideoIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x04, 0x24, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x64, 0x63, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x70, 0x75, 0x72, 0x6c, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x64, 0x63, 0x2f, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x31, 0x2e, 0x31, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x42, 0x61, 0x67, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x32, 0x31, 0x54, 0x32, 0x30, 0x3a, 0x30, 0x32, 0x3a, 0x37, 0x39, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0xcc, 0x4b, 0x33, 0xb9, 0x00, 0x00, 0x09, 0x5f, 0x49, 0x44, 0x41, 0x54, 0x68, 0x05, 0xed, 0x59, 0x7b, 0x4c, 0x54, 0xd9, 0x19, 0x9f, 0x99, 0x7b, 0x67, 0x18, 0x9e, 0x83, 0xc0, 0xcc, 0x30, 0x83, 0x2c, 0xa2, 0x80, 0x3c, 0x15, 0x96, 0xe2, 0xae, 0x8f, 0xd4, 0xf5, 0x11, 0x13, 0xb7, 0xb6, 0x31, 0xa6, 0xd5, 0x08, 0x6a, 0xb4, 0xba, 0x3e, 0x6a, 0x1a, 0x13, 0x63, 0xac, 0x35, 0x21, 0x9a, 0xfe, 0x63, 0x62, 0x8d, 0xb1, 0x35, 0x46, 0x8d, 0xd1, 0xac, 0xa6, 0x35, 0xd1, 0xa6, 0x66, 0xdd, 0x9a, 0xad, 0x31, 0x0d, 0x6e, 0xa3, 0x8d, 0x6f, 0x08, 0x6f, 0x99, 0x05, 0x11, 0x81, 0x85, 0x79, 0xc0, 0xbc, 0x98,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, 0xda, 0x30, 0x31, 0x54, 0xdf, 0x07, 0x00, 0x81, 0x0b, 0x91, 0xed, 0xdb, 0xb7, 0x8b, 0x22, 0xfb, 0xf7, 0xef, 0x47, 0x0b, 0x01, 0x20, 0xea, 0x87, 0x96, 0xb0, 0x92, 0x97, 0x97, 0x07, 0x91, 0x9b, 0x37, 0x6f, 0x92, 0x76, 0x7c, 0x77, 0x12, 0x47, 0x10, 0x1b, 0xe1, 0x10, 0xb1, 0x91, 0x10, 0xef, 0x78, 0xa5, 0xc4, 0xba, 0x41, 0xbc, 0x9e, 0x3f, 0x7f, 0xfe, 0xf2, 0xe5, 0xcb, 0x3d, 0x3d, 0x3d, 0x18, 0xee, 0xc0, 0x81, 0x03, 0x61, 0x93, 0x8d, 0x51, 0x85, 0x38, 0x7a, 0xe1, 0x16, 0x91, 0x27, 0x94, 0xd6, 0xeb, 0xf5, 0xa4, 0xfd, 0xd2, 0xa5, 0x4b, 0x65, 0x65, 0x65, 0x22, 0x0f, 0xdc, 0x42, 0xae, 0x8a, 0xc5, 0x45, 0x88, 0x4f, 0xc8, 0x48, 0x32, 0x84, 0x01, 0x34, 0x08, 0x04, 0x02, 0x2e, 0xf4, 0x45, 0x91, 0x1f, 0x88, 0x30, 0x40, 0xa4, 0xda, 0xd8, 0xd8, 0x88, 0x6e, 0xf8, 0x01, 0xef, 0x7b, 0xb0, 0x28, 0x79, 0x69, 0x0c, 0xe5, 0x84, 0x2b, 0xe1, 0x28, 0x32, 0x04, 0xac, 0x12, 0xba, 0x9f, 0xee, 0xd9, 0xb3, 0x07, 0xed, 0x50, 0xe8, 0xe1, 0xc3, 0x87, 0x10, 0x79, 0xfa, 0xf4, 0x29, 0xd2, 0x05, 0x5a, 0xc4, 0x35, 0x30, 0x7f, 0xfe, 0x7c, 0x54, 0xb1, 0x41, 0x89, 0xab, 0xb6, 0xa5, 0xa5, 0x05, 0x52, 0x27, 0x4e, 0x9c, 0x00, 0xbf, 0xdd, 0x6e, 0x27, 0xfe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, 0x41, 0x1a, 0xfb, 0x3d, 0x82, 0x04, 0x47, 0x09, 0x62, 0xef, 0xd1, 0x52, 0x48, 0x67, 0x58, 0x63, 0x08, 0x74, 0xd1, 0x63, 0x61, 0x3c, 0xd8, 0xb8, 0x31, 0xc8, 0x9c, 0x39, 0x73, 0x48, 0x50, 0x85, 0xf5, 0x92, 0xea, 0x58, 0x00, 0xde, 0x29, 0xf0, 0x53, 0x6b, 0x0c, 0x3f, 0x4a, 0xfc, 0xd4, 0xf4, 0x1b, 0x57, 0x9f, 0x18, 0x80, 0x71, 0x4d, 0x34, 0xcd, 0x0c, 0x31, 0x0f, 0x4c, 0xb3, 0x81, 0xc7, 0x1d, 0x3e, 0xe6, 0x81, 0x71, 0x4d, 0x34, 0xcd, 0x0c, 0x31, 0x0f, 0x4c, 0xb3, 0x81, 0xc7, 0x1d, 0x3e, 0xe6, 0x81, 0x71, 0x4d, 0x34, 0xcd, 0x0c, 0xff, 0x07, 0x71, 0xef, 0x64, 0x50, 0x13, 0xcd, 0x1c, 0x52, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXXMLIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x04, 0x24, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x64, 0x63, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x70, 0x75, 0x72, 0x6c, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x64, 0x63, 0x2f, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x31, 0x2e, 0x31, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x42, 0x61, 0x67, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x32, 0x31, 0x54, 0x32, 0x30, 0x3a, 0x30, 0x32, 0x3a, 0x30, 0x39, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0x9d, 0x3c, 0x78, 0xe3, 0x00, 0x00, 0x05, 0x7c, 0x49, 0x44, 0x41, 0x54, 0x68, 0x05, 0xed, 0x58, 0x59, 0x4c, 0x1b, 0x57, 0x14, 0xc5, 0x0b, 0xbb, 0xc1, 0x26, 0xa2, 0x31, 0x56, 0x58, 0x4c, 0xb1, 0x1b, 0x37, 0x15, 0x8e, 0x42, 0x05, 0x94, 0x25, 0x88, 0x25, 0x6c, 0x05, 0x52, 0x14, 0x0a, 0xfd, 0xa8, 0x08, 0x1f, 0x91, 0xe0, 0x83, 0x02, 0xa2, 0x2a, 0x6a, 0xfb, 0xd3, 0x82, 0x00, 0x15, 0x3e, 0x8a, 0x8a, 0x10, 0x42, 0x42, 0x4a, 0xbf, 0x10, 0x12, 0x84, 0x06, 0xd5, 0x12, 0x15, 0x5b, 0x49, 0x0a, 0x51, 0x31, 0x34, 0xdd, 0x00, 0xa5, 0xb5, 0x4d, 0x42, 0x83, 0xa1, 0x24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0x70, 0x63, 0x72, 0x09, 0xb9, 0xa6, 0x2b, 0x40, 0x28, 0x4d, 0x6e, 0x54, 0xa2, 0x2b, 0xe0, 0xc6, 0xe4, 0x12, 0x72, 0x4d, 0x57, 0x80, 0x50, 0x9a, 0xdc, 0xa8, 0xf4, 0x2f, 0x8a, 0xf9, 0x6c, 0x7c, 0x9d, 0x47, 0x95, 0x15, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +static const u_int8_t FLEXBinaryIcon2x[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x04, 0x24, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e, 0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x64, 0x63, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x70, 0x75, 0x72, 0x6c, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x64, 0x63, 0x2f, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x31, 0x2e, 0x31, 0x2f, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x35, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x31, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x36, 0x34, 0x3c, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x42, 0x61, 0x67, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x63, 0x3a, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x31, 0x35, 0x2d, 0x30, 0x32, 0x2d, 0x32, 0x31, 0x54, 0x32, 0x31, 0x3a, 0x30, 0x32, 0x3a, 0x38, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x6d, 0x61, 0x74, 0x6f, 0x72, 0x20, 0x33, 0x2e, 0x33, 0x2e, 0x31, 0x3c, 0x2f, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 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, 0x0e, 0x60, 0x99, 0x03, 0xdb, 0xee, 0xc7, 0xa5, 0x23, 0x30, 0xc4, 0xf3, 0x91, 0xb6, 0x83, 0x30, 0xc6, 0xfe, 0x60, 0x04, 0x60, 0x73, 0x46, 0x64, 0xbe, 0xc4, 0xc0, 0x92, 0x84, 0x66, 0x1b, 0x38, 0xc2, 0xa7, 0x05, 0x9f, 0x21, 0xa1, 0x2c, 0x5a, 0x42, 0x77, 0x37, 0x38, 0xbc, 0x59, 0x14, 0x1b, 0xd3, 0x30, 0x4c, 0x42, 0x6a, 0x6e, 0x90, 0x81, 0x99, 0x39, 0xb3, 0x62, 0x1a, 0x86, 0x61, 0x43, 0xb2, 0x05, 0x51, 0x00, 0x16, 0x3b, 0x67, 0x7b, 0xe2, 0x8d, 0x26, 0x61, 0x1a, 0x86, 0x89, 0x46, 0xc4, 0xea, 0x33, 0x30, 0x33, 0x67, 0x28, 0xa6, 0x61, 0x18, 0x36, 0x24, 0x5b, 0x10, 0x05, 0x90, 0x8a, 0x2b, 0x27, 0xd4, 0x7c, 0xff, 0x42, 0xd0, 0x2f, 0xe0, 0x39, 0x0e, 0x1f, 0x6d, 0x0c, 0x23, 0x18, 0x8e, 0xd3, 0x61, 0x60, 0xbd, 0x08, 0x85, 0x7e, 0x44, 0x01, 0x64, 0x3c, 0xc6, 0x01, 0x02, 0x7e, 0x72, 0x62, 0xf2, 0xdb, 0xee, 0x3c, 0xd7, 0x63, 0x18, 0xfe, 0x68, 0x3c, 0x99, 0x81, 0xf5, 0x22, 0x14, 0x3a, 0x12, 0x05, 0xf0, 0xf0, 0x93, 0xc0, 0x96, 0xe6, 0xca, 0xcf, 0x11, 0x30, 0xde, 0xa6, 0x7f, 0xdf, 0xe6, 0xba, 0x67, 0x4a, 0x23, 0x7a, 0x49, 0x49, 0x77, 0x42, 0xa1, 0x47, 0x51, 0x00, 0x78, 0x56, 0x9c, 0xbb, 0xc4, 0x61, 0x6e, 0x74, 0x82, 0x3f, 0x74, 0x25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5, 0x07, 0xd0, 0xdf, 0xdf, 0xbf, 0xba, 0xba, 0x8a, 0x85, 0xee, 0xed, 0xed, 0xc5, 0x5d, 0x8b, 0x4e, 0x4a, 0x4b, 0x23, 0x2f, 0x76, 0x78, 0x59, 0xe3, 0x4d, 0x4c, 0x3d, 0xf3, 0x65, 0xd4, 0xa0, 0x09, 0xd5, 0x53, 0x21, 0x10, 0x08, 0xf0, 0xbb, 0x54, 0x56, 0xf0, 0x2b, 0x73, 0xa9, 0x31, 0x58, 0x4d, 0x4d, 0x0d, 0x63, 0xc7, 0xab, 0x8a, 0x6e, 0x68, 0xd4, 0x14, 0x15, 0x15, 0x61, 0x29, 0x28, 0xac, 0xac, 0xac, 0x8c, 0x61, 0x98, 0x80, 0x2b, 0xed, 0xf8, 0xf8, 0x18, 0x37, 0x7a, 0x46, 0x46, 0x06, 0x55, 0xa2, 0x06, 0x4f, 0xd8, 0xac, 0xac, 0x2c, 0xda, 0xcd, 0xcc, 0xcc, 0xc4, 0xcb, 0x91, 0x39, 0x92, 0x29, 0x28, 0xae, 0x80, 0xd9, 0x4c, 0x4c, 0x1c, 0x0e, 0x47, 0x47, 0x47, 0x07, 0x26, 0x6f, 0x71, 0x71, 0x11, 0xd7, 0x40, 0x7d, 0x7d, 0xfd, 0xc8, 0xc8, 0x88, 0xd5, 0x6a, 0xa5, 0x53, 0xa1, 0x18, 0x2a, 0xb3, 0x5f, 0x54, 0xe2, 0x9c, 0xb0, 0x8b, 0x61, 0x53, 0x25, 0xde, 0xd3, 0xc8, 0xc0, 0xef, 0x52, 0x00, 0x33, 0x91, 0x23, 0x68, 0x7a, 0x56, 0xc1, 0x6d, 0xb7, 0xb0, 0xb0, 0x80, 0xbb, 0x10, 0x0f, 0x75, 0x39, 0xce, 0x92, 0x81, 0xd1, 0x14, 0x40, 0x32, 0x26, 0xa4, 0x94, 0x53, 0xf1, 0x12, 0x52, 0xea, 0x20, 0xd9, 0x78, 0x23, 0x80, 0x64, 0x67, 0x58, 0x8a, 0xdf, 0xa8, 0x80, 0x54, 0x86, 0x92, 0x3d, 0x6e, 0x54, 0x20, 0xd9, 0x19, 0x96, 0xe2, 0x37, 0x2a, 0x20, 0x95, 0xa1, 0x64, 0x8f, 0x1b, 0x15, 0x48, 0x76, 0x86, 0xa5, 0xf8, 0xff, 0x03, 0xf5, 0x1a, 0x5a, 0xe0, 0xcf, 0xeb, 0xd5, 0xa2, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; + +@implementation FLEXResources + + +#pragma mark - Images + +#define FLEXImage(base) (([[UIScreen mainScreen] scale] > 1.5) ? \ + [self imageWithBytesNoCopy:(void *)base##2x length:sizeof(base##2x) scale:2.0] : \ + [self imageWithBytesNoCopy:(void *)base length:sizeof(base) scale:1.0]) + +#define FLEXRetinaOnlyImage(base) ([self imageWithBytesNoCopy:(void *)(base) length:sizeof(base) scale:2.0]) + ++ (UIImage *)closeIcon +{ + return FLEXImage(FLEXCloseIcon); +} + ++ (UIImage *)dragHandle +{ + return FLEXImage(FLEXDragHandle); +} + ++ (UIImage *)globeIcon +{ + return FLEXImage(FLEXGlobeIcon); +} + ++ (UIImage *)hierarchyIndentPattern +{ + return FLEXImage(FLEXHierarchyIndentPattern); +} + ++ (UIImage *)listIcon +{ + return FLEXImage(FLEXListIcon); +} + ++ (UIImage *)moveIcon +{ + return FLEXImage(FLEXMoveIcon); +} + ++ (UIImage *)selectIcon +{ + return FLEXImage(FLEXSelectIcon); +} + ++ (UIImage *)jsonIcon +{ + return FLEXRetinaOnlyImage(FLEXJSONIcon2x); +} + ++ (UIImage *)textPlainIcon +{ + return FLEXRetinaOnlyImage(FLEXTextPlainIcon2x); +} + ++ (UIImage *)htmlIcon +{ + return FLEXRetinaOnlyImage(FLEXHTMLIcon2x); +} + ++ (UIImage *)audioIcon +{ + return FLEXRetinaOnlyImage(FLEXAudioIcon2x); +} + ++ (UIImage *)jsIcon +{ + return FLEXRetinaOnlyImage(FLEXJSIcon2x); +} + ++ (UIImage *)plistIcon +{ + return FLEXRetinaOnlyImage(FLEXPlistIcon2x); +} + ++ (UIImage *)textIcon +{ + return FLEXRetinaOnlyImage(FLEXTextIcon2x); +} + ++ (UIImage *)videoIcon +{ + return FLEXRetinaOnlyImage(FLEXVideoIcon2x); +} + ++ (UIImage *)xmlIcon +{ + return FLEXRetinaOnlyImage(FLEXXMLIcon2x); +} + ++ (UIImage *)binaryIcon +{ + return FLEXRetinaOnlyImage(FLEXBinaryIcon2x); +} + +#undef FLEXImage +#undef FLEXRetinaOnlyImage + + +#pragma mark - Helpers + ++ (UIImage *)imageWithBytesNoCopy:(void *)bytes length:(NSUInteger)length scale:(CGFloat)scale +{ + NSData *data = [NSData dataWithBytesNoCopy:bytes length:length freeWhenDone:NO]; + return [UIImage imageWithData:data scale:scale]; +} + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXRuntimeUtility.h b/Pods/FLEX/Classes/Utility/FLEXRuntimeUtility.h new file mode 100644 index 0000000000..e1e2ba34a8 --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXRuntimeUtility.h @@ -0,0 +1,59 @@ +// +// FLEXRuntimeUtility.h +// Flipboard +// +// Created by Ryan Olson on 6/8/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import +#import + +extern const unsigned int kFLEXNumberOfImplicitArgs; + +// See https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW6 +extern NSString *const kFLEXUtilityAttributeTypeEncoding; +extern NSString *const kFLEXUtilityAttributeBackingIvar; +extern NSString *const kFLEXUtilityAttributeReadOnly; +extern NSString *const kFLEXUtilityAttributeCopy; +extern NSString *const kFLEXUtilityAttributeRetain; +extern NSString *const kFLEXUtilityAttributeNonAtomic; +extern NSString *const kFLEXUtilityAttributeCustomGetter; +extern NSString *const kFLEXUtilityAttributeCustomSetter; +extern NSString *const kFLEXUtilityAttributeDynamic; +extern NSString *const kFLEXUtilityAttributeWeak; +extern NSString *const kFLEXUtilityAttributeGarbageCollectable; +extern NSString *const kFLEXUtilityAttributeOldStyleTypeEncoding; + +#define FLEXEncodeClass(class) ("@\"" #class "\"") + +@interface FLEXRuntimeUtility : NSObject + +// Property Helpers ++ (NSString *)prettyNameForProperty:(objc_property_t)property; ++ (NSString *)typeEncodingForProperty:(objc_property_t)property; ++ (BOOL)isReadonlyProperty:(objc_property_t)property; ++ (SEL)setterSelectorForProperty:(objc_property_t)property; ++ (NSString *)fullDescriptionForProperty:(objc_property_t)property; ++ (id)valueForProperty:(objc_property_t)property onObject:(id)object; ++ (NSString *)descriptionForIvarOrPropertyValue:(id)value; ++ (void)tryAddPropertyWithName:(const char *)name attributes:(NSDictionary *)attributePairs toClass:(__unsafe_unretained Class)theClass; + +// Ivar Helpers ++ (NSString *)prettyNameForIvar:(Ivar)ivar; ++ (id)valueForIvar:(Ivar)ivar onObject:(id)object; ++ (void)setValue:(id)value forIvar:(Ivar)ivar onObject:(id)object; + +// Method Helpers ++ (NSString *)prettyNameForMethod:(Method)method isClassMethod:(BOOL)isClassMethod; ++ (NSArray *)prettyArgumentComponentsForMethod:(Method)method; + +// Method Calling/Field Editing ++ (id)performSelector:(SEL)selector onObject:(id)object withArguments:(NSArray *)arguments error:(NSError * __autoreleasing *)error; ++ (NSString *)editableJSONStringForObject:(id)object; ++ (id)objectValueFromEditableJSONString:(NSString *)string; ++ (NSValue *)valueForNumberWithObjCType:(const char *)typeEncoding fromInputString:(NSString *)inputString; ++ (void)enumerateTypesInStructEncoding:(const char *)structEncoding usingBlock:(void (^)(NSString *structName, const char *fieldTypeEncoding, NSString *prettyTypeEncoding, NSUInteger fieldIndex, NSUInteger fieldOffset))typeBlock; ++ (NSValue *)valueForPrimitivePointer:(void *)pointer objCType:(const char *)type; + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXRuntimeUtility.m b/Pods/FLEX/Classes/Utility/FLEXRuntimeUtility.m new file mode 100644 index 0000000000..52b951bae9 --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXRuntimeUtility.m @@ -0,0 +1,708 @@ +// +// FLEXRuntimeUtility.m +// Flipboard +// +// Created by Ryan Olson on 6/8/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import +#import "FLEXRuntimeUtility.h" + +// See https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW6 +NSString *const kFLEXUtilityAttributeTypeEncoding = @"T"; +NSString *const kFLEXUtilityAttributeBackingIvar = @"V"; +NSString *const kFLEXUtilityAttributeReadOnly = @"R"; +NSString *const kFLEXUtilityAttributeCopy = @"C"; +NSString *const kFLEXUtilityAttributeRetain = @"&"; +NSString *const kFLEXUtilityAttributeNonAtomic = @"N"; +NSString *const kFLEXUtilityAttributeCustomGetter = @"G"; +NSString *const kFLEXUtilityAttributeCustomSetter = @"S"; +NSString *const kFLEXUtilityAttributeDynamic = @"D"; +NSString *const kFLEXUtilityAttributeWeak = @"W"; +NSString *const kFLEXUtilityAttributeGarbageCollectable = @"P"; +NSString *const kFLEXUtilityAttributeOldStyleTypeEncoding = @"t"; + +static NSString *const FLEXRuntimeUtilityErrorDomain = @"FLEXRuntimeUtilityErrorDomain"; +typedef NS_ENUM(NSInteger, FLEXRuntimeUtilityErrorCode) { + FLEXRuntimeUtilityErrorCodeDoesNotRecognizeSelector = 0, + FLEXRuntimeUtilityErrorCodeInvocationFailed = 1, + FLEXRuntimeUtilityErrorCodeArgumentTypeMismatch = 2 +}; + +// Arguments 0 and 1 are self and _cmd always +const unsigned int kFLEXNumberOfImplicitArgs = 2; + +@implementation FLEXRuntimeUtility + + +#pragma mark - Property Helpers (Public) + ++ (NSString *)prettyNameForProperty:(objc_property_t)property +{ + NSString *name = @(property_getName(property)); + NSString *encoding = [self typeEncodingForProperty:property]; + NSString *readableType = [self readableTypeForEncoding:encoding]; + return [self appendName:name toType:readableType]; +} + ++ (NSString *)typeEncodingForProperty:(objc_property_t)property +{ + NSDictionary *attributesDictionary = [self attributesDictionaryForProperty:property]; + return attributesDictionary[kFLEXUtilityAttributeTypeEncoding]; +} + ++ (BOOL)isReadonlyProperty:(objc_property_t)property +{ + return [[self attributesDictionaryForProperty:property] objectForKey:kFLEXUtilityAttributeReadOnly] != nil; +} + ++ (SEL)setterSelectorForProperty:(objc_property_t)property +{ + SEL setterSelector = NULL; + NSString *setterSelectorString = [[self attributesDictionaryForProperty:property] objectForKey:kFLEXUtilityAttributeCustomSetter]; + if (!setterSelectorString) { + NSString *propertyName = @(property_getName(property)); + setterSelectorString = [NSString stringWithFormat:@"set%@%@:", [[propertyName substringToIndex:1] uppercaseString], [propertyName substringFromIndex:1]]; + } + if (setterSelectorString) { + setterSelector = NSSelectorFromString(setterSelectorString); + } + return setterSelector; +} + ++ (NSString *)fullDescriptionForProperty:(objc_property_t)property +{ + NSDictionary *attributesDictionary = [self attributesDictionaryForProperty:property]; + NSMutableArray *attributesStrings = [NSMutableArray array]; + + // Atomicity + if (attributesDictionary[kFLEXUtilityAttributeNonAtomic]) { + [attributesStrings addObject:@"nonatomic"]; + } else { + [attributesStrings addObject:@"atomic"]; + } + + // Storage + if (attributesDictionary[kFLEXUtilityAttributeRetain]) { + [attributesStrings addObject:@"strong"]; + } else if (attributesDictionary[kFLEXUtilityAttributeCopy]) { + [attributesStrings addObject:@"copy"]; + } else if (attributesDictionary[kFLEXUtilityAttributeWeak]) { + [attributesStrings addObject:@"weak"]; + } else { + [attributesStrings addObject:@"assign"]; + } + + // Mutability + if (attributesDictionary[kFLEXUtilityAttributeReadOnly]) { + [attributesStrings addObject:@"readonly"]; + } else { + [attributesStrings addObject:@"readwrite"]; + } + + // Custom getter/setter + NSString *customGetter = attributesDictionary[kFLEXUtilityAttributeCustomGetter]; + NSString *customSetter = attributesDictionary[kFLEXUtilityAttributeCustomSetter]; + if (customGetter) { + [attributesStrings addObject:[NSString stringWithFormat:@"getter=%@", customGetter]]; + } + if (customSetter) { + [attributesStrings addObject:[NSString stringWithFormat:@"setter=%@", customSetter]]; + } + + NSString *attributesString = [attributesStrings componentsJoinedByString:@", "]; + NSString *shortName = [self prettyNameForProperty:property]; + + return [NSString stringWithFormat:@"@property (%@) %@", attributesString, shortName]; +} + ++ (id)valueForProperty:(objc_property_t)property onObject:(id)object +{ + NSString *customGetterString = nil; + char *customGetterName = property_copyAttributeValue(property, "G"); + if (customGetterName) { + customGetterString = @(customGetterName); + free(customGetterName); + } + + SEL getterSelector; + if ([customGetterString length] > 0) { + getterSelector = NSSelectorFromString(customGetterString); + } else { + NSString *propertyName = @(property_getName(property)); + getterSelector = NSSelectorFromString(propertyName); + } + + return [self performSelector:getterSelector onObject:object withArguments:nil error:NULL]; +} + ++ (NSString *)descriptionForIvarOrPropertyValue:(id)value +{ + NSString *description = nil; + + // Special case BOOL for better readability. + if ([value isKindOfClass:[NSValue class]]) { + const char *type = [value objCType]; + if (strcmp(type, @encode(BOOL)) == 0) { + BOOL boolValue = NO; + [value getValue:&boolValue]; + description = boolValue ? @"YES" : @"NO"; + } else if (strcmp(type, @encode(SEL)) == 0) { + SEL selector = NULL; + [value getValue:&selector]; + description = NSStringFromSelector(selector); + } + } + + if (!description) { + // Single line display - replace newlines and tabs with spaces. + description = [[value description] stringByReplacingOccurrencesOfString:@"\n" withString:@" "]; + description = [description stringByReplacingOccurrencesOfString:@"\t" withString:@" "]; + } + + if (!description) { + description = @"nil"; + } + + return description; +} + ++ (void)tryAddPropertyWithName:(const char *)name attributes:(NSDictionary *)attributePairs toClass:(__unsafe_unretained Class)theClass +{ + objc_property_t property = class_getProperty(theClass, name); + if (!property) { + unsigned int totalAttributesCount = (unsigned int)[attributePairs count]; + objc_property_attribute_t *attributes = malloc(sizeof(objc_property_attribute_t) * totalAttributesCount); + if (attributes) { + unsigned int attributeIndex = 0; + for (NSString *attributeName in [attributePairs allKeys]) { + objc_property_attribute_t attribute; + attribute.name = [attributeName UTF8String]; + attribute.value = [attributePairs[attributeName] UTF8String]; + attributes[attributeIndex++] = attribute; + } + + class_addProperty(theClass, name, attributes, totalAttributesCount); + free(attributes); + } + } +} + + +#pragma mark - Ivar Helpers (Public) + ++ (NSString *)prettyNameForIvar:(Ivar)ivar +{ + const char *nameCString = ivar_getName(ivar); + NSString *name = nameCString ? @(nameCString) : nil; + const char *encodingCString = ivar_getTypeEncoding(ivar); + NSString *encoding = encodingCString ? @(encodingCString) : nil; + NSString *readableType = [self readableTypeForEncoding:encoding]; + return [self appendName:name toType:readableType]; +} + ++ (id)valueForIvar:(Ivar)ivar onObject:(id)object +{ + id value = nil; + const char *type = ivar_getTypeEncoding(ivar); +#ifdef __arm64__ + // See http://www.sealiesoftware.com/blog/archive/2013/09/24/objc_explain_Non-pointer_isa.html + const char *name = ivar_getName(ivar); + if (type[0] == @encode(Class)[0] && strcmp(name, "isa") == 0) { + value = object_getClass(object); + } else +#endif + if (type[0] == @encode(id)[0] || type[0] == @encode(Class)[0]) { + value = object_getIvar(object, ivar); + } else { + ptrdiff_t offset = ivar_getOffset(ivar); + void *pointer = (__bridge void *)object + offset; + value = [self valueForPrimitivePointer:pointer objCType:type]; + } + return value; +} + ++ (void)setValue:(id)value forIvar:(Ivar)ivar onObject:(id)object +{ + const char *typeEncodingCString = ivar_getTypeEncoding(ivar); + if (typeEncodingCString[0] == '@') { + object_setIvar(object, ivar, value); + } else if ([value isKindOfClass:[NSValue class]]) { + // Primitive - unbox the NSValue. + NSValue *valueValue = (NSValue *)value; + + // Make sure that the box contained the correct type. + NSAssert(strcmp([valueValue objCType], typeEncodingCString) == 0, @"Type encoding mismatch (value: %s; ivar: %s) in setting ivar named: %s on object: %@", [valueValue objCType], typeEncodingCString, ivar_getName(ivar), object); + + NSUInteger bufferSize = 0; + @try { + // NSGetSizeAndAlignment barfs on type encoding for bitfields. + NSGetSizeAndAlignment(typeEncodingCString, &bufferSize, NULL); + } @catch (NSException *exception) { } + if (bufferSize > 0) { + void *buffer = calloc(bufferSize, 1); + [valueValue getValue:buffer]; + ptrdiff_t offset = ivar_getOffset(ivar); + void *pointer = (__bridge void *)object + offset; + memcpy(pointer, buffer, bufferSize); + free(buffer); + } + } +} + + +#pragma mark - Method Helpers (Public) + ++ (NSString *)prettyNameForMethod:(Method)method isClassMethod:(BOOL)isClassMethod +{ + NSString *selectorName = NSStringFromSelector(method_getName(method)); + NSString *methodTypeString = isClassMethod ? @"+" : @"-"; + char *returnType = method_copyReturnType(method); + NSString *readableReturnType = [self readableTypeForEncoding:@(returnType)]; + free(returnType); + NSString *prettyName = [NSString stringWithFormat:@"%@ (%@)", methodTypeString, readableReturnType]; + NSArray *components = [self prettyArgumentComponentsForMethod:method]; + if ([components count] > 0) { + prettyName = [prettyName stringByAppendingString:[components componentsJoinedByString:@" "]]; + } else { + prettyName = [prettyName stringByAppendingString:selectorName]; + } + + return prettyName; +} + ++ (NSArray *)prettyArgumentComponentsForMethod:(Method)method +{ + NSMutableArray *components = [NSMutableArray array]; + + NSString *selectorName = NSStringFromSelector(method_getName(method)); + NSArray *selectorComponents = [selectorName componentsSeparatedByString:@":"]; + unsigned int numberOfArguments = method_getNumberOfArguments(method); + + for (unsigned int argIndex = kFLEXNumberOfImplicitArgs; argIndex < numberOfArguments; argIndex++) { + char *argType = method_copyArgumentType(method, argIndex); + NSString *readableArgType = [self readableTypeForEncoding:@(argType)]; + free(argType); + NSString *prettyComponent = [NSString stringWithFormat:@"%@:(%@) ", [selectorComponents objectAtIndex:argIndex - kFLEXNumberOfImplicitArgs], readableArgType]; + [components addObject:prettyComponent]; + } + + return components; +} + + +#pragma mark - Method Calling/Field Editing (Public) + ++ (id)performSelector:(SEL)selector onObject:(id)object withArguments:(NSArray *)arguments error:(NSError * __autoreleasing *)error +{ + // Bail if the object won't respond to this selector. + if (![object respondsToSelector:selector]) { + if (error) { + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"%@ does not respond to the selector %@", object, NSStringFromSelector(selector)]}; + *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeDoesNotRecognizeSelector userInfo:userInfo]; + } + return nil; + } + + // Build the invocation + NSMethodSignature *methodSignature = [object methodSignatureForSelector:selector]; + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature]; + [invocation setSelector:selector]; + [invocation setTarget:object]; + [invocation retainArguments]; + + // Always self and _cmd + NSUInteger numberOfArguments = [methodSignature numberOfArguments]; + for (NSUInteger argumentIndex = kFLEXNumberOfImplicitArgs; argumentIndex < numberOfArguments; argumentIndex++) { + NSUInteger argumentsArrayIndex = argumentIndex - kFLEXNumberOfImplicitArgs; + id argumentObject = [arguments count] > argumentsArrayIndex ? arguments[argumentsArrayIndex] : nil; + + // NSNull in the arguments array can be passed as a placeholder to indicate nil. We only need to set the argument if it will be non-nil. + if (argumentObject && ![argumentObject isKindOfClass:[NSNull class]]) { + const char *typeEncodingCString = [methodSignature getArgumentTypeAtIndex:argumentIndex]; + if (typeEncodingCString[0] == @encode(id)[0] || typeEncodingCString[0] == @encode(Class)[0] || [self isTollFreeBridgedValue:argumentObject forCFType:typeEncodingCString]) { + // Object + [invocation setArgument:&argumentObject atIndex:argumentIndex]; + } else if (strcmp(typeEncodingCString, @encode(CGColorRef)) == 0 && [argumentObject isKindOfClass:[UIColor class]]) { + // Bridging UIColor to CGColorRef + CGColorRef colorRef = [argumentObject CGColor]; + [invocation setArgument:&colorRef atIndex:argumentIndex]; + } else if ([argumentObject isKindOfClass:[NSValue class]]) { + // Primitive boxed in NSValue + NSValue *argumentValue = (NSValue *)argumentObject; + + // Ensure that the type encoding on the NSValue matches the type encoding of the argument in the method signature + if (strcmp([argumentValue objCType], typeEncodingCString) != 0) { + if (error) { + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Type encoding mismatch for agrument at index %lu. Value type: %s; Method argument type: %s.", (unsigned long)argumentsArrayIndex, [argumentValue objCType], typeEncodingCString]}; + *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeArgumentTypeMismatch userInfo:userInfo]; + } + return nil; + } + + NSUInteger bufferSize = 0; + @try { + // NSGetSizeAndAlignment barfs on type encoding for bitfields. + NSGetSizeAndAlignment(typeEncodingCString, &bufferSize, NULL); + } @catch (NSException *exception) { } + + if (bufferSize > 0) { + void *buffer = calloc(bufferSize, 1); + [argumentValue getValue:buffer]; + [invocation setArgument:buffer atIndex:argumentIndex]; + free(buffer); + } + } + } + } + + // Try to invoke the invocation but guard against an exception being thrown. + BOOL successfullyInvoked = NO; + @try { + // Some methods are not fit to be called... + // Looking at you -[UIResponder(UITextInputAdditions) _caretRect] + [invocation invoke]; + successfullyInvoked = YES; + } @catch (NSException *exception) { + // Bummer... + if (error) { + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Exception thrown while performing selector %@ on object %@", NSStringFromSelector(selector), object]}; + *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeInvocationFailed userInfo:userInfo]; + } + } + + // Retreive the return value and box if necessary. + id returnObject = nil; + if (successfullyInvoked) { + const char *returnType = [methodSignature methodReturnType]; + if (returnType[0] == @encode(id)[0] || returnType[0] == @encode(Class)[0]) { + __unsafe_unretained id objectReturnedFromMethod = nil; + [invocation getReturnValue:&objectReturnedFromMethod]; + returnObject = objectReturnedFromMethod; + } else if (returnType[0] != @encode(void)[0]) { + void *returnValue = malloc([methodSignature methodReturnLength]); + if (returnValue) { + [invocation getReturnValue:returnValue]; + returnObject = [self valueForPrimitivePointer:returnValue objCType:returnType]; + free(returnValue); + } + } + } + + return returnObject; +} + ++ (BOOL)isTollFreeBridgedValue:(id)value forCFType:(const char *)typeEncoding +{ + // See https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Toll-FreeBridgin/Toll-FreeBridgin.html +#define CASE(cftype, foundationClass) \ + if(strcmp(typeEncoding, @encode(cftype)) == 0) { \ + return [value isKindOfClass:[foundationClass class]]; \ + } + + CASE(CFArrayRef, NSArray); + CASE(CFAttributedStringRef, NSAttributedString); + CASE(CFCalendarRef, NSCalendar); + CASE(CFCharacterSetRef, NSCharacterSet); + CASE(CFDataRef, NSData); + CASE(CFDateRef, NSDate); + CASE(CFDictionaryRef, NSDictionary); + CASE(CFErrorRef, NSError); + CASE(CFLocaleRef, NSLocale); + CASE(CFMutableArrayRef, NSMutableArray); + CASE(CFMutableAttributedStringRef, NSMutableAttributedString); + CASE(CFMutableCharacterSetRef, NSMutableCharacterSet); + CASE(CFMutableDataRef, NSMutableData); + CASE(CFMutableDictionaryRef, NSMutableDictionary); + CASE(CFMutableSetRef, NSMutableSet); + CASE(CFMutableStringRef, NSMutableString); + CASE(CFNumberRef, NSNumber); + CASE(CFReadStreamRef, NSInputStream); + CASE(CFRunLoopTimerRef, NSTimer); + CASE(CFSetRef, NSSet); + CASE(CFStringRef, NSString); + CASE(CFTimeZoneRef, NSTimeZone); + CASE(CFURLRef, NSURL); + CASE(CFWriteStreamRef, NSOutputStream); + +#undef CASE + + return NO; +} + ++ (NSString *)editableJSONStringForObject:(id)object +{ + NSString *editableDescription = nil; + + if (object) { + // This is a hack to use JSON serialization for our editable objects. + // NSJSONSerialization doesn't allow writing fragments - the top level object must be an array or dictionary. + // We always wrap the object inside an array and then strip the outer square braces off the final string. + NSArray *wrappedObject = @[object]; + if ([NSJSONSerialization isValidJSONObject:wrappedObject]) { + NSString *wrappedDescription = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:wrappedObject options:0 error:NULL] encoding:NSUTF8StringEncoding]; + editableDescription = [wrappedDescription substringWithRange:NSMakeRange(1, [wrappedDescription length] - 2)]; + } + } + + return editableDescription; +} + ++ (id)objectValueFromEditableJSONString:(NSString *)string +{ + id value = nil; + // nil for empty string/whitespace + if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0) { + value = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:NULL]; + } + return value; +} + ++ (NSValue *)valueForNumberWithObjCType:(const char *)typeEncoding fromInputString:(NSString *)inputString +{ + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; + NSNumber *number = [formatter numberFromString:inputString]; + + // Make sure we box the number with the correct type encoding so it can be propperly unboxed later via getValue: + NSValue *value = nil; + if (strcmp(typeEncoding, @encode(char)) == 0) { + char primitiveValue = [number charValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(int)) == 0) { + int primitiveValue = [number intValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(short)) == 0) { + short primitiveValue = [number shortValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(long)) == 0) { + long primitiveValue = [number longValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(long long)) == 0) { + long long primitiveValue = [number longLongValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(unsigned char)) == 0) { + unsigned char primitiveValue = [number unsignedCharValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(unsigned int)) == 0) { + unsigned int primitiveValue = [number unsignedIntValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(unsigned short)) == 0) { + unsigned short primitiveValue = [number unsignedShortValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(unsigned long)) == 0) { + unsigned long primitiveValue = [number unsignedLongValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(unsigned long long)) == 0) { + unsigned long long primitiveValue = [number unsignedLongValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(float)) == 0) { + float primitiveValue = [number floatValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } else if (strcmp(typeEncoding, @encode(double)) == 0) { + double primitiveValue = [number doubleValue]; + value = [NSValue value:&primitiveValue withObjCType:typeEncoding]; + } + + return value; +} + ++ (void)enumerateTypesInStructEncoding:(const char *)structEncoding usingBlock:(void (^)(NSString *structName, const char *fieldTypeEncoding, NSString *prettyTypeEncoding, NSUInteger fieldIndex, NSUInteger fieldOffset))typeBlock +{ + if (structEncoding && structEncoding[0] == '{') { + const char *equals = strchr(structEncoding, '='); + if (equals) { + const char *nameStart = structEncoding + 1; + NSString *structName = [@(structEncoding) substringWithRange:NSMakeRange(nameStart - structEncoding, equals - nameStart)]; + + NSUInteger fieldAlignment = 0; + NSUInteger structSize = 0; + @try { + // NSGetSizeAndAlignment barfs on type encoding for bitfields. + NSGetSizeAndAlignment(structEncoding, &structSize, &fieldAlignment); + } @catch (NSException *exception) { } + + if (structSize > 0) { + NSUInteger runningFieldIndex = 0; + NSUInteger runningFieldOffset = 0; + const char *typeStart = equals + 1; + while (*typeStart != '}') { + NSUInteger fieldSize = 0; + // If the struct type encoding was successfully handled by NSGetSizeAndAlignment above, we *should* be ok with the field here. + const char *nextTypeStart = NSGetSizeAndAlignment(typeStart, &fieldSize, NULL); + NSString *typeEncoding = [@(structEncoding) substringWithRange:NSMakeRange(typeStart - structEncoding, nextTypeStart - typeStart)]; + typeBlock(structName, [typeEncoding UTF8String], [self readableTypeForEncoding:typeEncoding], runningFieldIndex, runningFieldOffset); + runningFieldOffset += fieldSize; + // Padding to keep propper alignment. __attribute((packed)) structs will break here. + // The type encoding is no different for packed structs, so it's not clear there's anything we can do for those. + if (runningFieldOffset % fieldAlignment != 0) { + runningFieldOffset += fieldAlignment - runningFieldOffset % fieldAlignment; + } + runningFieldIndex++; + typeStart = nextTypeStart; + } + } + } + } +} + + +#pragma mark - Internal Helpers + ++ (NSDictionary *)attributesDictionaryForProperty:(objc_property_t)property +{ + NSString *attributes = @(property_getAttributes(property)); + // Thanks to MAObjcRuntime for inspiration here. + NSArray *attributePairs = [attributes componentsSeparatedByString:@","]; + NSMutableDictionary *attributesDictionary = [NSMutableDictionary dictionaryWithCapacity:[attributePairs count]]; + for (NSString *attributePair in attributePairs) { + [attributesDictionary setObject:[attributePair substringFromIndex:1] forKey:[attributePair substringToIndex:1]]; + } + return attributesDictionary; +} + ++ (NSString *)appendName:(NSString *)name toType:(NSString *)type +{ + NSString *combined = nil; + if ([type characterAtIndex:[type length] - 1] == '*') { + combined = [type stringByAppendingString:name]; + } else { + combined = [type stringByAppendingFormat:@" %@", name]; + } + return combined; +} + ++ (NSString *)readableTypeForEncoding:(NSString *)encodingString +{ + if (!encodingString) { + return nil; + } + + // See https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html + // class-dump has a much nicer and much more complete implementation for this task, but it is distributed under GPLv2 :/ + // See https://github.com/nygard/class-dump/blob/master/Source/CDType.m + // Warning: this method uses multiple middle returns and macros to cut down on boilerplate. + // The use of macros here was inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html + const char *encodingCString = [encodingString UTF8String]; + + // Objects + if (encodingCString[0] == '@') { + NSString *class = [encodingString substringFromIndex:1]; + class = [class stringByReplacingOccurrencesOfString:@"\"" withString:@""]; + if ([class length] == 0 || [class isEqual:@"?"]) { + class = @"id"; + } else { + class = [class stringByAppendingString:@" *"]; + } + return class; + } + + // C Types +#define TRANSLATE(ctype) \ + if (strcmp(encodingCString, @encode(ctype)) == 0) { \ + return (NSString *)CFSTR(#ctype); \ + } + + // Order matters here since some of the cocoa types are typedefed to c types. + // We can't recover the exact mapping, but we choose to prefer the cocoa types. + // This is not an exhaustive list, but it covers the most common types + TRANSLATE(CGRect); + TRANSLATE(CGPoint); + TRANSLATE(CGSize); + TRANSLATE(UIEdgeInsets); + TRANSLATE(UIOffset); + TRANSLATE(NSRange); + TRANSLATE(CGAffineTransform); + TRANSLATE(CATransform3D); + TRANSLATE(CGColorRef); + TRANSLATE(CGPathRef); + TRANSLATE(CGContextRef); + TRANSLATE(NSInteger); + TRANSLATE(NSUInteger); + TRANSLATE(CGFloat); + TRANSLATE(BOOL); + TRANSLATE(int); + TRANSLATE(short); + TRANSLATE(long); + TRANSLATE(long long); + TRANSLATE(unsigned char); + TRANSLATE(unsigned int); + TRANSLATE(unsigned short); + TRANSLATE(unsigned long); + TRANSLATE(unsigned long long); + TRANSLATE(float); + TRANSLATE(double); + TRANSLATE(long double); + TRANSLATE(char *); + TRANSLATE(Class); + TRANSLATE(objc_property_t); + TRANSLATE(Ivar); + TRANSLATE(Method); + TRANSLATE(Category); + TRANSLATE(NSZone *); + TRANSLATE(SEL); + TRANSLATE(void); + +#undef TRANSLATE + + // Qualifier Prefixes + // Do this after the checks above since some of the direct translations (i.e. Method) contain a prefix. +#define RECURSIVE_TRANSLATE(prefix, formatString) \ + if (encodingCString[0] == prefix) { \ + NSString *recursiveType = [self readableTypeForEncoding:[encodingString substringFromIndex:1]]; \ + return [NSString stringWithFormat:formatString, recursiveType]; \ + } + + // If there's a qualifier prefix on the encoding, translate it and then + // recursively call this method with the rest of the encoding string. + RECURSIVE_TRANSLATE('^', @"%@ *"); + RECURSIVE_TRANSLATE('r', @"const %@"); + RECURSIVE_TRANSLATE('n', @"in %@"); + RECURSIVE_TRANSLATE('N', @"inout %@"); + RECURSIVE_TRANSLATE('o', @"out %@"); + RECURSIVE_TRANSLATE('O', @"bycopy %@"); + RECURSIVE_TRANSLATE('R', @"byref %@"); + RECURSIVE_TRANSLATE('V', @"oneway %@"); + RECURSIVE_TRANSLATE('b', @"bitfield(%@)"); + +#undef RECURSIVE_TRANSLATE + + // If we couldn't translate, just return the original encoding string + return encodingString; +} + ++ (NSValue *)valueForPrimitivePointer:(void *)pointer objCType:(const char *)type +{ + // CASE macro inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html +#define CASE(ctype, selectorpart) \ + if(strcmp(type, @encode(ctype)) == 0) { \ + return [NSNumber numberWith ## selectorpart: *(ctype *)pointer]; \ + } + + CASE(BOOL, Bool); + CASE(unsigned char, UnsignedChar); + CASE(short, Short); + CASE(unsigned short, UnsignedShort); + CASE(int, Int); + CASE(unsigned int, UnsignedInt); + CASE(long, Long); + CASE(unsigned long, UnsignedLong); + CASE(long long, LongLong); + CASE(unsigned long long, UnsignedLongLong); + CASE(float, Float); + CASE(double, Double); + +#undef CASE + + NSValue *value = nil; + @try { + value = [NSValue valueWithBytes:pointer objCType:type]; + } @catch (NSException *exception) { + // Certain type encodings are not supported by valueWithBytes:objCType:. Just fail silently if an exception is thrown. + } + + return value; +} + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXUtility.h b/Pods/FLEX/Classes/Utility/FLEXUtility.h new file mode 100644 index 0000000000..850e036ee4 --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXUtility.h @@ -0,0 +1,52 @@ +// +// FLEXUtility.h +// Flipboard +// +// Created by Ryan Olson on 4/18/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import +#import +#import + +#define FLEXFloor(x) (floor([[UIScreen mainScreen] scale] * (x)) / [[UIScreen mainScreen] scale]) + +@interface FLEXUtility : NSObject + ++ (UIColor *)consistentRandomColorForObject:(id)object; ++ (NSString *)descriptionForView:(UIView *)view includingFrame:(BOOL)includeFrame; ++ (NSString *)stringForCGRect:(CGRect)rect; ++ (UIViewController *)viewControllerForView:(UIView *)view; ++ (UIViewController *)viewControllerForAncestralView:(UIView *)view; ++ (NSString *)detailDescriptionForView:(UIView *)view; ++ (UIImage *)circularImageWithColor:(UIColor *)color radius:(CGFloat)radius; ++ (UIColor *)scrollViewGrayColor; ++ (UIColor *)hierarchyIndentPatternColor; ++ (NSString *)applicationImageName; ++ (NSString *)applicationName; ++ (NSString *)safeDescriptionForObject:(id)object; ++ (UIFont *)defaultFontOfSize:(CGFloat)size; ++ (UIFont *)defaultTableViewCellLabelFont; ++ (NSString *)stringByEscapingHTMLEntitiesInString:(NSString *)originalString; ++ (UIInterfaceOrientationMask)infoPlistSupportedInterfaceOrientationsMask; ++ (NSString *)searchBarPlaceholderText; ++ (BOOL)isImagePathExtension:(NSString *)extension; ++ (UIImage *)thumbnailedImageWithMaxPixelDimension:(NSInteger)dimension fromImageData:(NSData *)data; ++ (NSString *)stringFromRequestDuration:(NSTimeInterval)duration; ++ (NSString *)statusCodeStringFromURLResponse:(NSURLResponse *)response; ++ (NSDictionary *)dictionaryFromQuery:(NSString *)query; ++ (NSString *)prettyJSONStringFromData:(NSData *)data; ++ (BOOL)isValidJSONData:(NSData *)data; ++ (NSData *)inflatedDataFromCompressedData:(NSData *)compressedData; + ++ (NSArray *)allWindows; + +// Swizzling utilities + ++ (SEL)swizzledSelectorForSelector:(SEL)selector; ++ (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls; ++ (void)replaceImplementationOfKnownSelector:(SEL)originalSelector onClass:(Class)class withBlock:(id)block swizzledSelector:(SEL)swizzledSelector; ++ (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock; + +@end diff --git a/Pods/FLEX/Classes/Utility/FLEXUtility.m b/Pods/FLEX/Classes/Utility/FLEXUtility.m new file mode 100644 index 0000000000..5892a27900 --- /dev/null +++ b/Pods/FLEX/Classes/Utility/FLEXUtility.m @@ -0,0 +1,428 @@ +// +// FLEXUtility.m +// Flipboard +// +// Created by Ryan Olson on 4/18/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXUtility.h" +#import "FLEXResources.h" +#import +#import +#import + +@implementation FLEXUtility + ++ (UIColor *)consistentRandomColorForObject:(id)object +{ + CGFloat hue = (((NSUInteger)object >> 4) % 256) / 255.0; + return [UIColor colorWithHue:hue saturation:1.0 brightness:1.0 alpha:1.0]; +} + ++ (NSString *)descriptionForView:(UIView *)view includingFrame:(BOOL)includeFrame +{ + NSString *description = [[view class] description]; + + NSString *viewControllerDescription = [[[self viewControllerForView:view] class] description]; + if ([viewControllerDescription length] > 0) { + description = [description stringByAppendingFormat:@" (%@)", viewControllerDescription]; + } + + if (includeFrame) { + description = [description stringByAppendingFormat:@" %@", [self stringForCGRect:view.frame]]; + } + + if ([view.accessibilityLabel length] > 0) { + description = [description stringByAppendingFormat:@" · %@", view.accessibilityLabel]; + } + + return description; +} + ++ (NSString *)stringForCGRect:(CGRect)rect +{ + return [NSString stringWithFormat:@"{(%g, %g), (%g, %g)}", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]; +} + ++ (UIViewController *)viewControllerForView:(UIView *)view +{ + UIViewController *viewController = nil; + SEL viewDelSel = NSSelectorFromString([NSString stringWithFormat:@"%@ewDelegate", @"_vi"]); + if ([view respondsToSelector:viewDelSel]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + viewController = [view performSelector:viewDelSel]; +#pragma clang diagnostic pop + } + return viewController; +} + ++ (UIViewController *)viewControllerForAncestralView:(UIView *)view{ + UIViewController *viewController = nil; + SEL viewDelSel = NSSelectorFromString([NSString stringWithFormat:@"%@ewControllerForAncestor", @"_vi"]); + if ([view respondsToSelector:viewDelSel]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + viewController = [view performSelector:viewDelSel]; +#pragma clang diagnostic pop + } + return viewController; +} + ++ (NSString *)detailDescriptionForView:(UIView *)view +{ + return [NSString stringWithFormat:@"frame %@", [self stringForCGRect:view.frame]]; +} + ++ (UIImage *)circularImageWithColor:(UIColor *)color radius:(CGFloat)radius +{ + CGFloat diameter = radius * 2.0; + UIGraphicsBeginImageContextWithOptions(CGSizeMake(diameter, diameter), NO, 0.0); + CGContextRef imageContext = UIGraphicsGetCurrentContext(); + CGContextSetFillColorWithColor(imageContext, [color CGColor]); + CGContextFillEllipseInRect(imageContext, CGRectMake(0, 0, diameter, diameter)); + UIImage *circularImage = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + return circularImage; +} + ++ (UIColor *)scrollViewGrayColor +{ + return [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1.0]; +} + ++ (UIColor *)hierarchyIndentPatternColor +{ + static UIColor *patternColor = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + UIImage *indentationPatternImage = [FLEXResources hierarchyIndentPattern]; + patternColor = [UIColor colorWithPatternImage:indentationPatternImage]; + }); + return patternColor; +} + ++ (NSString *)applicationImageName +{ + return [NSBundle mainBundle].executablePath; +} + ++ (NSString *)applicationName +{ + return [FLEXUtility applicationImageName].lastPathComponent; +} + ++ (NSString *)safeDescriptionForObject:(id)object +{ + // Don't assume that we have an NSObject subclass. + // Check to make sure the object responds to the description methods. + NSString *description = nil; + if ([object respondsToSelector:@selector(debugDescription)]) { + description = [object debugDescription]; + } else if ([object respondsToSelector:@selector(description)]) { + description = [object description]; + } + return description; +} + ++ (UIFont *)defaultFontOfSize:(CGFloat)size +{ + return [UIFont fontWithName:@"HelveticaNeue" size:size]; +} + ++ (UIFont *)defaultTableViewCellLabelFont +{ + return [self defaultFontOfSize:12.0]; +} + ++ (NSString *)stringByEscapingHTMLEntitiesInString:(NSString *)originalString +{ + static NSDictionary *escapingDictionary = nil; + static NSRegularExpression *regex = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + escapingDictionary = @{ @" " : @" ", + @">" : @">", + @"<" : @"<", + @"&" : @"&", + @"'" : @"'", + @"\"" : @""", + @"«" : @"«", + @"»" : @"»" + }; + regex = [NSRegularExpression regularExpressionWithPattern:@"(&|>|<|'|\"|«|»)" options:0 error:NULL]; + }); + + NSMutableString *mutableString = [originalString mutableCopy]; + + NSArray *matches = [regex matchesInString:mutableString options:0 range:NSMakeRange(0, [mutableString length])]; + for (NSTextCheckingResult *result in [matches reverseObjectEnumerator]) { + NSString *foundString = [mutableString substringWithRange:result.range]; + NSString *replacementString = escapingDictionary[foundString]; + if (replacementString) { + [mutableString replaceCharactersInRange:result.range withString:replacementString]; + } + } + + return [mutableString copy]; +} + ++ (UIInterfaceOrientationMask)infoPlistSupportedInterfaceOrientationsMask +{ + NSArray *supportedOrientations = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]; + UIInterfaceOrientationMask supportedOrientationsMask = 0; + if ([supportedOrientations containsObject:@"UIInterfaceOrientationPortrait"]) { + supportedOrientationsMask |= UIInterfaceOrientationMaskPortrait; + } + if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskLandscapeRight"]) { + supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeRight; + } + if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskPortraitUpsideDown"]) { + supportedOrientationsMask |= UIInterfaceOrientationMaskPortraitUpsideDown; + } + if ([supportedOrientations containsObject:@"UIInterfaceOrientationLandscapeLeft"]) { + supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeLeft; + } + return supportedOrientationsMask; +} + ++ (NSString *)searchBarPlaceholderText +{ + return @"Filter"; +} + ++ (BOOL)isImagePathExtension:(NSString *)extension +{ + // https://developer.apple.com/library/ios/documentation/uikit/reference/UIImage_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006890-CH3-SW3 + return [@[@"jpg", @"jpeg", @"png", @"gif", @"tiff", @"tif"] containsObject:extension]; +} + ++ (UIImage *)thumbnailedImageWithMaxPixelDimension:(NSInteger)dimension fromImageData:(NSData *)data +{ + UIImage *thumbnail = nil; + CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, 0); + if (imageSource) { + NSDictionary *options = @{ (__bridge id)kCGImageSourceCreateThumbnailWithTransform : @YES, + (__bridge id)kCGImageSourceCreateThumbnailFromImageAlways : @YES, + (__bridge id)kCGImageSourceThumbnailMaxPixelSize : @(dimension) }; + + CGImageRef scaledImageRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, (__bridge CFDictionaryRef)options); + if (scaledImageRef) { + thumbnail = [UIImage imageWithCGImage:scaledImageRef]; + CFRelease(scaledImageRef); + } + CFRelease(imageSource); + } + return thumbnail; +} + ++ (NSString *)stringFromRequestDuration:(NSTimeInterval)duration +{ + NSString *string = @"0s"; + if (duration > 0.0) { + if (duration < 1.0) { + string = [NSString stringWithFormat:@"%dms", (int)(duration * 1000)]; + } else if (duration < 10.0) { + string = [NSString stringWithFormat:@"%.2fs", duration]; + } else { + string = [NSString stringWithFormat:@"%.1fs", duration]; + } + } + return string; +} + ++ (NSString *)statusCodeStringFromURLResponse:(NSURLResponse *)response +{ + NSString *httpResponseString = nil; + if ([response isKindOfClass:[NSHTTPURLResponse class]]) { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; + NSString *statusCodeDescription = nil; + if (httpResponse.statusCode == 200) { + // Prefer OK to the default "no error" + statusCodeDescription = @"OK"; + } else { + statusCodeDescription = [NSHTTPURLResponse localizedStringForStatusCode:httpResponse.statusCode]; + } + httpResponseString = [NSString stringWithFormat:@"%ld %@", (long)httpResponse.statusCode, statusCodeDescription]; + } + return httpResponseString; +} + ++ (NSDictionary *)dictionaryFromQuery:(NSString *)query +{ + NSMutableDictionary *queryDictionary = [NSMutableDictionary dictionary]; + + // [a=1, b=2, c=3] + NSArray *queryComponents = [query componentsSeparatedByString:@"&"]; + for (NSString *keyValueString in queryComponents) { + // [a, 1] + NSArray *components = [keyValueString componentsSeparatedByString:@"="]; + if ([components count] == 2) { + NSString *key = [[components firstObject] stringByRemovingPercentEncoding]; + id value = [[components lastObject] stringByRemovingPercentEncoding]; + + // Handle multiple entries under the same key as an array + id existingEntry = queryDictionary[key]; + if (existingEntry) { + if ([existingEntry isKindOfClass:[NSArray class]]) { + value = [existingEntry arrayByAddingObject:value]; + } else { + value = @[existingEntry, value]; + } + } + + [queryDictionary setObject:value forKey:key]; + } + } + + return queryDictionary; +} + ++ (NSString *)prettyJSONStringFromData:(NSData *)data +{ + NSString *prettyString = nil; + + id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; + if ([NSJSONSerialization isValidJSONObject:jsonObject]) { + prettyString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:NULL] encoding:NSUTF8StringEncoding]; + // NSJSONSerialization escapes forward slashes. We want pretty json, so run through and unescape the slashes. + prettyString = [prettyString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"]; + } else { + prettyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + } + + return prettyString; +} + ++ (BOOL)isValidJSONData:(NSData *)data +{ + return [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL] ? YES : NO; +} + +// Thanks to the following links for help with this method +// http://www.cocoanetics.com/2012/02/decompressing-files-into-memory/ +// https://github.com/nicklockwood/GZIP ++ (NSData *)inflatedDataFromCompressedData:(NSData *)compressedData +{ + NSData *inflatedData = nil; + NSUInteger compressedDataLength = [compressedData length]; + if (compressedDataLength > 0) { + z_stream stream; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + stream.avail_in = (uInt)compressedDataLength; + stream.next_in = (void *)[compressedData bytes]; + stream.total_out = 0; + stream.avail_out = 0; + + NSMutableData *mutableData = [NSMutableData dataWithLength:compressedDataLength * 1.5]; + if (inflateInit2(&stream, 15 + 32) == Z_OK) { + int status = Z_OK; + while (status == Z_OK) { + if (stream.total_out >= [mutableData length]) { + mutableData.length += compressedDataLength / 2; + } + stream.next_out = (uint8_t *)[mutableData mutableBytes] + stream.total_out; + stream.avail_out = (uInt)([mutableData length] - stream.total_out); + status = inflate(&stream, Z_SYNC_FLUSH); + } + if (inflateEnd(&stream) == Z_OK) { + if (status == Z_STREAM_END) { + mutableData.length = stream.total_out; + inflatedData = [mutableData copy]; + } + } + } + } + return inflatedData; +} + ++ (NSArray *)allWindows +{ + BOOL includeInternalWindows = YES; + BOOL onlyVisibleWindows = NO; + + NSArray *allWindowsComponents = @[@"al", @"lWindo", @"wsIncl", @"udingInt", @"ernalWin", @"dows:o", @"nlyVisi", @"bleWin", @"dows:"]; + SEL allWindowsSelector = NSSelectorFromString([allWindowsComponents componentsJoinedByString:@""]); + + NSMethodSignature *methodSignature = [[UIWindow class] methodSignatureForSelector:allWindowsSelector]; + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature]; + + invocation.target = [UIWindow class]; + invocation.selector = allWindowsSelector; + [invocation setArgument:&includeInternalWindows atIndex:2]; + [invocation setArgument:&onlyVisibleWindows atIndex:3]; + [invocation invoke]; + + __unsafe_unretained NSArray *windows = nil; + [invocation getReturnValue:&windows]; + return windows; +} + ++ (SEL)swizzledSelectorForSelector:(SEL)selector +{ + return NSSelectorFromString([NSString stringWithFormat:@"_flex_swizzle_%x_%@", arc4random(), NSStringFromSelector(selector)]); +} + ++ (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls +{ + if ([cls instancesRespondToSelector:selector]) { + unsigned int numMethods = 0; + Method *methods = class_copyMethodList(cls, &numMethods); + + BOOL implementsSelector = NO; + for (int index = 0; index < numMethods; index++) { + SEL methodSelector = method_getName(methods[index]); + if (selector == methodSelector) { + implementsSelector = YES; + break; + } + } + + free(methods); + + if (!implementsSelector) { + return YES; + } + } + + return NO; +} + ++ (void)replaceImplementationOfKnownSelector:(SEL)originalSelector onClass:(Class)class withBlock:(id)block swizzledSelector:(SEL)swizzledSelector +{ + // This method is only intended for swizzling methods that are know to exist on the class. + // Bail if that isn't the case. + Method originalMethod = class_getInstanceMethod(class, originalSelector); + if (!originalMethod) { + return; + } + + IMP implementation = imp_implementationWithBlock(block); + class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalMethod)); + Method newMethod = class_getInstanceMethod(class, swizzledSelector); + method_exchangeImplementations(originalMethod, newMethod); +} + ++ (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock +{ + if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) { + return; + } + + IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock)); + + Method oldMethod = class_getInstanceMethod(cls, selector); + if (oldMethod) { + class_addMethod(cls, swizzledSelector, implementation, methodDescription.types); + + Method newMethod = class_getInstanceMethod(cls, swizzledSelector); + + method_exchangeImplementations(oldMethod, newMethod); + } else { + class_addMethod(cls, selector, implementation, methodDescription.types); + } +} + +@end diff --git a/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewCell.h b/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewCell.h new file mode 100644 index 0000000000..52817c5f63 --- /dev/null +++ b/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewCell.h @@ -0,0 +1,18 @@ +// +// FLEXHierarchyTableViewCell.h +// Flipboard +// +// Created by Ryan Olson on 2014-05-02. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@interface FLEXHierarchyTableViewCell : UITableViewCell + +- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier; + +@property (nonatomic, assign) NSInteger viewDepth; +@property (nonatomic, strong) UIColor *viewColor; + +@end diff --git a/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewCell.m b/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewCell.m new file mode 100644 index 0000000000..50d3bec0bc --- /dev/null +++ b/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewCell.m @@ -0,0 +1,106 @@ +// +// FLEXHierarchyTableViewCell.m +// Flipboard +// +// Created by Ryan Olson on 2014-05-02. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXHierarchyTableViewCell.h" +#import "FLEXUtility.h" + +@interface FLEXHierarchyTableViewCell () + +@property (nonatomic, strong) UIView *depthIndicatorView; +@property (nonatomic, strong) UIImageView *colorCircleImageView; + +@end + +@implementation FLEXHierarchyTableViewCell + +- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier +{ + return [self initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier]; +} + +- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier +{ + self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; + if (self) { + self.depthIndicatorView = [[UIView alloc] init]; + self.depthIndicatorView.backgroundColor = [FLEXUtility hierarchyIndentPatternColor]; + [self.contentView addSubview:self.depthIndicatorView]; + + UIImage *defaultCircleImage = [FLEXUtility circularImageWithColor:[UIColor blackColor] radius:5.0]; + self.colorCircleImageView = [[UIImageView alloc] initWithImage:defaultCircleImage]; + [self.contentView addSubview:self.colorCircleImageView]; + + self.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:14.0]; + self.detailTextLabel.font = [FLEXUtility defaultTableViewCellLabelFont]; + self.accessoryType = UITableViewCellAccessoryDetailButton; + } + return self; +} + +- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated +{ + [super setHighlighted:highlighted animated:animated]; + + // UITableViewCell changes all subviews in the contentView to backgroundColor = clearColor. + // We want to preserve the hierarchy background color when highlighted. + self.depthIndicatorView.backgroundColor = [FLEXUtility hierarchyIndentPatternColor]; +} + +- (void)setSelected:(BOOL)selected animated:(BOOL)animated +{ + [super setSelected:selected animated:animated]; + + // See setHighlighted above. + self.depthIndicatorView.backgroundColor = [FLEXUtility hierarchyIndentPatternColor]; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + const CGFloat kContentPadding = 10.0; + const CGFloat kDepthIndicatorWidthMultiplier = 4.0; + + CGRect depthIndicatorFrame = CGRectMake(kContentPadding, 0, self.viewDepth * kDepthIndicatorWidthMultiplier, self.contentView.bounds.size.height); + self.depthIndicatorView.frame = depthIndicatorFrame; + + CGRect circleFrame = self.colorCircleImageView.frame; + circleFrame.origin.x = CGRectGetMaxX(depthIndicatorFrame); + circleFrame.origin.y = self.textLabel.frame.origin.y + FLEXFloor((self.textLabel.frame.size.height - circleFrame.size.height) / 2.0); + self.colorCircleImageView.frame = circleFrame; + + CGRect textLabelFrame = self.textLabel.frame; + CGFloat textOriginX = CGRectGetMaxX(circleFrame) + 4.0; + textLabelFrame.origin.x = textOriginX; + textLabelFrame.size.width = CGRectGetMaxX(self.contentView.bounds) - kContentPadding - textOriginX; + self.textLabel.frame = textLabelFrame; + + CGRect detailTextLabelFrame = self.detailTextLabel.frame; + CGFloat detailOriginX = CGRectGetMaxX(depthIndicatorFrame); + detailTextLabelFrame.origin.x = detailOriginX; + detailTextLabelFrame.size.width = CGRectGetMaxX(self.contentView.bounds) - kContentPadding - detailOriginX; + self.detailTextLabel.frame = detailTextLabelFrame; +} + +- (void)setViewColor:(UIColor *)viewColor +{ + if (![_viewColor isEqual:viewColor]) { + _viewColor = viewColor; + self.colorCircleImageView.image = [FLEXUtility circularImageWithColor:viewColor radius:6.0]; + } +} + +- (void)setViewDepth:(NSInteger)viewDepth +{ + if (_viewDepth != viewDepth) { + _viewDepth = viewDepth; + [self setNeedsLayout]; + } +} + +@end diff --git a/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewController.h b/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewController.h new file mode 100644 index 0000000000..e2e7e061dd --- /dev/null +++ b/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewController.h @@ -0,0 +1,25 @@ +// +// FLEXHierarchyTableViewController.h +// Flipboard +// +// Created by Ryan Olson on 2014-05-01. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@protocol FLEXHierarchyTableViewControllerDelegate; + +@interface FLEXHierarchyTableViewController : UITableViewController + +- (id)initWithViews:(NSArray *)allViews viewsAtTap:(NSArray *)viewsAtTap selectedView:(UIView *)selectedView depths:(NSDictionary *)depthsForViews; + +@property (nonatomic, weak) id delegate; + +@end + +@protocol FLEXHierarchyTableViewControllerDelegate + +- (void)hierarchyViewController:(FLEXHierarchyTableViewController *)hierarchyViewController didFinishWithSelectedView:(UIView *)selectedView; + +@end diff --git a/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewController.m b/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewController.m new file mode 100644 index 0000000000..3075bd5154 --- /dev/null +++ b/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewController.m @@ -0,0 +1,207 @@ +// +// FLEXHierarchyTableViewController.m +// Flipboard +// +// Created by Ryan Olson on 2014-05-01. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXHierarchyTableViewController.h" +#import "FLEXUtility.h" +#import "FLEXHierarchyTableViewCell.h" +#import "FLEXObjectExplorerViewController.h" +#import "FLEXObjectExplorerFactory.h" + +static const NSInteger kFLEXHierarchyScopeViewsAtTapIndex = 0; +static const NSInteger kFLEXHierarchyScopeFullHierarchyIndex = 1; + +@interface FLEXHierarchyTableViewController () + +@property (nonatomic, strong) NSArray *allViews; +@property (nonatomic, strong) NSDictionary *depthsForViews; +@property (nonatomic, strong) NSArray *viewsAtTap; +@property (nonatomic, strong) UIView *selectedView; +@property (nonatomic, strong) NSArray *displayedViews; + +@property (nonatomic, strong) UISearchBar *searchBar; + +@end + +@implementation FLEXHierarchyTableViewController + +- (id)initWithViews:(NSArray *)allViews viewsAtTap:(NSArray *)viewsAtTap selectedView:(UIView *)selectedView depths:(NSDictionary *)depthsForViews +{ + self = [super initWithStyle:UITableViewStylePlain]; + if (self) { + self.allViews = allViews; + self.depthsForViews = depthsForViews; + self.viewsAtTap = viewsAtTap; + self.selectedView = selectedView; + + self.title = @"View Hierarchy"; + } + return self; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + // Preserve selection between presentations. + self.clearsSelectionOnViewWillAppear = NO; + // Done button. + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donePressed:)]; + + // A little more breathing room. + self.tableView.rowHeight = 50.0; + self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; + // Separator inset clashes with persistent cell selection. + [self.tableView setSeparatorInset:UIEdgeInsetsZero]; + + self.searchBar = [[UISearchBar alloc] init]; + self.searchBar.placeholder = [FLEXUtility searchBarPlaceholderText]; + self.searchBar.delegate = self; + if ([self showScopeBar]) { + self.searchBar.showsScopeBar = YES; + self.searchBar.scopeButtonTitles = @[@"Views at Tap", @"Full Hierarchy"]; + } + [self.searchBar sizeToFit]; + self.tableView.tableHeaderView = self.searchBar; + + [self updateDisplayedViews]; +} + +- (void)viewDidAppear:(BOOL)animated +{ + [super viewDidAppear:animated]; + + [self trySelectCellForSelectedViewWithScrollPosition:UITableViewScrollPositionMiddle]; +} + + +#pragma mark Selection and Filtering Helpers + +- (void)trySelectCellForSelectedViewWithScrollPosition:(UITableViewScrollPosition)scrollPosition +{ + NSUInteger selectedViewIndex = [self.displayedViews indexOfObject:self.selectedView]; + if (selectedViewIndex != NSNotFound) { + NSIndexPath *selectedViewIndexPath = [NSIndexPath indexPathForRow:selectedViewIndex inSection:0]; + [self.tableView selectRowAtIndexPath:selectedViewIndexPath animated:YES scrollPosition:scrollPosition]; + } +} + +- (void)updateDisplayedViews +{ + NSArray *candidateViews = nil; + if ([self showScopeBar]) { + if (self.searchBar.selectedScopeButtonIndex == kFLEXHierarchyScopeViewsAtTapIndex) { + candidateViews = self.viewsAtTap; + } else if (self.searchBar.selectedScopeButtonIndex == kFLEXHierarchyScopeFullHierarchyIndex) { + candidateViews = self.allViews; + } + } else { + candidateViews = self.allViews; + } + + if ([self.searchBar.text length] > 0) { + self.displayedViews = [candidateViews filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UIView *candidateView, NSDictionary *bindings) { + NSString *title = [FLEXUtility descriptionForView:candidateView includingFrame:NO]; + NSString *candidateViewPointerAddress = [NSString stringWithFormat:@"%p", candidateView]; + BOOL matchedViewPointerAddress = [candidateViewPointerAddress rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch].location != NSNotFound; + BOOL matchedViewTitle = [title rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch].location != NSNotFound; + return matchedViewPointerAddress || matchedViewTitle; + }]]; + } else { + self.displayedViews = candidateViews; + } + + [self.tableView reloadData]; +} + +- (BOOL)showScopeBar +{ + return [self.viewsAtTap count] > 0; +} + +- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope +{ + [self updateDisplayedViews]; + + // If the search bar text field is active, don't scroll on selection because we may want to continue typing. + // Otherwise, scroll so that the selected cell is visible. + UITableViewScrollPosition scrollPosition = self.searchBar.isFirstResponder ? UITableViewScrollPositionNone : UITableViewScrollPositionMiddle; + [self trySelectCellForSelectedViewWithScrollPosition:scrollPosition]; +} + +- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText +{ + [self updateDisplayedViews]; + [self trySelectCellForSelectedViewWithScrollPosition:UITableViewScrollPositionNone]; +} + +- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar +{ + [searchBar resignFirstResponder]; +} + + +#pragma mark - Table View Data Source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ + return [self.displayedViews count]; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *CellIdentifier = @"Cell"; + FLEXHierarchyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; + if (!cell) { + cell = [[FLEXHierarchyTableViewCell alloc] initWithReuseIdentifier:CellIdentifier]; + } + + UIView *view = self.displayedViews[indexPath.row]; + NSNumber *depth = [self.depthsForViews objectForKey:[NSValue valueWithNonretainedObject:view]]; + UIColor *viewColor = [FLEXUtility consistentRandomColorForObject:view]; + cell.textLabel.text = [FLEXUtility descriptionForView:view includingFrame:NO]; + cell.detailTextLabel.text = [FLEXUtility detailDescriptionForView:view]; + cell.viewColor = viewColor; + cell.viewDepth = [depth integerValue]; + if (view.isHidden || view.alpha < 0.01) { + cell.textLabel.textColor = [UIColor lightGrayColor]; + cell.detailTextLabel.textColor = [UIColor lightGrayColor]; + } else { + cell.textLabel.textColor = [UIColor blackColor]; + cell.detailTextLabel.textColor = [UIColor blackColor]; + } + + return cell; +} + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + self.selectedView = self.displayedViews[indexPath.row]; + [self.delegate hierarchyViewController:self didFinishWithSelectedView:self.selectedView]; +} + +- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath +{ + UIView *drillInView = self.displayedViews[indexPath.row]; + FLEXObjectExplorerViewController *viewExplorer = [FLEXObjectExplorerFactory explorerViewControllerForObject:drillInView]; + [self.navigationController pushViewController:viewExplorer animated:YES]; +} + + +#pragma mark - Button Actions + +- (void)donePressed:(id)sender +{ + [self.delegate hierarchyViewController:self didFinishWithSelectedView:self.selectedView]; +} + +@end diff --git a/Pods/FLEX/Classes/ViewHierarchy/FLEXImagePreviewViewController.h b/Pods/FLEX/Classes/ViewHierarchy/FLEXImagePreviewViewController.h new file mode 100644 index 0000000000..60f021dd61 --- /dev/null +++ b/Pods/FLEX/Classes/ViewHierarchy/FLEXImagePreviewViewController.h @@ -0,0 +1,15 @@ +// +// FLEXImagePreviewViewController.h +// Flipboard +// +// Created by Ryan Olson on 6/12/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import + +@interface FLEXImagePreviewViewController : UIViewController + +- (id)initWithImage:(UIImage *)image; + +@end diff --git a/Pods/FLEX/Classes/ViewHierarchy/FLEXImagePreviewViewController.m b/Pods/FLEX/Classes/ViewHierarchy/FLEXImagePreviewViewController.m new file mode 100644 index 0000000000..96cd99c5a1 --- /dev/null +++ b/Pods/FLEX/Classes/ViewHierarchy/FLEXImagePreviewViewController.m @@ -0,0 +1,86 @@ +// +// FLEXImagePreviewViewController.m +// Flipboard +// +// Created by Ryan Olson on 6/12/14. +// Copyright (c) 2014 Flipboard. All rights reserved. +// + +#import "FLEXImagePreviewViewController.h" +#import "FLEXUtility.h" + +@interface FLEXImagePreviewViewController () + +@property (nonatomic, strong) UIImage *image; + +@property (nonatomic, strong) UIScrollView *scrollView; +@property (nonatomic, strong) UIImageView *imageView; + +@end + +@implementation FLEXImagePreviewViewController + +- (id)initWithImage:(UIImage *)image +{ + self = [super initWithNibName:nil bundle:nil]; + if (self) { + self.title = @"Preview"; + self.image = image; + } + return self; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.view.backgroundColor = [FLEXUtility scrollViewGrayColor]; + + self.imageView = [[UIImageView alloc] initWithImage:self.image]; + self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds]; + self.scrollView.delegate = self; + self.scrollView.backgroundColor = self.view.backgroundColor; + self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + [self.scrollView addSubview:self.imageView]; + self.scrollView.contentSize = self.imageView.frame.size; + self.scrollView.minimumZoomScale = 1.0; + self.scrollView.maximumZoomScale = 2.0; + [self.view addSubview:self.scrollView]; + + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Copy" style:UIBarButtonItemStylePlain target:self action:@selector(copyButtonPressed:)]; +} + +- (void)viewDidLayoutSubviews +{ + [self centerContentInScrollViewIfNeeded]; +} + +- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView +{ + return self.imageView; +} + +- (void)scrollViewDidZoom:(UIScrollView *)scrollView +{ + [self centerContentInScrollViewIfNeeded]; +} + +- (void)centerContentInScrollViewIfNeeded +{ + CGFloat horizontalInset = 0.0; + CGFloat verticalInset = 0.0; + if (self.scrollView.contentSize.width < self.scrollView.bounds.size.width) { + horizontalInset = (self.scrollView.bounds.size.width - self.scrollView.contentSize.width) / 2.0; + } + if (self.scrollView.contentSize.height < self.scrollView.bounds.size.height) { + verticalInset = (self.scrollView.bounds.size.height - self.scrollView.contentSize.height) / 2.0; + } + self.scrollView.contentInset = UIEdgeInsetsMake(verticalInset, horizontalInset, verticalInset, horizontalInset); +} + +- (void)copyButtonPressed:(id)sender +{ + [[UIPasteboard generalPasteboard] setImage:self.image]; +} + +@end diff --git a/Pods/FLEX/LICENSE b/Pods/FLEX/LICENSE new file mode 100644 index 0000000000..43a8561b75 --- /dev/null +++ b/Pods/FLEX/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014-2016, Flipboard +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +* Neither the name of Flipboard nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Pods/FLEX/README.md b/Pods/FLEX/README.md new file mode 100644 index 0000000000..04d7b93db8 --- /dev/null +++ b/Pods/FLEX/README.md @@ -0,0 +1,169 @@ +# FLEX +[![CocoaPods](https://img.shields.io/cocoapods/v/FLEX.svg)](http://cocoapods.org/?q=FLEX) + [![CocoaPods](https://img.shields.io/cocoapods/l/FLEX.svg)](https://github.com/Flipboard/FLEX/blob/master/LICENSE) + [![CocoaPods](https://img.shields.io/cocoapods/p/FLEX.svg)]() + [![Twitter: @ryanolsonk](https://img.shields.io/badge/contact-@ryanolsonk-blue.svg?style=flat)](https://twitter.com/ryanolsonk) + [![Build Status](https://travis-ci.org/Flipboard/FLEX.svg?branch=master)](https://travis-ci.org/Flipboard/FLEX) + [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +FLEX (Flipboard Explorer) is a set of in-app debugging and exploration tools for iOS development. When presented, FLEX shows a toolbar that lives in a window above your application. From this toolbar, you can view and modify nearly every piece of state in your running application. + +![View Hierarchy Exploration](http://engineering.flipboard.com/assets/flex/basic-view-exploration.gif) + + +## Give Yourself Debugging Superpowers +- Inspect and modify views in the hierarchy. +- See the properties and ivars on any object. +- Dynamically modify many properties and ivars. +- Dynamically call instance and class methods. +- Observe detailed network request history with timing, headers, and full responses. +- Add your own simulator keyboard shortcuts. +- View system log messages (e.g. from `NSLog`). +- Access any live object via a scan of the heap. +- View the file system within your app's sandbox. +- Browse SQLite/Realm databases in the file system. +- Trigger 3D touch in the simulator using the control, shift, and command keys. +- Explore all classes in your app and linked systems frameworks (public and private). +- Quickly access useful objects such as `[UIApplication sharedApplication]`, the app delegate, the root view controller on the key window, and more. +- Dynamically view and modify `NSUserDefaults` values. + +Unlike many other debugging tools, FLEX runs entirely inside your app, so you don't need to be connected to LLDB/Xcode or a different remote debugging server. It works well in the simulator and on physical devices. + + +## Usage + +In the iOS simulator, you can use keyboard shortcuts to activate FLEX. `f` will toggle the FLEX toolbar. Hit the `?` key for a full list of shortcuts. You can also show FLEX programatically: + +Short version: + +```objc +[[FLEXManager sharedManager] showExplorer]; +``` + +More complete version: + +```objc +#if DEBUG +#import "FLEXManager.h" +#endif + +... + +- (void)handleSixFingerQuadrupleTap:(UITapGestureRecognizer *)tapRecognizer +{ +#if DEBUG + if (tapRecognizer.state == UIGestureRecognizerStateRecognized) { + // This could also live in a handler for a keyboard shortcut, debug menu item, etc. + [[FLEXManager sharedManager] showExplorer]; + } +#endif +} +``` + + +## Feature Examples +### Modify Views +Once a view is selected, you can tap on the info bar below the toolbar to present more details about the view. From there, you can modify properties and call methods. + +![View Modification](http://engineering.flipboard.com/assets/flex/advanced-view-editing.gif) + +### Network History +When enabled, network debugging allows you to view all requests made using NSURLConnection or NSURLSession. Settings allow you to adjust what kind of response bodies get cached and the maximum size limit of the response cache. You can choose to have network debugging enabled automatically on app launch. This setting is persisted across launches. + +![Network History](http://engineering.flipboard.com/assets/flex/network-history.gif) + +### All Objects on the Heap +FLEX queries malloc for all the live allocated memory blocks and searches for ones that look like objects. You can see everything from here. + +![Heap Exploration](http://engineering.flipboard.com/assets/flex/heap-browser.gif) + +### Simulator Keyboard Shortcuts +Default keyboard shortcuts allow you to activate the FLEX tools, scroll with the arrow keys, and close modals using the escape key. You can also add custom keyboard shortcuts via `-[FLEXMananger registerSimulatorShortcutWithKey:modifiers:action:description]` + +![Simulator Shortcuts](https://cloud.githubusercontent.com/assets/1422245/10002927/1106fd32-6067-11e5-8e21-57a357c259b6.png) + +### File Browser +View the file system within your app's sandbox. FLEX shows file sizes, image previews, and pretty prints `.json` and `.plist` files. You can copy text and image files to the pasteboard if you want to inspect them outside of your app. + +![File Browser](http://engineering.flipboard.com/assets/flex/file-browser.gif) + +### SQLite Browser +SQLite database files (with either `.db` or `.sqlite` extensions), or [Realm](http://realm.io) database files can be explored using FLEX. The database browser lets you view all tables, and individual tables can be sorted by tapping column headers. + +![Database Browser](https://cloud.githubusercontent.com/assets/1422245/11786700/d0ab95dc-a23c-11e5-80ce-0e1b4dba2b6b.png) + +### 3D Touch in the Simulator +Using a combination of the command, control, and shift keys, you can simulate different levels of 3D touch pressure in the simulator. Each key contributes 1/3 of maximum possible force. Note that you need to move the touch slightly to get pressure updates. + +![Simulator 3D Touch](https://cloud.githubusercontent.com/assets/1422245/11786615/5d4ef96c-a23c-11e5-975e-67275341e439.gif) + +### System Library Exploration +Go digging for all things public and private. To learn more about a class, you can create an instance of it and explore its default state. + +![System Libraries Browser](http://engineering.flipboard.com/assets/flex/system-libraries-browser.gif) + +### NSUserDefaults Editing +FLEX allows you to edit defaults that are any combination of strings, numbers, arrays, and dictionaries. The input is parsed as `JSON`. If other kinds of objects are set for a defaults key (i.e. `NSDate`), you can view them but not edit them. + +![NSUserDefaults Editor](http://engineering.flipboard.com/assets/flex/nsuserdefaults-editor.gif) + +### Learning from Other Apps +The code injection is left as an exercise for the reader. :innocent: + +![Springboard Lock Screen](http://engineering.flipboard.com/assets/flex/flex-readme-reverse-1.png) ![Springboard Home Screen](http://engineering.flipboard.com/assets/flex/flex-readme-reverse-2.png) + + +## Installation +FLEX is available on [CocoaPods](http://cocoapods.org/?q=FLEX). Simply add the following line to your podfile: + +```ruby +pod 'FLEX', '~> 2.0', :configurations => ['Debug'] +``` + +Alternatively, you can manually add the files in `Classes/` to your Xcode project. FLEX requires iOS 7 or higher. + + +## Excluding FLEX from Release (App Store) Builds +*Note: CocoaPods handles this automatically if you only specify the Debug configuration for FLEX in your Podfile.* +FLEX makes it easy to explore the internals of your app, so it is not something you should expose to your users. Fortunately, it is easy to exclude FLEX files from Release builds. In Xcode, navigate to the "Build Settings" tab of your project. Click the plus and select `Add User-Defined Setting`. + +![Add User-Defined Setting](http://engineering.flipboard.com/assets/flex/flex-readme-exclude-1.png) + +Name the setting `EXCLUDED_SOURCE_FILE_NAMES`. For your `Release` configuration, set the value to `FLEX*`. This will exclude all files with the prefix FLEX from compilation. Leave the value blank for your `Debug` configuration. + +![EXCLUDED_SOURCE_FILE_NAMES](http://engineering.flipboard.com/assets/flex/flex-readme-exclude-2.png) + +At the places in your code where you integrate FLEX, do a `#if DEBUG` check to ensure the tool is only accessible in your `Debug` builds and to avoid errors in your `Release` builds. For more help with integrating FLEX, see the example project. + + +## Additional Notes +- When setting fields of type `id` or values in `NSUserDefaults`, FLEX attempts to parse the input string as `JSON`. This allows you to use a combination of strings, numbers, arrays, and dictionaries. If you want to set a string value, it must be wrapped in quotes. For ivars or properties that are explicitly typed as `NSStrings`, quotes are not required. +- You may want to disable the exception breakpoint while using FLEX. Certain functions that FLEX uses throw exceptions when they get input they can't handle (i.e. `NSGetSizeAndAlignment()`). FLEX catches these to avoid crashing, but your breakpoint will get hit if it is active. + + +## Thanks & Credits +FLEX builds on ideas and inspiration from open source tools that came before it. The following resources have been particularly helpful: +- [DCIntrospect](https://github.com/domesticcatsoftware/DCIntrospect): view hierarchy debugging for the iOS simulator. +- [PonyDebugger](https://github.com/square/PonyDebugger): network, core data, and view hierarchy debugging using the Chrome Developer Tools interface. +- [Mike Ash](https://www.mikeash.com/pyblog/): well written, informative blog posts on all things obj-c and more. The links below were very useful for this project: + - [MAObjCRuntime](https://github.com/mikeash/MAObjCRuntime) + - [Let's Build Key Value Coding](https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html) + - [ARM64 and You](https://www.mikeash.com/pyblog/friday-qa-2013-09-27-arm64-and-you.html) +- [RHObjectiveBeagle](https://github.com/heardrwt/RHObjectiveBeagle): a tool for scanning the heap for live objects. It should be noted that the source code of RHObjectiveBeagle was not consulted due to licensing concerns. +- [heap_find.cpp](https://www.opensource.apple.com/source/lldb/lldb-179.1/examples/darwin/heap_find/heap/heap_find.cpp): an example of enumerating malloc blocks for finding objects on the heap. +- [Gist](https://gist.github.com/samdmarshall/17f4e66b5e2e579fd396) from [@samdmarshall](https://github.com/samdmarshall): another example of enumerating malloc blocks. +- [Non-pointer isa](http://www.sealiesoftware.com/blog/archive/2013/09/24/objc_explain_Non-pointer_isa.html): an explanation of changes to the isa field on iOS for ARM64 and mention of the useful `objc_debug_isa_class_mask` variable. +- [GZIP](https://github.com/nicklockwood/GZIP): A library for compressing/decompressing data on iOS using libz. +- [FMDB](https://github.com/ccgus/fmdb): This is an Objective-C wrapper around SQLite + + + + +## Contributing +Please see our [Contributing Guide](https://github.com/Flipboard/FLEX/blob/master/CONTRIBUTING.md). + + +## TODO +- Swift runtime introspection (swift classes, swift objects on the heap, etc.) +- Improved file type detection and display in the file browser +- Add new NSUserDefault key/value pairs on the fly diff --git a/Pods/Fabric/Fabric.framework/README b/Pods/Fabric/Fabric.framework/README new file mode 100644 index 0000000000..3b1fbe24e9 --- /dev/null +++ b/Pods/Fabric/Fabric.framework/README @@ -0,0 +1 @@ +We've now combined all our supported platforms into a single podspec. As a result, we moved our run script to a new location for Cocoapods projects: ${PODS_ROOT}/Fabric/run. To avoid breaking builds that reference the old location of the run script, we've placed this dummy script that calls to the correct location, while providing a helpful warning in Xcode if it is invoked. This bridge for backwards compatibility will be removed in a future release, so please heed the warning! diff --git a/Pods/Fabric/Fabric.framework/run b/Pods/Fabric/Fabric.framework/run new file mode 100755 index 0000000000..b9edd17f99 --- /dev/null +++ b/Pods/Fabric/Fabric.framework/run @@ -0,0 +1,6 @@ +if [[ -z $PODS_ROOT ]]; then + echo "error: The run binary delivered by cocoapods is in a new location, under '$"{"PODS_ROOT"}"/Fabric/run'. This script was put in place for backwards compatibility, but it relies on PODS_ROOT, which does not have a value in your current setup. Please update the path to the run binary to fix this issue." +else + echo "warning: The run script is now located at '$"{"PODS_ROOT"}"/Fabric/run'. To remove this warning, update your Run Script Build Phase to point to this new location." + sh "${PODS_ROOT}/Fabric/run" "$@" +fi diff --git a/Pods/Fabric/README.md b/Pods/Fabric/README.md new file mode 100644 index 0000000000..9eca6105ad --- /dev/null +++ b/Pods/Fabric/README.md @@ -0,0 +1,42 @@ +![Fabric Header](https://docs.fabric.io/ios/cocoapod-readmes/cocoapods-fabric-header.png) + +# Fabric + +## Overview + +[Fabric](https://get.fabric.io) provides developers with the tools they need to build the best apps. Developed and maintained by Google and the team that built Crashlytics, Fabric provides an easy way to manage all your SDKs so that you’ll never have to worry about tedious configurations or juggling different accounts. We let you get right into coding and building the next big app. + +For a full list of SDK provided through Fabric visit [https://fabric.io/kits](https://fabric.io/kits). + +## Setup + +The Fabric Pod is a dependency for all Fabric SDKs and is included when installing any Fabric related Pods. General setup instructions are shown below; however, these vary depending on the selected SDK. + +1. Visit [https://fabric.io/sign_up](https://fabric.io/sign_up) to create your Fabric account and to download Fabric.app. + +1. Open Fabric.app, login and select an SDK to install. + + ![Fabric Plugin](https://docs.fabric.io/ios/cocoapod-readmes/cocoapods-fabric-plugin.png) + +1. The Fabric app automatically detects when a project uses CocoaPods and gives you the option to install via the Podfile or Xcode. + + ![Fabric Installation Options](https://docs.fabric.io/ios/cocoapod-readmes/cocoapods-pod-installation-option.png) + +1. Select the Podfile option and follow the installation instructions to update your Podfile. Note: the example below is for the Crashlytics SDK. The instructions will vary based on the selected SDK. + + ![Fabric Podfile Instructions](https://docs.fabric.io/ios/cocoapod-readmes/cocoapods-podfile-instructions.png) + +1. Add a Run Script Build Phase and build your app. + + ![Fabric Run Script Build Phase](https://docs.fabric.io/ios/cocoapod-readmes/cocoapods-rsbp.png) + +1. Initialize the SDK by inserting code outlined in Fabric.app. + +1. Run your app to finish the installation. + +## Resources + +* [Documentation](https://docs.fabric.io/) +* [Forums](https://stackoverflow.com/questions/tagged/google-fabric) +* [Website](https://get.fabric.io) +* Follow us on Twitter: [@fabric](https://twitter.com/fabric) diff --git a/Pods/Fabric/iOS/Fabric.framework/Fabric b/Pods/Fabric/iOS/Fabric.framework/Fabric new file mode 100755 index 0000000000..3057fdf419 Binary files /dev/null and b/Pods/Fabric/iOS/Fabric.framework/Fabric differ diff --git a/Pods/Fabric/iOS/Fabric.framework/Headers/FABAttributes.h b/Pods/Fabric/iOS/Fabric.framework/Headers/FABAttributes.h new file mode 100644 index 0000000000..3a9355a7c6 --- /dev/null +++ b/Pods/Fabric/iOS/Fabric.framework/Headers/FABAttributes.h @@ -0,0 +1,51 @@ +// +// FABAttributes.h +// Fabric +// +// Copyright (C) 2015 Twitter, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once + +#define FAB_UNAVAILABLE(x) __attribute__((unavailable(x))) + +#if !__has_feature(nullability) + #define nonnull + #define nullable + #define _Nullable + #define _Nonnull +#endif + +#ifndef NS_ASSUME_NONNULL_BEGIN + #define NS_ASSUME_NONNULL_BEGIN +#endif + +#ifndef NS_ASSUME_NONNULL_END + #define NS_ASSUME_NONNULL_END +#endif + + +/** + * The following macros are defined here to provide + * backwards compatability. If you are still using + * them you should migrate to the native nullability + * macros. + */ +#define fab_nullable nullable +#define fab_nonnull nonnull +#define FAB_NONNULL __fab_nonnull +#define FAB_NULLABLE __fab_nullable +#define FAB_START_NONNULL NS_ASSUME_NONNULL_BEGIN +#define FAB_END_NONNULL NS_ASSUME_NONNULL_END diff --git a/Pods/Fabric/iOS/Fabric.framework/Headers/Fabric.h b/Pods/Fabric/iOS/Fabric.framework/Headers/Fabric.h new file mode 100644 index 0000000000..ecbdb53b84 --- /dev/null +++ b/Pods/Fabric/iOS/Fabric.framework/Headers/Fabric.h @@ -0,0 +1,82 @@ +// +// Fabric.h +// Fabric +// +// Copyright (C) 2015 Twitter, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#import +#import "FABAttributes.h" + +NS_ASSUME_NONNULL_BEGIN + +#if TARGET_OS_IPHONE +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 60000 + #error "Fabric's minimum iOS version is 6.0" +#endif +#else +#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1070 + #error "Fabric's minimum OS X version is 10.7" +#endif +#endif + +/** + * Fabric Base. Coordinates configuration and starts all provided kits. + */ +@interface Fabric : NSObject + +/** + * Initialize Fabric and all provided kits. Call this method within your App Delegate's `application:didFinishLaunchingWithOptions:` and provide the kits you wish to use. + * + * For example, in Objective-C: + * + * `[Fabric with:@[[Crashlytics class], [Twitter class], [Digits class], [MoPub class]]];` + * + * Swift: + * + * `Fabric.with([Crashlytics.self(), Twitter.self(), Digits.self(), MoPub.self()])` + * + * Only the first call to this method is honored. Subsequent calls are no-ops. + * + * @param kitClasses An array of kit Class objects + * + * @return Returns the shared Fabric instance. In most cases this can be ignored. + */ ++ (instancetype)with:(NSArray *)kitClasses; + +/** + * Returns the Fabric singleton object. + */ ++ (instancetype)sharedSDK; + +/** + * This BOOL enables or disables debug logging, such as kit version information. The default value is NO. + */ +@property (nonatomic, assign) BOOL debug; + +/** + * Unavailable. Use `+sharedSDK` to retrieve the shared Fabric instance. + */ +- (id)init FAB_UNAVAILABLE("Use +sharedSDK to retrieve the shared Fabric instance."); + +/** + * Unavailable. Use `+sharedSDK` to retrieve the shared Fabric instance. + */ ++ (instancetype)new FAB_UNAVAILABLE("Use +sharedSDK to retrieve the shared Fabric instance."); + +@end + +NS_ASSUME_NONNULL_END + diff --git a/Pods/Fabric/iOS/Fabric.framework/Info.plist b/Pods/Fabric/iOS/Fabric.framework/Info.plist new file mode 100644 index 0000000000..46b5064836 Binary files /dev/null and b/Pods/Fabric/iOS/Fabric.framework/Info.plist differ diff --git a/Pods/Fabric/iOS/Fabric.framework/Modules/module.modulemap b/Pods/Fabric/iOS/Fabric.framework/Modules/module.modulemap new file mode 100644 index 0000000000..2a312239dd --- /dev/null +++ b/Pods/Fabric/iOS/Fabric.framework/Modules/module.modulemap @@ -0,0 +1,6 @@ +framework module Fabric { + umbrella header "Fabric.h" + + export * + module * { export * } +} \ No newline at end of file diff --git a/Pods/Fabric/iOS/Fabric.framework/run b/Pods/Fabric/iOS/Fabric.framework/run new file mode 100755 index 0000000000..9058ea62c0 --- /dev/null +++ b/Pods/Fabric/iOS/Fabric.framework/run @@ -0,0 +1,28 @@ +#!/bin/sh + +# run +# +# Copyright (c) 2015 Crashlytics. All rights reserved. + +# Figure out where we're being called from +DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) + +# Quote path in case of spaces or special chars +DIR="\"${DIR}" + +PATH_SEP="/" +VALIDATE_COMMAND="uploadDSYM\" $@ validate run-script" +UPLOAD_COMMAND="uploadDSYM\" $@ run-script" + +# Ensure params are as expected, run in sync mode to validate +eval $DIR$PATH_SEP$VALIDATE_COMMAND +return_code=$? + +if [[ $return_code != 0 ]]; then + exit $return_code +fi + +# Verification passed, upload dSYM in background to prevent Xcode from waiting +# Note: Validation is performed again before upload. +# Output can still be found in Console.app +eval $DIR$PATH_SEP$UPLOAD_COMMAND > /dev/null 2>&1 & diff --git a/Pods/Fabric/iOS/Fabric.framework/uploadDSYM b/Pods/Fabric/iOS/Fabric.framework/uploadDSYM new file mode 100755 index 0000000000..2e823acfc2 Binary files /dev/null and b/Pods/Fabric/iOS/Fabric.framework/uploadDSYM differ diff --git a/Pods/Fabric/run b/Pods/Fabric/run new file mode 100755 index 0000000000..9058ea62c0 --- /dev/null +++ b/Pods/Fabric/run @@ -0,0 +1,28 @@ +#!/bin/sh + +# run +# +# Copyright (c) 2015 Crashlytics. All rights reserved. + +# Figure out where we're being called from +DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) + +# Quote path in case of spaces or special chars +DIR="\"${DIR}" + +PATH_SEP="/" +VALIDATE_COMMAND="uploadDSYM\" $@ validate run-script" +UPLOAD_COMMAND="uploadDSYM\" $@ run-script" + +# Ensure params are as expected, run in sync mode to validate +eval $DIR$PATH_SEP$VALIDATE_COMMAND +return_code=$? + +if [[ $return_code != 0 ]]; then + exit $return_code +fi + +# Verification passed, upload dSYM in background to prevent Xcode from waiting +# Note: Validation is performed again before upload. +# Output can still be found in Console.app +eval $DIR$PATH_SEP$UPLOAD_COMMAND > /dev/null 2>&1 & diff --git a/Pods/Fabric/upload-symbols b/Pods/Fabric/upload-symbols new file mode 100755 index 0000000000..b41105957c Binary files /dev/null and b/Pods/Fabric/upload-symbols differ diff --git a/Pods/Fabric/uploadDSYM b/Pods/Fabric/uploadDSYM new file mode 100755 index 0000000000..2e823acfc2 Binary files /dev/null and b/Pods/Fabric/uploadDSYM differ diff --git a/Pods/Firebase/CoreOnly/Sources/Firebase.h b/Pods/Firebase/CoreOnly/Sources/Firebase.h new file mode 100755 index 0000000000..6461547d8e --- /dev/null +++ b/Pods/Firebase/CoreOnly/Sources/Firebase.h @@ -0,0 +1,105 @@ +#import + +#if !defined(__has_include) + #error "Firebase.h won't import anything if your compiler doesn't support __has_include. Please \ + import the headers individually." +#else + #if __has_include() + #import + #else + #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING + #warning "FirebaseAnalytics.framework is not included in your target. Please add \ +`Firebase/Core` to your Podfile or add FirebaseAnalytics.framework to your project to ensure \ +Firebase services work as intended." + #endif // #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + +#endif // defined(__has_include) diff --git a/Pods/Firebase/CoreOnly/Sources/module.modulemap b/Pods/Firebase/CoreOnly/Sources/module.modulemap new file mode 100755 index 0000000000..3685b54a68 --- /dev/null +++ b/Pods/Firebase/CoreOnly/Sources/module.modulemap @@ -0,0 +1,4 @@ +module Firebase { + export * + header "Firebase.h" +} \ No newline at end of file diff --git a/Pods/Firebase/README.md b/Pods/Firebase/README.md new file mode 100755 index 0000000000..49aa2ee0c8 --- /dev/null +++ b/Pods/Firebase/README.md @@ -0,0 +1,87 @@ +# Firebase APIs for iOS + +Simplify your iOS development, grow your user base, and monetize more +effectively with Firebase services. + +Much more information can be found at [https://firebase.google.com](https://firebase.google.com). + +## Install a Firebase SDK using CocoaPods + +Firebase distributes several iOS specific APIs and SDKs via CocoaPods. +You can install the CocoaPods tool on OS X by running the following command from +the terminal. Detailed information is available in the [Getting Started +guide](https://guides.cocoapods.org/using/getting-started.html#getting-started). + +``` +$ sudo gem install cocoapods +``` + +## Try out an SDK + +You can try any of the SDKs with `pod try`. Run the following command and select +the SDK you are interested in when prompted: + +``` +$ pod try Firebase +``` + +Note that some SDKs may require credentials. More information is available in +the SDK-specific documentation at [https://firebase.google.com/docs/](https://firebase.google.com/docs/). + +## Add a Firebase SDK to your iOS app + +CocoaPods is used to install and manage dependencies in existing Xcode projects. + +1. Create an Xcode project, and save it to your local machine. +2. Create a file named `Podfile` in your project directory. This file defines + your project's dependencies, and is commonly referred to as a Podspec. +3. Open `Podfile`, and add your dependencies. A simple Podspec is shown here: + + ``` + platform :ios, '8.0' + pod 'Firebase' + ``` + +4. Save the file. + +5. Open a terminal and `cd` to the directory containing the Podfile. + + ``` + $ cd /project/ + ``` + +6. Run the `pod install` command. This will install the SDKs specified in the + Podspec, along with any dependencies they may have. + + ``` + $ pod install + ``` + +7. Open your app's `.xcworkspace` file to launch Xcode. Use this file for all + development on your app. + +8. You can also install other Firebase SDKs by adding the subspecs in the + Podfile. + + ``` + pod 'Firebase/AdMob' + pod 'Firebase/Analytics' + pod 'Firebase/Auth' + pod 'Firebase/Crash' + pod 'Firebase/Database' + pod 'Firebase/DynamicLinks' + pod 'Firebase/Firestore' + pod 'Firebase/Functions' + pod 'Firebase/Invites' + pod 'Firebase/Messaging' + pod 'Firebase/MLCommon' + pod 'Firebase/MLModelInterpreter' + pod 'Firebase/MLVision' + pod 'Firebase/MLVisionBarcodeModel' + pod 'Firebase/MLVisionFaceModel' + pod 'Firebase/MLVisionLabelModel' + pod 'Firebase/MLVisionTextModel' + pod 'Firebase/Performance' + pod 'Firebase/RemoteConfig' + pod 'Firebase/Storage' + ``` diff --git a/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/FIRAnalyticsConnector b/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/FIRAnalyticsConnector new file mode 100755 index 0000000000..897b5da29e Binary files /dev/null and b/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/FIRAnalyticsConnector differ diff --git a/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/Modules/module.modulemap b/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/Modules/module.modulemap new file mode 100755 index 0000000000..73fb1d7a0f --- /dev/null +++ b/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/Modules/module.modulemap @@ -0,0 +1,5 @@ +framework module FIRAnalyticsConnector { + export * + module * { export *} + link framework "Security" + link framework "SystemConfiguration"} diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/FirebaseAnalytics b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/FirebaseAnalytics new file mode 100755 index 0000000000..b20d5d25c2 Binary files /dev/null and b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/FirebaseAnalytics differ diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h new file mode 100755 index 0000000000..d499af668b --- /dev/null +++ b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h @@ -0,0 +1,62 @@ +#import + +#import "FIRAnalytics.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Provides App Delegate handlers to be used in your App Delegate. + * + * To save time integrating Firebase Analytics in an application, Firebase Analytics does not + * require delegation implementation from the AppDelegate. Instead this is automatically done by + * Firebase Analytics. Should you choose instead to delegate manually, you can turn off the App + * Delegate Proxy by adding FirebaseAppDelegateProxyEnabled into your app's Info.plist and setting + * it to NO, and adding the methods in this category to corresponding delegation handlers. + * + * To handle Universal Links, you must return YES in + * [UIApplicationDelegate application:didFinishLaunchingWithOptions:]. + */ +@interface FIRAnalytics (AppDelegate) + +/** + * Handles events related to a URL session that are waiting to be processed. + * + * For optimal use of Firebase Analytics, call this method from the + * [UIApplicationDelegate application:handleEventsForBackgroundURLSession:completionHandler] + * method of the app delegate in your app. + * + * @param identifier The identifier of the URL session requiring attention. + * @param completionHandler The completion handler to call when you finish processing the events. + * Calling this completion handler lets the system know that your app's user interface is + * updated and a new snapshot can be taken. + */ ++ (void)handleEventsForBackgroundURLSession:(NSString *)identifier + completionHandler:(nullable void (^)(void))completionHandler; + +/** + * Handles the event when the app is launched by a URL. + * + * Call this method from [UIApplicationDelegate application:openURL:options:] (on iOS 9.0 and + * above), or [UIApplicationDelegate application:openURL:sourceApplication:annotation:] (on + * iOS 8.x and below) in your app. + * + * @param url The URL resource to open. This resource can be a network resource or a file. + */ ++ (void)handleOpenURL:(NSURL *)url; + +/** + * Handles the event when the app receives data associated with user activity that includes a + * Universal Link (on iOS 9.0 and above). + * + * Call this method from [UIApplication continueUserActivity:restorationHandler:] in your app + * delegate (on iOS 9.0 and above). + * + * @param userActivity The activity object containing the data associated with the task the user + * was performing. + */ ++ (void)handleUserActivity:(id)userActivity; + +@end + +NS_ASSUME_NONNULL_END + diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h new file mode 100755 index 0000000000..39d23f18f2 --- /dev/null +++ b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h @@ -0,0 +1,119 @@ +#import + +#import "FIREventNames.h" +#import "FIRParameterNames.h" +#import "FIRUserPropertyNames.h" + +NS_ASSUME_NONNULL_BEGIN + +/// The top level Firebase Analytics singleton that provides methods for logging events and setting +/// user properties. See the developer guides for general +/// information on using Firebase Analytics in your apps. +NS_SWIFT_NAME(Analytics) +@interface FIRAnalytics : NSObject + +/// Logs an app event. The event can have up to 25 parameters. Events with the same name must have +/// the same parameters. Up to 500 event names are supported. Using predefined events and/or +/// parameters is recommended for optimal reporting. +/// +/// The following event names are reserved and cannot be used: +///
    +///
  • ad_activeview
  • +///
  • ad_click
  • +///
  • ad_exposure
  • +///
  • ad_impression
  • +///
  • ad_query
  • +///
  • adunit_exposure
  • +///
  • app_clear_data
  • +///
  • app_remove
  • +///
  • app_update
  • +///
  • error
  • +///
  • first_open
  • +///
  • in_app_purchase
  • +///
  • notification_dismiss
  • +///
  • notification_foreground
  • +///
  • notification_open
  • +///
  • notification_receive
  • +///
  • os_update
  • +///
  • screen_view
  • +///
  • session_start
  • +///
  • user_engagement
  • +///
+/// +/// @param name The name of the event. Should contain 1 to 40 alphanumeric characters or +/// underscores. The name must start with an alphabetic character. Some event names are +/// reserved. See FIREventNames.h for the list of reserved event names. The "firebase_", +/// "google_", and "ga_" prefixes are reserved and should not be used. Note that event names are +/// case-sensitive and that logging two events whose names differ only in case will result in +/// two distinct events. +/// @param parameters The dictionary of event parameters. Passing nil indicates that the event has +/// no parameters. Parameter names can be up to 40 characters long and must start with an +/// alphabetic character and contain only alphanumeric characters and underscores. Only NSString +/// and NSNumber (signed 64-bit integer and 64-bit floating-point number) parameter types are +/// supported. NSString parameter values can be up to 100 characters long. The "firebase_", +/// "google_", and "ga_" prefixes are reserved and should not be used for parameter names. ++ (void)logEventWithName:(NSString *)name + parameters:(nullable NSDictionary *)parameters + NS_SWIFT_NAME(logEvent(_:parameters:)); + +/// Sets a user property to a given value. Up to 25 user property names are supported. Once set, +/// user property values persist throughout the app lifecycle and across sessions. +/// +/// The following user property names are reserved and cannot be used: +///
    +///
  • first_open_time
  • +///
  • last_deep_link_referrer
  • +///
  • user_id
  • +///
+/// +/// @param value The value of the user property. Values can be up to 36 characters long. Setting the +/// value to nil removes the user property. +/// @param name The name of the user property to set. Should contain 1 to 24 alphanumeric characters +/// or underscores and must start with an alphabetic character. The "firebase_", "google_", and +/// "ga_" prefixes are reserved and should not be used for user property names. ++ (void)setUserPropertyString:(nullable NSString *)value forName:(NSString *)name + NS_SWIFT_NAME(setUserProperty(_:forName:)); + +/// Sets the user ID property. This feature must be used in accordance with +/// Google's Privacy Policy +/// +/// @param userID The user ID to ascribe to the user of this app on this device, which must be +/// non-empty and no more than 256 characters long. Setting userID to nil removes the user ID. ++ (void)setUserID:(nullable NSString *)userID; + +/// Sets the current screen name, which specifies the current visual context in your app. This helps +/// identify the areas in your app where users spend their time and how they interact with your app. +/// Must be called on the main thread. +/// +/// Note that screen reporting is enabled automatically and records the class name of the current +/// UIViewController for you without requiring you to call this method. If you implement +/// viewDidAppear in your UIViewController but do not call [super viewDidAppear:], that screen class +/// will not be automatically tracked. The class name can optionally be overridden by calling this +/// method in the viewDidAppear callback of your UIViewController and specifying the +/// screenClassOverride parameter. setScreenName:screenClass: must be called after +/// [super viewDidAppear:]. +/// +/// If your app does not use a distinct UIViewController for each screen, you should call this +/// method and specify a distinct screenName each time a new screen is presented to the user. +/// +/// The screen name and screen class remain in effect until the current UIViewController changes or +/// a new call to setScreenName:screenClass: is made. +/// +/// @param screenName The name of the current screen. Should contain 1 to 100 characters. Set to nil +/// to clear the current screen name. +/// @param screenClassOverride The name of the screen class. Should contain 1 to 100 characters. By +/// default this is the class name of the current UIViewController. Set to nil to revert to the +/// default class name. ++ (void)setScreenName:(nullable NSString *)screenName + screenClass:(nullable NSString *)screenClassOverride; + +/// The unique ID for this instance of the application. ++ (NSString *)appInstanceID; + +/// Clears all analytics data for this instance from the device and resets the app instance ID. +/// FIRAnalyticsConfiguration values will be reset to the default values. ++ (void)resetAnalyticsData; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h new file mode 100755 index 0000000000..c70c53e25f --- /dev/null +++ b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h @@ -0,0 +1,407 @@ +/// @file FIREventNames.h +/// +/// Predefined event names. +/// +/// An Event is an important occurrence in your app that you want to measure. You can report up to +/// 500 different types of Events per app and you can associate up to 25 unique parameters with each +/// Event type. Some common events are suggested below, but you may also choose to specify custom +/// Event types that are associated with your specific app. Each event type is identified by a +/// unique name. Event names can be up to 40 characters long, may only contain alphanumeric +/// characters and underscores ("_"), and must start with an alphabetic character. The "firebase_", +/// "google_", and "ga_" prefixes are reserved and should not be used. + +#import + +/// Add Payment Info event. This event signifies that a user has submitted their payment information +/// to your app. +static NSString *const kFIREventAddPaymentInfo NS_SWIFT_NAME(AnalyticsEventAddPaymentInfo) = + @"add_payment_info"; + +/// E-Commerce Add To Cart event. This event signifies that an item was added to a cart for +/// purchase. Add this event to a funnel with kFIREventEcommercePurchase to gauge the effectiveness +/// of your checkout process. Note: If you supply the @c kFIRParameterValue parameter, you must +/// also supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed +/// accurately. Params: +/// +///
    +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
+static NSString *const kFIREventAddToCart NS_SWIFT_NAME(AnalyticsEventAddToCart) = @"add_to_cart"; + +/// E-Commerce Add To Wishlist event. This event signifies that an item was added to a wishlist. +/// Use this event to identify popular gift items in your app. Note: If you supply the +/// @c kFIRParameterValue parameter, you must also supply the @c kFIRParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
+static NSString *const kFIREventAddToWishlist NS_SWIFT_NAME(AnalyticsEventAddToWishlist) = + @"add_to_wishlist"; + +/// App Open event. By logging this event when an App becomes active, developers can understand how +/// often users leave and return during the course of a Session. Although Sessions are automatically +/// reported, this event can provide further clarification around the continuous engagement of +/// app-users. +static NSString *const kFIREventAppOpen NS_SWIFT_NAME(AnalyticsEventAppOpen) = @"app_open"; + +/// E-Commerce Begin Checkout event. This event signifies that a user has begun the process of +/// checking out. Add this event to a funnel with your kFIREventEcommercePurchase event to gauge the +/// effectiveness of your checkout process. Note: If you supply the @c kFIRParameterValue +/// parameter, you must also supply the @c kFIRParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) +/// for travel bookings
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • +///
+static NSString *const kFIREventBeginCheckout NS_SWIFT_NAME(AnalyticsEventBeginCheckout) = + @"begin_checkout"; + +/// Campaign Detail event. Log this event to supply the referral details of a re-engagement +/// campaign. Note: you must supply at least one of the required parameters kFIRParameterSource, +/// kFIRParameterMedium or kFIRParameterCampaign. Params: +/// +///
    +///
  • @c kFIRParameterSource (NSString)
  • +///
  • @c kFIRParameterMedium (NSString)
  • +///
  • @c kFIRParameterCampaign (NSString)
  • +///
  • @c kFIRParameterTerm (NSString) (optional)
  • +///
  • @c kFIRParameterContent (NSString) (optional)
  • +///
  • @c kFIRParameterAdNetworkClickID (NSString) (optional)
  • +///
  • @c kFIRParameterCP1 (NSString) (optional)
  • +///
+static NSString *const kFIREventCampaignDetails NS_SWIFT_NAME(AnalyticsEventCampaignDetails) = + @"campaign_details"; + +/// Checkout progress. Params: +/// +///
    +///
  • @c kFIRParameterCheckoutStep (unsigned 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterCheckoutOption (NSString) (optional)
  • +///
+static NSString *const kFIREventCheckoutProgress NS_SWIFT_NAME(AnalyticsEventCheckoutProgress) = + @"checkout_progress"; + +/// Earn Virtual Currency event. This event tracks the awarding of virtual currency in your app. Log +/// this along with @c kFIREventSpendVirtualCurrency to better understand your virtual economy. +/// Params: +/// +///
    +///
  • @c kFIRParameterVirtualCurrencyName (NSString)
  • +///
  • @c kFIRParameterValue (signed 64-bit integer or double as NSNumber)
  • +///
+static NSString *const kFIREventEarnVirtualCurrency + NS_SWIFT_NAME(AnalyticsEventEarnVirtualCurrency) = @"earn_virtual_currency"; + +/// E-Commerce Purchase event. This event signifies that an item was purchased by a user. Note: +/// This is different from the in-app purchase event, which is reported automatically for App +/// Store-based apps. Note: If you supply the @c kFIRParameterValue parameter, you must also +/// supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed +/// accurately. Params: +/// +///
    +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • +///
  • @c kFIRParameterTax (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterShipping (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCoupon (NSString) (optional)
  • +///
  • @c kFIRParameterLocation (NSString) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) +/// for travel bookings
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • +///
+static NSString *const kFIREventEcommercePurchase NS_SWIFT_NAME(AnalyticsEventEcommercePurchase) = + @"ecommerce_purchase"; + +/// Generate Lead event. Log this event when a lead has been generated in the app to understand the +/// efficacy of your install and re-engagement campaigns. Note: If you supply the +/// @c kFIRParameterValue parameter, you must also supply the @c kFIRParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
+static NSString *const kFIREventGenerateLead NS_SWIFT_NAME(AnalyticsEventGenerateLead) = + @"generate_lead"; + +/// Join Group event. Log this event when a user joins a group such as a guild, team or family. Use +/// this event to analyze how popular certain groups or social features are in your app. Params: +/// +///
    +///
  • @c kFIRParameterGroupID (NSString)
  • +///
+static NSString *const kFIREventJoinGroup NS_SWIFT_NAME(AnalyticsEventJoinGroup) = @"join_group"; + +/// Level Up event. This event signifies that a player has leveled up in your gaming app. It can +/// help you gauge the level distribution of your userbase and help you identify certain levels that +/// are difficult to pass. Params: +/// +///
    +///
  • @c kFIRParameterLevel (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterCharacter (NSString) (optional)
  • +///
+static NSString *const kFIREventLevelUp NS_SWIFT_NAME(AnalyticsEventLevelUp) = @"level_up"; + +/// Login event. Apps with a login feature can report this event to signify that a user has logged +/// in. +static NSString *const kFIREventLogin NS_SWIFT_NAME(AnalyticsEventLogin) = @"login"; + +/// Post Score event. Log this event when the user posts a score in your gaming app. This event can +/// help you understand how users are actually performing in your game and it can help you correlate +/// high scores with certain audiences or behaviors. Params: +/// +///
    +///
  • @c kFIRParameterScore (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterLevel (signed 64-bit integer as NSNumber) (optional)
  • +///
  • @c kFIRParameterCharacter (NSString) (optional)
  • +///
+static NSString *const kFIREventPostScore NS_SWIFT_NAME(AnalyticsEventPostScore) = @"post_score"; + +/// Present Offer event. This event signifies that the app has presented a purchase offer to a user. +/// Add this event to a funnel with the kFIREventAddToCart and kFIREventEcommercePurchase to gauge +/// your conversion process. Note: If you supply the @c kFIRParameterValue parameter, you must +/// also supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed +/// accurately. Params: +/// +///
    +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
+static NSString *const kFIREventPresentOffer NS_SWIFT_NAME(AnalyticsEventPresentOffer) = + @"present_offer"; + +/// E-Commerce Purchase Refund event. This event signifies that an item purchase was refunded. +/// Note: If you supply the @c kFIRParameterValue parameter, you must also supply the +/// @c kFIRParameterCurrency parameter so that revenue metrics can be computed accurately. +/// Params: +/// +///
    +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • +///
+static NSString *const kFIREventPurchaseRefund NS_SWIFT_NAME(AnalyticsEventPurchaseRefund) = + @"purchase_refund"; + +/// Remove from cart event. Params: +/// +///
    +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
+static NSString *const kFIREventRemoveFromCart NS_SWIFT_NAME(AnalyticsEventRemoveFromCart) = + @"remove_from_cart"; + +/// Search event. Apps that support search features can use this event to contextualize search +/// operations by supplying the appropriate, corresponding parameters. This event can help you +/// identify the most popular content in your app. Params: +/// +///
    +///
  • @c kFIRParameterSearchTerm (NSString)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) +/// for travel bookings
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • +///
+static NSString *const kFIREventSearch NS_SWIFT_NAME(AnalyticsEventSearch) = @"search"; + +/// Select Content event. This general purpose event signifies that a user has selected some content +/// of a certain type in an app. The content can be any object in your app. This event can help you +/// identify popular content and categories of content in your app. Params: +/// +///
    +///
  • @c kFIRParameterContentType (NSString)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
+static NSString *const kFIREventSelectContent NS_SWIFT_NAME(AnalyticsEventSelectContent) = + @"select_content"; + +/// Set checkout option. Params: +/// +///
    +///
  • @c kFIRParameterCheckoutStep (unsigned 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterCheckoutOption (NSString)
  • +///
+static NSString *const kFIREventSetCheckoutOption NS_SWIFT_NAME(AnalyticsEventSetCheckoutOption) = + @"set_checkout_option"; + +/// Share event. Apps with social features can log the Share event to identify the most viral +/// content. Params: +/// +///
    +///
  • @c kFIRParameterContentType (NSString)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
+static NSString *const kFIREventShare NS_SWIFT_NAME(AnalyticsEventShare) = @"share"; + +/// Sign Up event. This event indicates that a user has signed up for an account in your app. The +/// parameter signifies the method by which the user signed up. Use this event to understand the +/// different behaviors between logged in and logged out users. Params: +/// +///
    +///
  • @c kFIRParameterSignUpMethod (NSString)
  • +///
+static NSString *const kFIREventSignUp NS_SWIFT_NAME(AnalyticsEventSignUp) = @"sign_up"; + +/// Spend Virtual Currency event. This event tracks the sale of virtual goods in your app and can +/// help you identify which virtual goods are the most popular objects of purchase. Params: +/// +///
    +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterVirtualCurrencyName (NSString)
  • +///
  • @c kFIRParameterValue (signed 64-bit integer or double as NSNumber)
  • +///
+static NSString *const kFIREventSpendVirtualCurrency + NS_SWIFT_NAME(AnalyticsEventSpendVirtualCurrency) = @"spend_virtual_currency"; + +/// Tutorial Begin event. This event signifies the start of the on-boarding process in your app. Use +/// this in a funnel with kFIREventTutorialComplete to understand how many users complete this +/// process and move on to the full app experience. +static NSString *const kFIREventTutorialBegin NS_SWIFT_NAME(AnalyticsEventTutorialBegin) = + @"tutorial_begin"; + +/// Tutorial End event. Use this event to signify the user's completion of your app's on-boarding +/// process. Add this to a funnel with kFIREventTutorialBegin to gauge the completion rate of your +/// on-boarding process. +static NSString *const kFIREventTutorialComplete NS_SWIFT_NAME(AnalyticsEventTutorialComplete) = + @"tutorial_complete"; + +/// Unlock Achievement event. Log this event when the user has unlocked an achievement in your +/// game. Since achievements generally represent the breadth of a gaming experience, this event can +/// help you understand how many users are experiencing all that your game has to offer. Params: +/// +///
    +///
  • @c kFIRParameterAchievementID (NSString)
  • +///
+static NSString *const kFIREventUnlockAchievement NS_SWIFT_NAME(AnalyticsEventUnlockAchievement) = + @"unlock_achievement"; + +/// View Item event. This event signifies that some content was shown to the user. This content may +/// be a product, a webpage or just a simple image or text. Use the appropriate parameters to +/// contextualize the event. Use this event to discover the most popular items viewed in your app. +/// Note: If you supply the @c kFIRParameterValue parameter, you must also supply the +/// @c kFIRParameterCurrency parameter so that revenue metrics can be computed accurately. +/// Params: +/// +///
    +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
  • @c kFIRParameterFlightNumber (NSString) (optional) for travel bookings
  • +///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) +/// for travel bookings
  • +///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for +/// travel bookings
  • +///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for +/// travel bookings
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterSearchTerm (NSString) (optional) for travel bookings
  • +///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • +///
+static NSString *const kFIREventViewItem NS_SWIFT_NAME(AnalyticsEventViewItem) = @"view_item"; + +/// View Item List event. Log this event when the user has been presented with a list of items of a +/// certain category. Params: +/// +///
    +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
+static NSString *const kFIREventViewItemList NS_SWIFT_NAME(AnalyticsEventViewItemList) = + @"view_item_list"; + +/// View Search Results event. Log this event when the user has been presented with the results of a +/// search. Params: +/// +///
    +///
  • @c kFIRParameterSearchTerm (NSString)
  • +///
+static NSString *const kFIREventViewSearchResults NS_SWIFT_NAME(AnalyticsEventViewSearchResults) = + @"view_search_results"; + +/// Level Start event. Log this event when the user starts a new level. Params: +/// +///
    +///
  • @c kFIRParameterLevelName (NSString)
  • +///
+static NSString *const kFIREventLevelStart NS_SWIFT_NAME(AnalyticsEventLevelStart) = + @"level_start"; + +/// Level End event. Log this event when the user finishes a level. Params: +/// +///
    +///
  • @c kFIRParameterLevelName (NSString)
  • +///
  • @c kFIRParameterSuccess (NSString)
  • +///
+static NSString *const kFIREventLevelEnd NS_SWIFT_NAME(AnalyticsEventLevelEnd) = @"level_end"; diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h new file mode 100755 index 0000000000..4e1366ce91 --- /dev/null +++ b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h @@ -0,0 +1,507 @@ +/// @file FIRParameterNames.h +/// +/// Predefined event parameter names. +/// +/// Params supply information that contextualize Events. You can associate up to 25 unique Params +/// with each Event type. Some Params are suggested below for certain common Events, but you are +/// not limited to these. You may supply extra Params for suggested Events or custom Params for +/// Custom events. Param names can be up to 40 characters long, may only contain alphanumeric +/// characters and underscores ("_"), and must start with an alphabetic character. Param values can +/// be up to 100 characters long. The "firebase_", "google_", and "ga_" prefixes are reserved and +/// should not be used. + +#import + +/// Game achievement ID (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterAchievementID : @"10_matches_won",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterAchievementID NS_SWIFT_NAME(AnalyticsParameterAchievementID) = + @"achievement_id"; + +/// Ad Network Click ID (NSString). Used for network-specific click IDs which vary in format. +///
+///     NSDictionary *params = @{
+///       kFIRParameterAdNetworkClickID : @"1234567",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterAdNetworkClickID + NS_SWIFT_NAME(AnalyticsParameterAdNetworkClickID) = @"aclid"; + +/// The store or affiliation from which this transaction occurred (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterAffiliation : @"Google Store",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterAffiliation NS_SWIFT_NAME(AnalyticsParameterAffiliation) = + @"affiliation"; + +/// The individual campaign name, slogan, promo code, etc. Some networks have pre-defined macro to +/// capture campaign information, otherwise can be populated by developer. Highly Recommended +/// (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCampaign : @"winter_promotion",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCampaign NS_SWIFT_NAME(AnalyticsParameterCampaign) = + @"campaign"; + +/// Character used in game (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCharacter : @"beat_boss",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCharacter NS_SWIFT_NAME(AnalyticsParameterCharacter) = + @"character"; + +/// The checkout step (1..N) (unsigned 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCheckoutStep : @"1",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCheckoutStep NS_SWIFT_NAME(AnalyticsParameterCheckoutStep) = + @"checkout_step"; + +/// Some option on a step in an ecommerce flow (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCheckoutOption : @"Visa",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCheckoutOption + NS_SWIFT_NAME(AnalyticsParameterCheckoutOption) = @"checkout_option"; + +/// Campaign content (NSString). +static NSString *const kFIRParameterContent NS_SWIFT_NAME(AnalyticsParameterContent) = @"content"; + +/// Type of content selected (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterContentType : @"news article",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterContentType NS_SWIFT_NAME(AnalyticsParameterContentType) = + @"content_type"; + +/// Coupon code for a purchasable item (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCoupon : @"zz123",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCoupon NS_SWIFT_NAME(AnalyticsParameterCoupon) = @"coupon"; + +/// Campaign custom parameter (NSString). Used as a method of capturing custom data in a campaign. +/// Use varies by network. +///
+///     NSDictionary *params = @{
+///       kFIRParameterCP1 : @"custom_data",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCP1 NS_SWIFT_NAME(AnalyticsParameterCP1) = @"cp1"; + +/// The name of a creative used in a promotional spot (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCreativeName : @"Summer Sale",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCreativeName NS_SWIFT_NAME(AnalyticsParameterCreativeName) = + @"creative_name"; + +/// The name of a creative slot (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCreativeSlot : @"summer_banner2",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCreativeSlot NS_SWIFT_NAME(AnalyticsParameterCreativeSlot) = + @"creative_slot"; + +/// Purchase currency in 3-letter +/// ISO_4217 format (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCurrency : @"USD",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCurrency NS_SWIFT_NAME(AnalyticsParameterCurrency) = + @"currency"; + +/// Flight or Travel destination (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterDestination : @"Mountain View, CA",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterDestination NS_SWIFT_NAME(AnalyticsParameterDestination) = + @"destination"; + +/// The arrival date, check-out date or rental end date for the item. This should be in +/// YYYY-MM-DD format (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterEndDate : @"2015-09-14",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterEndDate NS_SWIFT_NAME(AnalyticsParameterEndDate) = @"end_date"; + +/// Flight number for travel events (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterFlightNumber : @"ZZ800",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterFlightNumber NS_SWIFT_NAME(AnalyticsParameterFlightNumber) = + @"flight_number"; + +/// Group/clan/guild ID (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterGroupID : @"g1",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterGroupID NS_SWIFT_NAME(AnalyticsParameterGroupID) = @"group_id"; + +/// Index of an item in a list (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterIndex : @(1),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterIndex NS_SWIFT_NAME(AnalyticsParameterIndex) = @"index"; + +/// Item brand (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemBrand : @"Google",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemBrand NS_SWIFT_NAME(AnalyticsParameterItemBrand) = + @"item_brand"; + +/// Item category (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemCategory : @"t-shirts",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemCategory NS_SWIFT_NAME(AnalyticsParameterItemCategory) = + @"item_category"; + +/// Item ID (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemID : @"p7654",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemID NS_SWIFT_NAME(AnalyticsParameterItemID) = @"item_id"; + +/// The Google Place ID (NSString) that +/// corresponds to the associated item. Alternatively, you can supply your own custom Location ID. +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemLocationID : @"ChIJiyj437sx3YAR9kUWC8QkLzQ",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemLocationID + NS_SWIFT_NAME(AnalyticsParameterItemLocationID) = @"item_location_id"; + +/// Item name (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemName : @"abc",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemName NS_SWIFT_NAME(AnalyticsParameterItemName) = + @"item_name"; + +/// The list in which the item was presented to the user (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemList : @"Search Results",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemList NS_SWIFT_NAME(AnalyticsParameterItemList) = + @"item_list"; + +/// Item variant (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemVariant : @"Red",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemVariant NS_SWIFT_NAME(AnalyticsParameterItemVariant) = + @"item_variant"; + +/// Level in game (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterLevel : @(42),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterLevel NS_SWIFT_NAME(AnalyticsParameterLevel) = @"level"; + +/// Location (NSString). The Google Place ID +/// that corresponds to the associated event. Alternatively, you can supply your own custom +/// Location ID. +///
+///     NSDictionary *params = @{
+///       kFIRParameterLocation : @"ChIJiyj437sx3YAR9kUWC8QkLzQ",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterLocation NS_SWIFT_NAME(AnalyticsParameterLocation) = + @"location"; + +/// The advertising or marketing medium, for example: cpc, banner, email, push. Highly recommended +/// (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterMedium : @"email",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterMedium NS_SWIFT_NAME(AnalyticsParameterMedium) = @"medium"; + +/// Number of nights staying at hotel (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterNumberOfNights : @(3),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterNumberOfNights + NS_SWIFT_NAME(AnalyticsParameterNumberOfNights) = @"number_of_nights"; + +/// Number of passengers traveling (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterNumberOfPassengers : @(11),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterNumberOfPassengers + NS_SWIFT_NAME(AnalyticsParameterNumberOfPassengers) = @"number_of_passengers"; + +/// Number of rooms for travel events (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterNumberOfRooms : @(2),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterNumberOfRooms NS_SWIFT_NAME(AnalyticsParameterNumberOfRooms) = + @"number_of_rooms"; + +/// Flight or Travel origin (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterOrigin : @"Mountain View, CA",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterOrigin NS_SWIFT_NAME(AnalyticsParameterOrigin) = @"origin"; + +/// Purchase price (double as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterPrice : @(1.0),
+///       kFIRParameterCurrency : @"USD",  // e.g. $1.00 USD
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterPrice NS_SWIFT_NAME(AnalyticsParameterPrice) = @"price"; + +/// Purchase quantity (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterQuantity : @(1),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterQuantity NS_SWIFT_NAME(AnalyticsParameterQuantity) = + @"quantity"; + +/// Score in game (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterScore : @(4200),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterScore NS_SWIFT_NAME(AnalyticsParameterScore) = @"score"; + +/// The search string/keywords used (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterSearchTerm : @"periodic table",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterSearchTerm NS_SWIFT_NAME(AnalyticsParameterSearchTerm) = + @"search_term"; + +/// Shipping cost (double as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterShipping : @(9.50),
+///       kFIRParameterCurrency : @"USD",  // e.g. $9.50 USD
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterShipping NS_SWIFT_NAME(AnalyticsParameterShipping) = + @"shipping"; + +/// Sign up method (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterSignUpMethod : @"google",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterSignUpMethod NS_SWIFT_NAME(AnalyticsParameterSignUpMethod) = + @"sign_up_method"; + +/// The origin of your traffic, such as an Ad network (for example, google) or partner (urban +/// airship). Identify the advertiser, site, publication, etc. that is sending traffic to your +/// property. Highly recommended (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterSource : @"InMobi",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterSource NS_SWIFT_NAME(AnalyticsParameterSource) = @"source"; + +/// The departure date, check-in date or rental start date for the item. This should be in +/// YYYY-MM-DD format (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterStartDate : @"2015-09-14",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterStartDate NS_SWIFT_NAME(AnalyticsParameterStartDate) = + @"start_date"; + +/// Tax amount (double as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterTax : @(1.0),
+///       kFIRParameterCurrency : @"USD",  // e.g. $1.00 USD
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterTax NS_SWIFT_NAME(AnalyticsParameterTax) = @"tax"; + +/// If you're manually tagging keyword campaigns, you should use utm_term to specify the keyword +/// (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterTerm : @"game",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterTerm NS_SWIFT_NAME(AnalyticsParameterTerm) = @"term"; + +/// A single ID for a ecommerce group transaction (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterTransactionID : @"ab7236dd9823",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterTransactionID NS_SWIFT_NAME(AnalyticsParameterTransactionID) = + @"transaction_id"; + +/// Travel class (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterTravelClass : @"business",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterTravelClass NS_SWIFT_NAME(AnalyticsParameterTravelClass) = + @"travel_class"; + +/// A context-specific numeric value which is accumulated automatically for each event type. This is +/// a general purpose parameter that is useful for accumulating a key metric that pertains to an +/// event. Examples include revenue, distance, time and points. Value should be specified as signed +/// 64-bit integer or double as NSNumber. Notes: Values for pre-defined currency-related events +/// (such as @c kFIREventAddToCart) should be supplied using double as NSNumber and must be +/// accompanied by a @c kFIRParameterCurrency parameter. The valid range of accumulated values is +/// [-9,223,372,036,854.77, 9,223,372,036,854.77]. Supplying a non-numeric value, omitting the +/// corresponding @c kFIRParameterCurrency parameter, or supplying an invalid +/// currency code for conversion events will cause that +/// conversion to be omitted from reporting. +///
+///     NSDictionary *params = @{
+///       kFIRParameterValue : @(3.99),
+///       kFIRParameterCurrency : @"USD",  // e.g. $3.99 USD
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterValue NS_SWIFT_NAME(AnalyticsParameterValue) = @"value"; + +/// Name of virtual currency type (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterVirtualCurrencyName : @"virtual_currency_name",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterVirtualCurrencyName + NS_SWIFT_NAME(AnalyticsParameterVirtualCurrencyName) = @"virtual_currency_name"; + +/// The name of a level in a game (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterLevelName : @"room_1",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterLevelName NS_SWIFT_NAME(AnalyticsParameterLevelName) = + @"level_name"; + +/// The result of an operation. Specify 1 to indicate success and 0 to indicate failure (unsigned +/// integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterSuccess : @(1),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterSuccess NS_SWIFT_NAME(AnalyticsParameterSuccess) = @"success"; diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h new file mode 100755 index 0000000000..f50707fa15 --- /dev/null +++ b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h @@ -0,0 +1,17 @@ +/// @file FIRUserPropertyNames.h +/// +/// Predefined user property names. +/// +/// A UserProperty is an attribute that describes the app-user. By supplying UserProperties, you can +/// later analyze different behaviors of various segments of your userbase. You may supply up to 25 +/// unique UserProperties per app, and you can use the name and value of your choosing for each one. +/// UserProperty names can be up to 24 characters long, may only contain alphanumeric characters and +/// underscores ("_"), and must start with an alphabetic character. UserProperty values can be up to +/// 36 characters long. The "firebase_", "google_", and "ga_" prefixes are reserved and should not +/// be used. + +#import + +/// The method used to sign in. For example, "google", "facebook" or "twitter". +static NSString *const kFIRUserPropertySignUpMethod + NS_SWIFT_NAME(AnalyticsUserPropertySignUpMethod) = @"sign_up_method"; diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h new file mode 100755 index 0000000000..ed7588a6b7 --- /dev/null +++ b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h @@ -0,0 +1,5 @@ +#import "FIRAnalytics+AppDelegate.h" +#import "FIRAnalytics.h" +#import "FIREventNames.h" +#import "FIRParameterNames.h" +#import "FIRUserPropertyNames.h" diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap new file mode 100755 index 0000000000..ef80595cd7 --- /dev/null +++ b/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap @@ -0,0 +1,10 @@ +framework module FirebaseAnalytics { + umbrella header "FirebaseAnalytics.h" + export * + module * { export *} + link "sqlite3" + link "z" + link framework "Security" + link framework "StoreKit" + link framework "SystemConfiguration" + link framework "UIKit"} diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/FirebaseCoreDiagnostics b/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/FirebaseCoreDiagnostics new file mode 100755 index 0000000000..8384856183 Binary files /dev/null and b/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/FirebaseCoreDiagnostics differ diff --git a/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/Modules/module.modulemap b/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/Modules/module.modulemap new file mode 100755 index 0000000000..bbcb94e31d --- /dev/null +++ b/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/Modules/module.modulemap @@ -0,0 +1,6 @@ +framework module FirebaseCoreDiagnostics { + export * + module * { export *} + link "z" + link framework "Security" + link framework "SystemConfiguration"} diff --git a/Pods/FirebaseCore/Firebase/Core/FIRAnalyticsConfiguration.m b/Pods/FirebaseCore/Firebase/Core/FIRAnalyticsConfiguration.m new file mode 100644 index 0000000000..33aa1687f5 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRAnalyticsConfiguration.m @@ -0,0 +1,69 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRAnalyticsConfiguration.h" + +#import "Private/FIRAnalyticsConfiguration+Internal.h" + +@implementation FIRAnalyticsConfiguration + ++ (FIRAnalyticsConfiguration *)sharedInstance { + static FIRAnalyticsConfiguration *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[FIRAnalyticsConfiguration alloc] init]; + }); + return sharedInstance; +} + +- (void)postNotificationName:(NSString *)name value:(id)value { + if (!name.length || !value) { + return; + } + [[NSNotificationCenter defaultCenter] postNotificationName:name + object:self + userInfo:@{name : value}]; +} + +- (void)setMinimumSessionInterval:(NSTimeInterval)minimumSessionInterval { + [self postNotificationName:kFIRAnalyticsConfigurationSetMinimumSessionIntervalNotification + value:@(minimumSessionInterval)]; +} + +- (void)setSessionTimeoutInterval:(NSTimeInterval)sessionTimeoutInterval { + [self postNotificationName:kFIRAnalyticsConfigurationSetSessionTimeoutIntervalNotification + value:@(sessionTimeoutInterval)]; +} + +- (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled { + [self setAnalyticsCollectionEnabled:analyticsCollectionEnabled persistSetting:YES]; +} + +- (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled + persistSetting:(BOOL)shouldPersist { + // Persist the measurementEnabledState. Use FIRAnalyticsEnabledState values instead of YES/NO. + FIRAnalyticsEnabledState analyticsEnabledState = + analyticsCollectionEnabled ? kFIRAnalyticsEnabledStateSetYes : kFIRAnalyticsEnabledStateSetNo; + if (shouldPersist) { + NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; + [userDefaults setObject:@(analyticsEnabledState) + forKey:kFIRAPersistedConfigMeasurementEnabledStateKey]; + [userDefaults synchronize]; + } + + [self postNotificationName:kFIRAnalyticsConfigurationSetEnabledNotification + value:@(analyticsCollectionEnabled)]; +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIRApp.m b/Pods/FirebaseCore/Firebase/Core/FIRApp.m new file mode 100644 index 0000000000..3b352fa7d1 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRApp.m @@ -0,0 +1,791 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include + +#import "FIRApp.h" +#import "FIRConfiguration.h" +#import "Private/FIRAnalyticsConfiguration+Internal.h" +#import "Private/FIRAppInternal.h" +#import "Private/FIRBundleUtil.h" +#import "Private/FIRComponentContainerInternal.h" +#import "Private/FIRCoreConfigurable.h" +#import "Private/FIRLogger.h" +#import "Private/FIROptionsInternal.h" + +NSString *const kFIRServiceAdMob = @"AdMob"; +NSString *const kFIRServiceAuth = @"Auth"; +NSString *const kFIRServiceAuthUI = @"AuthUI"; +NSString *const kFIRServiceCrash = @"Crash"; +NSString *const kFIRServiceDatabase = @"Database"; +NSString *const kFIRServiceDynamicLinks = @"DynamicLinks"; +NSString *const kFIRServiceFirestore = @"Firestore"; +NSString *const kFIRServiceFunctions = @"Functions"; +NSString *const kFIRServiceInstanceID = @"InstanceID"; +NSString *const kFIRServiceInvites = @"Invites"; +NSString *const kFIRServiceMessaging = @"Messaging"; +NSString *const kFIRServiceMeasurement = @"Measurement"; +NSString *const kFIRServicePerformance = @"Performance"; +NSString *const kFIRServiceRemoteConfig = @"RemoteConfig"; +NSString *const kFIRServiceStorage = @"Storage"; +NSString *const kGGLServiceAnalytics = @"Analytics"; +NSString *const kGGLServiceSignIn = @"SignIn"; + +NSString *const kFIRDefaultAppName = @"__FIRAPP_DEFAULT"; +NSString *const kFIRAppReadyToConfigureSDKNotification = @"FIRAppReadyToConfigureSDKNotification"; +NSString *const kFIRAppDeleteNotification = @"FIRAppDeleteNotification"; +NSString *const kFIRAppIsDefaultAppKey = @"FIRAppIsDefaultAppKey"; +NSString *const kFIRAppNameKey = @"FIRAppNameKey"; +NSString *const kFIRGoogleAppIDKey = @"FIRGoogleAppIDKey"; + +NSString *const kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat = + @"/google/firebase/global_data_collection_enabled:%@"; +NSString *const kFIRGlobalAppDataCollectionEnabledPlistKey = + @"FirebaseDataCollectionDefaultEnabled"; + +NSString *const kFIRAppDiagnosticsNotification = @"FIRAppDiagnosticsNotification"; + +NSString *const kFIRAppDiagnosticsConfigurationTypeKey = @"ConfigType"; +NSString *const kFIRAppDiagnosticsErrorKey = @"Error"; +NSString *const kFIRAppDiagnosticsFIRAppKey = @"FIRApp"; +NSString *const kFIRAppDiagnosticsSDKNameKey = @"SDKName"; +NSString *const kFIRAppDiagnosticsSDKVersionKey = @"SDKVersion"; + +// Auth internal notification notification and key. +NSString *const FIRAuthStateDidChangeInternalNotification = + @"FIRAuthStateDidChangeInternalNotification"; +NSString *const FIRAuthStateDidChangeInternalNotificationAppKey = + @"FIRAuthStateDidChangeInternalNotificationAppKey"; +NSString *const FIRAuthStateDidChangeInternalNotificationTokenKey = + @"FIRAuthStateDidChangeInternalNotificationTokenKey"; +NSString *const FIRAuthStateDidChangeInternalNotificationUIDKey = + @"FIRAuthStateDidChangeInternalNotificationUIDKey"; + +/** + * The URL to download plist files. + */ +static NSString *const kPlistURL = @"https://console.firebase.google.com/"; + +/** + * An array of all classes that registered as `FIRCoreConfigurable` in order to receive lifecycle + * events from Core. + */ +static NSMutableArray> *gRegisteredAsConfigurable; + +@interface FIRApp () + +#ifdef DEBUG +@property(nonatomic) BOOL alreadyOutputDataCollectionFlag; +#endif // DEBUG + +@end + +@implementation FIRApp + +// This is necessary since our custom getter prevents `_options` from being created. +@synthesize options = _options; + +static NSMutableDictionary *sAllApps; +static FIRApp *sDefaultApp; +static NSMutableDictionary *sLibraryVersions; + ++ (void)configure { + FIROptions *options = [FIROptions defaultOptions]; + if (!options) { + // Read the Info.plist to see if the flag is set. At this point we can't check any user defaults + // since the app isn't configured at all, so only rely on the Info.plist value. + NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist]; + if (collectionEnabledPlistValue == nil || [collectionEnabledPlistValue boolValue]) { + [[NSNotificationCenter defaultCenter] + postNotificationName:kFIRAppDiagnosticsNotification + object:nil + userInfo:@{ + kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeCore), + kFIRAppDiagnosticsErrorKey : [FIRApp errorForMissingOptions] + }]; + } + + [NSException raise:kFirebaseCoreErrorDomain + format: + @"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) could not find " + @"a valid GoogleService-Info.plist in your project. Please download one " + @"from %@.", + kPlistURL]; + } + [FIRApp configureWithOptions:options]; +#if TARGET_OS_OSX || TARGET_OS_TV + FIRLogNotice(kFIRLoggerCore, @"I-COR000028", + @"tvOS and macOS SDK support is not part of the official Firebase product. " + @"Instead they are community supported. Details at " + @"https://github.com/firebase/firebase-ios-sdk/blob/master/README.md."); +#endif +} + ++ (void)configureWithOptions:(FIROptions *)options { + if (!options) { + [NSException raise:kFirebaseCoreErrorDomain + format:@"Options is nil. Please pass a valid options."]; + } + [FIRApp configureWithName:kFIRDefaultAppName options:options]; +} + ++ (void)configureWithName:(NSString *)name options:(FIROptions *)options { + if (!name || !options) { + [NSException raise:kFirebaseCoreErrorDomain format:@"Neither name nor options can be nil."]; + } + if (name.length == 0) { + [NSException raise:kFirebaseCoreErrorDomain format:@"Name cannot be empty."]; + } + + if ([name isEqualToString:kFIRDefaultAppName]) { + if (sDefaultApp) { + [NSException raise:kFirebaseCoreErrorDomain + format:@"Default app has already been configured."]; + } + + FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configuring the default app."); + } else { + // Validate the app name and ensure it hasn't been configured already. + for (NSUInteger charIndex = 0; charIndex < name.length; charIndex++) { + char character = [name characterAtIndex:charIndex]; + if (!((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || + (character >= '0' && character <= '9') || character == '_' || character == '-')) { + [NSException raise:kFirebaseCoreErrorDomain + format: + @"App name should only contain Letters, " + @"Numbers, Underscores, and Dashes."]; + } + } + + if (sAllApps && sAllApps[name]) { + [NSException raise:kFirebaseCoreErrorDomain + format:@"App named %@ has already been configured.", name]; + } + + FIRLogDebug(kFIRLoggerCore, @"I-COR000002", @"Configuring app named %@", name); + } + + @synchronized(self) { + FIRApp *app = [[FIRApp alloc] initInstanceWithName:name options:options]; + if (app.isDefaultApp) { + sDefaultApp = app; + } + + [FIRApp addAppToAppDictionary:app]; + [FIRApp sendNotificationsToSDKs:app]; + } +} + ++ (FIRApp *)defaultApp { + if (sDefaultApp) { + return sDefaultApp; + } + FIRLogError(kFIRLoggerCore, @"I-COR000003", + @"The default Firebase app has not yet been " + @"configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your " + @"application initialization. Read more: https://goo.gl/ctyzm8."); + return nil; +} + ++ (FIRApp *)appNamed:(NSString *)name { + @synchronized(self) { + if (sAllApps) { + FIRApp *app = sAllApps[name]; + if (app) { + return app; + } + } + FIRLogError(kFIRLoggerCore, @"I-COR000004", @"App with name %@ does not exist.", name); + return nil; + } +} + ++ (NSDictionary *)allApps { + @synchronized(self) { + if (!sAllApps) { + FIRLogError(kFIRLoggerCore, @"I-COR000005", @"No app has been configured yet."); + } + NSDictionary *dict = [NSDictionary dictionaryWithDictionary:sAllApps]; + return dict; + } +} + +// Public only for tests ++ (void)resetApps { + sDefaultApp = nil; + [sAllApps removeAllObjects]; + sAllApps = nil; + [sLibraryVersions removeAllObjects]; + sLibraryVersions = nil; +} + +- (void)deleteApp:(FIRAppVoidBoolCallback)completion { + @synchronized([self class]) { + if (sAllApps && sAllApps[self.name]) { + FIRLogDebug(kFIRLoggerCore, @"I-COR000006", @"Deleting app named %@", self.name); + + // Remove all cached instances from the container before deleting the app. + [self.container removeAllCachedInstances]; + + [sAllApps removeObjectForKey:self.name]; + [self clearDataCollectionSwitchFromUserDefaults]; + if ([self.name isEqualToString:kFIRDefaultAppName]) { + sDefaultApp = nil; + } + NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name}; + [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification + object:[self class] + userInfo:appInfoDict]; + completion(YES); + } else { + FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist."); + completion(NO); + } + } +} + ++ (void)addAppToAppDictionary:(FIRApp *)app { + if (!sAllApps) { + sAllApps = [NSMutableDictionary dictionary]; + } + if ([app configureCore]) { + sAllApps[app.name] = app; + } else { + [NSException raise:kFirebaseCoreErrorDomain + format: + @"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in " + @"GoogleService-Info.plist or set in the customized options."]; + } +} + +- (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options { + self = [super init]; + if (self) { + _name = [name copy]; + _options = [options copy]; + _options.editingLocked = YES; + _isDefaultApp = [name isEqualToString:kFIRDefaultAppName]; + _container = [[FIRComponentContainer alloc] initWithApp:self]; + } + return self; +} + +- (void)getTokenForcingRefresh:(BOOL)forceRefresh withCallback:(FIRTokenCallback)callback { + if (!_getTokenImplementation) { + callback(nil, nil); + return; + } + + _getTokenImplementation(forceRefresh, callback); +} + +- (BOOL)configureCore { + [self checkExpectedBundleID]; + if (![self isAppIDValid]) { + if (_options.usingOptionsFromDefaultPlist && [self isDataCollectionDefaultEnabled]) { + [[NSNotificationCenter defaultCenter] + postNotificationName:kFIRAppDiagnosticsNotification + object:nil + userInfo:@{ + kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeCore), + kFIRAppDiagnosticsErrorKey : [FIRApp errorForInvalidAppID], + }]; + } + return NO; + } + + if ([self isDataCollectionDefaultEnabled]) { + [[NSNotificationCenter defaultCenter] + postNotificationName:kFIRAppDiagnosticsNotification + object:nil + userInfo:@{ + kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeCore), + kFIRAppDiagnosticsFIRAppKey : self + }]; + } + +#if TARGET_OS_IOS + // Initialize the Analytics once there is a valid options under default app. Analytics should + // always initialize first by itself before the other SDKs. + if ([self.name isEqualToString:kFIRDefaultAppName]) { + Class firAnalyticsClass = NSClassFromString(@"FIRAnalytics"); + if (!firAnalyticsClass) { + FIRLogWarning(kFIRLoggerCore, @"I-COR000022", + @"Firebase Analytics is not available. To add it, include Firebase/Core in the " + @"Podfile or add FirebaseAnalytics.framework to the Link Build Phase"); + } else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundeclared-selector" + SEL startWithConfigurationSelector = @selector(startWithConfiguration:options:); +#pragma clang diagnostic pop + if ([firAnalyticsClass respondsToSelector:startWithConfigurationSelector]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + [firAnalyticsClass performSelector:startWithConfigurationSelector + withObject:[FIRConfiguration sharedInstance].analyticsConfiguration + withObject:_options]; +#pragma clang diagnostic pop + } + } + } +#endif + + return YES; +} + +- (FIROptions *)options { + return [_options copy]; +} + +- (void)setDataCollectionDefaultEnabled:(BOOL)dataCollectionDefaultEnabled { +#ifdef DEBUG + FIRLogDebug(kFIRLoggerCore, @"I-COR000034", @"Explicitly %@ data collection flag.", + dataCollectionDefaultEnabled ? @"enabled" : @"disabled"); + self.alreadyOutputDataCollectionFlag = YES; +#endif // DEBUG + + NSString *key = + [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name]; + [[NSUserDefaults standardUserDefaults] setBool:dataCollectionDefaultEnabled forKey:key]; + + // Core also controls the FirebaseAnalytics flag, so check if the Analytics flags are set + // within FIROptions and change the Analytics value if necessary. Analytics only works with the + // default app, so return if this isn't the default app. + if (!self.isDefaultApp) { + return; + } + + // Check if the Analytics flag is explicitly set. If so, no further actions are necessary. + if ([self.options isAnalyticsCollectionExpicitlySet]) { + return; + } + + // The Analytics flag has not been explicitly set, so update with the value being set. + [[FIRAnalyticsConfiguration sharedInstance] + setAnalyticsCollectionEnabled:dataCollectionDefaultEnabled + persistSetting:NO]; +} + +- (BOOL)isDataCollectionDefaultEnabled { + // Check if it's been manually set before in code, and use that as the higher priority value. + NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self]; + if (defaultsObject != nil) { +#ifdef DEBUG + if (!self.alreadyOutputDataCollectionFlag) { + FIRLogDebug(kFIRLoggerCore, @"I-COR000031", @"Data Collection flag is %@ in user defaults.", + [defaultsObject boolValue] ? @"enabled" : @"disabled"); + self.alreadyOutputDataCollectionFlag = YES; + } +#endif // DEBUG + return [defaultsObject boolValue]; + } + + // Read the Info.plist to see if the flag is set. If it's not set, it should default to `YES`. + // As per the implementation of `readDataCollectionSwitchFromPlist`, it's a cached value and has + // no performance impact calling multiple times. + NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist]; + if (collectionEnabledPlistValue != nil) { +#ifdef DEBUG + if (!self.alreadyOutputDataCollectionFlag) { + FIRLogDebug(kFIRLoggerCore, @"I-COR000032", @"Data Collection flag is %@ in plist.", + [collectionEnabledPlistValue boolValue] ? @"enabled" : @"disabled"); + self.alreadyOutputDataCollectionFlag = YES; + } +#endif // DEBUG + return [collectionEnabledPlistValue boolValue]; + } + +#ifdef DEBUG + if (!self.alreadyOutputDataCollectionFlag) { + FIRLogDebug(kFIRLoggerCore, @"I-COR000033", @"Data Collection flag is not set."); + self.alreadyOutputDataCollectionFlag = YES; + } +#endif // DEBUG + return YES; +} + +#pragma mark - private + ++ (void)sendNotificationsToSDKs:(FIRApp *)app { + // TODO: Remove this notification once all SDKs are registered with `FIRCoreConfigurable`. + NSNumber *isDefaultApp = [NSNumber numberWithBool:app.isDefaultApp]; + NSDictionary *appInfoDict = @{ + kFIRAppNameKey : app.name, + kFIRAppIsDefaultAppKey : isDefaultApp, + kFIRGoogleAppIDKey : app.options.googleAppID + }; + [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppReadyToConfigureSDKNotification + object:self + userInfo:appInfoDict]; + + // This is the new way of sending information to SDKs. + // TODO: Do we want this on a background thread, maybe? + for (Class library in gRegisteredAsConfigurable) { + [library configureWithApp:app]; + } +} + ++ (NSError *)errorForMissingOptions { + NSDictionary *errorDict = @{ + NSLocalizedDescriptionKey : + @"Unable to parse GoogleService-Info.plist in order to configure services.", + NSLocalizedRecoverySuggestionErrorKey : + @"Check formatting and location of GoogleService-Info.plist." + }; + return [NSError errorWithDomain:kFirebaseCoreErrorDomain + code:FIRErrorCodeInvalidPlistFile + userInfo:errorDict]; +} + ++ (NSError *)errorForSubspecConfigurationFailureWithDomain:(NSString *)domain + errorCode:(FIRErrorCode)code + service:(NSString *)service + reason:(NSString *)reason { + NSString *description = + [NSString stringWithFormat:@"Configuration failed for service %@.", service]; + NSDictionary *errorDict = + @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason}; + return [NSError errorWithDomain:domain code:code userInfo:errorDict]; +} + ++ (NSError *)errorForInvalidAppID { + NSDictionary *errorDict = @{ + NSLocalizedDescriptionKey : @"Unable to validate Google App ID", + NSLocalizedRecoverySuggestionErrorKey : + @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the " + @"customized options." + }; + return [NSError errorWithDomain:kFirebaseCoreErrorDomain + code:FIRErrorCodeInvalidAppID + userInfo:errorDict]; +} + ++ (void)registerAsConfigurable:(Class)klass { + // This is called at +load time, keep the work to a minimum. + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gRegisteredAsConfigurable = [[NSMutableArray alloc] initWithCapacity:1]; + }); + + NSAssert([(Class)klass conformsToProtocol:@protocol(FIRCoreConfigurable)], + @"The class being registered (%@) must conform to `FIRCoreConfigurable`.", klass); + [gRegisteredAsConfigurable addObject:klass]; +} + ++ (BOOL)isDefaultAppConfigured { + return (sDefaultApp != nil); +} + ++ (void)registerLibrary:(nonnull NSString *)library withVersion:(nonnull NSString *)version { + // Create the set of characters which aren't allowed, only if this feature is used. + NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet]; + [allowedSet addCharactersInString:@"-_."]; + NSCharacterSet *disallowedSet = [allowedSet invertedSet]; + // Make sure the library name and version strings do not contain unexpected characters, and + // add the name/version pair to the dictionary. + if ([library rangeOfCharacterFromSet:disallowedSet].location == NSNotFound && + [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) { + if (!sLibraryVersions) { + sLibraryVersions = [[NSMutableDictionary alloc] init]; + } + sLibraryVersions[library] = version; + } else { + FIRLogError(kFIRLoggerCore, @"I-COR000027", + @"The library name (%@) or version number (%@) contain illegal characters. " + @"Only alphanumeric, dash, underscore and period characters are allowed.", + library, version); + } +} + ++ (NSString *)firebaseUserAgent { + NSMutableArray *libraries = + [[NSMutableArray alloc] initWithCapacity:sLibraryVersions.count]; + for (NSString *libraryName in sLibraryVersions) { + [libraries + addObject:[NSString stringWithFormat:@"%@/%@", libraryName, sLibraryVersions[libraryName]]]; + } + [libraries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; + return [libraries componentsJoinedByString:@" "]; +} + +- (void)checkExpectedBundleID { + NSArray *bundles = [FIRBundleUtil relevantBundles]; + NSString *expectedBundleID = [self expectedBundleID]; + // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for + // backward compatibility. + if (expectedBundleID != nil && + ![FIRBundleUtil hasBundleIdentifier:expectedBundleID inBundles:bundles]) { + FIRLogError(kFIRLoggerCore, @"I-COR000008", + @"The project's Bundle ID is inconsistent with " + @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are " + @"using a customized options. To ensure that everything can be configured " + @"correctly, you may need to make the Bundle IDs consistent. To continue with this " + @"plist file, you may change your app's bundle identifier to '%@'. Or you can " + @"download a new configuration file that matches your bundle identifier from %@ " + @"and replace the current one.", + kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL); + } +} + +// TODO: Remove once SDKs transition to Auth interop library. +- (nullable NSString *)getUID { + if (!_getUIDImplementation) { + FIRLogWarning(kFIRLoggerCore, @"I-COR000025", @"FIRAuth getUID implementation wasn't set."); + return nil; + } + return _getUIDImplementation(); +} + +#pragma mark - private - App ID Validation + +/** + * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file. + * This is the main method for validating app ID. + * + * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise. + */ +- (BOOL)isAppIDValid { + NSString *appID = _options.googleAppID; + BOOL isValid = [FIRApp validateAppID:appID]; + if (!isValid) { + NSString *expectedBundleID = [self expectedBundleID]; + FIRLogError(kFIRLoggerCore, @"I-COR000009", + @"The GOOGLE_APP_ID either in the plist file " + @"'%@.%@' or the one set in the customized options is invalid. If you are using " + @"the plist file, use the iOS version of bundle identifier to download the file, " + @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle " + @"identifier to '%@'. Or you can download a new configuration file that matches " + @"your bundle identifier from %@ and replace the current one.", + kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL); + }; + return isValid; +} + ++ (BOOL)validateAppID:(NSString *)appID { + // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not + // have a valid fingerprint, otherwise we just warn about the potential issue. + if (!appID.length) { + return NO; + } + + // All app IDs must start with at least ":". + NSString *const versionPattern = @"^\\d+:"; + NSRegularExpression *versionRegex = + [NSRegularExpression regularExpressionWithPattern:versionPattern options:0 error:NULL]; + if (!versionRegex) { + return NO; + } + + NSRange appIDRange = NSMakeRange(0, appID.length); + NSArray *versionMatches = [versionRegex matchesInString:appID options:0 range:appIDRange]; + if (versionMatches.count != 1) { + return NO; + } + + NSRange versionRange = [(NSTextCheckingResult *)versionMatches.firstObject range]; + NSString *appIDVersion = [appID substringWithRange:versionRange]; + NSArray *knownVersions = @[ @"1:" ]; + if (![knownVersions containsObject:appIDVersion]) { + // Permit unknown yet properly formatted app ID versions. + return YES; + } + + if (![FIRApp validateAppIDFormat:appID withVersion:appIDVersion]) { + return NO; + } + + if (![FIRApp validateAppIDFingerprint:appID withVersion:appIDVersion]) { + return NO; + } + + return YES; +} + ++ (NSString *)actualBundleID { + return [[NSBundle mainBundle] bundleIdentifier]; +} + +/** + * Validates that the format of the app ID string is what is expected based on the supplied version. + * The version must end in ":". + * + * For v1 app ids the format is expected to be + * '::ios:'. + * + * This method does not verify that the contents of the app id are correct, just that they fulfill + * the expected format. + * + * @param appID Contents of GOOGLE_APP_ID from the plist file. + * @param version Indicates what version of the app id format this string should be. + * @return YES if provided string fufills the expected format, NO otherwise. + */ ++ (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version { + if (!appID.length || !version.length) { + return NO; + } + + if (![version hasSuffix:@":"]) { + return NO; + } + + if (![appID hasPrefix:version]) { + return NO; + } + + NSString *const pattern = @"^\\d+:ios:[a-f0-9]+$"; + NSRegularExpression *regex = + [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL]; + if (!regex) { + return NO; + } + + NSRange localRange = NSMakeRange(version.length, appID.length - version.length); + NSUInteger numberOfMatches = [regex numberOfMatchesInString:appID options:0 range:localRange]; + if (numberOfMatches != 1) { + return NO; + } + return YES; +} + +/** + * Validates that the fingerprint of the app ID string is what is expected based on the supplied + * version. The version must end in ":". + * + * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated. + * + * @param appID Contents of GOOGLE_APP_ID from the plist file. + * @param version Indicates what version of the app id format this string should be. + * @return YES if provided string fufills the expected fingerprint and the version is known, NO + * otherwise. + */ ++ (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version { + if (!appID.length || !version.length) { + return NO; + } + + if (![version hasSuffix:@":"]) { + return NO; + } + + if (![appID hasPrefix:version]) { + return NO; + } + + // Extract the supplied fingerprint from the supplied app ID. + // This assumes the app ID format is the same for all known versions below. If the app ID format + // changes in future versions, the tokenizing of the app ID format will need to take into account + // the version of the app ID. + NSArray *components = [appID componentsSeparatedByString:@":"]; + if (components.count != 4) { + return NO; + } + + NSString *suppliedFingerprintString = components[3]; + if (!suppliedFingerprintString.length) { + return NO; + } + + uint64_t suppliedFingerprint; + NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString]; + if (![scanner scanHexLongLong:&suppliedFingerprint]) { + return NO; + } + + if ([version isEqual:@"1:"]) { + // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated. + return YES; + } + + // Unknown version. + return NO; +} + +- (NSString *)expectedBundleID { + return _options.bundleID; +} + +// end App ID validation + +#pragma mark - Reading From Plist & User Defaults + +/** + * Clears the data collection switch from the standard NSUserDefaults for easier testing and + * readability. + */ +- (void)clearDataCollectionSwitchFromUserDefaults { + NSString *key = + [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name]; + [[NSUserDefaults standardUserDefaults] removeObjectForKey:key]; +} + +/** + * Reads the data collection switch from the standard NSUserDefaults for easier testing and + * readability. + */ ++ (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app { + // Read the object in user defaults, and only return if it's an NSNumber. + NSString *key = + [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name]; + id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key]; + if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) { + return collectionEnabledDefaultsObject; + } + + return nil; +} + +/** + * Reads the data collection switch from the Info.plist for easier testing and readability. Will + * only read once from the plist and return the cached value. + */ ++ (nullable NSNumber *)readDataCollectionSwitchFromPlist { + static NSNumber *collectionEnabledPlistObject; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber. + id plistValue = [[NSBundle mainBundle] + objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey]; + if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) { + collectionEnabledPlistObject = (NSNumber *)plistValue; + } + }); + + return collectionEnabledPlistObject; +} + +#pragma mark - Sending Logs + +- (void)sendLogsWithServiceName:(NSString *)serviceName + version:(NSString *)version + error:(NSError *)error { + // If the user has manually turned off data collection, return and don't send logs. + if (![self isDataCollectionDefaultEnabled]) { + return; + } + + NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithDictionary:@{ + kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeSDK), + kFIRAppDiagnosticsSDKNameKey : serviceName, + kFIRAppDiagnosticsSDKVersionKey : version, + kFIRAppDiagnosticsFIRAppKey : self + }]; + if (error) { + userInfo[kFIRAppDiagnosticsErrorKey] = error; + } + [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDiagnosticsNotification + object:nil + userInfo:userInfo]; +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIRAppAssociationRegistration.m b/Pods/FirebaseCore/Firebase/Core/FIRAppAssociationRegistration.m new file mode 100644 index 0000000000..2aecdabe1a --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRAppAssociationRegistration.m @@ -0,0 +1,47 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRAppAssociationRegistration.h" + +#import + +@implementation FIRAppAssociationRegistration + ++ (nullable id)registeredObjectWithHost:(id)host + key:(NSString *)key + creationBlock:(id _Nullable (^)(void))creationBlock { + @synchronized(self) { + SEL dictKey = @selector(registeredObjectWithHost:key:creationBlock:); + NSMutableDictionary *objectsByKey = objc_getAssociatedObject(host, dictKey); + if (!objectsByKey) { + objectsByKey = [[NSMutableDictionary alloc] init]; + objc_setAssociatedObject(host, dictKey, objectsByKey, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + id obj = objectsByKey[key]; + NSValue *creationBlockBeingCalled = [NSValue valueWithPointer:dictKey]; + if (obj) { + if ([creationBlockBeingCalled isEqual:obj]) { + [NSException raise:@"Reentering registeredObjectWithHost:key:creationBlock: not allowed" + format:@"host: %@ key: %@", host, key]; + } + return obj; + } + objectsByKey[key] = creationBlockBeingCalled; + obj = creationBlock(); + objectsByKey[key] = obj; + return obj; + } +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIRBundleUtil.m b/Pods/FirebaseCore/Firebase/Core/FIRBundleUtil.m new file mode 100644 index 0000000000..93ee02e97d --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRBundleUtil.m @@ -0,0 +1,57 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRBundleUtil.h" + +@implementation FIRBundleUtil + ++ (NSArray *)relevantBundles { + return @[ [NSBundle mainBundle], [NSBundle bundleForClass:[self class]] ]; +} + ++ (NSString *)optionsDictionaryPathWithResourceName:(NSString *)resourceName + andFileType:(NSString *)fileType + inBundles:(NSArray *)bundles { + // Loop through all bundles to find the config dict. + for (NSBundle *bundle in bundles) { + NSString *path = [bundle pathForResource:resourceName ofType:fileType]; + // Use the first one we find. + if (path) { + return path; + } + } + return nil; +} + ++ (NSArray *)relevantURLSchemes { + NSMutableArray *result = [[NSMutableArray alloc] init]; + for (NSBundle *bundle in [[self class] relevantBundles]) { + NSArray *urlTypes = [bundle objectForInfoDictionaryKey:@"CFBundleURLTypes"]; + for (NSDictionary *urlType in urlTypes) { + [result addObjectsFromArray:urlType[@"CFBundleURLSchemes"]]; + } + } + return result; +} + ++ (BOOL)hasBundleIdentifier:(NSString *)bundleIdentifier inBundles:(NSArray *)bundles { + for (NSBundle *bundle in bundles) { + if ([bundle.bundleIdentifier isEqualToString:bundleIdentifier]) { + return YES; + } + } + return NO; +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIRComponent.m b/Pods/FirebaseCore/Firebase/Core/FIRComponent.m new file mode 100644 index 0000000000..2474d1aabf --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRComponent.m @@ -0,0 +1,65 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Private/FIRComponent.h" + +#import "Private/FIRComponentContainer.h" +#import "Private/FIRDependency.h" + +@interface FIRComponent () + +- (instancetype)initWithProtocol:(Protocol *)protocol + instantiationTiming:(FIRInstantiationTiming)instantiationTiming + dependencies:(NSArray *)dependencies + creationBlock:(FIRComponentCreationBlock)creationBlock; + +@end + +@implementation FIRComponent + ++ (instancetype)componentWithProtocol:(Protocol *)protocol + creationBlock:(FIRComponentCreationBlock)creationBlock { + return [[FIRComponent alloc] initWithProtocol:protocol + instantiationTiming:FIRInstantiationTimingLazy + dependencies:@[] + creationBlock:creationBlock]; +} + ++ (instancetype)componentWithProtocol:(Protocol *)protocol + instantiationTiming:(FIRInstantiationTiming)instantiationTiming + dependencies:(NSArray *)dependencies + creationBlock:(FIRComponentCreationBlock)creationBlock { + return [[FIRComponent alloc] initWithProtocol:protocol + instantiationTiming:instantiationTiming + dependencies:dependencies + creationBlock:creationBlock]; +} + +- (instancetype)initWithProtocol:(Protocol *)protocol + instantiationTiming:(FIRInstantiationTiming)instantiationTiming + dependencies:(NSArray *)dependencies + creationBlock:(FIRComponentCreationBlock)creationBlock { + self = [super init]; + if (self) { + _protocol = protocol; + _instantiationTiming = instantiationTiming; + _dependencies = [dependencies copy]; + _creationBlock = creationBlock; + } + return self; +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIRComponentContainer.m b/Pods/FirebaseCore/Firebase/Core/FIRComponentContainer.m new file mode 100644 index 0000000000..381c95c431 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRComponentContainer.m @@ -0,0 +1,205 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Private/FIRComponentContainer.h" + +#import "Private/FIRAppInternal.h" +#import "Private/FIRComponent.h" +#import "Private/FIRComponentRegistrant.h" +#import "Private/FIRLogger.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRComponentContainer () + +/// The dictionary of components that are registered for a particular app. The key is an NSString +/// of the protocol. +@property(nonatomic, strong) NSMutableDictionary *components; + +/// Cached instances of components that requested to be cached. +@property(nonatomic, strong) NSMutableDictionary *cachedInstances; + +@end + +@implementation FIRComponentContainer + +// Collection of all classes that register to provide components. +static NSMutableSet *gFIRComponentRegistrants; + +#pragma mark - Public Registration + ++ (void)registerAsComponentRegistrant:(Class)klass { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gFIRComponentRegistrants = [[NSMutableSet alloc] init]; + }); + + [self registerAsComponentRegistrant:klass inSet:gFIRComponentRegistrants]; +} + ++ (void)registerAsComponentRegistrant:(Class)klass inSet:(NSMutableSet *)allRegistrants { + // Validate the array to store the components is initialized. + if (!allRegistrants) { + FIRLogWarning(kFIRLoggerCore, @"I-COR000025", + @"Attempted to store registered components in an empty set."); + return; + } + + // Ensure the class given conforms to the proper protocol. + if (![klass conformsToProtocol:@protocol(FIRComponentRegistrant)] || + ![klass respondsToSelector:@selector(componentsToRegister)]) { + [NSException raise:NSInvalidArgumentException + format: + @"Class %@ attempted to register components, but it does not conform to " + @"`FIRComponentRegistrant` or provide a `componentsToRegister:` method.", + klass]; + } + + [allRegistrants addObject:klass]; +} + +#pragma mark - Internal Initialization + +- (instancetype)initWithApp:(FIRApp *)app { + return [self initWithApp:app registrants:gFIRComponentRegistrants]; +} + +- (instancetype)initWithApp:(FIRApp *)app registrants:(NSMutableSet *)allRegistrants { + self = [super init]; + if (self) { + _app = app; + _cachedInstances = [NSMutableDictionary dictionary]; + _components = [NSMutableDictionary dictionary]; + + [self populateComponentsFromRegisteredClasses:allRegistrants forApp:app]; + } + return self; +} + +- (void)populateComponentsFromRegisteredClasses:(NSSet *)classes forApp:(FIRApp *)app { + // Loop through the verified component registrants and populate the components array. + for (Class klass in classes) { + // Loop through all the components being registered and store them as appropriate. + // Classes which do not provide functionality should use a dummy FIRComponentRegistrant + // protocol. + for (FIRComponent *component in [klass componentsToRegister]) { + // Check if the component has been registered before, and error out if so. + NSString *protocolName = NSStringFromProtocol(component.protocol); + if (self.components[protocolName]) { + FIRLogError(kFIRLoggerCore, @"I-COR000029", + @"Attempted to register protocol %@, but it already has an implementation.", + protocolName); + continue; + } + + // Store the creation block for later usage. + self.components[protocolName] = component.creationBlock; + + // Instantiate the + BOOL shouldInstantiateEager = + (component.instantiationTiming == FIRInstantiationTimingAlwaysEager); + BOOL shouldInstantiateDefaultEager = + (component.instantiationTiming == FIRInstantiationTimingEagerInDefaultApp && + [app isDefaultApp]); + if (shouldInstantiateEager || shouldInstantiateDefaultEager) { + [self instantiateInstanceForProtocol:component.protocol withBlock:component.creationBlock]; + } + } + } +} + +#pragma mark - Instance Creation + +/// Instantiate an instance of a class that conforms to the specified protocol. +/// This will: +/// - Call the block to create an instance if possible, +/// - Validate that the instance returned conforms to the protocol it claims to, +/// - Cache the instance if the block requests it +- (nullable id)instantiateInstanceForProtocol:(Protocol *)protocol + withBlock:(FIRComponentCreationBlock)creationBlock { + if (!creationBlock) { + return nil; + } + + // Create an instance using the creation block. + BOOL shouldCache = NO; + id instance = creationBlock(self, &shouldCache); + if (!instance) { + return nil; + } + + // An instance was created, validate that it conforms to the protocol it claims to. + NSString *protocolName = NSStringFromProtocol(protocol); + if (![instance conformsToProtocol:protocol]) { + FIRLogError(kFIRLoggerCore, @"I-COR000030", + @"An instance conforming to %@ was requested, but the instance provided does not " + @"conform to the protocol", + protocolName); + } + + // The instance is ready to be returned, but check if it should be cached first before returning. + if (shouldCache) { + self.cachedInstances[protocolName] = instance; + } + + return instance; +} + +#pragma mark - Internal Retrieval + +- (nullable id)instanceForProtocol:(Protocol *)protocol { + // Check if there is a cached instance, and return it if so. + NSString *protocolName = NSStringFromProtocol(protocol); + id cachedInstance = self.cachedInstances[protocolName]; + if (cachedInstance) { + return cachedInstance; + } + + // Use the creation block to instantiate an instance and return it. + FIRComponentCreationBlock creationBlock = self.components[protocolName]; + return [self instantiateInstanceForProtocol:protocol withBlock:creationBlock]; +} + +#pragma mark - Lifecycle + +- (void)removeAllCachedInstances { + // Loop through the cache and notify each instance that is a maintainer to clean up after itself. + for (id instance in self.cachedInstances.allValues) { + if ([instance conformsToProtocol:@protocol(FIRComponentLifecycleMaintainer)] && + [instance respondsToSelector:@selector(appWillBeDeleted:)]) { + [instance appWillBeDeleted:self.app]; + } + } + + [self.cachedInstances removeAllObjects]; +} + +#pragma mark - Testing Initializers + +// TODO(wilsonryan): Set up a testing flag so this only is compiled in with unit tests. +/// Initialize an instance with an app and existing components. +- (instancetype)initWithApp:(FIRApp *)app + components:(NSDictionary *)components { + self = [self initWithApp:app registrants:[[NSMutableSet alloc] init]]; + if (self) { + _components = [components mutableCopy]; + } + return self; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/FIRComponentType.m b/Pods/FirebaseCore/Firebase/Core/FIRComponentType.m new file mode 100644 index 0000000000..bdc004fbce --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRComponentType.m @@ -0,0 +1,28 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Private/FIRComponentType.h" + +#import "Private/FIRComponentContainerInternal.h" + +@implementation FIRComponentType + ++ (id)instanceForProtocol:(Protocol *)protocol inContainer:(FIRComponentContainer *)container { + // Forward the call to the container. + return [container instanceForProtocol:protocol]; +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIRConfiguration.m b/Pods/FirebaseCore/Firebase/Core/FIRConfiguration.m new file mode 100644 index 0000000000..cd6486257e --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRConfiguration.m @@ -0,0 +1,44 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRConfiguration.h" + +extern void FIRSetLoggerLevel(FIRLoggerLevel loggerLevel); + +@implementation FIRConfiguration + ++ (instancetype)sharedInstance { + static FIRConfiguration *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[FIRConfiguration alloc] init]; + }); + return sharedInstance; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _analyticsConfiguration = [FIRAnalyticsConfiguration sharedInstance]; + } + return self; +} + +- (void)setLoggerLevel:(FIRLoggerLevel)loggerLevel { + NSAssert(loggerLevel <= FIRLoggerLevelMax && loggerLevel >= FIRLoggerLevelMin, + @"Invalid logger level, %ld", (long)loggerLevel); + FIRSetLoggerLevel(loggerLevel); +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIRDependency.m b/Pods/FirebaseCore/Firebase/Core/FIRDependency.m new file mode 100644 index 0000000000..f979984147 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRDependency.m @@ -0,0 +1,44 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Private/FIRDependency.h" + +@interface FIRDependency () + +- (instancetype)initWithProtocol:(Protocol *)protocol isRequired:(BOOL)required; + +@end + +@implementation FIRDependency + ++ (instancetype)dependencyWithProtocol:(Protocol *)protocol { + return [[self alloc] initWithProtocol:protocol isRequired:YES]; +} + ++ (instancetype)dependencyWithProtocol:(Protocol *)protocol isRequired:(BOOL)required { + return [[self alloc] initWithProtocol:protocol isRequired:required]; +} + +- (instancetype)initWithProtocol:(Protocol *)protocol isRequired:(BOOL)required { + self = [super init]; + if (self) { + _protocol = protocol; + _isRequired = required; + } + return self; +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIRErrors.m b/Pods/FirebaseCore/Firebase/Core/FIRErrors.m new file mode 100644 index 0000000000..6d6d52d2ce --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRErrors.m @@ -0,0 +1,29 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRErrors.h" + +NSString *const kFirebaseErrorDomain = @"com.firebase"; +NSString *const kFirebaseAdMobErrorDomain = @"com.firebase.admob"; +NSString *const kFirebaseAppInviteErrorDomain = @"com.firebase.appinvite"; +NSString *const kFirebaseAuthErrorDomain = @"com.firebase.auth"; +NSString *const kFirebaseCloudMessagingErrorDomain = @"com.firebase.cloudmessaging"; +NSString *const kFirebaseConfigErrorDomain = @"com.firebase.config"; +NSString *const kFirebaseCoreErrorDomain = @"com.firebase.core"; +NSString *const kFirebaseCrashReportingErrorDomain = @"com.firebase.crashreporting"; +NSString *const kFirebaseDatabaseErrorDomain = @"com.firebase.database"; +NSString *const kFirebaseDurableDeepLinkErrorDomain = @"com.firebase.durabledeeplink"; +NSString *const kFirebaseInstanceIDErrorDomain = @"com.firebase.instanceid"; +NSString *const kFirebasePerfErrorDomain = @"com.firebase.perf"; +NSString *const kFirebaseStorageErrorDomain = @"com.firebase.storage"; diff --git a/Pods/FirebaseCore/Firebase/Core/FIRLogger.m b/Pods/FirebaseCore/Firebase/Core/FIRLogger.m new file mode 100644 index 0000000000..d1e3b37382 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRLogger.m @@ -0,0 +1,185 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRLogger.h" + +#import +#import +#import + +#import "Private/FIRVersion.h" + +FIRLoggerService kFIRLoggerABTesting = @"[Firebase/ABTesting]"; +FIRLoggerService kFIRLoggerAdMob = @"[Firebase/AdMob]"; +FIRLoggerService kFIRLoggerAnalytics = @"[Firebase/Analytics]"; +FIRLoggerService kFIRLoggerAuth = @"[Firebase/Auth]"; +FIRLoggerService kFIRLoggerCore = @"[Firebase/Core]"; +FIRLoggerService kFIRLoggerCrash = @"[Firebase/Crash]"; +FIRLoggerService kFIRLoggerDatabase = @"[Firebase/Database]"; +FIRLoggerService kFIRLoggerDynamicLinks = @"[Firebase/DynamicLinks]"; +FIRLoggerService kFIRLoggerFirestore = @"[Firebase/Firestore]"; +FIRLoggerService kFIRLoggerInstanceID = @"[Firebase/InstanceID]"; +FIRLoggerService kFIRLoggerInvites = @"[Firebase/Invites]"; +FIRLoggerService kFIRLoggerMLKit = @"[Firebase/MLKit]"; +FIRLoggerService kFIRLoggerMessaging = @"[Firebase/Messaging]"; +FIRLoggerService kFIRLoggerPerf = @"[Firebase/Performance]"; +FIRLoggerService kFIRLoggerRemoteConfig = @"[Firebase/RemoteConfig]"; +FIRLoggerService kFIRLoggerStorage = @"[Firebase/Storage]"; +FIRLoggerService kFIRLoggerSwizzler = @"[FirebaseSwizzlingUtilities]"; + +/// Arguments passed on launch. +NSString *const kFIRDisableDebugModeApplicationArgument = @"-FIRDebugDisabled"; +NSString *const kFIREnableDebugModeApplicationArgument = @"-FIRDebugEnabled"; +NSString *const kFIRLoggerForceSDTERRApplicationArgument = @"-FIRLoggerForceSTDERR"; + +/// Key for the debug mode bit in NSUserDefaults. +NSString *const kFIRPersistedDebugModeKey = @"/google/firebase/debug_mode"; + +/// NSUserDefaults that should be used to store and read variables. If nil, `standardUserDefaults` +/// will be used. +static NSUserDefaults *sFIRLoggerUserDefaults; + +static dispatch_once_t sFIRLoggerOnceToken; + +// The sFIRAnalyticsDebugMode flag is here to support the -FIRDebugEnabled/-FIRDebugDisabled +// flags used by Analytics. Users who use those flags expect Analytics to log verbosely, +// while the rest of Firebase logs at the default level. This flag is introduced to support +// that behavior. +static BOOL sFIRAnalyticsDebugMode; + +#ifdef DEBUG +/// The regex pattern for the message code. +static NSString *const kMessageCodePattern = @"^I-[A-Z]{3}[0-9]{6}$"; +static NSRegularExpression *sMessageCodeRegex; +#endif + +void FIRLoggerInitializeASL() { + dispatch_once(&sFIRLoggerOnceToken, ^{ + // Register Firebase Version with GULLogger. + GULLoggerRegisterVersion(FIRVersionString); + + // Override the aslOptions to ASL_OPT_STDERR if the override argument is passed in. + NSArray *arguments = [NSProcessInfo processInfo].arguments; + BOOL overrideSTDERR = [arguments containsObject:kFIRLoggerForceSDTERRApplicationArgument]; + + // Use the standard NSUserDefaults if it hasn't been explicitly set. + if (sFIRLoggerUserDefaults == nil) { + sFIRLoggerUserDefaults = [NSUserDefaults standardUserDefaults]; + } + + BOOL forceDebugMode = NO; + BOOL debugMode = [sFIRLoggerUserDefaults boolForKey:kFIRPersistedDebugModeKey]; + if ([arguments containsObject:kFIRDisableDebugModeApplicationArgument]) { // Default mode + [sFIRLoggerUserDefaults removeObjectForKey:kFIRPersistedDebugModeKey]; + } else if ([arguments containsObject:kFIREnableDebugModeApplicationArgument] || + debugMode) { // Debug mode + [sFIRLoggerUserDefaults setBool:YES forKey:kFIRPersistedDebugModeKey]; + forceDebugMode = YES; + } + GULLoggerInitializeASL(); + if (overrideSTDERR) { + GULLoggerEnableSTDERR(); + } + if (forceDebugMode) { + GULLoggerForceDebug(); + } + }); +} + +__attribute__((no_sanitize("thread"))) void FIRSetAnalyticsDebugMode(BOOL analyticsDebugMode) { + sFIRAnalyticsDebugMode = analyticsDebugMode; +} + +void FIRSetLoggerLevel(FIRLoggerLevel loggerLevel) { + FIRLoggerInitializeASL(); + GULSetLoggerLevel((GULLoggerLevel)loggerLevel); +} + +#ifdef DEBUG +void FIRResetLogger() { + extern void GULResetLogger(void); + sFIRLoggerOnceToken = 0; + [sFIRLoggerUserDefaults removeObjectForKey:kFIRPersistedDebugModeKey]; + sFIRLoggerUserDefaults = nil; + GULResetLogger(); +} + +void FIRSetLoggerUserDefaults(NSUserDefaults *defaults) { + sFIRLoggerUserDefaults = defaults; +} +#endif + +/** + * Check if the level is high enough to be loggable. + * + * Analytics can override the log level with an intentional race condition. + * Add the attribute to get a clean thread sanitizer run. + */ +__attribute__((no_sanitize("thread"))) BOOL FIRIsLoggableLevel(FIRLoggerLevel loggerLevel, + BOOL analyticsComponent) { + FIRLoggerInitializeASL(); + if (sFIRAnalyticsDebugMode && analyticsComponent) { + return YES; + } + return GULIsLoggableLevel((GULLoggerLevel)loggerLevel); +} + +void FIRLogBasic(FIRLoggerLevel level, + FIRLoggerService service, + NSString *messageCode, + NSString *message, + va_list args_ptr) { + FIRLoggerInitializeASL(); + GULLogBasic((GULLoggerLevel)level, service, + sFIRAnalyticsDebugMode && [kFIRLoggerAnalytics isEqualToString:service], messageCode, + message, args_ptr); +} + +/** + * Generates the logging functions using macros. + * + * Calling FIRLogError(kFIRLoggerCore, @"I-COR000001", @"Configure %@ failed.", @"blah") shows: + * yyyy-mm-dd hh:mm:ss.SSS sender[PID] [Firebase/Core][I-COR000001] Configure blah failed. + * Calling FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configure succeed.") shows: + * yyyy-mm-dd hh:mm:ss.SSS sender[PID] [Firebase/Core][I-COR000001] Configure succeed. + */ +#define FIR_LOGGING_FUNCTION(level) \ + void FIRLog##level(FIRLoggerService service, NSString *messageCode, NSString *message, ...) { \ + va_list args_ptr; \ + va_start(args_ptr, message); \ + FIRLogBasic(FIRLoggerLevel##level, service, messageCode, message, args_ptr); \ + va_end(args_ptr); \ + } + +FIR_LOGGING_FUNCTION(Error) +FIR_LOGGING_FUNCTION(Warning) +FIR_LOGGING_FUNCTION(Notice) +FIR_LOGGING_FUNCTION(Info) +FIR_LOGGING_FUNCTION(Debug) + +#undef FIR_MAKE_LOGGER + +#pragma mark - FIRLoggerWrapper + +@implementation FIRLoggerWrapper + ++ (void)logWithLevel:(FIRLoggerLevel)level + withService:(FIRLoggerService)service + withCode:(NSString *)messageCode + withMessage:(NSString *)message + withArgs:(va_list)args { + FIRLogBasic(level, service, messageCode, message, args); +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIROptions.m b/Pods/FirebaseCore/Firebase/Core/FIROptions.m new file mode 100644 index 0000000000..db83d9c654 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIROptions.m @@ -0,0 +1,444 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRAppInternal.h" +#import "Private/FIRBundleUtil.h" +#import "Private/FIRErrors.h" +#import "Private/FIRLogger.h" +#import "Private/FIROptionsInternal.h" + +// Keys for the strings in the plist file. +NSString *const kFIRAPIKey = @"API_KEY"; +NSString *const kFIRTrackingID = @"TRACKING_ID"; +NSString *const kFIRGoogleAppID = @"GOOGLE_APP_ID"; +NSString *const kFIRClientID = @"CLIENT_ID"; +NSString *const kFIRGCMSenderID = @"GCM_SENDER_ID"; +NSString *const kFIRAndroidClientID = @"ANDROID_CLIENT_ID"; +NSString *const kFIRDatabaseURL = @"DATABASE_URL"; +NSString *const kFIRStorageBucket = @"STORAGE_BUCKET"; +// The key to locate the expected bundle identifier in the plist file. +NSString *const kFIRBundleID = @"BUNDLE_ID"; +// The key to locate the project identifier in the plist file. +NSString *const kFIRProjectID = @"PROJECT_ID"; + +NSString *const kFIRIsMeasurementEnabled = @"IS_MEASUREMENT_ENABLED"; +NSString *const kFIRIsAnalyticsCollectionEnabled = @"FIREBASE_ANALYTICS_COLLECTION_ENABLED"; +NSString *const kFIRIsAnalyticsCollectionDeactivated = @"FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED"; + +NSString *const kFIRIsAnalyticsEnabled = @"IS_ANALYTICS_ENABLED"; +NSString *const kFIRIsSignInEnabled = @"IS_SIGNIN_ENABLED"; + +// Library version ID. +NSString *const kFIRLibraryVersionID = + @"5" // Major version (one or more digits) + @"01" // Minor version (exactly 2 digits) + @"07" // Build number (exactly 2 digits) + @"000"; // Fixed "000" +// Plist file name. +NSString *const kServiceInfoFileName = @"GoogleService-Info"; +// Plist file type. +NSString *const kServiceInfoFileType = @"plist"; + +// Exception raised from attempting to modify a FIROptions after it's been copied to a FIRApp. +NSString *const kFIRExceptionBadModification = + @"Attempted to modify options after it's set on FIRApp. Please modify all properties before " + @"initializing FIRApp."; + +@interface FIROptions () + +/** + * This property maintains the actual configuration key-value pairs. + */ +@property(nonatomic, readwrite) NSMutableDictionary *optionsDictionary; + +/** + * Calls `analyticsOptionsDictionaryWithInfoDictionary:` using [NSBundle mainBundle].infoDictionary. + * It combines analytics options from both the infoDictionary and the GoogleService-Info.plist. + * Values which are present in the main plist override values from the GoogleService-Info.plist. + */ +@property(nonatomic, readonly) NSDictionary *analyticsOptionsDictionary; + +/** + * Combination of analytics options from both the infoDictionary and the GoogleService-Info.plist. + * Values which are present in the infoDictionary override values from the GoogleService-Info.plist. + */ +- (NSDictionary *)analyticsOptionsDictionaryWithInfoDictionary:(NSDictionary *)infoDictionary; + +/** + * Throw exception if editing is locked when attempting to modify an option. + */ +- (void)checkEditingLocked; + +@end + +@implementation FIROptions { + /// Backing variable for self.analyticsOptionsDictionary. + NSDictionary *_analyticsOptionsDictionary; +} + +static FIROptions *sDefaultOptions = nil; +static NSDictionary *sDefaultOptionsDictionary = nil; + +#pragma mark - Public only for internal class methods + ++ (FIROptions *)defaultOptions { + if (sDefaultOptions != nil) { + return sDefaultOptions; + } + + NSDictionary *defaultOptionsDictionary = [self defaultOptionsDictionary]; + if (defaultOptionsDictionary == nil) { + return nil; + } + + sDefaultOptions = [[FIROptions alloc] initInternalWithOptionsDictionary:defaultOptionsDictionary]; + return sDefaultOptions; +} + +#pragma mark - Private class methods + ++ (void)initialize { + // Report FirebaseCore version for useragent string + NSRange major = NSMakeRange(0, 1); + NSRange minor = NSMakeRange(1, 2); + NSRange patch = NSMakeRange(3, 2); + [FIRApp + registerLibrary:@"fire-ios" + withVersion:[NSString stringWithFormat:@"%@.%d.%d", + [kFIRLibraryVersionID substringWithRange:major], + [[kFIRLibraryVersionID substringWithRange:minor] + intValue], + [[kFIRLibraryVersionID substringWithRange:patch] + intValue]]]; + NSDictionary *info = [[NSBundle mainBundle] infoDictionary]; + NSString *xcodeVersion = info[@"DTXcodeBuild"]; + NSString *sdkVersion = info[@"DTSDKBuild"]; + if (xcodeVersion) { + [FIRApp registerLibrary:@"xcode" withVersion:xcodeVersion]; + } + if (sdkVersion) { + [FIRApp registerLibrary:@"apple-sdk" withVersion:sdkVersion]; + } +} + ++ (NSDictionary *)defaultOptionsDictionary { + if (sDefaultOptionsDictionary != nil) { + return sDefaultOptionsDictionary; + } + NSString *plistFilePath = [FIROptions plistFilePathWithName:kServiceInfoFileName]; + if (plistFilePath == nil) { + return nil; + } + sDefaultOptionsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistFilePath]; + if (sDefaultOptionsDictionary == nil) { + FIRLogError(kFIRLoggerCore, @"I-COR000011", + @"The configuration file is not a dictionary: " + @"'%@.%@'.", + kServiceInfoFileName, kServiceInfoFileType); + } + return sDefaultOptionsDictionary; +} + +// Returns the path of the plist file with a given file name. ++ (NSString *)plistFilePathWithName:(NSString *)fileName { + NSArray *bundles = [FIRBundleUtil relevantBundles]; + NSString *plistFilePath = + [FIRBundleUtil optionsDictionaryPathWithResourceName:fileName + andFileType:kServiceInfoFileType + inBundles:bundles]; + if (plistFilePath == nil) { + FIRLogError(kFIRLoggerCore, @"I-COR000012", @"Could not locate configuration file: '%@.%@'.", + fileName, kServiceInfoFileType); + } + return plistFilePath; +} + ++ (void)resetDefaultOptions { + sDefaultOptions = nil; + sDefaultOptionsDictionary = nil; +} + +#pragma mark - Private instance methods + +- (instancetype)initInternalWithOptionsDictionary:(NSDictionary *)optionsDictionary { + self = [super init]; + if (self) { + _optionsDictionary = [optionsDictionary mutableCopy]; + _usingOptionsFromDefaultPlist = YES; + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + FIROptions *newOptions = [[[self class] allocWithZone:zone] init]; + if (newOptions) { + newOptions.optionsDictionary = self.optionsDictionary; + newOptions.deepLinkURLScheme = self.deepLinkURLScheme; + newOptions.editingLocked = self.isEditingLocked; + newOptions.usingOptionsFromDefaultPlist = self.usingOptionsFromDefaultPlist; + } + return newOptions; +} + +#pragma mark - Public instance methods + +- (instancetype)initWithContentsOfFile:(NSString *)plistPath { + self = [super init]; + if (self) { + if (plistPath == nil) { + FIRLogError(kFIRLoggerCore, @"I-COR000013", @"The plist file path is nil."); + return nil; + } + _optionsDictionary = [[NSDictionary dictionaryWithContentsOfFile:plistPath] mutableCopy]; + if (_optionsDictionary == nil) { + FIRLogError(kFIRLoggerCore, @"I-COR000014", + @"The configuration file at %@ does not exist or " + @"is not a well-formed plist file.", + plistPath); + return nil; + } + // TODO: Do we want to validate the dictionary here? It says we do that already in + // the public header. + } + return self; +} + +- (instancetype)initWithGoogleAppID:(NSString *)googleAppID GCMSenderID:(NSString *)GCMSenderID { + self = [super init]; + if (self) { + NSMutableDictionary *mutableOptionsDict = [NSMutableDictionary dictionary]; + [mutableOptionsDict setValue:googleAppID forKey:kFIRGoogleAppID]; + [mutableOptionsDict setValue:GCMSenderID forKey:kFIRGCMSenderID]; + [mutableOptionsDict setValue:[[NSBundle mainBundle] bundleIdentifier] forKey:kFIRBundleID]; + self.optionsDictionary = mutableOptionsDict; + } + return self; +} + +- (NSString *)APIKey { + return self.optionsDictionary[kFIRAPIKey]; +} + +- (void)checkEditingLocked { + if (self.isEditingLocked) { + [NSException raise:kFirebaseCoreErrorDomain format:kFIRExceptionBadModification]; + } +} + +- (void)setAPIKey:(NSString *)APIKey { + [self checkEditingLocked]; + _optionsDictionary[kFIRAPIKey] = [APIKey copy]; +} + +- (NSString *)clientID { + return self.optionsDictionary[kFIRClientID]; +} + +- (void)setClientID:(NSString *)clientID { + [self checkEditingLocked]; + _optionsDictionary[kFIRClientID] = [clientID copy]; +} + +- (NSString *)trackingID { + return self.optionsDictionary[kFIRTrackingID]; +} + +- (void)setTrackingID:(NSString *)trackingID { + [self checkEditingLocked]; + _optionsDictionary[kFIRTrackingID] = [trackingID copy]; +} + +- (NSString *)GCMSenderID { + return self.optionsDictionary[kFIRGCMSenderID]; +} + +- (void)setGCMSenderID:(NSString *)GCMSenderID { + [self checkEditingLocked]; + _optionsDictionary[kFIRGCMSenderID] = [GCMSenderID copy]; +} + +- (NSString *)projectID { + return self.optionsDictionary[kFIRProjectID]; +} + +- (void)setProjectID:(NSString *)projectID { + [self checkEditingLocked]; + _optionsDictionary[kFIRProjectID] = [projectID copy]; +} + +- (NSString *)androidClientID { + return self.optionsDictionary[kFIRAndroidClientID]; +} + +- (void)setAndroidClientID:(NSString *)androidClientID { + [self checkEditingLocked]; + _optionsDictionary[kFIRAndroidClientID] = [androidClientID copy]; +} + +- (NSString *)googleAppID { + return self.optionsDictionary[kFIRGoogleAppID]; +} + +- (void)setGoogleAppID:(NSString *)googleAppID { + [self checkEditingLocked]; + _optionsDictionary[kFIRGoogleAppID] = [googleAppID copy]; +} + +- (NSString *)libraryVersionID { + return kFIRLibraryVersionID; +} + +- (void)setLibraryVersionID:(NSString *)libraryVersionID { + _optionsDictionary[kFIRLibraryVersionID] = [libraryVersionID copy]; +} + +- (NSString *)databaseURL { + return self.optionsDictionary[kFIRDatabaseURL]; +} + +- (void)setDatabaseURL:(NSString *)databaseURL { + [self checkEditingLocked]; + + _optionsDictionary[kFIRDatabaseURL] = [databaseURL copy]; +} + +- (NSString *)storageBucket { + return self.optionsDictionary[kFIRStorageBucket]; +} + +- (void)setStorageBucket:(NSString *)storageBucket { + [self checkEditingLocked]; + _optionsDictionary[kFIRStorageBucket] = [storageBucket copy]; +} + +- (void)setDeepLinkURLScheme:(NSString *)deepLinkURLScheme { + [self checkEditingLocked]; + _deepLinkURLScheme = [deepLinkURLScheme copy]; +} + +- (NSString *)bundleID { + return self.optionsDictionary[kFIRBundleID]; +} + +- (void)setBundleID:(NSString *)bundleID { + [self checkEditingLocked]; + _optionsDictionary[kFIRBundleID] = [bundleID copy]; +} + +#pragma mark - Internal instance methods + +- (NSDictionary *)analyticsOptionsDictionaryWithInfoDictionary:(NSDictionary *)infoDictionary { + if (_analyticsOptionsDictionary == nil) { + NSMutableDictionary *tempAnalyticsOptions = [[NSMutableDictionary alloc] init]; + NSArray *measurementKeys = @[ + kFIRIsMeasurementEnabled, kFIRIsAnalyticsCollectionEnabled, + kFIRIsAnalyticsCollectionDeactivated + ]; + for (NSString *key in measurementKeys) { + id value = infoDictionary[key] ?: self.optionsDictionary[key] ?: nil; + if (!value) { + continue; + } + tempAnalyticsOptions[key] = value; + } + _analyticsOptionsDictionary = tempAnalyticsOptions; + } + return _analyticsOptionsDictionary; +} + +- (NSDictionary *)analyticsOptionsDictionary { + return [self analyticsOptionsDictionaryWithInfoDictionary:[NSBundle mainBundle].infoDictionary]; +} + +/** + * Whether or not Measurement was enabled. Measurement is enabled unless explicitly disabled in + * GoogleService-Info.plist. This uses the old plist flag IS_MEASUREMENT_ENABLED, which should still + * be supported. + */ +- (BOOL)isMeasurementEnabled { + if (self.isAnalyticsCollectionDeactivated) { + return NO; + } + NSNumber *value = self.analyticsOptionsDictionary[kFIRIsMeasurementEnabled]; + if (value == nil) { + // TODO: This could probably be cleaned up since FIROptions shouldn't know about FIRApp or have + // to check if it's the default app. The FIROptions instance can't be modified after + // `+configure` is called, so it's not a good place to copy it either in case the flag is + // changed at runtime. + + // If no values are set for Analytics, fall back to the global collection switch in FIRApp. + // Analytics only supports the default FIRApp, so check that first. + if (![FIRApp isDefaultAppConfigured]) { + return NO; + } + + // Fall back to the default app's collection switch when the key is not in the dictionary. + return [FIRApp defaultApp].isDataCollectionDefaultEnabled; + } + return [value boolValue]; +} + +- (BOOL)isAnalyticsCollectionExpicitlySet { + // If it's de-activated, it classifies as explicity set. If not, it's not a good enough indication + // that the developer wants FirebaseAnalytics enabled so continue checking. + if (self.isAnalyticsCollectionDeactivated) { + return YES; + } + + // Check if the current Analytics flag is set. + id collectionEnabledObject = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionEnabled]; + if (collectionEnabledObject && [collectionEnabledObject isKindOfClass:[NSNumber class]]) { + // It doesn't matter what the value is, it's explicitly set. + return YES; + } + + // Check if the old measurement flag is set. + id measurementEnabledObject = self.analyticsOptionsDictionary[kFIRIsMeasurementEnabled]; + if (measurementEnabledObject && [measurementEnabledObject isKindOfClass:[NSNumber class]]) { + // It doesn't matter what the value is, it's explicitly set. + return YES; + } + + // No flags are set to explicitly enable or disable FirebaseAnalytics. + return NO; +} + +- (BOOL)isAnalyticsCollectionEnabled { + if (self.isAnalyticsCollectionDeactivated) { + return NO; + } + NSNumber *value = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionEnabled]; + if (value == nil) { + return self.isMeasurementEnabled; // Fall back to older plist flag. + } + return [value boolValue]; +} + +- (BOOL)isAnalyticsCollectionDeactivated { + NSNumber *value = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionDeactivated]; + if (value == nil) { + return NO; // Analytics Collection is not deactivated when the key is not in the dictionary. + } + return [value boolValue]; +} + +- (BOOL)isAnalyticsEnabled { + return [self.optionsDictionary[kFIRIsAnalyticsEnabled] boolValue]; +} + +- (BOOL)isSignInEnabled { + return [self.optionsDictionary[kFIRIsSignInEnabled] boolValue]; +} + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/FIRVersion.m b/Pods/FirebaseCore/Firebase/Core/FIRVersion.m new file mode 100644 index 0000000000..ec0f6ba640 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/FIRVersion.m @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef Firebase_VERSION +#error "Firebase_VERSION is not defined: add -DFirebase_VERSION=... to the build invocation" +#endif + +#ifndef FIRCore_VERSION +#error "FIRCore_VERSION is not defined: add -DFIRCore_VERSION=... to the build invocation" +#endif + +// The following two macros supply the incantation so that the C +// preprocessor does not try to parse the version as a floating +// point number. See +// https://www.guyrutenberg.com/2008/12/20/expanding-macros-into-string-constants-in-c/ +#define STR(x) STR_EXPAND(x) +#define STR_EXPAND(x) #x + +const char *const FIRVersionString = (const char *const)STR(Firebase_VERSION); +const char *const FIRCoreVersionString = (const char *const)STR(FIRCore_VERSION); diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRAnalyticsConfiguration+Internal.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRAnalyticsConfiguration+Internal.h new file mode 100644 index 0000000000..be624b4941 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRAnalyticsConfiguration+Internal.h @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAnalyticsConfiguration.h" + +/// Values stored in analyticsEnabledState. Never alter these constants since they must match with +/// values persisted to disk. +typedef NS_ENUM(int64_t, FIRAnalyticsEnabledState) { + // 0 is the default value for keys not found stored in persisted config, so it cannot represent + // kFIRAnalyticsEnabledStateSetNo. It must represent kFIRAnalyticsEnabledStateNotSet. + kFIRAnalyticsEnabledStateNotSet = 0, + kFIRAnalyticsEnabledStateSetYes = 1, + kFIRAnalyticsEnabledStateSetNo = 2, +}; + +/// The user defaults key for the persisted measurementEnabledState value. FIRAPersistedConfig reads +/// measurementEnabledState using this same key. +static NSString *const kFIRAPersistedConfigMeasurementEnabledStateKey = + @"/google/measurement/measurement_enabled_state"; + +static NSString *const kFIRAnalyticsConfigurationSetEnabledNotification = + @"FIRAnalyticsConfigurationSetEnabledNotification"; +static NSString *const kFIRAnalyticsConfigurationSetMinimumSessionIntervalNotification = + @"FIRAnalyticsConfigurationSetMinimumSessionIntervalNotification"; +static NSString *const kFIRAnalyticsConfigurationSetSessionTimeoutIntervalNotification = + @"FIRAnalyticsConfigurationSetSessionTimeoutIntervalNotification"; + +@interface FIRAnalyticsConfiguration (Internal) + +/// Sets whether analytics collection is enabled for this app on this device, and a flag to persist +/// the value or not. The setting should not be persisted if being set by the global data collection +/// flag. +- (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled + persistSetting:(BOOL)shouldPersist; + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRAppAssociationRegistration.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRAppAssociationRegistration.h new file mode 100644 index 0000000000..3fc69c6c25 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRAppAssociationRegistration.h @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +// TODO: Remove this once Auth moves over to Core's instance registration system. +/** @class FIRAppAssociationRegistration + @brief Manages object associations as a singleton-dependent: At most one object is + registered for any given host/key pair, and the object shall be created on-the-fly when + asked for. + */ +@interface FIRAppAssociationRegistration : NSObject + +/** @fn registeredObjectWithHost:key:creationBlock: + @brief Retrieves the registered object with a particular host and key. + @param host The host object. + @param key The key to specify the registered object on the host. + @param creationBlock The block to return the object to be registered if not already. + The block is executed immediately before this method returns if it is executed at all. + It can also be executed multiple times across different method invocations if previous + execution of the block returns @c nil. + @return The registered object for the host/key pair, or @c nil if no object is registered + and @c creationBlock returns @c nil. + @remarks The method is thread-safe but non-reentrant in the sense that attempting to call this + method again within the @c creationBlock with the same host/key pair raises an exception. + The registered object is retained by the host. + */ ++ (nullable ObjectType)registeredObjectWithHost:(id)host + key:(NSString *)key + creationBlock:(ObjectType _Nullable (^)(void))creationBlock; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRAppInternal.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRAppInternal.h new file mode 100644 index 0000000000..e1aa65d0ba --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRAppInternal.h @@ -0,0 +1,222 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRApp.h" +#import "FIRErrors.h" + +@class FIRComponentContainer; +@protocol FIRCoreConfigurable; + +/** + * The internal interface to FIRApp. This is meant for first-party integrators, who need to receive + * FIRApp notifications, log info about the success or failure of their configuration, and access + * other internal functionality of FIRApp. + * + * TODO(b/28296561): Restructure this header. + */ +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, FIRConfigType) { + FIRConfigTypeCore = 1, + FIRConfigTypeSDK = 2, +}; + +/** + * Names of services provided by Firebase. + */ +extern NSString *const kFIRServiceAdMob; +extern NSString *const kFIRServiceAuth; +extern NSString *const kFIRServiceAuthUI; +extern NSString *const kFIRServiceCrash; +extern NSString *const kFIRServiceDatabase; +extern NSString *const kFIRServiceDynamicLinks; +extern NSString *const kFIRServiceInstanceID; +extern NSString *const kFIRServiceInvites; +extern NSString *const kFIRServiceMessaging; +extern NSString *const kFIRServiceMeasurement; +extern NSString *const kFIRServiceRemoteConfig; +extern NSString *const kFIRServiceStorage; + +/** + * Names of services provided by the Google pod, but logged by the Firebase pod. + */ +extern NSString *const kGGLServiceAnalytics; +extern NSString *const kGGLServiceSignIn; + +extern NSString *const kFIRDefaultAppName; +extern NSString *const kFIRAppReadyToConfigureSDKNotification; +extern NSString *const kFIRAppDeleteNotification; +extern NSString *const kFIRAppIsDefaultAppKey; +extern NSString *const kFIRAppNameKey; +extern NSString *const kFIRGoogleAppIDKey; + +/** + * The format string for the User Defaults key used for storing the data collection enabled flag. + * This includes formatting to append the Firebase App's name. + */ +extern NSString *const kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat; + +/** + * The plist key used for storing the data collection enabled flag. + */ +extern NSString *const kFIRGlobalAppDataCollectionEnabledPlistKey; + +/** + * A notification fired containing diagnostic information when SDK errors occur. + */ +extern NSString *const kFIRAppDiagnosticsNotification; + +/** @var FIRAuthStateDidChangeInternalNotification + @brief The name of the @c NSNotificationCenter notification which is posted when the auth state + changes (e.g. a new token has been produced, a user logs in or out). The object parameter of + the notification is a dictionary possibly containing the key: + @c FIRAuthStateDidChangeInternalNotificationTokenKey (the new access token.) If it does not + contain this key it indicates a sign-out event took place. + */ +extern NSString *const FIRAuthStateDidChangeInternalNotification; + +/** @var FIRAuthStateDidChangeInternalNotificationTokenKey + @brief A key present in the dictionary object parameter of the + @c FIRAuthStateDidChangeInternalNotification notification. The value associated with this + key will contain the new access token. + */ +extern NSString *const FIRAuthStateDidChangeInternalNotificationTokenKey; + +/** @var FIRAuthStateDidChangeInternalNotificationAppKey + @brief A key present in the dictionary object parameter of the + @c FIRAuthStateDidChangeInternalNotification notification. The value associated with this + key will contain the FIRApp associated with the auth instance. + */ +extern NSString *const FIRAuthStateDidChangeInternalNotificationAppKey; + +/** @var FIRAuthStateDidChangeInternalNotificationUIDKey + @brief A key present in the dictionary object parameter of the + @c FIRAuthStateDidChangeInternalNotification notification. The value associated with this + key will contain the new user's UID (or nil if there is no longer a user signed in). + */ +extern NSString *const FIRAuthStateDidChangeInternalNotificationUIDKey; + +/** @typedef FIRTokenCallback + @brief The type of block which gets called when a token is ready. + */ +typedef void (^FIRTokenCallback)(NSString *_Nullable token, NSError *_Nullable error); + +/** @typedef FIRAppGetTokenImplementation + @brief The type of block which can provide an implementation for the @c getTokenWithCallback: + method. + @param forceRefresh Forces the token to be refreshed. + @param callback The block which should be invoked when the async call completes. + */ +typedef void (^FIRAppGetTokenImplementation)(BOOL forceRefresh, FIRTokenCallback callback); + +/** @typedef FIRAppGetUID + @brief The type of block which can provide an implementation for the @c getUID method. + */ +typedef NSString *_Nullable (^FIRAppGetUIDImplementation)(void); + +@interface FIRApp () + +/** + * A flag indicating if this is the default app (has the default app name). + */ +@property(nonatomic, readonly) BOOL isDefaultApp; + +/** @property getTokenImplementation + @brief Gets or sets the block to use for the implementation of + @c getTokenForcingRefresh:withCallback: + */ +@property(nonatomic, copy) FIRAppGetTokenImplementation getTokenImplementation; + +/** @property getUIDImplementation + @brief Gets or sets the block to use for the implementation of @c getUID. + */ +@property(nonatomic, copy) FIRAppGetUIDImplementation getUIDImplementation; + +/* + * The container of interop SDKs for this app. + */ +@property(nonatomic) FIRComponentContainer *container; + +/** + * Creates an error for failing to configure a subspec service. This method is called by each + * FIRApp notification listener. + */ ++ (NSError *)errorForSubspecConfigurationFailureWithDomain:(NSString *)domain + errorCode:(FIRErrorCode)code + service:(NSString *)service + reason:(NSString *)reason; +/** + * Checks if the default app is configured without trying to configure it. + */ ++ (BOOL)isDefaultAppConfigured; + +/** + * Register a class that conforms to `FIRCoreConfigurable`. Each SDK should have one class that + * registers in order to provide critical information for interoperability and lifecycle events. + * TODO(wilsonryan): Write more documentation. + */ ++ (void)registerAsConfigurable:(Class)klass; + +/** + * Registers a given third-party library with the given version number to be reported for + * analyitcs. + * + * @param library Name of the library + * @param version Version of the library + */ +// clang-format off ++ (void)registerLibrary:(NSString *)library + withVersion:(NSString *)version NS_SWIFT_NAME(registerLibrary(_:version:)); +// clang-format on + +/** + * A concatenated string representing all the third-party libraries and version numbers. + */ ++ (NSString *)firebaseUserAgent; + +/** + * Used by each SDK to send logs about SDK configuration status to Clearcut. + */ +- (void)sendLogsWithServiceName:(NSString *)serviceName + version:(NSString *)version + error:(NSError *)error; + +/** + * Can be used by the unit tests in eack SDK to reset FIRApp. This method is thread unsafe. + */ ++ (void)resetApps; + +/** + * Can be used by the unit tests in each SDK to set customized options. + */ +- (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options; + +/** @fn getTokenForcingRefresh:withCallback: + @brief Retrieves the Firebase authentication token, possibly refreshing it. + @param forceRefresh Forces a token refresh. Useful if the token becomes invalid for some reason + other than an expiration. + @param callback The block to invoke when the token is available. + */ +- (void)getTokenForcingRefresh:(BOOL)forceRefresh withCallback:(FIRTokenCallback)callback; + +/** + * Expose the UID of the current user for Firestore. + */ +- (nullable NSString *)getUID; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRBundleUtil.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRBundleUtil.h new file mode 100644 index 0000000000..c458a2c4c6 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRBundleUtil.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** + * This class provides utilities for accessing resources in bundles. + */ +@interface FIRBundleUtil : NSObject + +/** + * Finds all relevant bundles, starting with [NSBundle mainBundle]. + */ ++ (NSArray *)relevantBundles; + +/** + * Reads the options dictionary from one of the provided bundles. + * + * @param resourceName The resource name, e.g. @"GoogleService-Info". + * @param fileType The file type (extension), e.g. @"plist". + * @param bundles The bundles to expect, in priority order. See also + * +[FIRBundleUtil relevantBundles]. + */ ++ (NSString *)optionsDictionaryPathWithResourceName:(NSString *)resourceName + andFileType:(NSString *)fileType + inBundles:(NSArray *)bundles; + +/** + * Finds URL schemes defined in all relevant bundles, starting with those from + * [NSBundle mainBundle]. + */ ++ (NSArray *)relevantURLSchemes; + +/** + * Checks if the bundle identifier exists in the given bundles. + */ ++ (BOOL)hasBundleIdentifier:(NSString *)bundleIdentifier inBundles:(NSArray *)bundles; + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRComponent.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponent.h new file mode 100644 index 0000000000..cb51ee70e2 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponent.h @@ -0,0 +1,91 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRApp; +@class FIRComponentContainer; + +NS_ASSUME_NONNULL_BEGIN + +/// Provides a system to clean up cached instances returned from the component system. +NS_SWIFT_NAME(ComponentLifecycleMaintainer) +@protocol FIRComponentLifecycleMaintainer +/// The associated app will be deleted, clean up any resources as they are about to be deallocated. +- (void)appWillBeDeleted:(FIRApp *)app; +@end + +typedef _Nullable id (^FIRComponentCreationBlock)(FIRComponentContainer *container, + BOOL *isCacheable) + NS_SWIFT_NAME(ComponentCreationBlock); + +@class FIRDependency; + +/// Describes the timing of instantiation. Note: new components should default to lazy unless there +/// is a strong reason to be eager. +typedef NS_ENUM(NSInteger, FIRInstantiationTiming) { + FIRInstantiationTimingLazy, + FIRInstantiationTimingAlwaysEager, + FIRInstantiationTimingEagerInDefaultApp +} NS_SWIFT_NAME(InstantiationTiming); + +/// A component that can be used from other Firebase SDKs. +NS_SWIFT_NAME(Component) +@interface FIRComponent : NSObject + +/// The protocol describing functionality provided from the Component. +@property(nonatomic, strong, readonly) Protocol *protocol; + +/// The timing of instantiation. +@property(nonatomic, readonly) FIRInstantiationTiming instantiationTiming; + +/// An array of dependencies for the component. +@property(nonatomic, copy, readonly) NSArray *dependencies; + +/// A block to instantiate an instance of the component with the appropriate dependencies. +@property(nonatomic, copy, readonly) FIRComponentCreationBlock creationBlock; + +// There's an issue with long NS_SWIFT_NAMES that causes compilation to fail, disable clang-format +// for the next two methods. +// clang-format off + +/// Creates a component with no dependencies that will be lazily initialized. ++ (instancetype)componentWithProtocol:(Protocol *)protocol + creationBlock:(FIRComponentCreationBlock)creationBlock +NS_SWIFT_NAME(init(_:creationBlock:)); + +/// Creates a component to be registered with the component container. +/// +/// @param protocol - The protocol describing functionality provided by the component. +/// @param instantiationTiming - When the component should be initialized. Use .lazy unless there's +/// a good reason to be instantiated earlier. +/// @param dependencies - Any dependencies the `implementingClass` has, optional or required. +/// @param creationBlock - A block to instantiate the component with a container, and if +/// @return A component that can be registered with the component container. ++ (instancetype)componentWithProtocol:(Protocol *)protocol + instantiationTiming:(FIRInstantiationTiming)instantiationTiming + dependencies:(NSArray *)dependencies + creationBlock:(FIRComponentCreationBlock)creationBlock +NS_SWIFT_NAME(init(_:instantiationTiming:dependencies:creationBlock:)); + +// clang-format on + +/// Unavailable. +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainer.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainer.h new file mode 100644 index 0000000000..10e2255389 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainer.h @@ -0,0 +1,47 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#import + +#import "FIRComponentType.h" + +NS_ASSUME_NONNULL_BEGIN + +/// A type-safe macro to retrieve a component from a container. This should be used to retrieve +/// components instead of using the container directly. +#define FIR_COMPONENT(type, container) \ + [FIRComponentType> instanceForProtocol:@protocol(type) inContainer:container] + +@class FIRApp; + +/// A container that holds different components that are registered via the +/// `registerAsComponentRegistrant:` call. These classes should conform to `FIRComponentRegistrant` +/// in order to properly register components for Core. +NS_SWIFT_NAME(FirebaseComponentContainer) +@interface FIRComponentContainer : NSObject + +/// A weak reference to the app that an instance of the container belongs to. +@property(nonatomic, weak, readonly) FIRApp *app; + +/// Unavailable. Use the `container` property on `FIRApp`. +- (instancetype)init NS_UNAVAILABLE; + +/// Register a class to provide components for the interoperability system. The class should conform +/// to `FIRComponentRegistrant` and provide an array of `FIRComponent` objects. ++ (void)registerAsComponentRegistrant:(Class)klass; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainerInternal.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainerInternal.h new file mode 100644 index 0000000000..bb73e7bab5 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainerInternal.h @@ -0,0 +1,39 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#import + +#import "FIRComponent.h" +#import "FIRComponentContainer.h" + +@class FIRApp; + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRComponentContainer (Private) + +/// Initializes a contain for a given app. This should only be called by the app itself. +- (instancetype)initWithApp:(FIRApp *)app; + +/// Retrieves an instance that conforms to the specified protocol. This will return `nil` if the +/// protocol wasn't registered, or if the instance couldn't instantiate for the provided app. +- (nullable id)instanceForProtocol:(Protocol *)protocol NS_SWIFT_NAME(instance(for:)); + +/// Remove all of the cached instances stored and allow them to clean up after themselves. +- (void)removeAllCachedInstances; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentRegistrant.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentRegistrant.h new file mode 100644 index 0000000000..ad2cad2146 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentRegistrant.h @@ -0,0 +1,38 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRComponentRegistrant_h +#define FIRComponentRegistrant_h + +#import + +@class FIRComponent; + +NS_ASSUME_NONNULL_BEGIN + +/// Describes functionality for SDKs registering components in the `FIRComponentContainer`. +NS_SWIFT_NAME(ComponentRegistrant) +@protocol FIRComponentRegistrant + +/// Returns one or more FIRComponents that will be registered in +/// FIRApp and participate in dependency resolution and injection. ++ (NSArray *)componentsToRegister; + +@end + +NS_ASSUME_NONNULL_END + +#endif /* FIRComponentRegistrant_h */ diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentType.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentType.h new file mode 100644 index 0000000000..6f2aca7b86 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentType.h @@ -0,0 +1,34 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRComponentContainer; + +NS_ASSUME_NONNULL_BEGIN + +/// Do not use directly. A placeholder type in order to provide a macro that will warn users of +/// mis-matched protocols. +NS_SWIFT_NAME(ComponentType) +@interface FIRComponentType<__covariant T> : NSObject + +/// Do not use directly. A factory method to retrieve an instance that provides a specific +/// functionality. ++ (T)instanceForProtocol:(Protocol *)protocol inContainer:(FIRComponentContainer *)container; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRCoreConfigurable.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRCoreConfigurable.h new file mode 100644 index 0000000000..6c2b077517 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRCoreConfigurable.h @@ -0,0 +1,38 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRCoreConfigurable_h +#define FIRCoreConfigurable_h + +#import + +@class FIRApp; + +NS_ASSUME_NONNULL_BEGIN + +/// Provides an interface to set up an SDK once a `FIRApp` is configured. +NS_SWIFT_NAME(CoreConfigurable) +@protocol FIRCoreConfigurable + +/// Configure the SDK if needed ahead of time. This method is called when the developer calls +/// `FirebaseApp.configure()`. ++ (void)configureWithApp:(FIRApp *)app; + +@end + +NS_ASSUME_NONNULL_END + +#endif /* FIRCoreConfigurable_h */ diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRDependency.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRDependency.h new file mode 100644 index 0000000000..46e9b7ea60 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRDependency.h @@ -0,0 +1,45 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// A dependency on a specific protocol's functionality. +NS_SWIFT_NAME(Dependency) +@interface FIRDependency : NSObject + +/// The protocol describing functionality being depended on. +@property(nonatomic, strong, readonly) Protocol *protocol; + +/// A flag to specify if the dependency is required or not. +@property(nonatomic, readonly) BOOL isRequired; + +/// Initializes a dependency that is required. Calls `initWithProtocol:isRequired` with `YES` for +/// the required parameter. +/// Creates a required dependency on the specified protocol's functionality. ++ (instancetype)dependencyWithProtocol:(Protocol *)protocol; + +/// Creates a dependency on the specified protocol's functionality and specify if it's required for +/// the class's functionality. ++ (instancetype)dependencyWithProtocol:(Protocol *)protocol isRequired:(BOOL)required; + +/// Use `dependencyWithProtocol:isRequired:` instead. +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRErrorCode.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRErrorCode.h new file mode 100644 index 0000000000..01d3c56e36 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRErrorCode.h @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Error codes in Firebase error domain. */ +typedef NS_ENUM(NSInteger, FIRErrorCode) { + /** + * Unknown error. + */ + FIRErrorCodeUnknown = 0, + /** + * Loading data from the GoogleService-Info.plist file failed. This is a fatal error and should + * not be ignored. Further calls to the API will fail and/or possibly cause crashes. + */ + FIRErrorCodeInvalidPlistFile = -100, + + /** + * Validating the Google App ID format failed. + */ + FIRErrorCodeInvalidAppID = -101, + + /** + * Error code for failing to configure a specific service. + */ + FIRErrorCodeAdMobFailed = -110, + FIRErrorCodeAppInviteFailed = -112, + FIRErrorCodeCloudMessagingFailed = -113, + FIRErrorCodeConfigFailed = -114, + FIRErrorCodeDatabaseFailed = -115, + FIRErrorCodeCrashReportingFailed = -118, + FIRErrorCodeDurableDeepLinkFailed = -119, + FIRErrorCodeAuthFailed = -120, + FIRErrorCodeInstanceIDFailed = -121, + FIRErrorCodeStorageFailed = -123, + + /** + * Error codes returned by Dynamic Links + */ + FIRErrorCodeDynamicLinksStrongMatchNotAvailable = -124, + FIRErrorCodeDynamicLinksManualRetrievalNotEnabled = -125, + FIRErrorCodeDynamicLinksPendingLinkOnlyAvailableAtFirstLaunch = -126, + FIRErrorCodeDynamicLinksPendingLinkRetrievalAlreadyRunning = -127, +}; diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRErrors.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRErrors.h new file mode 100644 index 0000000000..cf69252aa9 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRErrors.h @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#include "FIRErrorCode.h" + +extern NSString *const kFirebaseErrorDomain; +extern NSString *const kFirebaseAdMobErrorDomain; +extern NSString *const kFirebaseAppInviteErrorDomain; +extern NSString *const kFirebaseAuthErrorDomain; +extern NSString *const kFirebaseCloudMessagingErrorDomain; +extern NSString *const kFirebaseConfigErrorDomain; +extern NSString *const kFirebaseCoreErrorDomain; +extern NSString *const kFirebaseCrashReportingErrorDomain; +extern NSString *const kFirebaseDatabaseErrorDomain; +extern NSString *const kFirebaseDurableDeepLinkErrorDomain; +extern NSString *const kFirebaseInstanceIDErrorDomain; +extern NSString *const kFirebasePerfErrorDomain; +extern NSString *const kFirebaseStorageErrorDomain; diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRLogger.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRLogger.h new file mode 100644 index 0000000000..a538199be1 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRLogger.h @@ -0,0 +1,159 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRLoggerLevel.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * The Firebase services used in Firebase logger. + */ +typedef NSString *const FIRLoggerService; + +extern FIRLoggerService kFIRLoggerABTesting; +extern FIRLoggerService kFIRLoggerAdMob; +extern FIRLoggerService kFIRLoggerAnalytics; +extern FIRLoggerService kFIRLoggerAuth; +extern FIRLoggerService kFIRLoggerCore; +extern FIRLoggerService kFIRLoggerCrash; +extern FIRLoggerService kFIRLoggerDatabase; +extern FIRLoggerService kFIRLoggerDynamicLinks; +extern FIRLoggerService kFIRLoggerFirestore; +extern FIRLoggerService kFIRLoggerInstanceID; +extern FIRLoggerService kFIRLoggerInvites; +extern FIRLoggerService kFIRLoggerMLKit; +extern FIRLoggerService kFIRLoggerMessaging; +extern FIRLoggerService kFIRLoggerPerf; +extern FIRLoggerService kFIRLoggerRemoteConfig; +extern FIRLoggerService kFIRLoggerStorage; +extern FIRLoggerService kFIRLoggerSwizzler; + +/** + * The key used to store the logger's error count. + */ +extern NSString *const kFIRLoggerErrorCountKey; + +/** + * The key used to store the logger's warning count. + */ +extern NSString *const kFIRLoggerWarningCountKey; + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Enables or disables Analytics debug mode. + * If set to YES, the logging level for Analytics will be set to FIRLoggerLevelDebug. + * Enabling the debug mode has no effect if the app is running from App Store. + * (required) analytics debug mode flag. + */ +void FIRSetAnalyticsDebugMode(BOOL analyticsDebugMode); + +/** + * Changes the default logging level of FIRLoggerLevelNotice to a user-specified level. + * The default level cannot be set above FIRLoggerLevelNotice if the app is running from App Store. + * (required) log level (one of the FIRLoggerLevel enum values). + */ +void FIRSetLoggerLevel(FIRLoggerLevel loggerLevel); + +/** + * Checks if the specified logger level is loggable given the current settings. + * (required) log level (one of the FIRLoggerLevel enum values). + * (required) whether or not this function is called from the Analytics component. + */ +BOOL FIRIsLoggableLevel(FIRLoggerLevel loggerLevel, BOOL analyticsComponent); + +/** + * Logs a message to the Xcode console and the device log. If running from AppStore, will + * not log any messages with a level higher than FIRLoggerLevelNotice to avoid log spamming. + * (required) log level (one of the FIRLoggerLevel enum values). + * (required) service name of type FIRLoggerService. + * (required) message code starting with "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * (required) message string which can be a format string. + * (optional) variable arguments list obtained from calling va_start, used when message is a format + * string. + */ +extern void FIRLogBasic(FIRLoggerLevel level, + FIRLoggerService service, + NSString *messageCode, + NSString *message, +// On 64-bit simulators, va_list is not a pointer, so cannot be marked nullable +// See: http://stackoverflow.com/q/29095469 +#if __LP64__ && TARGET_OS_SIMULATOR || TARGET_OS_OSX + va_list args_ptr +#else + va_list _Nullable args_ptr +#endif +); + +/** + * The following functions accept the following parameters in order: + * (required) service name of type FIRLoggerService. + * (required) message code starting from "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * See go/firebase-log-proposal for details. + * (required) message string which can be a format string. + * (optional) the list of arguments to substitute into the format string. + * Example usage: + * FIRLogError(kFIRLoggerCore, @"I-COR000001", @"Configuration of %@ failed.", app.name); + */ +extern void FIRLogError(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); +extern void FIRLogWarning(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); +extern void FIRLogNotice(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); +extern void FIRLogInfo(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); +extern void FIRLogDebug(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +@interface FIRLoggerWrapper : NSObject + +/** + * Objective-C wrapper for FIRLogBasic to allow weak linking to FIRLogger + * (required) log level (one of the FIRLoggerLevel enum values). + * (required) service name of type FIRLoggerService. + * (required) message code starting with "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * (required) message string which can be a format string. + * (optional) variable arguments list obtained from calling va_start, used when message is a format + * string. + */ + ++ (void)logWithLevel:(FIRLoggerLevel)level + withService:(FIRLoggerService)service + withCode:(NSString *)messageCode + withMessage:(NSString *)message + withArgs:(va_list)args; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIROptionsInternal.h b/Pods/FirebaseCore/Firebase/Core/Private/FIROptionsInternal.h new file mode 100644 index 0000000000..7bb40fc10d --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIROptionsInternal.h @@ -0,0 +1,114 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIROptions.h" + +/** + * Keys for the strings in the plist file. + */ +extern NSString *const kFIRAPIKey; +extern NSString *const kFIRTrackingID; +extern NSString *const kFIRGoogleAppID; +extern NSString *const kFIRClientID; +extern NSString *const kFIRGCMSenderID; +extern NSString *const kFIRAndroidClientID; +extern NSString *const kFIRDatabaseURL; +extern NSString *const kFIRStorageBucket; +extern NSString *const kFIRBundleID; +extern NSString *const kFIRProjectID; + +/** + * Keys for the plist file name + */ +extern NSString *const kServiceInfoFileName; + +extern NSString *const kServiceInfoFileType; + +/** + * This header file exposes the initialization of FIROptions to internal use. + */ +@interface FIROptions () + +/** + * resetDefaultOptions and initInternalWithOptionsDictionary: are exposed only for unit tests. + */ ++ (void)resetDefaultOptions; + +/** + * Initializes the options with dictionary. The above strings are the keys of the dictionary. + * This is the designated initializer. + */ +- (instancetype)initInternalWithOptionsDictionary:(NSDictionary *)serviceInfoDictionary; + +/** + * defaultOptions and defaultOptionsDictionary are exposed in order to be used in FIRApp and + * other first party services. + */ ++ (FIROptions *)defaultOptions; + ++ (NSDictionary *)defaultOptionsDictionary; + +/** + * Indicates whether or not Analytics collection was explicitly enabled via a plist flag or at + * runtime. + */ +@property(nonatomic, readonly) BOOL isAnalyticsCollectionExpicitlySet; + +/** + * Whether or not Analytics Collection was enabled. Analytics Collection is enabled unless + * explicitly disabled in GoogleService-Info.plist. + */ +@property(nonatomic, readonly) BOOL isAnalyticsCollectionEnabled; + +/** + * Whether or not Analytics Collection was completely disabled. If YES, then + * isAnalyticsCollectionEnabled will be NO. + */ +@property(nonatomic, readonly) BOOL isAnalyticsCollectionDeactivated; + +/** + * The version ID of the client library, e.g. @"1100000". + */ +@property(nonatomic, readonly, copy) NSString *libraryVersionID; + +/** + * The flag indicating whether this object was constructed with the values in the default plist + * file. + */ +@property(nonatomic) BOOL usingOptionsFromDefaultPlist; + +/** + * Whether or not Measurement was enabled. Measurement is enabled unless explicitly disabled in + * GoogleService-Info.plist. + */ +@property(nonatomic, readonly) BOOL isMeasurementEnabled; + +/** + * Whether or not Analytics was enabled in the developer console. + */ +@property(nonatomic, readonly) BOOL isAnalyticsEnabled; + +/** + * Whether or not SignIn was enabled in the developer console. + */ +@property(nonatomic, readonly) BOOL isSignInEnabled; + +/** + * Whether or not editing is locked. This should occur after FIROptions has been set on a FIRApp. + */ +@property(nonatomic, getter=isEditingLocked) BOOL editingLocked; + +@end diff --git a/Pods/FirebaseCore/Firebase/Core/Private/FIRVersion.h b/Pods/FirebaseCore/Firebase/Core/Private/FIRVersion.h new file mode 100644 index 0000000000..226efb1a76 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Private/FIRVersion.h @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** The version of the Firebase SDK. */ +FOUNDATION_EXPORT const char *const FIRVersionString; + +/** The version of the FirebaseCore Component. */ +FOUNDATION_EXPORT const char *const FIRCoreVersionString; diff --git a/Pods/FirebaseCore/Firebase/Core/Public/FIRAnalyticsConfiguration.h b/Pods/FirebaseCore/Firebase/Core/Public/FIRAnalyticsConfiguration.h new file mode 100644 index 0000000000..ca1d32c6e2 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Public/FIRAnalyticsConfiguration.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * This class provides configuration fields for Firebase Analytics. + */ +NS_SWIFT_NAME(AnalyticsConfiguration) +@interface FIRAnalyticsConfiguration : NSObject + +/** + * Returns the shared instance of FIRAnalyticsConfiguration. + */ ++ (FIRAnalyticsConfiguration *)sharedInstance NS_SWIFT_NAME(shared()); + +/** + * Sets the minimum engagement time in seconds required to start a new session. The default value + * is 10 seconds. + */ +- (void)setMinimumSessionInterval:(NSTimeInterval)minimumSessionInterval; + +/** + * Sets the interval of inactivity in seconds that terminates the current session. The default + * value is 1800 seconds (30 minutes). + */ +- (void)setSessionTimeoutInterval:(NSTimeInterval)sessionTimeoutInterval; + +/** + * Sets whether analytics collection is enabled for this app on this device. This setting is + * persisted across app sessions. By default it is enabled. + */ +- (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Public/FIRApp.h b/Pods/FirebaseCore/Firebase/Core/Public/FIRApp.h new file mode 100644 index 0000000000..e0dd6d6929 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Public/FIRApp.h @@ -0,0 +1,127 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIROptions; + +NS_ASSUME_NONNULL_BEGIN + +/** A block that takes a BOOL and has no return value. */ +typedef void (^FIRAppVoidBoolCallback)(BOOL success) NS_SWIFT_NAME(FirebaseAppVoidBoolCallback); + +/** + * The entry point of Firebase SDKs. + * + * Initialize and configure FIRApp using +[FIRApp configure] + * or other customized ways as shown below. + * + * The logging system has two modes: default mode and debug mode. In default mode, only logs with + * log level Notice, Warning and Error will be sent to device. In debug mode, all logs will be sent + * to device. The log levels that Firebase uses are consistent with the ASL log levels. + * + * Enable debug mode by passing the -FIRDebugEnabled argument to the application. You can add this + * argument in the application's Xcode scheme. When debug mode is enabled via -FIRDebugEnabled, + * further executions of the application will also be in debug mode. In order to return to default + * mode, you must explicitly disable the debug mode with the application argument -FIRDebugDisabled. + * + * It is also possible to change the default logging level in code by calling setLoggerLevel: on + * the FIRConfiguration interface. + */ +NS_SWIFT_NAME(FirebaseApp) +@interface FIRApp : NSObject + +/** + * Configures a default Firebase app. Raises an exception if any configuration step fails. The + * default app is named "__FIRAPP_DEFAULT". This method should be called after the app is launched + * and before using Firebase services. This method is thread safe and contains synchronous file I/O + * (reading GoogleService-Info.plist from disk). + */ ++ (void)configure; + +/** + * Configures the default Firebase app with the provided options. The default app is named + * "__FIRAPP_DEFAULT". Raises an exception if any configuration step fails. This method is thread + * safe. + * + * @param options The Firebase application options used to configure the service. + */ ++ (void)configureWithOptions:(FIROptions *)options NS_SWIFT_NAME(configure(options:)); + +/** + * Configures a Firebase app with the given name and options. Raises an exception if any + * configuration step fails. This method is thread safe. + * + * @param name The application's name given by the developer. The name should should only contain + Letters, Numbers and Underscore. + * @param options The Firebase application options used to configure the services. + */ +// clang-format off ++ (void)configureWithName:(NSString *)name + options:(FIROptions *)options NS_SWIFT_NAME(configure(name:options:)); +// clang-format on + +/** + * Returns the default app, or nil if the default app does not exist. + */ ++ (nullable FIRApp *)defaultApp NS_SWIFT_NAME(app()); + +/** + * Returns a previously created FIRApp instance with the given name, or nil if no such app exists. + * This method is thread safe. + */ ++ (nullable FIRApp *)appNamed:(NSString *)name NS_SWIFT_NAME(app(name:)); + +/** + * Returns the set of all extant FIRApp instances, or nil if there are no FIRApp instances. This + * method is thread safe. + */ +@property(class, readonly, nullable) NSDictionary *allApps; + +/** + * Cleans up the current FIRApp, freeing associated data and returning its name to the pool for + * future use. This method is thread safe. + */ +- (void)deleteApp:(FIRAppVoidBoolCallback)completion; + +/** + * FIRApp instances should not be initialized directly. Call +[FIRApp configure], + * +[FIRApp configureWithOptions:], or +[FIRApp configureWithNames:options:] directly. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** + * Gets the name of this app. + */ +@property(nonatomic, copy, readonly) NSString *name; + +/** + * Gets a copy of the options for this app. These are non-modifiable. + */ +@property(nonatomic, copy, readonly) FIROptions *options; + +/** + * Gets or sets whether automatic data collection is enabled for all products. Defaults to `YES` + * unless `FirebaseDataCollectionDefaultEnabled` is set to `NO` in your app's Info.plist. This value + * is persisted across runs of the app so that it can be set once when users have consented to + * collection. + */ +@property(nonatomic, readwrite, getter=isDataCollectionDefaultEnabled) + BOOL dataCollectionDefaultEnabled; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Public/FIRConfiguration.h b/Pods/FirebaseCore/Firebase/Core/Public/FIRConfiguration.h new file mode 100644 index 0000000000..95bba5e7b3 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Public/FIRConfiguration.h @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAnalyticsConfiguration.h" +#import "FIRLoggerLevel.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * This interface provides global level properties that the developer can tweak, and the singleton + * of the Firebase Analytics configuration class. + */ +NS_SWIFT_NAME(FirebaseConfiguration) +@interface FIRConfiguration : NSObject + +/** Returns the shared configuration object. */ +@property(class, nonatomic, readonly) FIRConfiguration *sharedInstance NS_SWIFT_NAME(shared); + +/** The configuration class for Firebase Analytics. */ +@property(nonatomic, readwrite) FIRAnalyticsConfiguration *analyticsConfiguration; + +/** + * Sets the logging level for internal Firebase logging. Firebase will only log messages + * that are logged at or below loggerLevel. The messages are logged both to the Xcode + * console and to the device's log. Note that if an app is running from AppStore, it will + * never log above FIRLoggerLevelNotice even if loggerLevel is set to a higher (more verbose) + * setting. + * + * @param loggerLevel The maximum logging level. The default level is set to FIRLoggerLevelNotice. + */ +- (void)setLoggerLevel:(FIRLoggerLevel)loggerLevel; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Public/FIRLoggerLevel.h b/Pods/FirebaseCore/Firebase/Core/Public/FIRLoggerLevel.h new file mode 100644 index 0000000000..dca3aa0b01 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Public/FIRLoggerLevel.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Note that importing GULLoggerLevel.h will lead to a non-modular header +// import error. + +/** + * The log levels used by internal logging. + */ +typedef NS_ENUM(NSInteger, FIRLoggerLevel) { + /** Error level, matches ASL_LEVEL_ERR. */ + FIRLoggerLevelError = 3, + /** Warning level, matches ASL_LEVEL_WARNING. */ + FIRLoggerLevelWarning = 4, + /** Notice level, matches ASL_LEVEL_NOTICE. */ + FIRLoggerLevelNotice = 5, + /** Info level, matches ASL_LEVEL_INFO. */ + FIRLoggerLevelInfo = 6, + /** Debug level, matches ASL_LEVEL_DEBUG. */ + FIRLoggerLevelDebug = 7, + /** Minimum log level. */ + FIRLoggerLevelMin = FIRLoggerLevelError, + /** Maximum log level. */ + FIRLoggerLevelMax = FIRLoggerLevelDebug +} NS_SWIFT_NAME(FirebaseLoggerLevel); diff --git a/Pods/FirebaseCore/Firebase/Core/Public/FIROptions.h b/Pods/FirebaseCore/Firebase/Core/Public/FIROptions.h new file mode 100644 index 0000000000..87a01ddc71 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Public/FIROptions.h @@ -0,0 +1,116 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * This class provides constant fields of Google APIs. + */ +NS_SWIFT_NAME(FirebaseOptions) +@interface FIROptions : NSObject + +/** + * Returns the default options. The first time this is called it synchronously reads + * GoogleService-Info.plist from disk. + */ ++ (nullable FIROptions *)defaultOptions NS_SWIFT_NAME(defaultOptions()); + +/** + * An iOS API key used for authenticating requests from your app, e.g. + * @"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk", used to identify your app to Google servers. + */ +@property(nonatomic, copy, nullable) NSString *APIKey NS_SWIFT_NAME(apiKey); + +/** + * The bundle ID for the application. Defaults to `[[NSBundle mainBundle] bundleID]` when not set + * manually or in a plist. + */ +@property(nonatomic, copy) NSString *bundleID; + +/** + * The OAuth2 client ID for iOS application used to authenticate Google users, for example + * @"12345.apps.googleusercontent.com", used for signing in with Google. + */ +@property(nonatomic, copy, nullable) NSString *clientID; + +/** + * The tracking ID for Google Analytics, e.g. @"UA-12345678-1", used to configure Google Analytics. + */ +@property(nonatomic, copy, nullable) NSString *trackingID; + +/** + * The Project Number from the Google Developer's console, for example @"012345678901", used to + * configure Google Cloud Messaging. + */ +@property(nonatomic, copy) NSString *GCMSenderID NS_SWIFT_NAME(gcmSenderID); + +/** + * The Project ID from the Firebase console, for example @"abc-xyz-123". + */ +@property(nonatomic, copy, nullable) NSString *projectID; + +/** + * The Android client ID used in Google AppInvite when an iOS app has its Android version, for + * example @"12345.apps.googleusercontent.com". + */ +@property(nonatomic, copy, nullable) NSString *androidClientID; + +/** + * The Google App ID that is used to uniquely identify an instance of an app. + */ +@property(nonatomic, copy) NSString *googleAppID; + +/** + * The database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". + */ +@property(nonatomic, copy, nullable) NSString *databaseURL; + +/** + * The URL scheme used to set up Durable Deep Link service. + */ +@property(nonatomic, copy, nullable) NSString *deepLinkURLScheme; + +/** + * The Google Cloud Storage bucket name, e.g. @"abc-xyz-123.storage.firebase.com". + */ +@property(nonatomic, copy, nullable) NSString *storageBucket; + +/** + * Initializes a customized instance of FIROptions from the file at the given plist file path. This + * will read the file synchronously from disk. + * For example, + * NSString *filePath = + * [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; + * FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath]; + * Returns nil if the plist file does not exist or is invalid. + */ +- (nullable instancetype)initWithContentsOfFile:(NSString *)plistPath; + +/** + * Initializes a customized instance of FIROptions with required fields. Use the mutable properties + * to modify fields for configuring specific services. + */ +// clang-format off +- (instancetype)initWithGoogleAppID:(NSString *)googleAppID + GCMSenderID:(NSString *)GCMSenderID + NS_SWIFT_NAME(init(googleAppID:gcmSenderID:)); +// clang-format on + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseCore/Firebase/Core/Public/FirebaseCore.h b/Pods/FirebaseCore/Firebase/Core/Public/FirebaseCore.h new file mode 100644 index 0000000000..fa26f694b7 --- /dev/null +++ b/Pods/FirebaseCore/Firebase/Core/Public/FirebaseCore.h @@ -0,0 +1,21 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAnalyticsConfiguration.h" +#import "FIRApp.h" +#import "FIRConfiguration.h" +#import "FIRLoggerLevel.h" +#import "FIROptions.h" diff --git a/Pods/FirebaseCore/LICENSE b/Pods/FirebaseCore/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/Pods/FirebaseCore/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Pods/FirebaseCore/README.md b/Pods/FirebaseCore/README.md new file mode 100644 index 0000000000..00e6ade973 --- /dev/null +++ b/Pods/FirebaseCore/README.md @@ -0,0 +1,185 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseInAppMessagingDisplay, FirebaseMessaging and +FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +Instructions for the experimental Carthage distribution are at +[Carthage](Carthage.md). + +### Rome + +Instructions for installing binary frameworks via +[Rome](https://github.com/CocoaPods/Rome) are at [Rome](Rome.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[the Auth Sample README](Example/Auth/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/Pods/FirebaseInstanceID/CHANGELOG.md b/Pods/FirebaseInstanceID/CHANGELOG.md new file mode 100755 index 0000000000..b81d158e79 --- /dev/null +++ b/Pods/FirebaseInstanceID/CHANGELOG.md @@ -0,0 +1,132 @@ +# 2018-10-25 -- v3.3.0 +- Fixed a crash caused by keychain operation when accessing default access group. (#1399, #1393) +- Remove internal APIs that are no longer used. + +# 2018-09-25 -- v3.2.2 +- Fixed a crash caused by NSUserDefaults being called on background thread. + +# 2018-08-14 -- v3.2.1 +- Fixed an issue that checkin is not cached properly when app first started. (#1561) + +# 2018-07-31 -- v3.2.0 +- Added support for global Firebase data collection flag. (#1219) +- Improved message tracking sent by server API. +- Fixed an issue that InstanceID doesn't compile in app extensions, allowing its +dependents like remote config to be working inside the app extensions. + +# 2018-06-19 -- v3.1.1 +- Ensure the checkin and tokens are refreshed if firebase project changed. +- Fixed an issue that checkin should be turned off when FCM's autoInitEnabled flag is off. + +# 2018-06-12 -- v3.1.0 +- Added a new API to fetch InstanceID and Token with a completion handler. The completion handler returns a FIRInstanceIDResult with a instanceID and a token properties. +- Deprecated the token method. +- Added support to log a new customized label provided by developer. + +# 2018-05-08 -- v3.0.0 +- Removed deprecated method `setAPNSToken:type` defined in FIRInstanceID, please use `setAPNSToken:type` defined in FIRMessaging instead. +- Removed deprecated enum `FIRInstanceIDAPNSTokenType` defined in FIRInstanceID, please use `FIRMessagingAPNSTokenType` defined in FIRMessaging instead. +- Fixed an issue that FCM scheduled messages were not tracked successfully. + +# 2018-03-06 -- v2.0.10 +- Improved documentation on InstanceID usage for GDPR. +- Improved the keypair handling during GCM to FCM migration. If you are migrating from GCM to FCM, we encourage you to update to this version and above. + +# 2018-02-06 -- v2.0.9 +- Improved support for language targeting for FCM service. Server updates happen more efficiently when language changes. +- Improved support for FCM token auto generation enable/disable functions. + +# 2017-12-11 -- v2.0.8 +- Fixed a crash caused by a reflection call during logging. +- Updating server with the latest parameters and deprecating old ones. + +# 2017-11-27 -- v2.0.7 +- Improve identity reset process, ensuring all information is reset during Identity deletion. + +# 2017-11-06 -- v2.0.6 +- Make token refresh weekly. +- Fixed a crash when performing token operation. + +# 2017-10-11 -- v2.0.5 +- Improved support for working in shared Keychain environments. + +# 2017-09-26 -- v2.0.4 +- Fixed an issue where the FCM token was not associating correctly with an APNs + device token, depending on when the APNs device token was made available. +- Fixed an issue where FCM tokens for different Sender IDs were not associating + correctly with an APNs device token. +- Fixed an issue that was preventing the FCM direct channel from being + established on the first start after 24 hours of being opened. + +# 2017-09-13 -- v2.0.3 +- Fixed a race condition where a token was not being generated on first start, + if Firebase Messaging was included and the app did not register for remote + notifications. + +# 2017-08-25 -- v2.0.2 +- Fixed a startup performance regression, removing a call which was blocking the + main thread. + +# 2017-08-07 -- v2.0.1 +- Fixed issues with token and app identifier being inaccessible when the device + is locked. +- Fixed a crash if bundle identifier is nil, which is possible in some testing + environments. +- Fixed a small memory leak fetching a new token. +- Moved to a new and simplified token storage system. +- Moved to a new queuing system for token fetches and deletes. +- Simplified logic and code around configuration and logging. +- Added clarification about the 'apns_sandbox' parameter, in header comments. + +# 2017-05-08 -- v2.0.0 +- Introduced an improved interface for Swift 3 developers +- Deprecated some methods and properties after moving their logic to the + Firebase Cloud Messaging SDK +- Fixed an intermittent stability issue when a debug build of an app was + replaced with a release build of the same version +- Removed swizzling logic that was sometimes resulting in developers receiving + a validation notice about enabling push notification capabilities, even though + they weren't using push notifications +- Fixed a notification that would sometimes fire twice in quick succession + during the first run of an app + +# 2017-03-31 -- v1.0.10 + +- Improvements to token-fetching logic +- Fixed some warnings in Instance ID +- Improved error messages if Instance ID couldn't be initialized properly +- Improvements to console logging + +# 2017-01-31 -- v1.0.9 + +- Removed an error being mistakenly logged to the console. + +# 2016-07-06 -- v1.0.8 + +- Don't store InstanceID plists in Documents folder. + +# 2016-06-19 -- v1.0.7 + +- Fix remote-notifications warning on app submission. + +# 2016-05-16 -- v1.0.6 + +- Fix CocoaPod linter issues for InstanceID pod. + +# 2016-05-13 -- v1.0.5 + +- Fix Authorization errors for InstanceID tokens. + +# 2016-05-11 -- v1.0.4 + +- Reduce wait for InstanceID token during parallel requests. + +# 2016-04-18 -- v1.0.3 + +- Change flag to disable swizzling to *FirebaseAppDelegateProxyEnabled*. +- Fix incessant Keychain errors while accessing InstanceID. +- Fix max retries for fetching IID token. + +# 2016-04-18 -- v1.0.2 + +- Register for remote notifications on iOS8+ in the SDK itself. diff --git a/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/FirebaseInstanceID b/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/FirebaseInstanceID new file mode 100755 index 0000000000..46aff495d0 Binary files /dev/null and b/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/FirebaseInstanceID differ diff --git a/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h b/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h new file mode 100755 index 0000000000..97777e1c32 --- /dev/null +++ b/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h @@ -0,0 +1,304 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +@class FIRInstanceIDResult; +/** + * @memberof FIRInstanceID + * + * The scope to be used when fetching/deleting a token for Firebase Messaging. + */ +FOUNDATION_EXPORT NSString *const kFIRInstanceIDScopeFirebaseMessaging + NS_SWIFT_NAME(InstanceIDScopeFirebaseMessaging); + +#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 +/** + * Called when the system determines that tokens need to be refreshed. + * This method is also called if Instance ID has been reset in which + * case, tokens and FCM topic subscriptions also need to be refreshed. + * + * Instance ID service will throttle the refresh event across all devices + * to control the rate of token updates on application servers. + */ +FOUNDATION_EXPORT const NSNotificationName kFIRInstanceIDTokenRefreshNotification + NS_SWIFT_NAME(InstanceIDTokenRefresh); +#else +/** + * Called when the system determines that tokens need to be refreshed. + * This method is also called if Instance ID has been reset in which + * case, tokens and FCM topic subscriptions also need to be refreshed. + * + * Instance ID service will throttle the refresh event across all devices + * to control the rate of token updates on application servers. + */ +FOUNDATION_EXPORT NSString *const kFIRInstanceIDTokenRefreshNotification + NS_SWIFT_NAME(InstanceIDTokenRefreshNotification); +#endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the InstanceID token returns. If + * the call fails we return the appropriate `error code` as described below. + * + * @param token The valid token as returned by InstanceID backend. + * + * @param error The error describing why generating a new token + * failed. See the error codes below for a more detailed + * description. + */ +typedef void (^FIRInstanceIDTokenHandler)(NSString *__nullable token, NSError *__nullable error) + NS_SWIFT_NAME(InstanceIDTokenHandler); + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the InstanceID `deleteToken` returns. If + * the call fails we return the appropriate `error code` as described below + * + * @param error The error describing why deleting the token failed. + * See the error codes below for a more detailed description. + */ +typedef void (^FIRInstanceIDDeleteTokenHandler)(NSError *error) + NS_SWIFT_NAME(InstanceIDDeleteTokenHandler); + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the app identity is created. If the + * identity wasn't created for some reason we return the appropriate error code. + * + * @param identity A valid identity for the app instance, nil if there was an error + * while creating an identity. + * @param error The error if fetching the identity fails else nil. + */ +typedef void (^FIRInstanceIDHandler)(NSString *__nullable identity, NSError *__nullable error) + NS_SWIFT_NAME(InstanceIDHandler); + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the app identity and all the tokens associated + * with it are deleted. Returns a valid error object in case of failure else nil. + * + * @param error The error if deleting the identity and all the tokens associated with + * it fails else nil. + */ +typedef void (^FIRInstanceIDDeleteHandler)(NSError *__nullable error) + NS_SWIFT_NAME(InstanceIDDeleteHandler); + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the app identity and token are fetched. If the + * identity wasn't created for some reason we return the appropriate error code. + * + * @param result The result containing an identity for the app instance and a valid token, + * nil if there was an error while creating the result. + * @param error The error if fetching the identity or token fails else nil. + */ +typedef void (^FIRInstanceIDResultHandler)(FIRInstanceIDResult *__nullable result, + NSError *__nullable error) + NS_SWIFT_NAME(InstanceIDResultHandler); + +/** + * Public errors produced by InstanceID. + */ +typedef NS_ENUM(NSUInteger, FIRInstanceIDError) { + // Http related errors. + + /// Unknown error. + FIRInstanceIDErrorUnknown = 0, + + /// Auth Error -- GCM couldn't validate request from this client. + FIRInstanceIDErrorAuthentication = 1, + + /// NoAccess -- InstanceID service cannot be accessed. + FIRInstanceIDErrorNoAccess = 2, + + /// Timeout -- Request to InstanceID backend timed out. + FIRInstanceIDErrorTimeout = 3, + + /// Network -- No network available to reach the servers. + FIRInstanceIDErrorNetwork = 4, + + /// OperationInProgress -- Another similar operation in progress, + /// bailing this one. + FIRInstanceIDErrorOperationInProgress = 5, + + /// InvalidRequest -- Some parameters of the request were invalid. + FIRInstanceIDErrorInvalidRequest = 7, +} NS_SWIFT_NAME(InstanceIDError); + +/** + * A class contains the results of InstanceID and token query. + */ +NS_SWIFT_NAME(InstanceIDResult) +@interface FIRInstanceIDResult : NSObject + +/** + * An instanceID uniquely identifies the app instance. + */ +@property(nonatomic, readonly, copy) NSString *instanceID; + +/* + * Returns a Firebase Messaging scoped token for the firebase app. + */ +@property(nonatomic, readonly, copy) NSString *token; + +@end + +/** + * Instance ID provides a unique identifier for each app instance and a mechanism + * to authenticate and authorize actions (for example, sending an FCM message). + * + * Once an InstanceID is generated, the library periodically sends information about the + * application and the device where it's running to the Firebase backend. To stop this. see + * `[FIRInstanceID deleteIDWithHandler:]`. + * + * Instance ID is long lived but, may be reset if the device is not used for + * a long time or the Instance ID service detects a problem. + * If Instance ID is reset, the app will be notified via + * `kFIRInstanceIDTokenRefreshNotification`. + * + * If the Instance ID has become invalid, the app can request a new one and + * send it to the app server. + * To prove ownership of Instance ID and to allow servers to access data or + * services associated with the app, call + * `[FIRInstanceID tokenWithAuthorizedEntity:scope:options:handler]`. + */ +NS_SWIFT_NAME(InstanceID) +@interface FIRInstanceID : NSObject + +/** + * FIRInstanceID. + * + * @return A shared instance of FIRInstanceID. + */ ++ (instancetype)instanceID NS_SWIFT_NAME(instanceID()); + +/** + * Unavailable. Use +instanceID instead. + */ +- (instancetype)init __attribute__((unavailable("Use +instanceID instead."))); + +#pragma mark - Tokens + +/** + * Returns a result of app instance identifier InstanceID and a Firebase Messaging scoped token. + * param handler The callback handler invoked when an app instanceID and a default token + * are generated and returned. If instanceID and token fetching fail for some + * reason the callback is invoked with nil `result` and the appropriate error. + */ +- (void)instanceIDWithHandler:(FIRInstanceIDResultHandler)handler; + +/** + * Returns a Firebase Messaging scoped token for the firebase app. + * + * @return Returns the stored token if the device has registered with Firebase Messaging, otherwise + * returns nil. + */ +- (nullable NSString *)token __deprecated_msg("Use instanceIDWithHandler: instead."); + +/** + * Returns a token that authorizes an Entity (example: cloud service) to perform + * an action on behalf of the application identified by Instance ID. + * + * This is similar to an OAuth2 token except, it applies to the + * application instance instead of a user. + * + * This is an asynchronous call. If the token fetching fails for some reason + * we invoke the completion callback with nil `token` and the appropriate + * error. + * + * This generates an Instance ID if it does not exist yet, which starts periodically sending + * information to the Firebase backend (see `[FIRInstanceID getIDWithHandler:]`). + * + * Note, you can only have one `token` or `deleteToken` call for a given + * authorizedEntity and scope at any point of time. Making another such call with the + * same authorizedEntity and scope before the last one finishes will result in an + * error with code `OperationInProgress`. + * + * @see FIRInstanceID deleteTokenWithAuthorizedEntity:scope:handler: + * + * @param authorizedEntity Entity authorized by the token. + * @param scope Action authorized for authorizedEntity. + * @param options The extra options to be sent with your token request. The + * value for the `apns_token` should be the NSData object + * passed to the UIApplicationDelegate's + * `didRegisterForRemoteNotificationsWithDeviceToken` method. + * The value for `apns_sandbox` should be a boolean (or an + * NSNumber representing a BOOL in Objective C) set to true if + * your app is a debug build, which means that the APNs + * device token is for the sandbox environment. It should be + * set to false otherwise. If the `apns_sandbox` key is not + * provided, an automatically-detected value shall be used. + * @param handler The callback handler which is invoked when the token is + * successfully fetched. In case of success a valid `token` and + * `nil` error are returned. In case of any error the `token` + * is nil and a valid `error` is returned. The valid error + * codes have been documented above. + */ +- (void)tokenWithAuthorizedEntity:(NSString *)authorizedEntity + scope:(NSString *)scope + options:(nullable NSDictionary *)options + handler:(FIRInstanceIDTokenHandler)handler; + +/** + * Revokes access to a scope (action) for an entity previously + * authorized by `[FIRInstanceID tokenWithAuthorizedEntity:scope:options:handler]`. + * + * This is an asynchronous call. Call this on the main thread since InstanceID lib + * is not thread safe. In case token deletion fails for some reason we invoke the + * `handler` callback passed in with the appropriate error code. + * + * Note, you can only have one `token` or `deleteToken` call for a given + * authorizedEntity and scope at a point of time. Making another such call with the + * same authorizedEntity and scope before the last one finishes will result in an error + * with code `OperationInProgress`. + * + * @param authorizedEntity Entity that must no longer have access. + * @param scope Action that entity is no longer authorized to perform. + * @param handler The handler that is invoked once the unsubscribe call ends. + * In case of error an appropriate error object is returned + * else error is nil. + */ +- (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity + scope:(NSString *)scope + handler:(FIRInstanceIDDeleteTokenHandler)handler; + +#pragma mark - Identity + +/** + * Asynchronously fetch a stable identifier that uniquely identifies the app + * instance. If the identifier has been revoked or has expired, this method will + * return a new identifier. + * + * Once an InstanceID is generated, the library periodically sends information about the + * application and the device where it's running to the Firebase backend. To stop this. see + * `[FIRInstanceID deleteIDWithHandler:]`. + * + * @param handler The handler to invoke once the identifier has been fetched. + * In case of error an appropriate error object is returned else + * a valid identifier is returned and a valid identifier for the + * application instance. + */ +- (void)getIDWithHandler:(FIRInstanceIDHandler)handler NS_SWIFT_NAME(getID(handler:)); + +/** + * Resets Instance ID and revokes all tokens. + * + * This method also triggers a request to fetch a new Instance ID and Firebase Messaging scope + * token. Please listen to kFIRInstanceIDTokenRefreshNotification when the new ID and token are + * ready. + * + * This stops the periodic sending of data to the Firebase backend that began when the Instance ID + * was generated. No more data is sent until another library calls Instance ID internally again + * (like FCM, RemoteConfig or Analytics) or user explicitly calls Instance ID APIs to get an + * Instance ID and token again. + */ +- (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler NS_SWIFT_NAME(deleteID(handler:)); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h b/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h new file mode 100755 index 0000000000..053ec2b1cf --- /dev/null +++ b/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h @@ -0,0 +1 @@ +#import "FIRInstanceID.h" diff --git a/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap b/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap new file mode 100755 index 0000000000..2058956c1f --- /dev/null +++ b/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap @@ -0,0 +1,6 @@ +framework module FirebaseInstanceID { + umbrella header "FirebaseInstanceID.h" + export * + module * { export *} + link framework "Security" + link framework "SystemConfiguration"} diff --git a/Pods/FirebaseInstanceID/README.md b/Pods/FirebaseInstanceID/README.md new file mode 100755 index 0000000000..25fe2196fb --- /dev/null +++ b/Pods/FirebaseInstanceID/README.md @@ -0,0 +1,10 @@ +# InstanceID SDK for iOS + +Instance ID provides a unique ID per instance of your apps and also provides a +mechanism to authenticate and authorize actions, like sending messages via +Firebase Cloud Messaging (FCM). + + +Please visit [our developer +site](https://developers.google.com/instance-id/) for integration instructions, +documentation, support information, and terms of service. diff --git a/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/GoogleAppMeasurement b/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/GoogleAppMeasurement new file mode 100755 index 0000000000..fddcac6685 Binary files /dev/null and b/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/GoogleAppMeasurement differ diff --git a/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/Modules/module.modulemap b/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/Modules/module.modulemap new file mode 100755 index 0000000000..ea1e687ddc --- /dev/null +++ b/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/Modules/module.modulemap @@ -0,0 +1,9 @@ +framework module GoogleAppMeasurement { + export * + module * { export *} + link "sqlite3" + link "z" + link framework "Security" + link framework "StoreKit" + link framework "SystemConfiguration" + link framework "UIKit"} diff --git a/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/GULAppDelegateSwizzler.m b/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/GULAppDelegateSwizzler.m new file mode 100644 index 0000000000..59f400dcc6 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/GULAppDelegateSwizzler.m @@ -0,0 +1,718 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "TargetConditionals.h" + +#if TARGET_OS_IOS + +#import +#import +#import +#import "../Common/GULLoggerCodes.h" +#import "Internal/GULAppDelegateSwizzler_Private.h" +#import "Private/GULAppDelegateSwizzler.h" + +#import +#import + +// Implementations need to be typed before calling the implementation directly to cast the +// arguments and the return types correctly. Otherwise, it will crash the app. +typedef BOOL (*GULRealOpenURLSourceApplicationAnnotationIMP)( + id, SEL, UIApplication *, NSURL *, NSString *, id); + +typedef BOOL (*GULRealOpenURLOptionsIMP)( + id, SEL, UIApplication *, NSURL *, NSDictionary *); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wstrict-prototypes" +typedef void (*GULRealHandleEventsForBackgroundURLSessionIMP)( + id, SEL, UIApplication *, NSString *, void (^)()); +#pragma clang diagnostic pop + +// This is needed to for the library to be warning free on iOS versions < 8. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +typedef BOOL (*GULRealContinueUserActivityIMP)( + id, SEL, UIApplication *, NSUserActivity *, void (^)(NSArray *restorableObjects)); +#pragma clang diagnostic pop + +typedef void (^GULAppDelegateInterceptorCallback)(id); + +// The strings below are the keys for associated objects. +static char const *const kGULContinueUserActivityIMPKey = "GUL_continueUserActivityIMP"; +static char const *const kGULHandleBackgroundSessionIMPKey = "GUL_handleBackgroundSessionIMP"; +static char const *const kGULOpenURLOptionsIMPKey = "GUL_openURLOptionsIMP"; +static char const *const kGULOpenURLOptionsSourceAnnotationsIMPKey = + "GUL_openURLSourceApplicationAnnotationIMP"; +static char const *const kGULRealClassKey = "GUL_realClass"; +static NSString *const kGULAppDelegateKeyPath = @"delegate"; + +static GULLoggerService kGULLoggerSwizzler = @"[GoogleUtilities/AppDelegateSwizzler]"; + +// Since Firebase SDKs also use this for app delegate proxying, in order to not be a breaking change +// we disable App Delegate proxying when either of these two flags are set to NO. + +/** Plist key that allows Firebase developers to disable App Delegate Proxying. */ +static NSString *const kGULFirebaseAppDelegateProxyEnabledPlistKey = + @"FirebaseAppDelegateProxyEnabled"; + +/** Plist key that allows developers not using Firebase to disable App Delegate Proxying. */ +static NSString *const kGULGoogleUtilitiesAppDelegateProxyEnabledPlistKey = + @"GoogleUtilitiesAppDelegateProxyEnabled"; + +/** The prefix of the App Delegate. */ +static NSString *const kGULAppDelegatePrefix = @"GUL_"; + +/** The original instance of App Delegate. */ +static id gOriginalAppDelegate; + +/** + * This class is necessary to store the delegates in an NSArray without retaining them. + * [NSValue valueWithNonRetainedObject] also provides this functionality, but does not provide a + * zeroing pointer. This will cause EXC_BAD_ACCESS when trying to access the object after it is + * dealloced. Instead, this container stores a weak, zeroing reference to the object, which + * automatically is set to nil by the runtime when the object is dealloced. + */ +@interface GULZeroingWeakContainer : NSObject + +/** Stores a weak object. */ +@property(nonatomic, weak) id object; + +@end + +@implementation GULZeroingWeakContainer +@end + +@interface GULAppDelegateObserver : NSObject +@end + +@implementation GULAppDelegateObserver { + BOOL _isObserving; +} + ++ (GULAppDelegateObserver *)sharedInstance { + static GULAppDelegateObserver *instance; + static dispatch_once_t once; + dispatch_once(&once, ^{ + instance = [[GULAppDelegateObserver alloc] init]; + }); + return instance; +} + +- (void)observeUIApplication { + if (_isObserving) { + return; + } + [[GULAppDelegateSwizzler sharedApplication] + addObserver:self + forKeyPath:kGULAppDelegateKeyPath + options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld + context:nil]; + _isObserving = YES; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(NSDictionary *)change + context:(void *)context { + if ([keyPath isEqual:kGULAppDelegateKeyPath]) { + id newValue = change[NSKeyValueChangeNewKey]; + id oldValue = change[NSKeyValueChangeOldKey]; + if ([newValue isEqual:oldValue]) { + return; + } + // Free the stored app delegate instance because it has been changed to a different instance to + // avoid keeping it alive forever. + if ([oldValue isEqual:gOriginalAppDelegate]) { + gOriginalAppDelegate = nil; + // Remove the observer. Parse it to NSObject to avoid warning. + [[GULAppDelegateSwizzler sharedApplication] removeObserver:self + forKeyPath:kGULAppDelegateKeyPath]; + _isObserving = NO; + } + } +} + +@end + +@implementation GULAppDelegateSwizzler + +static dispatch_once_t sProxyAppDelegateOnceToken; + +#pragma mark - Public methods + ++ (BOOL)isAppDelegateProxyEnabled { + NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary; + + id isFirebaseProxyEnabledPlistValue = infoDictionary[kGULFirebaseAppDelegateProxyEnabledPlistKey]; + id isGoogleProxyEnabledPlistValue = + infoDictionary[kGULGoogleUtilitiesAppDelegateProxyEnabledPlistKey]; + + // Enabled by default. + BOOL isFirebaseAppDelegateProxyEnabled = YES; + BOOL isGoogleUtilitiesAppDelegateProxyEnabled = YES; + + if ([isFirebaseProxyEnabledPlistValue isKindOfClass:[NSNumber class]]) { + isFirebaseAppDelegateProxyEnabled = [isFirebaseProxyEnabledPlistValue boolValue]; + } + + if ([isGoogleProxyEnabledPlistValue isKindOfClass:[NSNumber class]]) { + isGoogleUtilitiesAppDelegateProxyEnabled = [isGoogleProxyEnabledPlistValue boolValue]; + } + + // Only deactivate the proxy if it is explicitly disabled by app developers using either one of + // the plist flags. + return isFirebaseAppDelegateProxyEnabled && isGoogleUtilitiesAppDelegateProxyEnabled; +} + ++ (GULAppDelegateInterceptorID)registerAppDelegateInterceptor: + (id)interceptor { + NSAssert(interceptor, @"AppDelegateProxy cannot add nil interceptor"); + NSAssert([interceptor conformsToProtocol:@protocol(UIApplicationDelegate)], + @"AppDelegateProxy interceptor does not conform to UIApplicationDelegate"); + + if (!interceptor) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling000], + @"AppDelegateProxy cannot add nil interceptor."); + return nil; + } + if (![interceptor conformsToProtocol:@protocol(UIApplicationDelegate)]) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling001], + @"AppDelegateProxy interceptor does not conform to UIApplicationDelegate"); + return nil; + } + + // The ID should be the same given the same interceptor object. + NSString *interceptorID = [NSString stringWithFormat:@"%@%p", kGULAppDelegatePrefix, interceptor]; + if (!interceptorID.length) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling002], + @"AppDelegateProxy cannot create Interceptor ID."); + return nil; + } + GULZeroingWeakContainer *weakObject = [[GULZeroingWeakContainer alloc] init]; + weakObject.object = interceptor; + [GULAppDelegateSwizzler interceptors][interceptorID] = weakObject; + return interceptorID; +} + ++ (void)unregisterAppDelegateInterceptorWithID:(GULAppDelegateInterceptorID)interceptorID { + NSAssert(interceptorID, @"AppDelegateProxy cannot unregister nil interceptor ID."); + NSAssert(((NSString *)interceptorID).length != 0, + @"AppDelegateProxy cannot unregister empty interceptor ID."); + + if (!interceptorID) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling003], + @"AppDelegateProxy cannot unregister empty interceptor ID."); + return; + } + + GULZeroingWeakContainer *weakContainer = [GULAppDelegateSwizzler interceptors][interceptorID]; + if (!weakContainer.object) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling004], + @"AppDelegateProxy cannot unregister interceptor that was not registered. " + "Interceptor ID %@", + interceptorID); + return; + } + + [[GULAppDelegateSwizzler interceptors] removeObjectForKey:interceptorID]; +} + ++ (void)proxyOriginalDelegate { + dispatch_once(&sProxyAppDelegateOnceToken, ^{ + id originalDelegate = + [GULAppDelegateSwizzler sharedApplication].delegate; + [GULAppDelegateSwizzler proxyAppDelegate:originalDelegate]; + }); +} + +#pragma mark - Create proxy + ++ (UIApplication *)sharedApplication { + if ([GULAppEnvironmentUtil isAppExtension]) { + return nil; + } + id sharedApplication = nil; + Class uiApplicationClass = NSClassFromString(@"UIApplication"); + if (uiApplicationClass && + [uiApplicationClass respondsToSelector:(NSSelectorFromString(@"sharedApplication"))]) { + sharedApplication = [uiApplicationClass sharedApplication]; + } + return sharedApplication; +} + +#pragma mark - Override default methods + +/** Creates a new subclass of the class of the given object and sets the isa value of the given + * object to the new subclass. Additionally this copies methods to that new subclass that allow us + * to intercept UIApplicationDelegate methods. This is better known as isa swizzling. + * + * @param anObject The object to which you want to isa swizzle. This has to conform to the + * UIApplicationDelegate subclass. + */ ++ (void)createSubclassWithObject:(id)anObject { + Class realClass = [anObject class]; + + // Create GUL__ + NSString *classNameWithPrefix = + [kGULAppDelegatePrefix stringByAppendingString:NSStringFromClass(realClass)]; + NSTimeInterval timestamp = [NSDate date].timeIntervalSince1970; + NSString *newClassName = + [NSString stringWithFormat:@"%@-%0.0f", classNameWithPrefix, timestamp * 1000]; + + if (NSClassFromString(newClassName)) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling005], + @"Cannot create a proxy for App Delegate. Subclass already exists. Original Class: " + @"%@, subclass: %@", + NSStringFromClass(realClass), newClassName); + return; + } + + // Register the new class as subclass of the real one. Do not allocate more than the real class + // size. + Class appDelegateSubClass = objc_allocateClassPair(realClass, newClassName.UTF8String, 0); + if (appDelegateSubClass == Nil) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling006], + @"Cannot create a proxy for App Delegate. Subclass already exists. Original Class: " + @"%@, subclass: Nil", + NSStringFromClass(realClass)); + return; + } + + // Add the following methods from GULAppDelegate class, and store the real implementation so it + // can forward to the real one. + // For application:openURL:options: + NSValue *openURLOptionsIMPPointer; + SEL applicationOpenURLOptionsSEL = @selector(application:openURL:options:); + if ([anObject respondsToSelector:applicationOpenURLOptionsSEL]) { + // Only add the application:openURL:options: method if the original AppDelegate implements it. + // This fixes a bug if an app only implements application:openURL:sourceApplication:annotation: + // (if we add the `options` method, iOS sees that one exists and does not call the + // `sourceApplication` method, which in this case is the only one the app implements). + + [GULAppDelegateSwizzler addInstanceMethodWithSelector:applicationOpenURLOptionsSEL + fromClass:[GULAppDelegateSwizzler class] + toClass:appDelegateSubClass]; + GULRealOpenURLOptionsIMP openURLOptionsIMP = (GULRealOpenURLOptionsIMP) + [GULAppDelegateSwizzler implementationOfMethodSelector:applicationOpenURLOptionsSEL + fromClass:realClass]; + openURLOptionsIMPPointer = [NSValue valueWithPointer:openURLOptionsIMP]; + } + + // For application:continueUserActivity:restorationHandler: + SEL continueUserActivitySEL = @selector(application:continueUserActivity:restorationHandler:); + [GULAppDelegateSwizzler addInstanceMethodWithSelector:continueUserActivitySEL + fromClass:[GULAppDelegateSwizzler class] + toClass:appDelegateSubClass]; + GULRealContinueUserActivityIMP continueUserActivityIMP = (GULRealContinueUserActivityIMP) + [GULAppDelegateSwizzler implementationOfMethodSelector:continueUserActivitySEL + fromClass:realClass]; + NSValue *continueUserActivityIMPPointer = [NSValue valueWithPointer:continueUserActivityIMP]; + + // For application:openURL:sourceApplication:annotation: + SEL openURLSourceApplicationAnnotationSEL = + @selector(application:openURL:sourceApplication:annotation:); + [GULAppDelegateSwizzler addInstanceMethodWithSelector:openURLSourceApplicationAnnotationSEL + fromClass:[GULAppDelegateSwizzler class] + toClass:appDelegateSubClass]; + GULRealOpenURLSourceApplicationAnnotationIMP openURLSourceApplicationAnnotationIMP = + (GULRealOpenURLSourceApplicationAnnotationIMP)[GULAppDelegateSwizzler + implementationOfMethodSelector:openURLSourceApplicationAnnotationSEL + fromClass:realClass]; + NSValue *openURLSourceAppAnnotationIMPPointer = + [NSValue valueWithPointer:openURLSourceApplicationAnnotationIMP]; + + // For application:handleEventsForBackgroundURLSession:completionHandler: + SEL handleEventsForBackgroundURLSessionSEL = + @selector(application:handleEventsForBackgroundURLSession:completionHandler:); + [GULAppDelegateSwizzler addInstanceMethodWithSelector:handleEventsForBackgroundURLSessionSEL + fromClass:[GULAppDelegateSwizzler class] + toClass:appDelegateSubClass]; + GULRealHandleEventsForBackgroundURLSessionIMP handleBackgroundSessionIMP = + (GULRealHandleEventsForBackgroundURLSessionIMP)[GULAppDelegateSwizzler + implementationOfMethodSelector:handleEventsForBackgroundURLSessionSEL + fromClass:realClass]; + NSValue *handleBackgroundSessionIMPPointer = + [NSValue valueWithPointer:handleBackgroundSessionIMP]; + + // Override the description too so the custom class name will not show up. + [GULAppDelegateSwizzler addInstanceMethodWithDestinationSelector:@selector(description) + withImplementationFromSourceSelector:@selector(fakeDescription) + fromClass:[self class] + toClass:appDelegateSubClass]; + + // Create fake properties for the real app delegate object. + objc_setAssociatedObject(anObject, &kGULContinueUserActivityIMPKey, + continueUserActivityIMPPointer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(anObject, &kGULHandleBackgroundSessionIMPKey, + handleBackgroundSessionIMPPointer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + if (openURLOptionsIMPPointer) { + objc_setAssociatedObject(anObject, &kGULOpenURLOptionsIMPKey, openURLOptionsIMPPointer, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + objc_setAssociatedObject(anObject, &kGULOpenURLOptionsSourceAnnotationsIMPKey, + openURLSourceAppAnnotationIMPPointer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(anObject, &kGULRealClassKey, realClass, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + // The subclass size has to be exactly the same size with the original class size. The subclass + // cannot have more ivars/properties than its superclass since it will cause an offset in memory + // that can lead to overwriting the isa of an object in the next frame. + if (class_getInstanceSize(realClass) != class_getInstanceSize(appDelegateSubClass)) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling007], + @"Cannot create subclass of App Delegate, because the created subclass is not the " + @"same size. %@", + NSStringFromClass(realClass)); + NSAssert(NO, @"Classes must be the same size to swizzle isa"); + return; + } + + // Make the newly created class to be the subclass of the real App Delegate class. + objc_registerClassPair(appDelegateSubClass); + if (object_setClass(anObject, appDelegateSubClass)) { + GULLogDebug(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling008], + @"Successfully created App Delegate Proxy automatically. To disable the " + @"proxy, set the flag %@ to NO (Boolean) in the Info.plist", + [GULAppDelegateSwizzler correctAppDelegateProxyKey]); + } + + // We have to do this to invalidate the cache that caches the original respondsToSelector of + // openURL handlers. Without this, it won't call the default implementations because the system + // checks and caches them. + // Register KVO only once. Otherwise, the observing method will be called as many times as + // being registered. + id delegate = [GULAppDelegateSwizzler sharedApplication].delegate; + [GULAppDelegateSwizzler sharedApplication].delegate = nil; + [GULAppDelegateSwizzler sharedApplication].delegate = delegate; + gOriginalAppDelegate = delegate; + [[GULAppDelegateObserver sharedInstance] observeUIApplication]; +} + +#pragma mark - Helper methods + ++ (GULMutableDictionary *)interceptors { + static dispatch_once_t onceToken; + static GULMutableDictionary *sInterceptors; + dispatch_once(&onceToken, ^{ + sInterceptors = [[GULMutableDictionary alloc] init]; + }); + return sInterceptors; +} + +/** Copies a method identified by the methodSelector from one class to the other. After this method + * is called, performing [toClassInstance methodSelector] will be similar to calling + * [fromClassInstance methodSelector]. This method does nothing if toClass already has a method + * identified by methodSelector. + * + * @param methodSelector The SEL that identifies both the method on the fromClass as well as the + * one on the toClass. + * @param fromClass The class from which a method is sourced. + * @param toClass The class to which the method is added. If the class already has a method with + * the same selector, this has no effect. + */ ++ (void)addInstanceMethodWithSelector:(SEL)methodSelector + fromClass:(Class)fromClass + toClass:(Class)toClass { + [self addInstanceMethodWithDestinationSelector:methodSelector + withImplementationFromSourceSelector:methodSelector + fromClass:fromClass + toClass:toClass]; +} + +/** Copies a method identified by the sourceSelector from the fromClass as a method for the + * destinationSelector on the toClass. After this method is called, performing + * [toClassInstance destinationSelector] will be similar to calling + * [fromClassInstance sourceSelector]. This method does nothing if toClass already has a method + * identified by destinationSelector. + * + * @param destinationSelector The SEL that identifies the method on the toClass. + * @param sourceSelector The SEL that identifies the method on the fromClass. + * @param fromClass The class from which a method is sourced. + * @param toClass The class to which the method is added. If the class already has a method with + * the same selector, this has no effect. + */ ++ (void)addInstanceMethodWithDestinationSelector:(SEL)destinationSelector + withImplementationFromSourceSelector:(SEL)sourceSelector + fromClass:(Class)fromClass + toClass:(Class)toClass { + Method method = class_getInstanceMethod(fromClass, sourceSelector); + IMP methodIMP = method_getImplementation(method); + const char *types = method_getTypeEncoding(method); + if (!class_addMethod(toClass, destinationSelector, methodIMP, types)) { + GULLogWarning(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling009], + @"Cannot copy method to destination selector %@ as it already exists", + NSStringFromSelector(destinationSelector)); + } +} + +/** Gets the IMP of the instance method on the class identified by the selector. + * + * @param selector The selector of which the IMP is to be fetched. + * @param aClass The class from which the IMP is to be fetched. + * @return The IMP of the instance method identified by selector and aClass. + */ ++ (IMP)implementationOfMethodSelector:(SEL)selector fromClass:(Class)aClass { + Method aMethod = class_getInstanceMethod(aClass, selector); + return method_getImplementation(aMethod); +} + +/** Enumerates through all the interceptors and if they respond to a given selector, executes a + * GULAppDelegateInterceptorCallback with the interceptor. + * + * @param methodSelector The SEL to check if an interceptor responds to. + * @param callback the GULAppDelegateInterceptorCallback. + */ ++ (void)notifyInterceptorsWithMethodSelector:(SEL)methodSelector + callback:(GULAppDelegateInterceptorCallback)callback { + if (!callback) { + return; + } + + NSDictionary *interceptors = [GULAppDelegateSwizzler interceptors].dictionary; + [interceptors enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + GULZeroingWeakContainer *interceptorContainer = obj; + id interceptor = interceptorContainer.object; + if (!interceptor) { + GULLogWarning( + kGULLoggerSwizzler, NO, + [NSString + stringWithFormat:@"I-SWZ%06ld", (long)kGULSwizzlerMessageCodeAppDelegateSwizzling010], + @"AppDelegateProxy cannot find interceptor with ID %@. Removing the interceptor.", key); + [[GULAppDelegateSwizzler interceptors] removeObjectForKey:key]; + return; + } + if ([interceptor respondsToSelector:methodSelector]) { + callback(interceptor); + } + }]; +} + +// The methods below are donor methods which are added to the dynamic subclass of the App Delegate. +// They are called within the scope of the real App Delegate so |self| does not refer to the +// GULAppDelegateSwizzler instance but the real App Delegate instance. + +#pragma mark - [Donor Methods] Overridden instance description method + +- (NSString *)fakeDescription { + Class realClass = objc_getAssociatedObject(self, &kGULRealClassKey); + return [NSString stringWithFormat:@"<%@: %p>", realClass, self]; +} + +#pragma mark - [Donor Methods] URL overridden handler methods + +- (BOOL)application:(UIApplication *)application + openURL:(NSURL *)url + options:(NSDictionary *)options { + // Call the real implementation if the real App Delegate has any. + NSValue *openURLIMPPointer = objc_getAssociatedObject(self, &kGULOpenURLOptionsIMPKey); + GULRealOpenURLOptionsIMP openURLOptionsIMP = [openURLIMPPointer pointerValue]; + + __block BOOL returnedValue = NO; + SEL methodSelector = @selector(application:openURL:options:); + +// This is needed to for the library to be warning free on iOS versions < 9. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + [GULAppDelegateSwizzler + notifyInterceptorsWithMethodSelector:methodSelector + callback:^(id interceptor) { + returnedValue |= [interceptor application:application + openURL:url + options:options]; + }]; +#pragma clang diagnostic pop + if (openURLOptionsIMP) { + returnedValue |= openURLOptionsIMP(self, methodSelector, application, url, options); + } + return returnedValue; +} + +- (BOOL)application:(UIApplication *)application + openURL:(NSURL *)url + sourceApplication:(NSString *)sourceApplication + annotation:(id)annotation { + // Call the real implementation if the real App Delegate has any. + NSValue *openURLSourceAppAnnotationIMPPointer = + objc_getAssociatedObject(self, &kGULOpenURLOptionsSourceAnnotationsIMPKey); + GULRealOpenURLSourceApplicationAnnotationIMP openURLSourceApplicationAnnotationIMP = + [openURLSourceAppAnnotationIMPPointer pointerValue]; + + __block BOOL returnedValue = NO; + SEL methodSelector = @selector(application:openURL:sourceApplication:annotation:); + [GULAppDelegateSwizzler + notifyInterceptorsWithMethodSelector:methodSelector + callback:^(id interceptor) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + returnedValue |= [interceptor application:application + openURL:url + sourceApplication:sourceApplication + annotation:annotation]; +#pragma clang diagnostic pop + }]; + if (openURLSourceApplicationAnnotationIMP) { + returnedValue |= openURLSourceApplicationAnnotationIMP(self, methodSelector, application, url, + sourceApplication, annotation); + } + return returnedValue; +} + +#pragma mark - [Donor Methods] Network overridden handler methods + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wstrict-prototypes" +- (void)application:(UIApplication *)application + handleEventsForBackgroundURLSession:(NSString *)identifier + completionHandler:(void (^)())completionHandler API_AVAILABLE(ios(7.0)) { +#pragma clang diagnostic pop + NSValue *handleBackgroundSessionPointer = + objc_getAssociatedObject(self, &kGULHandleBackgroundSessionIMPKey); + GULRealHandleEventsForBackgroundURLSessionIMP handleBackgroundSessionIMP = + [handleBackgroundSessionPointer pointerValue]; + + // Notify interceptors. + SEL methodSelector = + @selector(application:handleEventsForBackgroundURLSession:completionHandler:); + [GULAppDelegateSwizzler + notifyInterceptorsWithMethodSelector:methodSelector + callback:^(id interceptor) { + [interceptor application:application + handleEventsForBackgroundURLSession:identifier + completionHandler:completionHandler]; + }]; + // Call the real implementation if the real App Delegate has any. + if (handleBackgroundSessionIMP) { + handleBackgroundSessionIMP(self, methodSelector, application, identifier, completionHandler); + } +} + +#pragma mark - [Donor Methods] User Activities overridden handler methods + +// This is needed to for the library to be warning free on iOS versions < 8. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (BOOL)application:(UIApplication *)application + continueUserActivity:(NSUserActivity *)userActivity + restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler { + NSValue *continueUserActivityIMPPointer = + objc_getAssociatedObject(self, &kGULContinueUserActivityIMPKey); + GULRealContinueUserActivityIMP continueUserActivityIMP = + continueUserActivityIMPPointer.pointerValue; + + __block BOOL returnedValue = NO; + SEL methodSelector = @selector(application:continueUserActivity:restorationHandler:); + [GULAppDelegateSwizzler + notifyInterceptorsWithMethodSelector:methodSelector + callback:^(id interceptor) { + returnedValue |= [interceptor application:application + continueUserActivity:userActivity + restorationHandler:restorationHandler]; + }]; + // Call the real implementation if the real App Delegate has any. + if (continueUserActivityIMP) { + returnedValue |= continueUserActivityIMP(self, methodSelector, application, userActivity, + restorationHandler); + } + return returnedValue; +} +#pragma clang diagnostic pop + ++ (void)proxyAppDelegate:(id)appDelegate { + id originalDelegate = appDelegate; + // Do not create a subclass if it is not enabled. + if (![GULAppDelegateSwizzler isAppDelegateProxyEnabled]) { + GULLogNotice(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling011], + @"App Delegate Proxy is disabled. %@", + [GULAppDelegateSwizzler correctAlternativeWhenAppDelegateProxyNotCreated]); + return; + } + // Do not accept nil delegate. + if (!originalDelegate) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling012], + @"Cannot create App Delegate Proxy because App Delegate instance is nil. %@", + [GULAppDelegateSwizzler correctAlternativeWhenAppDelegateProxyNotCreated]); + return; + } + + @try { + [self createSubclassWithObject:originalDelegate]; + } @catch (NSException *exception) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling013], + @"Cannot create App Delegate Proxy. %@", + [GULAppDelegateSwizzler correctAlternativeWhenAppDelegateProxyNotCreated]); + return; + } +} + +#pragma mark - Methods to print correct debug logs + ++ (NSString *)correctAppDelegateProxyKey { + return NSClassFromString(@"FIRCore") ? kGULFirebaseAppDelegateProxyEnabledPlistKey + : kGULGoogleUtilitiesAppDelegateProxyEnabledPlistKey; +} + ++ (NSString *)correctAlternativeWhenAppDelegateProxyNotCreated { + return NSClassFromString(@"FIRCore") + ? @"To log deep link campaigns manually, call the methods in " + @"FIRAnalytics+AppDelegate.h." + : @""; +} + +#pragma mark - Private Methods for Testing + +#ifdef GUL_APP_DELEGATE_TESTING + ++ (void)clearInterceptors { + [[self interceptors] removeAllObjects]; +} + ++ (void)resetProxyOriginalDelegateOnceToken { + sProxyAppDelegateOnceToken = 0; +} + ++ (id)originalDelegate { + return gOriginalAppDelegate; +} + +#endif // GUL_APP_DELEGATE_TESTING + +@end + +#endif // TARGET_OS_IOS diff --git a/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Internal/GULAppDelegateSwizzler_Private.h b/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Internal/GULAppDelegateSwizzler_Private.h new file mode 100644 index 0000000000..219b220cfd --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Internal/GULAppDelegateSwizzler_Private.h @@ -0,0 +1,64 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +@class UIApplication; + +NS_ASSUME_NONNULL_BEGIN + +@interface GULAppDelegateSwizzler () + +/** Returns the current sharedApplication. + * + * @return the current UIApplication if in an app, or nil if in extension or if it doesn't exist. + */ ++ (nullable UIApplication *)sharedApplication; + +/** ISA Swizzles the given appDelegate as the original app delegate would be. + * + * @param appDelegate The object that needs to be isa swizzled. This should conform to the + * UIApplicationDelegate protocol. + */ ++ (void)proxyAppDelegate:(id)appDelegate; + +/** Returns a dictionary containing interceptor IDs mapped to a GULZeroingWeakContainer. + * + * @return A dictionary of the form {NSString : GULZeroingWeakContainer}, where the NSString is + * the interceptorID. + */ ++ (GULMutableDictionary *)interceptors; + +#ifdef GUL_APP_DELEGATE_TESTING // Methods only used in tests. + +/** Deletes all the registered interceptors. */ ++ (void)clearInterceptors; + +/** Resets the token that prevents the app delegate proxy from being isa swizzled multiple times. */ ++ (void)resetProxyOriginalDelegateOnceToken; + +/** Returns the original app delegate that was proxied. + * + * @return The original app delegate instance that was proxied. + */ ++ (id)originalDelegate; + +#endif // GUL_APP_DELEGATE_TESTING + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Private/GULAppDelegateSwizzler.h b/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Private/GULAppDelegateSwizzler.h new file mode 100644 index 0000000000..31fc4b0ab0 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Private/GULAppDelegateSwizzler.h @@ -0,0 +1,63 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol UIApplicationDelegate; + +NS_ASSUME_NONNULL_BEGIN + +typedef NSString *const GULAppDelegateInterceptorID; + +/** This class contains methods that isa swizzle the app delegate. */ +@interface GULAppDelegateSwizzler : NSProxy + +/** Registers an app delegate interceptor whose methods will be invoked as they're invoked on the + * original app delegate. + * + * @param interceptor An instance of a class that conforms to the UIApplicationDelegate protocol. + * The interceptor is NOT retained. + * @return A unique GULAppDelegateInterceptorID if interceptor was successfully registered; nil + * if it fails. + */ ++ (nullable GULAppDelegateInterceptorID)registerAppDelegateInterceptor: + (id)interceptor; + +/** Unregisters an interceptor with the given ID if it exists. + * + * @param interceptorID The object that was generated when the interceptor was registered. + */ ++ (void)unregisterAppDelegateInterceptorWithID:(GULAppDelegateInterceptorID)interceptorID; + +/** This method ensures that the original app delegate has been proxied. Call this before + * registering your interceptor. This method is safe to call multiple times (but it only proxies + * the app delegate once). + */ ++ (void)proxyOriginalDelegate NS_EXTENSION_UNAVAILABLE( + "App delegate proxy doesn't support extensions."); + +/** Indicates whether app delegate proxy is explicitly disabled or enabled. Enabled by default. + * + * @return YES if AppDelegateProxy is Enabled, NO otherwise. + */ ++ (BOOL)isAppDelegateProxyEnabled; + +/** Do not initialize this class. */ +- (instancetype)init NS_UNAVAILABLE; + +NS_ASSUME_NONNULL_END + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Common/GULLoggerCodes.h b/Pods/GoogleUtilities/GoogleUtilities/Common/GULLoggerCodes.h new file mode 100644 index 0000000000..b71c03797c --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Common/GULLoggerCodes.h @@ -0,0 +1,36 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +typedef NS_ENUM(NSInteger, GULSwizzlerMessageCode) { + // App Delegate Swizzling. + kGULSwizzlerMessageCodeAppDelegateSwizzling000 = 1000, // I-SWZ001000 + kGULSwizzlerMessageCodeAppDelegateSwizzling001 = 1001, // I-SWZ001001 + kGULSwizzlerMessageCodeAppDelegateSwizzling002 = 1002, // I-SWZ001002 + kGULSwizzlerMessageCodeAppDelegateSwizzling003 = 1003, // I-SWZ001003 + kGULSwizzlerMessageCodeAppDelegateSwizzling004 = 1004, // I-SWZ001004 + kGULSwizzlerMessageCodeAppDelegateSwizzling005 = 1005, // I-SWZ001005 + kGULSwizzlerMessageCodeAppDelegateSwizzling006 = 1006, // I-SWZ001006 + kGULSwizzlerMessageCodeAppDelegateSwizzling007 = 1007, // I-SWZ001007 + kGULSwizzlerMessageCodeAppDelegateSwizzling008 = 1008, // I-SWZ001008 + kGULSwizzlerMessageCodeAppDelegateSwizzling009 = 1009, // I-SWZ001009 + kGULSwizzlerMessageCodeAppDelegateSwizzling010 = 1010, // I-SWZ001010 + kGULSwizzlerMessageCodeAppDelegateSwizzling011 = 1011, // I-SWZ001011 + kGULSwizzlerMessageCodeAppDelegateSwizzling012 = 1012, // I-SWZ001012 + kGULSwizzlerMessageCodeAppDelegateSwizzling013 = 1013, // I-SWZ001013 + + // Method Swizzling. + kGULSwizzlerMessageCodeMethodSwizzling000 = 2000, // I-SWZ002000 +}; diff --git a/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.h b/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.h new file mode 100644 index 0000000000..5b562719cb --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.h @@ -0,0 +1,43 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface GULAppEnvironmentUtil : NSObject + +/// Indicates whether the app is from Apple Store or not. Returns NO if the app is on simulator, +/// development environment or sideloaded. ++ (BOOL)isFromAppStore; + +/// Indicates whether the app is a Testflight app. Returns YES if the app has sandbox receipt. +/// Returns NO otherwise. ++ (BOOL)isAppStoreReceiptSandbox; + +/// Indicates whether the app is on simulator or not at runtime depending on the device +/// architecture. ++ (BOOL)isSimulator; + +/// The current device model. Returns an empty string if device model cannot be retrieved. ++ (NSString *)deviceModel; + +/// The current operating system version. Returns an empty string if the system version cannot be +/// retrieved. ++ (NSString *)systemVersion; + +/// Indicates whether it is running inside an extension or an app. ++ (BOOL)isAppExtension; + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.m b/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.m new file mode 100644 index 0000000000..1fa767b185 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.m @@ -0,0 +1,250 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "GULAppEnvironmentUtil.h" + +#import +#import +#import +#import + +#if TARGET_OS_IOS +#import +#endif + +/// The encryption info struct and constants are missing from the iPhoneSimulator SDK, but not from +/// the iPhoneOS or Mac OS X SDKs. Since one doesn't ever ship a Simulator binary, we'll just +/// provide the definitions here. +#if TARGET_OS_SIMULATOR && !defined(LC_ENCRYPTION_INFO) +#define LC_ENCRYPTION_INFO 0x21 +struct encryption_info_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t cryptoff; + uint32_t cryptsize; + uint32_t cryptid; +}; +#endif + +@implementation GULAppEnvironmentUtil + +/// A key for the Info.plist to enable or disable checking if the App Store is running in a sandbox. +/// This will affect your data integrity when using Firebase Analytics, as it will disable some +/// necessary checks. +static NSString *const kFIRAppStoreReceiptURLCheckEnabledKey = + @"FirebaseAppStoreReceiptURLCheckEnabled"; + +/// The file name of the sandbox receipt. This is available on iOS >= 8.0 +static NSString *const kFIRAIdentitySandboxReceiptFileName = @"sandboxReceipt"; + +/// The following copyright from Landon J. Fuller applies to the isAppEncrypted function. +/// +/// Copyright (c) 2017 Landon J. Fuller +/// 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. +/// +/// Comment from iPhone Dev Wiki +/// Crack Prevention: +/// App Store binaries are signed by both their developer and Apple. This encrypts the binary so +/// that decryption keys are needed in order to make the binary readable. When iOS executes the +/// binary, the decryption keys are used to decrypt the binary into a readable state where it is +/// then loaded into memory and executed. iOS can tell the encryption status of a binary via the +/// cryptid structure member of LC_ENCRYPTION_INFO MachO load command. If cryptid is a non-zero +/// value then the binary is encrypted. +/// +/// 'Cracking' works by letting the kernel decrypt the binary then siphoning the decrypted data into +/// a new binary file, resigning, and repackaging. This will only work on jailbroken devices as +/// codesignature validation has been removed. Resigning takes place because while the codesignature +/// doesn't have to be valid thanks to the jailbreak, it does have to be in place unless you have +/// AppSync or similar to disable codesignature checks. +/// +/// More information at Landon Fuller's blog +static BOOL IsAppEncrypted() { + const struct mach_header *executableHeader = NULL; + for (uint32_t i = 0; i < _dyld_image_count(); i++) { + const struct mach_header *header = _dyld_get_image_header(i); + if (header && header->filetype == MH_EXECUTE) { + executableHeader = header; + break; + } + } + + if (!executableHeader) { + return NO; + } + + BOOL is64bit = (executableHeader->magic == MH_MAGIC_64); + uintptr_t cursor = (uintptr_t)executableHeader + + (is64bit ? sizeof(struct mach_header_64) : sizeof(struct mach_header)); + const struct segment_command *segmentCommand = NULL; + uint32_t i = 0; + + while (i++ < executableHeader->ncmds) { + segmentCommand = (struct segment_command *)cursor; + + if (!segmentCommand) { + continue; + } + + if ((!is64bit && segmentCommand->cmd == LC_ENCRYPTION_INFO) || + (is64bit && segmentCommand->cmd == LC_ENCRYPTION_INFO_64)) { + if (is64bit) { + struct encryption_info_command_64 *cryptCmd = + (struct encryption_info_command_64 *)segmentCommand; + return cryptCmd && cryptCmd->cryptid != 0; + } else { + struct encryption_info_command *cryptCmd = (struct encryption_info_command *)segmentCommand; + return cryptCmd && cryptCmd->cryptid != 0; + } + } + cursor += segmentCommand->cmdsize; + } + + return NO; +} + +static BOOL HasSCInfoFolder() { +#if TARGET_OS_IOS || TARGET_OS_TV + NSString *bundlePath = [NSBundle mainBundle].bundlePath; + NSString *scInfoPath = [bundlePath stringByAppendingPathComponent:@"SC_Info"]; + return [[NSFileManager defaultManager] fileExistsAtPath:scInfoPath]; +#elif TARGET_OS_OSX + return NO; +#endif +} + +static BOOL HasEmbeddedMobileProvision() { +#if TARGET_OS_IOS || TARGET_OS_TV + return [[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"].length > 0; +#elif TARGET_OS_OSX + return NO; +#endif +} + ++ (BOOL)isFromAppStore { + static dispatch_once_t isEncryptedOnce; + static BOOL isEncrypted = NO; + + dispatch_once(&isEncryptedOnce, ^{ + isEncrypted = IsAppEncrypted(); + }); + + if ([GULAppEnvironmentUtil isSimulator]) { + return NO; + } + + // If an app contain the sandboxReceipt file, it means its coming from TestFlight + // This must be checked before the SCInfo Folder check below since TestFlight apps may + // also have an SCInfo folder. + if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox]) { + return NO; + } + + if (HasSCInfoFolder()) { + // When iTunes downloads a .ipa, it also gets a customized .sinf file which is added to the + // main SC_Info directory. + return YES; + } + + // For iOS >= 8.0, iTunesMetadata.plist is moved outside of the sandbox. Any attempt to read + // the iTunesMetadata.plist outside of the sandbox will be rejected by Apple. + // If the app does not contain the embedded.mobileprovision which is stripped out by Apple when + // the app is submitted to store, then it is highly likely that it is from Apple Store. + return isEncrypted && !HasEmbeddedMobileProvision(); +} + ++ (BOOL)isAppStoreReceiptSandbox { + // Since checking the App Store's receipt URL can be memory intensive, check the option in the + // Info.plist if developers opted out of this check. + id enableSandboxCheck = + [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRAppStoreReceiptURLCheckEnabledKey]; + if (enableSandboxCheck && [enableSandboxCheck isKindOfClass:[NSNumber class]] && + ![enableSandboxCheck boolValue]) { + return NO; + } +// The #else is for pre Xcode 9 where @available is not yet implemented. +#if __has_builtin(__builtin_available) + if (@available(iOS 7.0, *)) { +#else + if ([[UIDevice currentDevice].systemVersion integerValue] >= 7) { +#endif + NSURL *appStoreReceiptURL = [NSBundle mainBundle].appStoreReceiptURL; + NSString *appStoreReceiptFileName = appStoreReceiptURL.lastPathComponent; + return [appStoreReceiptFileName isEqualToString:kFIRAIdentitySandboxReceiptFileName]; + } + return NO; +} + ++ (BOOL)isSimulator { +#if TARGET_OS_IOS || TARGET_OS_TV + NSString *platform = [GULAppEnvironmentUtil deviceModel]; + return [platform isEqual:@"x86_64"] || [platform isEqual:@"i386"]; +#elif TARGET_OS_OSX + return NO; +#endif +} + ++ (NSString *)deviceModel { + static dispatch_once_t once; + static NSString *deviceModel; + + dispatch_once(&once, ^{ + struct utsname systemInfo; + if (uname(&systemInfo) == 0) { + deviceModel = [NSString stringWithUTF8String:systemInfo.machine]; + } + }); + return deviceModel; +} + ++ (NSString *)systemVersion { +#if TARGET_OS_IOS + return [UIDevice currentDevice].systemVersion; +#elif TARGET_OS_OSX || TARGET_OS_TV + // Assemble the systemVersion, excluding the patch version if it's 0. + NSOperatingSystemVersion osVersion = [NSProcessInfo processInfo].operatingSystemVersion; + NSMutableString *versionString = [[NSMutableString alloc] + initWithFormat:@"%ld.%ld", (long)osVersion.majorVersion, (long)osVersion.minorVersion]; + if (osVersion.patchVersion != 0) { + [versionString appendFormat:@".%ld", (long)osVersion.patchVersion]; + } + return versionString; +#endif +} + ++ (BOOL)isAppExtension { +#if TARGET_OS_IOS || TARGET_OS_TV + // Documented by Apple + BOOL appExtension = [[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"]; + return appExtension; +#elif TARGET_OS_OSX + return NO; +#endif +} + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Logger/GULLogger.m b/Pods/GoogleUtilities/GoogleUtilities/Logger/GULLogger.m new file mode 100644 index 0000000000..4feb77a537 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Logger/GULLogger.m @@ -0,0 +1,207 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULLogger.h" + +#include + +#import +#import "Public/GULLoggerLevel.h" + +/// ASL client facility name used by GULLogger. +const char *kGULLoggerASLClientFacilityName = "com.google.utilities.logger"; + +static dispatch_once_t sGULLoggerOnceToken; + +static aslclient sGULLoggerClient; + +static dispatch_queue_t sGULClientQueue; + +static BOOL sGULLoggerDebugMode; + +static GULLoggerLevel sGULLoggerMaximumLevel; + +// Allow clients to register a version to include in the log. +static const char *sVersion = ""; + +static GULLoggerService kGULLoggerLogger = @"[GULLogger]"; + +#ifdef DEBUG +/// The regex pattern for the message code. +static NSString *const kMessageCodePattern = @"^I-[A-Z]{3}[0-9]{6}$"; +static NSRegularExpression *sMessageCodeRegex; +#endif + +void GULLoggerInitializeASL(void) { + dispatch_once(&sGULLoggerOnceToken, ^{ + NSInteger majorOSVersion = [[GULAppEnvironmentUtil systemVersion] integerValue]; + uint32_t aslOptions = ASL_OPT_STDERR; +#if TARGET_OS_SIMULATOR + // The iOS 11 simulator doesn't need the ASL_OPT_STDERR flag. + if (majorOSVersion >= 11) { + aslOptions = 0; + } +#else + // Devices running iOS 10 or higher don't need the ASL_OPT_STDERR flag. + if (majorOSVersion >= 10) { + aslOptions = 0; + } +#endif // TARGET_OS_SIMULATOR + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // asl is deprecated + // Initialize the ASL client handle. + sGULLoggerClient = asl_open(NULL, kGULLoggerASLClientFacilityName, aslOptions); + sGULLoggerMaximumLevel = GULLoggerLevelNotice; + + // Set the filter used by system/device log. Initialize in default mode. + asl_set_filter(sGULLoggerClient, ASL_FILTER_MASK_UPTO(ASL_LEVEL_NOTICE)); + + sGULClientQueue = dispatch_queue_create("GULLoggingClientQueue", DISPATCH_QUEUE_SERIAL); + dispatch_set_target_queue(sGULClientQueue, + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)); +#ifdef DEBUG + sMessageCodeRegex = + [NSRegularExpression regularExpressionWithPattern:kMessageCodePattern options:0 error:NULL]; +#endif + }); +} + +void GULLoggerEnableSTDERR(void) { + asl_add_log_file(sGULLoggerClient, STDERR_FILENO); +} + +void GULLoggerForceDebug(void) { + // We should enable debug mode if we're not running from App Store. + if (![GULAppEnvironmentUtil isFromAppStore]) { + sGULLoggerDebugMode = YES; + GULSetLoggerLevel(GULLoggerLevelDebug); + } +} + +__attribute__((no_sanitize("thread"))) void GULSetLoggerLevel(GULLoggerLevel loggerLevel) { + if (loggerLevel < GULLoggerLevelMin || loggerLevel > GULLoggerLevelMax) { + GULLogError(kGULLoggerLogger, NO, @"I-COR000023", @"Invalid logger level, %ld", + (long)loggerLevel); + return; + } + GULLoggerInitializeASL(); + // We should not raise the logger level if we are running from App Store. + if (loggerLevel >= GULLoggerLevelNotice && [GULAppEnvironmentUtil isFromAppStore]) { + return; + } + + sGULLoggerMaximumLevel = loggerLevel; + dispatch_async(sGULClientQueue, ^{ + asl_set_filter(sGULLoggerClient, ASL_FILTER_MASK_UPTO(loggerLevel)); + }); +} + +/** + * Check if the level is high enough to be loggable. + */ +__attribute__((no_sanitize("thread"))) BOOL GULIsLoggableLevel(GULLoggerLevel loggerLevel) { + GULLoggerInitializeASL(); + if (sGULLoggerDebugMode) { + return YES; + } + return (BOOL)(loggerLevel <= sGULLoggerMaximumLevel); +} + +#ifdef DEBUG +void GULResetLogger() { + sGULLoggerOnceToken = 0; +} + +aslclient getGULLoggerClient() { + return sGULLoggerClient; +} + +dispatch_queue_t getGULClientQueue() { + return sGULClientQueue; +} + +BOOL getGULLoggerDebugMode() { + return sGULLoggerDebugMode; +} +#endif + +void GULLoggerRegisterVersion(const char *version) { + sVersion = version; +} + +void GULLogBasic(GULLoggerLevel level, + GULLoggerService service, + BOOL forceLog, + NSString *messageCode, + NSString *message, + va_list args_ptr) { + GULLoggerInitializeASL(); + if (!(level <= sGULLoggerMaximumLevel || sGULLoggerDebugMode || forceLog)) { + return; + } + +#ifdef DEBUG + NSCAssert(messageCode.length == 11, @"Incorrect message code length."); + NSRange messageCodeRange = NSMakeRange(0, messageCode.length); + NSUInteger numberOfMatches = + [sMessageCodeRegex numberOfMatchesInString:messageCode options:0 range:messageCodeRange]; + NSCAssert(numberOfMatches == 1, @"Incorrect message code format."); +#endif + NSString *logMsg = [[NSString alloc] initWithFormat:message arguments:args_ptr]; + logMsg = [NSString stringWithFormat:@"%s - %@[%@] %@", sVersion, service, messageCode, logMsg]; + dispatch_async(sGULClientQueue, ^{ + asl_log(sGULLoggerClient, NULL, level, "%s", logMsg.UTF8String); + }); +} +#pragma clang diagnostic pop + +/** + * Generates the logging functions using macros. + * + * Calling GULLogError(kGULLoggerCore, @"I-COR000001", @"Configure %@ failed.", @"blah") shows: + * yyyy-mm-dd hh:mm:ss.SSS sender[PID] [{service}][I-COR000001] Configure blah failed. + * Calling GULLogDebug(kGULLoggerCore, @"I-COR000001", @"Configure succeed.") shows: + * yyyy-mm-dd hh:mm:ss.SSS sender[PID] [{service}][I-COR000001] Configure succeed. + */ +#define GUL_LOGGING_FUNCTION(level) \ + void GULLog##level(GULLoggerService service, BOOL force, NSString *messageCode, \ + NSString *message, ...) { \ + va_list args_ptr; \ + va_start(args_ptr, message); \ + GULLogBasic(GULLoggerLevel##level, service, force, messageCode, message, args_ptr); \ + va_end(args_ptr); \ + } + +GUL_LOGGING_FUNCTION(Error) +GUL_LOGGING_FUNCTION(Warning) +GUL_LOGGING_FUNCTION(Notice) +GUL_LOGGING_FUNCTION(Info) +GUL_LOGGING_FUNCTION(Debug) + +#undef GUL_MAKE_LOGGER + +#pragma mark - GULLoggerWrapper + +@implementation GULLoggerWrapper + ++ (void)logWithLevel:(GULLoggerLevel)level + withService:(GULLoggerService)service + withCode:(NSString *)messageCode + withMessage:(NSString *)message + withArgs:(va_list)args { + GULLogBasic(level, service, NO, messageCode, message, args); +} + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Logger/Private/GULLogger.h b/Pods/GoogleUtilities/GoogleUtilities/Logger/Private/GULLogger.h new file mode 100644 index 0000000000..ff42576868 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Logger/Private/GULLogger.h @@ -0,0 +1,159 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * The services used in the logger. + */ +typedef NSString *const GULLoggerService; + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Initialize GULLogger. + */ +extern void GULLoggerInitializeASL(void); + +/** + * Override log level to Debug. + */ +void GULLoggerForceDebug(void); + +/** + * Turn on logging to STDERR. + */ +extern void GULLoggerEnableSTDERR(void); + +/** + * Changes the default logging level of GULLoggerLevelNotice to a user-specified level. + * The default level cannot be set above GULLoggerLevelNotice if the app is running from App Store. + * (required) log level (one of the GULLoggerLevel enum values). + */ +extern void GULSetLoggerLevel(GULLoggerLevel loggerLevel); + +/** + * Checks if the specified logger level is loggable given the current settings. + * (required) log level (one of the GULLoggerLevel enum values). + */ +extern BOOL GULIsLoggableLevel(GULLoggerLevel loggerLevel); + +/** + * Register version to include in logs. + * (required) version + */ +extern void GULLoggerRegisterVersion(const char *version); + +/** + * Logs a message to the Xcode console and the device log. If running from AppStore, will + * not log any messages with a level higher than GULLoggerLevelNotice to avoid log spamming. + * (required) log level (one of the GULLoggerLevel enum values). + * (required) service name of type GULLoggerService. + * (required) message code starting with "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * (required) message string which can be a format string. + * (optional) variable arguments list obtained from calling va_start, used when message is a format + * string. + */ +extern void GULLogBasic(GULLoggerLevel level, + GULLoggerService service, + BOOL forceLog, + NSString *messageCode, + NSString *message, +// On 64-bit simulators, va_list is not a pointer, so cannot be marked nullable +// See: http://stackoverflow.com/q/29095469 +#if __LP64__ && TARGET_OS_SIMULATOR || TARGET_OS_OSX + va_list args_ptr +#else + va_list _Nullable args_ptr +#endif +); + +/** + * The following functions accept the following parameters in order: + * (required) service name of type GULLoggerService. + * (required) message code starting from "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * See go/firebase-log-proposal for details. + * (required) message string which can be a format string. + * (optional) the list of arguments to substitute into the format string. + * Example usage: + * GULLogError(kGULLoggerCore, @"I-COR000001", @"Configuration of %@ failed.", app.name); + */ +extern void GULLogError(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); +extern void GULLogWarning(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); +extern void GULLogNotice(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); +extern void GULLogInfo(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); +extern void GULLogDebug(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +@interface GULLoggerWrapper : NSObject + +/** + * Objective-C wrapper for GULLogBasic to allow weak linking to GULLogger + * (required) log level (one of the GULLoggerLevel enum values). + * (required) service name of type GULLoggerService. + * (required) message code starting with "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * (required) message string which can be a format string. + * (optional) variable arguments list obtained from calling va_start, used when message is a format + * string. + */ + ++ (void)logWithLevel:(GULLoggerLevel)level + withService:(GULLoggerService)service + withCode:(NSString *)messageCode + withMessage:(NSString *)message + withArgs:(va_list)args; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/GoogleUtilities/GoogleUtilities/Logger/Public/GULLoggerLevel.h b/Pods/GoogleUtilities/GoogleUtilities/Logger/Public/GULLoggerLevel.h new file mode 100644 index 0000000000..81ff212d71 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Logger/Public/GULLoggerLevel.h @@ -0,0 +1,35 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The log levels used by internal logging. + */ +typedef NS_ENUM(NSInteger, GULLoggerLevel) { + /** Error level, matches ASL_LEVEL_ERR. */ + GULLoggerLevelError = 3, + /** Warning level, matches ASL_LEVEL_WARNING. */ + GULLoggerLevelWarning = 4, + /** Notice level, matches ASL_LEVEL_NOTICE. */ + GULLoggerLevelNotice = 5, + /** Info level, matches ASL_LEVEL_INFO. */ + GULLoggerLevelInfo = 6, + /** Debug level, matches ASL_LEVEL_DEBUG. */ + GULLoggerLevelDebug = 7, + /** Minimum log level. */ + GULLoggerLevelMin = GULLoggerLevelError, + /** Maximum log level. */ + GULLoggerLevelMax = GULLoggerLevelDebug +} NS_SWIFT_NAME(GoogleLoggerLevel); diff --git a/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/GULSwizzler.m b/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/GULSwizzler.m new file mode 100644 index 0000000000..9839124dd3 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/GULSwizzler.m @@ -0,0 +1,185 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULSwizzler.h" + +#import + +#import +#import "../Common/GULLoggerCodes.h" + +#ifdef GUL_UNSWIZZLING_ENABLED +#import +// We need a private method for an assert. +#import +#endif + +static GULLoggerService kGULLoggerSwizzler = @"[GoogleUtilites/MethodSwizzler]"; + +dispatch_queue_t GetGULSwizzlingQueue() { + static dispatch_queue_t queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + queue = dispatch_queue_create("com.google.GULSwizzler", DISPATCH_QUEUE_SERIAL); + }); + return queue; +} + +@implementation GULSwizzler + ++ (void)swizzleClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector + withBlock:(nullable id)block { + dispatch_sync(GetGULSwizzlingQueue(), ^{ + NSAssert(selector, @"The selector cannot be NULL"); + NSAssert(aClass, @"The class cannot be Nil"); + Class resolvedClass = aClass; + Method method = nil; + if (isClassSelector) { + method = class_getClassMethod(aClass, selector); + resolvedClass = object_getClass(aClass); + } else { + method = class_getInstanceMethod(aClass, selector); + } + NSAssert(method, @"You're attempting to swizzle a method that doesn't exist. (%@, %@)", + NSStringFromClass(resolvedClass), NSStringFromSelector(selector)); + IMP newImp = imp_implementationWithBlock(block); + +#ifdef GUL_UNSWIZZLING_ENABLED + IMP currentImp = class_getMethodImplementation(resolvedClass, selector); + [[GULSwizzlingCache sharedInstance] cacheCurrentIMP:currentImp + forNewIMP:newImp + forClass:resolvedClass + withSelector:selector]; +#endif + + const char *typeEncoding = method_getTypeEncoding(method); + __unused IMP originalImpOfClass = + class_replaceMethod(resolvedClass, selector, newImp, typeEncoding); + +#ifdef GUL_UNSWIZZLING_ENABLED + // If !originalImpOfClass, then the IMP came from a superclass. + if (originalImpOfClass) { + if (originalImpOfClass != + [[GULSwizzlingCache sharedInstance] originalIMPOfCurrentIMP:currentImp]) { + GULLogWarning(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeMethodSwizzling000], + @"Swizzling class: %@ SEL:%@ after it has been previously been swizzled.", + NSStringFromClass(resolvedClass), NSStringFromSelector(selector)); + } + } +#endif + }); +} + ++ (void)unswizzleClass:(Class)aClass selector:(SEL)selector isClassSelector:(BOOL)isClassSelector { +#ifdef GUL_UNSWIZZLING_ENABLED + dispatch_sync(GetGULSwizzlingQueue(), ^{ + NSAssert(aClass != nil && selector != nil, @"You cannot unswizzle a nil class or selector."); + Method method = nil; + Class resolvedClass = aClass; + if (isClassSelector) { + resolvedClass = object_getClass(aClass); + method = class_getClassMethod(aClass, selector); + } else { + method = class_getInstanceMethod(aClass, selector); + } + NSAssert(method, @"Couldn't find the method you're unswizzling in the runtime."); + IMP originalImp = + [[GULSwizzlingCache sharedInstance] cachedIMPForClass:resolvedClass withSelector:selector]; + NSAssert(originalImp, @"This class/selector combination hasn't been swizzled"); + IMP currentImp = method_setImplementation(method, originalImp); + BOOL didRemoveBlock = imp_removeBlock(currentImp); + NSAssert(didRemoveBlock, @"Wasn't able to remove the block of a swizzled IMP."); + [[GULSwizzlingCache sharedInstance] clearCacheForSwizzledIMP:currentImp + selector:selector + aClass:resolvedClass]; + }); +#else + NSAssert(NO, @"Unswizzling is disabled."); +#endif +} + ++ (nullable IMP)originalImplementationForClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector { +#ifdef GUL_UNSWIZZLING_ENABLED + __block IMP originalImp = nil; + dispatch_sync(GetGULSwizzlingQueue(), ^{ + Class resolvedClass = isClassSelector ? object_getClass(aClass) : aClass; + originalImp = + [[GULSwizzlingCache sharedInstance] cachedIMPForClass:resolvedClass withSelector:selector]; + NSAssert(originalImp, @"The IMP for this class/selector combo doesn't exist (%@, %@).", + NSStringFromClass(resolvedClass), NSStringFromSelector(selector)); + }); + return originalImp; +#else + NSAssert(NO, @"Unswizzling is disabled and the original IMP is not cached."); + return nil; +#endif +} + ++ (nullable IMP)currentImplementationForClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector { + NSAssert(selector, @"The selector cannot be NULL"); + NSAssert(aClass, @"The class cannot be Nil"); + if (selector == NULL || aClass == nil) { + return nil; + } + __block IMP currentIMP = nil; + dispatch_sync(GetGULSwizzlingQueue(), ^{ + Method method = nil; + if (isClassSelector) { + method = class_getClassMethod(aClass, selector); + } else { + method = class_getInstanceMethod(aClass, selector); + } + NSAssert(method, @"The Method for this class/selector combo doesn't exist (%@, %@).", + NSStringFromClass(aClass), NSStringFromSelector(selector)); + if (method == nil) { + return; + } + currentIMP = method_getImplementation(method); + NSAssert(currentIMP, @"The IMP for this class/selector combo doesn't exist (%@, %@).", + NSStringFromClass(aClass), NSStringFromSelector(selector)); + }); + return currentIMP; +} + ++ (BOOL)selector:(SEL)selector existsInClass:(Class)aClass isClassSelector:(BOOL)isClassSelector { + Method method = isClassSelector ? class_getClassMethod(aClass, selector) + : class_getInstanceMethod(aClass, selector); + return method != nil; +} + ++ (NSArray *)ivarObjectsForObject:(id)object { + NSMutableArray *array = [NSMutableArray array]; + unsigned int count; + Ivar *vars = class_copyIvarList([object class], &count); + for (NSUInteger i = 0; i < count; i++) { + const char *typeEncoding = ivar_getTypeEncoding(vars[i]); + // Check to see if the ivar is an object. + if (strncmp(typeEncoding, "@", 1) == 0) { + id ivarObject = object_getIvar(object, vars[i]); + [array addObject:ivarObject]; + } + } + free(vars); + return array; +} + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULOriginalIMPConvenienceMacros.h b/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULOriginalIMPConvenienceMacros.h new file mode 100644 index 0000000000..a33262af09 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULOriginalIMPConvenienceMacros.h @@ -0,0 +1,207 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * GULOriginalIMPConvenienceMacros.h + * + * This header contains convenience macros for invoking the original IMP of a swizzled method. + */ + +/** + * Invokes original IMP when the original selector takes no arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + */ +#define GUL_INVOKE_ORIGINAL_IMP0(__receivingObject, __swizzledSEL, __returnType, __originalIMP) \ + ((__returnType(*)(id, SEL))__originalIMP)(__receivingObject, __swizzledSEL) + +/** + * Invokes original IMP when the original selector takes 1 argument. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP1(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1)))__originalIMP)(__receivingObject, __swizzledSEL, \ + __arg1) + +/** + * Invokes original IMP when the original selector takes 2 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP2(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2) + +/** + * Invokes original IMP when the original selector takes 3 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP3(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), \ + __typeof__(__arg3)))__originalIMP)(__receivingObject, __swizzledSEL, __arg1, \ + __arg2, __arg3) + +/** + * Invokes original IMP when the original selector takes 4 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP4(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4)))__originalIMP)(__receivingObject, __swizzledSEL, __arg1, \ + __arg2, __arg3, __arg4) + +/** + * Invokes original IMP when the original selector takes 5 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP5(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5) + +/** + * Invokes original IMP when the original selector takes 6 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + * @param __arg6 The sixth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP6(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5, __arg6) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5), __typeof__(__arg6)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6) + +/** + * Invokes original IMP when the original selector takes 7 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + * @param __arg6 The sixth argument. + * @param __arg7 The seventh argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP7(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5), __typeof__(__arg6), \ + __typeof__(__arg7)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7) + +/** + * Invokes original IMP when the original selector takes 8 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + * @param __arg6 The sixth argument. + * @param __arg7 The seventh argument. + * @param __arg8 The eighth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP8(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, __arg8) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5), __typeof__(__arg6), \ + __typeof__(__arg7), __typeof__(__arg8)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, \ + __arg8) + +/** + * Invokes original IMP when the original selector takes 9 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + * @param __arg6 The sixth argument. + * @param __arg7 The seventh argument. + * @param __arg8 The eighth argument. + * @param __arg9 The ninth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP9(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, __arg8, \ + __arg9) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5), __typeof__(__arg6), \ + __typeof__(__arg7), __typeof__(__arg8), __typeof__(__arg9)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, \ + __arg8, __arg9) diff --git a/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULSwizzler.h b/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULSwizzler.h new file mode 100644 index 0000000000..ab008cab92 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULSwizzler.h @@ -0,0 +1,91 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** This class handles the runtime manipulation necessary to instrument selectors. It stores the + * classes and selectors that have been swizzled, and runs all operations on its own queue. + */ +@interface GULSwizzler : NSObject + +/** Manipulates the Objective-C runtime to replace the original IMP with the supplied block. + * + * @param aClass The class to swizzle. + * @param selector The selector of the class to swizzle. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + * @param block The block that replaces the original IMP. + */ ++ (void)swizzleClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector + withBlock:(nullable id)block; + +/** Restores the original implementation. + * + * @param aClass The class to unswizzle. + * @param selector The selector to restore the original implementation of. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + */ ++ (void)unswizzleClass:(Class)aClass selector:(SEL)selector isClassSelector:(BOOL)isClassSelector; + +/** Returns the current IMP for the given class and selector. + * + * @param aClass The class to use. + * @param selector The selector to find the implementation of. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + * @return The implementation of the selector in the runtime. + */ ++ (nullable IMP)currentImplementationForClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector; + +/** Returns the original IMP for the given class and selector. + * + * @param aClass The class to use. + * @param selector The selector to find the implementation of. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + * @return The implementation of the selector in the runtime before any consumer or GULSwizzler + * swizzled. + */ ++ (nullable IMP)originalImplementationForClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector; + +/** Checks the runtime to see if a selector exists on a class. If a property is declared as + * @dynamic, we have a reverse swizzling situation, where the implementation of a method exists + * only in concrete subclasses, and NOT in the superclass. We can detect that situation using + * this helper method. Similarly, we can detect situations where a class doesn't implement a + * protocol method. + * + * @param selector The selector to check for. + * @param aClass The class to check. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + * @return YES if the method was found in this selector/class combination, NO otherwise. + */ ++ (BOOL)selector:(SEL)selector existsInClass:(Class)aClass isClassSelector:(BOOL)isClassSelector; + +/** Returns a list of all Objective-C (and not primitive) ivars contained by the given object. + * + * @param object The object whose ivars will be iterated. + * @return The list of ivar objects. + */ ++ (NSArray *)ivarObjectsForObject:(id)object; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.h b/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.h new file mode 100644 index 0000000000..36f94a7098 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.h @@ -0,0 +1,49 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +/// This is a copy of Google Toolbox for Mac library to avoid creating an extra framework. + +// NOTE: For 64bit, none of these apis handle input sizes >32bits, they will return nil when given +// such data. To handle data of that size you really should be streaming it rather then doing it all +// in memory. + +@interface NSData (GULGzip) + +/// Returns an data as the result of decompressing the payload of |data|.The data to decompress must +/// be a gzipped payloads. ++ (NSData *)gul_dataByInflatingGzippedData:(NSData *)data error:(NSError **)error; + +/// Returns an compressed data with the result of gzipping the payload of |data|. Uses the default +/// compression level. ++ (NSData *)gul_dataByGzippingData:(NSData *)data error:(NSError **)error; + +FOUNDATION_EXPORT NSString *const GULNSDataZlibErrorDomain; +FOUNDATION_EXPORT NSString *const GULNSDataZlibErrorKey; // NSNumber +FOUNDATION_EXPORT NSString *const GULNSDataZlibRemainingBytesKey; // NSNumber + +typedef NS_ENUM(NSInteger, GULNSDataZlibError) { + GULNSDataZlibErrorGreaterThan32BitsToCompress = 1024, + // An internal zlib error. + // GULNSDataZlibErrorKey will contain the error value. + // NSLocalizedDescriptionKey may contain an error string from zlib. + // Look in zlib.h for list of errors. + GULNSDataZlibErrorInternal, + // There was left over data in the buffer that was not used. + // GULNSDataZlibRemainingBytesKey will contain number of remaining bytes. + GULNSDataZlibErrorDataRemaining +}; + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.m b/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.m new file mode 100644 index 0000000000..cd3394a41d --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.m @@ -0,0 +1,207 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "GULNSData+zlib.h" + +#import + +#define kChunkSize 1024 +#define Z_DEFAULT_COMPRESSION (-1) + +NSString *const GULNSDataZlibErrorDomain = @"com.google.GULNSDataZlibErrorDomain"; +NSString *const GULNSDataZlibErrorKey = @"GULNSDataZlibErrorKey"; +NSString *const GULNSDataZlibRemainingBytesKey = @"GULNSDataZlibRemainingBytesKey"; + +@implementation NSData (GULGzip) + ++ (NSData *)gul_dataByInflatingGzippedData:(NSData *)data error:(NSError **)error { + const void *bytes = [data bytes]; + NSUInteger length = [data length]; + if (!bytes || !length) { + return nil; + } + +#if defined(__LP64__) && __LP64__ + // Don't support > 32bit length for 64 bit, see note in header. + if (length > UINT_MAX) { + return nil; + } +#endif + + z_stream strm; + bzero(&strm, sizeof(z_stream)); + + // Setup the input. + strm.avail_in = (unsigned int)length; + strm.next_in = (unsigned char *)bytes; + + int windowBits = 15; // 15 to enable any window size + windowBits += 32; // and +32 to enable zlib or gzip header detection. + + int retCode; + if ((retCode = inflateInit2(&strm, windowBits)) != Z_OK) { + if (error) { + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] + forKey:GULNSDataZlibErrorKey]; + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorInternal + userInfo:userInfo]; + } + return nil; + } + + // Hint the size at 4x the input size. + NSMutableData *result = [NSMutableData dataWithCapacity:(length * 4)]; + unsigned char output[kChunkSize]; + + // Loop to collect the data. + do { + // Update what we're passing in. + strm.avail_out = kChunkSize; + strm.next_out = output; + retCode = inflate(&strm, Z_NO_FLUSH); + if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) { + if (error) { + NSMutableDictionary *userInfo = + [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] + forKey:GULNSDataZlibErrorKey]; + if (strm.msg) { + NSString *message = [NSString stringWithUTF8String:strm.msg]; + if (message) { + [userInfo setObject:message forKey:NSLocalizedDescriptionKey]; + } + } + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorInternal + userInfo:userInfo]; + } + inflateEnd(&strm); + return nil; + } + // Collect what we got. + unsigned gotBack = kChunkSize - strm.avail_out; + if (gotBack > 0) { + [result appendBytes:output length:gotBack]; + } + + } while (retCode == Z_OK); + + // Make sure there wasn't more data tacked onto the end of a valid compressed stream. + if (strm.avail_in != 0) { + if (error) { + NSDictionary *userInfo = + [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedInt:strm.avail_in] + forKey:GULNSDataZlibRemainingBytesKey]; + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorDataRemaining + userInfo:userInfo]; + } + result = nil; + } + // The only way out of the loop was by hitting the end of the stream. + NSAssert(retCode == Z_STREAM_END, + @"Thought we finished inflate w/o getting a result of stream end, code %d", retCode); + + // Clean up. + inflateEnd(&strm); + + return result; +} + ++ (NSData *)gul_dataByGzippingData:(NSData *)data error:(NSError **)error { + const void *bytes = [data bytes]; + NSUInteger length = [data length]; + + int level = Z_DEFAULT_COMPRESSION; + if (!bytes || !length) { + return nil; + } + +#if defined(__LP64__) && __LP64__ + // Don't support > 32bit length for 64 bit, see note in header. + if (length > UINT_MAX) { + if (error) { + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorGreaterThan32BitsToCompress + userInfo:nil]; + } + return nil; + } +#endif + + z_stream strm; + bzero(&strm, sizeof(z_stream)); + + int memLevel = 8; // Default. + int windowBits = 15 + 16; // Enable gzip header instead of zlib header. + + int retCode; + if ((retCode = deflateInit2(&strm, level, Z_DEFLATED, windowBits, memLevel, + Z_DEFAULT_STRATEGY)) != Z_OK) { + if (error) { + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] + forKey:GULNSDataZlibErrorKey]; + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorInternal + userInfo:userInfo]; + } + return nil; + } + + // Hint the size at 1/4 the input size. + NSMutableData *result = [NSMutableData dataWithCapacity:(length / 4)]; + unsigned char output[kChunkSize]; + + // Setup the input. + strm.avail_in = (unsigned int)length; + strm.next_in = (unsigned char *)bytes; + + // Collect the data. + do { + // update what we're passing in + strm.avail_out = kChunkSize; + strm.next_out = output; + retCode = deflate(&strm, Z_FINISH); + if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) { + if (error) { + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] + forKey:GULNSDataZlibErrorKey]; + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorInternal + userInfo:userInfo]; + } + deflateEnd(&strm); + return nil; + } + // Collect what we got. + unsigned gotBack = kChunkSize - strm.avail_out; + if (gotBack > 0) { + [result appendBytes:output length:gotBack]; + } + + } while (retCode == Z_OK); + + // If the loop exits, it used all input and the stream ended. + NSAssert(strm.avail_in == 0, + @"Should have finished deflating without using all input, %u bytes left", strm.avail_in); + NSAssert(retCode == Z_STREAM_END, + @"thought we finished deflate w/o getting a result of stream end, code %d", retCode); + + // Clean up. + deflateEnd(&strm); + + return result; +} + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/GULMutableDictionary.m b/Pods/GoogleUtilities/GoogleUtilities/Network/GULMutableDictionary.m new file mode 100644 index 0000000000..d281eb4450 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/GULMutableDictionary.m @@ -0,0 +1,97 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULMutableDictionary.h" + +@implementation GULMutableDictionary { + /// The mutable dictionary. + NSMutableDictionary *_objects; + + /// Serial synchronization queue. All reads should use dispatch_sync, while writes use + /// dispatch_async. + dispatch_queue_t _queue; +} + +- (instancetype)init { + self = [super init]; + + if (self) { + _objects = [[NSMutableDictionary alloc] init]; + _queue = dispatch_queue_create("GULMutableDictionary", DISPATCH_QUEUE_SERIAL); + } + + return self; +} + +- (NSString *)description { + __block NSString *description; + dispatch_sync(_queue, ^{ + description = self->_objects.description; + }); + return description; +} + +- (id)objectForKey:(id)key { + __block id object; + dispatch_sync(_queue, ^{ + object = self->_objects[key]; + }); + return object; +} + +- (void)setObject:(id)object forKey:(id)key { + dispatch_async(_queue, ^{ + self->_objects[key] = object; + }); +} + +- (void)removeObjectForKey:(id)key { + dispatch_async(_queue, ^{ + [self->_objects removeObjectForKey:key]; + }); +} + +- (void)removeAllObjects { + dispatch_async(_queue, ^{ + [self->_objects removeAllObjects]; + }); +} + +- (NSUInteger)count { + __block NSUInteger count; + dispatch_sync(_queue, ^{ + count = self->_objects.count; + }); + return count; +} + +- (id)objectForKeyedSubscript:(id)key { + // The method this calls is already synchronized. + return [self objectForKey:key]; +} + +- (void)setObject:(id)obj forKeyedSubscript:(id)key { + // The method this calls is already synchronized. + [self setObject:obj forKey:key]; +} + +- (NSDictionary *)dictionary { + __block NSDictionary *dictionary; + dispatch_sync(_queue, ^{ + dictionary = [self->_objects copy]; + }); + return dictionary; +} + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetwork.m b/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetwork.m new file mode 100644 index 0000000000..233500b5cd --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetwork.m @@ -0,0 +1,388 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULNetwork.h" +#import "Private/GULNetworkMessageCode.h" + +#import +#import +#import +#import "Private/GULMutableDictionary.h" +#import "Private/GULNetworkConstants.h" + +/// Constant string for request header Content-Encoding. +static NSString *const kGULNetworkContentCompressionKey = @"Content-Encoding"; + +/// Constant string for request header Content-Encoding value. +static NSString *const kGULNetworkContentCompressionValue = @"gzip"; + +/// Constant string for request header Content-Length. +static NSString *const kGULNetworkContentLengthKey = @"Content-Length"; + +/// Constant string for request header Content-Type. +static NSString *const kGULNetworkContentTypeKey = @"Content-Type"; + +/// Constant string for request header Content-Type value. +static NSString *const kGULNetworkContentTypeValue = @"application/x-www-form-urlencoded"; + +/// Constant string for GET request method. +static NSString *const kGULNetworkGETRequestMethod = @"GET"; + +/// Constant string for POST request method. +static NSString *const kGULNetworkPOSTRequestMethod = @"POST"; + +/// Default constant string as a prefix for network logger. +static NSString *const kGULNetworkLogTag = @"Google/Utilities/Network"; + +@interface GULNetwork () +@end + +@implementation GULNetwork { + /// Network reachability. + GULReachabilityChecker *_reachability; + + /// The dictionary of requests by session IDs { NSString : id }. + GULMutableDictionary *_requests; +} + +- (instancetype)init { + return [self initWithReachabilityHost:kGULNetworkReachabilityHost]; +} + +- (instancetype)initWithReachabilityHost:(NSString *)reachabilityHost { + self = [super init]; + if (self) { + // Setup reachability. + _reachability = [[GULReachabilityChecker alloc] initWithReachabilityDelegate:self + withHost:reachabilityHost]; + if (![_reachability start]) { + return nil; + } + + _requests = [[GULMutableDictionary alloc] init]; + _timeoutInterval = kGULNetworkTimeOutInterval; + } + return self; +} + +- (void)dealloc { + _reachability.reachabilityDelegate = nil; + [_reachability stop]; +} + +#pragma mark - External Methods + ++ (void)handleEventsForBackgroundURLSessionID:(NSString *)sessionID + completionHandler:(GULNetworkSystemCompletionHandler)completionHandler { + [GULNetworkURLSession handleEventsForBackgroundURLSessionID:sessionID + completionHandler:completionHandler]; +} + +- (NSString *)postURL:(NSURL *)url + payload:(NSData *)payload + queue:(dispatch_queue_t)queue + usingBackgroundSession:(BOOL)usingBackgroundSession + completionHandler:(GULNetworkCompletionHandler)handler { + if (!url.absoluteString.length) { + [self handleErrorWithCode:GULErrorCodeNetworkInvalidURL queue:queue withHandler:handler]; + return nil; + } + + NSTimeInterval timeOutInterval = _timeoutInterval ?: kGULNetworkTimeOutInterval; + + NSMutableURLRequest *request = + [[NSMutableURLRequest alloc] initWithURL:url + cachePolicy:NSURLRequestReloadIgnoringLocalCacheData + timeoutInterval:timeOutInterval]; + + if (!request) { + [self handleErrorWithCode:GULErrorCodeNetworkSessionTaskCreation + queue:queue + withHandler:handler]; + return nil; + } + + NSError *compressError = nil; + NSData *compressedData = [NSData gul_dataByGzippingData:payload error:&compressError]; + if (!compressedData || compressError) { + if (compressError || payload.length > 0) { + // If the payload is not empty but it fails to compress the payload, something has been wrong. + [self handleErrorWithCode:GULErrorCodeNetworkPayloadCompression + queue:queue + withHandler:handler]; + return nil; + } + compressedData = [[NSData alloc] init]; + } + + NSString *postLength = @(compressedData.length).stringValue; + + // Set up the request with the compressed data. + [request setValue:postLength forHTTPHeaderField:kGULNetworkContentLengthKey]; + request.HTTPBody = compressedData; + request.HTTPMethod = kGULNetworkPOSTRequestMethod; + [request setValue:kGULNetworkContentTypeValue forHTTPHeaderField:kGULNetworkContentTypeKey]; + [request setValue:kGULNetworkContentCompressionValue + forHTTPHeaderField:kGULNetworkContentCompressionKey]; + + GULNetworkURLSession *fetcher = [[GULNetworkURLSession alloc] initWithNetworkLoggerDelegate:self]; + fetcher.backgroundNetworkEnabled = usingBackgroundSession; + + __weak GULNetwork *weakSelf = self; + NSString *requestID = [fetcher + sessionIDFromAsyncPOSTRequest:request + completionHandler:^(NSHTTPURLResponse *response, NSData *data, + NSString *sessionID, NSError *error) { + GULNetwork *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + dispatch_queue_t queueToDispatch = queue ? queue : dispatch_get_main_queue(); + dispatch_async(queueToDispatch, ^{ + if (sessionID.length) { + [strongSelf->_requests removeObjectForKey:sessionID]; + } + if (handler) { + handler(response, data, error); + } + }); + }]; + if (!requestID) { + [self handleErrorWithCode:GULErrorCodeNetworkSessionTaskCreation + queue:queue + withHandler:handler]; + return nil; + } + + [self GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeNetwork000 + message:@"Uploading data. Host" + context:url]; + _requests[requestID] = fetcher; + return requestID; +} + +- (NSString *)getURL:(NSURL *)url + headers:(NSDictionary *)headers + queue:(dispatch_queue_t)queue + usingBackgroundSession:(BOOL)usingBackgroundSession + completionHandler:(GULNetworkCompletionHandler)handler { + if (!url.absoluteString.length) { + [self handleErrorWithCode:GULErrorCodeNetworkInvalidURL queue:queue withHandler:handler]; + return nil; + } + + NSTimeInterval timeOutInterval = _timeoutInterval ?: kGULNetworkTimeOutInterval; + NSMutableURLRequest *request = + [[NSMutableURLRequest alloc] initWithURL:url + cachePolicy:NSURLRequestReloadIgnoringLocalCacheData + timeoutInterval:timeOutInterval]; + + if (!request) { + [self handleErrorWithCode:GULErrorCodeNetworkSessionTaskCreation + queue:queue + withHandler:handler]; + return nil; + } + + request.HTTPMethod = kGULNetworkGETRequestMethod; + request.allHTTPHeaderFields = headers; + + GULNetworkURLSession *fetcher = [[GULNetworkURLSession alloc] initWithNetworkLoggerDelegate:self]; + fetcher.backgroundNetworkEnabled = usingBackgroundSession; + + __weak GULNetwork *weakSelf = self; + NSString *requestID = [fetcher + sessionIDFromAsyncGETRequest:request + completionHandler:^(NSHTTPURLResponse *response, NSData *data, NSString *sessionID, + NSError *error) { + GULNetwork *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + dispatch_queue_t queueToDispatch = queue ? queue : dispatch_get_main_queue(); + dispatch_async(queueToDispatch, ^{ + if (sessionID.length) { + [strongSelf->_requests removeObjectForKey:sessionID]; + } + if (handler) { + handler(response, data, error); + } + }); + }]; + + if (!requestID) { + [self handleErrorWithCode:GULErrorCodeNetworkSessionTaskCreation + queue:queue + withHandler:handler]; + return nil; + } + + [self GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeNetwork001 + message:@"Downloading data. Host" + context:url]; + _requests[requestID] = fetcher; + return requestID; +} + +- (BOOL)hasUploadInProgress { + return _requests.count > 0; +} + +#pragma mark - Network Reachability + +/// Tells reachability delegate to call reachabilityDidChangeToStatus: to notify the network +/// reachability has changed. +- (void)reachability:(GULReachabilityChecker *)reachability + statusChanged:(GULReachabilityStatus)status { + _networkConnected = (status == kGULReachabilityViaCellular || status == kGULReachabilityViaWifi); + [_reachabilityDelegate reachabilityDidChange]; +} + +#pragma mark - Network logger delegate + +- (void)setLoggerDelegate:(id)loggerDelegate { + // Explicitly check whether the delegate responds to the methods because conformsToProtocol does + // not work correctly even though the delegate does respond to the methods. + if (!loggerDelegate || + ![loggerDelegate + respondsToSelector:@selector(GULNetwork_logWithLevel:messageCode:message:contexts:)] || + ![loggerDelegate + respondsToSelector:@selector(GULNetwork_logWithLevel:messageCode:message:context:)] || + ! + [loggerDelegate respondsToSelector:@selector(GULNetwork_logWithLevel:messageCode:message:)]) { + GULLogError(kGULLoggerNetwork, NO, + [NSString stringWithFormat:@"I-NET%06ld", (long)kGULNetworkMessageCodeNetwork002], + @"Cannot set the network logger delegate: delegate does not conform to the network " + "logger protocol."); + return; + } + _loggerDelegate = loggerDelegate; +} + +#pragma mark - Private methods + +/// Handles network error and calls completion handler with the error. +- (void)handleErrorWithCode:(NSInteger)code + queue:(dispatch_queue_t)queue + withHandler:(GULNetworkCompletionHandler)handler { + NSDictionary *userInfo = @{kGULNetworkErrorContext : @"Failed to create network request"}; + NSError *error = + [[NSError alloc] initWithDomain:kGULNetworkErrorDomain code:code userInfo:userInfo]; + [self GULNetwork_logWithLevel:kGULNetworkLogLevelWarning + messageCode:kGULNetworkMessageCodeNetwork002 + message:@"Failed to create network request. Code, error" + contexts:@[ @(code), error ]]; + if (handler) { + dispatch_queue_t queueToDispatch = queue ? queue : dispatch_get_main_queue(); + dispatch_async(queueToDispatch, ^{ + handler(nil, nil, error); + }); + } +} + +#pragma mark - Network logger + +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message + contexts:(NSArray *)contexts { + // Let the delegate log the message if there is a valid logger delegate. Otherwise, just log + // errors/warnings/info messages to the console log. + if (_loggerDelegate) { + [_loggerDelegate GULNetwork_logWithLevel:logLevel + messageCode:messageCode + message:message + contexts:contexts]; + return; + } + if (_isDebugModeEnabled || logLevel == kGULNetworkLogLevelError || + logLevel == kGULNetworkLogLevelWarning || logLevel == kGULNetworkLogLevelInfo) { + NSString *formattedMessage = GULStringWithLogMessage(message, logLevel, contexts); + NSLog(@"%@", formattedMessage); + GULLogBasic((GULLoggerLevel)logLevel, kGULLoggerNetwork, NO, + [NSString stringWithFormat:@"I-NET%06ld", (long)messageCode], formattedMessage, + NULL); + } +} + +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message + context:(id)context { + if (_loggerDelegate) { + [_loggerDelegate GULNetwork_logWithLevel:logLevel + messageCode:messageCode + message:message + context:context]; + return; + } + NSArray *contexts = context ? @[ context ] : @[]; + [self GULNetwork_logWithLevel:logLevel messageCode:messageCode message:message contexts:contexts]; +} + +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message { + if (_loggerDelegate) { + [_loggerDelegate GULNetwork_logWithLevel:logLevel messageCode:messageCode message:message]; + return; + } + [self GULNetwork_logWithLevel:logLevel messageCode:messageCode message:message contexts:@[]]; +} + +/// Returns a string for the given log level (e.g. kGULNetworkLogLevelError -> @"ERROR"). +static NSString *GULLogLevelDescriptionFromLogLevel(GULNetworkLogLevel logLevel) { + static NSDictionary *levelNames = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + levelNames = @{ + @(kGULNetworkLogLevelError) : @"ERROR", + @(kGULNetworkLogLevelWarning) : @"WARNING", + @(kGULNetworkLogLevelInfo) : @"INFO", + @(kGULNetworkLogLevelDebug) : @"DEBUG" + }; + }); + return levelNames[@(logLevel)]; +} + +/// Returns a formatted string to be used for console logging. +static NSString *GULStringWithLogMessage(NSString *message, + GULNetworkLogLevel logLevel, + NSArray *contexts) { + if (!message) { + message = @"(Message was nil)"; + } else if (!message.length) { + message = @"(Message was empty)"; + } + NSMutableString *result = [[NSMutableString alloc] + initWithFormat:@"<%@/%@> %@", kGULNetworkLogTag, GULLogLevelDescriptionFromLogLevel(logLevel), + message]; + + if (!contexts.count) { + return result; + } + + NSMutableArray *formattedContexts = [[NSMutableArray alloc] init]; + for (id item in contexts) { + [formattedContexts addObject:(item != [NSNull null] ? item : @"(nil)")]; + } + + [result appendString:@": "]; + [result appendString:[formattedContexts componentsJoinedByString:@", "]]; + return result; +} + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkConstants.m b/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkConstants.m new file mode 100644 index 0000000000..90bd03d57e --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkConstants.m @@ -0,0 +1,40 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULNetworkConstants.h" + +#import + +NSString *const kGULNetworkBackgroundSessionConfigIDPrefix = @"com.gul.network.background-upload"; +NSString *const kGULNetworkApplicationSupportSubdirectory = @"GUL/Network"; +NSString *const kGULNetworkTempDirectoryName = @"GULNetworkTemporaryDirectory"; +const NSTimeInterval kGULNetworkTempFolderExpireTime = 60 * 60; // 1 hour +const NSTimeInterval kGULNetworkTimeOutInterval = 60; // 1 minute. +NSString *const kGULNetworkReachabilityHost = @"app-measurement.com"; +NSString *const kGULNetworkErrorContext = @"Context"; + +const int kGULNetworkHTTPStatusOK = 200; +const int kGULNetworkHTTPStatusNoContent = 204; +const int kGULNetworkHTTPStatusCodeMultipleChoices = 300; +const int kGULNetworkHTTPStatusCodeMovedPermanently = 301; +const int kGULNetworkHTTPStatusCodeFound = 302; +const int kGULNetworkHTTPStatusCodeNotModified = 304; +const int kGULNetworkHTTPStatusCodeMovedTemporarily = 307; +const int kGULNetworkHTTPStatusCodeNotFound = 404; +const int kGULNetworkHTTPStatusCodeCannotAcceptTraffic = 429; +const int kGULNetworkHTTPStatusCodeUnavailable = 503; + +NSString *const kGULNetworkErrorDomain = @"com.gul.network.ErrorDomain"; + +GULLoggerService kGULLoggerNetwork = @"[GULNetwork]"; diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkURLSession.m b/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkURLSession.m new file mode 100644 index 0000000000..26da579a3b --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkURLSession.m @@ -0,0 +1,730 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +#import "Private/GULNetworkURLSession.h" + +#import +#import "Private/GULMutableDictionary.h" +#import "Private/GULNetworkConstants.h" +#import "Private/GULNetworkMessageCode.h" + +@implementation GULNetworkURLSession { + /// The handler to be called when the request completes or error has occurs. + GULNetworkURLSessionCompletionHandler _completionHandler; + + /// Session ID generated randomly with a fixed prefix. + NSString *_sessionID; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + /// The session configuration. NSURLSessionConfiguration' is only available on iOS 7.0 or newer. + NSURLSessionConfiguration *_sessionConfig; +#pragma clang diagnostic pop + + /// The path to the directory where all temporary files are stored before uploading. + NSURL *_networkDirectoryURL; + + /// The downloaded data from fetching. + NSData *_downloadedData; + + /// The path to the temporary file which stores the uploading data. + NSURL *_uploadingFileURL; + + /// The current request. + NSURLRequest *_request; +} + +#pragma mark - Init + +- (instancetype)initWithNetworkLoggerDelegate:(id)networkLoggerDelegate { + self = [super init]; + if (self) { + // Create URL to the directory where all temporary files to upload have to be stored. + NSArray *paths = + NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); + NSString *applicationSupportDirectory = paths.firstObject; + NSArray *tempPathComponents = @[ + applicationSupportDirectory, kGULNetworkApplicationSupportSubdirectory, + kGULNetworkTempDirectoryName + ]; + _networkDirectoryURL = [NSURL fileURLWithPathComponents:tempPathComponents]; + _sessionID = [NSString stringWithFormat:@"%@-%@", kGULNetworkBackgroundSessionConfigIDPrefix, + [[NSUUID UUID] UUIDString]]; + _loggerDelegate = networkLoggerDelegate; + } + return self; +} + +#pragma mark - External Methods + +#pragma mark - To be called from AppDelegate + ++ (void)handleEventsForBackgroundURLSessionID:(NSString *)sessionID + completionHandler: + (GULNetworkSystemCompletionHandler)systemCompletionHandler { + // The session may not be Analytics background. Ignore those that do not have the prefix. + if (![sessionID hasPrefix:kGULNetworkBackgroundSessionConfigIDPrefix]) { + return; + } + GULNetworkURLSession *fetcher = [self fetcherWithSessionIdentifier:sessionID]; + if (fetcher != nil) { + [fetcher addSystemCompletionHandler:systemCompletionHandler forSession:sessionID]; + } else { + GULLogError(kGULLoggerNetwork, NO, + [NSString stringWithFormat:@"I-NET%06ld", (long)kGULNetworkMessageCodeNetwork003], + @"Failed to retrieve background session with ID %@ after app is relaunched.", + sessionID); + } +} + +#pragma mark - External Methods + +/// Sends an async POST request using NSURLSession for iOS >= 7.0, and returns an ID of the +/// connection. +- (NSString *)sessionIDFromAsyncPOSTRequest:(NSURLRequest *)request + completionHandler:(GULNetworkURLSessionCompletionHandler)handler + API_AVAILABLE(ios(7.0)) { + // NSURLSessionUploadTask does not work with NSData in the background. + // To avoid this issue, write the data to a temporary file to upload it. + // Make a temporary file with the data subset. + _uploadingFileURL = [self temporaryFilePathWithSessionID:_sessionID]; + NSError *writeError; + NSURLSessionUploadTask *postRequestTask; + NSURLSession *session; + BOOL didWriteFile = NO; + + // Clean up the entire temp folder to avoid temp files that remain in case the previous session + // crashed and did not clean up. + [self maybeRemoveTempFilesAtURL:_networkDirectoryURL + expiringTime:kGULNetworkTempFolderExpireTime]; + + // If there is no background network enabled, no need to write to file. This will allow default + // network session which runs on the foreground. + if (_backgroundNetworkEnabled && [self ensureTemporaryDirectoryExists]) { + didWriteFile = [request.HTTPBody writeToFile:_uploadingFileURL.path + options:NSDataWritingAtomic + error:&writeError]; + + if (writeError) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession000 + message:@"Failed to write request data to file" + context:writeError]; + } + } + + if (didWriteFile) { + // Exclude this file from backing up to iTunes. There are conflicting reports that excluding + // directory from backing up does not excluding files of that directory from backing up. + [self excludeFromBackupForURL:_uploadingFileURL]; + + _sessionConfig = [self backgroundSessionConfigWithSessionID:_sessionID]; + [self populateSessionConfig:_sessionConfig withRequest:request]; + session = [NSURLSession sessionWithConfiguration:_sessionConfig + delegate:self + delegateQueue:[NSOperationQueue mainQueue]]; + postRequestTask = [session uploadTaskWithRequest:request fromFile:_uploadingFileURL]; + } else { + // If we cannot write to file, just send it in the foreground. + _sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; + [self populateSessionConfig:_sessionConfig withRequest:request]; + _sessionConfig.URLCache = nil; + session = [NSURLSession sessionWithConfiguration:_sessionConfig + delegate:self + delegateQueue:[NSOperationQueue mainQueue]]; + postRequestTask = [session uploadTaskWithRequest:request fromData:request.HTTPBody]; + } + + if (!session || !postRequestTask) { + NSError *error = [[NSError alloc] + initWithDomain:kGULNetworkErrorDomain + code:GULErrorCodeNetworkRequestCreation + userInfo:@{kGULNetworkErrorContext : @"Cannot create network session"}]; + [self callCompletionHandler:handler withResponse:nil data:nil error:error]; + return nil; + } + + // Save the session into memory. + [[self class] setSessionInFetcherMap:self forSessionID:_sessionID]; + + _request = [request copy]; + + // Store completion handler because background session does not accept handler block but custom + // delegate. + _completionHandler = [handler copy]; + [postRequestTask resume]; + + return _sessionID; +} + +/// Sends an async GET request using NSURLSession for iOS >= 7.0, and returns an ID of the session. +- (NSString *)sessionIDFromAsyncGETRequest:(NSURLRequest *)request + completionHandler:(GULNetworkURLSessionCompletionHandler)handler + API_AVAILABLE(ios(7.0)) { + if (_backgroundNetworkEnabled) { + _sessionConfig = [self backgroundSessionConfigWithSessionID:_sessionID]; + } else { + _sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; + } + + [self populateSessionConfig:_sessionConfig withRequest:request]; + + // Do not cache the GET request. + _sessionConfig.URLCache = nil; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:_sessionConfig + delegate:self + delegateQueue:[NSOperationQueue mainQueue]]; + NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request]; + + if (!session || !downloadTask) { + NSError *error = [[NSError alloc] + initWithDomain:kGULNetworkErrorDomain + code:GULErrorCodeNetworkRequestCreation + userInfo:@{kGULNetworkErrorContext : @"Cannot create network session"}]; + [self callCompletionHandler:handler withResponse:nil data:nil error:error]; + return nil; + } + + // Save the session into memory. + [[self class] setSessionInFetcherMap:self forSessionID:_sessionID]; + + _request = [request copy]; + + _completionHandler = [handler copy]; + [downloadTask resume]; + + return _sessionID; +} + +#pragma mark - NSURLSessionTaskDelegate + +/// Called by the NSURLSession once the download task is completed. The file is saved in the +/// provided URL so we need to read the data and store into _downloadedData. Once the session is +/// completed, URLSession:task:didCompleteWithError will be called and the completion handler will +/// be called with the downloaded data. +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)task + didFinishDownloadingToURL:(NSURL *)url API_AVAILABLE(ios(7.0)) { + if (!url.path) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession001 + message:@"Unable to read downloaded data from empty temp path"]; + _downloadedData = nil; + return; + } + + NSError *error; + _downloadedData = [NSData dataWithContentsOfFile:url.path options:0 error:&error]; + + if (error) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession002 + message:@"Cannot read the content of downloaded data" + context:error]; + _downloadedData = nil; + } +} + +#if TARGET_OS_IOS || TARGET_OS_TV +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session + API_AVAILABLE(ios(7.0)) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession003 + message:@"Background session finished" + context:session.configuration.identifier]; + [self callSystemCompletionHandler:session.configuration.identifier]; +} +#endif + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didCompleteWithError:(NSError *)error API_AVAILABLE(ios(7.0)) { + // Avoid any chance of recursive behavior leading to it being used repeatedly. + GULNetworkURLSessionCompletionHandler handler = _completionHandler; + _completionHandler = nil; + + if (task.response) { + // The following assertion should always be true for HTTP requests, see https://goo.gl/gVLxT7. + NSAssert([task.response isKindOfClass:[NSHTTPURLResponse class]], @"URL response must be HTTP"); + + // The server responded so ignore the error created by the system. + error = nil; + } else if (!error) { + error = [[NSError alloc] + initWithDomain:kGULNetworkErrorDomain + code:GULErrorCodeNetworkInvalidResponse + userInfo:@{kGULNetworkErrorContext : @"Network Error: Empty network response"}]; + } + + [self callCompletionHandler:handler + withResponse:(NSHTTPURLResponse *)task.response + data:_downloadedData + error:error]; + + // Remove the temp file to avoid trashing devices with lots of temp files. + [self removeTempItemAtURL:_uploadingFileURL]; + + // Try to clean up stale files again. + [self maybeRemoveTempFilesAtURL:_networkDirectoryURL + expiringTime:kGULNetworkTempFolderExpireTime]; + + // Invalidate the session only if it's owned by this class. + NSString *sessionID = session.configuration.identifier; + if ([sessionID hasPrefix:kGULNetworkBackgroundSessionConfigIDPrefix]) { + [session finishTasksAndInvalidate]; + + // Explicitly remove the session so it won't be reused. The weak map table should + // remove the session on deallocation, but dealloc may not happen immediately after + // calling `finishTasksAndInvalidate`. + [[self class] setSessionInFetcherMap:nil forSessionID:sessionID]; + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential *credential))completionHandler + API_AVAILABLE(ios(7.0)) { + // The handling is modeled after GTMSessionFetcher. + if ([challenge.protectionSpace.authenticationMethod + isEqualToString:NSURLAuthenticationMethodServerTrust]) { + SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; + if (serverTrust == NULL) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession004 + message:@"Received empty server trust for host. Host" + context:_request.URL]; + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + return; + } + NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; + if (!credential) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelWarning + messageCode:kGULNetworkMessageCodeURLSession005 + message:@"Unable to verify server identity. Host" + context:_request.URL]; + completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); + return; + } + + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession006 + message:@"Received SSL challenge for host. Host" + context:_request.URL]; + + void (^callback)(BOOL) = ^(BOOL allow) { + if (allow) { + completionHandler(NSURLSessionAuthChallengeUseCredential, credential); + } else { + [self->_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession007 + message:@"Cancelling authentication challenge for host. Host" + context:self->_request.URL]; + completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); + } + }; + + // Retain the trust object to avoid a SecTrustEvaluate() crash on iOS 7. + CFRetain(serverTrust); + + // Evaluate the certificate chain. + // + // The delegate queue may be the main thread. Trust evaluation could cause some + // blocking network activity, so we must evaluate async, as documented at + // https://developer.apple.com/library/ios/technotes/tn2232/ + dispatch_queue_t evaluateBackgroundQueue = + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + dispatch_async(evaluateBackgroundQueue, ^{ + SecTrustResultType trustEval = kSecTrustResultInvalid; + BOOL shouldAllow; + OSStatus trustError; + + @synchronized([GULNetworkURLSession class]) { + trustError = SecTrustEvaluate(serverTrust, &trustEval); + } + + if (trustError != errSecSuccess) { + [self->_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession008 + message:@"Cannot evaluate server trust. Error, host" + contexts:@[ @(trustError), self->_request.URL ]]; + shouldAllow = NO; + } else { + // Having a trust level "unspecified" by the user is the usual result, described at + // https://developer.apple.com/library/mac/qa/qa1360 + shouldAllow = + (trustEval == kSecTrustResultUnspecified || trustEval == kSecTrustResultProceed); + } + + // Call the call back with the permission. + callback(shouldAllow); + + CFRelease(serverTrust); + }); + return; + } + + // Default handling for other Auth Challenges. + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); +} + +#pragma mark - Internal Methods + +/// Stores system completion handler with session ID as key. +- (void)addSystemCompletionHandler:(GULNetworkSystemCompletionHandler)handler + forSession:(NSString *)identifier { + if (!handler) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession009 + message:@"Cannot store nil system completion handler in network"]; + return; + } + + if (!identifier.length) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession010 + message: + @"Cannot store system completion handler with empty network " + "session identifier"]; + return; + } + + GULMutableDictionary *systemCompletionHandlers = + [[self class] sessionIDToSystemCompletionHandlerDictionary]; + if (systemCompletionHandlers[identifier]) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelWarning + messageCode:kGULNetworkMessageCodeURLSession011 + message:@"Got multiple system handlers for a single session ID" + context:identifier]; + } + + systemCompletionHandlers[identifier] = handler; +} + +/// Calls the system provided completion handler with the session ID stored in the dictionary. +/// The handler will be removed from the dictionary after being called. +- (void)callSystemCompletionHandler:(NSString *)identifier { + GULMutableDictionary *systemCompletionHandlers = + [[self class] sessionIDToSystemCompletionHandlerDictionary]; + GULNetworkSystemCompletionHandler handler = [systemCompletionHandlers objectForKey:identifier]; + + if (handler) { + [systemCompletionHandlers removeObjectForKey:identifier]; + + dispatch_async(dispatch_get_main_queue(), ^{ + handler(); + }); + } +} + +/// Sets or updates the session ID of this session. +- (void)setSessionID:(NSString *)sessionID { + _sessionID = [sessionID copy]; +} + +/// Creates a background session configuration with the session ID using the supported method. +- (NSURLSessionConfiguration *)backgroundSessionConfigWithSessionID:(NSString *)sessionID + API_AVAILABLE(ios(7.0)) { +#if (TARGET_OS_OSX && defined(MAC_OS_X_VERSION_10_10) && \ + MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) || \ + TARGET_OS_TV || \ + (TARGET_OS_IOS && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0) + + // iOS 8/10.10 builds require the new backgroundSessionConfiguration method name. + return [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionID]; + +#elif (TARGET_OS_OSX && defined(MAC_OS_X_VERSION_10_10) && \ + MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10) || \ + (TARGET_OS_IOS && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0) + + // Do a runtime check to avoid a deprecation warning about using + // +backgroundSessionConfiguration: on iOS 8. + if ([NSURLSessionConfiguration + respondsToSelector:@selector(backgroundSessionConfigurationWithIdentifier:)]) { + // Running on iOS 8+/OS X 10.10+. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + return [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionID]; +#pragma clang diagnostic pop + } else { + // Running on iOS 7/OS X 10.9. + return [NSURLSessionConfiguration backgroundSessionConfiguration:sessionID]; + } + +#else + // Building with an SDK earlier than iOS 8/OS X 10.10. + return [NSURLSessionConfiguration backgroundSessionConfiguration:sessionID]; +#endif +} + +- (void)maybeRemoveTempFilesAtURL:(NSURL *)folderURL expiringTime:(NSTimeInterval)staleTime { + if (!folderURL.absoluteString.length) { + return; + } + + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSError *error = nil; + + NSArray *properties = @[ NSURLCreationDateKey ]; + NSArray *directoryContent = + [fileManager contentsOfDirectoryAtURL:folderURL + includingPropertiesForKeys:properties + options:NSDirectoryEnumerationSkipsSubdirectoryDescendants + error:&error]; + if (error && error.code != NSFileReadNoSuchFileError) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession012 + message:@"Cannot get files from the temporary network folder. Error" + context:error]; + return; + } + + if (!directoryContent.count) { + return; + } + + NSTimeInterval now = [NSDate date].timeIntervalSince1970; + for (NSURL *tempFile in directoryContent) { + NSDate *creationDate; + BOOL getCreationDate = + [tempFile getResourceValue:&creationDate forKey:NSURLCreationDateKey error:NULL]; + if (!getCreationDate) { + continue; + } + NSTimeInterval creationTimeInterval = creationDate.timeIntervalSince1970; + if (fabs(now - creationTimeInterval) > staleTime) { + [self removeTempItemAtURL:tempFile]; + } + } +} + +/// Removes the temporary file written to disk for sending the request. It has to be cleaned up +/// after the session is done. +- (void)removeTempItemAtURL:(NSURL *)fileURL { + if (!fileURL.absoluteString.length) { + return; + } + + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSError *error = nil; + + if (![fileManager removeItemAtURL:fileURL error:&error] && error.code != NSFileNoSuchFileError) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession013 + message:@"Failed to remove temporary uploading data file. Error" + context:error.localizedDescription]; + } +} + +/// Gets the fetcher with the session ID. ++ (instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier { + GULNetworkURLSession *session = [self sessionFromFetcherMapForSessionID:sessionIdentifier]; + if (!session && [sessionIdentifier hasPrefix:kGULNetworkBackgroundSessionConfigIDPrefix]) { + session = [[GULNetworkURLSession alloc] initWithNetworkLoggerDelegate:nil]; + [session setSessionID:sessionIdentifier]; + [self setSessionInFetcherMap:session forSessionID:sessionIdentifier]; + } + return session; +} + +/// Returns a map of the fetcher by session ID. Creates a map if it is not created. +/// When reading and writing from/to the session map, don't use this method directly. +/// To avoid thread safety issues, use one of the helper methods at the bottom of the +/// file: setSessionInFetcherMap:forSessionID:, sessionFromFetcherMapForSessionID: ++ (NSMapTable *)sessionIDToFetcherMap { + static NSMapTable *sessionIDToFetcherMap; + + static dispatch_once_t sessionMapOnceToken; + dispatch_once(&sessionMapOnceToken, ^{ + sessionIDToFetcherMap = [NSMapTable strongToWeakObjectsMapTable]; + }); + return sessionIDToFetcherMap; +} + ++ (NSLock *)sessionIDToFetcherMapReadWriteLock { + static NSLock *lock; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + lock = [[NSLock alloc] init]; + }); + return lock; +} + +/// Returns a map of system provided completion handler by session ID. Creates a map if it is not +/// created. ++ (GULMutableDictionary *)sessionIDToSystemCompletionHandlerDictionary { + static GULMutableDictionary *systemCompletionHandlers; + + static dispatch_once_t systemCompletionHandlerOnceToken; + dispatch_once(&systemCompletionHandlerOnceToken, ^{ + systemCompletionHandlers = [[GULMutableDictionary alloc] init]; + }); + return systemCompletionHandlers; +} + +- (NSURL *)temporaryFilePathWithSessionID:(NSString *)sessionID { + NSString *tempName = [NSString stringWithFormat:@"GULUpload_temp_%@", sessionID]; + return [_networkDirectoryURL URLByAppendingPathComponent:tempName]; +} + +/// Makes sure that the directory to store temp files exists. If not, tries to create it and returns +/// YES. If there is anything wrong, returns NO. +- (BOOL)ensureTemporaryDirectoryExists { + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSError *error = nil; + + // Create a temporary directory if it does not exist or was deleted. + if ([_networkDirectoryURL checkResourceIsReachableAndReturnError:&error]) { + return YES; + } + + if (error && error.code != NSFileReadNoSuchFileError) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelWarning + messageCode:kGULNetworkMessageCodeURLSession014 + message:@"Error while trying to access Network temp folder. Error" + context:error]; + } + + NSError *writeError = nil; + + [fileManager createDirectoryAtURL:_networkDirectoryURL + withIntermediateDirectories:YES + attributes:nil + error:&writeError]; + if (writeError) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession015 + message:@"Cannot create temporary directory. Error" + context:writeError]; + return NO; + } + + // Set the iCloud exclusion attribute on the Documents URL. + [self excludeFromBackupForURL:_networkDirectoryURL]; + + return YES; +} + +- (void)excludeFromBackupForURL:(NSURL *)url { + if (!url.path) { + return; + } + + // Set the iCloud exclusion attribute on the Documents URL. + NSError *preventBackupError = nil; + [url setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&preventBackupError]; + if (preventBackupError) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession016 + message:@"Cannot exclude temporary folder from iTunes backup"]; + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler API_AVAILABLE(ios(7.0)) { + NSArray *nonAllowedRedirectionCodes = @[ + @(kGULNetworkHTTPStatusCodeFound), @(kGULNetworkHTTPStatusCodeMovedPermanently), + @(kGULNetworkHTTPStatusCodeMovedTemporarily), @(kGULNetworkHTTPStatusCodeMultipleChoices) + ]; + + // Allow those not in the non allowed list to be followed. + if (![nonAllowedRedirectionCodes containsObject:@(response.statusCode)]) { + completionHandler(request); + return; + } + + // Do not allow redirection if the response code is in the non-allowed list. + NSURLRequest *newRequest = request; + + if (response) { + newRequest = nil; + } + + completionHandler(newRequest); +} + +#pragma mark - Helper Methods + ++ (void)setSessionInFetcherMap:(GULNetworkURLSession *)session forSessionID:(NSString *)sessionID { + [[self sessionIDToFetcherMapReadWriteLock] lock]; + GULNetworkURLSession *existingSession = + [[[self class] sessionIDToFetcherMap] objectForKey:sessionID]; + if (existingSession) { + // Invalidating doesn't seem like the right thing to do here since it may cancel an active + // background transfer if the background session is handling multiple requests. The old + // session will be dropped from the map table, but still complete its request. + NSString *message = [NSString stringWithFormat:@"Discarding session: %@", existingSession]; + [existingSession->_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelInfo + messageCode:kGULNetworkMessageCodeURLSession019 + message:message]; + } + if (session) { + [[[self class] sessionIDToFetcherMap] setObject:session forKey:sessionID]; + } else { + [[[self class] sessionIDToFetcherMap] removeObjectForKey:sessionID]; + } + [[self sessionIDToFetcherMapReadWriteLock] unlock]; +} + ++ (nullable GULNetworkURLSession *)sessionFromFetcherMapForSessionID:(NSString *)sessionID { + [[self sessionIDToFetcherMapReadWriteLock] lock]; + GULNetworkURLSession *session = [[[self class] sessionIDToFetcherMap] objectForKey:sessionID]; + [[self sessionIDToFetcherMapReadWriteLock] unlock]; + return session; +} + +- (void)callCompletionHandler:(GULNetworkURLSessionCompletionHandler)handler + withResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError *)error { + if (error) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession017 + message:@"Encounter network error. Code, error" + contexts:@[ @(error.code), error ]]; + } + + if (handler) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler(response, data, self->_sessionID, error); + }); + } +} + +// Always use the request parameters even if the default session configuration is more restrictive. +- (void)populateSessionConfig:(NSURLSessionConfiguration *)sessionConfig + withRequest:(NSURLRequest *)request API_AVAILABLE(ios(7.0)) { + sessionConfig.HTTPAdditionalHeaders = request.allHTTPHeaderFields; + sessionConfig.timeoutIntervalForRequest = request.timeoutInterval; + sessionConfig.timeoutIntervalForResource = request.timeoutInterval; + sessionConfig.requestCachePolicy = request.cachePolicy; +} + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULMutableDictionary.h b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULMutableDictionary.h new file mode 100644 index 0000000000..a8cc45b4b8 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULMutableDictionary.h @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/// A mutable dictionary that provides atomic accessor and mutators. +@interface GULMutableDictionary : NSObject + +/// Returns an object given a key in the dictionary or nil if not found. +- (id)objectForKey:(id)key; + +/// Updates the object given its key or adds it to the dictionary if it is not in the dictionary. +- (void)setObject:(id)object forKey:(id)key; + +/// Removes the object given its session ID from the dictionary. +- (void)removeObjectForKey:(id)key; + +/// Removes all objects. +- (void)removeAllObjects; + +/// Returns the number of current objects in the dictionary. +- (NSUInteger)count; + +/// Returns an object given a key in the dictionary or nil if not found. +- (id)objectForKeyedSubscript:(id)key; + +/// Updates the object given its key or adds it to the dictionary if it is not in the dictionary. +- (void)setObject:(id)obj forKeyedSubscript:(id)key; + +/// Returns the immutable dictionary. +- (NSDictionary *)dictionary; + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetwork.h b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetwork.h new file mode 100644 index 0000000000..0e75ae5d7e --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetwork.h @@ -0,0 +1,87 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "GULNetworkConstants.h" +#import "GULNetworkLoggerProtocol.h" +#import "GULNetworkURLSession.h" + +/// Delegate protocol for GULNetwork events. +@protocol GULNetworkReachabilityDelegate + +/// Tells the delegate to handle events when the network reachability changes to connected or not +/// connected. +- (void)reachabilityDidChange; + +@end + +/// The Network component that provides network status and handles network requests and responses. +/// This is not thread safe. +/// +/// NOTE: +/// User must add FIRAnalytics handleEventsForBackgroundURLSessionID:completionHandler to the +/// AppDelegate application:handleEventsForBackgroundURLSession:completionHandler: +@interface GULNetwork : NSObject + +/// Indicates if network connectivity is available. +@property(nonatomic, readonly, getter=isNetworkConnected) BOOL networkConnected; + +/// Indicates if there are any uploads in progress. +@property(nonatomic, readonly, getter=hasUploadInProgress) BOOL uploadInProgress; + +/// An optional delegate that can be used in the event when network reachability changes. +@property(nonatomic, weak) id reachabilityDelegate; + +/// An optional delegate that can be used to log messages, warnings or errors that occur in the +/// network operations. +@property(nonatomic, weak) id loggerDelegate; + +/// Indicates whether the logger should display debug messages. +@property(nonatomic, assign) BOOL isDebugModeEnabled; + +/// The time interval in seconds for the network request to timeout. +@property(nonatomic, assign) NSTimeInterval timeoutInterval; + +/// Initializes with the default reachability host. +- (instancetype)init; + +/// Initializes with a custom reachability host. +- (instancetype)initWithReachabilityHost:(NSString *)reachabilityHost; + +/// Handles events when background session with the given ID has finished. ++ (void)handleEventsForBackgroundURLSessionID:(NSString *)sessionID + completionHandler:(GULNetworkSystemCompletionHandler)completionHandler; + +/// Compresses and sends a POST request with the provided data to the URL. The session will be +/// background session if usingBackgroundSession is YES. Otherwise, the POST session is default +/// session. Returns a session ID or nil if an error occurs. +- (NSString *)postURL:(NSURL *)url + payload:(NSData *)payload + queue:(dispatch_queue_t)queue + usingBackgroundSession:(BOOL)usingBackgroundSession + completionHandler:(GULNetworkCompletionHandler)handler; + +/// Sends a GET request with the provided data to the URL. The session will be background session +/// if usingBackgroundSession is YES. Otherwise, the GET session is default session. Returns a +/// session ID or nil if an error occurs. +- (NSString *)getURL:(NSURL *)url + headers:(NSDictionary *)headers + queue:(dispatch_queue_t)queue + usingBackgroundSession:(BOOL)usingBackgroundSession + completionHandler:(GULNetworkCompletionHandler)handler; + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkConstants.h b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkConstants.h new file mode 100644 index 0000000000..44d440b99d --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkConstants.h @@ -0,0 +1,79 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +/// Error codes in Firebase Network error domain. +/// Note: these error codes should never change. It would make it harder to decode the errors if +/// we inadvertently altered any of these codes in a future SDK version. +typedef NS_ENUM(NSInteger, GULNetworkErrorCode) { + /// Unknown error. + GULNetworkErrorCodeUnknown = 0, + /// Error occurs when the request URL is invalid. + GULErrorCodeNetworkInvalidURL = 1, + /// Error occurs when request cannot be constructed. + GULErrorCodeNetworkRequestCreation = 2, + /// Error occurs when payload cannot be compressed. + GULErrorCodeNetworkPayloadCompression = 3, + /// Error occurs when session task cannot be created. + GULErrorCodeNetworkSessionTaskCreation = 4, + /// Error occurs when there is no response. + GULErrorCodeNetworkInvalidResponse = 5 +}; + +#pragma mark - Network constants + +/// The prefix of the ID of the background session. +extern NSString *const kGULNetworkBackgroundSessionConfigIDPrefix; + +/// The sub directory to store the files of data that is being uploaded in the background. +extern NSString *const kGULNetworkApplicationSupportSubdirectory; + +/// Name of the temporary directory that stores files for background uploading. +extern NSString *const kGULNetworkTempDirectoryName; + +/// The period when the temporary uploading file can stay. +extern const NSTimeInterval kGULNetworkTempFolderExpireTime; + +/// The default network request timeout interval. +extern const NSTimeInterval kGULNetworkTimeOutInterval; + +/// The host to check the reachability of the network. +extern NSString *const kGULNetworkReachabilityHost; + +/// The key to get the error context of the UserInfo. +extern NSString *const kGULNetworkErrorContext; + +#pragma mark - Network Status Code + +extern const int kGULNetworkHTTPStatusOK; +extern const int kGULNetworkHTTPStatusNoContent; +extern const int kGULNetworkHTTPStatusCodeMultipleChoices; +extern const int kGULNetworkHTTPStatusCodeMovedPermanently; +extern const int kGULNetworkHTTPStatusCodeFound; +extern const int kGULNetworkHTTPStatusCodeNotModified; +extern const int kGULNetworkHTTPStatusCodeMovedTemporarily; +extern const int kGULNetworkHTTPStatusCodeNotFound; +extern const int kGULNetworkHTTPStatusCodeCannotAcceptTraffic; +extern const int kGULNetworkHTTPStatusCodeUnavailable; + +#pragma mark - Error Domain + +extern NSString *const kGULNetworkErrorDomain; + +/// The logger service for GULNetwork. +extern GULLoggerService kGULLoggerNetwork; diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkLoggerProtocol.h b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkLoggerProtocol.h new file mode 100644 index 0000000000..f1be5906f8 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkLoggerProtocol.h @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import + +#import "GULNetworkMessageCode.h" + +/// The log levels used by GULNetworkLogger. +typedef NS_ENUM(NSInteger, GULNetworkLogLevel) { + kGULNetworkLogLevelError = GULLoggerLevelError, + kGULNetworkLogLevelWarning = GULLoggerLevelWarning, + kGULNetworkLogLevelInfo = GULLoggerLevelInfo, + kGULNetworkLogLevelDebug = GULLoggerLevelDebug, +}; + +@protocol GULNetworkLoggerDelegate + +@required +/// Tells the delegate to log a message with an array of contexts and the log level. +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message + contexts:(NSArray *)contexts; + +/// Tells the delegate to log a message with a context and the log level. +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message + context:(id)context; + +/// Tells the delegate to log a message with the log level. +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message; + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkMessageCode.h b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkMessageCode.h new file mode 100644 index 0000000000..f9d1628a84 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkMessageCode.h @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Make sure these codes do not overlap with any contained in the FIRAMessageCode enum. +typedef NS_ENUM(NSInteger, GULNetworkMessageCode) { + // GULNetwork.m + kGULNetworkMessageCodeNetwork000 = 900000, // I-NET900000 + kGULNetworkMessageCodeNetwork001 = 900001, // I-NET900001 + kGULNetworkMessageCodeNetwork002 = 900002, // I-NET900002 + kGULNetworkMessageCodeNetwork003 = 900003, // I-NET900003 + // GULNetworkURLSession.m + kGULNetworkMessageCodeURLSession000 = 901000, // I-NET901000 + kGULNetworkMessageCodeURLSession001 = 901001, // I-NET901001 + kGULNetworkMessageCodeURLSession002 = 901002, // I-NET901002 + kGULNetworkMessageCodeURLSession003 = 901003, // I-NET901003 + kGULNetworkMessageCodeURLSession004 = 901004, // I-NET901004 + kGULNetworkMessageCodeURLSession005 = 901005, // I-NET901005 + kGULNetworkMessageCodeURLSession006 = 901006, // I-NET901006 + kGULNetworkMessageCodeURLSession007 = 901007, // I-NET901007 + kGULNetworkMessageCodeURLSession008 = 901008, // I-NET901008 + kGULNetworkMessageCodeURLSession009 = 901009, // I-NET901009 + kGULNetworkMessageCodeURLSession010 = 901010, // I-NET901010 + kGULNetworkMessageCodeURLSession011 = 901011, // I-NET901011 + kGULNetworkMessageCodeURLSession012 = 901012, // I-NET901012 + kGULNetworkMessageCodeURLSession013 = 901013, // I-NET901013 + kGULNetworkMessageCodeURLSession014 = 901014, // I-NET901014 + kGULNetworkMessageCodeURLSession015 = 901015, // I-NET901015 + kGULNetworkMessageCodeURLSession016 = 901016, // I-NET901016 + kGULNetworkMessageCodeURLSession017 = 901017, // I-NET901017 + kGULNetworkMessageCodeURLSession018 = 901018, // I-NET901018 + kGULNetworkMessageCodeURLSession019 = 901019, // I-NET901019 +}; diff --git a/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkURLSession.h b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkURLSession.h new file mode 100644 index 0000000000..81190c63d9 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkURLSession.h @@ -0,0 +1,60 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "GULNetworkLoggerProtocol.h" + +typedef void (^GULNetworkCompletionHandler)(NSHTTPURLResponse *response, + NSData *data, + NSError *error); +typedef void (^GULNetworkURLSessionCompletionHandler)(NSHTTPURLResponse *response, + NSData *data, + NSString *sessionID, + NSError *error); +typedef void (^GULNetworkSystemCompletionHandler)(void); + +/// The protocol that uses NSURLSession for iOS >= 7.0 to handle requests and responses. +@interface GULNetworkURLSession + : NSObject + +/// Indicates whether the background network is enabled. Default value is NO. +@property(nonatomic, getter=isBackgroundNetworkEnabled) BOOL backgroundNetworkEnabled; + +/// The logger delegate to log message, errors or warnings that occur during the network operations. +@property(nonatomic, weak) id loggerDelegate; + +/// Calls the system provided completion handler after the background session is finished. ++ (void)handleEventsForBackgroundURLSessionID:(NSString *)sessionID + completionHandler:(GULNetworkSystemCompletionHandler)completionHandler; + +/// Initializes with logger delegate. +- (instancetype)initWithNetworkLoggerDelegate:(id)networkLoggerDelegate + NS_DESIGNATED_INITIALIZER; + +- (instancetype)init NS_UNAVAILABLE; + +/// Sends an asynchronous POST request and calls the provided completion handler when the request +/// completes or when errors occur, and returns an ID of the session/connection. +- (NSString *)sessionIDFromAsyncPOSTRequest:(NSURLRequest *)request + completionHandler:(GULNetworkURLSessionCompletionHandler)handler; + +/// Sends an asynchronous GET request and calls the provided completion handler when the request +/// completes or when errors occur, and returns an ID of the session. +- (NSString *)sessionIDFromAsyncGETRequest:(NSURLRequest *)request + completionHandler:(GULNetworkURLSessionCompletionHandler)handler; + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker+Internal.h b/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker+Internal.h new file mode 100644 index 0000000000..8883c4d194 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker+Internal.h @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +typedef SCNetworkReachabilityRef (*GULReachabilityCreateWithNameFn)(CFAllocatorRef allocator, + const char *host); + +typedef Boolean (*GULReachabilitySetCallbackFn)(SCNetworkReachabilityRef target, + SCNetworkReachabilityCallBack callback, + SCNetworkReachabilityContext *context); +typedef Boolean (*GULReachabilityScheduleWithRunLoopFn)(SCNetworkReachabilityRef target, + CFRunLoopRef runLoop, + CFStringRef runLoopMode); +typedef Boolean (*GULReachabilityUnscheduleFromRunLoopFn)(SCNetworkReachabilityRef target, + CFRunLoopRef runLoop, + CFStringRef runLoopMode); + +typedef void (*GULReachabilityReleaseFn)(CFTypeRef cf); + +struct GULReachabilityApi { + GULReachabilityCreateWithNameFn createWithNameFn; + GULReachabilitySetCallbackFn setCallbackFn; + GULReachabilityScheduleWithRunLoopFn scheduleWithRunLoopFn; + GULReachabilityUnscheduleFromRunLoopFn unscheduleFromRunLoopFn; + GULReachabilityReleaseFn releaseFn; +}; + +@interface GULReachabilityChecker (Internal) + +- (const struct GULReachabilityApi *)reachabilityApi; +- (void)setReachabilityApi:(const struct GULReachabilityApi *)reachabilityApi; + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker.m b/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker.m new file mode 100644 index 0000000000..1ddacdfc22 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker.m @@ -0,0 +1,240 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +#import "GULReachabilityChecker+Internal.h" +#import "Private/GULReachabilityChecker.h" +#import "Private/GULReachabilityMessageCode.h" + +#import +#import + +static GULLoggerService kGULLoggerReachability = @"[GULReachability]"; + +static void ReachabilityCallback(SCNetworkReachabilityRef reachability, + SCNetworkReachabilityFlags flags, + void *info); + +static const struct GULReachabilityApi kGULDefaultReachabilityApi = { + SCNetworkReachabilityCreateWithName, + SCNetworkReachabilitySetCallback, + SCNetworkReachabilityScheduleWithRunLoop, + SCNetworkReachabilityUnscheduleFromRunLoop, + CFRelease, +}; + +static NSString *const kGULReachabilityUnknownStatus = @"Unknown"; +static NSString *const kGULReachabilityConnectedStatus = @"Connected"; +static NSString *const kGULReachabilityDisconnectedStatus = @"Disconnected"; + +@interface GULReachabilityChecker () + +@property(nonatomic, assign) const struct GULReachabilityApi *reachabilityApi; +@property(nonatomic, assign) GULReachabilityStatus reachabilityStatus; +@property(nonatomic, copy) NSString *host; +@property(nonatomic, assign) SCNetworkReachabilityRef reachability; + +@end + +@implementation GULReachabilityChecker + +@synthesize reachabilityApi = reachabilityApi_; +@synthesize reachability = reachability_; + +- (const struct GULReachabilityApi *)reachabilityApi { + return reachabilityApi_; +} + +- (void)setReachabilityApi:(const struct GULReachabilityApi *)reachabilityApi { + if (reachability_) { + GULLogError(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode000], + @"Cannot change reachability API while reachability is running. " + @"Call stop first."); + return; + } + reachabilityApi_ = reachabilityApi; +} + +@synthesize reachabilityStatus = reachabilityStatus_; +@synthesize host = host_; +@synthesize reachabilityDelegate = reachabilityDelegate_; + +- (BOOL)isActive { + return reachability_ != nil; +} + +- (void)setReachabilityDelegate:(id)reachabilityDelegate { + if (reachabilityDelegate && + (![(NSObject *)reachabilityDelegate conformsToProtocol:@protocol(GULReachabilityDelegate)])) { + GULLogError(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-NET%06ld", (long)kGULReachabilityMessageCode005], + @"Reachability delegate doesn't conform to Reachability protocol."); + return; + } + reachabilityDelegate_ = reachabilityDelegate; +} + +- (instancetype)initWithReachabilityDelegate:(id)reachabilityDelegate + withHost:(NSString *)host { + self = [super init]; + + if (!host || !host.length) { + GULLogError(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode001], + @"Invalid host specified"); + return nil; + } + if (self) { + [self setReachabilityDelegate:reachabilityDelegate]; + reachabilityApi_ = &kGULDefaultReachabilityApi; + reachabilityStatus_ = kGULReachabilityUnknown; + host_ = [host copy]; + reachability_ = nil; + } + return self; +} + +- (void)dealloc { + reachabilityDelegate_ = nil; + [self stop]; +} + +- (BOOL)start { + if (!reachability_) { + reachability_ = reachabilityApi_->createWithNameFn(kCFAllocatorDefault, [host_ UTF8String]); + if (!reachability_) { + return NO; + } + SCNetworkReachabilityContext context = { + 0, /* version */ + (__bridge void *)(self), /* info (passed as last parameter to reachability callback) */ + NULL, /* retain */ + NULL, /* release */ + NULL /* copyDescription */ + }; + if (!reachabilityApi_->setCallbackFn(reachability_, ReachabilityCallback, &context) || + !reachabilityApi_->scheduleWithRunLoopFn(reachability_, CFRunLoopGetMain(), + kCFRunLoopCommonModes)) { + reachabilityApi_->releaseFn(reachability_); + reachability_ = nil; + + GULLogError(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode002], + @"Failed to start reachability handle"); + return NO; + } + } + GULLogDebug(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode003], + @"Monitoring the network status"); + return YES; +} + +- (void)stop { + if (reachability_) { + reachabilityStatus_ = kGULReachabilityUnknown; + reachabilityApi_->unscheduleFromRunLoopFn(reachability_, CFRunLoopGetMain(), + kCFRunLoopCommonModes); + reachabilityApi_->releaseFn(reachability_); + reachability_ = nil; + } +} + +- (GULReachabilityStatus)statusForFlags:(SCNetworkReachabilityFlags)flags { + GULReachabilityStatus status = kGULReachabilityNotReachable; + // If the Reachable flag is not set, we definitely don't have connectivity. + if (flags & kSCNetworkReachabilityFlagsReachable) { + // Reachable flag is set. Check further flags. + if (!(flags & kSCNetworkReachabilityFlagsConnectionRequired)) { +// Connection required flag is not set, so we have connectivity. +#if TARGET_OS_IOS || TARGET_OS_TV + status = (flags & kSCNetworkReachabilityFlagsIsWWAN) ? kGULReachabilityViaCellular + : kGULReachabilityViaWifi; +#elif TARGET_OS_OSX + status = kGULReachabilityViaWifi; +#endif + } else if ((flags & (kSCNetworkReachabilityFlagsConnectionOnDemand | + kSCNetworkReachabilityFlagsConnectionOnTraffic)) && + !(flags & kSCNetworkReachabilityFlagsInterventionRequired)) { +// If the connection on demand or connection on traffic flag is set, and user intervention +// is not required, we have connectivity. +#if TARGET_OS_IOS || TARGET_OS_TV + status = (flags & kSCNetworkReachabilityFlagsIsWWAN) ? kGULReachabilityViaCellular + : kGULReachabilityViaWifi; +#elif TARGET_OS_OSX + status = kGULReachabilityViaWifi; +#endif + } + } + return status; +} + +- (void)reachabilityFlagsChanged:(SCNetworkReachabilityFlags)flags { + GULReachabilityStatus status = [self statusForFlags:flags]; + if (reachabilityStatus_ != status) { + NSString *reachabilityStatusString; + if (status == kGULReachabilityUnknown) { + reachabilityStatusString = kGULReachabilityUnknownStatus; + } else { + reachabilityStatusString = (status == kGULReachabilityNotReachable) + ? kGULReachabilityDisconnectedStatus + : kGULReachabilityConnectedStatus; + } + + GULLogDebug(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode004], + @"Network status has changed. Code:%@, status:%@", @(status), + reachabilityStatusString); + reachabilityStatus_ = status; + [reachabilityDelegate_ reachability:self statusChanged:reachabilityStatus_]; + } +} + +@end + +static void ReachabilityCallback(SCNetworkReachabilityRef reachability, + SCNetworkReachabilityFlags flags, + void *info) { + GULReachabilityChecker *checker = (__bridge GULReachabilityChecker *)info; + [checker reachabilityFlagsChanged:flags]; +} + +// This function used to be at the top of the file, but it was moved here +// as a workaround for a suspected compiler bug. When compiled in Release mode +// and run on an iOS device with WiFi disabled, the reachability code crashed +// when calling SCNetworkReachabilityScheduleWithRunLoop, or shortly thereafter. +// After unsuccessfully trying to diagnose the cause of the crash, it was +// discovered that moving this function to the end of the file magically fixed +// the crash. If you are going to edit this file, exercise caution and make sure +// to test thoroughly with an iOS device under various network conditions. +const NSString *GULReachabilityStatusString(GULReachabilityStatus status) { + switch (status) { + case kGULReachabilityUnknown: + return @"Reachability Unknown"; + + case kGULReachabilityNotReachable: + return @"Not reachable"; + + case kGULReachabilityViaWifi: + return @"Reachable via Wifi"; + + case kGULReachabilityViaCellular: + return @"Reachable via Cellular Data"; + + default: + return [NSString stringWithFormat:@"Invalid reachability status %d", (int)status]; + } +} diff --git a/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityChecker.h b/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityChecker.h new file mode 100644 index 0000000000..b317a0be73 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityChecker.h @@ -0,0 +1,77 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +/// Reachability Status +typedef enum { + kGULReachabilityUnknown, ///< Have not yet checked or been notified whether host is reachable. + kGULReachabilityNotReachable, ///< Host is not reachable. + kGULReachabilityViaWifi, ///< Host is reachable via Wifi. + kGULReachabilityViaCellular, ///< Host is reachable via cellular. +} GULReachabilityStatus; + +const NSString *GULReachabilityStatusString(GULReachabilityStatus status); + +@class GULReachabilityChecker; + +/// Google Analytics iOS Reachability Checker. +@protocol GULReachabilityDelegate +@required +/// Called when network status has changed. +- (void)reachability:(GULReachabilityChecker *)reachability + statusChanged:(GULReachabilityStatus)status; +@end + +/// Google Analytics iOS Network Status Checker. +@interface GULReachabilityChecker : NSObject + +/// The last known reachability status, or GULReachabilityStatusUnknown if the +/// checker is not active. +@property(nonatomic, readonly) GULReachabilityStatus reachabilityStatus; +/// The host to which reachability status is to be checked. +@property(nonatomic, copy, readonly) NSString *host; +/// The delegate to be notified of reachability status changes. +@property(nonatomic, weak) id reachabilityDelegate; +/// `YES` if the reachability checker is active, `NO` otherwise. +@property(nonatomic, readonly) BOOL isActive; + +/// Initialize the reachability checker. Note that you must call start to begin checking for and +/// receiving notifications about network status changes. +/// +/// @param reachabilityDelegate The delegate to be notified when reachability status to host +/// changes. +/// +/// @param host The name of the host. +/// +- (instancetype)initWithReachabilityDelegate:(id)reachabilityDelegate + withHost:(NSString *)host; + +- (instancetype)init NS_UNAVAILABLE; + +/// Start checking for reachability to the specified host. This has no effect if the status +/// checker is already checking for connectivity. +/// +/// @return `YES` if initiating status checking was successful or the status checking has already +/// been initiated, `NO` otherwise. +- (BOOL)start; + +/// Stop checking for reachability to the specified host. This has no effect if the status +/// checker is not checking for connectivity. +- (void)stop; + +@end diff --git a/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityMessageCode.h b/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityMessageCode.h new file mode 100644 index 0000000000..283cdd5c10 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityMessageCode.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Make sure these codes do not overlap with any contained in the FIRAMessageCode enum. +typedef NS_ENUM(NSInteger, GULReachabilityMessageCode) { + // GULReachabilityChecker.m + kGULReachabilityMessageCode000 = 902000, // I-NET902000 + kGULReachabilityMessageCode001 = 902001, // I-NET902001 + kGULReachabilityMessageCode002 = 902002, // I-NET902002 + kGULReachabilityMessageCode003 = 902003, // I-NET902003 + kGULReachabilityMessageCode004 = 902004, // I-NET902004 + kGULReachabilityMessageCode005 = 902005, // I-NET902005 + kGULReachabilityMessageCode006 = 902006, // I-NET902006 +}; diff --git a/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/GULUserDefaults.m b/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/GULUserDefaults.m new file mode 100644 index 0000000000..1b1bafb76e --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/GULUserDefaults.m @@ -0,0 +1,235 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULUserDefaults.h" + +#import + +NS_ASSUME_NONNULL_BEGIN + +static NSTimeInterval const kGULSynchronizeInterval = 1.0; + +static NSString *const kGULLogFormat = @"I-GUL%06ld"; + +static GULLoggerService kGULLogUserDefaultsService = @"[GoogleUtilities/UserDefaults]"; + +typedef NS_ENUM(NSInteger, GULUDMessageCode) { + GULUDMessageCodeInvalidKeyGet = 1, + GULUDMessageCodeInvalidKeySet = 2, + GULUDMessageCodeInvalidObjectSet = 3, + GULUDMessageCodeSynchronizeFailed = 4, +}; + +@interface GULUserDefaults () + +/// Equivalent to the suite name for NSUserDefaults. +@property(readonly) CFStringRef appNameRef; + +@property(atomic) BOOL isPreferenceFileExcluded; + +@end + +@implementation GULUserDefaults { + // The application name is the same with the suite name of the NSUserDefaults, and it is used for + // preferences. + CFStringRef _appNameRef; +} + ++ (GULUserDefaults *)standardUserDefaults { + static GULUserDefaults *standardUserDefaults; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + standardUserDefaults = [[GULUserDefaults alloc] init]; + }); + return standardUserDefaults; +} + +- (instancetype)init { + return [self initWithSuiteName:nil]; +} + +- (instancetype)initWithSuiteName:(nullable NSString *)suiteName { + self = [super init]; + + NSString *name = [suiteName copy]; + + if (self) { + // `kCFPreferencesCurrentApplication` maps to the same defaults database as + // `[NSUserDefaults standardUserDefaults]`. + _appNameRef = + name.length ? (__bridge_retained CFStringRef)name : kCFPreferencesCurrentApplication; + } + + return self; +} + +- (void)dealloc { + // If we're using a custom `_appNameRef` it needs to be released. If it's a constant, it shouldn't + // need to be released since we don't own it. + if (CFStringCompare(_appNameRef, kCFPreferencesCurrentApplication, 0) != kCFCompareEqualTo) { + CFRelease(_appNameRef); + } + + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(synchronize) + object:nil]; +} + +- (nullable id)objectForKey:(NSString *)defaultName { + NSString *key = [defaultName copy]; + if (![key isKindOfClass:[NSString class]] || !key.length) { + GULLogWarning(@"", NO, + [NSString stringWithFormat:kGULLogFormat, (long)GULUDMessageCodeInvalidKeyGet], + @"Cannot get object for invalid user default key."); + return nil; + } + return (__bridge_transfer id)CFPreferencesCopyAppValue((__bridge CFStringRef)key, _appNameRef); +} + +- (void)setObject:(nullable id)value forKey:(NSString *)defaultName { + NSString *key = [defaultName copy]; + if (![key isKindOfClass:[NSString class]] || !key.length) { + GULLogWarning(kGULLogUserDefaultsService, NO, + [NSString stringWithFormat:kGULLogFormat, (long)GULUDMessageCodeInvalidKeySet], + @"Cannot set object for invalid user default key."); + return; + } + if (!value) { + CFPreferencesSetAppValue((__bridge CFStringRef)key, NULL, _appNameRef); + [self scheduleSynchronize]; + return; + } + BOOL isAcceptableValue = + [value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]] || + [value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]] || + [value isKindOfClass:[NSDate class]] || [value isKindOfClass:[NSData class]]; + if (!isAcceptableValue) { + GULLogWarning(kGULLogUserDefaultsService, NO, + [NSString stringWithFormat:kGULLogFormat, (long)GULUDMessageCodeInvalidObjectSet], + @"Cannot set invalid object to user defaults. Must be a string, number, array, " + @"dictionary, date, or data. Value: %@", + value); + return; + } + + CFPreferencesSetAppValue((__bridge CFStringRef)key, (__bridge CFStringRef)value, _appNameRef); + [self scheduleSynchronize]; +} + +- (void)removeObjectForKey:(NSString *)key { + [self setObject:nil forKey:key]; +} + +#pragma mark - Getters + +- (NSInteger)integerForKey:(NSString *)defaultName { + NSNumber *object = [self objectForKey:defaultName]; + return object.integerValue; +} + +- (float)floatForKey:(NSString *)defaultName { + NSNumber *object = [self objectForKey:defaultName]; + return object.floatValue; +} + +- (double)doubleForKey:(NSString *)defaultName { + NSNumber *object = [self objectForKey:defaultName]; + return object.doubleValue; +} + +- (BOOL)boolForKey:(NSString *)defaultName { + NSNumber *object = [self objectForKey:defaultName]; + return object.boolValue; +} + +- (nullable NSString *)stringForKey:(NSString *)defaultName { + return [self objectForKey:defaultName]; +} + +- (nullable NSArray *)arrayForKey:(NSString *)defaultName { + return [self objectForKey:defaultName]; +} + +- (nullable NSDictionary *)dictionaryForKey:(NSString *)defaultName { + return [self objectForKey:defaultName]; +} + +#pragma mark - Setters + +- (void)setInteger:(NSInteger)integer forKey:(NSString *)defaultName { + [self setObject:@(integer) forKey:defaultName]; +} + +- (void)setFloat:(float)value forKey:(NSString *)defaultName { + [self setObject:@(value) forKey:defaultName]; +} + +- (void)setDouble:(double)doubleNumber forKey:(NSString *)defaultName { + [self setObject:@(doubleNumber) forKey:defaultName]; +} + +- (void)setBool:(BOOL)boolValue forKey:(NSString *)defaultName { + [self setObject:@(boolValue) forKey:defaultName]; +} + +#pragma mark - Save data + +- (void)synchronize { + if (!CFPreferencesAppSynchronize(_appNameRef)) { + GULLogError(kGULLogUserDefaultsService, NO, + [NSString stringWithFormat:kGULLogFormat, (long)GULUDMessageCodeSynchronizeFailed], + @"Cannot synchronize user defaults to disk"); + } +} + +#pragma mark - Private methods + +/// Removes all values from the search list entry specified by 'domainName', the current user, and +/// any host. The change is persistent. Equivalent to -removePersistentDomainForName: of +/// NSUserDefaults. +- (void)clearAllData { + // On macOS, using `kCFPreferencesCurrentHost` will not set all the keys necessary to match + // `NSUserDefaults`. +#if TARGET_OS_MAC + CFStringRef host = kCFPreferencesAnyHost; +#else + CFStringRef host = kCFPreferencesCurrentHost; +#endif // TARGET_OS_OSX + + CFArrayRef keyList = CFPreferencesCopyKeyList(_appNameRef, kCFPreferencesCurrentUser, host); + if (!keyList) { + return; + } + + CFPreferencesSetMultiple(NULL, keyList, _appNameRef, kCFPreferencesCurrentUser, host); + CFRelease(keyList); + [self scheduleSynchronize]; +} + +- (void)scheduleSynchronize { + // Synchronize data using a timer so that multiple set... calls can be coalesced under one + // synchronize. + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(synchronize) + object:nil]; + // This method may be called on multiple queues (due to set... methods can be called on any queue) + // synchronize can be scheduled on different queues, so make sure that it does not crash. If this + // instance goes away, self will be released also, no one will retain it and the schedule won't be + // called. + [self performSelector:@selector(synchronize) withObject:nil afterDelay:kGULSynchronizeInterval]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/Private/GULUserDefaults.h b/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/Private/GULUserDefaults.h new file mode 100644 index 0000000000..0d04781841 --- /dev/null +++ b/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/Private/GULUserDefaults.h @@ -0,0 +1,110 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// A thread-safe user defaults that uses C functions from CFPreferences.h instead of +/// `NSUserDefaults`. This is to avoid sending an `NSNotification` when it's changed from a +/// background thread to avoid crashing. // TODO: Insert radar number here. +@interface GULUserDefaults : NSObject + +/// A shared user defaults similar to +[NSUserDefaults standardUserDefaults] and accesses the same +/// data of the standardUserDefaults. ++ (GULUserDefaults *)standardUserDefaults; + +/// Initializes preferences with a suite name that is the same with the NSUserDefaults' suite name. +/// Both of CFPreferences and NSUserDefaults share the same plist file so their data will exactly +/// the same. +/// +/// @param suiteName The name of the suite of the user defaults. +- (instancetype)initWithSuiteName:(nullable NSString *)suiteName; + +#pragma mark - Getters + +/// Searches the receiver's search list for a default with the key 'defaultName' and return it. If +/// another process has changed defaults in the search list, NSUserDefaults will automatically +/// update to the latest values. If the key in question has been marked as ubiquitous via a Defaults +/// Configuration File, the latest value may not be immediately available, and the registered value +/// will be returned instead. +- (nullable id)objectForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it will return nil if the value is not an NSArray. +- (nullable NSArray *)arrayForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it will return nil if the value +/// is not an NSDictionary. +- (nullable NSDictionary *)dictionaryForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it will convert NSNumber values to their NSString +/// representation. If a non-string non-number value is found, nil will be returned. +- (nullable NSString *)stringForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it converts the returned value to an NSInteger. If the +/// value is an NSNumber, the result of -integerValue will be returned. If the value is an NSString, +/// it will be converted to NSInteger if possible. If the value is a boolean, it will be converted +/// to either 1 for YES or 0 for NO. If the value is absent or can't be converted to an integer, 0 +/// will be returned. +- (NSInteger)integerForKey:(NSString *)defaultName; + +/// Similar to -integerForKey:, except that it returns a float, and boolean values will not be +/// converted. +- (float)floatForKey:(NSString *)defaultName; + +/// Similar to -integerForKey:, except that it returns a double, and boolean values will not be +/// converted. +- (double)doubleForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it converts the returned value to a BOOL. If the value +/// is an NSNumber, NO will be returned if the value is 0, YES otherwise. If the value is an +/// NSString, values of "YES" or "1" will return YES, and values of "NO", "0", or any other string +/// will return NO. If the value is absent or can't be converted to a BOOL, NO will be returned. +- (BOOL)boolForKey:(NSString *)defaultName; + +#pragma mark - Setters + +/// Immediately stores a value (or removes the value if `nil` is passed as the value) for the +/// provided key in the search list entry for the receiver's suite name in the current user and any +/// host, then asynchronously stores the value persistently, where it is made available to other +/// processes. +- (void)setObject:(nullable id)value forKey:(NSString *)defaultName; + +/// Equivalent to -setObject:forKey: except that the value is converted from a float to an NSNumber. +- (void)setFloat:(float)value forKey:(NSString *)defaultName; + +/// Equivalent to -setObject:forKey: except that the value is converted from a double to an +/// NSNumber. +- (void)setDouble:(double)value forKey:(NSString *)defaultName; + +/// Equivalent to -setObject:forKey: except that the value is converted from an NSInteger to an +/// NSNumber. +- (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName; + +/// Equivalent to -setObject:forKey: except that the value is converted from a BOOL to an NSNumber. +- (void)setBool:(BOOL)value forKey:(NSString *)defaultName; + +#pragma mark - Removing Defaults + +/// Equivalent to -[... setObject:nil forKey:defaultName] +- (void)removeObjectForKey:(NSString *)defaultName; + +#pragma mark - Save data + +/// Blocks the calling thread until all in-progress set operations have completed. +- (void)synchronize; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/GoogleUtilities/LICENSE b/Pods/GoogleUtilities/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/Pods/GoogleUtilities/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Pods/GoogleUtilities/README.md b/Pods/GoogleUtilities/README.md new file mode 100644 index 0000000000..eb6ea333f8 --- /dev/null +++ b/Pods/GoogleUtilities/README.md @@ -0,0 +1,180 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseInAppMessagingDisplay, FirebaseMessaging and +FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +An experimental Carthage distribution is now available. See +[Carthage](Carthage.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[the Auth Sample README](Example/Auth/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/Pods/Headers/Private/Firebase/Firebase.h b/Pods/Headers/Private/Firebase/Firebase.h new file mode 120000 index 0000000000..07ac6eb193 --- /dev/null +++ b/Pods/Headers/Private/Firebase/Firebase.h @@ -0,0 +1 @@ +../../../Firebase/CoreOnly/Sources/Firebase.h \ No newline at end of file diff --git a/Pods/Headers/Public/Firebase/Firebase.h b/Pods/Headers/Public/Firebase/Firebase.h new file mode 120000 index 0000000000..07ac6eb193 --- /dev/null +++ b/Pods/Headers/Public/Firebase/Firebase.h @@ -0,0 +1 @@ +../../../Firebase/CoreOnly/Sources/Firebase.h \ No newline at end of file diff --git a/Pods/Local Podspecs/MobilePlayer.podspec.json b/Pods/Local Podspecs/MobilePlayer.podspec.json new file mode 100644 index 0000000000..bfb9e615a1 --- /dev/null +++ b/Pods/Local Podspecs/MobilePlayer.podspec.json @@ -0,0 +1,27 @@ +{ + "name": "MobilePlayer", + "version": "1.2.0", + "summary": "A powerful and completely customizable media player for iOS.", + "homepage": "https://github.com/mobileplayer/mobileplayer-ios", + "license": "CC", + "authors": { + "Barış Şencan": "baris.sncn@gmail.com", + "Cem Olcay": "ccemolcay@gmail.com" + }, + "source": { + "git": "https://github.com/mobileplayer/mobileplayer-ios.git", + "tag": "1.2.0" + }, + "platforms": { + "ios": "8.0" + }, + "requires_arc": true, + "frameworks": [ + "UIKit", + "MediaPlayer" + ], + "source_files": "MobilePlayer/**/*.swift", + "resource_bundles": { + "MobilePlayer": "MobilePlayer/**/*.png" + } +} diff --git a/Pods/Local Podspecs/RCMarkdownParser.podspec.json b/Pods/Local Podspecs/RCMarkdownParser.podspec.json new file mode 100644 index 0000000000..89970aaabf --- /dev/null +++ b/Pods/Local Podspecs/RCMarkdownParser.podspec.json @@ -0,0 +1,20 @@ +{ + "name": "RCMarkdownParser", + "version": "3.0.6", + "summary": "A markdown parser written in swift", + "description": "A parser written to convert a string containing markdown to an NSAttributedString for Rocket.Chat. It was based off of LTMarkdownParser.", + "homepage": "https://github.com/RocketChat/RCMarkdownParser", + "license": "MIT", + "authors": { + "Matheus Cardoso": "matheus@cardo.so" + }, + "source": { + "git": "https://github.com/RocketChat/RCMarkdownParser.git", + "tag": "3.0.6" + }, + "platforms": { + "ios": "8.0" + }, + "requires_arc": true, + "source_files": "Pod/Classes/**/*" +} diff --git a/Pods/Local Podspecs/RocketChatViewController.podspec.json b/Pods/Local Podspecs/RocketChatViewController.podspec.json new file mode 100644 index 0000000000..6ba8e3cfa0 --- /dev/null +++ b/Pods/Local Podspecs/RocketChatViewController.podspec.json @@ -0,0 +1,46 @@ +{ + "name": "RocketChatViewController", + "version": "0.1.0", + "summary": "RocketChatViewController is a light weight library that allows you to implement a chat on iOS.", + "description": "TODO: Add long description of the pod here.", + "homepage": "https://github.com/RocketChat/RocketChatViewController", + "license": { + "type": "MIT", + "file": "LICENSE" + }, + "authors": { + "Rocket Chat": "ios@rocket.chat" + }, + "source": { + "git": "https://github.com/RocketChat/RocketChatViewController", + "tag": "0.1.0" + }, + "social_media_url": "https://twitter.com/RocketChat", + "platforms": { + "ios": "11.0" + }, + "subspecs": [ + { + "name": "ViewController", + "platforms": { + "ios": "11.0" + }, + "source_files": "RocketChatViewController/Classes/**/*", + "dependencies": { + "DifferenceKit": [ + "~> 0.7.2" + ] + } + }, + { + "name": "Composer", + "platforms": { + "ios": "11.0" + }, + "source_files": "Composer/Classes/**/*", + "resources": [ + "Composer/Assets/*" + ] + } + ] +} diff --git a/Pods/Local Podspecs/SimpleImageViewer.podspec.json b/Pods/Local Podspecs/SimpleImageViewer.podspec.json new file mode 100644 index 0000000000..c496faed08 --- /dev/null +++ b/Pods/Local Podspecs/SimpleImageViewer.podspec.json @@ -0,0 +1,31 @@ +{ + "name": "SimpleImageViewer", + "platforms": { + "ios": "9.0" + }, + "summary": "A snappy image viewer with zoom and interactive dismissal transition.", + "requires_arc": true, + "version": "1.2.0", + "license": { + "type": "MIT", + "file": "LICENSE" + }, + "authors": { + "Lucas": "lucas@afrogleap.com" + }, + "homepage": "https://github.com/aFrogleap/SimpleImageViewer", + "source": { + "git": "https://github.com/aFrogleap/SimpleImageViewer.git", + "tag": "1.2.0" + }, + "source_files": "ImageViewer/**/*.{swift}", + "resources": [ + "ImageViewer/**/*.{xib}", + "ImageViewer/**/*.{xcassets}" + ], + "dependencies": { + "FLAnimatedImage": [ + + ] + } +} diff --git a/Pods/MBProgressHUD/LICENSE b/Pods/MBProgressHUD/LICENSE new file mode 100644 index 0000000000..1c0d59bb85 --- /dev/null +++ b/Pods/MBProgressHUD/LICENSE @@ -0,0 +1,19 @@ +Copyright © 2009-2016 Matej Bukovinski + +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. \ No newline at end of file diff --git a/Pods/MBProgressHUD/MBProgressHUD.h b/Pods/MBProgressHUD/MBProgressHUD.h new file mode 100644 index 0000000000..a7b54ee978 --- /dev/null +++ b/Pods/MBProgressHUD/MBProgressHUD.h @@ -0,0 +1,443 @@ +// +// MBProgressHUD.h +// Version 1.1.0 +// Created by Matej Bukovinski on 2.4.09. +// + +// This code is distributed under the terms and conditions of the MIT license. + +// Copyright © 2009-2016 Matej Bukovinski +// +// 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 +#import +#import + +@class MBBackgroundView; +@protocol MBProgressHUDDelegate; + + +extern CGFloat const MBProgressMaxOffset; + +typedef NS_ENUM(NSInteger, MBProgressHUDMode) { + /// UIActivityIndicatorView. + MBProgressHUDModeIndeterminate, + /// A round, pie-chart like, progress view. + MBProgressHUDModeDeterminate, + /// Horizontal progress bar. + MBProgressHUDModeDeterminateHorizontalBar, + /// Ring-shaped progress view. + MBProgressHUDModeAnnularDeterminate, + /// Shows a custom view. + MBProgressHUDModeCustomView, + /// Shows only labels. + MBProgressHUDModeText +}; + +typedef NS_ENUM(NSInteger, MBProgressHUDAnimation) { + /// Opacity animation + MBProgressHUDAnimationFade, + /// Opacity + scale animation (zoom in when appearing zoom out when disappearing) + MBProgressHUDAnimationZoom, + /// Opacity + scale animation (zoom out style) + MBProgressHUDAnimationZoomOut, + /// Opacity + scale animation (zoom in style) + MBProgressHUDAnimationZoomIn +}; + +typedef NS_ENUM(NSInteger, MBProgressHUDBackgroundStyle) { + /// Solid color background + MBProgressHUDBackgroundStyleSolidColor, + /// UIVisualEffectView or UIToolbar.layer background view + MBProgressHUDBackgroundStyleBlur +}; + +typedef void (^MBProgressHUDCompletionBlock)(void); + + +NS_ASSUME_NONNULL_BEGIN + + +/** + * Displays a simple HUD window containing a progress indicator and two optional labels for short messages. + * + * This is a simple drop-in class for displaying a progress HUD view similar to Apple's private UIProgressHUD class. + * The MBProgressHUD window spans over the entire space given to it by the initWithFrame: constructor and catches all + * user input on this region, thereby preventing the user operations on components below the view. + * + * @note To still allow touches to pass through the HUD, you can set hud.userInteractionEnabled = NO. + * @attention MBProgressHUD is a UI class and should therefore only be accessed on the main thread. + */ +@interface MBProgressHUD : UIView + +/** + * Creates a new HUD, adds it to provided view and shows it. The counterpart to this method is hideHUDForView:animated:. + * + * @note This method sets removeFromSuperViewOnHide. The HUD will automatically be removed from the view hierarchy when hidden. + * + * @param view The view that the HUD will be added to + * @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use + * animations while appearing. + * @return A reference to the created HUD. + * + * @see hideHUDForView:animated: + * @see animationType + */ ++ (instancetype)showHUDAddedTo:(UIView *)view animated:(BOOL)animated; + +/// @name Showing and hiding + +/** + * Finds the top-most HUD subview that hasn't finished and hides it. The counterpart to this method is showHUDAddedTo:animated:. + * + * @note This method sets removeFromSuperViewOnHide. The HUD will automatically be removed from the view hierarchy when hidden. + * + * @param view The view that is going to be searched for a HUD subview. + * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use + * animations while disappearing. + * @return YES if a HUD was found and removed, NO otherwise. + * + * @see showHUDAddedTo:animated: + * @see animationType + */ ++ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated; + +/** + * Finds the top-most HUD subview that hasn't finished and returns it. + * + * @param view The view that is going to be searched. + * @return A reference to the last HUD subview discovered. + */ ++ (nullable MBProgressHUD *)HUDForView:(UIView *)view; + +/** + * A convenience constructor that initializes the HUD with the view's bounds. Calls the designated constructor with + * view.bounds as the parameter. + * + * @param view The view instance that will provide the bounds for the HUD. Should be the same instance as + * the HUD's superview (i.e., the view that the HUD will be added to). + */ +- (instancetype)initWithView:(UIView *)view; + +/** + * Displays the HUD. + * + * @note You need to make sure that the main thread completes its run loop soon after this method call so that + * the user interface can be updated. Call this method when your task is already set up to be executed in a new thread + * (e.g., when using something like NSOperation or making an asynchronous call like NSURLRequest). + * + * @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use + * animations while appearing. + * + * @see animationType + */ +- (void)showAnimated:(BOOL)animated; + +/** + * Hides the HUD. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to + * hide the HUD when your task completes. + * + * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use + * animations while disappearing. + * + * @see animationType + */ +- (void)hideAnimated:(BOOL)animated; + +/** + * Hides the HUD after a delay. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to + * hide the HUD when your task completes. + * + * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use + * animations while disappearing. + * @param delay Delay in seconds until the HUD is hidden. + * + * @see animationType + */ +- (void)hideAnimated:(BOOL)animated afterDelay:(NSTimeInterval)delay; + +/** + * The HUD delegate object. Receives HUD state notifications. + */ +@property (weak, nonatomic) id delegate; + +/** + * Called after the HUD is hiden. + */ +@property (copy, nullable) MBProgressHUDCompletionBlock completionBlock; + +/* + * Grace period is the time (in seconds) that the invoked method may be run without + * showing the HUD. If the task finishes before the grace time runs out, the HUD will + * not be shown at all. + * This may be used to prevent HUD display for very short tasks. + * Defaults to 0 (no grace time). + */ +@property (assign, nonatomic) NSTimeInterval graceTime; + +/** + * The minimum time (in seconds) that the HUD is shown. + * This avoids the problem of the HUD being shown and than instantly hidden. + * Defaults to 0 (no minimum show time). + */ +@property (assign, nonatomic) NSTimeInterval minShowTime; + +/** + * Removes the HUD from its parent view when hidden. + * Defaults to NO. + */ +@property (assign, nonatomic) BOOL removeFromSuperViewOnHide; + +/// @name Appearance + +/** + * MBProgressHUD operation mode. The default is MBProgressHUDModeIndeterminate. + */ +@property (assign, nonatomic) MBProgressHUDMode mode; + +/** + * A color that gets forwarded to all labels and supported indicators. Also sets the tintColor + * for custom views on iOS 7+. Set to nil to manage color individually. + * Defaults to semi-translucent black on iOS 7 and later and white on earlier iOS versions. + */ +@property (strong, nonatomic, nullable) UIColor *contentColor UI_APPEARANCE_SELECTOR; + +/** + * The animation type that should be used when the HUD is shown and hidden. + */ +@property (assign, nonatomic) MBProgressHUDAnimation animationType UI_APPEARANCE_SELECTOR; + +/** + * The bezel offset relative to the center of the view. You can use MBProgressMaxOffset + * and -MBProgressMaxOffset to move the HUD all the way to the screen edge in each direction. + * E.g., CGPointMake(0.f, MBProgressMaxOffset) would position the HUD centered on the bottom edge. + */ +@property (assign, nonatomic) CGPoint offset UI_APPEARANCE_SELECTOR; + +/** + * The amount of space between the HUD edge and the HUD elements (labels, indicators or custom views). + * This also represents the minimum bezel distance to the edge of the HUD view. + * Defaults to 20.f + */ +@property (assign, nonatomic) CGFloat margin UI_APPEARANCE_SELECTOR; + +/** + * The minimum size of the HUD bezel. Defaults to CGSizeZero (no minimum size). + */ +@property (assign, nonatomic) CGSize minSize UI_APPEARANCE_SELECTOR; + +/** + * Force the HUD dimensions to be equal if possible. + */ +@property (assign, nonatomic, getter = isSquare) BOOL square UI_APPEARANCE_SELECTOR; + +/** + * When enabled, the bezel center gets slightly affected by the device accelerometer data. + * Has no effect on iOS < 7.0. Defaults to YES. + */ +@property (assign, nonatomic, getter=areDefaultMotionEffectsEnabled) BOOL defaultMotionEffectsEnabled UI_APPEARANCE_SELECTOR; + +/// @name Progress + +/** + * The progress of the progress indicator, from 0.0 to 1.0. Defaults to 0.0. + */ +@property (assign, nonatomic) float progress; + +/// @name ProgressObject + +/** + * The NSProgress object feeding the progress information to the progress indicator. + */ +@property (strong, nonatomic, nullable) NSProgress *progressObject; + +/// @name Views + +/** + * The view containing the labels and indicator (or customView). + */ +@property (strong, nonatomic, readonly) MBBackgroundView *bezelView; + +/** + * View covering the entire HUD area, placed behind bezelView. + */ +@property (strong, nonatomic, readonly) MBBackgroundView *backgroundView; + +/** + * The UIView (e.g., a UIImageView) to be shown when the HUD is in MBProgressHUDModeCustomView. + * The view should implement intrinsicContentSize for proper sizing. For best results use approximately 37 by 37 pixels. + */ +@property (strong, nonatomic, nullable) UIView *customView; + +/** + * A label that holds an optional short message to be displayed below the activity indicator. The HUD is automatically resized to fit + * the entire text. + */ +@property (strong, nonatomic, readonly) UILabel *label; + +/** + * A label that holds an optional details message displayed below the labelText message. The details text can span multiple lines. + */ +@property (strong, nonatomic, readonly) UILabel *detailsLabel; + +/** + * A button that is placed below the labels. Visible only if a target / action is added. + */ +@property (strong, nonatomic, readonly) UIButton *button; + +@end + + +@protocol MBProgressHUDDelegate + +@optional + +/** + * Called after the HUD was fully hidden from the screen. + */ +- (void)hudWasHidden:(MBProgressHUD *)hud; + +@end + + +/** + * A progress view for showing definite progress by filling up a circle (pie chart). + */ +@interface MBRoundProgressView : UIView + +/** + * Progress (0.0 to 1.0) + */ +@property (nonatomic, assign) float progress; + +/** + * Indicator progress color. + * Defaults to white [UIColor whiteColor]. + */ +@property (nonatomic, strong) UIColor *progressTintColor; + +/** + * Indicator background (non-progress) color. + * Only applicable on iOS versions older than iOS 7. + * Defaults to translucent white (alpha 0.1). + */ +@property (nonatomic, strong) UIColor *backgroundTintColor; + +/* + * Display mode - NO = round or YES = annular. Defaults to round. + */ +@property (nonatomic, assign, getter = isAnnular) BOOL annular; + +@end + + +/** + * A flat bar progress view. + */ +@interface MBBarProgressView : UIView + +/** + * Progress (0.0 to 1.0) + */ +@property (nonatomic, assign) float progress; + +/** + * Bar border line color. + * Defaults to white [UIColor whiteColor]. + */ +@property (nonatomic, strong) UIColor *lineColor; + +/** + * Bar background color. + * Defaults to clear [UIColor clearColor]; + */ +@property (nonatomic, strong) UIColor *progressRemainingColor; + +/** + * Bar progress color. + * Defaults to white [UIColor whiteColor]. + */ +@property (nonatomic, strong) UIColor *progressColor; + +@end + + +@interface MBBackgroundView : UIView + +/** + * The background style. + * Defaults to MBProgressHUDBackgroundStyleBlur on iOS 7 or later and MBProgressHUDBackgroundStyleSolidColor otherwise. + * @note Due to iOS 7 not supporting UIVisualEffectView, the blur effect differs slightly between iOS 7 and later versions. + */ +@property (nonatomic) MBProgressHUDBackgroundStyle style; + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 || TARGET_OS_TV +/** + * The blur effect style, when using MBProgressHUDBackgroundStyleBlur. + * Defaults to UIBlurEffectStyleLight. + */ +@property (nonatomic) UIBlurEffectStyle blurEffectStyle; +#endif + +/** + * The background color or the blur tint color. + * @note Due to iOS 7 not supporting UIVisualEffectView, the blur effect differs slightly between iOS 7 and later versions. + */ +@property (nonatomic, strong) UIColor *color; + +@end + +@interface MBProgressHUD (Deprecated) + ++ (NSArray *)allHUDsForView:(UIView *)view __attribute__((deprecated("Store references when using more than one HUD per view."))); ++ (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated __attribute__((deprecated("Store references when using more than one HUD per view."))); + +- (id)initWithWindow:(UIWindow *)window __attribute__((deprecated("Use initWithView: instead."))); + +- (void)show:(BOOL)animated __attribute__((deprecated("Use showAnimated: instead."))); +- (void)hide:(BOOL)animated __attribute__((deprecated("Use hideAnimated: instead."))); +- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay __attribute__((deprecated("Use hideAnimated:afterDelay: instead."))); + +- (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated __attribute__((deprecated("Use GCD directly."))); +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block __attribute__((deprecated("Use GCD directly."))); +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block completionBlock:(nullable MBProgressHUDCompletionBlock)completion __attribute__((deprecated("Use GCD directly."))); +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue __attribute__((deprecated("Use GCD directly."))); +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue + completionBlock:(nullable MBProgressHUDCompletionBlock)completion __attribute__((deprecated("Use GCD directly."))); +@property (assign) BOOL taskInProgress __attribute__((deprecated("No longer needed."))); + +@property (nonatomic, copy) NSString *labelText __attribute__((deprecated("Use label.text instead."))); +@property (nonatomic, strong) UIFont *labelFont __attribute__((deprecated("Use label.font instead."))); +@property (nonatomic, strong) UIColor *labelColor __attribute__((deprecated("Use label.textColor instead."))); +@property (nonatomic, copy) NSString *detailsLabelText __attribute__((deprecated("Use detailsLabel.text instead."))); +@property (nonatomic, strong) UIFont *detailsLabelFont __attribute__((deprecated("Use detailsLabel.font instead."))); +@property (nonatomic, strong) UIColor *detailsLabelColor __attribute__((deprecated("Use detailsLabel.textColor instead."))); +@property (assign, nonatomic) CGFloat opacity __attribute__((deprecated("Customize bezelView properties instead."))); +@property (strong, nonatomic) UIColor *color __attribute__((deprecated("Customize the bezelView color instead."))); +@property (assign, nonatomic) CGFloat xOffset __attribute__((deprecated("Set offset.x instead."))); +@property (assign, nonatomic) CGFloat yOffset __attribute__((deprecated("Set offset.y instead."))); +@property (assign, nonatomic) CGFloat cornerRadius __attribute__((deprecated("Set bezelView.layer.cornerRadius instead."))); +@property (assign, nonatomic) BOOL dimBackground __attribute__((deprecated("Customize HUD background properties instead."))); +@property (strong, nonatomic) UIColor *activityIndicatorColor __attribute__((deprecated("Use UIAppearance to customize UIActivityIndicatorView. E.g.: [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = [UIColor redColor];"))); +@property (atomic, assign, readonly) CGSize size __attribute__((deprecated("Get the bezelView.frame.size instead."))); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MBProgressHUD/MBProgressHUD.m b/Pods/MBProgressHUD/MBProgressHUD.m new file mode 100644 index 0000000000..1bcf9e99d7 --- /dev/null +++ b/Pods/MBProgressHUD/MBProgressHUD.m @@ -0,0 +1,1495 @@ +// +// MBProgressHUD.m +// Version 1.1.0 +// Created by Matej Bukovinski on 2.4.09. +// + +#import "MBProgressHUD.h" +#import + + +#ifndef kCFCoreFoundationVersionNumber_iOS_7_0 + #define kCFCoreFoundationVersionNumber_iOS_7_0 847.20 +#endif + +#ifndef kCFCoreFoundationVersionNumber_iOS_8_0 + #define kCFCoreFoundationVersionNumber_iOS_8_0 1129.15 +#endif + +#define MBMainThreadAssert() NSAssert([NSThread isMainThread], @"MBProgressHUD needs to be accessed on the main thread."); + +CGFloat const MBProgressMaxOffset = 1000000.f; + +static const CGFloat MBDefaultPadding = 4.f; +static const CGFloat MBDefaultLabelFontSize = 16.f; +static const CGFloat MBDefaultDetailsLabelFontSize = 12.f; + + +@interface MBProgressHUD () { + // Deprecated + UIColor *_activityIndicatorColor; + CGFloat _opacity; +} + +@property (nonatomic, assign) BOOL useAnimation; +@property (nonatomic, assign, getter=hasFinished) BOOL finished; +@property (nonatomic, strong) UIView *indicator; +@property (nonatomic, strong) NSDate *showStarted; +@property (nonatomic, strong) NSArray *paddingConstraints; +@property (nonatomic, strong) NSArray *bezelConstraints; +@property (nonatomic, strong) UIView *topSpacer; +@property (nonatomic, strong) UIView *bottomSpacer; +@property (nonatomic, weak) NSTimer *graceTimer; +@property (nonatomic, weak) NSTimer *minShowTimer; +@property (nonatomic, weak) NSTimer *hideDelayTimer; +@property (nonatomic, weak) CADisplayLink *progressObjectDisplayLink; + +// Deprecated +@property (assign) BOOL taskInProgress; + +@end + + +@interface MBProgressHUDRoundedButton : UIButton +@end + + +@implementation MBProgressHUD + +#pragma mark - Class methods + ++ (instancetype)showHUDAddedTo:(UIView *)view animated:(BOOL)animated { + MBProgressHUD *hud = [[self alloc] initWithView:view]; + hud.removeFromSuperViewOnHide = YES; + [view addSubview:hud]; + [hud showAnimated:animated]; + return hud; +} + ++ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated { + MBProgressHUD *hud = [self HUDForView:view]; + if (hud != nil) { + hud.removeFromSuperViewOnHide = YES; + [hud hideAnimated:animated]; + return YES; + } + return NO; +} + ++ (MBProgressHUD *)HUDForView:(UIView *)view { + NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator]; + for (UIView *subview in subviewsEnum) { + if ([subview isKindOfClass:self]) { + MBProgressHUD *hud = (MBProgressHUD *)subview; + if (hud.hasFinished == NO) { + return hud; + } + } + } + return nil; +} + +#pragma mark - Lifecycle + +- (void)commonInit { + // Set default values for properties + _animationType = MBProgressHUDAnimationFade; + _mode = MBProgressHUDModeIndeterminate; + _margin = 20.0f; + _opacity = 1.f; + _defaultMotionEffectsEnabled = YES; + + // Default color, depending on the current iOS version + BOOL isLegacy = kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iOS_7_0; + _contentColor = isLegacy ? [UIColor whiteColor] : [UIColor colorWithWhite:0.f alpha:0.7f]; + // Transparent background + self.opaque = NO; + self.backgroundColor = [UIColor clearColor]; + // Make it invisible for now + self.alpha = 0.0f; + self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + self.layer.allowsGroupOpacity = NO; + + [self setupViews]; + [self updateIndicators]; + [self registerForNotifications]; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if ((self = [super initWithFrame:frame])) { + [self commonInit]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + if ((self = [super initWithCoder:aDecoder])) { + [self commonInit]; + } + return self; +} + +- (id)initWithView:(UIView *)view { + NSAssert(view, @"View must not be nil."); + return [self initWithFrame:view.bounds]; +} + +- (void)dealloc { + [self unregisterFromNotifications]; +} + +#pragma mark - Show & hide + +- (void)showAnimated:(BOOL)animated { + MBMainThreadAssert(); + [self.minShowTimer invalidate]; + self.useAnimation = animated; + self.finished = NO; + // If the grace time is set, postpone the HUD display + if (self.graceTime > 0.0) { + NSTimer *timer = [NSTimer timerWithTimeInterval:self.graceTime target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; + self.graceTimer = timer; + } + // ... otherwise show the HUD immediately + else { + [self showUsingAnimation:self.useAnimation]; + } +} + +- (void)hideAnimated:(BOOL)animated { + MBMainThreadAssert(); + [self.graceTimer invalidate]; + self.useAnimation = animated; + self.finished = YES; + // If the minShow time is set, calculate how long the HUD was shown, + // and postpone the hiding operation if necessary + if (self.minShowTime > 0.0 && self.showStarted) { + NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:self.showStarted]; + if (interv < self.minShowTime) { + NSTimer *timer = [NSTimer timerWithTimeInterval:(self.minShowTime - interv) target:self selector:@selector(handleMinShowTimer:) userInfo:nil repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; + self.minShowTimer = timer; + return; + } + } + // ... otherwise hide the HUD immediately + [self hideUsingAnimation:self.useAnimation]; +} + +- (void)hideAnimated:(BOOL)animated afterDelay:(NSTimeInterval)delay { + // Cancel any scheduled hideDelayed: calls + [self.hideDelayTimer invalidate]; + + NSTimer *timer = [NSTimer timerWithTimeInterval:delay target:self selector:@selector(handleHideTimer:) userInfo:@(animated) repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; + self.hideDelayTimer = timer; +} + +#pragma mark - Timer callbacks + +- (void)handleGraceTimer:(NSTimer *)theTimer { + // Show the HUD only if the task is still running + if (!self.hasFinished) { + [self showUsingAnimation:self.useAnimation]; + } +} + +- (void)handleMinShowTimer:(NSTimer *)theTimer { + [self hideUsingAnimation:self.useAnimation]; +} + +- (void)handleHideTimer:(NSTimer *)timer { + [self hideAnimated:[timer.userInfo boolValue]]; +} + +#pragma mark - View Hierrarchy + +- (void)didMoveToSuperview { + [self updateForCurrentOrientationAnimated:NO]; +} + +#pragma mark - Internal show & hide operations + +- (void)showUsingAnimation:(BOOL)animated { + // Cancel any previous animations + [self.bezelView.layer removeAllAnimations]; + [self.backgroundView.layer removeAllAnimations]; + + // Cancel any scheduled hideDelayed: calls + [self.hideDelayTimer invalidate]; + + self.showStarted = [NSDate date]; + self.alpha = 1.f; + + // Needed in case we hide and re-show with the same NSProgress object attached. + [self setNSProgressDisplayLinkEnabled:YES]; + + if (animated) { + [self animateIn:YES withType:self.animationType completion:NULL]; + } else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + self.bezelView.alpha = self.opacity; +#pragma clang diagnostic pop + self.backgroundView.alpha = 1.f; + } +} + +- (void)hideUsingAnimation:(BOOL)animated { + if (animated && self.showStarted) { + self.showStarted = nil; + [self animateIn:NO withType:self.animationType completion:^(BOOL finished) { + [self done]; + }]; + } else { + self.showStarted = nil; + self.bezelView.alpha = 0.f; + self.backgroundView.alpha = 1.f; + [self done]; + } +} + +- (void)animateIn:(BOOL)animatingIn withType:(MBProgressHUDAnimation)type completion:(void(^)(BOOL finished))completion { + // Automatically determine the correct zoom animation type + if (type == MBProgressHUDAnimationZoom) { + type = animatingIn ? MBProgressHUDAnimationZoomIn : MBProgressHUDAnimationZoomOut; + } + + CGAffineTransform small = CGAffineTransformMakeScale(0.5f, 0.5f); + CGAffineTransform large = CGAffineTransformMakeScale(1.5f, 1.5f); + + // Set starting state + UIView *bezelView = self.bezelView; + if (animatingIn && bezelView.alpha == 0.f && type == MBProgressHUDAnimationZoomIn) { + bezelView.transform = small; + } else if (animatingIn && bezelView.alpha == 0.f && type == MBProgressHUDAnimationZoomOut) { + bezelView.transform = large; + } + + // Perform animations + dispatch_block_t animations = ^{ + if (animatingIn) { + bezelView.transform = CGAffineTransformIdentity; + } else if (!animatingIn && type == MBProgressHUDAnimationZoomIn) { + bezelView.transform = large; + } else if (!animatingIn && type == MBProgressHUDAnimationZoomOut) { + bezelView.transform = small; + } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + bezelView.alpha = animatingIn ? self.opacity : 0.f; +#pragma clang diagnostic pop + self.backgroundView.alpha = animatingIn ? 1.f : 0.f; + }; + + // Spring animations are nicer, but only available on iOS 7+ +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 || TARGET_OS_TV + if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_7_0) { + [UIView animateWithDuration:0.3 delay:0. usingSpringWithDamping:1.f initialSpringVelocity:0.f options:UIViewAnimationOptionBeginFromCurrentState animations:animations completion:completion]; + return; + } +#endif + [UIView animateWithDuration:0.3 delay:0. options:UIViewAnimationOptionBeginFromCurrentState animations:animations completion:completion]; +} + +- (void)done { + // Cancel any scheduled hideDelayed: calls + [self.hideDelayTimer invalidate]; + [self setNSProgressDisplayLinkEnabled:NO]; + + if (self.hasFinished) { + self.alpha = 0.0f; + if (self.removeFromSuperViewOnHide) { + [self removeFromSuperview]; + } + } + MBProgressHUDCompletionBlock completionBlock = self.completionBlock; + if (completionBlock) { + completionBlock(); + } + id delegate = self.delegate; + if ([delegate respondsToSelector:@selector(hudWasHidden:)]) { + [delegate performSelector:@selector(hudWasHidden:) withObject:self]; + } +} + +#pragma mark - UI + +- (void)setupViews { + UIColor *defaultColor = self.contentColor; + + MBBackgroundView *backgroundView = [[MBBackgroundView alloc] initWithFrame:self.bounds]; + backgroundView.style = MBProgressHUDBackgroundStyleSolidColor; + backgroundView.backgroundColor = [UIColor clearColor]; + backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + backgroundView.alpha = 0.f; + [self addSubview:backgroundView]; + _backgroundView = backgroundView; + + MBBackgroundView *bezelView = [MBBackgroundView new]; + bezelView.translatesAutoresizingMaskIntoConstraints = NO; + bezelView.layer.cornerRadius = 5.f; + bezelView.alpha = 0.f; + [self addSubview:bezelView]; + _bezelView = bezelView; + [self updateBezelMotionEffects]; + + UILabel *label = [UILabel new]; + label.adjustsFontSizeToFitWidth = NO; + label.textAlignment = NSTextAlignmentCenter; + label.textColor = defaultColor; + label.font = [UIFont boldSystemFontOfSize:MBDefaultLabelFontSize]; + label.opaque = NO; + label.backgroundColor = [UIColor clearColor]; + _label = label; + + UILabel *detailsLabel = [UILabel new]; + detailsLabel.adjustsFontSizeToFitWidth = NO; + detailsLabel.textAlignment = NSTextAlignmentCenter; + detailsLabel.textColor = defaultColor; + detailsLabel.numberOfLines = 0; + detailsLabel.font = [UIFont boldSystemFontOfSize:MBDefaultDetailsLabelFontSize]; + detailsLabel.opaque = NO; + detailsLabel.backgroundColor = [UIColor clearColor]; + _detailsLabel = detailsLabel; + + UIButton *button = [MBProgressHUDRoundedButton buttonWithType:UIButtonTypeCustom]; + button.titleLabel.textAlignment = NSTextAlignmentCenter; + button.titleLabel.font = [UIFont boldSystemFontOfSize:MBDefaultDetailsLabelFontSize]; + [button setTitleColor:defaultColor forState:UIControlStateNormal]; + _button = button; + + for (UIView *view in @[label, detailsLabel, button]) { + view.translatesAutoresizingMaskIntoConstraints = NO; + [view setContentCompressionResistancePriority:998.f forAxis:UILayoutConstraintAxisHorizontal]; + [view setContentCompressionResistancePriority:998.f forAxis:UILayoutConstraintAxisVertical]; + [bezelView addSubview:view]; + } + + UIView *topSpacer = [UIView new]; + topSpacer.translatesAutoresizingMaskIntoConstraints = NO; + topSpacer.hidden = YES; + [bezelView addSubview:topSpacer]; + _topSpacer = topSpacer; + + UIView *bottomSpacer = [UIView new]; + bottomSpacer.translatesAutoresizingMaskIntoConstraints = NO; + bottomSpacer.hidden = YES; + [bezelView addSubview:bottomSpacer]; + _bottomSpacer = bottomSpacer; +} + +- (void)updateIndicators { + UIView *indicator = self.indicator; + BOOL isActivityIndicator = [indicator isKindOfClass:[UIActivityIndicatorView class]]; + BOOL isRoundIndicator = [indicator isKindOfClass:[MBRoundProgressView class]]; + + MBProgressHUDMode mode = self.mode; + if (mode == MBProgressHUDModeIndeterminate) { + if (!isActivityIndicator) { + // Update to indeterminate indicator + [indicator removeFromSuperview]; + indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; + [(UIActivityIndicatorView *)indicator startAnimating]; + [self.bezelView addSubview:indicator]; + } + } + else if (mode == MBProgressHUDModeDeterminateHorizontalBar) { + // Update to bar determinate indicator + [indicator removeFromSuperview]; + indicator = [[MBBarProgressView alloc] init]; + [self.bezelView addSubview:indicator]; + } + else if (mode == MBProgressHUDModeDeterminate || mode == MBProgressHUDModeAnnularDeterminate) { + if (!isRoundIndicator) { + // Update to determinante indicator + [indicator removeFromSuperview]; + indicator = [[MBRoundProgressView alloc] init]; + [self.bezelView addSubview:indicator]; + } + if (mode == MBProgressHUDModeAnnularDeterminate) { + [(MBRoundProgressView *)indicator setAnnular:YES]; + } + } + else if (mode == MBProgressHUDModeCustomView && self.customView != indicator) { + // Update custom view indicator + [indicator removeFromSuperview]; + indicator = self.customView; + [self.bezelView addSubview:indicator]; + } + else if (mode == MBProgressHUDModeText) { + [indicator removeFromSuperview]; + indicator = nil; + } + indicator.translatesAutoresizingMaskIntoConstraints = NO; + self.indicator = indicator; + + if ([indicator respondsToSelector:@selector(setProgress:)]) { + [(id)indicator setValue:@(self.progress) forKey:@"progress"]; + } + + [indicator setContentCompressionResistancePriority:998.f forAxis:UILayoutConstraintAxisHorizontal]; + [indicator setContentCompressionResistancePriority:998.f forAxis:UILayoutConstraintAxisVertical]; + + [self updateViewsForColor:self.contentColor]; + [self setNeedsUpdateConstraints]; +} + +- (void)updateViewsForColor:(UIColor *)color { + if (!color) return; + + self.label.textColor = color; + self.detailsLabel.textColor = color; + [self.button setTitleColor:color forState:UIControlStateNormal]; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (self.activityIndicatorColor) { + color = self.activityIndicatorColor; + } +#pragma clang diagnostic pop + + // UIAppearance settings are prioritized. If they are preset the set color is ignored. + + UIView *indicator = self.indicator; + if ([indicator isKindOfClass:[UIActivityIndicatorView class]]) { + UIActivityIndicatorView *appearance = nil; +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 90000 + appearance = [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil]; +#else + // For iOS 9+ + appearance = [UIActivityIndicatorView appearanceWhenContainedInInstancesOfClasses:@[[MBProgressHUD class]]]; +#endif + + if (appearance.color == nil) { + ((UIActivityIndicatorView *)indicator).color = color; + } + } else if ([indicator isKindOfClass:[MBRoundProgressView class]]) { + MBRoundProgressView *appearance = nil; +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 90000 + appearance = [MBRoundProgressView appearanceWhenContainedIn:[MBProgressHUD class], nil]; +#else + appearance = [MBRoundProgressView appearanceWhenContainedInInstancesOfClasses:@[[MBProgressHUD class]]]; +#endif + if (appearance.progressTintColor == nil) { + ((MBRoundProgressView *)indicator).progressTintColor = color; + } + if (appearance.backgroundTintColor == nil) { + ((MBRoundProgressView *)indicator).backgroundTintColor = [color colorWithAlphaComponent:0.1]; + } + } else if ([indicator isKindOfClass:[MBBarProgressView class]]) { + MBBarProgressView *appearance = nil; +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 90000 + appearance = [MBBarProgressView appearanceWhenContainedIn:[MBProgressHUD class], nil]; +#else + appearance = [MBBarProgressView appearanceWhenContainedInInstancesOfClasses:@[[MBProgressHUD class]]]; +#endif + if (appearance.progressColor == nil) { + ((MBBarProgressView *)indicator).progressColor = color; + } + if (appearance.lineColor == nil) { + ((MBBarProgressView *)indicator).lineColor = color; + } + } else { +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 || TARGET_OS_TV + if ([indicator respondsToSelector:@selector(setTintColor:)]) { + [indicator setTintColor:color]; + } +#endif + } +} + +- (void)updateBezelMotionEffects { +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 || TARGET_OS_TV + MBBackgroundView *bezelView = self.bezelView; + if (![bezelView respondsToSelector:@selector(addMotionEffect:)]) return; + + if (self.defaultMotionEffectsEnabled) { + CGFloat effectOffset = 10.f; + UIInterpolatingMotionEffect *effectX = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; + effectX.maximumRelativeValue = @(effectOffset); + effectX.minimumRelativeValue = @(-effectOffset); + + UIInterpolatingMotionEffect *effectY = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; + effectY.maximumRelativeValue = @(effectOffset); + effectY.minimumRelativeValue = @(-effectOffset); + + UIMotionEffectGroup *group = [[UIMotionEffectGroup alloc] init]; + group.motionEffects = @[effectX, effectY]; + + [bezelView addMotionEffect:group]; + } else { + NSArray *effects = [bezelView motionEffects]; + for (UIMotionEffect *effect in effects) { + [bezelView removeMotionEffect:effect]; + } + } +#endif +} + +#pragma mark - Layout + +- (void)updateConstraints { + UIView *bezel = self.bezelView; + UIView *topSpacer = self.topSpacer; + UIView *bottomSpacer = self.bottomSpacer; + CGFloat margin = self.margin; + NSMutableArray *bezelConstraints = [NSMutableArray array]; + NSDictionary *metrics = @{@"margin": @(margin)}; + + NSMutableArray *subviews = [NSMutableArray arrayWithObjects:self.topSpacer, self.label, self.detailsLabel, self.button, self.bottomSpacer, nil]; + if (self.indicator) [subviews insertObject:self.indicator atIndex:1]; + + // Remove existing constraints + [self removeConstraints:self.constraints]; + [topSpacer removeConstraints:topSpacer.constraints]; + [bottomSpacer removeConstraints:bottomSpacer.constraints]; + if (self.bezelConstraints) { + [bezel removeConstraints:self.bezelConstraints]; + self.bezelConstraints = nil; + } + + // Center bezel in container (self), applying the offset if set + CGPoint offset = self.offset; + NSMutableArray *centeringConstraints = [NSMutableArray array]; + [centeringConstraints addObject:[NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.f constant:offset.x]]; + [centeringConstraints addObject:[NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.f constant:offset.y]]; + [self applyPriority:998.f toConstraints:centeringConstraints]; + [self addConstraints:centeringConstraints]; + + // Ensure minimum side margin is kept + NSMutableArray *sideConstraints = [NSMutableArray array]; + [sideConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-(>=margin)-[bezel]-(>=margin)-|" options:0 metrics:metrics views:NSDictionaryOfVariableBindings(bezel)]]; + [sideConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=margin)-[bezel]-(>=margin)-|" options:0 metrics:metrics views:NSDictionaryOfVariableBindings(bezel)]]; + [self applyPriority:999.f toConstraints:sideConstraints]; + [self addConstraints:sideConstraints]; + + // Minimum bezel size, if set + CGSize minimumSize = self.minSize; + if (!CGSizeEqualToSize(minimumSize, CGSizeZero)) { + NSMutableArray *minSizeConstraints = [NSMutableArray array]; + [minSizeConstraints addObject:[NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:minimumSize.width]]; + [minSizeConstraints addObject:[NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:minimumSize.height]]; + [self applyPriority:997.f toConstraints:minSizeConstraints]; + [bezelConstraints addObjectsFromArray:minSizeConstraints]; + } + + // Square aspect ratio, if set + if (self.square) { + NSLayoutConstraint *square = [NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:bezel attribute:NSLayoutAttributeWidth multiplier:1.f constant:0]; + square.priority = 997.f; + [bezelConstraints addObject:square]; + } + + // Top and bottom spacing + [topSpacer addConstraint:[NSLayoutConstraint constraintWithItem:topSpacer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:margin]]; + [bottomSpacer addConstraint:[NSLayoutConstraint constraintWithItem:bottomSpacer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:margin]]; + // Top and bottom spaces should be equal + [bezelConstraints addObject:[NSLayoutConstraint constraintWithItem:topSpacer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:bottomSpacer attribute:NSLayoutAttributeHeight multiplier:1.f constant:0.f]]; + + // Layout subviews in bezel + NSMutableArray *paddingConstraints = [NSMutableArray new]; + [subviews enumerateObjectsUsingBlock:^(UIView *view, NSUInteger idx, BOOL *stop) { + // Center in bezel + [bezelConstraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:bezel attribute:NSLayoutAttributeCenterX multiplier:1.f constant:0.f]]; + // Ensure the minimum edge margin is kept + [bezelConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-(>=margin)-[view]-(>=margin)-|" options:0 metrics:metrics views:NSDictionaryOfVariableBindings(view)]]; + // Element spacing + if (idx == 0) { + // First, ensure spacing to bezel edge + [bezelConstraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:bezel attribute:NSLayoutAttributeTop multiplier:1.f constant:0.f]]; + } else if (idx == subviews.count - 1) { + // Last, ensure spacing to bezel edge + [bezelConstraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:bezel attribute:NSLayoutAttributeBottom multiplier:1.f constant:0.f]]; + } + if (idx > 0) { + // Has previous + NSLayoutConstraint *padding = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:subviews[idx - 1] attribute:NSLayoutAttributeBottom multiplier:1.f constant:0.f]; + [bezelConstraints addObject:padding]; + [paddingConstraints addObject:padding]; + } + }]; + + [bezel addConstraints:bezelConstraints]; + self.bezelConstraints = bezelConstraints; + + self.paddingConstraints = [paddingConstraints copy]; + [self updatePaddingConstraints]; + + [super updateConstraints]; +} + +- (void)layoutSubviews { + // There is no need to update constraints if they are going to + // be recreated in [super layoutSubviews] due to needsUpdateConstraints being set. + // This also avoids an issue on iOS 8, where updatePaddingConstraints + // would trigger a zombie object access. + if (!self.needsUpdateConstraints) { + [self updatePaddingConstraints]; + } + [super layoutSubviews]; +} + +- (void)updatePaddingConstraints { + // Set padding dynamically, depending on whether the view is visible or not + __block BOOL hasVisibleAncestors = NO; + [self.paddingConstraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *padding, NSUInteger idx, BOOL *stop) { + UIView *firstView = (UIView *)padding.firstItem; + UIView *secondView = (UIView *)padding.secondItem; + BOOL firstVisible = !firstView.hidden && !CGSizeEqualToSize(firstView.intrinsicContentSize, CGSizeZero); + BOOL secondVisible = !secondView.hidden && !CGSizeEqualToSize(secondView.intrinsicContentSize, CGSizeZero); + // Set if both views are visible or if there's a visible view on top that doesn't have padding + // added relative to the current view yet + padding.constant = (firstVisible && (secondVisible || hasVisibleAncestors)) ? MBDefaultPadding : 0.f; + hasVisibleAncestors |= secondVisible; + }]; +} + +- (void)applyPriority:(UILayoutPriority)priority toConstraints:(NSArray *)constraints { + for (NSLayoutConstraint *constraint in constraints) { + constraint.priority = priority; + } +} + +#pragma mark - Properties + +- (void)setMode:(MBProgressHUDMode)mode { + if (mode != _mode) { + _mode = mode; + [self updateIndicators]; + } +} + +- (void)setCustomView:(UIView *)customView { + if (customView != _customView) { + _customView = customView; + if (self.mode == MBProgressHUDModeCustomView) { + [self updateIndicators]; + } + } +} + +- (void)setOffset:(CGPoint)offset { + if (!CGPointEqualToPoint(offset, _offset)) { + _offset = offset; + [self setNeedsUpdateConstraints]; + } +} + +- (void)setMargin:(CGFloat)margin { + if (margin != _margin) { + _margin = margin; + [self setNeedsUpdateConstraints]; + } +} + +- (void)setMinSize:(CGSize)minSize { + if (!CGSizeEqualToSize(minSize, _minSize)) { + _minSize = minSize; + [self setNeedsUpdateConstraints]; + } +} + +- (void)setSquare:(BOOL)square { + if (square != _square) { + _square = square; + [self setNeedsUpdateConstraints]; + } +} + +- (void)setProgressObjectDisplayLink:(CADisplayLink *)progressObjectDisplayLink { + if (progressObjectDisplayLink != _progressObjectDisplayLink) { + [_progressObjectDisplayLink invalidate]; + + _progressObjectDisplayLink = progressObjectDisplayLink; + + [_progressObjectDisplayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; + } +} + +- (void)setProgressObject:(NSProgress *)progressObject { + if (progressObject != _progressObject) { + _progressObject = progressObject; + [self setNSProgressDisplayLinkEnabled:YES]; + } +} + +- (void)setProgress:(float)progress { + if (progress != _progress) { + _progress = progress; + UIView *indicator = self.indicator; + if ([indicator respondsToSelector:@selector(setProgress:)]) { + [(id)indicator setValue:@(self.progress) forKey:@"progress"]; + } + } +} + +- (void)setContentColor:(UIColor *)contentColor { + if (contentColor != _contentColor && ![contentColor isEqual:_contentColor]) { + _contentColor = contentColor; + [self updateViewsForColor:contentColor]; + } +} + +- (void)setDefaultMotionEffectsEnabled:(BOOL)defaultMotionEffectsEnabled { + if (defaultMotionEffectsEnabled != _defaultMotionEffectsEnabled) { + _defaultMotionEffectsEnabled = defaultMotionEffectsEnabled; + [self updateBezelMotionEffects]; + } +} + +#pragma mark - NSProgress + +- (void)setNSProgressDisplayLinkEnabled:(BOOL)enabled { + // We're using CADisplayLink, because NSProgress can change very quickly and observing it may starve the main thread, + // so we're refreshing the progress only every frame draw + if (enabled && self.progressObject) { + // Only create if not already active. + if (!self.progressObjectDisplayLink) { + self.progressObjectDisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateProgressFromProgressObject)]; + } + } else { + self.progressObjectDisplayLink = nil; + } +} + +- (void)updateProgressFromProgressObject { + self.progress = self.progressObject.fractionCompleted; +} + +#pragma mark - Notifications + +- (void)registerForNotifications { +#if !TARGET_OS_TV + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + + [nc addObserver:self selector:@selector(statusBarOrientationDidChange:) + name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; +#endif +} + +- (void)unregisterFromNotifications { +#if !TARGET_OS_TV + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + [nc removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; +#endif +} + +#if !TARGET_OS_TV +- (void)statusBarOrientationDidChange:(NSNotification *)notification { + UIView *superview = self.superview; + if (!superview) { + return; + } else { + [self updateForCurrentOrientationAnimated:YES]; + } +} +#endif + +- (void)updateForCurrentOrientationAnimated:(BOOL)animated { + // Stay in sync with the superview in any case + if (self.superview) { + self.frame = self.superview.bounds; + } + + // Not needed on iOS 8+, compile out when the deployment target allows, + // to avoid sharedApplication problems on extension targets +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 + // Only needed pre iOS 8 when added to a window + BOOL iOS8OrLater = kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0; + if (iOS8OrLater || ![self.superview isKindOfClass:[UIWindow class]]) return; + + // Make extension friendly. Will not get called on extensions (iOS 8+) due to the above check. + // This just ensures we don't get a warning about extension-unsafe API. + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + if (!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) return; + + UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)]; + UIInterfaceOrientation orientation = application.statusBarOrientation; + CGFloat radians = 0; + + if (UIInterfaceOrientationIsLandscape(orientation)) { + radians = orientation == UIInterfaceOrientationLandscapeLeft ? -(CGFloat)M_PI_2 : (CGFloat)M_PI_2; + // Window coordinates differ! + self.bounds = CGRectMake(0, 0, self.bounds.size.height, self.bounds.size.width); + } else { + radians = orientation == UIInterfaceOrientationPortraitUpsideDown ? (CGFloat)M_PI : 0.f; + } + + if (animated) { + [UIView animateWithDuration:0.3 animations:^{ + self.transform = CGAffineTransformMakeRotation(radians); + }]; + } else { + self.transform = CGAffineTransformMakeRotation(radians); + } +#endif +} + +@end + + +@implementation MBRoundProgressView + +#pragma mark - Lifecycle + +- (id)init { + return [self initWithFrame:CGRectMake(0.f, 0.f, 37.f, 37.f)]; +} + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + self.backgroundColor = [UIColor clearColor]; + self.opaque = NO; + _progress = 0.f; + _annular = NO; + _progressTintColor = [[UIColor alloc] initWithWhite:1.f alpha:1.f]; + _backgroundTintColor = [[UIColor alloc] initWithWhite:1.f alpha:.1f]; + } + return self; +} + +#pragma mark - Layout + +- (CGSize)intrinsicContentSize { + return CGSizeMake(37.f, 37.f); +} + +#pragma mark - Properties + +- (void)setProgress:(float)progress { + if (progress != _progress) { + _progress = progress; + [self setNeedsDisplay]; + } +} + +- (void)setProgressTintColor:(UIColor *)progressTintColor { + NSAssert(progressTintColor, @"The color should not be nil."); + if (progressTintColor != _progressTintColor && ![progressTintColor isEqual:_progressTintColor]) { + _progressTintColor = progressTintColor; + [self setNeedsDisplay]; + } +} + +- (void)setBackgroundTintColor:(UIColor *)backgroundTintColor { + NSAssert(backgroundTintColor, @"The color should not be nil."); + if (backgroundTintColor != _backgroundTintColor && ![backgroundTintColor isEqual:_backgroundTintColor]) { + _backgroundTintColor = backgroundTintColor; + [self setNeedsDisplay]; + } +} + +#pragma mark - Drawing + +- (void)drawRect:(CGRect)rect { + CGContextRef context = UIGraphicsGetCurrentContext(); + BOOL isPreiOS7 = kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iOS_7_0; + + if (_annular) { + // Draw background + CGFloat lineWidth = isPreiOS7 ? 5.f : 2.f; + UIBezierPath *processBackgroundPath = [UIBezierPath bezierPath]; + processBackgroundPath.lineWidth = lineWidth; + processBackgroundPath.lineCapStyle = kCGLineCapButt; + CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); + CGFloat radius = (self.bounds.size.width - lineWidth)/2; + CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees + CGFloat endAngle = (2 * (float)M_PI) + startAngle; + [processBackgroundPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + [_backgroundTintColor set]; + [processBackgroundPath stroke]; + // Draw progress + UIBezierPath *processPath = [UIBezierPath bezierPath]; + processPath.lineCapStyle = isPreiOS7 ? kCGLineCapRound : kCGLineCapSquare; + processPath.lineWidth = lineWidth; + endAngle = (self.progress * 2 * (float)M_PI) + startAngle; + [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + [_progressTintColor set]; + [processPath stroke]; + } else { + // Draw background + CGFloat lineWidth = 2.f; + CGRect allRect = self.bounds; + CGRect circleRect = CGRectInset(allRect, lineWidth/2.f, lineWidth/2.f); + CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); + [_progressTintColor setStroke]; + [_backgroundTintColor setFill]; + CGContextSetLineWidth(context, lineWidth); + if (isPreiOS7) { + CGContextFillEllipseInRect(context, circleRect); + } + CGContextStrokeEllipseInRect(context, circleRect); + // 90 degrees + CGFloat startAngle = - ((float)M_PI / 2.f); + // Draw progress + if (isPreiOS7) { + CGFloat radius = (CGRectGetWidth(self.bounds) / 2.f) - lineWidth; + CGFloat endAngle = (self.progress * 2.f * (float)M_PI) + startAngle; + [_progressTintColor setFill]; + CGContextMoveToPoint(context, center.x, center.y); + CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0); + CGContextClosePath(context); + CGContextFillPath(context); + } else { + UIBezierPath *processPath = [UIBezierPath bezierPath]; + processPath.lineCapStyle = kCGLineCapButt; + processPath.lineWidth = lineWidth * 2.f; + CGFloat radius = (CGRectGetWidth(self.bounds) / 2.f) - (processPath.lineWidth / 2.f); + CGFloat endAngle = (self.progress * 2.f * (float)M_PI) + startAngle; + [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + // Ensure that we don't get color overlapping when _progressTintColor alpha < 1.f. + CGContextSetBlendMode(context, kCGBlendModeCopy); + [_progressTintColor set]; + [processPath stroke]; + } + } +} + +@end + + +@implementation MBBarProgressView + +#pragma mark - Lifecycle + +- (id)init { + return [self initWithFrame:CGRectMake(.0f, .0f, 120.0f, 20.0f)]; +} + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + _progress = 0.f; + _lineColor = [UIColor whiteColor]; + _progressColor = [UIColor whiteColor]; + _progressRemainingColor = [UIColor clearColor]; + self.backgroundColor = [UIColor clearColor]; + self.opaque = NO; + } + return self; +} + +#pragma mark - Layout + +- (CGSize)intrinsicContentSize { + BOOL isPreiOS7 = kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iOS_7_0; + return CGSizeMake(120.f, isPreiOS7 ? 20.f : 10.f); +} + +#pragma mark - Properties + +- (void)setProgress:(float)progress { + if (progress != _progress) { + _progress = progress; + [self setNeedsDisplay]; + } +} + +- (void)setProgressColor:(UIColor *)progressColor { + NSAssert(progressColor, @"The color should not be nil."); + if (progressColor != _progressColor && ![progressColor isEqual:_progressColor]) { + _progressColor = progressColor; + [self setNeedsDisplay]; + } +} + +- (void)setProgressRemainingColor:(UIColor *)progressRemainingColor { + NSAssert(progressRemainingColor, @"The color should not be nil."); + if (progressRemainingColor != _progressRemainingColor && ![progressRemainingColor isEqual:_progressRemainingColor]) { + _progressRemainingColor = progressRemainingColor; + [self setNeedsDisplay]; + } +} + +#pragma mark - Drawing + +- (void)drawRect:(CGRect)rect { + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextSetLineWidth(context, 2); + CGContextSetStrokeColorWithColor(context,[_lineColor CGColor]); + CGContextSetFillColorWithColor(context, [_progressRemainingColor CGColor]); + + // Draw background and Border + CGFloat radius = (rect.size.height / 2) - 2; + CGContextMoveToPoint(context, 2, rect.size.height/2); + CGContextAddArcToPoint(context, 2, 2, radius + 2, 2, radius); + CGContextAddArcToPoint(context, rect.size.width - 2, 2, rect.size.width - 2, rect.size.height / 2, radius); + CGContextAddArcToPoint(context, rect.size.width - 2, rect.size.height - 2, rect.size.width - radius - 2, rect.size.height - 2, radius); + CGContextAddArcToPoint(context, 2, rect.size.height - 2, 2, rect.size.height/2, radius); + CGContextDrawPath(context, kCGPathFillStroke); + + CGContextSetFillColorWithColor(context, [_progressColor CGColor]); + radius = radius - 2; + CGFloat amount = self.progress * rect.size.width; + + // Progress in the middle area + if (amount >= radius + 4 && amount <= (rect.size.width - radius - 4)) { + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, amount, 4); + CGContextAddLineToPoint(context, amount, radius + 4); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, amount, rect.size.height - 4); + CGContextAddLineToPoint(context, amount, radius + 4); + + CGContextFillPath(context); + } + + // Progress in the right arc + else if (amount > radius + 4) { + CGFloat x = amount - (rect.size.width - radius - 4); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 4, 4); + CGFloat angle = -acos(x/radius); + if (isnan(angle)) angle = 0; + CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height/2, radius, M_PI, angle, 0); + CGContextAddLineToPoint(context, amount, rect.size.height/2); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 4, rect.size.height - 4); + angle = acos(x/radius); + if (isnan(angle)) angle = 0; + CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height/2, radius, -M_PI, angle, 1); + CGContextAddLineToPoint(context, amount, rect.size.height/2); + + CGContextFillPath(context); + } + + // Progress is in the left arc + else if (amount < radius + 4 && amount > 0) { + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); + + CGContextFillPath(context); + } +} + +@end + + +@interface MBBackgroundView () + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 || TARGET_OS_TV +@property UIVisualEffectView *effectView; +#endif +#if !TARGET_OS_TV +@property UIToolbar *toolbar; +#endif + +@end + + +@implementation MBBackgroundView + +#pragma mark - Lifecycle + +- (instancetype)initWithFrame:(CGRect)frame { + if ((self = [super initWithFrame:frame])) { + if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_7_0) { + _style = MBProgressHUDBackgroundStyleBlur; +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 || TARGET_OS_TV + _blurEffectStyle = UIBlurEffectStyleLight; +#endif + if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0) { + _color = [UIColor colorWithWhite:0.8f alpha:0.6f]; + } else { + _color = [UIColor colorWithWhite:0.95f alpha:0.6f]; + } + } else { + _style = MBProgressHUDBackgroundStyleSolidColor; + _color = [[UIColor blackColor] colorWithAlphaComponent:0.8]; + } + + self.clipsToBounds = YES; + + [self updateForBackgroundStyle]; + } + return self; +} + +#pragma mark - Layout + +- (CGSize)intrinsicContentSize { + // Smallest size possible. Content pushes against this. + return CGSizeZero; +} + +#pragma mark - Appearance + +- (void)setStyle:(MBProgressHUDBackgroundStyle)style { + if (style == MBProgressHUDBackgroundStyleBlur && kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iOS_7_0) { + style = MBProgressHUDBackgroundStyleSolidColor; + } + if (_style != style) { + _style = style; + [self updateForBackgroundStyle]; + } +} + +- (void)setColor:(UIColor *)color { + NSAssert(color, @"The color should not be nil."); + if (color != _color && ![color isEqual:_color]) { + _color = color; + [self updateViewsForColor:color]; + } +} + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 || TARGET_OS_TV + +- (void)setBlurEffectStyle:(UIBlurEffectStyle)blurEffectStyle { + if (_blurEffectStyle == blurEffectStyle) { + return; + } + + _blurEffectStyle = blurEffectStyle; + + [self updateForBackgroundStyle]; +} + +#endif + +/////////////////////////////////////////////////////////////////////////////////////////// +#pragma mark - Views + +- (void)updateForBackgroundStyle { + MBProgressHUDBackgroundStyle style = self.style; + if (style == MBProgressHUDBackgroundStyleBlur) { +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 || TARGET_OS_TV + if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0) { + UIBlurEffect *effect = [UIBlurEffect effectWithStyle:self.blurEffectStyle]; + UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect]; + [self addSubview:effectView]; + effectView.frame = self.bounds; + effectView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; + self.backgroundColor = self.color; + self.layer.allowsGroupOpacity = NO; + self.effectView = effectView; + } else { +#endif +#if !TARGET_OS_TV + UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectInset(self.bounds, -100.f, -100.f)]; + toolbar.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; + toolbar.barTintColor = self.color; + toolbar.translucent = YES; + [self addSubview:toolbar]; + self.toolbar = toolbar; +#endif +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 || TARGET_OS_TV + } +#endif + } else { +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 || TARGET_OS_TV + if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0) { + [self.effectView removeFromSuperview]; + self.effectView = nil; + } else { +#endif +#if !TARGET_OS_TV + [self.toolbar removeFromSuperview]; + self.toolbar = nil; +#endif +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 || TARGET_OS_TV + } +#endif + self.backgroundColor = self.color; + } +} + +- (void)updateViewsForColor:(UIColor *)color { + if (self.style == MBProgressHUDBackgroundStyleBlur) { + if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0) { + self.backgroundColor = self.color; + } else { +#if !TARGET_OS_TV + self.toolbar.barTintColor = color; +#endif + } + } else { + self.backgroundColor = self.color; + } +} + +@end + + +@implementation MBProgressHUD (Deprecated) + +#pragma mark - Class + ++ (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated { + NSArray *huds = [MBProgressHUD allHUDsForView:view]; + for (MBProgressHUD *hud in huds) { + hud.removeFromSuperViewOnHide = YES; + [hud hideAnimated:animated]; + } + return [huds count]; +} + ++ (NSArray *)allHUDsForView:(UIView *)view { + NSMutableArray *huds = [NSMutableArray array]; + NSArray *subviews = view.subviews; + for (UIView *aView in subviews) { + if ([aView isKindOfClass:self]) { + [huds addObject:aView]; + } + } + return [NSArray arrayWithArray:huds]; +} + +#pragma mark - Lifecycle + +- (id)initWithWindow:(UIWindow *)window { + return [self initWithView:window]; +} + +#pragma mark - Show & hide + +- (void)show:(BOOL)animated { + [self showAnimated:animated]; +} + +- (void)hide:(BOOL)animated { + [self hideAnimated:animated]; +} + +- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay { + [self hideAnimated:animated afterDelay:delay]; +} + +#pragma mark - Threading + +- (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated { + [self showAnimated:animated whileExecutingBlock:^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + // Start executing the requested task + [target performSelector:method withObject:object]; +#pragma clang diagnostic pop + }]; +} + +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block { + dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:NULL]; +} + +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block completionBlock:(void (^)(void))completion { + dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:completion]; +} + +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue { + [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:NULL]; +} + +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue completionBlock:(nullable MBProgressHUDCompletionBlock)completion { + self.taskInProgress = YES; + self.completionBlock = completion; + dispatch_async(queue, ^(void) { + block(); + dispatch_async(dispatch_get_main_queue(), ^(void) { + [self cleanUp]; + }); + }); + [self showAnimated:animated]; +} + +- (void)cleanUp { + self.taskInProgress = NO; + [self hideAnimated:self.useAnimation]; +} + +#pragma mark - Labels + +- (NSString *)labelText { + return self.label.text; +} + +- (void)setLabelText:(NSString *)labelText { + MBMainThreadAssert(); + self.label.text = labelText; +} + +- (UIFont *)labelFont { + return self.label.font; +} + +- (void)setLabelFont:(UIFont *)labelFont { + MBMainThreadAssert(); + self.label.font = labelFont; +} + +- (UIColor *)labelColor { + return self.label.textColor; +} + +- (void)setLabelColor:(UIColor *)labelColor { + MBMainThreadAssert(); + self.label.textColor = labelColor; +} + +- (NSString *)detailsLabelText { + return self.detailsLabel.text; +} + +- (void)setDetailsLabelText:(NSString *)detailsLabelText { + MBMainThreadAssert(); + self.detailsLabel.text = detailsLabelText; +} + +- (UIFont *)detailsLabelFont { + return self.detailsLabel.font; +} + +- (void)setDetailsLabelFont:(UIFont *)detailsLabelFont { + MBMainThreadAssert(); + self.detailsLabel.font = detailsLabelFont; +} + +- (UIColor *)detailsLabelColor { + return self.detailsLabel.textColor; +} + +- (void)setDetailsLabelColor:(UIColor *)detailsLabelColor { + MBMainThreadAssert(); + self.detailsLabel.textColor = detailsLabelColor; +} + +- (CGFloat)opacity { + return _opacity; +} + +- (void)setOpacity:(CGFloat)opacity { + MBMainThreadAssert(); + _opacity = opacity; +} + +- (UIColor *)color { + return self.bezelView.color; +} + +- (void)setColor:(UIColor *)color { + MBMainThreadAssert(); + self.bezelView.color = color; +} + +- (CGFloat)yOffset { + return self.offset.y; +} + +- (void)setYOffset:(CGFloat)yOffset { + MBMainThreadAssert(); + self.offset = CGPointMake(self.offset.x, yOffset); +} + +- (CGFloat)xOffset { + return self.offset.x; +} + +- (void)setXOffset:(CGFloat)xOffset { + MBMainThreadAssert(); + self.offset = CGPointMake(xOffset, self.offset.y); +} + +- (CGFloat)cornerRadius { + return self.bezelView.layer.cornerRadius; +} + +- (void)setCornerRadius:(CGFloat)cornerRadius { + MBMainThreadAssert(); + self.bezelView.layer.cornerRadius = cornerRadius; +} + +- (BOOL)dimBackground { + MBBackgroundView *backgroundView = self.backgroundView; + UIColor *dimmedColor = [UIColor colorWithWhite:0.f alpha:.2f]; + return backgroundView.style == MBProgressHUDBackgroundStyleSolidColor && [backgroundView.color isEqual:dimmedColor]; +} + +- (void)setDimBackground:(BOOL)dimBackground { + MBMainThreadAssert(); + self.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor; + self.backgroundView.color = dimBackground ? [UIColor colorWithWhite:0.f alpha:.2f] : [UIColor clearColor]; +} + +- (CGSize)size { + return self.bezelView.frame.size; +} + +- (UIColor *)activityIndicatorColor { + return _activityIndicatorColor; +} + +- (void)setActivityIndicatorColor:(UIColor *)activityIndicatorColor { + if (activityIndicatorColor != _activityIndicatorColor) { + _activityIndicatorColor = activityIndicatorColor; + UIActivityIndicatorView *indicator = (UIActivityIndicatorView *)self.indicator; + if ([indicator isKindOfClass:[UIActivityIndicatorView class]]) { + [indicator setColor:activityIndicatorColor]; + } + } +} + +@end + +@implementation MBProgressHUDRoundedButton + +#pragma mark - Lifecycle + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + CALayer *layer = self.layer; + layer.borderWidth = 1.f; + } + return self; +} + +#pragma mark - Layout + +- (void)layoutSubviews { + [super layoutSubviews]; + // Fully rounded corners + CGFloat height = CGRectGetHeight(self.bounds); + self.layer.cornerRadius = ceil(height / 2.f); +} + +- (CGSize)intrinsicContentSize { + // Only show if we have associated control events + if (self.allControlEvents == 0) return CGSizeZero; + CGSize size = [super intrinsicContentSize]; + // Add some side padding + size.width += 20.f; + return size; +} + +#pragma mark - Color + +- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state { + [super setTitleColor:color forState:state]; + // Update related colors + [self setHighlighted:self.highlighted]; + self.layer.borderColor = color.CGColor; +} + +- (void)setHighlighted:(BOOL)highlighted { + [super setHighlighted:highlighted]; + UIColor *baseColor = [self titleColorForState:UIControlStateSelected]; + self.backgroundColor = highlighted ? [baseColor colorWithAlphaComponent:0.1f] : [UIColor clearColor]; +} + +@end diff --git a/Pods/MBProgressHUD/README.mdown b/Pods/MBProgressHUD/README.mdown new file mode 100644 index 0000000000..21ba843bb7 --- /dev/null +++ b/Pods/MBProgressHUD/README.mdown @@ -0,0 +1,126 @@ +# MBProgressHUD + +[![Build Status](https://travis-ci.org/matej/MBProgressHUD.svg?branch=master)](https://travis-ci.org/matej/MBProgressHUD) [![codecov.io](https://codecov.io/github/matej/MBProgressHUD/coverage.svg?branch=master)](https://codecov.io/github/matej/MBProgressHUD?branch=master) + [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) [![CocoaPods compatible](https://img.shields.io/cocoapods/v/MBProgressHUD.svg?style=flat)](https://cocoapods.org/pods/MBProgressHUD) [![License: MIT](https://img.shields.io/cocoapods/l/MBProgressHUD.svg?style=flat)](http://opensource.org/licenses/MIT) + +`MBProgressHUD` is an iOS drop-in class that displays a translucent HUD with an indicator and/or labels while work is being done in a background thread. The HUD is meant as a replacement for the undocumented, private `UIKit` `UIProgressHUD` with some additional features. + +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/1-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/1.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/2-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/2.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/3-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/3.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/4-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/4.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/5-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/5.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/6-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/6.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/7-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/7.png) + +**NOTE:** The class has recently undergone a major rewrite. The old version is available in the [legacy](https://github.com/jdg/MBProgressHUD/tree/legacy) branch, should you need it. + +## Requirements + +`MBProgressHUD` works on iOS 6+ and requires ARC to build. It depends on the following Apple frameworks, which should already be included with most Xcode templates: + +* Foundation.framework +* UIKit.framework +* CoreGraphics.framework + +You will need the latest developer tools in order to build `MBProgressHUD`. Old Xcode versions might work, but compatibility will not be explicitly maintained. + +## Adding MBProgressHUD to your project + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is the recommended way to add MBProgressHUD to your project. + +1. Add a pod entry for MBProgressHUD to your Podfile `pod 'MBProgressHUD', '~> 1.1.0'` +2. Install the pod(s) by running `pod install`. +3. Include MBProgressHUD wherever you need it with `#import "MBProgressHUD.h"`. + +### Carthage + +1. Add MBProgressHUD to your Cartfile. e.g., `github "jdg/MBProgressHUD" ~> 1.1.0` +2. Run `carthage update` +3. Follow the rest of the [standard Carthage installation instructions](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) to add MBProgressHUD to your project. + +### Source files + +Alternatively you can directly add the `MBProgressHUD.h` and `MBProgressHUD.m` source files to your project. + +1. Download the [latest code version](https://github.com/matej/MBProgressHUD/archive/master.zip) or add the repository as a git submodule to your git-tracked project. +2. Open your project in Xcode, then drag and drop `MBProgressHUD.h` and `MBProgressHUD.m` onto your project (use the "Product Navigator view"). Make sure to select Copy items when asked if you extracted the code archive outside of your project. +3. Include MBProgressHUD wherever you need it with `#import "MBProgressHUD.h"`. + +### Static library + +You can also add MBProgressHUD as a static library to your project or workspace. + +1. Download the [latest code version](https://github.com/matej/MBProgressHUD/downloads) or add the repository as a git submodule to your git-tracked project. +2. Open your project in Xcode, then drag and drop `MBProgressHUD.xcodeproj` onto your project or workspace (use the "Product Navigator view"). +3. Select your target and go to the Build phases tab. In the Link Binary With Libraries section select the add button. On the sheet find and add `libMBProgressHUD.a`. You might also need to add `MBProgressHUD` to the Target Dependencies list. +4. Include MBProgressHUD wherever you need it with `#import `. + +## Usage + +The main guideline you need to follow when dealing with MBProgressHUD while running long-running tasks is keeping the main thread work-free, so the UI can be updated promptly. The recommended way of using MBProgressHUD is therefore to set it up on the main thread and then spinning the task, that you want to perform, off onto a new thread. + +```objective-c +[MBProgressHUD showHUDAddedTo:self.view animated:YES]; +dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ + // Do something... + dispatch_async(dispatch_get_main_queue(), ^{ + [MBProgressHUD hideHUDForView:self.view animated:YES]; + }); +}); +``` + +You can add the HUD on any view or window. It is however a good idea to avoid adding the HUD to certain `UIKit` views with complex view hierarchies - like `UITableView` or `UICollectionView`. Those can mutate their subviews in unexpected ways and thereby break HUD display. + +If you need to configure the HUD you can do this by using the MBProgressHUD reference that showHUDAddedTo:animated: returns. + +```objective-c +MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; +hud.mode = MBProgressHUDModeAnnularDeterminate; +hud.label.text = @"Loading"; +[self doSomethingInBackgroundWithProgressCallback:^(float progress) { + hud.progress = progress; +} completionCallback:^{ + [hud hideAnimated:YES]; +}]; +``` + +You can also use a `NSProgress` object and MBProgressHUD will update itself when there is progress reported through that object. + +```objective-c +MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; +hud.mode = MBProgressHUDModeAnnularDeterminate; +hud.label.text = @"Loading"; +NSProgress *progress = [self doSomethingInBackgroundCompletion:^{ + [hud hideAnimated:YES]; +}]; +hud.progressObject = progress; +``` + +Keep in mind that UI updates, inclining calls to MBProgressHUD should always be done on the main thread. + +If you need to run your long-running task in the main thread, you should perform it with a slight delay, so UIKit will have enough time to update the UI (i.e., draw the HUD) before you block the main thread with your task. + +```objective-c +[MBProgressHUD showHUDAddedTo:self.view animated:YES]; +dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC); +dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ + // Do something... + [MBProgressHUD hideHUDForView:self.view animated:YES]; +}); +``` + +You should be aware that any HUD updates issued inside the above block won't be displayed until the block completes. + +For more examples, including how to use MBProgressHUD with asynchronous operations such as NSURLConnection, take a look at the bundled demo project. Extensive API documentation is provided in the header file (MBProgressHUD.h). + + +## License + +This code is distributed under the terms and conditions of the [MIT license](LICENSE). + +## Change-log + +A brief summary of each MBProgressHUD release can be found in the [CHANGELOG](CHANGELOG.mdown). diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000000..0163286d30 --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,199 @@ +PODS: + - 1PasswordExtension (1.8.5) + - Crashlytics (3.11.1): + - Fabric (~> 1.8.1) + - DifferenceKit (0.7.2): + - DifferenceKit/Core (= 0.7.2) + - DifferenceKit/UIKitExtension (= 0.7.2) + - DifferenceKit/Core (0.7.2) + - DifferenceKit/UIKitExtension (0.7.2): + - DifferenceKit/Core + - Fabric (1.8.2) + - Firebase/Core (5.12.0): + - Firebase/CoreOnly + - FirebaseAnalytics (= 5.3.0) + - Firebase/CoreOnly (5.12.0): + - FirebaseCore (= 5.1.7) + - FirebaseAnalytics (5.3.0): + - FirebaseCore (~> 5.1) + - FirebaseInstanceID (~> 3.3) + - GoogleAppMeasurement (~> 5.3) + - GoogleUtilities/AppDelegateSwizzler (~> 5.2) + - GoogleUtilities/MethodSwizzler (~> 5.2) + - GoogleUtilities/Network (~> 5.2) + - "GoogleUtilities/NSData+zlib (~> 5.2)" + - nanopb (~> 0.3) + - FirebaseCore (5.1.7): + - GoogleUtilities/Logger (~> 5.2) + - FirebaseInstanceID (3.3.0): + - FirebaseCore (~> 5.1) + - GoogleUtilities/Environment (~> 5.3) + - GoogleUtilities/UserDefaults (~> 5.3) + - FLAnimatedImage (1.0.12) + - FLEX (2.4.0) + - GoogleAppMeasurement (5.3.0): + - GoogleUtilities/AppDelegateSwizzler (~> 5.2) + - GoogleUtilities/MethodSwizzler (~> 5.2) + - GoogleUtilities/Network (~> 5.2) + - "GoogleUtilities/NSData+zlib (~> 5.2)" + - nanopb (~> 0.3) + - GoogleUtilities/AppDelegateSwizzler (5.3.4): + - GoogleUtilities/Environment + - GoogleUtilities/Logger + - GoogleUtilities/Network + - GoogleUtilities/Environment (5.3.4) + - GoogleUtilities/Logger (5.3.4): + - GoogleUtilities/Environment + - GoogleUtilities/MethodSwizzler (5.3.4): + - GoogleUtilities/Logger + - GoogleUtilities/Network (5.3.4): + - GoogleUtilities/Logger + - "GoogleUtilities/NSData+zlib" + - GoogleUtilities/Reachability + - "GoogleUtilities/NSData+zlib (5.3.4)" + - GoogleUtilities/Reachability (5.3.4): + - GoogleUtilities/Logger + - GoogleUtilities/UserDefaults (5.3.4): + - GoogleUtilities/Logger + - MBProgressHUD (1.1.0) + - MobilePlayer (1.2.0) + - nanopb (0.3.901): + - nanopb/decode (= 0.3.901) + - nanopb/encode (= 0.3.901) + - nanopb/decode (0.3.901) + - nanopb/encode (0.3.901) + - Nuke (7.5.1) + - Nuke-FLAnimatedImage-Plugin (6.0): + - FLAnimatedImage (~> 1.0) + - Nuke (~> 7.5) + - OAuthSwift (1.2.2) + - RCMarkdownParser (3.0.6) + - ReachabilitySwift (4.2.1) + - Realm (3.11.1): + - Realm/Headers (= 3.11.1) + - Realm/Headers (3.11.1) + - RealmSwift (3.11.1): + - Realm (= 3.11.1) + - RocketChatViewController (0.1.0): + - RocketChatViewController/Composer (= 0.1.0) + - RocketChatViewController/ViewController (= 0.1.0) + - RocketChatViewController/Composer (0.1.0) + - RocketChatViewController/ViewController (0.1.0): + - DifferenceKit (~> 0.7.2) + - semver (1.1.0) + - SimpleImageViewer (1.2.0): + - FLAnimatedImage + - Starscream (2.1.1) + - SwiftLint (0.27.0) + - SwiftyJSON (4.2.0) + - SwipeCellKit (2.5.0) + +DEPENDENCIES: + - 1PasswordExtension + - Crashlytics + - DifferenceKit/Core + - Fabric + - Firebase/Core + - FLEX (~> 2.0) + - MBProgressHUD (~> 1.1.0) + - MobilePlayer (from `https://github.com/RocketChat/RCiOSMobilePlayer`) + - Nuke (~> 7.3) + - Nuke-FLAnimatedImage-Plugin + - OAuthSwift + - RCMarkdownParser (from `https://github.com/RocketChat/RCMarkdownParser.git`) + - ReachabilitySwift + - RealmSwift + - RocketChatViewController (from `https://github.com/RocketChat/RocketChatViewController`) + - semver + - SimpleImageViewer (from `https://github.com/cardoso/SimpleImageViewer.git`) + - Starscream (~> 2) + - SwiftLint + - SwiftyJSON + - SwipeCellKit + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - 1PasswordExtension + - Crashlytics + - DifferenceKit + - Fabric + - Firebase + - FirebaseAnalytics + - FirebaseCore + - FirebaseInstanceID + - FLAnimatedImage + - FLEX + - GoogleAppMeasurement + - GoogleUtilities + - MBProgressHUD + - nanopb + - Nuke + - Nuke-FLAnimatedImage-Plugin + - OAuthSwift + - ReachabilitySwift + - Realm + - RealmSwift + - semver + - Starscream + - SwiftLint + - SwiftyJSON + - SwipeCellKit + +EXTERNAL SOURCES: + MobilePlayer: + :git: https://github.com/RocketChat/RCiOSMobilePlayer + RCMarkdownParser: + :git: https://github.com/RocketChat/RCMarkdownParser.git + RocketChatViewController: + :git: https://github.com/RocketChat/RocketChatViewController + SimpleImageViewer: + :git: https://github.com/cardoso/SimpleImageViewer.git + +CHECKOUT OPTIONS: + MobilePlayer: + :commit: c7160990d7b50d34a45514df4535011e64541340 + :git: https://github.com/RocketChat/RCiOSMobilePlayer + RCMarkdownParser: + :commit: c34d9ccef689c55b9eae69f3c65283da8d8b0c6c + :git: https://github.com/RocketChat/RCMarkdownParser.git + RocketChatViewController: + :commit: 723f1a6857f8d49af11e582dbb7077a99c28cb78 + :git: https://github.com/RocketChat/RocketChatViewController + SimpleImageViewer: + :commit: 8222c338de0f285ca0c2d556c5d8dedd4a365b52 + :git: https://github.com/cardoso/SimpleImageViewer.git + +SPEC CHECKSUMS: + 1PasswordExtension: 0e95bdea64ec8ff2f4f693be5467a09fac42a83d + Crashlytics: ca7ab4bc304aa216bdc2e4c1a96389ee77252203 + DifferenceKit: 5179eaf0e76a1b9fbaeb93f4c1a82510be63ca65 + Fabric: d2b22f443ba195d8a7cc204da230977c72733b40 + Firebase: 9190018e296139d938b99521cde0c15a6e8d2946 + FirebaseAnalytics: 63202d2665de4e6adcbdce189135255d8b5962ba + FirebaseCore: 027d350adc039aa5483357c6f56556f117c5170e + FirebaseInstanceID: e2fa4cb35ef5558c200f7f0ad8a53e212215f93e + FLAnimatedImage: 4a0b56255d9b05f18b6dd7ee06871be5d3b89e31 + FLEX: bd1a39e55b56bb413b6f1b34b3c10a0dc44ef079 + GoogleAppMeasurement: 5029d78f2b438bd30ffb44e6c558b57c21622727 + GoogleUtilities: abb092d2c12e817fa3e0e7b274987dd72fb86ec3 + MBProgressHUD: e7baa36a220447d8aeb12769bf0585582f3866d9 + MobilePlayer: 069b13482499f14c25b6ce53f63a91e17975b073 + nanopb: 2901f78ea1b7b4015c860c2fdd1ea2fee1a18d48 + Nuke: 3814db501e55f17951451839c726ffd91641e9a5 + Nuke-FLAnimatedImage-Plugin: e4c39d13061a08ac0bdcb0cd7a23882f4a43f4a6 + OAuthSwift: 27b34fe80b76b67cd8f45571e0be2432bc9f6de1 + RCMarkdownParser: 518b616a4f48bb02247243544d4fd55c048288a4 + ReachabilitySwift: 35720ffea59c1c76d15f885be77fd33e33985427 + Realm: 037c5919b9ceb59d6beed5d3b031096856b119b3 + RealmSwift: c9580133e73ef40ed340401af2dbc9a5790dfea7 + RocketChatViewController: 00d436e393ac0bd0a62bc72d9a35a9043fc3f3a5 + semver: 11ae3bc4a6036efbc86b5863ef5fa32c065c8bbd + SimpleImageViewer: 6ed0d2acf7c166a5b4e795bccc7b9ea1b225ff9b + Starscream: 142bd8ef24592d985daee9fa48c936070b85b15f + SwiftLint: 3207c1faa2240bf8973b191820a116113cd11073 + SwiftyJSON: c4bcba26dd9ec7a027fc8eade48e2c911f229e96 + SwipeCellKit: d8f2617538ce3021cb0a11d1b93856a06a2f2e20 + +PODFILE CHECKSUM: 5d62982fe6d8cd234f28edafc23b27595439d854 + +COCOAPODS: 1.5.3 diff --git a/Pods/MobilePlayer/LICENSE b/Pods/MobilePlayer/LICENSE new file mode 100644 index 0000000000..64aacc80c6 --- /dev/null +++ b/Pods/MobilePlayer/LICENSE @@ -0,0 +1,69 @@ +Creative Commons + + +Creative Commons Legal Code + +Attribution-NonCommercial-ShareAlike 3.0 United States + + +CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM ITS USE. +License + +THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. + +BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. + +1. Definitions + +"Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with one or more other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License. +"Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License. +"Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. +"Original Author" means the individual, individuals, entity or entities who created the Work. +"Work" means the copyrightable work of authorship offered under the terms of this License. +"You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. +"License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, Noncommercial, ShareAlike. +2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws. + +3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: + +to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works; +to create and reproduce Derivative Works provided that any such Derivative Work, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified."; +to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works; +to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works; +The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved, including but not limited to the rights set forth in Sections 4(e) and 4(f). + +4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: + +You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of a recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. When You distribute, publicly display, publicly perform, or publicly digitally perform the Work, You may not impose any technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by Section 4(d), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by Section 4(d), as requested. +You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under: (i) the terms of this License; (ii) a later version of this License with the same License Elements as this License; or, (iii) either the unported Creative Commons license or a Creative Commons license for another jurisdiction (either this or a later license version) that contains the same License Elements as this License (e.g. Attribution-NonCommercial-ShareAlike 3.0 (Unported)) ("the Applicable License"). You must include a copy of, or the Uniform Resource Identifier for, the Applicable License with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that restrict the terms of the Applicable License or the ability of a recipient of the Work to exercise the rights granted to that recipient under the terms of the Applicable License. You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties. When You distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work, You may not impose any technological measures on the Derivative Work that restrict the ability of a recipient of the Derivative Work from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of the Applicable License. +You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed toward commercial advantage or private monetary compensation. The exchange of the Work for other copyrighted works by means of digital file-sharing or otherwise shall not be considered to be intended for or directed toward commercial advantage or private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange of copyrighted works. +If You distribute, publicly display, publicly perform, or publicly digitally perform the Work (as defined in Section 1 above) or any Derivative Works (as defined in Section 1 above) or Collective Works (as defined in Section 1 above), You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and, consistent with Section 3(b) in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(d) may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear, if a credit for all contributing authors of the Derivative Work or Collective Work appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. +For the avoidance of doubt, where the Work is a musical composition: + +Performance Royalties Under Blanket Licenses. Licensor reserves the exclusive right to collect whether individually or, in the event that Licensor is a member of a performance rights society (e.g. ASCAP, BMI, SESAC), via that society, royalties for the public performance or public digital performance (e.g. webcast) of the Work if that performance is primarily intended for or directed toward commercial advantage or private monetary compensation. +Mechanical Rights and Statutory Royalties. Licensor reserves the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions), if Your distribution of such cover version is primarily intended for or directed toward commercial advantage or private monetary compensation. +Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor reserves the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions), if Your public digital performance is primarily intended for or directed toward commercial advantage or private monetary compensation. +5. Representations, Warranties and Disclaimer + +UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND ONLY TO THE EXTENT OF ANY RIGHTS HELD IN THE LICENSED WORK BY THE LICENSOR. THE LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MARKETABILITY, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. + +6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. Termination + +This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works (as defined in Section 1 above) or Collective Works (as defined in Section 1 above) from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. +Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. +8. Miscellaneous + +Each time You distribute or publicly digitally perform the Work (as defined in Section 1 above) or a Collective Work (as defined in Section 1 above), the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. +Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. +If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. +No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. +This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. +Creative Commons Notice + +Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor. + +Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, Creative Commons does not authorize the use by either party of the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time. For the avoidance of doubt, this trademark restriction does not form part of this License. + +Creative Commons may be contacted at http://creativecommons.org/. diff --git a/Pods/MobilePlayer/MobilePlayer/Config/BarConfig.swift b/Pods/MobilePlayer/MobilePlayer/Config/BarConfig.swift new file mode 100644 index 0000000000..a207e87b8b --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Config/BarConfig.swift @@ -0,0 +1,109 @@ +// +// BarConfig.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/15/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +/// Holds bar configuration values. +public class BarConfig { + + /// Bar background color. If there is more than one value, background will be a gradient. + public let backgroundColor: [UIColor] + + /// Bar height. + public let height: CGFloat + + /// Height of the top edge border view. + public let topBorderHeight: CGFloat + + /// Background color of the top edge border view. + public let topBorderColor: UIColor + + /// Height of the bottom edge border view. + public let bottomBorderHeight: CGFloat + + /// Background color of the bottom edge border view. + public let bottomBorderColor: UIColor + + /// An array of configuration objects for the elements of the bar. + public let elements: [ElementConfig] + + /// Initializes using default values. + public convenience init() { + self.init(dictionary: [String: Any]()) + } + + /// Initializes using a dictionary. + /// + /// * Key for `backgroundColor` is `"backgroundColor"` colors and its value should either be a color hex string, or an array + /// of color hex strings for a gradient background. + /// * Key for `height` is `"height"` and its value should be a number. + /// * Key for `topBorderHeight` is `"topBorderHeight"` and its value should be a number. + /// * Key for `topBorderColor` is `"topBorderColor"` and its value should be a color hex string. + /// * Key for `bottomBorderHeight is `"bottomBorderHeight"` and its value should be a number. + /// * Key for `bottomBorderColor` is `"bottomBorderColor"` and its value should be a color hex string. + /// * Key for `elements` is `"elements"` and its value should be an array of element configuration dictionaries. + /// + /// - parameters: + /// - dictionary: Bar configuration dictionary. + public init(dictionary: [String: Any]) { + // Values need to be AnyObject for type conversions to work correctly. + let dictionary = dictionary as [String: AnyObject] + + if let backgroundColorHexes = dictionary["backgroundColor"] as? [String] { + var colors = [UIColor]() + for hex in backgroundColorHexes { + colors.append(UIColor(hex: hex)) + } + backgroundColor = colors + } else if let backgroundColorHex = dictionary["backgroundColor"] as? String { + backgroundColor = [UIColor(hex: backgroundColorHex)] + } else { + backgroundColor = [UIColor(white: 0, alpha: 0.7)] + } + + height = (dictionary["height"] as? CGFloat) ?? 40 + topBorderHeight = (dictionary["topBorderHeight"] as? CGFloat) ?? 0 + + if let topBorderColorHex = dictionary["topBorderColor"] as? String { + topBorderColor = UIColor(hex: topBorderColorHex) + } else { + topBorderColor = UIColor.clear + } + + bottomBorderHeight = (dictionary["bottomBorderHeight"] as? CGFloat) ?? 0 + + if let bottomBorderColorHex = dictionary["bottomBorderColor"] as? String { + bottomBorderColor = UIColor(hex: bottomBorderColorHex) + } else { + bottomBorderColor = UIColor.clear + } + + if let elementDictionaries = dictionary["elements"] as? [[String: AnyObject]] { + var validElements = [ElementConfig]() + for elementDictionary in elementDictionaries { + if let type = elementDictionary["type"] as? String { + switch type { + case "button": + validElements.append(ButtonConfig(dictionary: elementDictionary)) + case "toggleButton": + validElements.append(ToggleButtonConfig(dictionary: elementDictionary)) + case "label": + validElements.append(LabelConfig(dictionary: elementDictionary)) + case "slider": + validElements.append(SliderConfig(dictionary: elementDictionary)) + default: + break + } + } + } + elements = validElements + } else { + elements = [] + } + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Config/ButtonConfig.swift b/Pods/MobilePlayer/MobilePlayer/Config/ButtonConfig.swift new file mode 100644 index 0000000000..3fbcebd006 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Config/ButtonConfig.swift @@ -0,0 +1,65 @@ +// +// ButtonConfig.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/16/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +/// Holds button configuration values. +public class ButtonConfig: ElementConfig { + + /// Button height. Default value is 40. + public let height: CGFloat + + /// Button image. + public let image: UIImage? + + /// Button tint color. Default value is white. + public let tintColor: UIColor + + /// Initializes using default values. + public convenience init() { + self.init(dictionary: [String: Any]()) + } + + /// Initializes using a dictionary. + /// + /// * Key for `height` is `"height"` and its value should be a number. + /// * Key for `image` is `"image"` and its value should be an image asset name. + /// * Key for `tintColor` is `"tintColor"` and its value should be a color hex string. + /// + /// - parameters: + /// - dictionary: Button configuration dictionary. + public override init(dictionary: [String: Any]) { + // Values need to be AnyObject for type conversions to work correctly. + let dictionary = dictionary as [String: AnyObject] + + height = (dictionary["height"] as? CGFloat) ?? 40 + + if let imageName = dictionary["image"] as? String { + image = UIImage(named: imageName) + } else if let identifier = dictionary["identifier"] as? String { + switch identifier { + case "close": + image = UIImage(podResourceNamed: "MLCloseButton.png")?.template + case "action": + image = UIImage(podResourceNamed: "MLShareButton")?.template + default: + image = nil + } + } else { + image = nil + } + + if let tintColorHex = dictionary["tintColor"] as? String { + tintColor = UIColor(hex: tintColorHex) + } else { + tintColor = UIColor.white + } + + super.init(dictionary: dictionary) + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Config/ElementConfig.swift b/Pods/MobilePlayer/MobilePlayer/Config/ElementConfig.swift new file mode 100644 index 0000000000..474325d7e1 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Config/ElementConfig.swift @@ -0,0 +1,129 @@ +// +// ElementConfig.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/17/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import Foundation + +/// Determines the type of an element. +public enum ElementType: String { + + /// Element type is unknown, it won't be added to the UI hierarchy. + case Unknown = "unknown" + + /// Element is a label. + case Label = "label" + + /// Element is a button. + case Button = "button" + + /// Element is a button that can be toggled between two states. (e.g. Play/pause button) + case ToggleButton = "toggleButton" + + /// Element is a slider. + case Slider = "slider" +} + +/// Determines how an element's width will be calculated. +public enum ElementWidthCalculation: String { + + /// Element width will always be as defined in its `width` property. + case AsDefined = "asDefined" + + /// Element width will be adjusted to fit its contents. + case Fit = "fit" + + /// Element width will be adjusted to fill the remaining horizontal space in its container. + case Fill = "fill" +} + +/// Holds basic element configuration values. +public class ElementConfig { + + /// Type of the element. Default value is `.Unknown`. + public let type: ElementType + + /// Identifier of the element. + /// + /// * Special identifiers are: + /// * Labels + /// * "title" + /// * "currentTime" + /// * "remainingTime" + /// * "duration" + /// * Buttons + /// * "close" + /// * "action" + /// * Toggle Buttons + /// * "play" + /// * Sliders + /// * "playback" + public let identifier: String? + + /// How the width of the element will be calculated. Default value is `.Fill` for title label and playback slider, + /// `.Fit` for other labels, and `.AsDefined` for the rest. + public let widthCalculation: ElementWidthCalculation + + /// Element width, effective only if `widthCalculation` is set to `.AsDefined`. Default value is `40`. + public let width: CGFloat + + /// The horizontal space to the left of this element that will be left empty. Default value is `0`. + public let marginLeft: CGFloat + + /// The horizontal space to the right of this element that will be left empty. Default value is `0`. + public let marginRight: CGFloat + + /// Initializes using default values. + public convenience init() { + self.init(dictionary: [String: Any]()) + } + + /// Initializes using a dictionary. + /// + /// * Key for `type` is `"type"` and its value should be a raw `ElementType` enum value. + /// * Key for `identifier` is `"identifier"` and its value should be a string. + /// * Key for `widthCalculation` is `"widthCalculation"` and its value should be a raw `ElementWidthCalculation` enum + /// value. + /// * Key for `width` is `"width"` and its value should be a number. + /// * Key for `marginLeft` is `"marginLeft"` and its value should be a number. + /// * Key for `marginRight` is `"marginRight"` and its value should be a number. + /// + /// - parameters: + /// - dictionary: Element configuration dictionary. + public init(dictionary: [String: Any]) { + // Values need to be AnyObject for type conversions to work correctly. + let dictionary = dictionary as [String: AnyObject] + + if + let elementTypeString = dictionary["type"] as? String, + let elementType = ElementType(rawValue: elementTypeString) { + type = elementType + } else { + type = .Unknown + } + + let id = dictionary["identifier"] as? String + self.identifier = id + + let isTitleLabel = (type == .Label && id == "title") + let isPlaybackSlider = (type == .Slider && id == "playback") + if + let elementWidthCalculationString = dictionary["widthCalculation"] as? String, + let elementWidthCalculation = ElementWidthCalculation(rawValue: elementWidthCalculationString) { + widthCalculation = elementWidthCalculation + } else if isTitleLabel || isPlaybackSlider { + widthCalculation = .Fill + } else if type == .Label { + widthCalculation = .Fit + } else { + widthCalculation = .AsDefined + } + + width = (dictionary["width"] as? CGFloat) ?? 40 + marginLeft = (dictionary["marginLeft"] as? CGFloat) ?? 0 + marginRight = (dictionary["marginRight"] as? CGFloat) ?? 0 + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Config/LabelConfig.swift b/Pods/MobilePlayer/MobilePlayer/Config/LabelConfig.swift new file mode 100644 index 0000000000..cfc1153922 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Config/LabelConfig.swift @@ -0,0 +1,59 @@ +// +// LabelConfig.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/15/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +/// Holds label configuration values. +public class LabelConfig: ElementConfig { + + /// Initial text for the label. + public let text: String? + + /// Label font. Default value is system font of size 14 (16 if `identifier` is `"title"`). + public let font: UIFont + + /// Color of the text. Default value is white. + public let textColor: UIColor + + /// Initializes using default values. + public convenience init() { + self.init(dictionary: [String: Any]()) + } + + /// Initializes using a dictionary. + /// + /// * Key for `text` is `"text"` and its value should be a string. + /// * Keys for `font` are `"font"` and `"size"`; value of `"font"` should be a font name, and `"size"` should be a + /// number. + /// * Key for `textColor` is `"textColor"` and its value should be a color hex string. + /// + /// - parameters: + /// - dictionary: Label configuration dictionary. + public override init(dictionary: [String: Any]) { + // Values need to be AnyObject for type conversions to work correctly. + let dictionary = dictionary as [String: AnyObject] + + text = dictionary["text"] as? String + + let fontName = dictionary["font"] as? String + let size = (dictionary["size"] as? CGFloat) ?? ((dictionary["identifier"] as? String) == "title" ? 16 : 14) + if let fontName = fontName, let font = UIFont(name: fontName, size: size) { + self.font = font + } else { + font = UIFont.systemFont(ofSize: size) + } + + if let textColorHex = dictionary["textColor"] as? String { + textColor = UIColor(hex: textColorHex) + } else { + textColor = UIColor.white + } + + super.init(dictionary: dictionary) + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Config/MobilePlayerConfig.swift b/Pods/MobilePlayer/MobilePlayer/Config/MobilePlayerConfig.swift new file mode 100644 index 0000000000..0f12f351da --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Config/MobilePlayerConfig.swift @@ -0,0 +1,73 @@ +// +// MobilePlayerConfig.swift +// MobilePlayer +// +// Created by Baris Sencan on 12/02/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import Foundation + +/// Holds player configuration values. +public class MobilePlayerConfig { + + /// Watermark configuration. + public let watermarkConfig: WatermarkConfig? + + /// Top controls bar configuration. + public let topBarConfig: BarConfig + + /// Bottom controls bar configuration. + public let bottomBarConfig: BarConfig + + /// Initializes with default values. + public convenience init() { + self.init(dictionary: [String: Any]()) + } + + /// Initializes using a configuration JSON file. + /// + /// - parameters: + /// - fileURL: URL indicating the location of the configuration file. + public convenience init(fileURL: URL) { + if + let jsonString = (try? String(contentsOf: fileURL, encoding: String.Encoding.utf8)), + let jsonData = jsonString.data(using: String.Encoding.utf8), + let dictionary = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [String: AnyObject] { + self.init(dictionary: dictionary) + } else { + self.init() + } + } + + /// Initializes using a dictionary. + /// + /// * Key for `watermarkConfig` is `"watermark"` and its value should be a watermark configuration dictionary. + /// * Key for `topBarConfig` is `"topBar"` and its value should be a bar configuration dictionary. + /// * Key for `bottomBarConfig` is `"bottomBar"` and its value should be a bar configuration dictionary. + /// + /// - parameters: + /// - dictionary: Configuration dictionary. + public init(dictionary: [String: Any]) { + // Values need to be AnyObject for type conversions to work correctly. + let dictionary = dictionary as [String: AnyObject] + + if let watermarkDictionary = dictionary["watermark"] as? [String: Any] { + watermarkConfig = WatermarkConfig(dictionary: watermarkDictionary) + } else { + watermarkConfig = nil + } + + if let topBarDictionary = dictionary["topBar"] as? [String: Any] { + topBarConfig = BarConfig(dictionary: topBarDictionary) + } else { + topBarConfig = BarConfig() + } + + if let bottomBarDictionary = dictionary["bottomBar"] as? [String: Any] { + bottomBarConfig = BarConfig(dictionary: bottomBarDictionary) + } else { + bottomBarConfig = BarConfig() + } + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Config/SliderConfig.swift b/Pods/MobilePlayer/MobilePlayer/Config/SliderConfig.swift new file mode 100644 index 0000000000..f465f30e7b --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Config/SliderConfig.swift @@ -0,0 +1,113 @@ +// +// SliderConfig.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/15/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +/// Holds slider configuration values. +public class SliderConfig: ElementConfig { + + /// Height of the slider track. + public let trackHeight: CGFloat + + /// Corner radius of the slider track. + public let trackCornerRadius: CGFloat + + /// Color of the track to the left of slider thumb. + public let minimumTrackTintColor: UIColor + + /// Color of the parts of the track which fall to the right side of slider thumb and represent available value + /// (e.g. buffered duration of a video). + public let availableTrackTintColor: UIColor + + /// Color of the track to the right of slider thumb. + public let maximumTrackTintColor: UIColor + + /// Color of the slider thumb. + public let thumbTintColor: UIColor + + /// Width of the slider thumb. + public let thumbWidth: CGFloat + + /// Height of the slider thumb. + public let thumbHeight: CGFloat + + /// Corner radius of the slider thumb. + public let thumbCornerRadius: CGFloat + + /// Border width of the slider thumb. + public let thumbBorderWidth: CGFloat + + /// Border color of the slider thumb. + public let thumbBorderColor: CGColor + + /// Initializes using default values. + public convenience init() { + self.init(dictionary: [String: Any]()) + } + + /// Initializes using a dictionary. + /// + /// * Key for `trackHeight` is `"trackHeight"` and its value should be a number. + /// * Key for `trackCornerRadius` is `"trackCornerRadius"` and its value should be a number. + /// * Key for `minimumTrackTintColor` is `"minimumTrackTintColor"` and its value should be a color hex string. + /// * Key for `availableTrackTintColor` is `"availableTrackTintColor"` and its value should be a color hex string. + /// * Key for `maximumTrackTintColor` is `"maximumTrackTintColor"` and its value should be a color hex string. + /// * Key for `thumbTintColor` is `"thumbTintColor"` and its value should be a color hex string. + /// * Key for `thumbWidth` is `"thumbWidth"` and its value should be a number. + /// * Key for `thumbHeight` is `"thumbHeight"` and its value should be a number. + /// * Key for `thumbCornerRadius` is `"thumbCornerRadius"` and its value should be a number. + /// * Key for `thumbBorderWidth` is `"thumbBorderWidth"` and its value should be a number. + /// * Key for `thumbBorderColor` is `"thumbBorderColor"` and its value should be a color hex string. + /// + /// - parameters: + /// - dictionary: Toggle button configuration dictionary. + public override init(dictionary: [String: Any]) { + // Values need to be AnyObject for type conversions to work correctly. + let dictionary = dictionary as [String: AnyObject] + + trackHeight = (dictionary["trackHeight"] as? CGFloat) ?? 6 + trackCornerRadius = (dictionary["trackCornerRadius"] as? CGFloat) ?? 3 + + if let minimumTrackTintColorHex = dictionary["minimumTrackTintColor"] as? String { + minimumTrackTintColor = UIColor(hex: minimumTrackTintColorHex) + } else { + minimumTrackTintColor = UIColor(white: 0.9, alpha: 1) + } + + if let availableTrackTintColorHex = dictionary["availableTrackTintColor"] as? String { + availableTrackTintColor = UIColor(hex: availableTrackTintColorHex) + } else { + availableTrackTintColor = UIColor(white: 0.6, alpha: 1) + } + + if let maximumTrackTintColorHex = dictionary["maximumTrackTintColor"] as? String { + maximumTrackTintColor = UIColor(hex: maximumTrackTintColorHex) + } else { + maximumTrackTintColor = UIColor(white: 0.3, alpha: 1) + } + + if let thumbTintColorHex = dictionary["thumbTintColor"] as? String { + thumbTintColor = UIColor(hex: thumbTintColorHex) + } else { + thumbTintColor = UIColor.white + } + + thumbWidth = (dictionary["thumbWidth"] as? CGFloat) ?? 16 + thumbHeight = (dictionary["thumbHeight"] as? CGFloat) ?? 16 + thumbCornerRadius = (dictionary["thumbCornerRadius"] as? CGFloat) ?? 8 + thumbBorderWidth = (dictionary["thumbBorderWidth"] as? CGFloat) ?? 0 + + if let thumbBorderColorHex = dictionary["thumbBorderColor"] as? String { + thumbBorderColor = UIColor(hex: thumbBorderColorHex).cgColor + } else { + thumbBorderColor = UIColor.clear.cgColor + } + + super.init(dictionary: dictionary) + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Config/ToggleButtonConfig.swift b/Pods/MobilePlayer/MobilePlayer/Config/ToggleButtonConfig.swift new file mode 100644 index 0000000000..49df09ba0e --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Config/ToggleButtonConfig.swift @@ -0,0 +1,82 @@ +// +// ToggleButtonConfig.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/15/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +/// Holds toggle button configuration values. +public class ToggleButtonConfig: ElementConfig { + + /// Button height. Default value is 40. + public let height: CGFloat + + /// Button image when it's not toggled. + public let image: UIImage? + + /// Button tint color when it's not toggled. Default value is white. + public let tintColor: UIColor + + /// Button image when it's toggled. + public let toggledImage: UIImage? + + /// Button tint color when it's toggled. Default value is white. + public let toggledTintColor: UIColor + + /// Initializes using default values. + public convenience init() { + self.init(dictionary: [String: Any]()) + } + + /// Initializes using a dictionary. + /// + /// * Key for `height` is `"height"` and its value should be a number. + /// * Key for `image` is `"image"` and its value should be an image asset name. + /// * Key for `tintColor` is `"tintColor"` and its value should be a color hex string. + /// * Key for `toggledImage` is `"toggledImage"` and its value should be an image asset name. + /// * Key for `toggledTintColor` is `"toggledTintColor"` and its value should be a color hex string. + /// + /// - parameters: + /// - dictionary: Toggle button configuration dictionary. + public override init(dictionary: [String: Any]) { + // Values need to be AnyObject for type conversions to work correctly. + let dictionary = dictionary as [String: AnyObject] + + let identifier = dictionary["identifier"] as? String + + height = (dictionary["height"] as? CGFloat) ?? 40 + + if let imageName = dictionary["image"] as? String { + image = UIImage(named: imageName) + } else if identifier == "play" { + image = UIImage(podResourceNamed: "MLPlayButton")?.template + } else { + image = nil + } + + if let tintColorHex = dictionary["tintColor"] as? String { + tintColor = UIColor(hex: tintColorHex) + } else { + tintColor = UIColor.white + } + + if let toggledImageName = dictionary["toggledImage"] as? String { + toggledImage = UIImage(named: toggledImageName) + } else if identifier == "play" { + toggledImage = UIImage(podResourceNamed: "MLPauseButton")?.template + } else { + toggledImage = nil + } + + if let toggledTintColorHex = dictionary["toggledTintColor"] as? String { + toggledTintColor = UIColor(hex: toggledTintColorHex) + } else { + toggledTintColor = UIColor.white + } + + super.init(dictionary: dictionary) + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Config/WatermarkConfig.swift b/Pods/MobilePlayer/MobilePlayer/Config/WatermarkConfig.swift new file mode 100644 index 0000000000..97ad28917c --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Config/WatermarkConfig.swift @@ -0,0 +1,80 @@ +// +// WatermarkConfig.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/18/15. +// Copyright © 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +/// Indicates the position of watermark in content area. +public enum WatermarkPosition: String { + + /// Place watermark at the center. + case Center = "center" + + /// Place watermark at the top edge, centered horizontally. + case Top = "top" + + /// Place watermark at the top right corner. + case TopRight = "topRight" + + /// Place watermark at the right edge, centered vertically. + case Right = "right" + + /// Place watermark at the bottom right corner. + case BottomRight = "bottomRight" + + /// Place watermark at the bottom edge, centered horizontally. + case Bottom = "bottom" + + /// Place watermark at the bottom left corner. + case BottomLeft = "bottomLeft" + + /// Place watermark at the left edge, centered vertically. + case Left = "left" + + /// Place watermark at the top left corner. + case TopLeft = "topLeft" +} + +/// Holds watermark configuration values. +public class WatermarkConfig { + + /// Watermark image. + public let image: UIImage? + + /// Watermark position. Default value is `.BottomRight`. + public let position: WatermarkPosition + + /// Initializes using default values. + public convenience init() { + self.init(dictionary: [String: Any]()) + } + + /// Initializes using a dictionary. + /// + /// * Key for `image` is `"image"` and its value should be an image asset name. + /// * Key for `position` is `"position"` and its value should be a raw `WaterMarkPosition` enum value. + /// + /// - parameters: + /// - dictionary: Watermark configuration dictionary. + public init(dictionary: [String: Any]) { + // Values need to be AnyObject for type conversions to work correctly. + let dictionary = dictionary as [String: AnyObject] + + if let imageName = dictionary["image"] as? String { + image = UIImage(named: imageName) + } else { + image = nil + } + if + let positionString = dictionary["position"] as? String, + let positionValue = WatermarkPosition(rawValue: positionString) { + position = positionValue + } else { + position = .BottomRight + } + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Extensions/ClosureSupport.swift b/Pods/MobilePlayer/MobilePlayer/Extensions/ClosureSupport.swift new file mode 100644 index 0000000000..3f2abc5dd4 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Extensions/ClosureSupport.swift @@ -0,0 +1,66 @@ +// +// ClosureSupport.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/10/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +class CallbackContainer { + let callback: () -> Void + + init(callback: @escaping () -> Void) { + self.callback = callback + } + + @objc func callCallback() { + callback() + } +} + +extension Timer { + + class func scheduledTimerWithTimeInterval(ti: TimeInterval, callback: @escaping () -> Void, repeats: Bool) -> Timer { + let callbackContainer = CallbackContainer(callback: callback) + return scheduledTimer( + timeInterval: ti, + target: callbackContainer, + selector: #selector(CallbackContainer.callCallback), + userInfo: nil, + repeats: repeats) + } +} + +extension UIControl { + + @discardableResult + func addCallback(callback: @escaping () -> Void, forControlEvents controlEvents: UIControlEvents) -> UnsafeMutableRawPointer { + let callbackContainer = CallbackContainer(callback: callback) + let key = Unmanaged.passUnretained(callbackContainer).toOpaque() + objc_setAssociatedObject(self, key, callbackContainer, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) + addTarget(callbackContainer, action: #selector(CallbackContainer.callCallback), for: controlEvents) + return key + } + + func removeCallbackForKey(key: UnsafeRawPointer) { + if let callbackContainer = objc_getAssociatedObject(self, key) as? CallbackContainer { + removeTarget(callbackContainer, action: #selector(CallbackContainer.callCallback), for: .allEvents) + objc_setAssociatedObject(self, key, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +extension UIGestureRecognizer { + + convenience init(callback: @escaping () -> Void) { + let callbackContainer = CallbackContainer(callback: callback) + self.init(target: callbackContainer, action: #selector(CallbackContainer.callCallback)) + objc_setAssociatedObject( + self, + Unmanaged.passUnretained(callbackContainer).toOpaque(), + callbackContainer, + objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Extensions/UIColor+Hex.swift b/Pods/MobilePlayer/MobilePlayer/Extensions/UIColor+Hex.swift new file mode 100644 index 0000000000..e10539802d --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Extensions/UIColor+Hex.swift @@ -0,0 +1,54 @@ +// +// UIColor+Extension.swift +// MobilePlayer +// +// Created by Toygar Dündaralp on 27/05/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +extension UIColor { + + convenience init(hex: String) { + var red = CGFloat(0) + var green = CGFloat(0) + var blue = CGFloat(0) + var alpha = CGFloat(1) + if hex.hasPrefix("#") { + let index = hex.index(hex.startIndex, offsetBy: 1) + let hex = hex.substring(from: index) + let scanner = Scanner(string: hex) + var hexValue = CUnsignedLongLong(0) + if scanner.scanHexInt64(&hexValue) { + switch (hex.characters.count) { + case 3: + red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 + green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 + blue = CGFloat(hexValue & 0x00F) / 15.0 + case 4: + red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 + green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 + blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 + alpha = CGFloat(hexValue & 0x000F) / 15.0 + case 6: + red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 + green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 + blue = CGFloat(hexValue & 0x0000FF) / 255.0 + case 8: + red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 + green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 + blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 + alpha = CGFloat(hexValue & 0x000000FF) / 255.0 + default: + assert(false, "Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8") + } + } else { + assert(false, "Scan hex error") + } + } else { + assert(false, "Invalid RGB string, missing '#' as prefix") + } + self.init(red: red, green: green, blue: blue, alpha: alpha) + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Extensions/UIImage+CocoaPods.swift b/Pods/MobilePlayer/MobilePlayer/Extensions/UIImage+CocoaPods.swift new file mode 100644 index 0000000000..a315825368 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Extensions/UIImage+CocoaPods.swift @@ -0,0 +1,24 @@ +// +// UIImage+CocoaPods.swift +// MobilePlayer +// +// Created by Baris Sencan on 16/11/2015. +// Copyright © 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +extension UIImage { + + convenience init?(podResourceNamed name: String) { + let bundleUrl = + Bundle(for: MobilePlayerViewController.self).url(forResource: "MobilePlayer", withExtension: "bundle") ?? + Bundle(for: MobilePlayerViewController.self).bundleURL + let bundle = Bundle(url: bundleUrl) + self.init(named: name, in: bundle, compatibleWith: nil) + } + + var template: UIImage { + return withRenderingMode(.alwaysTemplate) + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Helpers/StateHelper.swift b/Pods/MobilePlayer/MobilePlayer/Helpers/StateHelper.swift new file mode 100644 index 0000000000..f7549bf0bc --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Helpers/StateHelper.swift @@ -0,0 +1,30 @@ +// +// StateHelper.swift +// MobilePlayer +// +// Created by Toygar Dündaralp on 8/6/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit +import MediaPlayer + +struct StateHelper { + + static func calculateStateUsing( + previousState: MobilePlayerViewController.State, + andPlaybackState playbackState: MPMoviePlaybackState) -> MobilePlayerViewController.State { + switch playbackState { + case .stopped: + return .idle + case .playing: + return .playing + case .paused: + return .paused + case .interrupted: + return .buffering + case .seekingForward, .seekingBackward: + return previousState + } + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/MobilePlayerNotification.swift b/Pods/MobilePlayer/MobilePlayer/MobilePlayerNotification.swift new file mode 100644 index 0000000000..392d2af50d --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/MobilePlayerNotification.swift @@ -0,0 +1,20 @@ +// +// MobilePlayerNotification.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/29/15. +// Copyright © 2015 MovieLaLa. All rights reserved. +// + +import Foundation + +/// Posted when a MobilePlayerViewController encounters an error loading or playing a media file. The userInfo +/// dictionary of this notification contains the MobilePlayerErrorUserInfoKey key, which indicates the error that +/// was encountered. +public let MobilePlayerDidEncounterErrorNotification = "MobilePlayerDidEncounterError" + +/// The value of this key is an NSError containing the error encountered while trying to load or play a media file. +public let MobilePlayerErrorUserInfoKey = "error" + +/// Posted when a MobilePlayerViewController changes state. There is no userInfo dictionary. +public let MobilePlayerStateDidChangeNotification = "MobilePlayerStateDidChange" diff --git a/Pods/MobilePlayer/MobilePlayer/MobilePlayerOverlayViewController.swift b/Pods/MobilePlayer/MobilePlayer/MobilePlayerOverlayViewController.swift new file mode 100644 index 0000000000..0984a72eff --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/MobilePlayerOverlayViewController.swift @@ -0,0 +1,35 @@ +// +// MobilePlayerOverlayViewController.swift +// MobilePlayer +// +// Created by Baris Sencan on 12/02/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +struct TimedOverlayInfo { + let startTime: TimeInterval + let duration: TimeInterval + let overlay: MobilePlayerOverlayViewController +} + +protocol MobilePlayerOverlayViewControllerDelegate: class { + func dismiss(mobilePlayerOverlayViewController: MobilePlayerOverlayViewController) +} + +/// A view controller used for presenting views on top of player content. Meant to be subclassed. +open class MobilePlayerOverlayViewController: UIViewController { + weak var delegate: MobilePlayerOverlayViewControllerDelegate? + + /// The MobilePlayerViewController instance that the overlay is being shown by. + /// It's value is nil if the overlay is not being shown at the time this property is accessed. + public var mobilePlayer: MobilePlayerViewController? { + return delegate as? MobilePlayerViewController + } + + /// Causes the view controller's view to be removed from on top of player content if it is being displayed. + public func dismiss() { + delegate?.dismiss(mobilePlayerOverlayViewController: self) + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/MobilePlayerViewController.swift b/Pods/MobilePlayer/MobilePlayer/MobilePlayerViewController.swift new file mode 100644 index 0000000000..a45095fa26 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/MobilePlayerViewController.swift @@ -0,0 +1,642 @@ +// +// MobilePlayerViewController.swift +// MobilePlayer +// +// Created by Baris Sencan on 12/02/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit +import MediaPlayer + +/// A view controller for playing media content. +open class MobilePlayerViewController: MPMoviePlayerViewController { + // MARK: Playback State + + /// Playback state. + public enum State { + + /// Either playback has not started or playback was stopped due to a `stop()` call or an error. When an error + /// occurs, a corresponding `MobilePlayerDidEncounterErrorNotification` notification is posted. + case idle + + /// The video will start playing, but sufficient data to start playback has to be loaded first. + case buffering + + /// The video is currently playing. + case playing + + /// The video is currently paused. + case paused + } + + /// The previous value of `state`. Default is `.Idle`. + public private(set) var previousState: State = .idle + + /// Current `State` of the player. Default is `.Idle`. + public private(set) var state: State = .idle { + didSet { + previousState = oldValue + } + } + + // MARK: Player Configuration + + // TODO: Move inside MobilePlayerConfig + private static let playbackInterfaceUpdateInterval = 0.25 + + /// The global player configuration object that is loaded by a player if none is passed for its + /// initialization. + public static let globalConfig = MobilePlayerConfig() + + /// The configuration object that was used to initialize the player, may point to the global player configuration + /// object. + public let config: MobilePlayerConfig + + // MARK: Mapped Properties + + /// A localized string that represents the video this controller manages. Setting a value will update the title label + /// in the user interface if one exists. + open override var title: String? { + didSet { + guard let titleLabel = getViewForElementWithIdentifier("title") as? Label else { return} + titleLabel.text = title + titleLabel.superview?.setNeedsLayout() + } + } + + // MARK: Private Properties + private let controlsView: MobilePlayerControlsView + private var previousStatusBarHiddenValue: Bool? + private var previousStatusBarStyle: UIStatusBarStyle! + private var isFirstPlay = true + fileprivate var seeking = false + fileprivate var wasPlayingBeforeSeek = false + private var playbackInterfaceUpdateTimer: Timer? + private var hideControlsTimer: Timer? + + // MARK: Initialization + + /// Initializes a player with content given by `contentURL`. If provided, the overlay view controllers used to + /// initialize the player should be different instances from each other. + /// + /// - parameters: + /// - contentURL: URL of the content that will be used for playback. + /// - config: Player configuration. Defaults to `globalConfig`. + /// - prerollViewController: Pre-roll view controller. Defaults to `nil`. + /// - pauseOverlayViewController: Pause overlay view controller. Defaults to `nil`. + /// - postrollViewController: Post-roll view controller. Defaults to `nil`. + public init(contentURL: URL, + config: MobilePlayerConfig = MobilePlayerViewController.globalConfig, + prerollViewController: MobilePlayerOverlayViewController? = nil, + pauseOverlayViewController: MobilePlayerOverlayViewController? = nil, + postrollViewController: MobilePlayerOverlayViewController? = nil) { + self.config = config + controlsView = MobilePlayerControlsView(config: config) + self.prerollViewController = prerollViewController + self.pauseOverlayViewController = pauseOverlayViewController + self.postrollViewController = postrollViewController + super.init(contentURL: contentURL) + initializeMobilePlayerViewController() + } + + /// Returns a player initialized from data in a given unarchiver. `globalConfig` is used for configuration in this + /// case. In most cases the other intializer should be used. + /// + /// - parameters: + /// - coder: An unarchiver object. + public required init?(coder aDecoder: NSCoder) { + config = MobilePlayerViewController.globalConfig + controlsView = MobilePlayerControlsView(config: config) + self.prerollViewController = nil + self.pauseOverlayViewController = nil + self.postrollViewController = nil + super.init(coder: aDecoder) + initializeMobilePlayerViewController() + } + + private func initializeMobilePlayerViewController() { + view.clipsToBounds = true + edgesForExtendedLayout = [] + moviePlayer.scalingMode = .aspectFit + moviePlayer.controlStyle = .none + initializeNotificationObservers() + initializeControlsView() + parseContentURLIfNeeded() + if let watermarkConfig = config.watermarkConfig { + showOverlayViewController(WatermarkViewController(config: watermarkConfig)) + } + } + + private func initializeNotificationObservers() { + let notificationCenter = NotificationCenter.default + notificationCenter.addObserver( + forName: NSNotification.Name.MPMoviePlayerPlaybackStateDidChange, + object: moviePlayer, + queue: OperationQueue.main) { [weak self] notification in + guard let slf = self else { + return + } + slf.handleMoviePlayerPlaybackStateDidChangeNotification() + NotificationCenter.default.post(name: NSNotification.Name(rawValue: MobilePlayerStateDidChangeNotification), object: slf) + } + notificationCenter.removeObserver( + self, + name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, + object: moviePlayer) + notificationCenter.addObserver( + forName: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, + object: moviePlayer, + queue: OperationQueue.main) { [weak self] notification in + guard let slf = self else { + return + } + if + let userInfo = notification.userInfo as? [String: AnyObject], + let error = userInfo["error"] as? NSError { + NotificationCenter.default.post(name: NSNotification.Name(rawValue: MobilePlayerDidEncounterErrorNotification), object: self, userInfo: [MobilePlayerErrorUserInfoKey: error]) + } + if let postrollVC = slf.postrollViewController { + slf.prerollViewController?.dismiss() + slf.pauseOverlayViewController?.dismiss() + slf.showOverlayViewController(postrollVC) + } + } + } + + private func initializeControlsView() { + (getViewForElementWithIdentifier("playback") as? Slider)?.delegate = self + + (getViewForElementWithIdentifier("close") as? Button)?.addCallback( + callback: { [weak self] in + guard let slf = self else { + return + } + if let navigationController = slf.navigationController { + navigationController.popViewController(animated: true) + } else if let presentingController = slf.presentingViewController { + presentingController.dismissMoviePlayerViewControllerAnimated() + } + }, + forControlEvents: .touchUpInside) + + if let actionButton = getViewForElementWithIdentifier("action") as? Button { + actionButton.isHidden = true // Initially hidden until 1 or more `activityItems` are set. + actionButton.addCallback( + callback: { [weak self] in + guard let slf = self else { + return + } + slf.showContentActions(sourceView: actionButton) + }, + forControlEvents: .touchUpInside) + } + + (getViewForElementWithIdentifier("play") as? ToggleButton)?.addCallback( + callback: { [weak self] in + guard let slf = self else { + return + } + slf.resetHideControlsTimer() + slf.state == .playing ? slf.pause() : slf.play() + }, + forControlEvents: .touchUpInside) + + initializeControlsViewTapRecognizers() + } + + private func initializeControlsViewTapRecognizers() { + let singleTapRecognizer = UITapGestureRecognizer { [weak self] in self?.handleContentTap() } + singleTapRecognizer.numberOfTapsRequired = 1 + controlsView.addGestureRecognizer(singleTapRecognizer) + let doubleTapRecognizer = UITapGestureRecognizer { [weak self] in self?.handleContentDoubleTap() } + doubleTapRecognizer.numberOfTapsRequired = 2 + controlsView.addGestureRecognizer(doubleTapRecognizer) + singleTapRecognizer.require(toFail: doubleTapRecognizer) + } + + // MARK: View Controller Lifecycle + + /// Called after the controller'€™s view is loaded into memory. + /// + /// This method is called after the view controller has loaded its view hierarchy into memory. This method is + /// called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the + /// `loadView` method. You usually override this method to perform additional initialization on views that were + /// loaded from nib files. + /// + /// If you override this method make sure you call super's implementation. + open override func viewDidLoad() { + super.viewDidLoad() + view.addSubview(controlsView) + playbackInterfaceUpdateTimer = Timer.scheduledTimerWithTimeInterval( + ti: MobilePlayerViewController.playbackInterfaceUpdateInterval, + callback: { [weak self] in self?.updatePlaybackInterface() }, + repeats: true) + if let prerollViewController = prerollViewController { + shouldAutoplay = false + showOverlayViewController(prerollViewController) + } + } + + /// Called to notify the view controller that its view is about to layout its subviews. + /// + /// When a view'€™s bounds change, the view adjusts the position of its subviews. Your view controller can override + /// this method to make changes before the view lays out its subviews. + /// + /// The default implementation of this method sets the frame of the controls view. + open override func viewWillLayoutSubviews() { + super.viewWillLayoutSubviews() + controlsView.frame = view.bounds + } + + /// Notifies the view controller that its view is about to be added to a view hierarchy. + /// + /// If `true`, the view is being added to the window using an animation. + /// + /// The default implementation of this method hides the status bar. + /// + /// - parameters: + /// - animated: If `true`, the view is being added to the window using an animation. + open override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + // Force hide status bar. + previousStatusBarHiddenValue = UIApplication.shared.isStatusBarHidden + UIApplication.shared.isStatusBarHidden = true + setNeedsStatusBarAppearanceUpdate() + } + + /// Notifies the view controller that its view is about to be removed from a view hierarchy. + /// + /// If `true`, the disappearance of the view is being animated. + /// + /// The default implementation of this method stops playback and restores status bar appearance to how it was before + /// the view appeared. + /// + /// - parameters: + /// - animated: If `true`, the disappearance of the view is being animated. + open override func viewWillDisappear(_ animated: Bool) { + // Restore status bar appearance. + if let previousStatusBarHidden = previousStatusBarHiddenValue { + UIApplication.shared.isStatusBarHidden = previousStatusBarHidden + setNeedsStatusBarAppearanceUpdate() + } + super.viewWillDisappear(animated) + stop() + } + + // MARK: Deinitialization + + deinit { + playbackInterfaceUpdateTimer?.invalidate() + hideControlsTimer?.invalidate() + NotificationCenter.default.removeObserver(self) + } + + // MARK: Playback + + /// Indicates whether content should begin playback automatically. + /// + /// The default value of this property is true. This property determines whether the playback of network-based + /// content begins automatically when there is enough buffered data to ensure uninterrupted playback. + public var shouldAutoplay: Bool { + get { + return moviePlayer.shouldAutoplay + } + set { + moviePlayer.shouldAutoplay = newValue + } + } + + /// Initiates playback of current content. + /// + /// Starting playback causes dismiss to be called on prerollViewController, pauseOverlayViewController + /// and postrollViewController. + public func play() { + moviePlayer.play() + } + + /// Pauses playback of current content. + /// + /// Pausing playback causes pauseOverlayViewController to be shown. + public func pause() { + moviePlayer.pause() + } + + /// Ends playback of current content. + public func stop() { + moviePlayer.stop() + } + + // MARK: Video Rendering + + /// Makes playback content fit into player's view. + public func fitVideo() { + moviePlayer.scalingMode = .aspectFit + } + + /// Makes playback content fill player's view. + public func fillVideo() { + moviePlayer.scalingMode = .aspectFill + } + + /// Makes playback content switch between fill/fit modes when content area is double tapped. Overriding this method + /// is recommended if you want to change this behavior. + public func handleContentDoubleTap() { + // TODO: videoScalingMode property and enum. + moviePlayer.scalingMode != .aspectFill ? fillVideo() : fitVideo() + } + + // MARK: Social + + /// An array of activity items that will be used for presenting a `UIActivityViewController` when the action + /// button is pressed (if it exists). If content is playing, it is paused automatically at presentation and will + /// continue after the controller is dismissed. Override `showContentActions()` if you want to change the button's + /// behavior. + public var activityItems: [Any]? { + didSet { + let isEmpty = activityItems?.isEmpty ?? true + getViewForElementWithIdentifier("action")?.isHidden = isEmpty + } + } + + /// Method that is called when a control interface button with identifier "action" is tapped. Presents a + /// `UIActivityViewController` with `activityItems` set as its activity items. If content is playing, it is paused + /// automatically at presentation and will continue after the controller is dismissed. Overriding this method is + /// recommended if you want to change this behavior. + /// + /// parameters: + /// - sourceView: On iPads the activity view controller is presented as a popover and a source view needs to + /// provided or a crash will occur. + open func showContentActions(sourceView: UIView? = nil) { + guard let activityItems = activityItems, !activityItems.isEmpty else { return } + let wasPlaying = (state == .playing) + moviePlayer.pause() + let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) + activityVC.excludedActivityTypes = [ + .assignToContact, + .saveToCameraRoll, + .postToVimeo, + .airDrop + ] + activityVC.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in + if wasPlaying { + self.moviePlayer.play() + } + } + if let sourceView = sourceView { + activityVC.popoverPresentationController?.sourceView = controlsView + activityVC.popoverPresentationController?.sourceRect = sourceView.convert( + sourceView.bounds, + to: controlsView) + } + present(activityVC, animated: true, completion: nil) + } + + // MARK: Controls + + /// Indicates if player controls are hidden. Setting its value will animate controls in or out. + public var controlsHidden: Bool { + get { + return controlsView.controlsHidden + } + set { + newValue ? hideControlsTimer?.invalidate() : resetHideControlsTimer() + controlsView.controlsHidden = newValue + } + } + + /// Returns the view associated with given player control element identifier. + /// + /// - parameters: + /// - identifier: Element identifier. + /// - returns: View or nil if element is not found. + public func getViewForElementWithIdentifier(_ identifier: String) -> UIView? { + if let view = controlsView.topBar.getViewForElementWithIdentifier(identifier: identifier) { + return view + } + return controlsView.bottomBar.getViewForElementWithIdentifier(identifier: identifier) + } + + /// Hides/shows controls when content area is tapped once. Overriding this method is recommended if you want to change + /// this behavior. + public func handleContentTap() { + controlsHidden = !controlsHidden + } + + // MARK: Overlays + + private var timedOverlays = [TimedOverlayInfo]() + + /// The `MobilePlayerOverlayViewController` that will be presented on top of the player content at start. If a + /// controller is set then content will not start playing automatically even if `shouldAutoplay` is `true`. The + /// controller will dismiss if user presses the play button or `play()` is called. + public let prerollViewController: MobilePlayerOverlayViewController? + + /// The `MobilePlayerOverlayViewController` that will be presented on top of the player content whenever playback is + /// paused. Does not include pauses in playback due to buffering. + public let pauseOverlayViewController: MobilePlayerOverlayViewController? + + /// The `MobilePlayerOverlayViewController` that will be presented on top of the player content when playback + /// finishes. + public let postrollViewController: MobilePlayerOverlayViewController? + + /// Presents given overlay view controller on top of the player content immediately, or at a given content time for + /// a given duration. Both starting time and duration parameters should be provided to show a timed overlay. + /// + /// - parameters: + /// - overlayViewController: The `MobilePlayerOverlayViewController` to be presented. + /// - startingAtTime: Content time the overlay will be presented at. + /// - forDuration: Added on top of `startingAtTime` to calculate the content time when overlay will be dismissed. + public func showOverlayViewController(_ overlayViewController: MobilePlayerOverlayViewController, + startingAtTime presentationTime: TimeInterval? = nil, + forDuration showDuration: TimeInterval? = nil) { + if let presentationTime = presentationTime, let showDuration = showDuration { + timedOverlays.append(TimedOverlayInfo( + startTime: presentationTime, + duration: showDuration, + overlay: overlayViewController)) + } else if overlayViewController.parent == nil { + overlayViewController.delegate = self + addChildViewController(overlayViewController) + overlayViewController.view.clipsToBounds = true + overlayViewController.view.frame = controlsView.overlayContainerView.bounds + controlsView.overlayContainerView.addSubview(overlayViewController.view) + overlayViewController.didMove(toParentViewController: self) + } + } + + /// Dismisses all currently presented overlay view controllers and clears any timed overlays. + public func clearOverlays() { + for timedOverlayInfo in timedOverlays { + timedOverlayInfo.overlay.dismiss() + } + timedOverlays.removeAll() + for childViewController in childViewControllers { + if childViewController is WatermarkViewController { continue } + (childViewController as? MobilePlayerOverlayViewController)?.dismiss() + } + } + + // MARK: Private Methods + + private func parseContentURLIfNeeded() { + guard let youtubeID = YoutubeParser.youtubeIDFromURL(url: moviePlayer.contentURL) else { return } + YoutubeParser.h264videosWithYoutubeID(youtubeID) { videoInfo, error in + if let error = error { + NotificationCenter.default.post(name: NSNotification.Name(rawValue: MobilePlayerDidEncounterErrorNotification), object: self, userInfo: [MobilePlayerErrorUserInfoKey: error]) + } + guard let videoInfo = videoInfo else { return } + self.title = self.title ?? videoInfo.title + if + let previewImageURLString = videoInfo.previewImageURL, + let previewImageURL = URL(string: previewImageURLString) { + URLSession.shared.dataTask(with: previewImageURL) { data, response, error in + guard let data = data else { return } + DispatchQueue.main.async { + self.controlsView.previewImageView.image = UIImage(data: data) + } + } + } + if let videoURL = videoInfo.videoURL { + self.moviePlayer.contentURL = URL(string: videoURL) + } + } + } + + private func doFirstPlaySetupIfNeeded() { + if isFirstPlay { + isFirstPlay = false + controlsView.previewImageView.isHidden = true + controlsView.activityIndicatorView.stopAnimating() + } + } + + private func updatePlaybackInterface() { + if let playbackSlider = getViewForElementWithIdentifier("playback") as? Slider { + playbackSlider.maximumValue = Float(moviePlayer.duration.isNormal ? moviePlayer.duration : 0) + if !seeking { + let sliderValue = Float(moviePlayer.currentPlaybackTime.isNormal ? moviePlayer.currentPlaybackTime : 0) + playbackSlider.setValue(value: sliderValue, animatedForDuration: MobilePlayerViewController.playbackInterfaceUpdateInterval) + } + let availableValue = Float(moviePlayer.playableDuration.isNormal ? moviePlayer.playableDuration : 0) + playbackSlider.setAvailableValue( + availableValue: availableValue, + animatedForDuration: MobilePlayerViewController.playbackInterfaceUpdateInterval) + } + if let currentTimeLabel = getViewForElementWithIdentifier("currentTime") as? Label { + currentTimeLabel.text = textForPlaybackTime(time: moviePlayer.currentPlaybackTime) + currentTimeLabel.superview?.setNeedsLayout() + } + if let remainingTimeLabel = getViewForElementWithIdentifier("remainingTime") as? Label { + remainingTimeLabel.text = "-\(textForPlaybackTime(time: moviePlayer.duration - moviePlayer.currentPlaybackTime))" + remainingTimeLabel.superview?.setNeedsLayout() + } + if let durationLabel = getViewForElementWithIdentifier("duration") as? Label { + durationLabel.text = textForPlaybackTime(time: moviePlayer.duration) + durationLabel.superview?.setNeedsLayout() + } + updateShownTimedOverlays() + } + + private func textForPlaybackTime(time: TimeInterval) -> String { + if !time.isNormal { + return "00:00" + } + let hours = Int(floor(time / 3600)) + let minutes = Int(floor((time / 60).truncatingRemainder(dividingBy: 60))) + let seconds = Int(floor(time.truncatingRemainder(dividingBy: 60))) + let minutesAndSeconds = NSString(format: "%02d:%02d", minutes, seconds) as String + if hours > 0 { + return NSString(format: "%02d:%@", hours, minutesAndSeconds) as String + } else { + return minutesAndSeconds + } + } + + private func resetHideControlsTimer() { + hideControlsTimer?.invalidate() + hideControlsTimer = Timer.scheduledTimerWithTimeInterval( + ti: 3, + callback: { + self.controlsView.controlsHidden = (self.state == .playing) + }, + repeats: false) + } + + private func handleMoviePlayerPlaybackStateDidChangeNotification() { + state = StateHelper.calculateStateUsing(previousState: previousState, andPlaybackState: moviePlayer.playbackState) + let playButton = getViewForElementWithIdentifier("play") as? ToggleButton + if state == .playing { + doFirstPlaySetupIfNeeded() + playButton?.toggled = true + if !controlsView.controlsHidden { + resetHideControlsTimer() + } + prerollViewController?.dismiss() + pauseOverlayViewController?.dismiss() + postrollViewController?.dismiss() + } else { + playButton?.toggled = false + hideControlsTimer?.invalidate() + controlsView.controlsHidden = false + if let pauseOverlayViewController = pauseOverlayViewController, (state == .paused && !seeking) { + showOverlayViewController(pauseOverlayViewController) + } + } + } + + private func updateShownTimedOverlays() { + let currentTime = self.moviePlayer.currentPlaybackTime + if !currentTime.isNormal { + return + } + DispatchQueue.global().async { + for timedOverlayInfo in self.timedOverlays { + if timedOverlayInfo.startTime <= currentTime && currentTime <= timedOverlayInfo.startTime + timedOverlayInfo.duration { + if timedOverlayInfo.overlay.parent == nil { + DispatchQueue.main.async { + self.showOverlayViewController(timedOverlayInfo.overlay) + } + } + } else if timedOverlayInfo.overlay.parent != nil { + DispatchQueue.main.async { + timedOverlayInfo.overlay.dismiss() + } + } + } + } + } +} + +// MARK: - MobilePlayerOverlayViewControllerDelegate +extension MobilePlayerViewController: MobilePlayerOverlayViewControllerDelegate { + + func dismiss(mobilePlayerOverlayViewController overlayViewController: MobilePlayerOverlayViewController) { + overlayViewController.willMove(toParentViewController: nil) + overlayViewController.view.removeFromSuperview() + overlayViewController.removeFromParentViewController() + if overlayViewController == prerollViewController { + play() + } + } +} + +// MARK: - TimeSliderDelegate +extension MobilePlayerViewController: SliderDelegate { + + func sliderThumbPanDidBegin(slider: Slider) { + seeking = true + wasPlayingBeforeSeek = (state == .playing) + pause() + } + + func sliderThumbDidPan(slider: Slider) {} + + func sliderThumbPanDidEnd(slider: Slider) { + seeking = false + moviePlayer.currentPlaybackTime = TimeInterval(slider.value) + if wasPlayingBeforeSeek { + play() + } + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Parsers/YoutubeParser.swift b/Pods/MobilePlayer/MobilePlayer/Parsers/YoutubeParser.swift new file mode 100644 index 0000000000..e71db3846c --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Parsers/YoutubeParser.swift @@ -0,0 +1,104 @@ +// +// YoutubeParser.swift +// MobilePlayer +// +// Created by Toygar Dündaralp on 09/06/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import Foundation + +struct YoutubeVideoInfo { + let title: String? + let previewImageURL: String? + let videoURL: String? + let isStream: Bool? +} + +class YoutubeParser: NSObject { + static let infoURL = "https://www.youtube.com/get_video_info?video_id=" + static let userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)" + + " AppleWebKit/537.4 (KHTML, like Gecko)" + + " Chrome/22.0.1229.79 Safari/537.4" + + private static func decodeURLEncodedString(urlString: String) -> String { + let withSpaces = urlString.replacingOccurrences(of: "+", with: " ") + return withSpaces.removingPercentEncoding ?? withSpaces + } + + private static func queryStringToDictionary(queryString: String) -> [String: Any] { + var parameters = [String: Any]() + for keyValuePair in queryString.components(separatedBy: "&") { + let keyValueArray = keyValuePair.components(separatedBy: "=") + if keyValueArray.count < 2 { + continue + } + let key = decodeURLEncodedString(urlString: keyValueArray[0]) + let value = decodeURLEncodedString(urlString: keyValueArray[1]) + parameters[key] = value + } + return parameters + } + + static func youtubeIDFromURL(url: URL) -> String? { + guard let host = url.host else { return nil } + + if host.range(of: "youtu.be") != nil { + return url.pathComponents[1] + } else if (host.range(of: "youtube.com") != nil && url.pathComponents[1] == "embed") || (host == "youtube.googleapis.com") { + return url.pathComponents[2] + } else if + host.range(of: "youtube.com") != nil, + let queryString = url.query, + let videoParam = queryStringToDictionary(queryString: queryString)["v"] as? String { + return videoParam + } + + return nil + } + + static func h264videosWithYoutubeID(_ youtubeID: String, + completion: @escaping (_ videoInfo: YoutubeVideoInfo?, _ error: NSError?) -> Void) { + var request = URLRequest(url: URL(string: "\(infoURL)\(youtubeID)")!) + request.setValue(userAgent, forHTTPHeaderField: "User-Agent") + request.httpMethod = "GET" + NSURLConnection.sendAsynchronousRequest( + request, + queue: .main, + completionHandler: { response, data, error in + if let error = error { + completion(nil, error as NSError?) + return + } + guard let + data = data, + let dataString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String else { + completion( + nil, + NSError(domain: "com.movielala.MobilePlayer.error", code: 0, userInfo: nil)) + return + } + let parts = self.queryStringToDictionary(queryString: dataString) + let title = parts["title"] as? String + let previewImageURL = parts["iurl"] as? String + if parts["live_playback"] != nil { + completion( + YoutubeVideoInfo( + title: title, + previewImageURL: previewImageURL, + videoURL: parts["hlsvp"] as? String, + isStream: true), + nil) + } else if let fmtStreamMap = parts["url_encoded_fmt_stream_map"] as? String { + let videoComponents = self.queryStringToDictionary(queryString: fmtStreamMap.components(separatedBy: ",")[0]) + completion( + YoutubeVideoInfo( + title: title, + previewImageURL: previewImageURL, + videoURL: videoComponents["url"] as? String, + isStream: false), + nil) + } + }) + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLCloseButton.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLCloseButton.png new file mode 100644 index 0000000000..90501738bc Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLCloseButton.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLCloseButton@2x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLCloseButton@2x.png new file mode 100644 index 0000000000..4d04a5927d Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLCloseButton@2x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLCloseButton@3x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLCloseButton@3x.png new file mode 100644 index 0000000000..b787055eaa Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLCloseButton@3x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLIncreaseVolume.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLIncreaseVolume.png new file mode 100644 index 0000000000..c34bded47e Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLIncreaseVolume.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLIncreaseVolume@2x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLIncreaseVolume@2x.png new file mode 100644 index 0000000000..b4ea340c1b Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLIncreaseVolume@2x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLIncreaseVolume@3x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLIncreaseVolume@3x.png new file mode 100644 index 0000000000..2620bf2027 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLIncreaseVolume@3x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLPauseButton.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLPauseButton.png new file mode 100644 index 0000000000..2dc78a60b4 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLPauseButton.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLPauseButton@2x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLPauseButton@2x.png new file mode 100644 index 0000000000..110b16277d Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLPauseButton@2x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLPauseButton@3x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLPauseButton@3x.png new file mode 100644 index 0000000000..0098149d22 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLPauseButton@3x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLPlayButton.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLPlayButton.png new file mode 100644 index 0000000000..f1cf0dab09 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLPlayButton.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLPlayButton@2x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLPlayButton@2x.png new file mode 100644 index 0000000000..07d3204dbd Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLPlayButton@2x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLPlayButton@3x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLPlayButton@3x.png new file mode 100644 index 0000000000..9f0653bc20 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLPlayButton@3x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLReduceVolume.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLReduceVolume.png new file mode 100644 index 0000000000..12cf4ed321 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLReduceVolume.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLReduceVolume@2x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLReduceVolume@2x.png new file mode 100644 index 0000000000..dd4fb7391a Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLReduceVolume@2x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLReduceVolume@3x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLReduceVolume@3x.png new file mode 100644 index 0000000000..6c2bda04f5 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLReduceVolume@3x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLShareButton.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLShareButton.png new file mode 100644 index 0000000000..a973e8ffe2 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLShareButton.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLShareButton@2x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLShareButton@2x.png new file mode 100644 index 0000000000..167672ef4d Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLShareButton@2x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLShareButton@3x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLShareButton@3x.png new file mode 100644 index 0000000000..18d4b1279f Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLShareButton@3x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLVolumeButton.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLVolumeButton.png new file mode 100644 index 0000000000..77fce7653f Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLVolumeButton.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLVolumeButton@2x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLVolumeButton@2x.png new file mode 100644 index 0000000000..7682360091 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLVolumeButton@2x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Resources/MLVolumeButton@3x.png b/Pods/MobilePlayer/MobilePlayer/Resources/MLVolumeButton@3x.png new file mode 100644 index 0000000000..18fd468024 Binary files /dev/null and b/Pods/MobilePlayer/MobilePlayer/Resources/MLVolumeButton@3x.png differ diff --git a/Pods/MobilePlayer/MobilePlayer/Views/Bar.swift b/Pods/MobilePlayer/MobilePlayer/Views/Bar.swift new file mode 100644 index 0000000000..31073263d4 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Views/Bar.swift @@ -0,0 +1,135 @@ +// +// Bar.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/16/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +class Bar: UIView { + let config: BarConfig + let gradientLayer: CAGradientLayer? + let topBorderView = UIView(frame: .zero) + let bottomBorderView = UIView(frame: .zero) + var elements = [Element]() + private var elementFindCache = [String: UIView]() + + init(config: BarConfig = BarConfig()) { + self.config = config + if config.backgroundColor.count > 1 { + let gradientLayer = CAGradientLayer() + gradientLayer.colors = [config.backgroundColor.first!.cgColor, config.backgroundColor.last!.cgColor] + gradientLayer.locations = [0, 1] + self.gradientLayer = gradientLayer + } else { + gradientLayer = nil + } + super.init(frame: .zero) + if config.backgroundColor.count == 1 { + backgroundColor = config.backgroundColor[0] + } else if let gradientLayer = gradientLayer { + layer.addSublayer(gradientLayer) + } + topBorderView.backgroundColor = config.topBorderColor + addSubview(topBorderView) + bottomBorderView.backgroundColor = config.bottomBorderColor + addSubview(bottomBorderView) + for elementConfig in config.elements { + addElement(usingConfig: elementConfig) + } + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func addElement(usingConfig config: ElementConfig) { + let elementView: UIView? + switch config.type { + case .Button: + guard let buttonConfig = config as? ButtonConfig else { return } + elementView = Button(config: buttonConfig) + case .ToggleButton: + guard let toggleButtonConfig = config as? ToggleButtonConfig else { return } + elementView = ToggleButton(config: toggleButtonConfig) + case .Label: + guard let labelConfig = config as? LabelConfig else { return } + elementView = Label(config: labelConfig) + case .Slider: + guard let sliderConfig = config as? SliderConfig else { return } + elementView = Slider(config: sliderConfig) + case .Unknown: + elementView = nil + } + if + let elementView = elementView, + let element = elementView as? Element { + addSubview(elementView) + elements.append(element) + setNeedsLayout() + } + } + + func getViewForElementWithIdentifier(identifier: String) -> UIView? { + if let view = elementFindCache[identifier] { + return view + } + for element in elements { + if element.identifier == identifier { + elementFindCache[identifier] = element.view + return element.view + } + } + return nil + } + + override func sizeThatFits(_ size: CGSize) -> CGSize { + return CGSize(width: size.width, height: config.height + config.bottomBorderHeight + config.topBorderHeight) + } + + override func layoutSubviews() { + let size = bounds.size + + if let gradientLayer = gradientLayer { + gradientLayer.frame = bounds + } + + topBorderView.frame = CGRect(x: 0, y: 0, width: size.width, height: config.topBorderHeight) + bottomBorderView.frame = CGRect( + x: 0, + y: size.height - config.bottomBorderHeight, + width: size.width, + height: config.bottomBorderHeight) + + // Size element views. + var viewsToFillAvailableWidth = [UIView]() + var totalOccupiedWidth = CGFloat(0) + for element in elements { + element.view.sizeToFit() + switch element.widthCalculation { + case .AsDefined, .Fit: + totalOccupiedWidth += element.view.frame.size.width + case .Fill: + viewsToFillAvailableWidth.append(element.view) + } + totalOccupiedWidth += element.marginLeft + element.marginRight + } + + if viewsToFillAvailableWidth.count > 0 { + let widthPerFillerView = (size.width - totalOccupiedWidth) / CGFloat(viewsToFillAvailableWidth.count) + for view in viewsToFillAvailableWidth { + view.frame.size.width = widthPerFillerView + } + } + + // Position them. + var left = CGFloat(0) + for element in elements { + left += element.marginLeft + element.view.frame.origin = CGPoint(x: left, y: (size.height - element.view.frame.size.height) / 2) + left += element.view.frame.size.width + element.marginRight + } + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Views/Button.swift b/Pods/MobilePlayer/MobilePlayer/Views/Button.swift new file mode 100644 index 0000000000..3f04e212f5 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Views/Button.swift @@ -0,0 +1,43 @@ +// +// Button.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/16/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +class Button: UIButton { + let config: ButtonConfig + + init(config: ButtonConfig = ButtonConfig()) { + self.config = config + super.init(frame: .zero) + accessibilityLabel = accessibilityLabel ?? config.identifier + tintColor = config.tintColor + setImage(config.image, for: .normal) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func sizeThatFits(_ size: CGSize) -> CGSize { + let superSize = super.sizeThatFits(size) + return CGSize( + width: (config.widthCalculation == .AsDefined) ? config.width : superSize.width, + height: config.height) + } +} + +// MARK: - Element +extension Button: Element { + var type: ElementType { return config.type } + var identifier: String? { return config.identifier } + var widthCalculation: ElementWidthCalculation { return config.widthCalculation } + var width: CGFloat { return config.width } + var marginLeft: CGFloat { return config.marginLeft } + var marginRight: CGFloat { return config.marginRight } + var view: UIView { return self } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Views/Element.swift b/Pods/MobilePlayer/MobilePlayer/Views/Element.swift new file mode 100644 index 0000000000..2b210586c2 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Views/Element.swift @@ -0,0 +1,17 @@ +// +// Element.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/17/15. +// Copyright © 2015 MovieLaLa. All rights reserved. +// + +protocol Element { + var type: ElementType { get } + var identifier: String? { get } + var widthCalculation: ElementWidthCalculation { get } + var width: CGFloat { get } + var marginLeft: CGFloat { get } + var marginRight: CGFloat { get } + var view: UIView { get } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Views/Label.swift b/Pods/MobilePlayer/MobilePlayer/Views/Label.swift new file mode 100644 index 0000000000..cf78f0c50f --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Views/Label.swift @@ -0,0 +1,47 @@ +// +// Label.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/16/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +class Label: UILabel { + let config: LabelConfig + + init(config: LabelConfig = LabelConfig()) { + self.config = config + super.init(frame: .zero) + accessibilityLabel = accessibilityLabel ?? config.identifier + text = config.text + font = config.font + textColor = config.textColor + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func sizeThatFits(_ size: CGSize) -> CGSize { + let superSize = super.sizeThatFits(size) + switch config.widthCalculation { + case .AsDefined: + return CGSize(width: config.width, height: superSize.height) + default: + return superSize + } + } +} + +// MARK: - Element +extension Label: Element { + var type: ElementType { return config.type } + var identifier: String? { return config.identifier } + var widthCalculation: ElementWidthCalculation { return config.widthCalculation } + var width: CGFloat { return config.width } + var marginLeft: CGFloat { return config.marginLeft } + var marginRight: CGFloat { return config.marginRight } + var view: UIView { return self } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Views/MobilePlayerControlsView.swift b/Pods/MobilePlayer/MobilePlayer/Views/MobilePlayerControlsView.swift new file mode 100644 index 0000000000..dfef41b28c --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Views/MobilePlayerControlsView.swift @@ -0,0 +1,94 @@ +// +// MobilePlayerControlsView.swift +// MobilePlayer +// +// Created by Baris Sencan on 12/02/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit +import MediaPlayer + +final class MobilePlayerControlsView: UIView { + let config: MobilePlayerConfig + let previewImageView = UIImageView(frame: .zero) + let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white) + let overlayContainerView = UIView(frame: .zero) + let topBar: Bar + let bottomBar: Bar + + var controlsHidden: Bool = false { + didSet { + if oldValue != controlsHidden { + UIView.animate(withDuration: 0.2) { + self.layoutSubviews() + } + } + } + } + + init(config: MobilePlayerConfig) { + self.config = config + topBar = Bar(config: config.topBarConfig) + bottomBar = Bar(config: config.bottomBarConfig) + super.init(frame: .zero) + previewImageView.contentMode = .scaleAspectFit + addSubview(previewImageView) + activityIndicatorView.startAnimating() + addSubview(activityIndicatorView) + addSubview(overlayContainerView) + if topBar.elements.count == 0 { + topBar.addElement(usingConfig: ButtonConfig(dictionary: ["type": "button", "identifier": "close"])) + topBar.addElement(usingConfig: LabelConfig(dictionary: ["type": "label", "identifier": "title"])) + topBar.addElement(usingConfig: ButtonConfig(dictionary: ["type": "button", "identifier": "action"])) + } + addSubview(topBar) + if bottomBar.elements.count == 0 { + bottomBar.addElement(usingConfig: ToggleButtonConfig(dictionary: ["type": "toggleButton", "identifier": "play"])) + bottomBar.addElement(usingConfig: LabelConfig(dictionary: ["type": "label", "identifier": "currentTime"])) + bottomBar.addElement(usingConfig: SliderConfig(dictionary: ["type": "slider", "identifier": "playback", "marginLeft": 8, "marginRight": 8])) + bottomBar.addElement(usingConfig: LabelConfig(dictionary: ["type": "label", "identifier": "duration", "marginRight": 8])) + } + addSubview(bottomBar) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func layoutSubviews() { + + let iPhoneX = UIDevice().userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.height == 2436 + let landscape = UIScreen.main.bounds.height != 812 + + let size = bounds.size + previewImageView.frame = bounds + activityIndicatorView.sizeToFit() + activityIndicatorView.frame.origin = CGPoint( + x: (size.width - activityIndicatorView.frame.size.width) / 2, + y: (size.height - activityIndicatorView.frame.size.height) / 2) + topBar.sizeToFit() + topBar.frame = CGRect( + x: (iPhoneX && landscape) ? 44 : 0, + y: controlsHidden ? -topBar.frame.size.height : ((iPhoneX && !landscape) ? 44 : 0), + width: size.width - ((iPhoneX && landscape) ? 88 : 0), + height: topBar.frame.size.height) + topBar.alpha = controlsHidden ? 0 : 1 + bottomBar.sizeToFit() + bottomBar.frame = CGRect( + x: (iPhoneX && landscape) ? 44 : 0, + y: size.height - (controlsHidden ? 0 : bottomBar.frame.size.height + ((iPhoneX && !landscape) ? 34 : 0)), + width: size.width - ((iPhoneX && landscape) ? 88 : 0), + height: bottomBar.frame.size.height) + bottomBar.alpha = controlsHidden ? 0 : 1 + overlayContainerView.frame = CGRect( + x: 0, + y: controlsHidden ? 0 : topBar.frame.size.height, + width: size.width, + height: size.height - (controlsHidden ? 0 : (topBar.frame.size.height + bottomBar.frame.size.height))) + for overlay in overlayContainerView.subviews { + overlay.frame = overlayContainerView.bounds + } + super.layoutSubviews() + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Views/Slider.swift b/Pods/MobilePlayer/MobilePlayer/Views/Slider.swift new file mode 100644 index 0000000000..c66a376c72 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Views/Slider.swift @@ -0,0 +1,164 @@ +// +// Slider.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/16/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +// MARK: - Delegate +protocol SliderDelegate: class { + func sliderThumbPanDidBegin(slider: Slider) + func sliderThumbDidPan(slider: Slider) + func sliderThumbPanDidEnd(slider: Slider) +} + +// MARK: - Class +class Slider: UIView { + let config: SliderConfig + weak var delegate: SliderDelegate? + var minimumValue: Float = 0 { didSet { setNeedsLayout() } } + var value: Float = 0 { didSet { setNeedsLayout() } } + var availableValue: Float = 0 { didSet { setNeedsLayout() } } + var maximumValue: Float = 1 { didSet { setNeedsLayout() } } + + let maximumTrack = UIView(frame: .zero) + let availableTrack = UIView(frame: .zero) + let minimumTrack = UIView(frame: .zero) + let thumb = UIView(frame: .zero) + + // MARK: Initialization + + init(config: SliderConfig = SliderConfig()) { + self.config = config + super.init(frame: .zero) + accessibilityLabel = accessibilityLabel ?? config.identifier + maximumTrack.backgroundColor = config.maximumTrackTintColor + maximumTrack.clipsToBounds = true + maximumTrack.layer.cornerRadius = config.trackCornerRadius + addSubview(maximumTrack) + availableTrack.backgroundColor = config.availableTrackTintColor + availableTrack.clipsToBounds = true + availableTrack.layer.cornerRadius = config.trackCornerRadius + maximumTrack.addSubview(availableTrack) + minimumTrack.backgroundColor = config.minimumTrackTintColor + maximumTrack.addSubview(minimumTrack) + thumb.backgroundColor = config.thumbTintColor + thumb.accessibilityLabel = "thumb" + thumb.clipsToBounds = true + thumb.layer.cornerRadius = config.thumbCornerRadius + thumb.layer.borderColor = config.thumbBorderColor + thumb.layer.borderWidth = config.thumbBorderWidth + addSubview(thumb) + thumb.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(didPanThumb))) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: Setters + + func setValue(value: Float, animatedForDuration duration: TimeInterval) { + self.value = value + if duration > 0 { + UIView.animate( + withDuration: duration, + delay: 0, + options: .allowUserInteraction, + animations: { + self.layoutIfNeeded() + }, + completion: nil) + } + } + + func setAvailableValue(availableValue: Float, animatedForDuration duration: TimeInterval) { + self.availableValue = availableValue + if duration > 0 { + UIView.animate( + withDuration: duration, + animations: { + self.layoutIfNeeded() + }) + } + } + + // MARK: Seeking + + func didPanThumb(recognizer: UIPanGestureRecognizer!) { + let locationInTrack = recognizer.location(in: maximumTrack) + let trackWidth = maximumTrack.frame.size.width + if recognizer.state == .began { + delegate?.sliderThumbPanDidBegin(slider: self) + } + if recognizer.state == .changed || recognizer.state == .ended || recognizer.state == .cancelled { + var targetX = locationInTrack.x + if targetX < 0 { + targetX = 0 + } else if targetX > trackWidth { + targetX = trackWidth + } + value = minimumValue + (maximumValue - minimumValue) * Float(targetX / trackWidth) + if recognizer.state == .changed { + delegate?.sliderThumbDidPan(slider: self) + } else { + delegate?.sliderThumbPanDidEnd(slider: self) + } + } + } + + // MARK: Layout + + override func sizeThatFits(_ size: CGSize) -> CGSize { + let width = (config.widthCalculation == .AsDefined) ? config.width : size.width + + let minHeight = max(config.thumbHeight, config.trackHeight) + let height = (size.height < minHeight) ? minHeight : size.height + + return CGSize(width: width, height: height) + } + + override func layoutSubviews() { + let realMaximumValue = max(0.00001, CGFloat(maximumValue - minimumValue)) + let realAvailableValue = max(0, min(realMaximumValue, CGFloat(availableValue - minimumValue))) + let realValue = max(0, min(realMaximumValue, CGFloat(value - minimumValue))) + + maximumTrack.frame = CGRect( + x: 0, + y: (bounds.height - config.trackHeight) / 2, + width: bounds.width, + height: config.trackHeight) + + availableTrack.frame = CGRect( + x: 0, + y: 0, + width: maximumTrack.frame.width * (realAvailableValue / realMaximumValue), + height: config.trackHeight) + + thumb.frame = CGRect( + x: (bounds.width - config.thumbWidth) * (realValue / realMaximumValue), + y: (bounds.height - config.thumbHeight) / 2, + width: config.thumbWidth, + height: config.thumbHeight) + + minimumTrack.frame = CGRect( + x: 0, + y: 0, + width: thumb.frame.midX, + height: config.trackHeight) + } +} + +// MARK: - Element +extension Slider: Element { + var type: ElementType { return config.type } + var identifier: String? { return config.identifier } + var widthCalculation: ElementWidthCalculation { return config.widthCalculation } + var width: CGFloat { return config.width } + var marginLeft: CGFloat { return config.marginLeft } + var marginRight: CGFloat { return config.marginRight } + var view: UIView { return self } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Views/ToggleButton.swift b/Pods/MobilePlayer/MobilePlayer/Views/ToggleButton.swift new file mode 100644 index 0000000000..3ad6c9d750 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Views/ToggleButton.swift @@ -0,0 +1,54 @@ +// +// ToggleButton.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/16/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +class ToggleButton: UIButton { + let config: ToggleButtonConfig + var toggled = false { didSet { update() } } + + init(config: ToggleButtonConfig = ToggleButtonConfig()) { + self.config = config + super.init(frame: .zero) + accessibilityLabel = accessibilityLabel ?? config.identifier + tintColor = config.tintColor + setImage(config.image, for: .normal) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update() { + if toggled { + tintColor = config.toggledTintColor + setImage(config.toggledImage, for: .normal) + } else { + tintColor = config.tintColor + setImage(config.image, for: .normal) + } + } + + override func sizeThatFits(_ size: CGSize) -> CGSize { + let superSize = super.sizeThatFits(size) + return CGSize( + width: (config.widthCalculation == .AsDefined) ? config.width : superSize.width, + height: config.height) + } +} + +// MARK: - Element +extension ToggleButton: Element { + var type: ElementType { return config.type } + var identifier: String? { return config.identifier } + var widthCalculation: ElementWidthCalculation { return config.widthCalculation } + var width: CGFloat { return config.width } + var marginLeft: CGFloat { return config.marginLeft } + var marginRight: CGFloat { return config.marginRight } + var view: UIView { return self } +} diff --git a/Pods/MobilePlayer/MobilePlayer/Views/VolumeView.swift b/Pods/MobilePlayer/MobilePlayer/Views/VolumeView.swift new file mode 100644 index 0000000000..92049215b7 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/Views/VolumeView.swift @@ -0,0 +1,45 @@ +// +// VolumeView.swift +// MobilePlayer +// +// Created by Toygar Dündaralp on 25/06/15. +// Copyright (c) 2015 MovieLaLa. All rights reserved. +// + +import UIKit +import MediaPlayer + +private let defaultIncreaseVolumeTintColor = UIColor.black +private let defaultReduceVolumeTintColor = UIColor.black + +class VolumeView: UIView { + let volumeSlider = MPVolumeView(frame: CGRect(x: -22, y: 50, width: 110, height: 50)) + let increaseVolumeImage = UIImageView(frame: CGRect(x: 10, y: 0, width: 20, height: 20)) + let reduceVolumeImage = UIImageView(frame: CGRect(x: 10, y: 130, width: 20, height: 20)) + + init( + increaseVolumeTintColor: UIColor = defaultIncreaseVolumeTintColor, + reduceVolumeTintColor: UIColor = defaultReduceVolumeTintColor) { + super.init(frame: .zero) + layer.cornerRadius = 5 + layer.borderColor = UIColor.gray.cgColor + layer.borderWidth = 0.5 + layer.masksToBounds = true + backgroundColor = UIColor.white + volumeSlider.transform = CGAffineTransform(rotationAngle: .pi / -2) + volumeSlider.showsRouteButton = false + addSubview(volumeSlider) + increaseVolumeImage.contentMode = .scaleAspectFit + increaseVolumeImage.image = UIImage(podResourceNamed: "MLIncreaseVolume")?.template + increaseVolumeImage.tintColor = increaseVolumeTintColor + addSubview(increaseVolumeImage) + reduceVolumeImage.contentMode = .scaleAspectFit + reduceVolumeImage.image = UIImage(podResourceNamed: "MLReduceVolume")?.template + reduceVolumeImage.tintColor = reduceVolumeTintColor + addSubview(reduceVolumeImage) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/Pods/MobilePlayer/MobilePlayer/WatermarkViewController.swift b/Pods/MobilePlayer/MobilePlayer/WatermarkViewController.swift new file mode 100644 index 0000000000..d005544990 --- /dev/null +++ b/Pods/MobilePlayer/MobilePlayer/WatermarkViewController.swift @@ -0,0 +1,61 @@ +// +// WatermarkViewController.swift +// MobilePlayer +// +// Created by Baris Sencan on 9/18/15. +// Copyright © 2015 MovieLaLa. All rights reserved. +// + +import UIKit + +class WatermarkViewController: MobilePlayerOverlayViewController { + let config: WatermarkConfig + let watermarkImageView = UIImageView(frame: .zero) + + init(config: WatermarkConfig) { + self.config = config + super.init(nibName: nil, bundle: nil) + watermarkImageView.image = config.image + view.addSubview(watermarkImageView) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + let size = view.frame.size + let watermarkSize = watermarkImageView.image?.size ?? .zero + watermarkImageView.frame.size = watermarkSize + switch config.position { + case .Center: + watermarkImageView.frame.origin.x = (size.width - watermarkSize.width) / 2 + watermarkImageView.frame.origin.y = (size.height - watermarkSize.height) / 2 + case .Top: + watermarkImageView.frame.origin.x = (size.width - watermarkSize.width) / 2 + watermarkImageView.frame.origin.y = 8 + case .TopRight: + watermarkImageView.frame.origin.x = size.width - watermarkSize.width - 8 + watermarkImageView.frame.origin.y = 8 + case .Right: + watermarkImageView.frame.origin.x = size.width - watermarkSize.width - 8 + watermarkImageView.frame.origin.y = (size.height - watermarkSize.height) / 2 + case .BottomRight: + watermarkImageView.frame.origin.x = size.width - watermarkSize.width - 8 + watermarkImageView.frame.origin.y = size.height - watermarkSize.height - 8 + case .Bottom: + watermarkImageView.frame.origin.x = (size.width - watermarkSize.width) / 2 + watermarkImageView.frame.origin.y = size.height - watermarkSize.height - 8 + case .BottomLeft: + watermarkImageView.frame.origin.x = 8 + watermarkImageView.frame.origin.y = size.height - watermarkSize.height - 8 + case .Left: + watermarkImageView.frame.origin.x = 8 + watermarkImageView.frame.origin.y = (size.height - watermarkSize.height) / 2 + case .TopLeft: + watermarkImageView.frame.origin.x = 8 + watermarkImageView.frame.origin.y = 8 + } + } +} diff --git a/Pods/MobilePlayer/README.md b/Pods/MobilePlayer/README.md new file mode 100644 index 0000000000..39b83f4aca --- /dev/null +++ b/Pods/MobilePlayer/README.md @@ -0,0 +1,289 @@ +![logo](http://i.imgur.com/W9QtXEp.png) + +MobilePlayer [![CocoaPods](https://img.shields.io/cocoapods/p/MobilePlayer.svg?style=flat)](https://cocoapods.org/pods/MobilePlayer) +================== +[![codebeat badge](https://codebeat.co/badges/d9492bce-7a4b-4221-b7e0-9b5abf6dda6a)](https://codebeat.co/projects/github-com-mobileplayer-mobileplayer-ios) +[![CocoaPods](http://img.shields.io/cocoapods/v/MobilePlayer.svg?style=flat)](http://cocoapods.org/?q=MobilePlayer) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Dependencies](https://img.shields.io/badge/dependencies-none-brightgreen.svg)](https://github.com/mobileplayer/mobileplayer-ios) +[![Ready](https://badge.waffle.io/mobileplayer/mobileplayer-ios.png?label=Ready&title=Ready)](https://waffle.io/mobileplayer/mobileplayer-ios) +[![StackOverflow](https://img.shields.io/badge/StackOverflow-Ask%20a%20question!-blue.svg)](http://stackoverflow.com/questions/ask?tags=mobile player+ios+swift+video player) +[![Join the chat at https://gitter.im/mobileplayer/mobileplayer-ios](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mobileplayer/mobileplayer-ios?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +A powerful and completely customizable media player for iOS. + +![introduction](http://imgur.com/uDq19mw.gif) + +Table of Contents +================== +1. [Features](#features) +2. [Installation](#installation) +3. [Usage](#usage) +4. [Customization](#customization) + - [Skinning](#skinning) + - [Showing overlays](#showing-overlays) + - [Showing timed overlays](#showing-timed-overlays) + - [Pre-roll](#pre-roll) + - [Pause overlay](#pause-overlay) + - [Post-roll](#post-roll) +6. [Examples](#examples) +7. [Documentation](#documentation) +8. [License](#license) + +Features +================== +- Branding + - Flexible skinning. Add a watermark, add/remove/move/resize interface elements, change their appearances and much more. + - Easily set up A/B tests. You can manage multiple player skins and configurations. Player view controllers can load configuration data from a local JSON file or remote JSON data. You also have the option to initialize and pass configuration objects programmatically, which allows for greater flexibility. +- Engagement + - Comes with a built-in share button. + - Standard sharing behavior can easily be modified. + - Show any view controller as pre-roll or post-roll content. + - Powerful overlay system. Add any view controller as an overlay to your video. Make them permanently visible, set them to appear in defined playback time intervals, or while playback is paused. +- 100% documented. + +### Future plans +- Well defined and extensive `NSNotification`s. +- Volume button and volume slider elements. +- Airplay support. +- Plugin support. +- Pre-bundled analytics plugins for various platforms. +- VAST support. +- Monetization. + +Installation +================== + +### [CocoaPods](https://github.com/CocoaPods/CocoaPods) +Add the following line in your `Podfile`. +``` +pod "MobilePlayer" +``` + +### [Carthage](https://github.com/Carthage/Carthage#installing-carthage) +Add the following line to your [Cartfile](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfile). +``` +github "mobileplayer/mobileplayer-ios" +``` + +Usage +================== +```swift +import MobilePlayer + +let playerVC = MobilePlayerViewController(contentURL: videoURL) +playerVC.title = "Vanilla Player - \(videoTitle)" +playerVC.activityItems = [videoURL] // Check the documentation for more information. +presentMoviePlayerViewControllerAnimated(playerVC) +``` +![example-plain](http://i.imgur.com/J6QpSKb.gif) + +Customization +================== + +**Initialize using local configuration file** +```swift +let bundle = NSBundle.mainBundle() +let config = MobilePlayerConfig(fileURL: bundle.URLForResource( + "WatermarkedPlayer", + withExtension: "json")!) +let playerVC = MobilePlayerViewController( + contentURL: videoURL, + config: config) +playerVC.title = "Watermarked Player - \(videoTitle)" +playerVC.activityItems = [videoURL] +presentMoviePlayerViewControllerAnimated(playerVC) +``` + +**Initialize using remote configuration data** +```swift +guard let configURL = NSURL(string: "https://goo.gl/c73ANK") else { return } +let playerVC = MobilePlayerViewController( + contentURL: videoURL, + config: MobilePlayerConfig(fileURL: configURL)) +playerVC.title = "Watermarked Player - \(videoTitle)" +playerVC.activityItems = [videoURL] +presentMoviePlayerViewControllerAnimated(playerVC) +``` + +**Configuration data** +```json +{ + "watermark": { + "image": "MovielalaLogo" + } +} +``` + +**Without a configuration file URL** +```swift +let playerVC = MobilePlayerViewController( + contentURL: videoURL, + config: MobilePlayerConfig( + dictionary: ["watermark": ["image": "MovielalaLogo"]])) +playerVC.title = "Watermarked Player - \(videoTitle)" +playerVC.activityItems = [videoURL] +presentMoviePlayerViewControllerAnimated(playerVC) +``` + +**Result** +![example-customization](http://i.imgur.com/tGodgQx.png) + +### Skinning +```json +{ + "watermark": { + "image": "MovielalaLogo", + "position": "topRight" + }, + "topBar": { + "backgroundColor": ["#a60500b0", "#a60500a0"], + "elements": [ + { + "type": "button", + "identifier": "close" + }, + { + "type": "slider", + "identifier": "playback", + "trackHeight": 6, + "trackCornerRadius": 3, + "minimumTrackTintColor": "#eee", + "availableTrackTintColor": "#9e9b9a", + "maximumTrackTintColor": "#cccccc", + "thumbTintColor": "#f9f9f9", + "thumbBorderWidth": 1, + "thumbBorderColor": "#fff", + "marginRight": 4 + } + ] + }, + "bottomBar": { + "backgroundColor": ["#a60500a0", "#a60500b0"], + "elements": [ + { + "type": "label", + "text": "Now Watching", + "font": "Baskerville", + "size": 12, + "marginLeft": 8, + "marginRight": 8 + }, + { + "type": "label", + "identifier": "title", + "size": 14 + }, + { + "type": "button", + "identifier": "action" + }, + { + "type": "toggleButton", + "identifier": "play" + } + ] + } +} +``` +For all available `identifier`s, check the documentation or [here](https://github.com/mobileplayer/mobileplayer-ios/blob/master/MobilePlayer/Config/ElementConfig.swift#L51). Same `identifier` value shouldn't be used more than once in a single configuration. + +**Result** +![example-skinning](http://i.imgur.com/YyiYJCc.png) + +**Example designs** +![example-design-skinning](http://i.imgur.com/qNDrx9T.gif) + +### Showing overlays +```swift +let playerVC = MobilePlayerViewController(contentURL: videoURL) +playerVC.title = videoTitle +playerVC.activityItems = [videoURL] +presentMoviePlayerViewControllerAnimated(playerVC) +ProductStore.getProduct("1", success: { product in + guard let product = product else { return } + playerVC.showOverlayViewController( + BuyOverlayViewController(product: product)) +}) +``` +![example-overlay](http://i.imgur.com/wAtNYjE.png) + +### Showing timed overlays +```swift +let playerVC = MobilePlayerViewController(contentURL: videoURL) +playerVC.title = videoTitle +playerVC.activityItems = [videoURL] +presentMoviePlayerViewControllerAnimated(playerVC) +ProductStore.getProductPlacementsForVideo( + videoID, + success: { productPlacements in + guard let productPlacements = productPlacements else { return } + for placement in productPlacements { + ProductStore.getProduct(placement.productID, success: { product in + guard let product = product else { return } + playerVC.showOverlayViewController( + BuyOverlayViewController(product: product), + startingAtTime: placement.startTime, + forDuration: placement.duration) + }) + } +}) +``` +![example-timed-overlays](http://i.imgur.com/FuaJB7O.gif) + +### Pre-roll +```swift +let playerVC = MobilePlayerViewController( + contentURL: videoURL, + prerollViewController: PrerollOverlayViewController()) +playerVC.title = videoTitle +playerVC.activityItems = [videoURL] +presentMoviePlayerViewControllerAnimated(playerVC) +``` +![example-preroll](http://i.imgur.com/oBV0HCF.png) + +### Pause overlay +```swift +let playerVC = MobilePlayerViewController( + contentURL: videoURL, + pauseOverlayViewController: PauseOverlayViewController()) +playerVC.title = videoTitle +playerVC.activityItems = [videoURL] +presentMoviePlayerViewControllerAnimated(playerVC) +``` + +**Result** +![example-pause-overlay](http://i.imgur.com/wfC9a7t.gif) + +**Example designs** +![example-design-pause-overlay](http://i.imgur.com/ectKEwy.gif) + +### Post-roll +```swift +let playerVC = MobilePlayerViewController( + contentURL: videoURL, + postrollViewController: PostrollOverlayViewController()) +playerVC.title = videoTitle +playerVC.activityItems = [videoURL] +presentMoviePlayerViewControllerAnimated(playerVC) +``` + +**Result** +![example-postroll](http://i.imgur.com/Hp8NEfg.png) + +**Example designs** +![example-design-postroll](http://i.imgur.com/MRVxNAt.gif) + +Examples +================== +After cloning the repo, run the `MobilePlayerExamples` target to see examples for many use cases. +![examples](http://i.imgur.com/ztOPUW6.gif) + +Documentation +================== +The entire documentation for the library can be found [here](https://htmlpreview.github.io/?https://github.com/movielala/mobileplayer-ios/blob/master/Documentation/index.html). + +License +================== +The use of the MobilePlayer open source edition is governed by a [Creative Commons license](http://creativecommons.org/licenses/by-nc-sa/3.0/). You can use, modify, copy, and distribute this edition as long as it’s for non-commercial use, you provide attribution, and share under a similar license. +http://mobileplayer.io/license/ diff --git a/Pods/Nuke-FLAnimatedImage-Plugin/LICENSE b/Pods/Nuke-FLAnimatedImage-Plugin/LICENSE new file mode 100644 index 0000000000..68e4c36a42 --- /dev/null +++ b/Pods/Nuke-FLAnimatedImage-Plugin/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Alexander Grebenyuk + +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/Nuke-FLAnimatedImage-Plugin/README.md b/Pods/Nuke-FLAnimatedImage-Plugin/README.md new file mode 100644 index 0000000000..92ab113b46 --- /dev/null +++ b/Pods/Nuke-FLAnimatedImage-Plugin/README.md @@ -0,0 +1,59 @@ +

+ +

+ + +

+ +[FLAnimatedImage](https://github.com/Flipboard/FLAnimatedImage) plugin for [Nuke](https://github.com/kean/Nuke) that allows you to load and display animated GIFs with [smooth scrolling performance](https://www.youtube.com/watch?v=fEJqQMJrET4) and low memory footprint. You can see it for yourself in a demo, included in the project. + +## Usage + +All you need to do to enable GIF support is set `isAnimatedImageDataEnabled` to `true`. After you do that, you can start using `FLAnimatedImageView`. + +```swift +ImagePipeline.Configuration.isAnimatedImageDataEnabled = true + +let view = FLAnimatedImageView() +Nuke.loadImage(with: URL(string: "http://.../cat.gif")!, into: view) +``` + +## Installation + +### Manually + +The entire plugin is a single file with 23 lines of code which you can just copy into your project without having to deal with extra framework dependencies. + +### [CocoaPods](http://cocoapods.org) + +To install the plugin add a dependency to your Podfile: + +```ruby +# source 'https://github.com/CocoaPods/Specs.git' +# use_frameworks! + +pod "Nuke-FLAnimatedImage-Plugin" +``` + +### [Carthage](https://github.com/Carthage/Carthage) + +To install the plugin add a dependency to your Cartfile: + +``` +github "kean/Nuke-FLAnimatedImage-Plugin" +``` + +## Minimum Requirements + +- iOS 9 +- Xcode 9.2 +- Swift 4.0 + +## Dependencies + +- [Nuke 7.0](https://github.com/kean/Nuke) +- [FLAnimatedImage 1](https://github.com/Flipboard/FLAnimatedImage) + +## License + +Nuke is available under the MIT license. See the LICENSE file for more info. diff --git a/Pods/Nuke-FLAnimatedImage-Plugin/Source/AnimatedImage.swift b/Pods/Nuke-FLAnimatedImage-Plugin/Source/AnimatedImage.swift new file mode 100644 index 0000000000..bafa3f9c28 --- /dev/null +++ b/Pods/Nuke-FLAnimatedImage-Plugin/Source/AnimatedImage.swift @@ -0,0 +1,35 @@ +// The MIT License (MIT) +// +// Copyright (c) 2016-2018 Alexander Grebenyuk (github.com/kean). + +import UIKit +import FLAnimatedImage +import Nuke + +extension FLAnimatedImageView { + @objc open override func display(image: Image?) { + guard image != nil else { + self.animatedImage = nil + self.image = nil + return + } + if let data = image?.animatedImageData { + // Display poster image immediately + self.image = image + + // Prepare FLAnimatedImage object asynchronously (it takes a + // noticeable amount of time), and start playback. + DispatchQueue.global().async { + let animatedImage = FLAnimatedImage(animatedGIFData: data) + DispatchQueue.main.async { + // If view is still displaying the same image + if self.image === image { + self.animatedImage = animatedImage + } + } + } + } else { + self.image = image + } + } +} diff --git a/Pods/Nuke/LICENSE b/Pods/Nuke/LICENSE new file mode 100644 index 0000000000..f55c06e701 --- /dev/null +++ b/Pods/Nuke/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2018 Alexander Grebenyuk + +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/Nuke/README.md b/Pods/Nuke/README.md new file mode 100644 index 0000000000..6c78a2c1e5 --- /dev/null +++ b/Pods/Nuke/README.md @@ -0,0 +1,511 @@ +

+ +

+ + + + +

+ +A powerful **image loading** and **caching** system. It makes simple tasks like loading images into views extremely simple, while also supporting advanced features for more demanding apps. + +- Fast LRU memory cache, native HTTP disk cache, and custom aggressive LRU disk cache +- Progressive image loading (progressive JPEG and WebP) +- Resumable downloads, request prioritization, deduplication, rate limiting and more +- [Alamofire](https://github.com/kean/Nuke-Alamofire-Plugin), [WebP](https://github.com/ryokosuge/Nuke-WebP-Plugin), [Gifu](https://github.com/kean/Nuke-Gifu-Plugin), [FLAnimatedImage](https://github.com/kean/Nuke-FLAnimatedImage-Plugin) extensions +- [RxNuke](https://github.com/kean/RxNuke) - [RxSwift](https://github.com/ReactiveX/RxSwift) extensions +- Automates [prefetching](https://kean.github.io/post/image-preheating) with [Preheat](https://github.com/kean/Preheat) (*deprecated in iOS 10*) + +# Getting Started + +> Upgrading from the previous version? Use a [**Migration Guide**](https://github.com/kean/Nuke/blob/master/Documentation/Migrations). + +- [**Quick Start Guide**](#h_usage) + - [Load Image into Image View](#load-image-into-image-view) + - [Placeholders, Transitions and More](#placeholders-transitions-and-more) + - [Image Requests](#image-requests), [Process an Image](#process-an-image) +- [**Advanced Usage Guide**](#advanced-usage) + - [Image Pipeline](#image-pipeline), [Configuring Image Pipeline](#configuring-image-pipeline) + - [Memory Cache](#memory-cache), [HTTP Disk Cache](#http-disk-cache), [Aggressive Disk Cache](#aggressive-disk-cache) + - [Preheat Images](#preheat-images) + - [Progressive Decoding](#progressive-decoding), [Animated Images](#animated-images), [WebP](#webp) + - [RxNuke](#rxnuke) +- Detailed [**Image Pipeline**](#h_design) description +- An entire section dedicated to [**Performance**](#h_performance) +- List of [**Extensions**](#h_plugins) +- [**Contributing**](#h_contribute) and roadmap +- [**Requirements**](#h_requirements) + +More information is available in [**Documentation**](https://github.com/kean/Nuke/blob/master/Documentation/) directory and a full [**API Reference**](https://kean.github.io/Nuke/reference/7.3/index.html). When you are ready to install Nuke you can follow an [**Installation Guide**](https://github.com/kean/Nuke/blob/master/Documentation/Guides/Installation%20Guide.md) - all major package managers are supported. + +# Quick Start + +#### Load Image into Image View + +You can load an image into an image view with a single line of code. + +```swift +Nuke.loadImage(with: url, into: imageView) +``` + +Nuke will automatically load image data, decompress it in the background, store image in memory cache and display it. + +> To learn more about the `ImagePipeline` [see the dedicated section](#h_design). + +When you request a new image for the view, the previous outstanding request gets canceled and the image is set to `nil`. The request also gets canceled automatically when the view is deallocated. + +```swift +func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + ... + Nuke.loadImage(with: url, into: cell.imageView) + ... +} +``` + +#### Placeholders, Transitions and More + +Use an `options` parameter (`ImageLoadingOptions`) to customize the way images are loaded and displayed. You can provide a placeholder, select one of the built-in transitions or provide a custom one. When using transitions, be aware that UIKit may keep a reference to the image, preventing it from being removed for long animations or loading many transitions at once. + +```swift +Nuke.loadImage( + with: url, + options: ImageLoadingOptions( + placeholder: UIImage(named: "placeholder"), + transition: .fadeIn(duration: 0.33) + ), + into: imageView +) +``` + +There is a very common scenario when the placeholder (or the failure image) needs to be displayed with a _content mode_ different from the one used for the loaded image. + +```swift +let options = ImageLoadingOptions( + placeholder: UIImage(named: "placeholder"), + failureImage: UIImage(named: "failure_image"), + contentModes: .init( + success: .scaleAspectFill, + failure: .center, + placeholder: .center + ) +) + +Nuke.loadImage(with: url, options: options, into: imageView) +``` + +To make all image views in the app share the same behavior modify `ImageLoadingOptions.shared`. + +> If `ImageLoadingOptions` are missing a feature that you need, please use `ImagePipeline` directly. If you think that everyone could benefit from this feature, PRs are welcome. + +#### Image Requests + +Each request is represented by an `ImageRequest` struct. A request can be created either with `URL` or `URLRequest`. + +```swift +var request = ImageRequest(url: url) +// var request = ImageRequest(urlRequest: URLRequest(url: url)) + +// Change memory cache policy: +request.memoryCacheOptions.isWriteAllowed = false + +// Update the request priority: +request.priority = .high + +Nuke.loadImage(with: request, into: imageView) +``` + +#### Process an Image + +Resize an image using special `ImageRequest` initializer. + +```swift +// Target size is in pixels. +ImageRequest(url: url, targetSize: CGSize(width: 640, height: 320), contentMode: .aspectFill) +``` + +Perform custom tranformation using `processed(key:closure:)` method. Her's how to create a circular avatar using [Toucan](https://github.com/gavinbunney/Toucan). + +```swift +ImageRequest(url: url).process(key: "circularAvatar") { + Toucan(image: $0).maskWithEllipse().image +} +``` + +All those APIs are built on top of `ImageProcessing` protocol which you can also use to implement custom processors. Keep in mind that `ImageProcessing` also requires `Equatable` conformance which helps Nuke identify images in memory cache. + +> See [Core Image Integration Guide](https://github.com/kean/Nuke/blob/master/Documentation/Guides/Core%20Image%20Integration%20Guide.md) for info about using Core Image with Nuke + +# Advanced Usage + +#### Image Pipeline + +Use `ImagePipeline` directly to load images without a view. + +```swift +let task = ImagePipeline.shared.loadImage( + with: url, + progress: { _, completed, total in + print("progress updated") + }, + completion: { response, error in + print("task completed") + } +) +``` + +Tasks can be used to monitor download progress, cancel the requests, and dynamically update download priority. + +```swift +task.cancel() +task.setPriority(.high) +``` + +> To learn more about the `ImagePipeline` [see the dedicated section](#h_design). + +#### Configuring Image Pipeline + +Apart from using a shared `ImagePipeline` instance, you can create your own. + +```swift +let pipeline = ImagePipeline { + $0.dataLoader = ... + $0.dataLoadingQueue = ... + $0.imageCache = ... + ... +} + +// When you're done you can make the pipeline a shared one: +ImagePipeline.shared = pipeline +``` + +#### Memory Cache + +Default Nuke's `ImagePipeline` has two cache layers. + +First, there is a memory cache for storing processed images ready for display. You can get a direct access to this cache: + +```swift +// Configure cache +ImageCache.shared.costLimit = 1024 * 1024 * 100 // 100 MB +ImageCache.shared.countLimit = 100 +ImageCache.shared.ttl = 120 // Invalidate image after 120 sec + +// Read and write images +let request = ImageRequest(url: url) +ImageCache.shared[request] = image +let image = ImageCache.shared[request] + +// Clear cache +ImageCache.shared.removeAll() +``` + +#### HTTP Disk Cache + +To store unprocessed image data Nuke uses a `URLCache` instance: + +```swift +// Configure cache +DataLoader.sharedUrlCache.diskCapacity = 100 +DataLoader.sharedUrlCache.memoryCapacity = 0 + +// Read and write responses +let request = ImageRequest(url: url) +let _ = DataLoader.sharedUrlCache.cachedResponse(for: request.urlRequest) +DataLoader.sharedUrlCache.removeCachedResponse(for: request.urlRequest) + +// Clear cache +DataLoader.sharedUrlCache.removeAllCachedResponses() +``` + +#### Aggressive Disk Cache + +A custom LRU disk cache can be used for fast and reliable *aggressive* data caching (ignores [HTTP cache control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)). You can enable it using pipeline's configuration. + +```swift +$0.dataCache = try! DataCache(name: "com.myapp.datacache") +// On Swift 4.1 and lower you'll also need to provide a `FilenameGenerator`. +``` + +If you enable aggressive disk cache, make sure that you also disable native URL cache (see `DataLoader`), or you might end up storing the same image data twice. + +> `DataCache` type implements public `DataCaching` protocol which can be used for implementing custom data caches. + +#### Prefetching Images + +[Prefethcing](https://kean.github.io/post/image-preheating) images in advance reduces the wait time for users. Nuke provides an `ImagePreheater` to do just that: + +```swift +let preheater = ImagePreheater() +preheater.startPreheating(with: urls) + +// Cancels all of the preheating tasks created for the given requests. +preheater.stopPreheating(with: urls) +``` + +There are trade-offs, prefetching takes up users's data and puts an extra pressure on CPU and memory. To reduce the CPU and memory usage you have an option to choose only the disk cache as a prefetching destination: + +```swift +// The preheater with `.diskCache` destination will skip image data decoding +// entirely to reduce CPU and memory usage. It will still load the image data +// and store it in disk caches to be used later. +let preheater = ImagePreheater(destination: .diskCache) +``` + +To make sure that the prefetching requests don't interfere with normal requests it's best to reduce their priority. + +You can use Nuke in combination with [Preheat](https://github.com/kean/Preheat) library which automates preheating of content in `UICollectionView` and `UITableView`. On iOS 10.0 you might want to use new [prefetching APIs](https://developer.apple.com/reference/uikit/uitableviewdatasourceprefetching) provided by iOS instead. + +> Check out [Performance Guide](https://github.com/kean/Nuke/blob/master/Documentation/Guides/Performance%20Guide.md) to see what else you can do to improve performance + +#### Progressive Decoding + +To use progressive image loading you need a pipeline with progressive decoding enabled. + +```swift +let pipeline = ImagePipeline { + $0.isProgressiveDecodingEnabled = true +} +``` + +And that's it, you can start observing images as they are produced by the pipeline. The progress handler also works as a progressive image handler. + +```swift +let imageView = UIImageView() +let task = ImagePipeline.shared.loadImage( + with: url, + progress: { response, _, _ in + imageView.image = response?.image + }, + completion: { response, _ in + imageView.image = response?.image + } +) +``` + +> See "Progressive Decoding" demo to see progressive JPEG in practice. + +#### Animated Images + +Nuke extends `UIImage` with `animatedImageData` property. If you enable it by setting `ImagePipeline.Configuration.isAnimatedImageDataEnabled` to `true` the pipeline will start attaching original image data to the animated images (built-in decoder only supports GIFs for now). + +> `ImageCache` takes `animatedImageData` into account when computing the cost of cached items. `ImagePipeline` doesn't apply processors to the images with animated data. + +There is no built-in way to render those images, but there are two integrations available: [FLAnimatedImage](https://github.com/kean/Nuke-FLAnimatedImage-Plugin) and [Gifu](https://github.com/kean/Nuke-Gifu-Plugin) which are both fast and efficient. + +> `GIF` is not the most efficient format for transferring and displaying animated images. The current best practice is to [use short videos instead of GIFs](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/replace-animated-gifs-with-video/) (e.g. `MP4`, `WebM`). There is a PoC available in the demo project which uses Nuke to load, cache and display an `MP4` video. + +#### WebP + +WebP support is provided by [Nuke WebP Plugin](https://github.com/ryokosuge/Nuke-WebP-Plugin) built by [Ryo Kosuge](https://github.com/ryokosuge). Please follow the intructions from the repo to install it. + +#### RxNuke + +[RxNuke](https://github.com/kean/RxNuke) adds [RxSwift](https://github.com/ReactiveX/RxSwift) extensions for Nuke and enables many common use cases: + +- [Going from low to high resolution](https://github.com/kean/RxNuke#going-from-low-to-high-resolution) +- [Loading the first available image](https://github.com/kean/RxNuke#loading-the-first-available-image) +- [Showing stale image while validating it](https://github.com/kean/RxNuke#showing-stale-image-while-validating-it) +- [Load multiple images, display all at once](https://github.com/kean/RxNuke#load-multiple-images-display-all-at-once) +- [Auto retry on failures](https://github.com/kean/RxNuke#auto-retry) +- And [more...](https://github.com/kean/RxNuke#use-cases) + +Here's an example of how easy it is to load go flow log to high resolution: + +```swift +let pipeline = ImagePipeline.shared +Observable.concat(pipeline.loadImage(with: lowResUrl).orEmpty, + pipeline.loadImage(with: highResUtl).orEmpty) + .subscribe(onNext: { imageView.image = $0 }) + .disposed(by: disposeBag) +``` + + +# Image Pipeline + +Nuke's image pipeline consists of roughly five stages which can be customized using the following protocols: + +|Protocol|Description| +|--------|-----------| +|`DataLoading`|Download (or return cached) image data| +|`DataCaching`|Custom data cache| +|`ImageDecoding`|Convert data into image objects| +|`ImageProcessing`|Apply image transformations| +|`ImageCaching`|Store image into memory cache| + +### Default Image Pipeline + +The default image pipeline configuration looks like this: + +```swift +ImagePipeline { + // Shared image cache with a `sizeLimit` equal to ~20% of available RAM. + $0.imageCache = ImageCache.shared + + // Data loader with a `URLSessionConfiguration.default` but with a + // custom shared URLCache instance: + // + // public static let sharedUrlCache = URLCache( + // memoryCapacity: 0, + // diskCapacity: 150 * 1024 * 1024, // 150 MB + // diskPath: "com.github.kean.Nuke.Cache" + // ) + $0.dataLoader = DataLoader() + + // Custom disk cache is disabled by default, the native URL cache used + // by a `DataLoader` is used instead. + $0.dataCache = nil + + // Each stage is executed on a dedicated queue with has its own limits. + $0.dataLoadingQueue.maxConcurrentOperationCount = 6 + $0.imageDecodingQueue.maxConcurrentOperationCount = 1 + $0.imageProcessingQueue.maxConcurrentOperationCount = 2 + + // Combine the requests for the same original image into one. + $0.isDeduplicationEnabled = true + + // Progressive decoding is a resource intensive feature so it is + // disabled by default. + $0.isProgressiveDecodingEnabled = false +} +``` + +### Image Pipeline Overview + +Here's what happens when you call `Nuke.loadImage(with: url, into: imageView` method. + +First, Nuke synchronously checks if the image is available in the memory cache (`pipeline.configuration.imageCache`). If it's not, Nuke calls `pipeline.loadImage(with: request)` method. The pipeline also checks if the image is available in its memory cache, and if not, starts loading it. + +Before starting to load image data, the pipeline also checks whether there are any existing outstanding requests for the same image. If it finds one, no new requests are created. + +By default, the data is loaded using [`URLSession`](https://developer.apple.com/reference/foundation/nsurlsession) with a custom [`URLCache`](https://developer.apple.com/reference/foundation/urlcache) instance (see configuration above). The `URLCache` supports on-disk caching but it requires HTTP cache to be enabled. + +> See [Image Caching Guide](https://kean.github.io/post/image-caching) to learn more. + +When the data is loaded the pipeline decodes the data (creates `UIImage` object from `Data`). Then it applies a default image processor - `ImageDecompressor` - to force data decompression in a background. The processed image is then stored in the memory cache and returned in the completion closure. + +> When you create `UIImage` object form data, the data doesn't get decoded immediately. It's decoded the first time it's used - for example, when you display the image in an image view. Decoding is a resource-intensive operation, if you do it on the main thread you might see dropped frames, especially for image formats like JPEG. +> +> To prevent decoding happening on the main thread, Nuke perform it in a background for you. But for even better performance it's recommended to downsample the images. To do so create a request with a target view size: +> +> ImageRequest(url: url, targetSize: CGSize(width: 640, height: 320), contentMode: .aspectFill) +> +> **Warning:** target size is in pixels! +> +> See [Image and Graphics Best Practices](https://developer.apple.com/videos/play/wwdc2018/219) to learn more about image decoding and downsampling. + +### Data Loading and Caching + +A built-in `DataLoader` class implements `DataLoading` protocol and uses [`URLSession`](https://developer.apple.com/reference/foundation/nsurlsession) to load image data. The data is cached on disk using a [`URLCache`](https://developer.apple.com/reference/foundation/urlcache) instance, which by default is initialized with a memory capacity of 0 MB (Nuke stores images in memory, not image data) and a disk capacity of 150 MB. + +The `URLSession` class natively supports the `data`, `file`, `ftp`, `http`, and `https` URL schemes. Image pipeline can be used with any of those schemes as well. + +> See [Image Caching Guide](https://kean.github.io/post/image-caching) to learn more about image caching + +> See [Third Party Libraries](https://github.com/kean/Nuke/blob/master/Documentation/Guides/Third%20Party%20Libraries.md#using-other-caching-libraries) guide to learn how to use a custom data loader or cache + +Most developers either implement their own networking layer or use a third-party framework. Nuke supports both of those workflows. You can integrate your custom networking layer by implementing `DataLoading` protocol. + +> See [Alamofire Plugin](https://github.com/kean/Nuke-Alamofire-Plugin) that implements `DataLoading` protocol using [Alamofire](https://github.com/Alamofire/Alamofire) framework + +### Memory Cache + +Processed images which are ready to be displayed are stored in a fast in-memory cache (`ImageCache`). It uses [LRU (least recently used)](https://en.wikipedia.org/wiki/Cache_algorithms#Examples) replacement algorithm and has a limit which prevents it from using more than ~20% of available RAM. As a good citizen, `ImageCache` automatically evicts images on memory warnings and removes most of the images when the application enters background. + +### Resumable Downloads + +If the data task is terminated (either because of a failure or a cancelation) and the image was partially loaded, the next load will resume where it was left off. + +Resumable downloads require server to support [HTTP Range Requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests). Nuke supports both validators (`ETag` and `Last-Modified`). The resumable downloads are enabled by default. + +> By default resumable data is stored in an efficient memory cache. Future versions might include more customization. + +### Request Dedupication + +By default `ImagePipeline` combines the requests for the same image (but can be different processors) into the same task. The task's priority is set to the highest priority of registered requests and gets updated when requests are added or removed to the task. The task only gets canceled when all the registered requests are. + +> Deduplication can be disabled using `ImagePipeline.Configuration`. + + +# Performance + +Performance is one of the key differentiating factors for Nuke. + +The framework is tuned to do as little work on the main thread as possible. It uses multiple optimizations techniques to achieve that: reducing number of allocations, reducing dynamic dispatch, backing some structs by reference typed storage to reduce ARC overhead, etc. + +Nuke is fully asynchronous and works great under stress. `ImagePipeline` schedules each of its stages on a dedicated queue. Each queue limits the number of concurrent tasks, respect request priorities even when moving between queue, and cancels the work as soon as possible. Under certain loads, `ImagePipeline` will also rate limit the requests to prevent trashing of the underlying systems. + +Another important performance characteristic is memory usage. Nuke uses a custom memory cache with [LRU (least recently used)](https://en.wikipedia.org/wiki/Cache_algorithms#Examples) replacement algorithm. It has a limit which prevents it from using more than ~20% of available RAM. As a good citizen, `ImageCache` automatically evicts images on memory warnings and removes most of the images when the application enters background. + +### Performance Metrics + +When optimizing performance, it's important to measure. Nuke collects detailed performance metrics during the execution of each image task: + +```swift +ImagePipeline.shared.didFinishCollectingMetrics = { task, metrics in + print(metrics) +} +``` + +![timeline](https://user-images.githubusercontent.com/1567433/39193766-8dfd81b2-47dc-11e8-86b3-f3f69dc73d3a.png) + +``` +(lldb) po metrics + +Task Information { + Task ID - 1 + Duration - 22:35:16.123 – 22:35:16.475 (0.352s) + Was canceled - false + Is Memory Cache Hit - false + Was Subscribed To Existing Session - false +} +Session Information { + Session ID - 1 + Total Duration - 0.351s + Was Canceled - false +} +Timeline { + 22:35:16.124 – 22:35:16.475 (0.351s) - Total + ------------------------------------ + nil – nil (nil) - Check Disk Cache + 22:35:16.131 – 22:35:16.410 (0.278s) - Load Data + 22:35:16.410 – 22:35:16.468 (0.057s) - Decode + 22:35:16.469 – 22:35:16.474 (0.005s) - Process +} +Resumable Data { + Was Resumed - nil + Resumable Data Count - nil + Server Confirmed Resume - nil +} +``` + + +# Extensions + +There are a variety extensions available for Nuke some of which are built by the community. + +|Name|Description| +|--|--| +|[**RxNuke**](https://github.com/kean/RxNuke)|[RxSwift](https://github.com/ReactiveX/RxSwift) extensions for Nuke with examples of common use cases solved by Rx| +|[**Alamofire**](https://github.com/kean/Nuke-Alamofire-Plugin)|Replace networking layer with [Alamofire](https://github.com/Alamofire/Alamofire) and combine the power of both frameworks| +|[**WebP**](https://github.com/ryokosuge/Nuke-WebP-Plugin)| **[Community]** [WebP](https://developers.google.com/speed/webp/) support, built by [Ryo Kosuge](https://github.com/ryokosuge)| +|[**Gifu**](https://github.com/kean/Nuke-Gifu-Plugin)|Use [Gifu](https://github.com/kaishin/Gifu) to load and display animated GIFs| +|[**FLAnimatedImage**](https://github.com/kean/Nuke-AnimatedImage-Plugin)|Use [FLAnimatedImage](https://github.com/Flipboard/FLAnimatedImage) to load and display [animated GIFs]((https://www.youtube.com/watch?v=fEJqQMJrET4))| + + + +# Contribution + +[Nuke's roadmap](https://trello.com/b/Us4rHryT/nuke) is managed in Trello and is publically available. + +If you'd like to contribute, please feel free to create a PR. + + +# Requirements + +- iOS 9.0 / watchOS 2.0 / macOS 10.10 / tvOS 9.0 +- Xcode 9.2 - Xcode 10 +- Swift 4.0 - Swift 4.2 + +# License + +Nuke is available under the MIT license. See the LICENSE file for more info. diff --git a/Pods/Nuke/Sources/DataCache.swift b/Pods/Nuke/Sources/DataCache.swift new file mode 100644 index 0000000000..31f1d337fc --- /dev/null +++ b/Pods/Nuke/Sources/DataCache.swift @@ -0,0 +1,461 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation + +// MARK: - DataCaching + +/// Data cache. +/// +/// - warning: The implementation must be thread safe. +public protocol DataCaching { + /// Retrieves data from cache for the given key. + func cachedData(for key: String) -> Data? + + /// Stores data for the given key. + /// - note: The implementation must return immediately and store data + /// asynchronously. + func storeData(_ data: Data, for key: String) +} + +// MARK: - DataCache + +/// Data cache backed by a local storage. +/// +/// The DataCache uses LRU cleanup policy (least recently used items are removed +/// first). The elements stored in the cache are automatically discarded if +/// either *cost* or *count* limit is reached. The sweeps are performed periodically. +/// +/// DataCache always writes and removes data asynchronously. It also allows for +/// reading and writing data in parallel. This is implemented using a "staging" +/// area which stores changes until they are flushed to disk: +/// +/// // Schedules data to be written asynchronously and returns immediately +/// cache[key] = data +/// +/// // The data is returned from the staging area +/// let data = cache[key] +/// +/// // Schedules data to be removed asynchronously and returns immediately +/// cache[key] = nil +/// +/// // Data is nil +/// let data = cache[key] +/// +/// Thread-safe. +/// +/// - warning: It's possible to have more than one instance of `DataCache` with +/// the same `path` but it is not recommended. +public final class DataCache: DataCaching { + /// A cache key. + public typealias Key = String + + /// The maximum number of items. `1000` by default. + /// + /// Changes tos `countLimit` will take effect when the next LRU sweep is run. + public var countLimit: Int = 1000 + + /// Size limit in bytes. `100 Mb` by default. + /// + /// Changes to `sizeLimit` will take effect when the next LRU sweep is run. + public var sizeLimit: Int = 1024 * 1024 * 100 + + /// When performing a sweep, the cache will remote entries until the size of + /// the remaining items is lower than or equal to `sizeLimit * trimRatio` and + /// the total count is lower than or equal to `countLimit * trimRatio`. `0.7` + /// by default. + internal var trimRatio = 0.7 + + /// The path for the directory managed by the cache. + public let path: URL + + /// The number of seconds between each LRU sweep. 30 by default. + /// The first sweep is performed right after the cache is initialized. + /// + /// Sweeps are performed in a background and can be performed in parallel + /// with reading. + public var sweepInterval: TimeInterval = 30 + + /// The delay after which the initial sweep is performed. 10 by default. + /// The initial sweep is performed after a delay to avoid competing with + /// other subsystems for the resources. + private var initialSweepDelay: TimeInterval = 15 + + // Staging + private let _lock = NSLock() + private var _staging = Staging() + + /* testable */ let _wqueue = DispatchQueue(label: "com.github.kean.Nuke.DataCache.WriteQueue") + + /// A function which generates a filename for the given key. A good candidate + /// for a filename generator is a _cryptographic_ hash function like SHA1. + /// + /// The reason why filename needs to be generated in the first place is + /// that filesystems have a size limit for filenames (e.g. 255 UTF-8 characters + /// in AFPS) and do not allow certain characters to be used in filenames. + public typealias FilenameGenerator = (_ key: String) -> String? + + private let _filenameGenerator: FilenameGenerator + + #if swift(>=4.2) + /// Creates a cache instance with a given `name`. The cache creates a directory + /// with the given `name` in a `.cachesDirectory` in `.userDomainMask`. + /// - parameter filenameGenerator: Generates a filename for the given URL. + /// The default implementation generates a filename using SHA1 hash function. + public convenience init(name: String, filenameGenerator: @escaping (String) -> String? = DataCache.filename(for:)) throws { + guard let root = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { + throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: nil) + } + try self.init(path: root.appendingPathComponent(name, isDirectory: true), filenameGenerator: filenameGenerator) + } + + /// Creates a cache instance with a given path. + /// - parameter filenameGenerator: Generates a filename for the given URL. + /// The default implementation generates a filename using SHA1 hash function. + public init(path: URL, filenameGenerator: @escaping (String) -> String? = DataCache.filename(for:)) throws { + self.path = path + self._filenameGenerator = filenameGenerator + try self._didInit() + } + + /// A `FilenameGenerator` implementation which uses SHA1 hash function to + /// generate a filename from the given key. + public static func filename(for key: String) -> String? { + return key.sha1 + } + #else + /// Creates a cache instance with a given `name`. The cache creates a directory + /// with the given `name` in a `.cachesDirectory` in `.userDomainMask`. + /// - parameter filenameGenerator: Generates a filename for the given URL. + public convenience init(name: String, filenameGenerator: @escaping (String) -> String?) throws { + guard let root = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { + throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: nil) + } + try self.init(path: root.appendingPathComponent(name, isDirectory: true), filenameGenerator: filenameGenerator) + } + + /// Creates a cache instance with a given path. + /// - parameter filenameGenerator: Generates a filename for the given URL. + public init(path: URL, filenameGenerator: @escaping (String) -> String?) throws { + self.path = path + self._filenameGenerator = filenameGenerator + try self._didInit() + } + #endif + + private func _didInit() throws { + try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true, attributes: nil) + _wqueue.asyncAfter(deadline: .now() + initialSweepDelay) { [weak self] in + self?._performAndScheduleSweep() + } + } + + // MARK: DataCaching + + /// Retrieves data for the given key. The completion will be called + /// syncrhonously if there is no cached data for the given key. + public func cachedData(for key: Key) -> Data? { + _lock.lock() + + if let change = _staging.change(for: key) { + _lock.unlock() + switch change { + case let .add(data): + return data + case .remove: + return nil + } + } + + _lock.unlock() + + guard let url = _url(for: key) else { + return nil + } + return try? Data(contentsOf: url) + } + + /// Stores data for the given key. The method returns instantly and the data + /// is written asynchronously. + public func storeData(_ data: Data, for key: Key) { + _lock.sync { + let change = _staging.add(data: data, for: key) + _wqueue.async { + if let url = self._url(for: key) { + try? data.write(to: url) + } + self._lock.sync { + self._staging.flushed(change) + } + } + } + } + + /// Removes data for the given key. The method returns instantly, the data + /// is removed asynchronously. + public func removeData(for key: Key) { + _lock.sync { + let change = _staging.removeData(for: key) + _wqueue.async { + if let url = self._url(for: key) { + try? FileManager.default.removeItem(at: url) + } + self._lock.sync { + self._staging.flushed(change) + } + } + } + } + + /// Removes all items. The method returns instantly, the data is removed + /// asynchronously. + public func removeAll() { + _lock.sync { + let change = _staging.removeAll() + _wqueue.async { + try? FileManager.default.removeItem(at: self.path) + try? FileManager.default.createDirectory(at: self.path, withIntermediateDirectories: true, attributes: nil) + self._lock.sync { + self._staging.flushed(change) + } + } + } + } + + /// Accesses the data associated with the given key for reading and writing. + /// + /// When you assign a new data for a key and the key already exists, the cache + /// overwrites the existing data. + /// + /// When assigning or removing data, the subscript adds a requested operation + /// in a staging area and returns immediately. The staging area allows for + /// reading and writing data in parallel. + /// + /// // Schedules data to be written asynchronously and returns immediately + /// cache[key] = data + /// + /// // The data is returned from the staging area + /// let data = cache[key] + /// + /// // Schedules data to be removed asynchronously and returns immediately + /// cache[key] = nil + /// + /// // Data is nil + /// let data = cache[key] + /// + public subscript(key: Key) -> Data? { + get { + return cachedData(for: key) + } + set { + if let data = newValue { + storeData(data, for: key) + } else { + removeData(for: key) + } + } + } + + // MARK: Managing URLs + + /// Uses the `FilenameGenerator` that the cache was initialized with to + /// generate and return a filename for the given key. + public func filename(for key: Key) -> String? { + return _filenameGenerator(key) + } + + /* testable */ func _url(for key: Key) -> URL? { + guard let filename = self.filename(for: key) else { + return nil + } + return self.path.appendingPathComponent(filename, isDirectory: false) + } + + // MARK: Flush Changes + + /// Synchronously waits on the caller's thread until all outstanding disk IO + /// operations are finished. + func flush() { + _wqueue.sync {} + } + + // MARK: Sweep + + private func _performAndScheduleSweep() { + _sweep() + _wqueue.asyncAfter(deadline: .now() + sweepInterval) { [weak self] in + self?._performAndScheduleSweep() + } + } + + /// Schedules a cache sweep to be performed immediately. + public func sweep() { + _wqueue.async { + self._sweep() + } + } + + /// Discards the least recently used items first. + private func _sweep() { + var items = contents(keys: [.contentAccessDateKey, .totalFileAllocatedSizeKey]) + guard !items.isEmpty else { + return + } + var size = items.reduce(0) { $0 + ($1.meta.totalFileAllocatedSize ?? 0) } + var count = items.count + let sizeLimit = self.sizeLimit / Int(1 / trimRatio) + let countLimit = self.countLimit / Int(1 / trimRatio) + + guard size > sizeLimit || count > countLimit else { + return // All good, no need to perform any work. + } + + // Most recently accessed items first + let past = Date.distantPast + items.sort { // Sort in place + ($0.meta.contentAccessDate ?? past) > ($1.meta.contentAccessDate ?? past) + } + + // Remove the items until we satisfy both size and count limits. + while (size > sizeLimit || count > countLimit), let item = items.popLast() { + size -= (item.meta.totalFileAllocatedSize ?? 0) + count -= 1 + try? FileManager.default.removeItem(at: item.url) + } + } + + // MARK: Contents + + struct Entry { + let url: URL + let meta: URLResourceValues + } + + func contents(keys: [URLResourceKey] = []) -> [Entry] { + guard let urls = try? FileManager.default.contentsOfDirectory(at: path, includingPropertiesForKeys: keys, options: .skipsHiddenFiles) else { + return [] + } + let _keys = Set(keys) + return urls.compactMap { + guard let meta = try? $0.resourceValues(forKeys: _keys) else { + return nil + } + return Entry(url: $0, meta: meta) + } + } + + // MARK: Inspection + + /// The total number of items in the cache. + /// - warning: Requires disk IO, avoid using from the main thread. + public var totalCount: Int { + return contents().count + } + + /// The total file size of items written on disk. + /// + /// Uses `URLResourceKey.fileSizeKey` to calculate the size of each entry. + /// The total allocated size (see `totalAllocatedSize`. on disk might + /// actually be bigger. + /// + /// - warning: Requires disk IO, avoid using from the main thread. + public var totalSize: Int { + return contents(keys: [.fileSizeKey]).reduce(0) { + $0 + ($1.meta.fileSize ?? 0) + } + } + + /// The total file allocated size of all the items written on disk. + /// + /// Uses `URLResourceKey.totalFileAllocatedSizeKey`. + /// + /// - warning: Requires disk IO, avoid using from the main thread. + public var totalAllocatedSize: Int { + return contents(keys: [.totalFileAllocatedSizeKey]).reduce(0) { + $0 + ($1.meta.totalFileAllocatedSize ?? 0) + } + } + + // MARK: - Staging + + /// DataCache allows for parallel reads and writes. This is made possible by + /// DataCacheStaging. + /// + /// For example, when the data is added in cache, it is first added to staging + /// and is removed from staging only after data is written to disk. Removal works + /// the same way. + private final class Staging { + private var changes = [String: Change]() + private var changeRemoveAll: ChangeRemoveAll? + + struct ChangeRemoveAll { + let id: Int + } + + struct Change { + let key: String + let id: Int + let type: ChangeType + } + + enum ChangeType { + case add(Data) + case remove + } + + private var nextChangeId = 0 + + // MARK: Changes + + func change(for key: String) -> ChangeType? { + if let change = changes[key] { + return change.type + } + if changeRemoveAll != nil { + return .remove + } + return nil + } + + // MARK: Register Changes + + func add(data: Data, for key: String) -> Change { + return _makeChange(.add(data), for: key) + } + + func removeData(for key: String) -> Change { + return _makeChange(.remove, for: key) + } + + private func _makeChange(_ type: ChangeType, for key: String) -> Change { + nextChangeId += 1 + let change = Change(key: key, id: nextChangeId, type: type) + changes[key] = change + return change + } + + func removeAll() -> ChangeRemoveAll { + nextChangeId += 1 + let change = ChangeRemoveAll(id: nextChangeId) + changeRemoveAll = change + changes.removeAll() + return change + } + + // MARK: Flush Changes + + func flushed(_ change: Change) { + if let index = changes.index(forKey: change.key), + changes[index].value.id == change.id { + changes.remove(at: index) + } + } + + func flushed(_ change: ChangeRemoveAll) { + if changeRemoveAll?.id == change.id { + changeRemoveAll = nil + } + } + } +} diff --git a/Pods/Nuke/Sources/DataLoader.swift b/Pods/Nuke/Sources/DataLoader.swift new file mode 100644 index 0000000000..cbf2625802 --- /dev/null +++ b/Pods/Nuke/Sources/DataLoader.swift @@ -0,0 +1,160 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation + +public protocol Cancellable: class { + func cancel() +} + +public protocol DataLoading { + /// - parameter didReceiveData: Can be called multiple times if streaming + /// is supported. + /// - parameter completion: Must be called once after all (or none in case + /// of an error) `didReceiveData` closures have been called. + func loadData(with request: URLRequest, + didReceiveData: @escaping (Data, URLResponse) -> Void, + completion: @escaping (Error?) -> Void) -> Cancellable +} + +extension URLSessionTask: Cancellable {} + +/// Provides basic networking using `URLSession`. +public final class DataLoader: DataLoading { + public let session: URLSession + private let _impl: _DataLoader + + /// Initializes `DataLoader` with the given configuration. + /// - parameter configuration: `URLSessionConfiguration.default` with + /// `URLCache` with 0 MB memory capacity and 150 MB disk capacity. + public init(configuration: URLSessionConfiguration = DataLoader.defaultConfiguration, + validate: @escaping (URLResponse) -> Swift.Error? = DataLoader.validate) { + self._impl = _DataLoader() + self.session = URLSession(configuration: configuration, delegate: _impl, delegateQueue: _impl.queue) + self._impl.session = self.session + self._impl.validate = validate + } + + /// Returns a default configuration which has a `sharedUrlCache` set + /// as a `urlCache`. + public static var defaultConfiguration: URLSessionConfiguration { + let conf = URLSessionConfiguration.default + conf.urlCache = DataLoader.sharedUrlCache + return conf + } + + /// Validates `HTTP` responses by checking that the status code is 2xx. If + /// it's not returns `DataLoader.Error.statusCodeUnacceptable`. + public static func validate(response: URLResponse) -> Swift.Error? { + guard let response = response as? HTTPURLResponse else { return nil } + return (200..<300).contains(response.statusCode) ? nil : Error.statusCodeUnacceptable(response.statusCode) + } + +#if !os(macOS) + private static let cachePath = "com.github.kean.Nuke.Cache" +#else + private static let cachePath: String = { + let cachePaths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) + if let cachePath = cachePaths.first, let identifier = Bundle.main.bundleIdentifier { + return cachePath.appending("/" + identifier) + } + + return "" + }() +#endif + + /// Shared url cached used by a default `DataLoader`. The cache is + /// initialized with 0 MB memory capacity and 150 MB disk capacity. + public static let sharedUrlCache = URLCache( + memoryCapacity: 0, + diskCapacity: 150 * 1024 * 1024, // 150 MB + diskPath: cachePath + ) + + public func loadData(with request: URLRequest, didReceiveData: @escaping (Data, URLResponse) -> Void, completion: @escaping (Swift.Error?) -> Void) -> Cancellable { + return _impl.loadData(with: request, didReceiveData: didReceiveData, completion: completion) + } + + /// Errors produced by `DataLoader`. + public enum Error: Swift.Error, CustomDebugStringConvertible { + /// Validation failed. + case statusCodeUnacceptable(Int) + /// Either the response or body was empty. + @available(*, deprecated, message: "This error case is not used any more") + case responseEmpty + + public var debugDescription: String { + switch self { + case let .statusCodeUnacceptable(code): return "Response status code was unacceptable: " + code.description // compiles faster than interpolation + case .responseEmpty: return "Either the response or body was empty." + } + } + } +} + +// Actual data loader implementation. We hide NSObject inheritance, hide +// URLSessionDataDelegate conformance, and break retain cycle between URLSession +// and URLSessionDataDelegate. +private final class _DataLoader: NSObject, URLSessionDataDelegate { + weak var session: URLSession! // This is safe. + var validate: (URLResponse) -> Swift.Error? = DataLoader.validate + let queue = OperationQueue() + + private var handlers = [URLSessionTask: _Handler]() + + override init() { + self.queue.maxConcurrentOperationCount = 1 + } + + /// Loads data with the given request. + func loadData(with request: URLRequest, didReceiveData: @escaping (Data, URLResponse) -> Void, completion: @escaping (Error?) -> Void) -> Cancellable { + let task = session.dataTask(with: request) + let handler = _Handler(didReceiveData: didReceiveData, completion: completion) + queue.addOperation { // `URLSession` is configured to use this same queue + self.handlers[task] = handler + } + task.resume() + return task + } + + // MARK: URLSessionDelegate + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + guard let handler = handlers[dataTask] else { + completionHandler(.cancel) + return + } + // Validate response as soon as we receive it can cancel the request if necessary + if let error = validate(response) { + handler.completion(error) + completionHandler(.cancel) + return + } + completionHandler(.allow) + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + guard let handler = handlers[task] else { return } + handlers[task] = nil + handler.completion(error) + } + + // MARK: URLSessionDataDelegate + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + guard let handler = handlers[dataTask], let response = dataTask.response else { return } + // We don't store data anywhere, just send it to the pipeline. + handler.didReceiveData(data, response) + } + + private final class _Handler { + let didReceiveData: (Data, URLResponse) -> Void + let completion: (Error?) -> Void + + init(didReceiveData: @escaping (Data, URLResponse) -> Void, completion: @escaping (Error?) -> Void) { + self.didReceiveData = didReceiveData + self.completion = completion + } + } +} diff --git a/Pods/Nuke/Sources/ImageCache.swift b/Pods/Nuke/Sources/ImageCache.swift new file mode 100644 index 0000000000..f6f4cc5860 --- /dev/null +++ b/Pods/Nuke/Sources/ImageCache.swift @@ -0,0 +1,305 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation +#if !os(macOS) +import UIKit +#else +import Cocoa +#endif + +/// In-memory image cache. +/// +/// The implementation must be thread safe. +public protocol ImageCaching: class { + /// Returns the `ImageResponse` stored in the cache with the given request. + func cachedResponse(for request: ImageRequest) -> ImageResponse? + + /// Stores the given `ImageResponse` in the cache using the given request. + func storeResponse(_ response: ImageResponse, for request: ImageRequest) + + /// Remove the response for the given request. + func removeResponse(for request: ImageRequest) +} + +/// Convenience subscript. +public extension ImageCaching { + /// Accesses the image associated with the given request. + public subscript(request: ImageRequest) -> Image? { + get { + return cachedResponse(for: request)?.image + } + set { + if let newValue = newValue { + storeResponse(ImageResponse(image: newValue, urlResponse: nil), for: request) + } else { + removeResponse(for: request) + } + } + } +} + +/// Memory cache with LRU cleanup policy (least recently used are removed first). +/// +/// The elements stored in cache are automatically discarded if either *cost* or +/// *count* limit is reached. The default cost limit represents a number of bytes +/// and is calculated based on the amount of physical memory available on the +/// device. The default cmount limit is set to `Int.max`. +/// +/// `Cache` automatically removes all stored elements when it received a +/// memory warning. It also automatically removes *most* of cached elements +/// when the app enters background. +public final class ImageCache: ImageCaching { + private let _impl: _Cache + + /// The maximum total cost that the cache can hold. + public var costLimit: Int { + get { return _impl.costLimit } + set { _impl.costLimit = newValue } + } + + /// The maximum number of items that the cache can hold. + public var countLimit: Int { + get { return _impl.countLimit } + set { _impl.countLimit = newValue } + } + + /// Default TTL (time to live) for each entry. Can be used to make sure that + /// the entries get validated at some point. `0` (never expire) by default. + public var ttl: TimeInterval { + get { return _impl.ttl } + set { _impl.ttl = newValue } + } + + /// The total cost of items in the cache. + public var totalCost: Int { + return _impl.totalCost + } + + /// The total number of items in the cache. + public var totalCount: Int { + return _impl.totalCount + } + + /// Shared `Cache` instance. + public static let shared = ImageCache() + + /// Initializes `Cache`. + /// - parameter costLimit: Default value representes a number of bytes and is + /// calculated based on the amount of the phisical memory available on the device. + /// - parameter countLimit: `Int.max` by default. + public init(costLimit: Int = ImageCache.defaultCostLimit(), countLimit: Int = Int.max) { + _impl = _Cache(costLimit: costLimit, countLimit: countLimit) + } + + /// Returns a recommended cost limit which is computed based on the amount + /// of the phisical memory available on the device. + public static func defaultCostLimit() -> Int { + let physicalMemory = ProcessInfo.processInfo.physicalMemory + let ratio = physicalMemory <= (536_870_912 /* 512 Mb */) ? 0.1 : 0.2 + let limit = physicalMemory / UInt64(1 / ratio) + return limit > UInt64(Int.max) ? Int.max : Int(limit) + } + + /// Returns the `ImageResponse` stored in the cache with the given request. + public func cachedResponse(for request: ImageRequest) -> ImageResponse? { + return _impl.value(forKey: ImageRequest.CacheKey(request: request)) + } + + /// Stores the given `ImageResponse` in the cache using the given request. + public func storeResponse(_ response: ImageResponse, for request: ImageRequest) { + _impl.set(response, forKey: ImageRequest.CacheKey(request: request), cost: self.cost(for: response.image)) + } + + /// Removes response stored with the given request. + public func removeResponse(for request: ImageRequest) { + _impl.removeValue(forKey: ImageRequest.CacheKey(request: request)) + } + + /// Removes all cached images. + public func removeAll() { + _impl.removeAll() + } + /// Removes least recently used items from the cache until the total cost + /// of the remaining items is less than the given cost limit. + public func trim(toCost limit: Int) { + _impl.trim(toCost: limit) + } + + /// Removes least recently used items from the cache until the total count + /// of the remaining items is less than the given count limit. + public func trim(toCount limit: Int) { + _impl.trim(toCount: limit) + } + + /// Returns cost for the given image by approximating its bitmap size in bytes in memory. + func cost(for image: Image) -> Int { + #if !os(macOS) + let dataCost = ImagePipeline.Configuration.isAnimatedImageDataEnabled ? (image.animatedImageData?.count ?? 0) : 0 + + // bytesPerRow * height gives a rough estimation of how much memory + // image uses in bytes. In practice this algorithm combined with a + // concervative default cost limit works OK. + guard let cgImage = image.cgImage else { + return 1 + dataCost + } + return cgImage.bytesPerRow * cgImage.height + dataCost + + #else + return 1 + #endif + } +} + +internal final class _Cache { + // We don't use `NSCache` because it's not LRU + + private var map = [Key: LinkedList.Node]() + private let list = LinkedList() + private let lock = NSLock() + + var costLimit: Int { + didSet { lock.sync(_trim) } + } + + var countLimit: Int { + didSet { lock.sync(_trim) } + } + + private(set) var totalCost = 0 + var ttl: TimeInterval = 0 + + var totalCount: Int { + return map.count + } + + init(costLimit: Int, countLimit: Int) { + self.costLimit = costLimit + self.countLimit = countLimit + #if os(iOS) || os(tvOS) + #if swift(>=4.2) + NotificationCenter.default.addObserver(self, selector: #selector(removeAll), name: UIApplication.didReceiveMemoryWarningNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) + #else + NotificationCenter.default.addObserver(self, selector: #selector(removeAll), name: .UIApplicationDidReceiveMemoryWarning, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: .UIApplicationDidEnterBackground, object: nil) + #endif + #endif + } + + deinit { + #if os(iOS) || os(tvOS) + NotificationCenter.default.removeObserver(self) + #endif + } + + func value(forKey key: Key) -> Value? { + lock.lock(); defer { lock.unlock() } + + guard let node = map[key] else { + return nil + } + + guard !node.value.isExpired else { + _remove(node: node) + return nil + } + + // bubble node up to make it last added (most recently used) + list.remove(node) + list.append(node) + + return node.value.value + } + + func set(_ value: Value, forKey key: Key, cost: Int = 0, ttl: TimeInterval? = nil) { + lock.lock(); defer { lock.unlock() } + + let ttl = ttl ?? self.ttl + let expiration = ttl == 0 ? nil : (Date() + ttl) + let entry = Entry(value: value, key: key, cost: cost, expiration: expiration) + _add(entry) + _trim() // _trim is extremely fast, it's OK to call it each time + } + + @discardableResult + func removeValue(forKey key: Key) -> Value? { + lock.lock(); defer { lock.unlock() } + + guard let node = map[key] else { return nil } + _remove(node: node) + return node.value.value + } + + private func _add(_ element: Entry) { + if let existingNode = map[element.key] { + _remove(node: existingNode) + } + map[element.key] = list.append(element) + totalCost += element.cost + } + + private func _remove(node: LinkedList.Node) { + list.remove(node) + map[node.value.key] = nil + totalCost -= node.value.cost + } + + @objc dynamic func removeAll() { + lock.sync { + map.removeAll() + list.removeAll() + totalCost = 0 + } + } + + private func _trim() { + _trim(toCost: costLimit) + _trim(toCount: countLimit) + } + + @objc private dynamic func didEnterBackground() { + // Remove most of the stored items when entering background. + // This behavior is similar to `NSCache` (which removes all + // items). This feature is not documented and may be subject + // to change in future Nuke versions. + lock.sync { + _trim(toCost: Int(Double(costLimit) * 0.1)) + _trim(toCount: Int(Double(countLimit) * 0.1)) + } + } + + func trim(toCost limit: Int) { + lock.sync { _trim(toCost: limit) } + } + + private func _trim(toCost limit: Int) { + _trim(while: { totalCost > limit }) + } + + func trim(toCount limit: Int) { + lock.sync { _trim(toCount: limit) } + } + + private func _trim(toCount limit: Int) { + _trim(while: { totalCount > limit }) + } + + private func _trim(while condition: () -> Bool) { + while condition(), let node = list.first { // least recently used + _remove(node: node) + } + } + + private struct Entry { + let value: Value + let key: Key + let cost: Int + let expiration: Date? + var isExpired: Bool { + guard let expiration = expiration else { return false } + return expiration.timeIntervalSinceNow < 0 + } + } +} diff --git a/Pods/Nuke/Sources/ImageDecoding.swift b/Pods/Nuke/Sources/ImageDecoding.swift new file mode 100644 index 0000000000..51945300b8 --- /dev/null +++ b/Pods/Nuke/Sources/ImageDecoding.swift @@ -0,0 +1,230 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +#if !os(macOS) +import UIKit +#else +import Cocoa +#endif + +#if os(watchOS) +import WatchKit +#endif + +// MARK: - ImageDecoding + +/// Decodes image data. +public protocol ImageDecoding { + /// Produces an image from the image data. A decoder is a one-shot object + /// created for a single image decoding session. If image pipeline has + /// progressive decoding enabled, the `decode(data:isFinal:)` method gets + /// called each time the data buffer has new data available. The decoder may + /// decide whether or not to produce a new image based on the previous scans. + func decode(data: Data, isFinal: Bool) -> Image? +} + +// An image decoder that uses native APIs. Supports progressive decoding. +// The decoder is stateful. +public final class ImageDecoder: ImageDecoding { + // `nil` if decoder hasn't detected whether progressive decoding is enabled. + private(set) internal var isProgressive: Bool? + // Number of scans that the decoder has found so far. The last scan might be + // incomplete at this point. + private(set) internal var numberOfScans = 0 + private var lastStartOfScan: Int = 0 // Index of the last Start of Scan that we found + private var scannedIndex: Int = -1 // Index at which previous scan was finished + + public init() { } + + public func decode(data: Data, isFinal: Bool) -> Image? { + let format = ImageFormat.format(for: data) + + guard !isFinal else { // Just decode the data. + let image = _decode(data) + if ImagePipeline.Configuration.isAnimatedImageDataEnabled, case .gif? = format { // Keep original data around in case of GIF + image?.animatedImageData = data + } + return image + } + + // Determined (if we haven't yet) whether the image supports progressive + // decoding or not (only proressive JPEG is allowed for now, but you can + // add support for other formats by implementing your own decoder). + isProgressive = isProgressive ?? format?.isProgressive + guard isProgressive == true else { return nil } + + // Check if there is more data to scan. + guard (scannedIndex + 1) < data.count else { return nil } + + // Start scaning from the where we left off previous time. + var index = (scannedIndex + 1) + var numberOfScans = self.numberOfScans + while index < (data.count - 1) { + scannedIndex = index + // 0xFF, 0xDA - Start Of Scan + if data[index] == 0xFF, data[index+1] == 0xDA { + lastStartOfScan = index + numberOfScans += 1 + } + index += 1 + } + + // Found more scans this the previous time + guard numberOfScans > self.numberOfScans else { return nil } + self.numberOfScans = numberOfScans + + // `> 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. + return (numberOfScans > 1 && lastStartOfScan > 0) ? _decode(data[0.. The immutable nature of image objects also means that they are safe +// to create and use from any thread. +// +// However, there are some versions of iOS which violated this. The +// `UIImage` is supposably fully thread safe again starting with iOS 10. +// +// The `queue.sync` call below prevents the majority of the potential +// crashes that could happen on the previous versions of iOS. +// +// See also https://github.com/AFNetworking/AFNetworking/issues/2572 +private let _queue = DispatchQueue(label: "com.github.kean.Nuke.DataDecoder") + +internal func _decode(_ data: Data) -> Image? { + return _queue.sync { + #if os(macOS) + return NSImage(data: data) + #else + #if os(iOS) || os(tvOS) + let scale = UIScreen.main.scale + #else + let scale = WKInterfaceDevice.current().screenScale + #endif + return UIImage(data: data, scale: scale) + #endif + } +} + +// MARK: - ImageDecoderRegistry + +/// A register of image codecs (only decoding). +public final class ImageDecoderRegistry { + /// A shared registry. + public static let shared = ImageDecoderRegistry() + + private var matches = [(ImageDecodingContext) -> ImageDecoding?]() + + /// Returns a decoder which matches the given context. + public func decoder(for context: ImageDecodingContext) -> ImageDecoding { + for match in matches { + if let decoder = match(context) { + return decoder + } + } + return ImageDecoder() // Return default decoder if couldn't find a custom one. + } + + /// Registers a decoder to be used in a given decoding context. The closure + /// is going to be executed before all other already registered closures. + public func register(_ match: @escaping (ImageDecodingContext) -> ImageDecoding?) { + matches.insert(match, at: 0) + } + + func clear() { + matches = [] + } +} + +/// Image decoding context used when selecting which decoder to use. +public struct ImageDecodingContext { + public let request: ImageRequest + internal let urlResponse: URLResponse? + public let data: Data +} + +// MARK: - Image Formats + +enum ImageFormat: Equatable { + /// `isProgressive` is nil if we determined that it's a jpeg, but we don't + /// know if it is progressive or baseline yet. + case jpeg(isProgressive: Bool?) + case png + case gif + + // Returns `nil` if not enough data. + static func format(for data: Data) -> ImageFormat? { + // JPEG magic numbers https://en.wikipedia.org/wiki/JPEG + if _match(data, [0xFF, 0xD8, 0xFF]) { + var index = 3 // start scanning right after magic numbers + while index < (data.count - 1) { + // A example of first few bytes of progressive jpeg image: + // FF D8 FF E0 00 10 4A 46 49 46 00 01 01 00 00 48 00 ... + // + // 0xFF, 0xC0 - Start Of Frame (baseline DCT) + // 0xFF, 0xC2 - Start Of Frame (progressive DCT) + // https://en.wikipedia.org/wiki/JPEG + if data[index] == 0xFF { + if data[index+1] == 0xC2 { return .jpeg(isProgressive: true) } // progressive + if data[index+1] == 0xC0 { return .jpeg(isProgressive: false) } // baseline + } + index += 1 + } + // It's a jpeg but we don't know if progressive or not yet. + return .jpeg(isProgressive: nil) + } + + // GIF magic numbers https://en.wikipedia.org/wiki/GIF + if _match(data, [0x47, 0x49, 0x46]) { + return .gif + } + + // PNG Magic numbers https://en.wikipedia.org/wiki/Portable_Network_Graphics + if _match(data, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) { + return .png + } + + // Either not enough data, or we just don't know this format yet. + return nil + } + + var isProgressive: Bool? { + if case let .jpeg(isProgressive) = self { return isProgressive } + return false + } + + private static func _match(_ data: Data, _ numbers: [UInt8]) -> Bool { + guard data.count >= numbers.count else { return false } + return !zip(numbers.indices, numbers).contains { (index, number) in + data[index] != number + } + } + + #if !swift(>=4.1) + static func == (lhs: ImageFormat, rhs: ImageFormat) -> Bool { + switch (lhs, rhs) { + case let (.jpeg(lhs), .jpeg(rhs)): return lhs == rhs + case (.png, .png): return true + case (.gif, .gif): return true + default: return false + } + } + #endif +} + +// MARK: - Animated Images + +private var _animatedImageDataAK = "Nuke.AnimatedImageData.AssociatedKey" + +extension Image { + // Animated image data. Only not `nil` when image data actually contains + // an animated image. + public var animatedImageData: Data? { + get { return objc_getAssociatedObject(self, &_animatedImageDataAK) as? Data } + set { objc_setAssociatedObject(self, &_animatedImageDataAK, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } + } +} diff --git a/Pods/Nuke/Sources/ImagePipeline.swift b/Pods/Nuke/Sources/ImagePipeline.swift new file mode 100644 index 0000000000..59f6d6d0bc --- /dev/null +++ b/Pods/Nuke/Sources/ImagePipeline.swift @@ -0,0 +1,901 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation + +// MARK: - ImageTask + +/// A task performed by the `ImagePipeline`. The pipeline maintains a strong +/// reference to the task until the request finishes or fails; you do not need +/// to maintain a reference to the task unless it is useful to do so for your +/// app’s internal bookkeeping purposes. +public /* final */ class ImageTask: Hashable { + /// An identifier uniquely identifies the task within a given pipeline. Only + /// unique within this pipeline. + public let taskId: Int + + fileprivate weak var delegate: ImageTaskDelegate? + + /// The request with which the task was created. The request might change + /// during the exetucion of a task. When you update the priority of the task, + /// the request's prir also gets updated. + public private(set) var request: ImageRequest + + /// The number of bytes that the task has received. + public fileprivate(set) var completedUnitCount: Int64 = 0 + + /// A best-guess upper bound on the number of bytes the client expects to send. + public fileprivate(set) var totalUnitCount: Int64 = 0 + + /// Returns a progress object for the task. The object is created lazily. + public var progress: Progress { + if _progress == nil { _progress = Progress() } + return _progress! + } + fileprivate private(set) var _progress: Progress? + + /// A completion handler to be called when task finishes or fails. + public typealias Completion = (_ response: ImageResponse?, _ error: ImagePipeline.Error?) -> Void + + /// A progress handler to be called periodically during the lifetime of a task. + public typealias ProgressHandler = (_ response: ImageResponse?, _ completed: Int64, _ total: Int64) -> Void + + // internal stuff associated with a task + fileprivate var metrics: ImageTaskMetrics + + fileprivate weak var session: ImageLoadingSession? + + internal init(taskId: Int, request: ImageRequest) { + self.taskId = taskId + self.request = request + self.metrics = ImageTaskMetrics(taskId: taskId, startDate: Date()) + } + + // MARK: - Priority + + /// Update s priority of the task even if the task is already running. + public func setPriority(_ priority: ImageRequest.Priority) { + request.priority = priority + delegate?.imageTask(self, didUpdatePrioity: priority) + } + + // MARK: - Cancellation + + fileprivate var isCancelled: Bool { + return _wasCancelled == 1 + } + + private var _wasCancelled: Int32 = 0 + + /// Marks task as being cancelled. + /// + /// The pipeline will immediately cancel any work associated with a task + /// unless there is an equivalent outstanding task running (see + /// `ImagePipeline.Configuration.isDeduplicationEnabled` for more info). + public func cancel() { + // Make sure that we ignore if `cancel` being called more than once. + if OSAtomicCompareAndSwap32Barrier(0, 1, &_wasCancelled) { + delegate?.imageTaskWasCancelled(self) + } + } + + // MARK: - Hashable + + public static func == (lhs: ImageTask, rhs: ImageTask) -> Bool { + return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } + + public var hashValue: Int { + return ObjectIdentifier(self).hashValue + } +} + +protocol ImageTaskDelegate: class { + func imageTaskWasCancelled(_ task: ImageTask) + func imageTask(_ task: ImageTask, didUpdatePrioity: ImageRequest.Priority) +} + +// MARK: - ImageResponse + +/// Represents an image response. +public final class ImageResponse { + public let image: Image + public let urlResponse: URLResponse? + // the response is only nil when new disk cache is enabled (it only stores + // data for now, but this might change in the future). + + public init(image: Image, urlResponse: URLResponse?) { + self.image = image; self.urlResponse = urlResponse + } +} + +// MARK: - ImagePipeline + +/// `ImagePipeline` will load and decode image data, process loaded images and +/// store them in caches. +/// +/// See [Nuke's README](https://github.com/kean/Nuke) for a detailed overview of +/// the image pipeline and all of the related classes. +/// +/// `ImagePipeline` is created with a configuration (`Configuration`). +/// +/// `ImagePipeline` is thread-safe. +public /* final */ class ImagePipeline: ImageTaskDelegate { + public let configuration: Configuration + + // This is a queue on which we access the sessions. + private let queue = DispatchQueue(label: "com.github.kean.Nuke.ImagePipeline") + + // Image loading sessions. One or more tasks can be handled by the same session. + private var sessions = [AnyHashable: ImageLoadingSession]() + + private var nextTaskId: Int32 = 0 + private var nextSessionId: Int32 = 0 + + private let rateLimiter: RateLimiter + + /// Shared image pipeline. + public static var shared = ImagePipeline() + + /// The closure that gets called each time the task is completed (or cancelled). + /// Guaranteed to be called on the main thread. + public var didFinishCollectingMetrics: ((ImageTask, ImageTaskMetrics) -> Void)? + + public struct Configuration { + /// Image cache used by the pipeline. + public var imageCache: ImageCaching? + + /// Data loader used by the pipeline. + public var dataLoader: DataLoading + + /// Data loading queue. Default maximum concurrent task count is 6. + public var dataLoadingQueue = OperationQueue() + + /// Data cache used by the pipeline. + public var dataCache: DataCaching? + + /// Data caching queue. Default maximum concurrent task count is 2. + public var dataCachingQueue = OperationQueue() + + /// Default implementation uses shared `ImageDecoderRegistry` to create + /// a decoder that matches the context. + internal var imageDecoder: (ImageDecodingContext) -> ImageDecoding = { + return ImageDecoderRegistry.shared.decoder(for: $0) + } + + /// Image decoding queue. Default maximum concurrent task count is 1. + public var imageDecodingQueue = OperationQueue() + + /// This is here just for backward compatibility with `Loader`. + internal var imageProcessor: (Image, ImageRequest) -> AnyImageProcessor? = { $1.processor } + + /// Image processing queue. Default maximum concurrent task count is 2. + public var imageProcessingQueue = OperationQueue() + + /// `true` by default. If `true` the pipeline will combine the requests + /// with the same `loadKey` into a single request. The request only gets + /// cancelled when all the registered requests are. + public var isDeduplicationEnabled = true + + /// `true` by default. It `true` the pipeline will rate limits the requests + /// to prevent trashing of the underlying systems (e.g. `URLSession`). + /// The rate limiter only comes into play when the requests are started + /// and cancelled at a high rate (e.g. scrolling through a collection view). + public var isRateLimiterEnabled = true + + /// `false` by default. If `true` the pipeline will try to produce a new + /// image each time it receives a new portion of data from data loader. + /// The decoder used by the image loading session determines whether + /// to produce a partial image or not. + public var isProgressiveDecodingEnabled = false + + /// If the data task is terminated (either because of a failure or a + /// cancellation) and the image was partially loaded, the next load will + /// resume where it was left off. Supports both validators (`ETag`, + /// `Last-Modified`). The resumable downloads are enabled by default. + public var isResumableDataEnabled = true + + /// If `true` pipeline will detects GIFs and set `animatedImageData` + /// (`UIImage` property). It will also disable processing of such images, + /// and alter the way cache cost is calculated. However, this will not + /// enable actual animated image rendering. To do that take a look at + /// satellite projects (FLAnimatedImage and Gifu plugins for Nuke). + /// `false` by default (to preserve resources). + public static var isAnimatedImageDataEnabled = false + + /// Creates default configuration. + /// - parameter dataLoader: `DataLoader()` by default. + /// - parameter imageCache: `Cache.shared` by default. + public init(dataLoader: DataLoading = DataLoader(), imageCache: ImageCaching? = ImageCache.shared) { + self.dataLoader = dataLoader + self.imageCache = imageCache + + self.dataLoadingQueue.maxConcurrentOperationCount = 6 + self.dataCachingQueue.maxConcurrentOperationCount = 2 + self.imageDecodingQueue.maxConcurrentOperationCount = 1 + self.imageProcessingQueue.maxConcurrentOperationCount = 2 + } + } + + /// Initializes `ImagePipeline` instance with the given configuration. + /// - parameter configuration: `Configuration()` by default. + public init(configuration: Configuration = Configuration()) { + self.configuration = configuration + self.rateLimiter = RateLimiter(queue: queue) + } + + public convenience init(_ configure: (inout ImagePipeline.Configuration) -> Void) { + var configuration = ImagePipeline.Configuration() + configure(&configuration) + self.init(configuration: configuration) + } + + // MARK: Loading Images + + /// Loads an image with the given url. + @discardableResult + public func loadImage(with url: URL, progress: ImageTask.ProgressHandler? = nil, completion: ImageTask.Completion? = nil) -> ImageTask { + return loadImage(with: ImageRequest(url: url), progress: progress, completion: completion) + } + + /// Loads an image for the given request using image loading pipeline. + @discardableResult + public func loadImage(with request: ImageRequest, progress: ImageTask.ProgressHandler? = nil, completion: ImageTask.Completion? = nil) -> ImageTask { + let task = ImageTask(taskId: Int(OSAtomicIncrement32(&nextTaskId)), request: request) + task.delegate = self + queue.async { + // Fast memory cache lookup. We do this asynchronously because we + // expect users to check memory cache synchronously if needed. + if task.request.memoryCacheOptions.isReadAllowed, + let response = self.configuration.imageCache?.cachedResponse(for: task.request) { + task.metrics.isMemoryCacheHit = true + self._didCompleteTask(task, response: response, error: nil, completion: completion) + return + } + // Memory cache lookup failed -> start loading. + self._startLoadingImage( + for: task, + handlers: ImageLoadingSession.Handlers(progress: progress, completion: completion) + ) + } + return task + } + + private func _startLoadingImage(for task: ImageTask, handlers: ImageLoadingSession.Handlers) { + // Create a new image loading session or register with an existing one. + let session = _createSession(with: task.request) + task.session = session + + task.metrics.session = session.metrics + task.metrics.wasSubscibedToExistingSession = !session.tasks.isEmpty + + // Register handler with a session. + session.tasks[task] = handlers + session.updatePriority() + + // Already loaded and decoded the final image and started processing + // for previously registered tasks (if any). + if let image = session.decodedFinalImage { + _session(session, processImage: image, for: task) + } + } + + // MARK: ImageTaskDelegate + + func imageTaskWasCancelled(_ task: ImageTask) { + queue.async { + self._didCancelTask(task) + } + } + + func imageTask(_ task: ImageTask, didUpdatePrioity: ImageRequest.Priority) { + queue.async { + guard let session = task.session else { return } + session.updatePriority() + session.processingSessions[task]?.updatePriority() + } + } + + // MARK: ImageLoadingSession (Managing) + + private func _createSession(with request: ImageRequest) -> ImageLoadingSession { + // Check if session for the given key already exists. + // + // This part is more clever than I would like. The reason why we need a + // key even when deduplication is disabled is to have a way to retain + // a session by storing it in `sessions` dictionary. + let key: AnyHashable = configuration.isDeduplicationEnabled ? ImageRequest.LoadKey(request: request) : UUID() + if let session = sessions[key] { + return session + } + let session = ImageLoadingSession(sessionId: Int(OSAtomicIncrement32(&nextSessionId)), request: request, key: key) + sessions[key] = session + _loadImage(for: session) // Start the pipeline + return session + } + + private func _cancelSession(for task: ImageTask) { + guard let session = task.session else { return } + + session.tasks[task] = nil + + // When all registered tasks are cancelled, the session is deallocated + // and the underlying operation is cancelled automatically. + let processingSession = session.processingSessions.removeValue(forKey: task) + processingSession?.tasks.remove(task) + + // Cancel the session when there are no remaining tasks. + if session.tasks.isEmpty { + _tryToSaveResumableData(for: session) + session.cts.cancel() + session.metrics.wasCancelled = true + _didFinishSession(session) + } else { + // We're not cancelling the task session yet because there are + // still tasks registered to it, but we need to update the priority. + session.updatePriority() + processingSession?.updatePriority() + } + } + + // MARK: Pipeline (Loading Data) + + private func _loadImage(for session: ImageLoadingSession) { + // Use rate limiter to prevent trashing of the underlying systems + if configuration.isRateLimiterEnabled { + // Rate limiter is synchronized on pipeline's queue. Delayed work is + // executed asynchronously also on this same queue. + rateLimiter.execute(token: session.cts.token) { [weak self, weak session] in + guard let session = session else { return } + self?._checkDiskCache(for: session) + } + } else { // Start loading immediately. + _checkDiskCache(for: session) + } + } + + private func _checkDiskCache(for session: ImageLoadingSession) { + guard let cache = configuration.dataCache, let key = session.request.urlString else { + _loadData(for: session) // Skip disk cache lookup, load data + return + } + + session.metrics.checkDiskCacheStartDate = Date() + + let operation = BlockOperation { [weak self, weak session] in + guard let session = session else { return } + let data = cache.cachedData(for: key) + session.metrics.checkDiskCacheEndDate = Date() + self?.queue.async { + if let data = data { + self?._decodeFinalImage(for: session, data: data) + } else { + self?._loadData(for: session) + } + } + } + configuration.dataCachingQueue.enqueue(operation, for: session) + } + + private func _loadData(for session: ImageLoadingSession) { + guard !session.token.isCancelling else { return } // Preflight check + + // Wrap data request in an operation to limit maximum number of + // concurrent data tasks. + let operation = Operation(starter: { [weak self, weak session] finish in + guard let session = session else { finish(); return } + self?.queue.async { + self?._actuallyLoadData(for: session, finish: finish) + } + }) + configuration.dataLoadingQueue.enqueue(operation, for: session) + } + + // This methods gets called inside data loading operation (Operation). + private func _actuallyLoadData(for session: ImageLoadingSession, finish: @escaping () -> Void) { + session.metrics.loadDataStartDate = Date() + + var urlRequest = session.request.urlRequest + + // Read and remove resumable data from cache (we're going to insert it + // back in the cache if the request fails to complete again). + if configuration.isResumableDataEnabled, + let resumableData = ResumableData.removeResumableData(for: urlRequest) { + // Update headers to add "Range" and "If-Range" headers + resumableData.resume(request: &urlRequest) + // Save resumable data so that we could use it later (we need to + // verify that server returns "206 Partial Content" before using it. + session.resumableData = resumableData + + // Collect metrics + session.metrics.wasResumed = true + session.metrics.resumedDataCount = resumableData.data.count + } + + let task = configuration.dataLoader.loadData( + with: urlRequest, + didReceiveData: { [weak self, weak session] (data, response) in + self?.queue.async { + guard let session = session else { return } + self?._session(session, didReceiveData: data, response: response) + } + }, + completion: { [weak self, weak session] (error) in + finish() // Important! Mark Operation as finished. + self?.queue.async { + guard let session = session else { return } + self?._session(session, didFinishLoadingDataWithError: error) + } + }) + session.token.register { + task.cancel() + finish() // Make sure we always finish the operation. + } + } + + private func _session(_ session: ImageLoadingSession, didReceiveData chunk: Data, response: URLResponse) { + // Check if this is the first response. + if session.urlResponse == nil { + // See if the server confirmed that we can use the resumable data. + if let resumableData = session.resumableData { + if ResumableData.isResumedResponse(response) { + session.data = resumableData.data + session.resumedDataCount = Int64(resumableData.data.count) + session.metrics.serverConfirmedResume = true + } + session.resumableData = nil // Get rid of resumable data + } + } + + // Append data and save response + session.data.append(chunk) + session.urlResponse = response + + // Collect metrics + session.metrics.downloadedDataCount = ((session.metrics.downloadedDataCount ?? 0) + chunk.count) + + // Update tasks' progress and call progress closures if any + let (completed, total) = (Int64(session.data.count), response.expectedContentLength + session.resumedDataCount) + let tasks = session.tasks + DispatchQueue.main.async { + for (task, handlers) in tasks where !task.isCancelled { + (task.completedUnitCount, task.totalUnitCount) = (completed, total) + handlers.progress?(nil, completed, total) + task._progress?.completedUnitCount = completed + task._progress?.totalUnitCount = total + } + } + + // Check if progressive decoding is enabled (disabled by default) + if configuration.isProgressiveDecodingEnabled { + // Check if we haven't loaded an entire image yet. We give decoder + // an opportunity to decide whether to decode this chunk or not. + // In case `expectedContentLength` is undetermined (e.g. 0) we + // don't allow progressive decoding. + guard session.data.count < response.expectedContentLength else { return } + + _setNeedsDecodePartialImage(for: session) + } + } + + private func _session(_ session: ImageLoadingSession, didFinishLoadingDataWithError error: Swift.Error?) { + session.metrics.loadDataEndDate = Date() + + if let error = error { + _tryToSaveResumableData(for: session) + _session(session, didFailWithError: .dataLoadingFailed(error)) + return + } + + let data = session.data + session.data.removeAll() // We no longer need the data stored in session. + + _decodeFinalImage(for: session, data: data) + } + + // MARK: Pipeline (Decoding) + + private func _setNeedsDecodePartialImage(for session: ImageLoadingSession) { + guard session.decodingOperation == nil else { + return // Already enqueued an operation. + } + let operation = BlockOperation { [weak self, weak session] in + guard let session = session else { return } + self?._actuallyDecodePartialImage(for: session) + } + _enqueueDecodingOperation(operation, for: session) + } + + private func _actuallyDecodePartialImage(for session: ImageLoadingSession) { + // As soon as we get a chance to execute, grab the latest available + // data, create a decoder (if necessary) and decode the data. + let (data, decoder): (Data, ImageDecoding?) = queue.sync { + let data = session.data + let decoder = _decoder(for: session, data: data) + return (data, decoder) + } + + // Produce partial image + if let image = decoder?.decode(data: data, isFinal: false) { + let scanNumber: Int? = (decoder as? ImageDecoder)?.numberOfScans + queue.async { + let container = ImageContainer(image: image, isFinal: false, scanNumber: scanNumber) + for task in session.tasks.keys { + self._session(session, processImage: container, for: task) + } + } + } + } + + private func _decodeFinalImage(for session: ImageLoadingSession, data: Data) { + // Basic sanity checks, should never happen in practice. + guard !data.isEmpty, let decoder = _decoder(for: session, data: data) else { + _session(session, didFailWithError: .decodingFailed) + return + } + + let metrics = session.metrics + let operation = BlockOperation { [weak self, weak session] in + guard let session = session else { return } + metrics.decodeStartDate = Date() + let image = autoreleasepool { + decoder.decode(data: data, isFinal: true) // Produce final image + } + metrics.decodeEndDate = Date() + self?.queue.async { + let container = image.map { + ImageContainer(image: $0, isFinal: true, scanNumber: nil) + } + self?._session(session, didDecodeFinalImage: container, data: data) + } + } + _enqueueDecodingOperation(operation, for: session) + } + + private func _enqueueDecodingOperation(_ operation: Foundation.Operation, for session: ImageLoadingSession) { + configuration.imageDecodingQueue.enqueue(operation, for: session) + session.decodingOperation?.cancel() + session.decodingOperation = operation + } + + // Lazily creates a decoder if necessary. + private func _decoder(for session: ImageLoadingSession, data: Data) -> ImageDecoding? { + guard !session.isDecodingDisabled else { + return nil + } + + // Return the existing processor in case it has already been created. + if let decoder = session.decoder { + return decoder + } + + // Basic sanity checks. + guard !data.isEmpty else { + return nil + } + + let context = ImageDecodingContext(request: session.request, urlResponse: session.urlResponse, data: data) + let decoder = configuration.imageDecoder(context) + session.decoder = decoder + return decoder + } + + private func _tryToSaveResumableData(for session: ImageLoadingSession) { + // Try to save resumable data in case the task was cancelled + // (`URLError.cancelled`) or failed to complete with other error. + if configuration.isResumableDataEnabled, + let response = session.urlResponse, !session.data.isEmpty, + let resumableData = ResumableData(response: response, data: session.data) { + ResumableData.storeResumableData(resumableData, for: session.request.urlRequest) + } + } + + private func _session(_ session: ImageLoadingSession, didDecodeFinalImage image: ImageContainer?, data: Data) { + session.decoder = nil // Decoding session completed, no longer need decoder. + session.decodedFinalImage = image + + guard let image = image else { + _session(session, didFailWithError: .decodingFailed) + return + } + + // Store data in data cache (in case it's enabled)) + if !data.isEmpty, let dataCache = configuration.dataCache, let key = session.request.urlString { + dataCache.storeData(data, for: key) + } + + for task in session.tasks.keys { + _session(session, processImage: image, for: task) + } + } + + // MARK: Pipeline (Processing) + + /// Processes the input image for each of the given tasks. The image is processed + /// only once for the equivalent processors. + /// - parameter completion: Will get called synchronously if processing is not + /// required. If it is will get called on `self.queue` when processing is finished. + private func _session(_ session: ImageLoadingSession, processImage image: ImageContainer, for task: ImageTask) { + let isFinal = image.isFinal + guard let processor = _processor(for: image.image, request: task.request) else { + _session(session, didProcessImage: image.image, isFinal: isFinal, metrics: TaskMetrics(), for: task) + return // No processing needed. + } + + if !image.isFinal && session.processingSessions[task] != nil { + return // Back pressure - we'are already busy processing another partial image + } + + // Find existing session or create a new one. + let processingSession = _processingSession(for: image, processor: processor, session: session, task: task) + + // Register task with a processing session. + processingSession.tasks.insert(task) + session.processingSessions[task] = processingSession + processingSession.updatePriority() + } + + private func _processingSession(for image: ImageContainer, processor: AnyImageProcessor, session: ImageLoadingSession, task: ImageTask) -> ImageProcessingSession { + func findExistingSession() -> ImageProcessingSession? { + return session.processingSessions.values.first { + $0.processor == processor && $0.image.image === image.image + } + } + + if let processingSession = findExistingSession() { + return processingSession + } + + let processingSession = ImageProcessingSession(processor: processor, image: image) + + let isFinal = image.isFinal + let operation = BlockOperation { [weak self, weak session, weak processingSession] in + var metrics = TaskMetrics.started() + let output: Image? = autoreleasepool { + processor.process(image: image, request: task.request) + } + metrics.end() + + self?.queue.async { + guard let session = session else { return } + for task in (processingSession?.tasks ?? []) { + if session.processingSessions[task] === processingSession { + session.processingSessions[task] = nil + } + self?._session(session, didProcessImage: output, isFinal: isFinal, metrics: metrics, for: task) + } + } + } + + operation.queuePriority = task.request.priority.queuePriority + session.priority.observe { [weak operation] in + operation?.queuePriority = $0.queuePriority + } + configuration.imageProcessingQueue.addOperation(operation) + processingSession.operation = operation + + return processingSession + } + + private func _processor(for image: Image, request: ImageRequest) -> AnyImageProcessor? { + if Configuration.isAnimatedImageDataEnabled && image.animatedImageData != nil { + return nil // Don't process animated images. + } + return configuration.imageProcessor(image, request) + } + + private func _session(_ session: ImageLoadingSession, didProcessImage image: Image?, isFinal: Bool, metrics: TaskMetrics, for task: ImageTask) { + if isFinal { + task.metrics.processStartDate = metrics.startDate + task.metrics.processEndDate = metrics.endDate + let error: Error? = (image == nil ? .processingFailed : nil) + _session(session, didCompleteTask: task, image: image, error: error) + } else { + guard let image = image else { return } + _session(session, didProducePartialImage: image, for: task) + } + } + + // MARK: ImageLoadingSession (Callbacks) + + private func _session(_ session: ImageLoadingSession, didProducePartialImage image: Image, for task: ImageTask) { + // Check if we haven't completed the session yet by producing a final image + // or cancelling the task. + guard sessions[session.key] === session else { return } + + let response = ImageResponse(image: image, urlResponse: session.urlResponse) + if let handler = session.tasks[task], let progress = handler.progress { + DispatchQueue.main.async { + guard !task.isCancelled else { return } + progress(response, task.completedUnitCount, task.totalUnitCount) + } + } + } + + private func _session(_ session: ImageLoadingSession, didCompleteTask task: ImageTask, image: Image?, error: Error?) { + let response = image.map { + ImageResponse(image: $0, urlResponse: session.urlResponse) + } + // Store response in memory cache if allowed. + if let response = response, task.request.memoryCacheOptions.isWriteAllowed { + configuration.imageCache?.storeResponse(response, for: task.request) + } + if let handlers = session.tasks.removeValue(forKey: task) { + _didCompleteTask(task, response: response, error: error, completion: handlers.completion) + } + if session.tasks.isEmpty { + _didFinishSession(session) + } + } + + private func _session(_ session: ImageLoadingSession, didFailWithError error: Error) { + for task in session.tasks.keys { + _session(session, didCompleteTask: task, image: nil, error: error) + } + } + + private func _didFinishSession(_ session: ImageLoadingSession) { + // Check if session is still registered. + guard sessions[session.key] === session else { return } + session.metrics.endDate = Date() + sessions[session.key] = nil + } + + // Cancel the session in case all handlers were removed. + private func _didCancelTask(_ task: ImageTask) { + task.metrics.wasCancelled = true + task.metrics.endDate = Date() + + _cancelSession(for: task) + + guard let didCollectMetrics = didFinishCollectingMetrics else { return } + DispatchQueue.main.async { + didCollectMetrics(task, task.metrics) + } + } + + private func _didCompleteTask(_ task: ImageTask, response: ImageResponse?, error: Error?, completion: ImageTask.Completion?) { + task.metrics.endDate = Date() + DispatchQueue.main.async { + guard !task.isCancelled else { return } + completion?(response, error) + self.didFinishCollectingMetrics?(task, task.metrics) + } + } + + // MARK: Errors + + /// Represents all possible image pipeline errors. + public enum Error: Swift.Error, CustomDebugStringConvertible { + /// Data loader failed to load image data with a wrapped error. + case dataLoadingFailed(Swift.Error) + /// Decoder failed to produce a final image. + case decodingFailed + /// Processor failed to produce a final image. + case processingFailed + + public var debugDescription: String { + switch self { + case let .dataLoadingFailed(error): return "Failed to load image data: \(error)" + case .decodingFailed: return "Failed to create an image from the image data" + case .processingFailed: return "Failed to process the image" + } + } + } +} + +// MARK: - ImageLoadingSession + +/// A image loading session. During a lifetime of a session handlers can +/// subscribe to and unsubscribe from it. +private final class ImageLoadingSession { + let sessionId: Int + + /// The original request with which the session was created. + let request: ImageRequest + let key: AnyHashable // loading key + let cts = CancellationTokenSource() + var token: CancellationToken { return cts.token } + + // Registered image tasks. + var tasks = [ImageTask: Handlers]() + + struct Handlers { + let progress: ImageTask.ProgressHandler? + let completion: ImageTask.Completion? + } + + // Data loading session. + var urlResponse: URLResponse? + var resumableData: ResumableData? + var resumedDataCount: Int64 = 0 + lazy var data = Data() + + // Decoding session. + var decoder: ImageDecoding? + var decodedFinalImage: ImageContainer? // Decoding result + weak var decodingOperation: Foundation.Operation? + + // Processing sessions. + var processingSessions = [ImageTask: ImageProcessingSession]() + + // Metrics that we collect during the lifetime of a session. + let metrics: ImageTaskMetrics.SessionMetrics + + let priority: Property + + deinit { + decodingOperation?.cancel() + } + + init(sessionId: Int, request: ImageRequest, key: AnyHashable) { + self.sessionId = sessionId + self.request = request + self.key = key + self.metrics = ImageTaskMetrics.SessionMetrics(sessionId: sessionId) + self.priority = Property(value: request.priority) + } + + func updatePriority() { + priority.update(with: tasks.keys) + } + + var isDecodingDisabled: Bool { + return !tasks.keys.contains { + !$0.request.isDecodingDisabled + } + } +} + +private final class ImageProcessingSession { + let processor: AnyImageProcessor + let image: ImageContainer + var tasks = Set() + weak var operation: Foundation.Operation? + + let priority = Property(value: .normal) + + deinit { + operation?.cancel() + } + + init(processor: AnyImageProcessor, image: ImageContainer) { + self.processor = processor; self.image = image + } + + // Update priority for processing operations (those are per image task, + // not per image session). + func updatePriority() { + priority.update(with: tasks) + } +} + +struct ImageContainer { + let image: Image + let isFinal: Bool + let scanNumber: Int? +} + +// MARK: - Extensions + +private extension Property where T == ImageRequest.Priority { + func update(with tasks: Tasks) where Tasks.Element == ImageTask { + if let newPriority = tasks.map({ $0.request.priority }).max(), self.value != newPriority { + self.value = newPriority + } + } +} + +private extension Foundation.OperationQueue { + func enqueue(_ operation: Foundation.Operation, for session: ImageLoadingSession) { + operation.queuePriority = session.priority.value.queuePriority + session.priority.observe { [weak operation] in + operation?.queuePriority = $0.queuePriority + } + session.token.register { [weak operation] in + operation?.cancel() + } + addOperation(operation) + } +} diff --git a/Pods/Nuke/Sources/ImagePreheater.swift b/Pods/Nuke/Sources/ImagePreheater.swift new file mode 100644 index 0000000000..fd31db6222 --- /dev/null +++ b/Pods/Nuke/Sources/ImagePreheater.swift @@ -0,0 +1,182 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation + +/// Prefetches and caches image in order to eliminate delays when you request +/// individual images later. +/// +/// To start preheating call `startPreheating(with:)` method. When you +/// need an individual image just start loading an image using `Loading` object. +/// When preheating is no longer necessary call `stopPreheating(with:)` method. +/// +/// All `Preheater` methods are thread-safe. +public final class ImagePreheater { + private let pipeline: ImagePipeline + private let queue = DispatchQueue(label: "com.github.kean.Nuke.Preheater") + private let preheatQueue = OperationQueue() + private var tasks = [PreheatKey: Task]() + private let destination: Destination + + /// Prefetching destination. + public enum Destination { + /// Prefetches the image and stores it both in memory and disk caches + /// (in case they are enabled, naturally, there is no reason to prefetch + /// unless they are). + case memoryCache + + /// Prefetches image data and stores in disk cache. Will no decode + /// the image data and will therefore useless less CPU. + case diskCache + } + + /// Initializes the `Preheater` instance. + /// - parameter manager: `Loader.shared` by default. + /// - parameter `maxConcurrentRequestCount`: 2 by default. + /// - parameter destination: `.memoryCache` by default. + public init(pipeline: ImagePipeline = ImagePipeline.shared, destination: Destination = .memoryCache, maxConcurrentRequestCount: Int = 2) { + self.pipeline = pipeline + self.destination = destination + self.preheatQueue.maxConcurrentOperationCount = maxConcurrentRequestCount + } + + /// Starte preheating images for the given urls. + /// - note: See `func startPreheating(with requests: [ImageRequest])` for more info + public func startPreheating(with urls: [URL]) { + startPreheating(with: _requests(for: urls)) + } + + /// Starts preheating images for the given requests. + /// + /// When you call this method, `Preheater` starts to load and cache images + /// for the given requests. At any time afterward, you can create tasks + /// for individual images with equivalent requests. + public func startPreheating(with requests: [ImageRequest]) { + queue.async { + for request in requests { + self._startPreheating(with: self._updatedRequest(request)) + } + } + } + + private func _startPreheating(with request: ImageRequest) { + let key = PreheatKey(request: request) + + // Check if we we've already started preheating. + guard tasks[key] == nil else { return } + + // Check if the image is already in memory cache. + guard pipeline.configuration.imageCache?.cachedResponse(for: request) == nil else { + return // already in memory cache + } + + let task = Task(request: request, key: key) + let token = task.cts.token + + let operation = Operation(starter: { [weak self] finish in + let task = self?.pipeline.loadImage(with: request) { [weak self] _, _ in + self?._remove(task) + finish() + } + token.register { + task?.cancel() + finish() + } + }) + preheatQueue.addOperation(operation) + token.register { [weak operation] in operation?.cancel() } + + tasks[key] = task + } + + private func _remove(_ task: Task) { + queue.async { + guard self.tasks[task.key] === task else { return } + self.tasks[task.key] = nil + } + } + + /// Stops preheating images for the given urls. + public func stopPreheating(with urls: [URL]) { + stopPreheating(with: _requests(for: urls)) + } + + /// Stops preheating images for the given requests and cancels outstanding + /// requests. + /// + /// - parameter destination: `.memoryCache` by default. + public func stopPreheating(with requests: [ImageRequest]) { + queue.async { + for request in requests { + self._stopPreheating(with: self._updatedRequest(request)) + } + } + } + + private func _stopPreheating(with request: ImageRequest) { + if let task = tasks[PreheatKey(request: request)] { + tasks[task.key] = nil + task.cts.cancel() + } + } + + /// Stops all preheating tasks. + public func stopPreheating() { + queue.async { + self.tasks.forEach { $0.1.cts.cancel() } + self.tasks.removeAll() + } + } + + private func _requests(for urls: [URL]) -> [ImageRequest] { + return urls.map { + var request = ImageRequest(url: $0) + request.priority = .low + return request + } + } + + private func _updatedRequest(_ request: ImageRequest) -> ImageRequest { + guard destination == .diskCache else { + return request // Avoid creating a new copy + } + + var request = request + // What we do under the hood is we disable decoding for the requests + // that are meant to not be stored in memory cache. + request.isDecodingDisabled = (destination == .diskCache) + return request + } + + private final class Task { + let key: PreheatKey + let request: ImageRequest + let cts = CancellationTokenSource() + + init(request: ImageRequest, key: PreheatKey) { + self.request = request + self.key = key + } + } + + private struct PreheatKey: Hashable { + let cacheKey: ImageRequest.CacheKey + let loadKey: ImageRequest.LoadKey + + init(request: ImageRequest) { + self.cacheKey = ImageRequest.CacheKey(request: request) + self.loadKey = ImageRequest.LoadKey(request: request) + } + + #if !swift(>=4.1) + var hashValue: Int { + return cacheKey.hashValue + } + + static func == (lhs: PreheatKey, rhs: PreheatKey) -> Bool { + return lhs.cacheKey == rhs.cacheKey && lhs.loadKey == rhs.loadKey + } + #endif + } +} diff --git a/Pods/Nuke/Sources/ImageProcessing.swift b/Pods/Nuke/Sources/ImageProcessing.swift new file mode 100644 index 0000000000..b93a01958e --- /dev/null +++ b/Pods/Nuke/Sources/ImageProcessing.swift @@ -0,0 +1,193 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation + +/// Performs image processing. +public protocol ImageProcessing: Equatable { + /// Returns processed image. + func process(image: Image, context: ImageProcessingContext) -> Image? +} + +/// Image processing context used when selecting which processor to use. +public struct ImageProcessingContext { + public let request: ImageRequest + public let isFinal: Bool + public let scanNumber: Int? // need a more general purpose way to implement this +} + +/// Composes multiple processors. +internal struct ImageProcessorComposition: ImageProcessing { + private let processors: [AnyImageProcessor] + + /// Composes multiple processors. + public init(_ processors: [AnyImageProcessor]) { + self.processors = processors + } + + /// Processes the given image by applying each processor in an order in + /// which they were added. If one of the processors fails to produce + /// an image the processing stops and `nil` is returned. + func process(image: Image, context: ImageProcessingContext) -> Image? { + return processors.reduce(image) { image, processor in + return autoreleasepool { + image.flatMap { processor.process(image: $0, context: context) } + } + } + } + + /// Returns true if the underlying processors are pairwise-equivalent. + public static func == (lhs: ImageProcessorComposition, rhs: ImageProcessorComposition) -> Bool { + return lhs.processors == rhs.processors + } +} + +/// Type-erased image processor. +public struct AnyImageProcessor: ImageProcessing { + private let _process: (Image, ImageProcessingContext) -> Image? + private let _processor: Any + private let _equals: (AnyImageProcessor) -> Bool + + public init(_ processor: P) { + self._process = { processor.process(image: $0, context: $1) } + self._processor = processor + self._equals = { ($0._processor as? P) == processor } + } + + public func process(image: Image, context: ImageProcessingContext) -> Image? { + return self._process(image, context) + } + + public static func == (lhs: AnyImageProcessor, rhs: AnyImageProcessor) -> Bool { + return lhs._equals(rhs) + } +} + +internal struct AnonymousImageProcessor: ImageProcessing { + private let _key: Key + private let _closure: (Image) -> Image? + + init(_ key: Key, _ closure: @escaping (Image) -> Image?) { + self._key = key; self._closure = closure + } + + func process(image: Image, context: ImageProcessingContext) -> Image? { + return self._closure(image) + } + + static func == (lhs: AnonymousImageProcessor, rhs: AnonymousImageProcessor) -> Bool { + return lhs._key == rhs._key + } +} + +extension ImageProcessing { + func process(image: ImageContainer, request: ImageRequest) -> Image? { + let context = ImageProcessingContext(request: request, isFinal: image.isFinal, scanNumber: image.scanNumber) + return process(image: image.image, context: context) + } +} + +#if !os(macOS) +import UIKit + +/// Decompresses and (optionally) scales down input images. Maintains +/// original aspect ratio. +/// +/// Decompressing compressed image formats (such as JPEG) can significantly +/// improve drawing performance as it allows a bitmap representation to be +/// created in a background rather than on the main thread. +public struct ImageDecompressor: ImageProcessing { + + /// An option for how to resize the image. + public enum ContentMode { + /// Scales the image so that it completely fills the target size. + /// Doesn't clip images. + case aspectFill + + /// Scales the image so that it fits the target size. + case aspectFit + } + + /// Size to pass to disable resizing. + public static let MaximumSize = CGSize( + width: CGFloat.greatestFiniteMagnitude, + height: CGFloat.greatestFiniteMagnitude + ) + + private let targetSize: CGSize + private let contentMode: ContentMode + private let upscale: Bool + + /// Initializes `Decompressor` with the given parameters. + /// - parameter targetSize: Size in pixels. `MaximumSize` by default. + /// - parameter contentMode: An option for how to resize the image + /// to the target size. `.aspectFill` by default. + public init(targetSize: CGSize = MaximumSize, contentMode: ContentMode = .aspectFill, upscale: Bool = false) { + self.targetSize = targetSize + self.contentMode = contentMode + self.upscale = upscale + } + + /// Decompresses and scales the image. + public func process(image: Image, context: ImageProcessingContext) -> Image? { + return decompress(image, targetSize: targetSize, contentMode: contentMode, upscale: upscale) + } + + /// Returns true if both have the same `targetSize` and `contentMode`. + public static func == (lhs: ImageDecompressor, rhs: ImageDecompressor) -> Bool { + return lhs.targetSize == rhs.targetSize && lhs.contentMode == rhs.contentMode + } + + #if !os(watchOS) + /// Returns target size in pixels for the given view. Takes main screen + /// scale into the account. + public static func targetSize(for view: UIView) -> CGSize { // in pixels + let scale = UIScreen.main.scale + let size = view.bounds.size + return CGSize(width: size.width * scale, height: size.height * scale) + } + #endif +} + +internal func decompress(_ image: UIImage, targetSize: CGSize, contentMode: ImageDecompressor.ContentMode, upscale: Bool) -> UIImage { + guard let cgImage = image.cgImage else { return image } + let bitmapSize = CGSize(width: cgImage.width, height: cgImage.height) + let scaleHor = targetSize.width / bitmapSize.width + let scaleVert = targetSize.height / bitmapSize.height + let scale = contentMode == .aspectFill ? max(scaleHor, scaleVert) : min(scaleHor, scaleVert) + return decompress(image, scale: CGFloat(upscale ? scale : min(scale, 1))) +} + +internal func decompress(_ image: UIImage, scale: CGFloat) -> UIImage { + guard let cgImage = image.cgImage else { return image } + + let size = CGSize( + width: round(scale * CGFloat(cgImage.width)), + height: round(scale * CGFloat(cgImage.height)) + ) + + // For more info see: + // - Quartz 2D Programming Guide + // - https://github.com/kean/Nuke/issues/35 + // - https://github.com/kean/Nuke/issues/57 + let alphaInfo: CGImageAlphaInfo = isOpaque(cgImage) ? .noneSkipLast : .premultipliedLast + + guard let ctx = CGContext( + data: nil, + width: Int(size.width), height: Int(size.height), + bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: alphaInfo.rawValue) else { + return image + } + ctx.draw(cgImage, in: CGRect(origin: CGPoint.zero, size: size)) + guard let decompressed = ctx.makeImage() else { return image } + return UIImage(cgImage: decompressed, scale: image.scale, orientation: image.imageOrientation) +} + +private func isOpaque(_ image: CGImage) -> Bool { + let alpha = image.alphaInfo + return alpha == .none || alpha == .noneSkipFirst || alpha == .noneSkipLast +} +#endif diff --git a/Pods/Nuke/Sources/ImageRequest.swift b/Pods/Nuke/Sources/ImageRequest.swift new file mode 100644 index 0000000000..90826df074 --- /dev/null +++ b/Pods/Nuke/Sources/ImageRequest.swift @@ -0,0 +1,333 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation + +#if !os(macOS) +import UIKit +#endif + +/// Represents an image request. +public struct ImageRequest { + + // MARK: Parameters of the Request + + internal var urlString: String? { + return _ref._urlString + } + + /// The `URLRequest` used for loading an image. + public var urlRequest: URLRequest { + get { return _ref.resource.urlRequest } + set { + _mutate { + $0.resource = Resource.urlRequest(newValue) + $0._urlString = newValue.url?.absoluteString + } + } + } + + /// Processor to be applied to the image. `Decompressor` by default. + /// + /// Decompressing compressed image formats (such as JPEG) can significantly + /// improve drawing performance as it allows a bitmap representation to be + /// created in a background rather than on the main thread. + public var processor: AnyImageProcessor? { + get { + // Default processor on macOS is nil, on other platforms is Decompressor + #if !os(macOS) + return _ref._isDefaultProcessorUsed ? ImageRequest.decompressor : _ref._processor + #else + return _ref._isDefaultProcessorUsed ? nil : _ref._processor + #endif + } + set { + _mutate { + $0._isDefaultProcessorUsed = false + $0._processor = newValue + } + } + } + + /// The policy to use when reading or writing images to the memory cache. + public struct MemoryCacheOptions { + /// `true` by default. + public var isReadAllowed = true + + /// `true` by default. + public var isWriteAllowed = true + + public init() {} + } + + /// `MemoryCacheOptions()` (read allowed, write allowed) by default. + public var memoryCacheOptions: MemoryCacheOptions { + get { return _ref.memoryCacheOptions } + set { _mutate { $0.memoryCacheOptions = newValue } } + } + + /// The execution priority of the request. + public enum Priority: Int, Comparable { + case veryLow = 0, low, normal, high, veryHigh + + internal var queuePriority: Operation.QueuePriority { + switch self { + case .veryLow: return .veryLow + case .low: return .low + case .normal: return .normal + case .high: return .high + case .veryHigh: return .veryHigh + } + } + + public static func < (lhs: Priority, rhs: Priority) -> Bool { + return lhs.rawValue < rhs.rawValue + } + } + + /// The relative priority of the operation. This value is used to influence + /// the order in which requests are executed. `.normal` by default. + public var priority: Priority { + get { return _ref.priority } + set { _mutate { $0.priority = newValue }} + } + + /// Returns a key that compares requests with regards to caching images. + /// + /// The default key considers two requests equivalent it they have the same + /// `URLRequests` and the same processors. `URLRequests` are compared + /// just by their `URLs`. + public var cacheKey: AnyHashable? { + get { return _ref.cacheKey } + set { _mutate { $0.cacheKey = newValue } } + } + + /// Returns a key that compares requests with regards to loading images. + /// + /// The default key considers two requests equivalent it they have the same + /// `URLRequests` and the same processors. `URLRequests` are compared by + /// their `URL`, `cachePolicy`, and `allowsCellularAccess` properties. + public var loadKey: AnyHashable? { + get { return _ref.loadKey } + set { _mutate { $0.loadKey = newValue } } + } + + /// If decoding is disabled, when the image data is loaded, the pipeline is + /// not going to create an image from it and will produce the `.decodingFailed` + /// error instead. `false` by default. + var isDecodingDisabled: Bool { + // This only used by `ImagePreheater` right now + get { return _ref.isDecodingDisabled } + set { _mutate { $0.isDecodingDisabled = newValue } } + } + + /// Custom info passed alongside the request. + public var userInfo: Any? { + get { return _ref.userInfo } + set { _mutate { $0.userInfo = newValue }} + } + + // MARK: Initializers + + /// Initializes a request with the given URL. + public init(url: URL) { + _ref = Container(resource: Resource.url(url)) + _ref._urlString = url.absoluteString + // creating `.absoluteString` takes 50% of time of Request creation, + // it's still faster than using URLs as cache keys + } + + /// Initializes a request with the given request. + public init(urlRequest: URLRequest) { + _ref = Container(resource: Resource.urlRequest(urlRequest)) + _ref._urlString = urlRequest.url?.absoluteString + } + + #if !os(macOS) + + /// Initializes a request with the given URL. + /// - parameter processor: Custom image processer. + public init(url: URL, processor: Processor) { + self.init(url: url) + self.processor = AnyImageProcessor(processor) + } + + /// Initializes a request with the given request. + /// - parameter processor: Custom image processer. + public init(urlRequest: URLRequest, processor: Processor) { + self.init(urlRequest: urlRequest) + self.processor = AnyImageProcessor(processor) + } + + /// Initializes a request with the given URL. + /// - parameter targetSize: Size in pixels. + /// - parameter contentMode: An option for how to resize the image + /// to the target size. + public init(url: URL, targetSize: CGSize, contentMode: ImageDecompressor.ContentMode, upscale: Bool = false) { + self.init(url: url, processor: ImageDecompressor( + targetSize: targetSize, + contentMode: contentMode, + upscale: upscale + )) + } + + /// Initializes a request with the given request. + /// - parameter targetSize: Size in pixels. + /// - parameter contentMode: An option for how to resize the image + /// to the target size. + public init(urlRequest: URLRequest, targetSize: CGSize, contentMode: ImageDecompressor.ContentMode, upscale: Bool = false) { + self.init(urlRequest: urlRequest, processor: ImageDecompressor( + targetSize: targetSize, + contentMode: contentMode, + upscale: upscale + )) + } + + fileprivate static let decompressor = AnyImageProcessor(ImageDecompressor()) + + #endif + + // CoW: + + private var _ref: Container + + private mutating func _mutate(_ closure: (Container) -> Void) { + if !isKnownUniquelyReferenced(&_ref) { + _ref = Container(container: _ref) + } + closure(_ref) + } + + /// Just like many Swift built-in types, `ImageRequest` uses CoW approach to + /// avoid memberwise retain/releases when `ImageRequest` is passed around. + private class Container { + var resource: Resource + var _urlString: String? // memoized absoluteString + // true unless user set a custom one, this allows us not to store the + // default processor anywhere in the `Container` & skip equality tests + // when the default processor is used + var _isDefaultProcessorUsed: Bool = true + var _processor: AnyImageProcessor? + var memoryCacheOptions = MemoryCacheOptions() + var priority: ImageRequest.Priority = .normal + var cacheKey: AnyHashable? + var loadKey: AnyHashable? + var isDecodingDisabled: Bool = false + var userInfo: Any? + + /// Creates a resource with a default processor. + init(resource: Resource) { + self.resource = resource + } + + /// Creates a copy. + init(container ref: Container) { + self.resource = ref.resource + self._urlString = ref._urlString + self._isDefaultProcessorUsed = ref._isDefaultProcessorUsed + self._processor = ref._processor + self.memoryCacheOptions = ref.memoryCacheOptions + self.priority = ref.priority + self.cacheKey = ref.cacheKey + self.loadKey = ref.loadKey + self.isDecodingDisabled = ref.isDecodingDisabled + self.userInfo = ref.userInfo + } + } + + /// Resource representation (either URL or URLRequest). + private enum Resource { + case url(URL) + case urlRequest(URLRequest) + + var urlRequest: URLRequest { + switch self { + case let .url(url): return URLRequest(url: url) // create lazily + case let .urlRequest(urlRequest): return urlRequest + } + } + } +} + +public extension ImageRequest { + /// Appends a processor to the request. You can append arbitrary number of + /// processors to the request. + public mutating func process(with processor: P) { + guard let existing = self.processor else { + self.processor = AnyImageProcessor(processor) + return + } + // Chain new processor and the existing one. + self.processor = AnyImageProcessor(ImageProcessorComposition([existing, AnyImageProcessor(processor)])) + } + + /// Appends a processor to the request. You can append arbitrary number of + /// processors to the request. + public func processed(with processor: P) -> ImageRequest { + var request = self + request.process(with: processor) + return request + } + + /// Appends a processor to the request. You can append arbitrary number of + /// processors to the request. + public mutating func process(key: Key, _ closure: @escaping (Image) -> Image?) { + process(with: AnonymousImageProcessor(key, closure)) + } + + /// Appends a processor to the request. You can append arbitrary number of + /// processors to the request. + public func processed(key: Key, _ closure: @escaping (Image) -> Image?) -> ImageRequest { + return processed(with: AnonymousImageProcessor(key, closure)) + } +} + +internal extension ImageRequest { + struct CacheKey: Hashable { + let request: ImageRequest + + var hashValue: Int { + if let customKey = request._ref.cacheKey { + return customKey.hashValue + } + return request._ref._urlString?.hashValue ?? 0 + } + + static func == (lhs: CacheKey, rhs: CacheKey) -> Bool { + let lhs = lhs.request, rhs = rhs.request + if let lhsCustomKey = lhs._ref.cacheKey, let rhsCustomKey = rhs._ref.cacheKey { + return lhsCustomKey == rhsCustomKey + } + guard lhs._ref._urlString == rhs._ref._urlString else { + return false + } + return (lhs._ref._isDefaultProcessorUsed && rhs._ref._isDefaultProcessorUsed) + || (lhs.processor == rhs.processor) + } + } + + struct LoadKey: Hashable { + let request: ImageRequest + + var hashValue: Int { + if let customKey = request._ref.loadKey { + return customKey.hashValue + } + return request._ref._urlString?.hashValue ?? 0 + } + + static func == (lhs: LoadKey, rhs: LoadKey) -> Bool { + func isEqual(_ lhs: URLRequest, _ rhs: URLRequest) -> Bool { + return lhs.cachePolicy == rhs.cachePolicy + && lhs.allowsCellularAccess == rhs.allowsCellularAccess + } + let lhs = lhs.request, rhs = rhs.request + if let lhsCustomKey = lhs._ref.loadKey, let rhsCustomKey = rhs._ref.loadKey { + return lhsCustomKey == rhsCustomKey + } + return lhs._ref._urlString == rhs._ref._urlString + && isEqual(lhs.urlRequest, rhs.urlRequest) + } + } +} diff --git a/Pods/Nuke/Sources/ImageTaskMetrics.swift b/Pods/Nuke/Sources/ImageTaskMetrics.swift new file mode 100644 index 0000000000..68ef8b7acc --- /dev/null +++ b/Pods/Nuke/Sources/ImageTaskMetrics.swift @@ -0,0 +1,115 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation + +public struct ImageTaskMetrics: CustomDebugStringConvertible { + public let taskId: Int + public internal(set) var wasCancelled: Bool = false + public internal(set) var session: SessionMetrics? + + public let startDate: Date + public internal(set) var processStartDate: Date? + public internal(set) var processEndDate: Date? + public internal(set) var endDate: Date? // failed or completed + public var totalDuration: TimeInterval? { + guard let endDate = endDate else { return nil } + return endDate.timeIntervalSince(startDate) + } + + /// Returns `true` is the task wasn't the one that initiated image loading. + public internal(set) var wasSubscibedToExistingSession: Bool = false + public internal(set) var isMemoryCacheHit: Bool = false + + init(taskId: Int, startDate: Date) { + self.taskId = taskId; self.startDate = startDate + } + + public var debugDescription: String { + var printer = Printer() + printer.section(title: "Task Information") { + $0.value("Task ID", taskId) + $0.timeline("Duration", startDate, endDate, isReversed: false) + $0.timeline("Process", processStartDate, processEndDate) + $0.value("Was Cancelled", wasCancelled) + $0.value("Is Memory Cache Hit", isMemoryCacheHit) + $0.value("Was Subscribed To Existing Image Loading Session", wasSubscibedToExistingSession) + } + printer.section(title: "Image Loading Session") { + $0.string(session.map({ $0.debugDescription }) ?? "nil") + } + return printer.output() + } + + // Download session metrics. One more more tasks can share the same + // session metrics. + public final class SessionMetrics: CustomDebugStringConvertible { + /// - important: Data loading might start prior to `timeResumed` if the task gets + /// coalesced with another task. + public let sessionId: Int + public internal(set) var wasCancelled: Bool = false + + // MARK: - Timeline + + public let startDate = Date() + + public internal(set) var checkDiskCacheStartDate: Date? + public internal(set) var checkDiskCacheEndDate: Date? + + public internal(set) var loadDataStartDate: Date? + public internal(set) var loadDataEndDate: Date? + + public internal(set) var decodeStartDate: Date? + public internal(set) var decodeEndDate: Date? + + @available(*, deprecated, message: "Please use the same property on `ImageTaskMetrics` instead.") + public internal(set) var processStartDate: Date? + + @available(*, deprecated, message: "Please use the same property on `ImageTaskMetrics` instead.") + public internal(set) var processEndDate: Date? + + public internal(set) var endDate: Date? // failed or completed + + public var totalDuration: TimeInterval? { + guard let endDate = endDate else { return nil } + return endDate.timeIntervalSince(startDate) + } + + // MARK: - Resumable Data + + public internal(set) var wasResumed: Bool? + public internal(set) var resumedDataCount: Int? + public internal(set) var serverConfirmedResume: Bool? + + public internal(set) var downloadedDataCount: Int? + public var totalDownloadedDataCount: Int? { + guard let downloaded = self.downloadedDataCount else { return nil } + return downloaded + (resumedDataCount ?? 0) + } + + init(sessionId: Int) { self.sessionId = sessionId } + + public var debugDescription: String { + var printer = Printer() + printer.section(title: "Session Information") { + $0.value("Session ID", sessionId) + $0.value("Total Duration", Printer.duration(totalDuration)) + $0.value("Was Cancelled", wasCancelled) + } + printer.section(title: "Timeline") { + $0.timeline("Total", startDate, endDate) + $0.line(String(repeating: "-", count: 36)) + $0.timeline("Check Disk Cache", checkDiskCacheStartDate, checkDiskCacheEndDate) + $0.timeline("Load Data", loadDataStartDate, loadDataEndDate) + $0.timeline("Decode", decodeStartDate, decodeEndDate) + } + printer.section(title: "Resumable Data") { + $0.value("Was Resumed", wasResumed) + $0.value("Resumable Data Count", resumedDataCount) + $0.value("Server Confirmed Resume", serverConfirmedResume) + } + return printer.output() + } + } +} diff --git a/Pods/Nuke/Sources/ImageView.swift b/Pods/Nuke/Sources/ImageView.swift new file mode 100644 index 0000000000..127401e878 --- /dev/null +++ b/Pods/Nuke/Sources/ImageView.swift @@ -0,0 +1,517 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation + +#if !os(macOS) +import UIKit.UIImage +/// Alias for `UIImage`. +public typealias Image = UIImage +#else +import AppKit.NSImage +/// Alias for `NSImage`. +public typealias Image = NSImage +#endif + +#if !os(watchOS) + +/// Displays images. Adopt this protocol in views to make them compatible with +/// Nuke APIs. +/// +/// The protocol is defined as `@objc` to enable users to override its methods +/// in extensions (e.g. you can override `display(image:)` in `UIImageView` subclass). +@objc public protocol ImageDisplaying { + @objc func display(image: Image?) +} + +#if !os(macOS) +import UIKit +/// A `UIView` that implements `ImageDisplaying` protocol. +public typealias ImageDisplayingView = UIView & ImageDisplaying + +extension UIImageView: ImageDisplaying { + /// Displays an image. + open func display(image: Image?) { + self.image = image + } +} +#else +import Cocoa +/// An `NSView` that implements `ImageDisplaying` protocol. +public typealias ImageDisplayingView = NSView & ImageDisplaying + +extension NSImageView: ImageDisplaying { + /// Displays an image. + open func display(image: Image?) { + self.image = image + } +} +#endif + +/// Loads an image into the view. +/// +/// Before loading the new image prepares the view for reuse by cancelling any +/// outstanding requests and removing previously displayed images (if any). +/// +/// If the image is stored in memory cache, the image is displayed immediately. +/// If not, the image is loaded using an image pipeline. Displays a `placeholder` +/// if it was provided. When the request completes the loaded image is displayed +/// (or `failureImage` in case of an error). +/// +/// Nuke keeps a weak reference to the view. If the view is deallocated +/// the associated request automatically gets cancelled. +/// +/// - parameter options: `ImageLoadingOptions.shared` by default. +/// - parameter progress: A closure to be called periodically on the main thread +/// when the progress is updated. `nil` by default. +/// - parameter completion: A closure to be called on the main thread when the +/// request is finished. Gets called synchronously if the response was found in +/// memory cache. `nil` by default. +/// - returns: An image task of `nil` if the image was found in memory cache. +@discardableResult +public func loadImage(with url: URL, + options: ImageLoadingOptions = ImageLoadingOptions.shared, + into view: ImageDisplayingView, + progress: ImageTask.ProgressHandler? = nil, + completion: ImageTask.Completion? = nil) -> ImageTask? { + return loadImage(with: ImageRequest(url: url), options: options, into: view, progress: progress, completion: completion) +} + +/// Loads an image into the view. +/// +/// Before loading the new image prepares the view for reuse by cancelling any +/// outstanding requests and removing previously displayed images (if any). +/// +/// If the image is stored in memory cache, the image is displayed immediately. +/// If not, the image is loaded using an image pipeline. Displays a `placeholder` +/// if it was provided. When the request completes the loaded image is displayed +/// (or `failureImage` in case of an error). +/// +/// Nuke keeps a weak reference to the view. If the view is deallocated +/// the associated request automatically gets cancelled. +/// +/// - parameter options: `ImageLoadingOptions.shared` by default. +/// - parameter progress: A closure to be called periodically on the main thread +/// when the progress is updated. `nil` by default. +/// - parameter completion: A closure to be called on the main thread when the +/// request is finished. Gets called synchronously if the response was found in +/// memory cache. `nil` by default. +/// - returns: An image task of `nil` if the image was found in memory cache. +@discardableResult +public func loadImage(with request: ImageRequest, + options: ImageLoadingOptions = ImageLoadingOptions.shared, + into view: ImageDisplayingView, + progress: ImageTask.ProgressHandler? = nil, + completion: ImageTask.Completion? = nil) -> ImageTask? { + assert(Thread.isMainThread) + let controller = ImageViewController.controller(for: view) + return controller.loadImage(with: request, options: options, progress: progress, completion: completion) +} + +/// Cancels an outstanding request associated with the view. +public func cancelRequest(for view: ImageDisplayingView) { + assert(Thread.isMainThread) + ImageViewController.controller(for: view).cancelOutstandingTask() +} + +// MARK: - ImageLoadingOptions + +/// A range of options that control how the image is loaded and displayed. +public struct ImageLoadingOptions { + /// Shared options. + public static var shared = ImageLoadingOptions() + + /// Placeholder to be displayed when the image is loading. `nil` by default. + public var placeholder: Image? + + /// The image transition animation performed when displaying a loaded image. + /// Only runs when the image was not found in memory cache. `.nil` by default. + public var transition: Transition? + + /// Image to be displayed when the request fails. `nil` by default. + public var failureImage: Image? + + /// The image transition animation performed when displaying a failure image. + /// `.nil` by default. + public var failureImageTransition: Transition? + + /// If true, every time you request a new image for a view, the view will be + /// automatically prepared for reuse: image will be set to `nil`, and animations + /// will be removed. `true` by default. + public var isPrepareForReuseEnabled = true + + /// Custom pipeline to be used. `nil` by default. + public var pipeline: ImagePipeline? + + #if !os(macOS) + /// Content modes to be used for each image type (placeholder, success, + /// failure). `nil` by default (don't change content mode). + public var contentModes: ContentModes? + + /// Custom content modes to be used for each image type (placeholder, success, + /// failure). + public struct ContentModes { + #if swift(>=4.2) + /// Content mode to be used for the loaded image. + public var success: UIView.ContentMode + /// Content mode to be used when displaying a `failureImage`. + public var failure: UIView.ContentMode + /// Content mode to be used when displaying a `placeholder`. + public var placeholder: UIView.ContentMode + + /// - parameter success: A content mode to be used with a loaded image. + /// - parameter failure: A content mode to be used with a `failureImage`. + /// - parameter placeholder: A content mode to be used with a `placeholder`. + public init(success: UIView.ContentMode, failure: UIView.ContentMode, placeholder: UIView.ContentMode) { + self.success = success; self.failure = failure; self.placeholder = placeholder + } + #else + /// Content mode to be used for the loaded image. + public var success: UIViewContentMode + /// Content mode to be used when displaying a `failureImage`. + public var failure: UIViewContentMode + /// Content mode to be used when displaying a `placeholder`. + public var placeholder: UIViewContentMode + + /// - parameter success: A content mode to be used with a loaded image. + /// - parameter failure: A content mode to be used with a `failureImage`. + /// - parameter placeholder: A content mode to be used with a `placeholder`. + public init(success: UIViewContentMode, failure: UIViewContentMode, placeholder: UIViewContentMode) { + self.success = success; self.failure = failure; self.placeholder = placeholder + } + #endif + } + + /// - parameter placeholder: Placeholder to be displayed when the image is + /// loading . `nil` by default. + /// - parameter transision: The image transition animation performed when + /// displaying a loaded image. Only runs when the image was not found in + /// memory cache `.nil` by default (no animations). + /// - parameter failureImage: Image to be displayd when request fails. + /// `nil` by default. + /// - parameter failureImageTransition: The image transition animation + /// performed when displaying a failure image. `.nil` by default. + /// - parameter contentModes: Content modes to be used for each image type + /// (placeholder, success, failure). `nil` by default (don't change content mode). + public init(placeholder: Image? = nil, transition: Transition? = nil, failureImage: Image? = nil, failureImageTransition: Transition? = nil, contentModes: ContentModes? = nil) { + self.placeholder = placeholder + self.transition = transition + self.failureImage = failureImage + self.failureImageTransition = failureImageTransition + self.contentModes = contentModes + } + #else + public init(placeholder: Image? = nil, transition: Transition? = nil, failureImage: Image? = nil, failureImageTransition: Transition? = nil) { + self.placeholder = placeholder + self.transition = transition + self.failureImage = failureImage + self.failureImageTransition = failureImageTransition + } + #endif + + /// An animated image transition. + public struct Transition { + var style: Style + + struct Parameters { // internal representation + let duration: TimeInterval + #if !os(macOS) + #if swift(>=4.2) + let options: UIView.AnimationOptions + #else + let options: UIViewAnimationOptions + #endif + #endif + } + + enum Style { // internal representation + case fadeIn(parameters: Parameters) + case custom((ImageDisplayingView, Image) -> Void) + } + + #if !os(macOS) + /// Fade-in transition (cross-fade in case the image view is already + /// displaying an image). + #if swift(>=4.2) + public static func fadeIn(duration: TimeInterval, options: UIView.AnimationOptions = .allowUserInteraction) -> Transition { + return Transition(style: .fadeIn(parameters: Parameters(duration: duration, options: options))) + } + #else + public static func fadeIn(duration: TimeInterval, options: UIViewAnimationOptions = .allowUserInteraction) -> Transition { + return Transition(style: .fadeIn(parameters: Parameters(duration: duration, options: options))) + } + #endif + #else + /// Fade-in transition. + public static func fadeIn(duration: TimeInterval) -> Transition { + return Transition(style: .fadeIn(parameters: Parameters(duration: duration))) + } + #endif + + /// Custom transition. Only runs when the image was not found in memory cache. + public static func custom(_ closure: @escaping (ImageDisplayingView, Image) -> Void) -> Transition { + return Transition(style: .custom(closure)) + } + } + + public init() {} +} + +// MARK: - ImageViewController + +/// Manages image requests on behalf of an image view. +/// +/// - note: With a few modifications this might become public at some point, +/// however as it stands today `ImageViewController` is just a helper class, +/// making it public wouldn't expose any additional functionality to the users. +private final class ImageViewController { + // Ideally should be `unowned` but can't because of the Swift bug + // https://bugs.swift.org/browse/SR-7369 + private weak var imageView: ImageDisplayingView? + private weak var task: ImageTask? + private var taskId: Int = 0 + + // Automatically cancel the request when the view is deallocated. + deinit { + cancelOutstandingTask() + } + + init(view: /* weak */ ImageDisplayingView) { + self.imageView = view + } + + // MARK: - Associating Controller + + static var controllerAK = "ImageViewController.AssociatedKey" + + // Lazily create a controller for a given view and associate it with a view. + static func controller(for view: ImageDisplayingView) -> ImageViewController { + if let controller = objc_getAssociatedObject(view, &ImageViewController.controllerAK) as? ImageViewController { + return controller + } + let controller = ImageViewController(view: view) + objc_setAssociatedObject(view, &ImageViewController.controllerAK, controller, .OBJC_ASSOCIATION_RETAIN) + return controller + } + + // MARK: - Loading Images + + func loadImage(with request: ImageRequest, + options: ImageLoadingOptions, + progress: ImageTask.ProgressHandler? = nil, + completion: ImageTask.Completion? = nil) -> ImageTask? { + cancelOutstandingTask() + + guard let imageView = imageView else { + return nil + } + + if options.isPrepareForReuseEnabled { // enabled by default + #if !os(macOS) + imageView.layer.removeAllAnimations() + #else + imageView.layer?.removeAllAnimations() + #endif + } + + let pipeline = options.pipeline ?? ImagePipeline.shared + + // Quick synchronous memory cache lookup + if request.memoryCacheOptions.isReadAllowed, + let imageCache = pipeline.configuration.imageCache, + let response = imageCache.cachedResponse(for: request) { + handle(response: response, error: nil, fromMemCache: true, options: options) + completion?(response, nil) + return nil + } + + // Display a placeholder. + if let placeholder = options.placeholder { + imageView.display(image: placeholder) + #if !os(macOS) + if let contentMode = options.contentModes?.placeholder { + imageView.contentMode = contentMode + } + #endif + } else { + if options.isPrepareForReuseEnabled { + imageView.display(image: nil) // Remove previously displayed images (if any) + } + } + + // Makes sure that view reuse is handled correctly. + let taskId = self.taskId + + // Start the request. + self.task = pipeline.loadImage( + with: request, + progress: { [weak self] response, completed, total in + guard self?.taskId == taskId else { return } + self?.handle(partialImage: response, options: options) + progress?(response, completed, total) + }, + completion: { [weak self] response, error in + guard self?.taskId == taskId else { return } + self?.handle(response: response, error: error, fromMemCache: false, options: options) + completion?(response, error) + } + ) + return self.task + } + + func cancelOutstandingTask() { + taskId += 1 + task?.cancel() + task = nil + } + + // MARK: - Handling Responses + + #if !os(macOS) + + private func handle(response: ImageResponse?, error: Error?, fromMemCache: Bool, options: ImageLoadingOptions) { + if let image = response?.image { + _display(image, options.transition, fromMemCache, options.contentModes?.success) + } else if let failureImage = options.failureImage { + _display(failureImage, options.failureImageTransition, fromMemCache, options.contentModes?.failure) + } + self.task = nil + } + + private func handle(partialImage response: ImageResponse?, options: ImageLoadingOptions) { + guard let image = response?.image else { return } + _display(image, options.transition, false, options.contentModes?.success) + } + + #else + + private func handle(response: ImageResponse?, error: Error?, fromMemCache: Bool, options: ImageLoadingOptions) { + // NSImageView doesn't support content mode, unfortunately. + if let image = response?.image { + _display(image, options.transition, fromMemCache, nil) + } else if let failureImage = options.failureImage { + _display(failureImage, options.failureImageTransition, fromMemCache, nil) + } + self.task = nil + } + + private func handle(partialImage response: ImageResponse?, options: ImageLoadingOptions) { + guard let image = response?.image else { return } + _display(image, options.transition, false, nil) + } + + #endif + + private func _display(_ image: Image, _ transition: ImageLoadingOptions.Transition?, _ fromMemCache: Bool, _ newContentMode: _ContentMode?) { + guard let imageView = imageView else { return } + + if !fromMemCache, let transition = transition { + switch transition.style { + case let .fadeIn(params): + _runFadeInTransition(image: image, params: params, contentMode: newContentMode) + case let .custom(closure): + // The user is reponsible for both displaying an image and performing + // animations. + closure(imageView, image) + } + } else { + imageView.display(image: image) + } + #if !os(macOS) + if let newContentMode = newContentMode { + imageView.contentMode = newContentMode + } + #endif + } + + // MARK: - Animations + + #if !os(macOS) + + // Image view used for cross-fade transition between images with different + // content modes. + private lazy var transitionImageView = UIImageView() + + #if swift(>=4.2) + private typealias _ContentMode = UIView.ContentMode + #else + private typealias _ContentMode = UIViewContentMode + #endif + + private func _runFadeInTransition(image: Image, params: ImageLoadingOptions.Transition.Parameters, contentMode: _ContentMode?) { + guard let imageView = imageView else { return } + + // Special case where we animate between content modes, only works + // on imageView subclasses. + if let contentMode = contentMode, imageView.contentMode != contentMode, let imageView = imageView as? UIImageView, imageView.image != nil { + _runCrossDissolveWithContentMode(imageView: imageView, image: image, params: params) + } else { + _runSimpleFadeIn(image: image, params: params) + } + } + + private func _runSimpleFadeIn(image: Image, params: ImageLoadingOptions.Transition.Parameters) { + guard let imageView = imageView else { return } + + UIView.transition( + with: imageView, + duration: params.duration, + options: params.options.union(.transitionCrossDissolve), + animations: { + imageView.display(image: image) + }, + completion: nil + ) + } + + /// Performs cross-dissolve animation alonside transition to a new content + /// mode. This isn't natively supported feature and it requires a second + /// image view. There might be better ways to implement it. + private func _runCrossDissolveWithContentMode(imageView: UIImageView, image: Image, params: ImageLoadingOptions.Transition.Parameters) { + // Lazily create a transition view. + let transitionView = self.transitionImageView + + // Create a transition view which mimics current view's contents. + transitionView.image = imageView.image + transitionView.contentMode = imageView.contentMode + imageView.addSubview(transitionView) + transitionView.frame = imageView.bounds + + // "Manual" cross-fade. + transitionView.alpha = 1 + imageView.alpha = 0 + imageView.image = image // Display new image in current view + + UIView.animate( + withDuration: params.duration, + delay: 0, + options: params.options, + animations: { + transitionView.alpha = 0 + imageView.alpha = 1 + }, + completion: { isCompleted in + if isCompleted { + transitionView.removeFromSuperview() + } + } + ) + } + + #else + + private typealias _ContentMode = Void // There is no content mode on macOS + + private func _runFadeInTransition(image: Image, params: ImageLoadingOptions.Transition.Parameters, contentMode: _ContentMode?) { + let animation = CABasicAnimation(keyPath: "opacity") + animation.duration = params.duration + animation.fromValue = 0 + animation.toValue = 1 + imageView?.layer?.add(animation, forKey: "imageTransition") + } + + #endif +} + +#endif diff --git a/Pods/Nuke/Sources/Internal.swift b/Pods/Nuke/Sources/Internal.swift new file mode 100644 index 0000000000..6ee642c1a8 --- /dev/null +++ b/Pods/Nuke/Sources/Internal.swift @@ -0,0 +1,571 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). + +import Foundation + +// MARK: - Lock + +extension NSLock { + func sync(_ closure: () -> T) -> T { + lock(); defer { unlock() } + return closure() + } +} + +// MARK: - RateLimiter + +/// Controls the rate at which the work is executed. Uses the classic [token +/// bucket](https://en.wikipedia.org/wiki/Token_bucket) algorithm. +/// +/// The main use case for rate limiter is to support large (infinite) collections +/// of images by preventing trashing of underlying systems, primary URLSession. +/// +/// The implementation supports quick bursts of requests which can be executed +/// without any delays when "the bucket is full". This is important to prevent +/// rate limiter from affecting "normal" requests flow. +internal final class RateLimiter { + private let bucket: TokenBucket + private let queue: DispatchQueue + private var pending = LinkedList() // fast append, fast remove first + private var isExecutingPendingTasks = false + + private typealias Task = (CancellationToken, () -> Void) + + /// Initializes the `RateLimiter` with the given configuration. + /// - parameter queue: Queue on which to execute pending tasks. + /// - parameter rate: Maximum number of requests per second. 80 by default. + /// - parameter burst: Maximum number of requests which can be executed without + /// any delays when "bucket is full". 25 by default. + init(queue: DispatchQueue, rate: Int = 80, burst: Int = 25) { + self.queue = queue + self.bucket = TokenBucket(rate: Double(rate), burst: Double(burst)) + } + + func execute(token: CancellationToken, _ closure: @escaping () -> Void) { + let task = Task(token, closure) + if !pending.isEmpty || !_execute(task) { + pending.append(task) + _setNeedsExecutePendingTasks() + } + } + + private func _execute(_ task: Task) -> Bool { + guard !task.0.isCancelling else { + return true // No need to execute + } + return bucket.execute(task.1) + } + + private func _setNeedsExecutePendingTasks() { + guard !isExecutingPendingTasks else { return } + isExecutingPendingTasks = true + // Compute a delay such that by the time the closure is executed the + // bucket is refilled to a point that is able to execute at least one + // pending task. With a rate of 100 tasks we expect a refill every 10 ms. + let delay = Int(1.15 * (1000 / bucket.rate)) // 14 ms for rate 80 (default) + let bounds = max(100, min(5, delay)) // Make the delay is reasonable + queue.asyncAfter(deadline: .now() + .milliseconds(bounds), execute: _executePendingTasks) + } + + private func _executePendingTasks() { + while let node = pending.first, _execute(node.value) { + pending.remove(node) + } + isExecutingPendingTasks = false + if !pending.isEmpty { // Not all pending items were executed + _setNeedsExecutePendingTasks() + } + } + + private final class TokenBucket { + let rate: Double + private let burst: Double // maximum bucket size + private var bucket: Double + private var timestamp: TimeInterval // last refill timestamp + + /// - parameter rate: Rate (tokens/second) at which bucket is refilled. + /// - parameter burst: Bucket size (maximum number of tokens). + init(rate: Double, burst: Double) { + self.rate = rate + self.burst = burst + self.bucket = burst + self.timestamp = CFAbsoluteTimeGetCurrent() + } + + /// Returns `true` if the closure was executed, `false` if dropped. + func execute(_ closure: () -> Void) -> Bool { + refill() + guard bucket >= 1.0 else { + return false // bucket is empty + } + bucket -= 1.0 + closure() + return true + } + + private func refill() { + let now = CFAbsoluteTimeGetCurrent() + bucket += rate * max(0, now - timestamp) // rate * (time delta) + timestamp = now + if bucket > burst { // prevent bucket overflow + bucket = burst + } + } + } +} + +// MARK: - Operation + +internal final class Operation: Foundation.Operation { + private var _isExecuting = false + private var _isFinished = false + private var _isFinishCalled: Int32 = 0 + + override var isExecuting: Bool { + set { + guard _isExecuting != newValue else { + fatalError("Invalid state, operation is already (not) executing") + } + willChangeValue(forKey: "isExecuting") + _isExecuting = newValue + didChangeValue(forKey: "isExecuting") + } + get { + return _isExecuting + } + } + override var isFinished: Bool { + set { + guard !_isFinished else { + fatalError("Invalid state, operation is already finished") + } + willChangeValue(forKey: "isFinished") + _isFinished = newValue + didChangeValue(forKey: "isFinished") + } + get { + return _isFinished + } + } + + typealias Starter = (_ finish: @escaping () -> Void) -> Void + private let starter: Starter + + init(starter: @escaping Starter) { + self.starter = starter + } + + override func start() { + guard !isCancelled else { + isFinished = true + return + } + isExecuting = true + starter { [weak self] in + self?._finish() + } + } + + private func _finish() { + // Make sure that we ignore if `finish` is called more than once. + if OSAtomicCompareAndSwap32Barrier(0, 1, &_isFinishCalled) { + isExecuting = false + isFinished = true + } + } +} + +// MARK: - LinkedList + +/// A doubly linked list. +internal final class LinkedList { + // first <-> node <-> ... <-> last + private(set) var first: Node? + private(set) var last: Node? + + deinit { + removeAll() + } + + var isEmpty: Bool { + return last == nil + } + + /// Adds an element to the end of the list. + @discardableResult + func append(_ element: Element) -> Node { + let node = Node(value: element) + append(node) + return node + } + + /// Adds a node to the end of the list. + func append(_ node: Node) { + if let last = last { + last.next = node + node.previous = last + self.last = node + } else { + last = node + first = node + } + } + + func remove(_ node: Node) { + node.next?.previous = node.previous // node.previous is nil if node=first + node.previous?.next = node.next // node.next is nil if node=last + if node === last { + last = node.previous + } + if node === first { + first = node.next + } + node.next = nil + node.previous = nil + } + + func removeAll() { + // avoid recursive Nodes deallocation + var node = first + while let next = node?.next { + node?.next = nil + next.previous = nil + node = next + } + last = nil + first = nil + } + + final class Node { + let value: Element + fileprivate var next: Node? + fileprivate var previous: Node? + + init(value: Element) { + self.value = value + } + } +} + +// MARK: - CancellationTokenSource + +/// Manages cancellation tokens and signals them when cancellation is requested. +/// +/// All `CancellationTokenSource` methods are thread safe. +internal final class CancellationTokenSource { + /// Returns `true` if cancellation has been requested. + var isCancelling: Bool { + return _lock.sync { _observers == nil } + } + + /// Creates a new token associated with the source. + var token: CancellationToken { + return CancellationToken(source: self) + } + + private var _observers: ContiguousArray<() -> Void>? = [] + + /// Initializes the `CancellationTokenSource` instance. + init() {} + + fileprivate func register(_ closure: @escaping () -> Void) { + if !_register(closure) { + closure() + } + } + + private func _register(_ closure: @escaping () -> Void) -> Bool { + _lock.lock(); defer { _lock.unlock() } + _observers?.append(closure) + return _observers != nil + } + + /// Communicates a request for cancellation to the managed tokens. + func cancel() { + if let observers = _cancel() { + observers.forEach { $0() } + } + } + + private func _cancel() -> ContiguousArray<() -> Void>? { + _lock.lock(); defer { _lock.unlock() } + let observers = _observers + _observers = nil // transition to `isCancelling` state + return observers + } +} + +// We use the same lock across different tokens because the design of CTS +// prevents potential issues. For example, closures registered with a token +// are never executed inside a lock. +private let _lock = NSLock() + +/// Enables cooperative cancellation of operations. +/// +/// You create a cancellation token by instantiating a `CancellationTokenSource` +/// object and calling its `token` property. You then pass the token to any +/// number of threads, tasks, or operations that should receive notice of +/// cancellation. When the owning object calls `cancel()`, the `isCancelling` +/// property on every copy of the cancellation token is set to `true`. +/// The registered objects can respond in whatever manner is appropriate. +/// +/// All `CancellationToken` methods are thread safe. +internal struct CancellationToken { + fileprivate let source: CancellationTokenSource? // no-op when `nil` + + /// Returns `true` if cancellation has been requested for this token. + /// Returns `false` if the source was deallocated. + var isCancelling: Bool { + return source?.isCancelling ?? false + } + + /// Registers the closure that will be called when the token is canceled. + /// If this token is already cancelled, the closure will be run immediately + /// and synchronously. + func register(_ closure: @escaping () -> Void) { + source?.register(closure) + } +} + +// MARK: - ResumableData + +/// Resumable data support. For more info see: +/// - https://developer.apple.com/library/content/qa/qa1761/_index.html +internal struct ResumableData { + let data: Data + let validator: String // Either Last-Modified or ETag + + init?(response: URLResponse, data: Data) { + // Check if "Accept-Ranges" is present and the response is valid. + guard !data.isEmpty, + let response = response as? HTTPURLResponse, + response.statusCode == 200 /* OK */ || response.statusCode == 206, /* Partial Content */ + let acceptRanges = response.allHeaderFields["Accept-Ranges"] as? String, + acceptRanges.lowercased() == "bytes", + let validator = ResumableData._validator(from: response) else { + return nil + } + + // NOTE: https://developer.apple.com/documentation/foundation/httpurlresponse/1417930-allheaderfields + // HTTP headers are case insensitive. To simplify your code, certain + // header field names are canonicalized into their standard form. + // For example, if the server sends a content-length header, + // it is automatically adjusted to be Content-Length. + + self.data = data; self.validator = validator + } + + private static func _validator(from response: HTTPURLResponse) -> String? { + if let entityTag = response.allHeaderFields["ETag"] as? String { + return entityTag // Prefer ETag + } + // There seems to be a bug with ETag where HTTPURLResponse would canonicalize + // it to Etag instead of ETag + // https://bugs.swift.org/browse/SR-2429 + if let entityTag = response.allHeaderFields["Etag"] as? String { + return entityTag // Prefer ETag + } + if let lastModified = response.allHeaderFields["Last-Modified"] as? String { + return lastModified + } + return nil + } + + func resume(request: inout URLRequest) { + var headers = request.allHTTPHeaderFields ?? [:] + // "bytes=1000-" means bytes from 1000 up to the end (inclusive) + headers["Range"] = "bytes=\(data.count)-" + headers["If-Range"] = validator + request.allHTTPHeaderFields = headers + } + + // Check if the server decided to resume the response. + static func isResumedResponse(_ response: URLResponse) -> Bool { + // "206 Partial Content" (server accepted "If-Range") + return (response as? HTTPURLResponse)?.statusCode == 206 + } + + // MARK: Storing Resumable Data + + /// Shared between multiple pipelines. Thread safe. In the future version we + /// might feature more customization options. + static var _cache = _Cache(costLimit: 32 * 1024 * 1024, countLimit: 100) // internal only for testing purposes + + static func removeResumableData(for request: URLRequest) -> ResumableData? { + guard let url = request.url?.absoluteString else { return nil } + return _cache.removeValue(forKey: url) + } + + static func storeResumableData(_ data: ResumableData, for request: URLRequest) { + guard let url = request.url?.absoluteString else { return } + _cache.set(data, forKey: url, cost: data.data.count) + } +} + +// MARK: - Printer + +/// Helper type for printing nice debug descriptions. +internal struct Printer { + private(set) internal var _out = String() + + private let timelineFormatter: DateFormatter + + init(_ string: String = "") { + self._out = string + + timelineFormatter = DateFormatter() + timelineFormatter.dateFormat = "HH:mm:ss.SSS" + } + + func output(indent: Int = 0) -> String { + return _out.components(separatedBy: .newlines) + .map { $0.isEmpty ? "" : String(repeating: " ", count: indent) + $0 } + .joined(separator: "\n") + } + + mutating func string(_ str: String) { + _out.append(str) + } + + mutating func line(_ str: String) { + _out.append(str) + _out.append("\n") + } + + mutating func value(_ key: String, _ value: CustomStringConvertible?) { + let val = value.map { String(describing: $0) } + line(key + " - " + (val ?? "nil")) + } + + /// For producting nicely formatted timelines like this: + /// + /// 11:45:52.737 - Data Loading Start Date + /// 11:45:52.739 - Data Loading End Date + /// nil - Decoding Start Date + mutating func timeline(_ key: String, _ date: Date?) { + let value = date.map { timelineFormatter.string(from: $0) } + self.value((value ?? "nil "), key) // Swtich key with value + } + + mutating func timeline(_ key: String, _ start: Date?, _ end: Date?, isReversed: Bool = true) { + let duration = _duration(from: start, to: end) + let value = "\(_string(from: start)) – \(_string(from: end)) (\(duration))" + if isReversed { + self.value(value.padding(toLength: 36, withPad: " ", startingAt: 0), key) + } else { + self.value(key, value) + } + } + + mutating func section(title: String, _ closure: (inout Printer) -> Void) { + _out.append(contentsOf: title) + _out.append(" {\n") + var printer = Printer() + closure(&printer) + _out.append(printer.output(indent: 4)) + _out.append("}\n") + } + + // MARK: Formatters + + private func _string(from date: Date?) -> String { + return date.map { timelineFormatter.string(from: $0) } ?? "nil" + } + + private func _duration(from: Date?, to: Date?) -> String { + guard let from = from else { return "nil" } + guard let to = to else { return "unknown" } + return Printer.duration(to.timeIntervalSince(from)) ?? "nil" + } + + static func duration(_ duration: TimeInterval?) -> String? { + guard let duration = duration else { return nil } + + let m: Int = Int(duration) / 60 + let s: Int = Int(duration) % 60 + let ms: Int = Int(duration * 1000) % 1000 + + var output = String() + if m > 0 { output.append("\(m):") } + output.append(output.isEmpty ? "\(s)." : String(format: "%02d.", s)) + output.append(String(format: "%03ds", ms)) + return output + } +} + +// MARK: - Misc + +struct TaskMetrics { + var startDate: Date? = nil + var endDate: Date? = nil + + static func started() -> TaskMetrics { + var metrics = TaskMetrics() + metrics.start() + return metrics + } + + mutating func start() { + startDate = Date() + } + + mutating func end() { + endDate = Date() + } +} + +/// A simple observable property. Not thread safe. +final class Property { + var value: T { + didSet { + for observer in observers { + observer(value) + } + } + } + + init(value: T) { + self.value = value + } + + private var observers = [(T) -> Void]() + + // For our use-cases we can just ignore unsubscribing for now. + func observe(_ closure: @escaping (T) -> Void) { + observers.append(closure) + } +} + +// MARK: - Misc + +#if !swift(>=4.1) +extension Sequence { + public func compactMap(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { + return try flatMap(transform) + } +} +#endif + +#if swift(>=4.2) +import CommonCrypto + +extension String { + /// Calculates SHA1 from the given string and returns its hex representation. + /// + /// ```swift + /// print("http://test.com".sha1) + /// // prints "50334ee0b51600df6397ce93ceed4728c37fee4e" + /// ``` + var sha1: String? { + guard let input = self.data(using: .utf8) else { + return nil + } + var hash = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) + input.withUnsafeBytes { + _ = CC_SHA1($0, CC_LONG(input.count), &hash) + } + return hash.map({ String(format: "%02x", $0) }).joined() + } +} +#endif diff --git a/Pods/OAuthSwift/LICENSE b/Pods/OAuthSwift/LICENSE new file mode 100644 index 0000000000..fa84148b8f --- /dev/null +++ b/Pods/OAuthSwift/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Dongri Jin + +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/OAuthSwift/README.md b/Pods/OAuthSwift/README.md new file mode 100644 index 0000000000..c1069613e0 --- /dev/null +++ b/Pods/OAuthSwift/README.md @@ -0,0 +1,262 @@ +

+ OAuthSwift +

+ +# OAuthSwift + +Swift based OAuth library for iOS and macOS. + +## Support OAuth1.0, OAuth2.0 + +Twitter, Flickr, Github, Instagram, Foursquare, Fitbit, Withings, Linkedin, Dropbox, Dribbble, Salesforce, BitBucket, GoogleDrive, Smugmug, Intuit, Zaim, Tumblr, Slack, Uber, Gitter, Facebook, Spotify, Typetalk, SoundCloud, etc + +## Sponsored by Auth0 +If you want to easily add authentication to Swift apps, feel free to check out Auth0's Swift SDK and free plan at [auth0.com/overview](https://auth0.com/overview?utm_source=GHsponsor&utm_medium=GHsponsor&utm_campaign=oauthswift&utm_content=auth) + +## Installation + +OAuthSwift is packaged as a Swift framework. Currently this is the simplest way to add it to your app: + +* Drag OAuthSwift.xcodeproj to your project in the Project Navigator. +* Select your project and then your app target. Open the Build Phases panel. +* Expand the Target Dependencies group, and add OAuthSwift framework. +* import OAuthSwift whenever you want to use OAuthSwift. + +### Support Carthage + +* Install Carthage (https://github.com/Carthage/Carthage) +* Create Cartfile file +``` +github "OAuthSwift/OAuthSwift" ~> 1.2.0 +``` +* Run `carthage update`. +* On your application targets’ “General” settings tab, in the “Embedded Binaries” section, drag and drop OAuthSwift.framework from the Carthage/Build/iOS folder on disk. + +### Support CocoaPods + +* Podfile + +``` +platform :ios, '10.0' +use_frameworks! + +pod 'OAuthSwift', '~> 1.2.0' +``` + +### swift 3 + +Use the `swift3` branch, or the tag `1.1.2` on main branch + +## How to +### Setting URL Schemes +In info tab of your target +![Image](Assets/URLSchemes.png "Image") +Replace oauth-swift by your application name + +### Handle URL in AppDelegate +- On iOS implement `UIApplicationDelegate` method +```swift +func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { + if (url.host == "oauth-callback") { + OAuthSwift.handle(url: url) + } + return true +} +``` +:warning: Any other application may try to open a URL with your url scheme. So you can check the source application, for instance for safari controller : +``` +if (options[.sourceApplication] as? String == "com.apple.SafariViewService") { +``` + +- On macOS you must register an handler on `NSAppleEventManager` for event type `kAEGetURL` (see demo code) +```swift +func applicationDidFinishLaunching(_ aNotification: NSNotification) { + NSAppleEventManager.shared().setEventHandler(self, andSelector:#selector(AppDelegate.handleGetURL(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) +} +func handleGetURL(event: NSAppleEventDescriptor!, withReplyEvent: NSAppleEventDescriptor!) { + if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue, let url = URL(string: urlString) { + OAuthSwift.handle(url: url) + } +} +``` + +### Authorize with OAuth1.0 +```swift +// create an instance and retain it +oauthswift = OAuth1Swift( + consumerKey: "********", + consumerSecret: "********", + requestTokenUrl: "https://api.twitter.com/oauth/request_token", + authorizeUrl: "https://api.twitter.com/oauth/authorize", + accessTokenUrl: "https://api.twitter.com/oauth/access_token" +) +// authorize +let handle = oauthswift.authorize( + withCallbackURL: URL(string: "oauth-swift://oauth-callback/twitter")!, + success: { credential, response, parameters in + print(credential.oauthToken) + print(credential.oauthTokenSecret) + print(parameters["user_id"]) + // Do your request + }, + failure: { error in + print(error.localizedDescription) + } +) +``` +### OAuth1 without authorization +No urls to specify here +```swift +// create an instance and retain it +oauthswift = OAuth1Swift( + consumerKey: "********", + consumerSecret: "********" +) +// do your HTTP request without authorize +oauthswift.client.get("https://api.example.com/foo/bar", + success: { response in + //.... + }, + failure: { error in + //... + } +) +``` + +### Authorize with OAuth2.0 +```swift +// create an instance and retain it +oauthswift = OAuth2Swift( + consumerKey: "********", + consumerSecret: "********", + authorizeUrl: "https://api.instagram.com/oauth/authorize", + responseType: "token" +) +let handle = oauthswift.authorize( + withCallbackURL: URL(string: "oauth-swift://oauth-callback/instagram")!, + scope: "likes+comments", state:"INSTAGRAM", + success: { credential, response, parameters in + print(credential.oauthToken) + // Do your request + }, + failure: { error in + print(error.localizedDescription) + } +) + +``` + +See demo for more examples + +### Handle authorize URL +The authorize URL allows the user to connect to a provider and give access to your application. + +By default this URL is opened into the external web browser (ie. safari), but apple does not allow it for app-store iOS applications. + +To change this behavior you must set an `OAuthSwiftURLHandlerType`, simple protocol to handle an `URL` +```swift +oauthswift.authorizeURLHandler = .. +``` +For instance you can embed a web view into your application by providing a controller that displays a web view (`UIWebView`, `WKWebView`). +Then this controller must implement `OAuthSwiftURLHandlerType` to load the URL into the web view +```swift +func handle(_ url: NSURL) { + let req = URLRequest(URL: targetURL) + self.webView.loadRequest(req) + ... +``` +and present the view (`present(viewController`, `performSegue(withIdentifier: `, ...) +*You can extend `OAuthWebViewController` for a default implementation of view presentation and dismiss* + +#### Use the SFSafariViewController (iOS9) +A default implementation of `OAuthSwiftURLHandlerType` is provided using the `SFSafariViewController`, with automatic view dismiss. +```swift +oauthswift.authorizeURLHandler = SafariURLHandler(viewController: self, oauthSwift: oauthswift) +``` +Of course you can create your own class or customize the controller by setting the variable `SafariURLHandler#factory`. + +### Make signed request + +Just call HTTP functions of `oauthswift.client` + +```swift +oauthswift.client.get("https://api.linkedin.com/v1/people/~", + success: { response in + let dataString = response.string + print(dataString) + }, + failure: { error in + print(error) + } +) +// same with request method +oauthswift.client.request("https://api.linkedin.com/v1/people/~", .GET, + parameters: [:], headers: [:], + success: { ... +``` + +See more examples in the demo application: [ViewController.swift](/Demo/Common/ViewController.swift) + +## OAuth provider pages + +* [Twitter](https://dev.twitter.com/oauth) +* [Flickr](https://www.flickr.com/services/api/auth.oauth.html) +* [Github](https://developer.github.com/v3/oauth/) +* [Instagram](http://instagram.com/developer/authentication) +* [Foursquare](https://developer.foursquare.com/overview/auth) +* [Fitbit](https://dev.fitbit.com/build/reference/web-api/oauth2/) +* [Withings](http://oauth.withings.com/api) +* [Linkedin](https://developer.linkedin.com/docs/oauth2) +* [Dropbox](https://www.dropbox.com/developers/core/docs) +* [Dribbble](http://developer.dribbble.com/v1/oauth/) +* [Salesforce](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/) +* [BitBucket](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) +* [GoogleDrive](https://developers.google.com/drive/v2/reference/) +* [Smugmug](https://smugmug.atlassian.net/wiki/display/API/OAuth) +* [Intuit](https://developer.intuit.com/docs/0100_accounting/0060_authentication_and_authorization/oauth_management_api) +* [Zaim](https://dev.zaim.net/home/api/authorize) +* [Tumblr](https://www.tumblr.com/docs/en/api/v2#auth) +* [Slack](https://api.slack.com/docs/oauth) +* [Uber](https://developer.uber.com/docs/ride-requests/guides/authentication/introduction#oauth-20) +* [Gitter](https://developer.gitter.im/docs/authentication) +* [Facebook](https://developers.facebook.com/docs/facebook-login) +* [Spotify](https://developer.spotify.com/web-api/authorization-guide/) +* [Trello](https://developers.trello.com/authorize) +* [Buffer](https://buffer.com/developers/api/oauth) +* [Goodreads](https://www.goodreads.com/api/documentation#oauth) +* [Typetalk](http://developer.nulab-inc.com/docs/typetalk/auth) +* [SoundCloud](https://developers.soundcloud.com/docs/api/guide#authentication) +* [Doper](https://doper.io/developer/oauth) +* [NounProject](http://api.thenounproject.com/getting_started.html#authentication) + +## Images + +![Image](Assets/Services.png "Image") +![Image](Assets/TwitterOAuth.png "Image") +![Image](Assets/TwitterOAuthTokens.png "Image") + +## Contributing + See [CONTRIBUTING.md](.github/CONTRIBUTING.md) + +[Add a new service in demo app](https://github.com/OAuthSwift/OAuthSwift/wiki/Demo-application#add-a-new-service-in-demo-app) + + +## Integration +OAuthSwift could be used with others frameworks + +You can sign [Alamofire](https://github.com/Alamofire/Alamofire) request with [OAuthSwiftAlamofire](https://github.com/OAuthSwift/OAuthSwiftAlamofire) + +To achieve great asynchronous code you can use one of these integration frameworks +- [OAuthSwiftFutures](https://github.com/OAuthSwift/OAuthSwiftFutures) - [BrightFutures](https://github.com/Thomvis/BrightFutures) +- [OAuthRxSwift](https://github.com/OAuthSwift/OAuthRxSwift) - [RxSwift](https://github.com/ReactiveX/RxSwift) +- [OAuthReactiveSwift](https://github.com/OAuthSwift/OAuthReactiveSwift) - [ReactiveSwift](https://github.com/ReactiveCocoa/ReactiveSwift) + +## License + +OAuthSwift is available under the MIT license. See the LICENSE file for more info. + +[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat + )](http://mit-license.org) [![Platform](https://img.shields.io/badge/platform-iOS_OSX_TVOS-lightgrey.svg?style=flat + )](https://developer.apple.com/resources/) [![Language](https://img.shields.io/badge/language-swift-orange.svg?style=flat + )](https://developer.apple.com/swift) [![Cocoapod](https://img.shields.io/cocoapods/v/OAuthSwift.svg?style=flat)](http://cocoadocs.org/docsets/OAuthSwift/) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) diff --git a/Pods/OAuthSwift/Sources/Collection+OAuthSwift.swift b/Pods/OAuthSwift/Sources/Collection+OAuthSwift.swift new file mode 100644 index 0000000000..72b6cea39e --- /dev/null +++ b/Pods/OAuthSwift/Sources/Collection+OAuthSwift.swift @@ -0,0 +1,34 @@ +// +// Collection+OAuthSwift.swift +// OAuthSwift +// +// Created by phimage on 02/10/16. +// Copyright © 2016 Dongri Jin. All rights reserved. +// + +import Foundation + +extension Collection where Self.Iterator.Element == UInt8, Self.Index == Int { + + var toUInt32: UInt32 { + assert(self.count > 3) + // XXX optimize do the job only for the first one... + return toUInt32Array()[0] + } + + func toUInt32Array() -> [UInt32] { + var result = [UInt32]() + result.reserveCapacity(16) + for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout.size) { + var val: UInt32 = 0 + val |= self.count > 3 ? UInt32(self[idx.advanced(by: 3)]) << 24 : 0 + val |= self.count > 2 ? UInt32(self[idx.advanced(by: 2)]) << 16 : 0 + val |= self.count > 1 ? UInt32(self[idx.advanced(by: 1)]) << 8 : 0 + //swiftlint:disable:next empty_count + val |= self.count > 0 ? UInt32(self[idx]) : 0 + result.append(val) + } + + return result + } +} diff --git a/Pods/OAuthSwift/Sources/Data+OAuthSwift.swift b/Pods/OAuthSwift/Sources/Data+OAuthSwift.swift new file mode 100644 index 0000000000..69303473d0 --- /dev/null +++ b/Pods/OAuthSwift/Sources/Data+OAuthSwift.swift @@ -0,0 +1,45 @@ +// +// Data+OAuthSwift.swift +// OAuthSwift +// +// Created by Dongri Jin on 1/28/15. +// Copyright (c) 2015 Dongri Jin. All rights reserved. +// + +import Foundation + +extension Data { + + internal init(data: Data) { + self.init() + self.append(data) + } + + internal mutating func append(_ bytes: [UInt8]) { + self.append(bytes, count: bytes.count) + } + internal mutating func append(_ byte: UInt8) { + append([byte]) + } + internal mutating func append(_ byte: UInt16) { + append(UInt8(byte >> 0 & 0xFF)) + append(UInt8(byte >> 8 & 0xFF)) + } + internal mutating func append(_ byte: UInt32) { + append(UInt16(byte >> 0 & 0xFFFF)) + append(UInt16(byte >> 16 & 0xFFFF)) + } + internal mutating func append(_ byte: UInt64) { + append(UInt32(byte >> 0 & 0xFFFFFFFF)) + append(UInt32(byte >> 32 & 0xFFFFFFFF)) + } + + var bytes: [UInt8] { + return Array(self) + /* let count = self.count / MemoryLayout.size + var bytesArray = [UInt8](repeating: 0, count: count) + self.copyBytes(to:&bytesArray, count: count * MemoryLayout.size) + return bytesArray*/ + } + +} diff --git a/Pods/OAuthSwift/Sources/Dictionary+OAuthSwift.swift b/Pods/OAuthSwift/Sources/Dictionary+OAuthSwift.swift new file mode 100755 index 0000000000..f47a4e5b96 --- /dev/null +++ b/Pods/OAuthSwift/Sources/Dictionary+OAuthSwift.swift @@ -0,0 +1,79 @@ +// +// Dictionary+OAuthSwift.swift +// OAuthSwift +// +// Created by Dongri Jin on 6/21/14. +// Copyright (c) 2014 Dongri Jin. All rights reserved. +// + +import Foundation + +extension Dictionary { + + func join(_ other: Dictionary) -> Dictionary { + var joinedDictionary = Dictionary() + + for (key, value) in self { + joinedDictionary.updateValue(value, forKey: key) + } + + for (key, value) in other { + joinedDictionary.updateValue(value, forKey: key) + } + + return joinedDictionary + } + + var urlEncodedQuery: String { + var parts = [String]() + + for (key, value) in self { + let keyString = "\(key)".urlEncoded + let valueString = "\(value)".urlEncoded + let query = "\(keyString)=\(valueString)" + parts.append(query) + } + + return parts.joined(separator: "&") + } + + mutating func merge(_ dictionaries: Dictionary...) { + for dict in dictionaries { + for (key, value) in dict { + if let v = value as? Value, let k = key as? Key { + self.updateValue(v, forKey: k) + } + } + } + } + + func map (_ transform: (Key, Value) -> (K, V)) -> [K: V] { + var results: [K: V] = [:] + for k in self.keys { + if let value = self[ k ] { + let (u, w) = transform(k, value) + results.updateValue(w, forKey: u) + } + } + return results + } +} + +extension Dictionary { + @available(swift, introduced: 3.2, obsoleted: 4.0) + public func filter(_ isIncluded: (Key, Value) throws -> Bool) rethrows -> [Key: Value] { + var resultDictionary = [Key: Value](minimumCapacity: count) + for (key, value) in self { + if try isIncluded(key, value) { + resultDictionary[key] = value + } + } + return resultDictionary + } +} + +func += (left: inout [K: V], right: [K: V]) { left.merge(right) } +func + (left: [K: V], right: [K: V]) -> [K: V] { return left.join(right) } +func += (left: inout [K: V]?, right: [K: V]) { + if left != nil { left?.merge(right) } else { left = right } +} diff --git a/Pods/OAuthSwift/Sources/HMAC.swift b/Pods/OAuthSwift/Sources/HMAC.swift new file mode 100644 index 0000000000..27b13c568a --- /dev/null +++ b/Pods/OAuthSwift/Sources/HMAC.swift @@ -0,0 +1,55 @@ +// +// HMAC.swift +// OAuthSwift +// +// Created by Dongri Jin on 1/28/15. +// Copyright (c) 2015 Dongri Jin. All rights reserved. +// + +import Foundation + +open class HMAC { + + let key: [UInt8] = [] + + class internal func sha1(key: Data, message: Data) -> Data? { + let blockSize = 64 + var key = key.bytes + let message = message.bytes + + if key.count > blockSize { + key = SHA1(key).calculate() + } else if key.count < blockSize { // padding + key += [UInt8](repeating: 0, count: blockSize - key.count) + } + + var ipad = [UInt8](repeating: 0x36, count: blockSize) + for idx in key.indices { + ipad[idx] = key[idx] ^ ipad[idx] + } + + var opad = [UInt8](repeating: 0x5c, count: blockSize) + for idx in key.indices { + opad[idx] = key[idx] ^ opad[idx] + } + + let ipadAndMessageHash = SHA1(ipad + message).calculate() + let mac = SHA1(opad + ipadAndMessageHash).calculate() + + return Data(bytes: UnsafePointer(mac), count: mac.count) + + } + +} + +extension HMAC: OAuthSwiftSignatureDelegate { + open static func sign(hashMethod: OAuthSwiftHashMethod, key: Data, message: Data) -> Data? { + switch hashMethod { + case .sha1: + return sha1(key: key, message: message) + case .none: + assertionFailure("Must no sign with none") + return nil + } + } +} diff --git a/Pods/OAuthSwift/Sources/Int+OAuthSwift.swift b/Pods/OAuthSwift/Sources/Int+OAuthSwift.swift new file mode 100644 index 0000000000..022aff2564 --- /dev/null +++ b/Pods/OAuthSwift/Sources/Int+OAuthSwift.swift @@ -0,0 +1,33 @@ +// +// Int+OAuthSwift.swift +// OAuthSwift +// +// Created by Dongri Jin on 1/28/15. +// Copyright (c) 2015 Dongri Jin. All rights reserved. +// + +import Foundation + +extension Int { + public func bytes(_ totalBytes: Int = MemoryLayout.size) -> [UInt8] { + return arrayOfBytes(self, length: totalBytes) + } +} + +private func arrayOfBytes(_ value: T, length: Int? = nil) -> [UInt8] { + let totalBytes = length ?? MemoryLayout.size + + let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) + valuePointer.pointee = value + + let bytesPointer = UnsafeMutablePointer(OpaquePointer(valuePointer)) + var bytes = [UInt8](repeating: 0, count: totalBytes) + for j in 0...size, totalBytes) { + bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee + } + + valuePointer.deinitialize(count: 1) + valuePointer.deallocate() + + return bytes +} diff --git a/Pods/OAuthSwift/Sources/NSError+OAuthSwift.swift b/Pods/OAuthSwift/Sources/NSError+OAuthSwift.swift new file mode 100644 index 0000000000..dc31919730 --- /dev/null +++ b/Pods/OAuthSwift/Sources/NSError+OAuthSwift.swift @@ -0,0 +1,70 @@ +// +// NSError+OAuthSwift.swift +// OAuthSwift +// +// Created by Goessler, Florian on 04/04/16. +// Copyright © 2016 Dongri Jin. All rights reserved. +// + +import Foundation + +public extension NSError { + + /// Checks the headers contained in the userInfo whether this error was caused by an + /// expired/invalid access token. + /// + /// Criteria for invalid token error: WWW-Authenticate header contains a field "error" with + /// value "invalid_token". + /// + /// Also implements a special handling for the Facebook API, which indicates invalid tokens in a + /// different manner. See https://developers.facebook.com/docs/graph-api/using-graph-api#errors + public var isExpiredToken: Bool { + guard self.domain == NSURLErrorDomain else { + return false + } + if self.code == 401 { + if let reponseHeaders = self.userInfo["Response-Headers"] as? [String: String], + let authenticateHeader = reponseHeaders["WWW-Authenticate"] ?? reponseHeaders["Www-Authenticate"] { + let headerDictionary = authenticateHeader.headerDictionary + if let error = headerDictionary["error"], error == "invalid_token" || error == "\"invalid_token\"" { + return true + } + } + if let body = self.userInfo["Response-Body"] as? String, + let bodyData = body.data(using: OAuthSwiftDataEncoding), + let json = try? JSONSerialization.jsonObject(with: bodyData, options: []), + let jsonDic = json as? [String: AnyObject] { + if let error = jsonDic["error"] as? String, error == "invalid_token" || error == "\"invalid_token\"" { + return true + } + if let errors = jsonDic["errors"] as? [[String: AnyObject]] { + for error in errors { + if let errorType = error["errorType"] as? String, errorType == "invalid_token" { + return true + } + } + } + } + } + + // Detect access token expiration errors from facebook + // Docu: https://developers.facebook.com/docs/graph-api/using-graph-api#errors + if self.code == 400 { + if let urlString = self.userInfo[NSURLErrorFailingURLErrorKey] as? String, urlString.contains("graph.facebook.com") { + if let body = self.userInfo["Response-Body"] as? String, + let bodyData = body.data(using: OAuthSwiftDataEncoding), + let json = try? JSONSerialization.jsonObject(with: bodyData, options: []), + let jsonDic = json as? [String: AnyObject] { + let errorCode = jsonDic["error"]?["code"] as? Int + let errorSubCode = jsonDic["error"]?["error_subcode"] as? Int + if (errorCode == 102 && errorSubCode == nil) || errorSubCode == 463 || errorSubCode == 467 { + return true + } + } + } + } + + return false + } + +} diff --git a/Pods/OAuthSwift/Sources/NotificationCenter+OAuthSwift.swift b/Pods/OAuthSwift/Sources/NotificationCenter+OAuthSwift.swift new file mode 100644 index 0000000000..2c5649b9e4 --- /dev/null +++ b/Pods/OAuthSwift/Sources/NotificationCenter+OAuthSwift.swift @@ -0,0 +1,13 @@ +// +// NotificationCenter+OAuthSwift.swift +// OAuthSwift +// +// Created by hiragram on 2017/04/04. +// Copyright © 2017年 Dongri Jin. All rights reserved. +// + +import Foundation + +public extension Notification.Name { + public static let OAuthSwiftHandleCallbackURL: Notification.Name = .init("OAuthSwiftCallbackNotificationName") +} diff --git a/Pods/OAuthSwift/Sources/OAuth1Swift.swift b/Pods/OAuthSwift/Sources/OAuth1Swift.swift new file mode 100644 index 0000000000..7e3f0f2a76 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuth1Swift.swift @@ -0,0 +1,177 @@ +// +// OAuth1Swift.swift +// OAuthSwift +// +// Created by Dongri Jin on 6/22/14. +// Copyright (c) 2014 Dongri Jin. All rights reserved. +// + +import Foundation + +open class OAuth1Swift: OAuthSwift { + + /// If your oauth provider doesn't provide `oauth_verifier` + /// set this value to true (default: false) + open var allowMissingOAuthVerifier: Bool = false + + /// Optionally add callback URL to authorize Url (default: false) + open var addCallbackURLToAuthorizeURL: Bool = false + + var consumerKey: String + var consumerSecret: String + var requestTokenUrl: String + var authorizeUrl: String + var accessTokenUrl: String + + // MARK: init + public init(consumerKey: String, consumerSecret: String, requestTokenUrl: String, authorizeUrl: String, accessTokenUrl: String) { + self.consumerKey = consumerKey + self.consumerSecret = consumerSecret + self.requestTokenUrl = requestTokenUrl + self.authorizeUrl = authorizeUrl + self.accessTokenUrl = accessTokenUrl + super.init(consumerKey: consumerKey, consumerSecret: consumerSecret) + self.client.credential.version = .oauth1 + } + + public convenience override init(consumerKey: String, consumerSecret: String) { + self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, requestTokenUrl: "", authorizeUrl: "", accessTokenUrl: "") + } + + public convenience init?(parameters: ConfigParameters) { + guard let consumerKey = parameters["consumerKey"], let consumerSecret = parameters["consumerSecret"], + let requestTokenUrl = parameters["requestTokenUrl"], let authorizeUrl = parameters["authorizeUrl"], let accessTokenUrl = parameters["accessTokenUrl"] else { + return nil + } + self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, + requestTokenUrl: requestTokenUrl, + authorizeUrl: authorizeUrl, + accessTokenUrl: accessTokenUrl) + } + + open var parameters: ConfigParameters { + return [ + "consumerKey": consumerKey, + "consumerSecret": consumerSecret, + "requestTokenUrl": requestTokenUrl, + "authorizeUrl": authorizeUrl, + "accessTokenUrl": accessTokenUrl + ] + } + + // MARK: functions + // 0. Start + @discardableResult + open func authorize(withCallbackURL callbackURL: URL, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? { + + self.postOAuthRequestToken(callbackURL: callbackURL, success: { [unowned self] credential, _, _ in + + self.observeCallback { [weak self] url in + guard let this = self else { OAuthSwift.retainError(failure); return } + var responseParameters = [String: String]() + if let query = url.query { + responseParameters += query.parametersFromQueryString + } + if let fragment = url.fragment, !fragment.isEmpty { + responseParameters += fragment.parametersFromQueryString + } + if let token = responseParameters["token"] { + responseParameters["oauth_token"] = token + } + + if let token = responseParameters["oauth_token"], !token.isEmpty { + this.client.credential.oauthToken = token.safeStringByRemovingPercentEncoding + if let oauth_verifier = responseParameters["oauth_verifier"] { + this.client.credential.oauthVerifier = oauth_verifier.safeStringByRemovingPercentEncoding + } else { + if !this.allowMissingOAuthVerifier { + failure?(OAuthSwiftError.configurationError(message: "Missing oauth_verifier. Maybe use allowMissingOAuthVerifier=true")) + return + } + } + this.postOAuthAccessTokenWithRequestToken(success: success, failure: failure) + } else { + failure?(OAuthSwiftError.missingToken) + return + } + } + // 2. Authorize + if let token = credential.oauthToken.urlQueryEncoded { + var urlString = self.authorizeUrl + (self.authorizeUrl.contains("?") ? "&" : "?") + urlString += "oauth_token=\(token)" + if self.addCallbackURLToAuthorizeURL { + urlString += "&oauth_callback=\(callbackURL.absoluteString)" + } + if let queryURL = URL(string: urlString) { + self.authorizeURLHandler.handle(queryURL) + } else { + failure?(OAuthSwiftError.encodingError(urlString: urlString)) + } + } else { + failure?(OAuthSwiftError.encodingError(urlString: credential.oauthToken)) //TODO specific error + } + + }, failure: failure) + + return self + } + + @discardableResult + open func authorize(withCallbackURL urlString: String, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? { + guard let url = URL(string: urlString) else { + failure?(OAuthSwiftError.encodingError(urlString: urlString)) + return nil + } + return authorize(withCallbackURL: url, success: success, failure: failure) + } + + // 1. Request token + func postOAuthRequestToken(callbackURL: URL, success: @escaping TokenSuccessHandler, failure: FailureHandler?) { + var parameters = [String: Any]() + parameters["oauth_callback"] = callbackURL.absoluteString + + if let handle = self.client.post( + self.requestTokenUrl, parameters: parameters, + success: { [weak self] response in + guard let this = self else { OAuthSwift.retainError(failure); return } + let parameters = response.string?.parametersFromQueryString ?? [:] + if let oauthToken = parameters["oauth_token"] { + this.client.credential.oauthToken = oauthToken.safeStringByRemovingPercentEncoding + } + if let oauthTokenSecret=parameters["oauth_token_secret"] { + this.client.credential.oauthTokenSecret = oauthTokenSecret.safeStringByRemovingPercentEncoding + } + success(this.client.credential, response, parameters) + }, failure: failure + ) { + self.putHandle(handle, withKey: UUID().uuidString) + } + } + + // 3. Get Access token + func postOAuthAccessTokenWithRequestToken(success: @escaping TokenSuccessHandler, failure: FailureHandler?) { + var parameters = [String: Any]() + parameters["oauth_token"] = self.client.credential.oauthToken + if !self.allowMissingOAuthVerifier { + parameters["oauth_verifier"] = self.client.credential.oauthVerifier + } + + if let handle = self.client.post( + self.accessTokenUrl, parameters: parameters, + success: { [weak self] response in + guard let this = self else { OAuthSwift.retainError(failure); return } + let parameters = response.string?.parametersFromQueryString ?? [:] + if let oauthToken = parameters["oauth_token"] { + this.client.credential.oauthToken = oauthToken.safeStringByRemovingPercentEncoding + } + if let oauthTokenSecret = parameters["oauth_token_secret"] { + this.client.credential.oauthTokenSecret = oauthTokenSecret.safeStringByRemovingPercentEncoding + } + success(this.client.credential, response, parameters) + }, failure: failure + ) { + self.putHandle(handle, withKey: UUID().uuidString) + } + } + +} diff --git a/Pods/OAuthSwift/Sources/OAuth2Swift.swift b/Pods/OAuthSwift/Sources/OAuth2Swift.swift new file mode 100644 index 0000000000..8cbb6240a5 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuth2Swift.swift @@ -0,0 +1,341 @@ +// +// OAuth2Swift.swift +// OAuthSwift +// +// Created by Dongri Jin on 6/22/14. +// Copyright (c) 2014 Dongri Jin. All rights reserved. +// + +import Foundation + +open class OAuth2Swift: OAuthSwift { + + /// If your oauth provider need to use basic authentification + /// set value to true (default: false) + open var accessTokenBasicAuthentification = false + + /// Set to true to deactivate state check. Be careful of CSRF + open var allowMissingStateCheck: Bool = false + + /// Encode callback url, some services require it to be encoded. + open var encodeCallbackURL: Bool = false + + /// Encode callback url inside the query, this is second encoding phase when the entire query string gets assembled. In rare + /// cases, like with Imgur, the url needs to be encoded only once and this value needs to be set to `false`. + open var encodeCallbackURLQuery: Bool = true + + var consumerKey: String + var consumerSecret: String + var authorizeUrl: String + var accessTokenUrl: String? + var responseType: String + var contentType: String? + + // MARK: init + public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String) { + self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType) + self.accessTokenUrl = accessTokenUrl + } + + public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String, contentType: String) { + self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType) + self.accessTokenUrl = accessTokenUrl + self.contentType = contentType + } + + public init(consumerKey: String, consumerSecret: String, authorizeUrl: String, responseType: String) { + self.consumerKey = consumerKey + self.consumerSecret = consumerSecret + self.authorizeUrl = authorizeUrl + self.responseType = responseType + super.init(consumerKey: consumerKey, consumerSecret: consumerSecret) + self.client.credential.version = .oauth2 + } + + public convenience init?(parameters: ConfigParameters) { + guard let consumerKey = parameters["consumerKey"], let consumerSecret = parameters["consumerSecret"], + let responseType = parameters["responseType"], let authorizeUrl = parameters["authorizeUrl"] else { + return nil + } + if let accessTokenUrl = parameters["accessTokenUrl"] { + self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, + authorizeUrl: authorizeUrl, accessTokenUrl: accessTokenUrl, responseType: responseType) + } else { + self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, + authorizeUrl: authorizeUrl, responseType: responseType) + } + } + + open var parameters: ConfigParameters { + return [ + "consumerKey": consumerKey, + "consumerSecret": consumerSecret, + "authorizeUrl": authorizeUrl, + "accessTokenUrl": accessTokenUrl ?? "", + "responseType": responseType + ] + } + + // MARK: functions + @discardableResult + open func authorize(withCallbackURL callbackURL: URL?, scope: String, state: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? { + + self.observeCallback { [weak self] url in + guard let this = self else { + OAuthSwift.retainError(failure) + return + } + var responseParameters = [String: String]() + if let query = url.query { + responseParameters += query.parametersFromQueryString + } + if let fragment = url.fragment, !fragment.isEmpty { + responseParameters += fragment.parametersFromQueryString + } + if let accessToken = responseParameters["access_token"] { + this.client.credential.oauthToken = accessToken.safeStringByRemovingPercentEncoding + if let expiresIn: String = responseParameters["expires_in"], let offset = Double(expiresIn) { + this.client.credential.oauthTokenExpiresAt = Date(timeInterval: offset, since: Date()) + } + success(this.client.credential, nil, responseParameters) + } else if let code = responseParameters["code"] { + if !this.allowMissingStateCheck { + guard let responseState = responseParameters["state"] else { + failure?(OAuthSwiftError.missingState) + return + } + if responseState != state { + failure?(OAuthSwiftError.stateNotEqual(state: state, responseState: responseState)) + return + } + } + let callbackURLEncoded: URL? + if let callbackURL = callbackURL { + callbackURLEncoded = URL(string: callbackURL.absoluteString.urlEncoded)! + } else { + callbackURLEncoded = nil + } + if let handle = this.postOAuthAccessTokenWithRequestToken( + byCode: code.safeStringByRemovingPercentEncoding, + callbackURL: callbackURLEncoded, headers: headers, success: success, failure: failure) { + this.putHandle(handle, withKey: UUID().uuidString) + } + } else if let error = responseParameters["error"] { + let description = responseParameters["error_description"] ?? "" + let message = NSLocalizedString(error, comment: description) + failure?(OAuthSwiftError.serverError(message: message)) + } else { + let message = "No access_token, no code and no error provided by server" + failure?(OAuthSwiftError.serverError(message: message)) + } + } + + var queryErrorString = "" + let encodeError: (String, String) -> Void = { name, value in + if let newQuery = queryErrorString.urlQueryByAppending(parameter: name, value: value, encode: false) { + queryErrorString = newQuery + } + } + + var queryString: String? = "" + queryString = queryString?.urlQueryByAppending(parameter: "client_id", value: self.consumerKey, encodeError) + if let callbackURL = callbackURL { + queryString = queryString?.urlQueryByAppending(parameter: "redirect_uri", value: self.encodeCallbackURL ? callbackURL.absoluteString.urlEncoded : callbackURL.absoluteString, encode: self.encodeCallbackURLQuery, encodeError) + } + queryString = queryString?.urlQueryByAppending(parameter: "response_type", value: self.responseType, encodeError) + queryString = queryString?.urlQueryByAppending(parameter: "scope", value: scope, encodeError) + queryString = queryString?.urlQueryByAppending(parameter: "state", value: state, encodeError) + + for (name, value) in parameters { + queryString = queryString?.urlQueryByAppending(parameter: name, value: "\(value)", encodeError) + } + + if let queryString = queryString { + let urlString = self.authorizeUrl.urlByAppending(query: queryString) + if let url: URL = URL(string: urlString) { + self.authorizeURLHandler.handle(url) + return self + } else { + failure?(OAuthSwiftError.encodingError(urlString: urlString)) + } + } else { + let urlString = self.authorizeUrl.urlByAppending(query: queryErrorString) + failure?(OAuthSwiftError.encodingError(urlString: urlString)) + } + self.cancel() // ie. remove the observer. + return nil + } + + @discardableResult + open func authorize(withCallbackURL urlString: String, scope: String, state: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? { + guard let url = URL(string: urlString) else { + failure?(OAuthSwiftError.encodingError(urlString: urlString)) + return nil + } + return authorize(withCallbackURL: url, scope: scope, state: state, parameters: parameters, headers: headers, success: success, failure: failure) + } + + open func postOAuthAccessTokenWithRequestToken(byCode code: String, callbackURL: URL?, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? { + var parameters = OAuthSwift.Parameters() + parameters["client_id"] = self.consumerKey + parameters["client_secret"] = self.consumerSecret + parameters["code"] = code + parameters["grant_type"] = "authorization_code" + if let callbackURL = callbackURL { + parameters["redirect_uri"] = callbackURL.absoluteString.safeStringByRemovingPercentEncoding + } + + return requestOAuthAccessToken(withParameters: parameters, headers: headers, success: success, failure: failure) + } + + @discardableResult + open func renewAccessToken(withRefreshToken refreshToken: String, parameters: OAuthSwift.Parameters? = nil, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? { + var parameters = parameters ?? OAuthSwift.Parameters() + parameters["client_id"] = self.consumerKey + parameters["client_secret"] = self.consumerSecret + parameters["refresh_token"] = refreshToken + parameters["grant_type"] = "refresh_token" + + return requestOAuthAccessToken(withParameters: parameters, headers: headers, success: success, failure: failure) + } + + fileprivate func requestOAuthAccessToken(withParameters parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? { + let successHandler: OAuthSwiftHTTPRequest.SuccessHandler = { [weak self] response in + guard let this = self else { + OAuthSwift.retainError(failure) + return + } + let responseJSON: Any? = try? response.jsonObject(options: .mutableContainers) + + let responseParameters: OAuthSwift.Parameters + + if let jsonDico = responseJSON as? [String: Any] { + responseParameters = jsonDico + } else { + responseParameters = response.string?.parametersFromQueryString ?? [:] + } + + guard let accessToken = responseParameters["access_token"] as? String else { + let message = NSLocalizedString("Could not get Access Token", comment: "Due to an error in the OAuth2 process, we couldn't get a valid token.") + failure?(OAuthSwiftError.serverError(message: message)) + return + } + + if let refreshToken = responseParameters["refresh_token"] as? String { + this.client.credential.oauthRefreshToken = refreshToken.safeStringByRemovingPercentEncoding + } + + if let expiresIn = responseParameters["expires_in"] as? String, let offset = Double(expiresIn) { + this.client.credential.oauthTokenExpiresAt = Date(timeInterval: offset, since: Date()) + } else if let expiresIn = responseParameters["expires_in"] as? Double { + this.client.credential.oauthTokenExpiresAt = Date(timeInterval: expiresIn, since: Date()) + } + + this.client.credential.oauthToken = accessToken.safeStringByRemovingPercentEncoding + success(this.client.credential, response, responseParameters) + } + + guard let accessTokenUrl = accessTokenUrl else { + let message = NSLocalizedString("access token url not defined", comment: "access token url not defined with code type auth") + failure?(OAuthSwiftError.configurationError(message: message)) + return nil + } + + if self.contentType == "multipart/form-data" { + // Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token. + return self.client.postMultiPartRequest(accessTokenUrl, method: .POST, parameters: parameters, headers: headers, checkTokenExpiration: false, success: successHandler, failure: failure) + } else { + // special headers + var finalHeaders: OAuthSwift.Headers? = headers + if accessTokenBasicAuthentification { + + let authentification = "\(self.consumerKey):\(self.consumerSecret)".data(using: String.Encoding.utf8) + if let base64Encoded = authentification?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) { + finalHeaders += ["Authorization": "Basic \(base64Encoded)"] as OAuthSwift.Headers + } + } + + // Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token. + return self.client.request(accessTokenUrl, method: .POST, parameters: parameters, headers: finalHeaders, checkTokenExpiration: false, success: successHandler, failure: failure) + } + } + + /** + Convenience method to start a request that must be authorized with the previously retrieved access token. + Since OAuth 2 requires support for the access token refresh mechanism, this method will take care to automatically + refresh the token if needed such that the developer only has to be concerned about the outcome of the request. + + - parameter url: The url for the request. + - parameter method: The HTTP method to use. + - parameter parameters: The request's parameters. + - parameter headers: The request's headers. + - parameter renewHeaders: The request's headers if renewing. If nil, the `headers`` are used when renewing. + - parameter body: The request's HTTP body. + - parameter onTokenRenewal: Optional callback triggered in case the access token renewal was required in order to properly authorize the request. + - parameter success: The success block. Takes the successfull response and data as parameter. + - parameter failure: The failure block. Takes the error as parameter. + */ + @discardableResult + open func startAuthorizedRequest(_ url: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, renewHeaders: OAuthSwift.Headers? = nil, body: Data? = nil, onTokenRenewal: TokenRenewedHandler? = nil, success: @escaping OAuthSwiftHTTPRequest.SuccessHandler, failure: @escaping OAuthSwiftHTTPRequest.FailureHandler) -> OAuthSwiftRequestHandle? { + // build request + return self.client.request(url, method: method, parameters: parameters, headers: headers, body: body, success: success) { (error) in + switch error { + + case OAuthSwiftError.tokenExpired: + _ = self.renewAccessToken(withRefreshToken: self.client.credential.oauthRefreshToken, headers: renewHeaders ?? headers, success: { (credential, _, _) in + // Ommit response parameters so they don't override the original ones + // We have successfully renewed the access token. + + // If provided, fire the onRenewal closure + if let renewalCallBack = onTokenRenewal { + renewalCallBack(credential) + } + + // Reauthorize the request again, this time with a brand new access token ready to be used. + _ = self.startAuthorizedRequest(url, method: method, parameters: parameters, headers: headers, body: body, onTokenRenewal: onTokenRenewal, success: success, failure: failure) + }, failure: failure) + default: + failure(error) + } + } + } + + // OAuth 2.0 Specification: https://tools.ietf.org/html/draft-ietf-oauth-v2-13#section-4.3 + @discardableResult + open func authorize(username: String, password: String, scope: String?, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: @escaping OAuthSwiftHTTPRequest.FailureHandler) -> OAuthSwiftRequestHandle? { + + var parameters = OAuthSwift.Parameters() + parameters["client_id"] = self.consumerKey + parameters["client_secret"] = self.consumerSecret + parameters["username"] = username + parameters["password"] = password + parameters["grant_type"] = "password" + + if let scope = scope { + parameters["scope"] = scope + } + + return requestOAuthAccessToken( + withParameters: parameters, + headers: headers, + success: success, + failure: failure + ) + } + + @discardableResult + open func authorize(deviceToken deviceCode: String, grantType: String = "http://oauth.net/grant_type/device/1.0", success: @escaping TokenSuccessHandler, failure: @escaping OAuthSwiftHTTPRequest.FailureHandler) -> OAuthSwiftRequestHandle? { + var parameters = OAuthSwift.Parameters() + parameters["client_id"] = self.consumerKey + parameters["client_secret"] = self.consumerSecret + parameters["code"] = deviceCode + parameters["grant_type"] = grantType + + return requestOAuthAccessToken( + withParameters: parameters, + success: success, + failure: failure + ) + } + +} diff --git a/Pods/OAuthSwift/Sources/OAuthSwift.swift b/Pods/OAuthSwift/Sources/OAuthSwift.swift new file mode 100644 index 0000000000..b0c379aff3 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuthSwift.swift @@ -0,0 +1,110 @@ +// +// OAuthSwift.swift +// OAuthSwift +// +// Created by phimage on 04/12/15. +// Copyright © 2015 Dongri Jin. All rights reserved. +// + +import Foundation + +open class OAuthSwift: NSObject, OAuthSwiftRequestHandle { + + // MARK: Properties + + /// Client to make signed request + open var client: OAuthSwiftClient + /// Version of the protocol + open var version: OAuthSwiftCredential.Version { return self.client.credential.version } + + /// Handle the authorize url into a web view or browser + open var authorizeURLHandler: OAuthSwiftURLHandlerType = OAuthSwiftOpenURLExternally.sharedInstance + + fileprivate var currentRequests: [String: OAuthSwiftRequestHandle] = [:] + + // MARK: init + init(consumerKey: String, consumerSecret: String) { + self.client = OAuthSwiftClient(consumerKey: consumerKey, consumerSecret: consumerSecret) + } + + // MARK: callback notification + struct CallbackNotification { + @available(*, deprecated: 0.5, message: "Use Notification.Name.OAuthSwiftHandleCallbackURL") + static let notificationName = Notification.Name(rawValue: "OAuthSwiftCallbackNotificationName") + static let optionsURLKey = "OAuthSwiftCallbackNotificationOptionsURLKey" + } + + /// Handle callback url which contains now token information + open class func handle(url: URL) { + let notification = Notification(name: NSNotification.Name.OAuthSwiftHandleCallbackURL, object: nil, + userInfo: [CallbackNotification.optionsURLKey: url]) + notificationCenter.post(notification) + } + + var observer: NSObjectProtocol? + open class var notificationCenter: NotificationCenter { + return NotificationCenter.default + } + open class var notificationQueue: OperationQueue { + return OperationQueue.main + } + + func observeCallback(_ block: @escaping (_ url: URL) -> Void) { + self.observer = OAuthSwift.notificationCenter.addObserver(forName: NSNotification.Name.OAuthSwiftHandleCallbackURL, object: nil, queue: OperationQueue.main) { [weak self] notification in + self?.removeCallbackNotificationObserver() + + if let urlFromUserInfo = notification.userInfo?[CallbackNotification.optionsURLKey] as? URL { + block(urlFromUserInfo) + } else { + // Internal error + assertionFailure() + } + } + } + + /// Remove internal observer on authentification + public func removeCallbackNotificationObserver() { + if let observer = self.observer { + OAuthSwift.notificationCenter.removeObserver(observer) + } + } + + /// Function to call when web view is dismissed without authentification + public func cancel() { + self.removeCallbackNotificationObserver() + for (_, request) in self.currentRequests { + request.cancel() + } + self.currentRequests = [:] + } + + func putHandle(_ handle: OAuthSwiftRequestHandle, withKey key: String) { + // self.currentRequests[withKey] = handle + // TODO before storing handle, find a way to remove it when network request end (ie. all failure and success ie. complete) + } + + /// Run block in main thread + static func main(block: @escaping () -> Void) { + if Thread.isMainThread { + block() + } else { + DispatchQueue.main.async { + block() + } + } + } + +} + +// MARK: - alias +extension OAuthSwift { + + public typealias Parameters = [String: Any] + public typealias Headers = [String: String] + public typealias ConfigParameters = [String: String] + /// MARK: callback alias + public typealias TokenSuccess = (credential: OAuthSwiftCredential, response: OAuthSwiftResponse?, parameters: Parameters) + public typealias TokenSuccessHandler = (_ credential: OAuthSwiftCredential, _ response: OAuthSwiftResponse?, _ parameters: Parameters) -> Void + public typealias FailureHandler = (_ error: OAuthSwiftError) -> Void + public typealias TokenRenewedHandler = (_ credential: OAuthSwiftCredential) -> Void +} diff --git a/Pods/OAuthSwift/Sources/OAuthSwiftClient.swift b/Pods/OAuthSwift/Sources/OAuthSwiftClient.swift new file mode 100644 index 0000000000..215ca639a1 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuthSwiftClient.swift @@ -0,0 +1,194 @@ +// +// OAuthSwiftClient.swift +// OAuthSwift +// +// Created by Dongri Jin on 6/21/14. +// Copyright (c) 2014 Dongri Jin. All rights reserved. +// + +import Foundation + +public var OAuthSwiftDataEncoding: String.Encoding = .utf8 + +@objc public protocol OAuthSwiftRequestHandle { + func cancel() +} + +open class OAuthSwiftClient: NSObject { + + fileprivate(set) open var credential: OAuthSwiftCredential + open var paramsLocation: OAuthSwiftHTTPRequest.ParamsLocation = .authorizationHeader + /// Contains default URL session configuration + open var sessionFactory = URLSessionFactory() + + static let separator: String = "\r\n" + static var separatorData: Data = { + return OAuthSwiftClient.separator.data(using: OAuthSwiftDataEncoding)! + }() + + // MARK: init + public init(credential: OAuthSwiftCredential) { + self.credential = credential + } + + public convenience init(consumerKey: String, consumerSecret: String, version: OAuthSwiftCredential.Version = .oauth1) { + let credential = OAuthSwiftCredential(consumerKey: consumerKey, consumerSecret: consumerSecret) + credential.version = version + self.init(credential: credential) + } + + public convenience init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String, version: OAuthSwiftCredential.Version) { + self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, version: version) + self.credential.oauthToken = oauthToken + self.credential.oauthTokenSecret = oauthTokenSecret + } + + // MARK: client methods + @discardableResult + open func get(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .GET, parameters: parameters, headers: headers, success: success, failure: failure) + } + + @discardableResult + open func post(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .POST, parameters: parameters, headers: headers, body: body, success: success, failure: failure) + } + + @discardableResult + open func put(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .PUT, parameters: parameters, headers: headers, body: body, success: success, failure: failure) + } + + @discardableResult + open func delete(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .DELETE, parameters: parameters, headers: headers, success: success, failure: failure) + } + + @discardableResult + open func patch(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .PATCH, parameters: parameters, headers: headers, success: success, failure: failure) + } + + @discardableResult + open func request(_ urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, checkTokenExpiration: Bool = true, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { + + if checkTokenExpiration && self.credential.isTokenExpired() { + failure?(OAuthSwiftError.tokenExpired(error: nil)) + return nil + } + + guard URL(string: urlString) != nil else { + failure?(OAuthSwiftError.encodingError(urlString: urlString)) + return nil + } + + if let request = makeRequest(urlString, method: method, parameters: parameters, headers: headers, body: body) { + request.start(success: success, failure: failure) + return request + } + return nil + } + + open func makeRequest(_ request: URLRequest) -> OAuthSwiftHTTPRequest { + let request = OAuthSwiftHTTPRequest(request: request, paramsLocation: self.paramsLocation, sessionFactory: self.sessionFactory) + request.config.updateRequest(credential: self.credential) + return request + } + + open func makeRequest(_ urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil) -> OAuthSwiftHTTPRequest? { + guard let url = URL(string: urlString) else { + return nil + } + + let request = OAuthSwiftHTTPRequest(url: url, method: method, parameters: parameters, paramsLocation: self.paramsLocation, httpBody: body, headers: headers ?? [:], sessionFactory: self.sessionFactory) + request.config.updateRequest(credential: self.credential) + return request + } + + @discardableResult + public func postImage(_ urlString: String, parameters: OAuthSwift.Parameters, image: Data, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.multiPartRequest(url: urlString, method: .POST, parameters: parameters, image: image, success: success, failure: failure) + } + + open func makeMultiPartRequest(_ urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], multiparts: [OAuthSwiftMultipartData] = [], headers: OAuthSwift.Headers? = nil) -> OAuthSwiftHTTPRequest? { + let boundary = "AS-boundary-\(arc4random())-\(arc4random())" + let type = "multipart/form-data; boundary=\(boundary)" + let body = self.multiDataFromObject(parameters, multiparts: multiparts, boundary: boundary) + + var finalHeaders = [kHTTPHeaderContentType: type] + finalHeaders += headers ?? [:] + + return makeRequest(urlString, method: method, parameters: parameters, headers: finalHeaders, body: body) + } + + func multiPartRequest(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, image: Data, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { + let multiparts = [ OAuthSwiftMultipartData(name: "media", data: image, fileName: "file", mimeType: "image/jpeg") ] + + if let request = makeMultiPartRequest(url, method: method, parameters: parameters, multiparts: multiparts) { + request.start(success: success, failure: failure) + return request + } + + return nil + } + + open func multiPartBody(from inputParameters: OAuthSwift.Parameters, boundary: String) -> Data { + var parameters = OAuthSwift.Parameters() + var multiparts = [OAuthSwiftMultipartData]() + + for (key, value) in inputParameters { + if let data = value as? Data, key == "media" { + let sectionType = "image/jpeg" + let sectionFilename = "file" + multiparts.append(OAuthSwiftMultipartData(name: key, data: data, fileName: sectionFilename, mimeType: sectionType)) + } else { + parameters[key] = value + } + } + + return multiDataFromObject(parameters, multiparts: multiparts, boundary: boundary) + } + + @discardableResult + open func postMultiPartRequest(_ url: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, multiparts: [OAuthSwiftMultipartData] = [], checkTokenExpiration: Bool = true, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { + + if checkTokenExpiration && self.credential.isTokenExpired() { + failure?(OAuthSwiftError.tokenExpired(error: nil)) + return nil + } + + if let request = makeMultiPartRequest(url, method: method, parameters: parameters, multiparts: multiparts, headers: headers) { + request.start(success: success, failure: failure) + return request + } + return nil + } + + func multiDataFromObject(_ object: OAuthSwift.Parameters, multiparts: [OAuthSwiftMultipartData], boundary: String) -> Data { + var data = Data() + + let prefixString = "--\(boundary)\r\n" + let prefixData = prefixString.data(using: OAuthSwiftDataEncoding)! + + for (key, value) in object { + guard let valueData = "\(value)".data(using: OAuthSwiftDataEncoding) else { + continue + } + data.append(prefixData) + let multipartData = OAuthSwiftMultipartData(name: key, data: valueData, fileName: nil, mimeType: nil) + data.append(multipartData, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData) + } + + for multipart in multiparts { + data.append(prefixData) + data.append(multipart, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData) + } + + let endingString = "--\(boundary)--\r\n" + let endingData = endingString.data(using: OAuthSwiftDataEncoding)! + data.append(endingData) + + return data + } + +} diff --git a/Pods/OAuthSwift/Sources/OAuthSwiftCredential.swift b/Pods/OAuthSwift/Sources/OAuthSwiftCredential.swift new file mode 100644 index 0000000000..ad812600d0 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuthSwiftCredential.swift @@ -0,0 +1,428 @@ +// +// OAuthSwiftCredential.swift +// OAuthSwift +// +// Created by Dongri Jin on 6/22/14. +// Copyright (c) 2014 Dongri Jin. All rights reserved. +// +import Foundation + +/// Allow to customize computed headers +public protocol OAuthSwiftCredentialHeadersFactory { + func make(_ url: URL, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, body: Data?) -> [String: String] +} + +/// Allow to sign +// swiftlint:disable:next class_delegate_protocol +public protocol OAuthSwiftSignatureDelegate { + static func sign(hashMethod: OAuthSwiftHashMethod, key: Data, message: Data) -> Data? +} + +// The hash method used. +public enum OAuthSwiftHashMethod: String { + case sha1 + case none + + func hash(data: Data) -> Data? { + switch self { + case .sha1: + let mac = SHA1(data).calculate() + return Data(bytes: UnsafePointer(mac), count: mac.count) + case .none: + return data + } + } +} + +/// The credential for authentification +open class OAuthSwiftCredential: NSObject, NSSecureCoding, Codable { + + public static let supportsSecureCoding = true + + public enum Version: Codable { + case oauth1, oauth2 + + public var shortVersion: String { + switch self { + case .oauth1: + return "1.0" + case .oauth2: + return "2.0" + } + } + + var toInt32: Int32 { + switch self { + case .oauth1: + return 1 + case .oauth2: + return 2 + } + } + + init(_ value: Int32) { + switch value { + case 1: + self = .oauth1 + case 2: + self = .oauth2 + default: + self = .oauth1 + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(self.toInt32) + } + + public init(from decoder: Decoder) throws { + self.init(try decoder.singleValueContainer().decode(Int32.self)) + } + } + + public enum SignatureMethod: String { + case HMAC_SHA1 = "HMAC-SHA1" + case RSA_SHA1 = "RSA-SHA1" + case PLAINTEXT = "PLAINTEXT" + + public static var delegates: [SignatureMethod: OAuthSwiftSignatureDelegate.Type] = + [HMAC_SHA1: HMAC.self] + + var hashMethod: OAuthSwiftHashMethod { + switch self { + case .HMAC_SHA1, .RSA_SHA1: + return .sha1 + case .PLAINTEXT: + return .none + } + } + + func sign(key: Data, message: Data) -> Data? { + if let delegate = SignatureMethod.delegates[self] { + return delegate.sign(hashMethod: self.hashMethod, key: key, message: message) + } + assert(self == .PLAINTEXT, "No signature method installed for \(self)") + return message + } + + } + + // MARK: attributes + open internal(set) var consumerKey = "" + open internal(set) var consumerSecret = "" + open var oauthToken = "" + open var oauthRefreshToken = "" + open var oauthTokenSecret = "" + open var oauthTokenExpiresAt: Date? + open internal(set) var oauthVerifier = "" + open var version: Version = .oauth1 + open var signatureMethod: SignatureMethod = .HMAC_SHA1 + + /// hook to replace headers creation + open var headersFactory: OAuthSwiftCredentialHeadersFactory? + + // MARK: init + override init() { + } + + public init(consumerKey: String, consumerSecret: String) { + self.consumerKey = consumerKey + self.consumerSecret = consumerSecret + } + + // MARK: NSCoding protocol + fileprivate struct NSCodingKeys { + static let bundleId = Bundle.main.bundleIdentifier + ?? Bundle(for: OAuthSwiftCredential.self).bundleIdentifier + ?? "" + static let base = bundleId + "." + static let consumerKey = base + "comsumer_key" + static let consumerSecret = base + "consumer_secret" + static let oauthToken = base + "oauth_token" + static let oauthRefreshToken = base + "oauth_refresh_token" + static let oauthTokenExpiresAt = base + "oauth_token_expires_at" + static let oauthTokenSecret = base + "oauth_token_secret" + static let oauthVerifier = base + "oauth_verifier" + static let version = base + "version" + static let signatureMethod = base + "signatureMethod" + } + + /// Cannot declare a required initializer within an extension. + /// extension OAuthSwiftCredential: NSCoding { + public required convenience init?(coder decoder: NSCoder) { + + guard let consumerKey = decoder + .decodeObject(of: NSString.self, + forKey: NSCodingKeys.consumerKey) as String? else { + if #available(iOS 9, OSX 10.11, *) { + let error = CocoaError.error(.coderValueNotFound) + decoder.failWithError(error) + } + return nil + } + + guard let consumerSecret = decoder + .decodeObject(of: NSString.self, + forKey: NSCodingKeys.consumerSecret) as String? else { + if #available(iOS 9, OSX 10.11, *) { + let error = CocoaError.error(.coderValueNotFound) + decoder.failWithError(error) + } + return nil + } + self.init(consumerKey: consumerKey, consumerSecret: consumerSecret) + + guard let oauthToken = decoder + .decodeObject(of: NSString.self, + forKey: NSCodingKeys.oauthToken) as String? else { + if #available(iOS 9, OSX 10.11, *) { + let error = CocoaError.error(.coderValueNotFound) + decoder.failWithError(error) + } + return nil + } + self.oauthToken = oauthToken + + guard let oauthRefreshToken = decoder + .decodeObject(of: NSString.self, + forKey: NSCodingKeys.oauthRefreshToken) as String? else { + if #available(iOS 9, OSX 10.11, *) { + let error = CocoaError.error(.coderValueNotFound) + decoder.failWithError(error) + } + return nil + } + self.oauthRefreshToken = oauthRefreshToken + + guard let oauthTokenSecret = decoder + .decodeObject(of: NSString.self, + forKey: NSCodingKeys.oauthTokenSecret) as String? else { + if #available(iOS 9, OSX 10.11, *) { + let error = CocoaError.error(.coderValueNotFound) + decoder.failWithError(error) + } + return nil + } + self.oauthTokenSecret = oauthTokenSecret + + guard let oauthVerifier = decoder + .decodeObject(of: NSString.self, + forKey: NSCodingKeys.oauthVerifier) as String? else { + if #available(iOS 9, OSX 10.11, *) { + let error = CocoaError.error(.coderValueNotFound) + decoder.failWithError(error) + } + return nil + } + self.oauthVerifier = oauthVerifier + + self.oauthTokenExpiresAt = decoder + .decodeObject(of: NSDate.self, forKey: NSCodingKeys.oauthTokenExpiresAt) as Date? + self.version = Version(decoder.decodeInt32(forKey: NSCodingKeys.version)) + if case .oauth1 = version { + self.signatureMethod = SignatureMethod(rawValue: (decoder.decodeObject(of: NSString.self, forKey: NSCodingKeys.signatureMethod) as String?) ?? "HMAC_SHA1") ?? .HMAC_SHA1 + } + } + + open func encode(with coder: NSCoder) { + coder.encode(self.consumerKey, forKey: NSCodingKeys.consumerKey) + coder.encode(self.consumerSecret, forKey: NSCodingKeys.consumerSecret) + coder.encode(self.oauthToken, forKey: NSCodingKeys.oauthToken) + coder.encode(self.oauthRefreshToken, forKey: NSCodingKeys.oauthRefreshToken) + coder.encode(self.oauthTokenSecret, forKey: NSCodingKeys.oauthTokenSecret) + coder.encode(self.oauthVerifier, forKey: NSCodingKeys.oauthVerifier) + coder.encode(self.oauthTokenExpiresAt, forKey: NSCodingKeys.oauthTokenExpiresAt) + coder.encode(self.version.toInt32, forKey: NSCodingKeys.version) + if case .oauth1 = version { + coder.encode(self.signatureMethod.rawValue, forKey: NSCodingKeys.signatureMethod) + } + } + // } // End NSCoding extension + + // MARK: Codable protocol + enum CodingKeys: String, CodingKey { + case consumerKey + case consumerSecret + case oauthToken + case oauthRefreshToken + case oauthTokenSecret + case oauthVerifier + case oauthTokenExpiresAt + case version + case signatureMethodRawValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.consumerKey, forKey: .consumerKey) + try container.encode(self.consumerSecret, forKey: .consumerSecret) + try container.encode(self.oauthToken, forKey: .oauthToken) + try container.encode(self.oauthRefreshToken, forKey: .oauthRefreshToken) + try container.encode(self.oauthTokenSecret, forKey: .oauthTokenSecret) + try container.encode(self.oauthVerifier, forKey: .oauthVerifier) + try container.encodeIfPresent(self.oauthTokenExpiresAt, forKey: .oauthTokenExpiresAt) + try container.encode(self.version, forKey: .version) + if case .oauth1 = version { + try container.encode(self.signatureMethod.rawValue, forKey: .signatureMethodRawValue) + } + } + + public required convenience init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.init() + + self.consumerKey = try container.decode(String.self, forKey: .consumerKey) + self.consumerSecret = try container.decode(String.self, forKey: .consumerSecret) + + self.oauthToken = try container.decode(type(of: self.oauthToken), forKey: .oauthToken) + self.oauthRefreshToken = try container.decode(type(of: self.oauthRefreshToken), forKey: .oauthRefreshToken) + self.oauthTokenSecret = try container.decode(type(of: self.oauthTokenSecret), forKey: .oauthTokenSecret) + self.oauthVerifier = try container.decode(type(of: self.oauthVerifier), forKey: .oauthVerifier) + self.oauthTokenExpiresAt = try container.decodeIfPresent(Date.self, forKey: .oauthTokenExpiresAt) + self.version = try container.decode(type(of: self.version), forKey: .version) + + if case .oauth1 = version { + self.signatureMethod = SignatureMethod(rawValue: try container.decode(type(of: self.signatureMethod.rawValue), forKey: .signatureMethodRawValue))! + } + } + + // MARK: functions + /// for OAuth1 parameters must contains sorted query parameters and url must not contains query parameters + open func makeHeaders(_ url: URL, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, body: Data? = nil) -> [String: String] { + if let factory = headersFactory { + return factory.make(url, method: method, parameters: parameters, body: body) + } + switch self.version { + case .oauth1: + return ["Authorization": self.authorizationHeader(method: method, url: url, parameters: parameters, body: body)] + case .oauth2: + return self.oauthToken.isEmpty ? [:] : ["Authorization": "Bearer \(self.oauthToken)"] + } + } + + open func authorizationHeader(method: OAuthSwiftHTTPRequest.Method, url: URL, parameters: OAuthSwift.Parameters, body: Data? = nil) -> String { + let timestamp = String(Int64(Date().timeIntervalSince1970)) + let nonce = OAuthSwiftCredential.generateNonce() + return self.authorizationHeader(method: method, url: url, parameters: parameters, body: body, timestamp: timestamp, nonce: nonce) + } + + open class func generateNonce() -> String { + let uuidString: String = UUID().uuidString + return uuidString[0..<8] + } + + open func authorizationHeader(method: OAuthSwiftHTTPRequest.Method, url: URL, parameters: OAuthSwift.Parameters, body: Data? = nil, timestamp: String, nonce: String) -> String { + assert(self.version == .oauth1) + let authorizationParameters = self.authorizationParametersWithSignature(method: method, url: url, parameters: parameters, body: body, timestamp: timestamp, nonce: nonce) + + var parameterComponents = authorizationParameters.urlEncodedQuery.components(separatedBy: "&") as [String] + parameterComponents.sort { $0 < $1 } + + var headerComponents = [String]() + for component in parameterComponents { + let subcomponent = component.components(separatedBy: "=") as [String] + if subcomponent.count == 2 { + headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"") + } + } + + return "OAuth " + headerComponents.joined(separator: ", ") + } + + open func authorizationParametersWithSignature(method: OAuthSwiftHTTPRequest.Method, url: URL, parameters: OAuthSwift.Parameters, body: Data? = nil) -> OAuthSwift.Parameters { + let timestamp = String(Int64(Date().timeIntervalSince1970)) + let nonce = OAuthSwiftCredential.generateNonce() + return self.authorizationParametersWithSignature(method: method, url: url, parameters: parameters, body: body, timestamp: timestamp, nonce: nonce) + } + + open func authorizationParametersWithSignature(method: OAuthSwiftHTTPRequest.Method, url: URL, parameters: OAuthSwift.Parameters, body: Data? = nil, timestamp: String, nonce: String) -> OAuthSwift.Parameters { + var authorizationParameters = self.authorizationParameters(body, timestamp: timestamp, nonce: nonce) + + for (key, value) in parameters { + if key.hasPrefix("oauth_") { + authorizationParameters.updateValue(value, forKey: key) + } + } + + let combinedParameters = authorizationParameters.join(parameters) + + authorizationParameters["oauth_signature"] = self.signature(method: method, url: url, parameters: combinedParameters) + + return authorizationParameters + } + + open func authorizationParameters(_ body: Data?, timestamp: String, nonce: String) -> OAuthSwift.Parameters { + var authorizationParameters = OAuthSwift.Parameters() + authorizationParameters["oauth_version"] = self.version.shortVersion + authorizationParameters["oauth_signature_method"] = self.signatureMethod.rawValue + authorizationParameters["oauth_consumer_key"] = self.consumerKey + authorizationParameters["oauth_timestamp"] = timestamp + authorizationParameters["oauth_nonce"] = nonce + if let b = body, let hash = self.signatureMethod.hashMethod.hash(data: b) { + authorizationParameters["oauth_body_hash"] = hash.base64EncodedString(options: []) + } + + if !self.oauthToken.isEmpty { + authorizationParameters["oauth_token"] = self.oauthToken + } + return authorizationParameters + } + + open func signature(method: OAuthSwiftHTTPRequest.Method, url: URL, parameters: OAuthSwift.Parameters) -> String { + let encodedTokenSecret = self.oauthTokenSecret.urlEncoded + let encodedConsumerSecret = self.consumerSecret.urlEncoded + + let signingKey = "\(encodedConsumerSecret)&\(encodedTokenSecret)" + + var parameterComponents = parameters.urlEncodedQuery.components(separatedBy: "&") + parameterComponents.sort { + let p0 = $0.components(separatedBy: "=") + let p1 = $1.components(separatedBy: "=") + if p0.first == p1.first { return p0.last ?? "" < p1.last ?? "" } + return p0.first ?? "" < p1.first ?? "" + } + + let parameterString = parameterComponents.joined(separator: "&") + let encodedParameterString = parameterString.urlEncoded + + let encodedURL = url.absoluteString.urlEncoded + + let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)" + + let key = signingKey.data(using: .utf8)! + let msg = signatureBaseString.data(using: .utf8)! + + let sha1 = self.signatureMethod.sign(key: key, message: msg)! + return sha1.base64EncodedString(options: []) + } + + open func isTokenExpired() -> Bool { + if let expiresDate = oauthTokenExpiresAt { + return expiresDate <= Date() + } + + // If no expires date is available we assume the token is still valid since it doesn't have an expiration date to check with. + return false + } + + // MARK: Equatable + + override open func isEqual(_ object: Any?) -> Bool { + guard let rhs = object as? OAuthSwiftCredential else { + return false + } + let lhs = self + return lhs.consumerKey == rhs.consumerKey + && lhs.consumerSecret == rhs.consumerSecret + && lhs.oauthToken == rhs.oauthToken + && lhs.oauthRefreshToken == rhs.oauthRefreshToken + && lhs.oauthTokenSecret == rhs.oauthTokenSecret + && lhs.oauthTokenExpiresAt == rhs.oauthTokenExpiresAt + && lhs.oauthVerifier == rhs.oauthVerifier + && lhs.version == rhs.version + && lhs.signatureMethod == rhs.signatureMethod + } + +} diff --git a/Pods/OAuthSwift/Sources/OAuthSwiftError.swift b/Pods/OAuthSwift/Sources/OAuthSwiftError.swift new file mode 100644 index 0000000000..5e0ba2512b --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuthSwiftError.swift @@ -0,0 +1,153 @@ +// +// OAuthSwiftError.swift +// OAuthSwift +// +// Created by phimage on 02/10/16. +// Copyright © 2016 Dongri Jin. All rights reserved. +// + +import Foundation + +// MARK: - OAuthSwift errors +public enum OAuthSwiftError: Error { + + /// Configuration problem with oauth provider. + case configurationError(message: String) + /// The provided token is expired, retrieve new token by using the refresh token + case tokenExpired(error: Error?) + /// State missing from request (you can set allowMissingStateCheck = true to ignore) + case missingState + /// Returned state value is wrong + case stateNotEqual(state: String, responseState: String) + /// Error from server + case serverError(message: String) + /// Failed to create URL \(urlString) not convertible to URL, please encode + case encodingError(urlString: String) + case authorizationPending + /// Failed to create request with \(urlString) + case requestCreation(message: String) + /// Authentification failed. No token + case missingToken + /// Please retain OAuthSwift object or handle + case retain + /// Request error + case requestError(error: Error, request: URLRequest) + /// Request cancelled + case cancelled + + public static let Domain = "OAuthSwiftError" + public static let ResponseDataKey = "OAuthSwiftError.response.data" + public static let ResponseKey = "OAuthSwiftError.response" + + fileprivate enum Code: Int { + case configurationError = -1 + case tokenExpired = -2 + case missingState = -3 + case stateNotEqual = -4 + case serverError = -5 + case encodingError = -6 + case authorizationPending = -7 + case requestCreation = -8 + case missingToken = -9 + case retain = -10 + case requestError = -11 + case cancelled = -12 + } + + fileprivate var code: Code { + switch self { + case .configurationError: return Code.configurationError + case .tokenExpired: return Code.tokenExpired + case .missingState: return Code.missingState + case .stateNotEqual: return Code.stateNotEqual + case .serverError: return Code.serverError + case .encodingError: return Code.encodingError + case .authorizationPending: return Code.authorizationPending + case .requestCreation: return Code.requestCreation + case .missingToken: return Code.missingToken + case .retain: return Code.retain + case .requestError: return Code.requestError + case .cancelled : return Code.cancelled + } + } + + public var underlyingError: Error? { + switch self { + case .tokenExpired(let e): return e + case .requestError(let e, _): return e + default: return nil + } + } + + public var underlyingMessage: String? { + switch self { + case .serverError(let m): return m + case .configurationError(let m): return m + case .requestCreation(let m): return m + default: return nil + } + } + +} + +extension OAuthSwiftError: CustomStringConvertible { + + public var description: String { + switch self { + case .configurationError(let m): return "configurationError[\(m)]" + case .tokenExpired(let e): return "tokenExpired[\(String(describing: e))]" + case .missingState: return "missingState" + case .stateNotEqual(let s, let e): return "stateNotEqual[\(s)<>\(e)]" + case .serverError(let m): return "serverError[\(m)]" + case .encodingError(let urlString): return "encodingError[\(urlString)]" + case .authorizationPending: return "authorizationPending" + case .requestCreation(let m): return "requestCreation[\(m)]" + case .missingToken: return "missingToken" + case .retain: return "retain" + case .requestError(let e, _): return "requestError[\(e)]" + case .cancelled : return "cancelled" + } + } +} + +extension OAuthSwift { + + static func retainError(_ failureHandler: FailureHandler?) { + #if !OAUTH_NO_RETAIN_ERROR + failureHandler?(OAuthSwiftError.retain) + #endif + } + +} + +// MARK: NSError +extension OAuthSwiftError: CustomNSError { + + public static var errorDomain: String { return OAuthSwiftError.Domain } + + public var errorCode: Int { return self.code.rawValue } + + /// The user-info dictionary. + public var errorUserInfo: [String: Any] { + switch self { + case .configurationError(let m): return ["message": m] + case .serverError(let m): return ["message": m] + case .requestCreation(let m): return ["message": m] + + case .tokenExpired(let e): return ["error": e as Any] + case .requestError(let e, let request): return ["error": e, "request": request] + + case .encodingError(let urlString): return ["url": urlString] + + case .stateNotEqual(let s, let e): return ["state": s, "expected": e] + default: return [:] + } + } + + public var _code: Int { + return self.code.rawValue + } + public var _domain: String { + return OAuthSwiftError.Domain + } +} diff --git a/Pods/OAuthSwift/Sources/OAuthSwiftHTTPRequest.swift b/Pods/OAuthSwift/Sources/OAuthSwiftHTTPRequest.swift new file mode 100644 index 0000000000..417563cea8 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuthSwiftHTTPRequest.swift @@ -0,0 +1,497 @@ +// +// OAuthSwiftHTTPRequest.swift +// OAuthSwift +// +// Created by Dongri Jin on 6/21/14. +// Copyright (c) 2014 Dongri Jin. All rights reserved. +// + +import Foundation + +let kHTTPHeaderContentType = "Content-Type" + +open class OAuthSwiftHTTPRequest: NSObject, OAuthSwiftRequestHandle { + + public typealias SuccessHandler = (_ response: OAuthSwiftResponse) -> Void + public typealias FailureHandler = (_ error: OAuthSwiftError) -> Void + + /// HTTP request method + /// https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods + public enum Method: String { + case GET, POST, PUT, DELETE, PATCH, HEAD //, OPTIONS, TRACE, CONNECT + + var isBody: Bool { + return self == .POST || self == .PUT || self == .PATCH + } + } + + /// Where the additional parameters will be injected + @objc public enum ParamsLocation: Int { + case authorizationHeader, /*FormEncodedBody,*/ requestURIQuery + } + + public var config: Config + + private var request: URLRequest? + private var task: URLSessionTask? + private var session: URLSession! + + fileprivate var cancelRequested = false + + open static var executionContext: (@escaping () -> Void) -> Void = { block in + return DispatchQueue.main.async(execute: block) + } + + // MARK: INIT + + convenience init(url: URL, method: Method = .GET, parameters: OAuthSwift.Parameters = [:], paramsLocation: ParamsLocation = .authorizationHeader, httpBody: Data? = nil, headers: OAuthSwift.Headers = [:], sessionFactory: URLSessionFactory = .default) { + self.init(config: Config(url: url, httpMethod: method, httpBody: httpBody, headers: headers, parameters: parameters, paramsLocation: paramsLocation, sessionFactory: sessionFactory)) + } + + convenience init(request: URLRequest, paramsLocation: ParamsLocation = .authorizationHeader, sessionFactory: URLSessionFactory = .default) { + self.init(config: Config(urlRequest: request, paramsLocation: paramsLocation, sessionFactory: sessionFactory)) + } + + init(config: Config) { + self.config = config + } + + /// START request + func start(success: SuccessHandler?, failure: FailureHandler?) { + guard request == nil else { return } // Don't start the same request twice! + + let successHandler = success + let failureHandler = failure + + do { + self.request = try self.makeRequest() + } catch let error as NSError { + failureHandler?(OAuthSwiftError.requestCreation(message: error.localizedDescription)) + self.request = nil + return + } + + OAuthSwiftHTTPRequest.executionContext { + // perform lock here to prevent cancel calls on another thread while creating the request + objc_sync_enter(self) + defer { objc_sync_exit(self) } + if self.cancelRequested { + return + } + + self.session = self.config.sessionFactory.build() + let usedRequest = self.request! + + if self.config.sessionFactory.useDataTaskClosure { + let completionHandler: (Data?, URLResponse?, Error?) -> Void = { data, resp, error in + OAuthSwiftHTTPRequest.completionHandler(successHandler: success, + failureHandler: failure, + request: usedRequest, + data: data, + resp: resp, + error: error) + } + self.task = self.session.dataTask(with: usedRequest, completionHandler: completionHandler) + } else { + self.task = self.session.dataTask(with: usedRequest) + } + + self.task?.resume() + self.session.finishTasksAndInvalidate() + + #if os(iOS) + #if !OAUTH_APP_EXTENSIONS + UIApplication.shared.isNetworkActivityIndicatorVisible = self.config.sessionFactory.isNetworkActivityIndicatorVisible + #endif + #endif + } + } + + /// Function called when receiving data from server. + public static func completionHandler(successHandler: SuccessHandler?, failureHandler: FailureHandler?, request: URLRequest, data: Data?, resp: URLResponse?, error: Error?) { + #if os(iOS) + #if !OAUTH_APP_EXTENSIONS + UIApplication.shared.isNetworkActivityIndicatorVisible = false + #endif + #endif + + // MARK: failure error returned by server + if let error = error { + var oauthError: OAuthSwiftError = .requestError(error: error, request: request) + let nsError = error as NSError + if nsError.code == NSURLErrorCancelled { + oauthError = .cancelled + } else if nsError.isExpiredToken { + oauthError = .tokenExpired(error: error) + } + + failureHandler?(oauthError) + return + } + + // MARK: failure no response or data returned by server + guard let response = resp as? HTTPURLResponse, let responseData = data else { + let badRequestCode = 400 + let localizedDescription = OAuthSwiftHTTPRequest.descriptionForHTTPStatus(badRequestCode, responseString: "") + var userInfo: [String: Any] = [ + NSLocalizedDescriptionKey: localizedDescription + ] + if let response = resp { // there is only no data + userInfo[OAuthSwiftError.ResponseKey] = response + } + if let response = resp as? HTTPURLResponse { + userInfo["Response-Headers"] = response.allHeaderFields + } + let error = NSError(domain: OAuthSwiftError.Domain, code: badRequestCode, userInfo: userInfo) + failureHandler?(.requestError(error:error, request: request)) + return + } + + // MARK: failure code > 400 + guard response.statusCode < 400 else { + var localizedDescription = String() + let responseString = String(data: responseData, encoding: OAuthSwiftDataEncoding) + + // Try to get error information from data as json + let responseJSON = try? JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) + if let responseJSON = responseJSON as? OAuthSwift.Parameters { + if let code = responseJSON["error"] as? String, let description = responseJSON["error_description"] as? String { + + localizedDescription = NSLocalizedString("\(code) \(description)", comment: "") + if code == "authorization_pending" { + failureHandler?(.authorizationPending) + return + } + } + } else { + localizedDescription = OAuthSwiftHTTPRequest.descriptionForHTTPStatus(response.statusCode, responseString: String(data: responseData, encoding: OAuthSwiftDataEncoding)!) + } + + var userInfo: [String: Any] = [ + NSLocalizedDescriptionKey: localizedDescription, + "Response-Headers": response.allHeaderFields, + OAuthSwiftError.ResponseKey: response, + OAuthSwiftError.ResponseDataKey: responseData + ] + if let string = responseString { + userInfo["Response-Body"] = string + } + if let urlString = response.url?.absoluteString { + userInfo[NSURLErrorFailingURLErrorKey] = urlString + } + + let error = NSError(domain: NSURLErrorDomain, code: response.statusCode, userInfo: userInfo) + if error.isExpiredToken { + failureHandler?(.tokenExpired(error: error)) + } else { + failureHandler?(.requestError(error: error, request: request)) + } + return + } + + // MARK: success + successHandler?(OAuthSwiftResponse(data: responseData, response: response, request: request)) + } + + open func cancel() { + // perform lock here to prevent cancel calls on another thread while creating the request + objc_sync_enter(self) + defer { objc_sync_exit(self) } + // either cancel the request if it's already running or set the flag to prohibit creation of the request + if let task = task { + task.cancel() + } else { + cancelRequested = true + } + } + + open func makeRequest() throws -> URLRequest { + return try OAuthSwiftHTTPRequest.makeRequest(config: self.config) + } + + open class func makeRequest(config: Config) throws -> URLRequest { + var request = config.urlRequest + return try setupRequestForOAuth(request: &request, + parameters: config.parameters, + dataEncoding: config.dataEncoding, + paramsLocation: config.paramsLocation + ) + } + + open class func makeRequest( + url: Foundation.URL, + method: Method, + headers: OAuthSwift.Headers, + parameters: OAuthSwift.Parameters, + dataEncoding: String.Encoding, + body: Data? = nil, + paramsLocation: ParamsLocation = .authorizationHeader) throws -> URLRequest { + + var request = URLRequest(url: url) + request.httpMethod = method.rawValue + for (key, value) in headers { + request.setValue(value, forHTTPHeaderField: key) + } + + return try setupRequestForOAuth( + request: &request, + parameters: parameters, + dataEncoding: dataEncoding, + body: body, + paramsLocation: paramsLocation + ) + } + + open class func setupRequestForOAuth( + request: inout URLRequest, + parameters: OAuthSwift.Parameters, + dataEncoding: String.Encoding = OAuthSwiftDataEncoding, + body: Data? = nil, + paramsLocation: ParamsLocation = .authorizationHeader) throws -> URLRequest { + + let finalParameters: OAuthSwift.Parameters + switch paramsLocation { + case .authorizationHeader: + finalParameters = parameters.filter { key, _ in !key.hasPrefix("oauth_") } + case .requestURIQuery: + finalParameters = parameters + } + + if let b = body { + request.httpBody = b + } else { + if !finalParameters.isEmpty { + let charset = dataEncoding.charset + let headers = request.allHTTPHeaderFields ?? [:] + if request.httpMethod == "GET" || request.httpMethod == "HEAD" || request.httpMethod == "DELETE" { + let queryString = finalParameters.urlEncodedQuery + let url = request.url! + request.url = url.urlByAppending(queryString: queryString) + if headers[kHTTPHeaderContentType] == nil { + request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: kHTTPHeaderContentType) + } + } else { + if let contentType = headers[kHTTPHeaderContentType], contentType.contains("application/json") { + let jsonData = try JSONSerialization.data(withJSONObject: finalParameters, options: []) + request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: kHTTPHeaderContentType) + request.httpBody = jsonData + } else if let contentType = headers[kHTTPHeaderContentType], contentType.contains("multipart/form-data") { + // snip + } else { + request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: kHTTPHeaderContentType) + let queryString = finalParameters.urlEncodedQuery + request.httpBody = queryString.data(using: dataEncoding, allowLossyConversion: true) + } + } + } + } + return request + } + +} + +// MARK: - Request configuraiton +extension OAuthSwiftHTTPRequest { + + /// Configuration for request + public struct Config { + + /// URLRequest (url, method, ...) + public var urlRequest: URLRequest + /// These parameters are either added to the query string for GET, HEAD and DELETE requests or + /// used as the http body in case of POST, PUT or PATCH requests. + /// + /// If used in the body they are either encoded as JSON or as encoded plaintext based on the Content-Type header field. + public var parameters: OAuthSwift.Parameters + public let paramsLocation: ParamsLocation + public let dataEncoding: String.Encoding + public let sessionFactory: URLSessionFactory + + /// Shortcut + public var httpMethod: Method { + if let requestMethod = urlRequest.httpMethod { + return Method(rawValue: requestMethod) ?? .GET + } + return .GET + } + + public var url: Foundation.URL? { + return urlRequest.url + } + + // MARK: init + public init(url: URL, httpMethod: Method = .GET, httpBody: Data? = nil, headers: OAuthSwift.Headers = [:], timeoutInterval: TimeInterval = 60, httpShouldHandleCookies: Bool = false, parameters: OAuthSwift.Parameters, paramsLocation: ParamsLocation = .authorizationHeader, dataEncoding: String.Encoding = OAuthSwiftDataEncoding, sessionFactory: URLSessionFactory = .default) { + var urlRequest = URLRequest(url: url) + urlRequest.httpMethod = httpMethod.rawValue + urlRequest.httpBody = httpBody + urlRequest.allHTTPHeaderFields = headers + urlRequest.timeoutInterval = timeoutInterval + urlRequest.httpShouldHandleCookies = httpShouldHandleCookies + self.init(urlRequest: urlRequest, parameters: parameters, paramsLocation: paramsLocation, dataEncoding: dataEncoding, sessionFactory: sessionFactory) + } + + public init(urlRequest: URLRequest, parameters: OAuthSwift.Parameters = [:], paramsLocation: ParamsLocation = .authorizationHeader, dataEncoding: String.Encoding = OAuthSwiftDataEncoding, sessionFactory: URLSessionFactory = .default) { + self.urlRequest = urlRequest + self.parameters = parameters + self.paramsLocation = paramsLocation + self.dataEncoding = dataEncoding + self.sessionFactory = sessionFactory + } + + /// Modify request with authentification + public mutating func updateRequest(credential: OAuthSwiftCredential) { + let method = self.httpMethod + let url = self.urlRequest.url! + let headers: OAuthSwift.Headers = self.urlRequest.allHTTPHeaderFields ?? [:] + let paramsLocation = self.paramsLocation + let parameters = self.parameters + + var signatureUrl = url + var signatureParameters = parameters + + // Check if body must be hashed (oauth1) + let body: Data? = nil + if method.isBody { + if let contentType = headers[kHTTPHeaderContentType]?.lowercased() { + + if contentType.contains("application/json") { + // TODO: oauth_body_hash create body before signing if implementing body hashing + /*do { + let jsonData: Data = try JSONSerialization.jsonObject(parameters, options: []) + request.HTTPBody = jsonData + requestHeaders["Content-Length"] = "\(jsonData.length)" + body = jsonData + } + catch { + }*/ + + signatureParameters = [:] // parameters are not used for general signature (could only be used for body hashing + } + // else other type are not supported, see setupRequestForOAuth() + } + } + + // Need to account for the fact that some consumers will have additional parameters on the + // querystring, including in the case of fetching a request token. Especially in the case of + // additional parameters on the request, authorize, or access token exchanges, we need to + // normalize the URL and add to the parametes collection. + + var queryStringParameters = OAuthSwift.Parameters() + var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false ) + if let queryItems = urlComponents?.queryItems { + for queryItem in queryItems { + let value = queryItem.value?.safeStringByRemovingPercentEncoding ?? "" + queryStringParameters.updateValue(value, forKey: queryItem.name) + } + } + + // According to the OAuth1.0a spec, the url used for signing is ONLY scheme, path, and query + if !queryStringParameters.isEmpty { + urlComponents?.query = nil + // This is safe to unwrap because these just came from an NSURL + signatureUrl = urlComponents?.url ?? url + } + signatureParameters = signatureParameters.join(queryStringParameters) + + var requestHeaders = OAuthSwift.Headers() + switch paramsLocation { + case .authorizationHeader: + //Add oauth parameters in the Authorization header + requestHeaders += credential.makeHeaders(signatureUrl, method: method, parameters: signatureParameters, body: body) + case .requestURIQuery: + //Add oauth parameters as request parameters + self.parameters += credential.authorizationParametersWithSignature(method: method, url: signatureUrl, parameters: signatureParameters, body: body) + } + + self.urlRequest.allHTTPHeaderFields = requestHeaders + headers + } + + } +} + +// MARK: - session configuration + +/// configure how URLSession is initialized +public struct URLSessionFactory { + + public static let `default` = URLSessionFactory() + + public var configuration = URLSessionConfiguration.default + public var queue = OperationQueue.main + /// An optional delegate for the URLSession + public weak var delegate: URLSessionDelegate? + + /// Monitor session: see UIApplication.shared.isNetworkActivityIndicatorVisible + public var isNetworkActivityIndicatorVisible = true + + /// By default use a closure to receive data from server. + /// If you set to false, you must in `delegate` take care of server response. + /// and maybe call in delegate `OAuthSwiftHTTPRequest.completionHandler` + public var useDataTaskClosure = true + + /// Create a new URLSession + func build() -> URLSession { + return URLSession(configuration: self.configuration, delegate: self.delegate, delegateQueue: self.queue) + } +} + +// MARK: - status code mapping + +extension OAuthSwiftHTTPRequest { + + class func descriptionForHTTPStatus(_ status: Int, responseString: String) -> String { + + var s = "HTTP Status \(status)" + + var description: String? + // http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml + if status == 400 { description = "Bad Request" } + if status == 401 { description = "Unauthorized" } + if status == 402 { description = "Payment Required" } + if status == 403 { description = "Forbidden" } + if status == 404 { description = "Not Found" } + if status == 405 { description = "Method Not Allowed" } + if status == 406 { description = "Not Acceptable" } + if status == 407 { description = "Proxy Authentication Required" } + if status == 408 { description = "Request Timeout" } + if status == 409 { description = "Conflict" } + if status == 410 { description = "Gone" } + if status == 411 { description = "Length Required" } + if status == 412 { description = "Precondition Failed" } + if status == 413 { description = "Payload Too Large" } + if status == 414 { description = "URI Too Long" } + if status == 415 { description = "Unsupported Media Type" } + if status == 416 { description = "Requested Range Not Satisfiable" } + if status == 417 { description = "Expectation Failed" } + if status == 422 { description = "Unprocessable Entity" } + if status == 423 { description = "Locked" } + if status == 424 { description = "Failed Dependency" } + if status == 425 { description = "Unassigned" } + if status == 426 { description = "Upgrade Required" } + if status == 427 { description = "Unassigned" } + if status == 428 { description = "Precondition Required" } + if status == 429 { description = "Too Many Requests" } + if status == 430 { description = "Unassigned" } + if status == 431 { description = "Request Header Fields Too Large" } + if status == 432 { description = "Unassigned" } + if status == 500 { description = "Internal Server Error" } + if status == 501 { description = "Not Implemented" } + if status == 502 { description = "Bad Gateway" } + if status == 503 { description = "Service Unavailable" } + if status == 504 { description = "Gateway Timeout" } + if status == 505 { description = "HTTP Version Not Supported" } + if status == 506 { description = "Variant Also Negotiates" } + if status == 507 { description = "Insufficient Storage" } + if status == 508 { description = "Loop Detected" } + if status == 509 { description = "Unassigned" } + if status == 510 { description = "Not Extended" } + if status == 511 { description = "Network Authentication Required" } + + if description != nil { + s += ": " + description! + ", Response: " + responseString + } + + return s + } + +} diff --git a/Pods/OAuthSwift/Sources/OAuthSwiftMultipartData.swift b/Pods/OAuthSwift/Sources/OAuthSwiftMultipartData.swift new file mode 100644 index 0000000000..30d35e1698 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuthSwiftMultipartData.swift @@ -0,0 +1,48 @@ +// +// OAuthSwiftMultipartData.swift +// OAuthSwift +// +// Created by Tomohiro Kawaji on 12/18/15. +// Copyright (c) 2015 Dongri Jin. All rights reserved. +// + +import Foundation + +public struct OAuthSwiftMultipartData { + + public var name: String + public var data: Data + public var fileName: String? + public var mimeType: String? + + public init(name: String, data: Data, fileName: String?, mimeType: String?) { + self.name = name + self.data = data + self.fileName = fileName + self.mimeType = mimeType + } + +} + +extension Data { + + public mutating func append(_ multipartData: OAuthSwiftMultipartData, encoding: String.Encoding, separatorData: Data) { + var filenameClause = "" + if let filename = multipartData.fileName { + filenameClause = " filename=\"\(filename)\"" + } + let contentDispositionString = "Content-Disposition: form-data; name=\"\(multipartData.name)\";\(filenameClause)\r\n" + let contentDispositionData = contentDispositionString.data(using: encoding)! + self.append(contentDispositionData) + + if let mimeType = multipartData.mimeType { + let contentTypeString = "Content-Type: \(mimeType)\r\n" + let contentTypeData = contentTypeString.data(using: encoding)! + self.append(contentTypeData) + } + + self.append(separatorData) + self.append(multipartData.data) + self.append(separatorData) + } +} diff --git a/Pods/OAuthSwift/Sources/OAuthSwiftResponse.swift b/Pods/OAuthSwift/Sources/OAuthSwiftResponse.swift new file mode 100644 index 0000000000..8940b82cc5 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuthSwiftResponse.swift @@ -0,0 +1,50 @@ +// +// OAuthSwiftResponse.swift +// OAuthSwift +// +// Created by phimage on 04/11/16. +// Copyright © 2016 Dongri Jin. All rights reserved. +// + +import Foundation + +/// Response object +@objc +public class OAuthSwiftResponse: NSObject { // not a struct for objc + /// The data returned by the server. + public var data: Data + /// The server's response to the URL request. + public var response: HTTPURLResponse + /// The URL request sent to the server. + public var request: URLRequest? + + public init(data: Data, response: HTTPURLResponse, request: URLRequest?) { + self.data = data + self.response = response + self.request = request + } + +} + +/// Extends this object to convert data into your business objects +extension OAuthSwiftResponse { + + public func dataString(encoding: String.Encoding = OAuthSwiftDataEncoding) -> String? { + return String(data: self.data, encoding: encoding) + } + + /// `data` converted to string using data encoding + public var string: String? { + return dataString() + } + + /// Convert to json object using JSONSerialization + public func jsonObject(options opt: JSONSerialization.ReadingOptions = []) throws -> Any { + return try JSONSerialization.jsonObject(with: self.data, options: opt) + } + + /// Convert to object using PropertyListSerialization + public func propertyList(options opt: PropertyListSerialization.ReadOptions = [], format: UnsafeMutablePointer? = nil) throws -> Any { + return try PropertyListSerialization.propertyList(from: self.data, options: opt, format: format) + } +} diff --git a/Pods/OAuthSwift/Sources/OAuthSwiftURLHandlerType.swift b/Pods/OAuthSwift/Sources/OAuthSwiftURLHandlerType.swift new file mode 100644 index 0000000000..d5b5426e89 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuthSwiftURLHandlerType.swift @@ -0,0 +1,167 @@ +// +// OAuthSwiftURLHandlerType.swift +// OAuthSwift +// +// Created by phimage on 11/05/15. +// Copyright (c) 2015 Dongri Jin. All rights reserved. +// + +import Foundation + +#if os(iOS) || os(tvOS) + import UIKit +#elseif os(watchOS) + import WatchKit +#elseif os(OSX) + import AppKit +#endif + +@objc public protocol OAuthSwiftURLHandlerType { + func handle(_ url: URL) +} + +// MARK: Open externally +open class OAuthSwiftOpenURLExternally: OAuthSwiftURLHandlerType { + + public static var sharedInstance: OAuthSwiftOpenURLExternally = OAuthSwiftOpenURLExternally() + + @objc open func handle(_ url: URL) { + #if os(iOS) || os(tvOS) + #if !OAUTH_APP_EXTENSIONS + UIApplication.shared.openURL(url) + #endif + #elseif os(watchOS) + // WATCHOS: not implemented + #elseif os(OSX) + NSWorkspace.shared.open(url) + #endif + } +} + +// MARK: Open SFSafariViewController +#if os(iOS) +import SafariServices + + @available(iOS 9.0, *) + open class SafariURLHandler: NSObject, OAuthSwiftURLHandlerType, SFSafariViewControllerDelegate { + + public typealias UITransion = (_ controller: SFSafariViewController, _ handler: SafariURLHandler) -> Void + + weak open var oauthSwift: OAuthSwift? + open var present: UITransion + open var dismiss: UITransion + /// retains observers + var observers = [String: NSObjectProtocol]() + + open var factory: (_ URL: URL) -> SFSafariViewController = {URL in + return SFSafariViewController(url: URL) + } + + /// delegates + open weak var delegate: SFSafariViewControllerDelegate? + + // configure default presentation and dismissal code + + open var animated: Bool = true + open var presentCompletion: (() -> Void)? + open var dismissCompletion: (() -> Void)? + open var delay: UInt32? = 1 + + /// init + public init(viewController: UIViewController, oauthSwift: OAuthSwift) { + self.oauthSwift = oauthSwift + self.present = { [weak viewController] controller, handler in + viewController?.present(controller, animated: handler.animated, completion: handler.presentCompletion) + } + self.dismiss = { [weak viewController] _, handler in + viewController?.dismiss(animated: handler.animated, completion: handler.dismissCompletion) + } + } + + public init(present: @escaping UITransion, dismiss: @escaping UITransion, oauthSwift: OAuthSwift) { + self.oauthSwift = oauthSwift + self.present = present + self.dismiss = dismiss + } + + @objc open func handle(_ url: URL) { + let controller = factory(url) + controller.delegate = self + + // present controller in main thread + OAuthSwift.main { [weak self] in + guard let this = self else { + return + } + if let delay = this.delay { // sometimes safari show a blank view.. + sleep(delay) + } + this.present(controller, this) + } + + let key = UUID().uuidString + + observers[key] = OAuthSwift.notificationCenter.addObserver( + forName: NSNotification.Name.OAuthSwiftHandleCallbackURL, + object: nil, + queue: OperationQueue.main, + using: { [weak self] _ in + guard let this = self else { + return + } + if let observer = this.observers[key] { + OAuthSwift.notificationCenter.removeObserver(observer) + this.observers.removeValue(forKey: key) + } + OAuthSwift.main { + this.dismiss(controller, this) + } + } + ) + } + + /// Clear internal observers on authentification flow + open func clearObservers() { + clearLocalObservers() + self.oauthSwift?.removeCallbackNotificationObserver() + } + + open func clearLocalObservers() { + for (_, observer) in observers { + OAuthSwift.notificationCenter.removeObserver(observer) + } + observers.removeAll() + } + + /// SFSafariViewControllerDelegate + public func safariViewController(_ controller: SFSafariViewController, activityItemsFor URL: Foundation.URL, title: String?) -> [UIActivity] { + return self.delegate?.safariViewController?(controller, activityItemsFor: URL, title: title) ?? [] + } + + public func safariViewControllerDidFinish(_ controller: SFSafariViewController) { + // "Done" pressed + self.clearObservers() + self.delegate?.safariViewControllerDidFinish?(controller) + } + + public func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) { + self.delegate?.safariViewController?(controller, didCompleteInitialLoad: didLoadSuccessfully) + } + + } + +#endif + +// MARK: Open url using NSExtensionContext +open class ExtensionContextURLHandler: OAuthSwiftURLHandlerType { + + fileprivate var extensionContext: NSExtensionContext + + public init(extensionContext: NSExtensionContext) { + self.extensionContext = extensionContext + } + + @objc open func handle(_ url: URL) { + extensionContext.open(url, completionHandler: nil) + } +} diff --git a/Pods/OAuthSwift/Sources/OAuthWebViewController.swift b/Pods/OAuthSwift/Sources/OAuthWebViewController.swift new file mode 100644 index 0000000000..ae2a6defa4 --- /dev/null +++ b/Pods/OAuthSwift/Sources/OAuthWebViewController.swift @@ -0,0 +1,193 @@ +// +// OAuthWebViewController.swift +// OAuthSwift +// +// Created by Dongri Jin on 2/11/15. +// Copyright (c) 2015 Dongri Jin. All rights reserved. +// + +import Foundation + +#if os(iOS) || os(tvOS) + import UIKit + public typealias OAuthViewController = UIViewController +#elseif os(watchOS) + import WatchKit + public typealias OAuthViewController = WKInterfaceController +#elseif os(OSX) + import AppKit + public typealias OAuthViewController = NSViewController +#endif + +/// Delegate for OAuthWebViewController +public protocol OAuthWebViewControllerDelegate: class { + + #if os(iOS) || os(tvOS) + /// Did web view presented (work only without navigation controller) + func oauthWebViewControllerDidPresent() + /// Did web view dismiss (work only without navigation controller) + func oauthWebViewControllerDidDismiss() + #endif + + func oauthWebViewControllerWillAppear() + func oauthWebViewControllerDidAppear() + func oauthWebViewControllerWillDisappear() + func oauthWebViewControllerDidDisappear() +} + +/// A web view controller, which handler OAuthSwift authentification. +open class OAuthWebViewController: OAuthViewController, OAuthSwiftURLHandlerType { + + #if os(iOS) || os(tvOS) || os(OSX) + /// Delegate for this view + public weak var delegate: OAuthWebViewControllerDelegate? + #endif + + #if os(iOS) || os(tvOS) + /// If controller have an navigation controller, application top view controller could be used if true + public var useTopViewControlerInsteadOfNavigation = false + + /// Set false to disable present animation. + public var presentViewControllerAnimated = true + /// Set false to disable dismiss animation. + public var dismissViewControllerAnimated = true + + public var topViewController: UIViewController? { + #if !OAUTH_APP_EXTENSIONS + return UIApplication.topViewController + #else + return nil + #endif + } + #elseif os(OSX) + /// How to present this view controller if parent view controller set + public enum Present { + case asModalWindow + case asSheet + case asPopover(relativeToRect: NSRect, ofView : NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) + case transitionFrom(fromViewController: NSViewController, options: NSViewController.TransitionOptions) + case animator(animator: NSViewControllerPresentationAnimator) + case segue(segueIdentifier: String) + } + public var present: Present = .asModalWindow + #endif + + open func handle(_ url: URL) { + // do UI in main thread + OAuthSwift.main { [unowned self] in + self.doHandle(url) + } + } + + #if os(watchOS) + public static var userActivityType: String = "org.github.dongri.oauthswift.connect" + #endif + + open func doHandle(_ url: URL) { + #if os(iOS) || os(tvOS) + let completion: () -> Void = { [unowned self] in + self.delegate?.oauthWebViewControllerDidPresent() + } + if let navigationController = self.navigationController, (!useTopViewControlerInsteadOfNavigation || self.topViewController == nil) { + navigationController.pushViewController(self, animated: presentViewControllerAnimated) + } else if let p = self.parent { + p.present(self, animated: presentViewControllerAnimated, completion: completion) + } else if let topViewController = topViewController { + topViewController.present(self, animated: presentViewControllerAnimated, completion: completion) + } else { + // assert no presentation + assertionFailure("Failed to present. Maybe add a parent") + } + #elseif os(watchOS) + if url.scheme == "http" || url.scheme == "https" { + self.updateUserActivity(OAuthWebViewController.userActivityType, userInfo: nil, webpageURL: url) + } + #elseif os(OSX) + if let p = self.parent { // default behaviour if this controller affected as child controller + switch self.present { + case .asSheet: + p.presentViewControllerAsSheet(self) + case .asModalWindow: + p.presentViewControllerAsModalWindow(self) + // FIXME: if we present as window, window close must detected and oauthswift.cancel() must be called... + case .asPopover(let positioningRect, let positioningView, let preferredEdge, let behavior): + p.presentViewController(self, asPopoverRelativeTo: positioningRect, of: positioningView, preferredEdge: preferredEdge, behavior: behavior) + case .transitionFrom(let fromViewController, let options): + let completion: () -> Void = { /*[unowned self] in*/ + //self.delegate?.oauthWebViewControllerDidPresent() + } + p.transition(from: fromViewController, to: self, options: options, completionHandler: completion) + case .animator(let animator): + p.presentViewController(self, animator: animator) + case .segue(let segueIdentifier): + p.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: segueIdentifier), sender: self) // The segue must display self.view + } + } else if let window = self.view.window { + window.makeKeyAndOrderFront(nil) + } else { + assertionFailure("Failed to present. Add controller into a window or add a parent") + } + // or create an NSWindow or NSWindowController (/!\ keep a strong reference on it) + #endif + } + + open func dismissWebViewController() { + #if os(iOS) || os(tvOS) + let completion: () -> Void = { [unowned self] in + self.delegate?.oauthWebViewControllerDidDismiss() + } + if let navigationController = self.navigationController, (!useTopViewControlerInsteadOfNavigation || self.topViewController == nil) { + navigationController.popViewController(animated: dismissViewControllerAnimated) + } else if let parentViewController = self.parent { + // The presenting view controller is responsible for dismissing the view controller it presented + parentViewController.dismiss(animated: dismissViewControllerAnimated, completion: completion) + } else if let topViewController = topViewController { + topViewController.dismiss(animated: dismissViewControllerAnimated, completion: completion) + } else { + // keep old code... + self.dismiss(animated: dismissViewControllerAnimated, completion: completion) + } + #elseif os(watchOS) + self.dismiss() + #elseif os(OSX) + if self.presenting != nil { + self.dismiss(nil) + if self.parent != nil { + self.removeFromParentViewController() + } + } else if let window = self.view.window { + window.performClose(nil) + } + #endif + } + + // MARK: overrides + #if os(iOS) || os(tvOS) + open override func viewWillAppear(_ animated: Bool) { + self.delegate?.oauthWebViewControllerWillAppear() + } + open override func viewDidAppear(_ animated: Bool) { + self.delegate?.oauthWebViewControllerDidAppear() + } + open override func viewWillDisappear(_ animated: Bool) { + self.delegate?.oauthWebViewControllerWillDisappear() + } + open override func viewDidDisappear(_ animated: Bool) { + self.delegate?.oauthWebViewControllerDidDisappear() + } + #elseif os(OSX) + open override func viewWillAppear() { + self.delegate?.oauthWebViewControllerWillAppear() + } + open override func viewDidAppear() { + self.delegate?.oauthWebViewControllerDidAppear() + } + open override func viewWillDisappear() { + self.delegate?.oauthWebViewControllerWillDisappear() + } + open override func viewDidDisappear() { + self.delegate?.oauthWebViewControllerDidDisappear() + } + + #endif +} diff --git a/Pods/OAuthSwift/Sources/Objc.swift b/Pods/OAuthSwift/Sources/Objc.swift new file mode 100644 index 0000000000..637bf826d8 --- /dev/null +++ b/Pods/OAuthSwift/Sources/Objc.swift @@ -0,0 +1,75 @@ +// +// Objc.swift +// OAuthSwift +// +// Created by phimage on 05/11/16. +// Copyright © 2016 Dongri Jin. All rights reserved. +// + +import Foundation + +extension OAuthSwift { + // swiftlint:disable:next type_name + public typealias Obj_FailureHandler = (_ error: Error) -> Void +} + +extension OAuth1Swift { + + open func objc_authorize(withCallbackURL urlString: String, success: @escaping TokenSuccessHandler, failure: Obj_FailureHandler?) -> OAuthSwiftRequestHandle? { + guard let url = URL(string: urlString) else { + failure?(OAuthSwiftError.encodingError(urlString: urlString)) + return nil + } + return authorize(withCallbackURL: url, success: success, failure: failure) + } + +} + +extension OAuth2Swift { + + open func objc_authorize(withCallbackURL urlString: String, scope: String, state: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: Obj_FailureHandler?) -> OAuthSwiftRequestHandle? { + guard let url = URL(string: urlString) else { + failure?(OAuthSwiftError.encodingError(urlString: urlString)) + return nil + } + return authorize(withCallbackURL: url, scope: scope, state: state, parameters: parameters, headers: headers, success: success, failure: failure) + } + + open func objc_renewAccessToken(withRefreshToken refreshToken: String, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: Obj_FailureHandler?) -> OAuthSwiftRequestHandle? { + return renewAccessToken(withRefreshToken: refreshToken, headers: headers, success: success, failure: failure) + } + +} + +extension OAuthSwiftHTTPRequest { + // swiftlint:disable:next type_name + public typealias Obj_FailureHandler = (_ error: Error) -> Void +} + +extension OAuthSwiftClient { + + open func objc_request(_ urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, checkTokenExpiration: Bool = true, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? { + return request(urlString, method: method, parameters: parameters, headers: headers, body: body, checkTokenExpiration: checkTokenExpiration, success: success, failure: failure) + } + + open func get(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .GET, parameters: parameters, headers: headers, success: success, failure: failure) + } + + open func post(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .POST, parameters: parameters, headers: headers, body: body, success: success, failure: failure) + } + + open func put(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .PUT, parameters: parameters, headers: headers, body: body, success: success, failure: failure) + } + + open func delete(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .DELETE, parameters: parameters, headers: headers, success: success, failure: failure) + } + + open func patch(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? { + return self.request(urlString, method: .PATCH, parameters: parameters, headers: headers, success: success, failure: failure) + } + +} diff --git a/Pods/OAuthSwift/Sources/SHA1.swift b/Pods/OAuthSwift/Sources/SHA1.swift new file mode 100644 index 0000000000..f430a1d1f8 --- /dev/null +++ b/Pods/OAuthSwift/Sources/SHA1.swift @@ -0,0 +1,152 @@ +// +// SHA1.swift +// OAuthSwift +// +// Created by Dongri Jin on 1/28/15. +// Copyright (c) 2015 Dongri Jin. All rights reserved. +// + +import Foundation + +class SHA1 { + + private var message: [UInt8] + + fileprivate let h: [UInt32] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] + + init(_ message: Data) { + self.message = message.bytes + } + init(_ message: [UInt8]) { + self.message = message + } + + /// Common part for hash calculation. Prepare header data. + func prepare(_ message: [UInt8], _ blockSize: Int, _ allowance: Int) -> [UInt8] { + var tmpMessage = message + + // Step 1. Append Padding Bits + tmpMessage.append(0x80) // append one bit (Byte 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 % blockSize != (blockSize - allowance) { + counter += 1 + msgLength += 1 + } + + tmpMessage += [UInt8](repeating: 0, count: counter) + + return tmpMessage + } + + func calculate() -> [UInt8] { + var tmpMessage = self.prepare(self.message, 64, 64 / 8) + + // hash values + var hh = h + + // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits. + tmpMessage += (self.message.count * 8).bytes(64 / 8) + + // Process the message in successive 512-bit chunks: + let chunkSizeBytes = 512 / 8 // 64 + for chunk in BytesSequence(data: tmpMessage, chunkSize: chunkSizeBytes) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 32-bit words into eighty 32-bit words: + var M: [UInt32] = [UInt32](repeating: 0, count: 80) + for x in 0...size + let start = chunk.startIndex + (x * memorySize) + let end = start + memorySize + let le = chunk[start..> 8) & 0xff), UInt8((item >> 16) & 0xff), UInt8((item >> 24) & 0xff)] + } + + return result + } + + private func rotateLeft(_ v: UInt32, n: UInt32) -> UInt32 { + return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) + } + +} + +private struct BytesSequence: Sequence where D.Iterator.Element == UInt8, D.Index == Int { + let data: D + let chunkSize: Int + + func makeIterator() -> AnyIterator { + var offset = data.startIndex + return AnyIterator { + let end = Swift.min(self.chunkSize, self.data.count - offset) + let result = self.data[offset.. Void)? = nil) -> String? { + if value.isEmpty { + return self + } else if let value = encode ? value.urlQueryEncoded : value { + return "\(self)\(self.isEmpty ? "" : "&")\(name)=\(value)" + } else { + encodeError?(name, value) + return nil + } + } + + /// Returns new url string by appending query string at the end. + func urlByAppending(query: String) -> String { + return "\(self)\(self.contains("?") ? "&" : "?")\(query)" + } + + fileprivate func dictionaryBySplitting(_ elementSeparator: String, keyValueSeparator: String) -> [String: String] { + var string = self + + if hasPrefix(elementSeparator) { + string = String(dropFirst(1)) + } + + var parameters = [String: String]() + + let scanner = Scanner(string: string) + + var key: NSString? + var value: NSString? + + while !scanner.isAtEnd { + key = nil + scanner.scanUpTo(keyValueSeparator, into: &key) + scanner.scanString(keyValueSeparator, into: nil) + + value = nil + scanner.scanUpTo(elementSeparator, into: &value) + scanner.scanString(elementSeparator, into: nil) + + if let key = key as String? { + if let value = value as String? { + if key.contains(elementSeparator) { + var keys = key.components(separatedBy: elementSeparator) + if let key = keys.popLast() { + parameters.updateValue(value, forKey: String(key)) + } + for flag in keys { + parameters.updateValue("", forKey: flag) + } + } else { + parameters.updateValue(value, forKey: key) + } + } else { + parameters.updateValue("", forKey: key) + } + } + } + + return parameters + } + + public var headerDictionary: OAuthSwift.Headers { + return dictionaryBySplitting(",", keyValueSeparator: "=") + } + + var safeStringByRemovingPercentEncoding: String { + return self.removingPercentEncoding ?? self + } + + mutating func dropLast() { + self.remove(at: self.index(before: self.endIndex)) + } + + subscript (bounds: CountableClosedRange) -> String { + let start = index(startIndex, offsetBy: bounds.lowerBound) + let end = index(startIndex, offsetBy: bounds.upperBound) + return String(self[start...end]) + } + + subscript (bounds: CountableRange) -> String { + let start = index(startIndex, offsetBy: bounds.lowerBound) + let end = index(startIndex, offsetBy: bounds.upperBound) + return String(self[start.. UIViewController { + guard let presentedViewController = viewController.presentedViewController else { + return viewController + } + #if !topVCCastDisabled + if let navigationController = presentedViewController as? UINavigationController { + if let visibleViewController = navigationController.visibleViewController { + return topViewController(visibleViewController) + } + } else if let tabBarController = presentedViewController as? UITabBarController { + if let selectedViewController = tabBarController.selectedViewController { + return topViewController(selectedViewController) + } + } + #endif + return topViewController(presentedViewController) + } + } + +#endif diff --git a/Pods/OAuthSwift/Sources/URL+OAuthSwift.swift b/Pods/OAuthSwift/Sources/URL+OAuthSwift.swift new file mode 100755 index 0000000000..e96375429d --- /dev/null +++ b/Pods/OAuthSwift/Sources/URL+OAuthSwift.swift @@ -0,0 +1,29 @@ +// +// URL+OAuthSwift.swift +// OAuthSwift +// +// Created by Dongri Jin on 6/21/14. +// Copyright (c) 2014 Dongri Jin. All rights reserved. +// + +import Foundation + +extension URL { + + func urlByAppending(queryString: String) -> URL { + if queryString.utf16.isEmpty { + return self + } + + var absoluteURLString = absoluteString + + if absoluteURLString.hasSuffix("?") { + absoluteURLString.dropLast() + } + + let string = absoluteURLString + (absoluteURLString.range(of: "?") != nil ? "&" : "?") + queryString + + return URL(string: string)! + } + +} diff --git a/Pods/OAuthSwift/Sources/Utils.swift b/Pods/OAuthSwift/Sources/Utils.swift new file mode 100644 index 0000000000..8d13615209 --- /dev/null +++ b/Pods/OAuthSwift/Sources/Utils.swift @@ -0,0 +1,23 @@ +// +// Utils.swift +// OAuthSwift +// +// Created by Dongri Jin on 1/28/15. +// Copyright (c) 2015 Dongri Jin. All rights reserved. +// + +import Foundation + +public func generateState(withLength len: Int) -> String { + let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + let length = UInt32(letters.count) + + var randomString = "" + for _ in 0.. + +The MIT License (MIT) + +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/RCMarkdownParser/Pod/Classes/NSAttributedString+Markdown.swift b/Pods/RCMarkdownParser/Pod/Classes/NSAttributedString+Markdown.swift new file mode 100644 index 0000000000..3b1bbaa8ed --- /dev/null +++ b/Pods/RCMarkdownParser/Pod/Classes/NSAttributedString+Markdown.swift @@ -0,0 +1,146 @@ +import Foundation +import UIKit + +public extension NSAttributedString { + + public func markdownString() -> String { + let bulletCharacter = Character("\u{2022}") + let nonBreakingSpaceCharacter = Character("\u{00A0}") + + var markdownString = "" + + enum FormattingChange { + case enable + case disable + case keep + + static func getFormattingChange(_ before: Bool, after: Bool) -> FormattingChange { + if !before && after { return .enable } + if before && !after { return .disable } + return .keep + } + } + + var stringHasBoldEnabled = false + var stringHasItalicEnabled = false + var closingString = "" + var characterOnBulletedListLine = false + var openedNumberedListStarter = false + var characterOnNumberedListLine = false + var numberedListIsFirstLine = false + var previousCharacter: Character? + enumerateAttributes(in: NSRange(location: 0, length: length), options: []) { attributes, range, shouldStop in + if let traits = (attributes[NSFontAttributeName] as? UIFont)?.fontDescriptor.symbolicTraits { + let boldChange = FormattingChange.getFormattingChange(stringHasBoldEnabled, after: traits.contains(.traitBold)) + let italicChange = FormattingChange.getFormattingChange(stringHasItalicEnabled, after: traits.contains(.traitItalic)) + var formatString = "" + switch boldChange { + case .enable: + formatString += "**" + closingString = "**\(closingString)" + case .disable: + if stringHasItalicEnabled && italicChange == .keep { + formatString += "_**_" + closingString = "_" + } else { + formatString += "**" + closingString = "" + } + case .keep: + break + } + + switch italicChange { + case .enable: + formatString += "_" + closingString = "_\(closingString)" + case .disable: + if stringHasBoldEnabled && boldChange == .keep { + formatString = "**_**\(formatString)" + closingString = "**" + } else { + formatString = "_\(formatString)" + closingString = "" + } + case .keep: + break + } + + markdownString += formatString + + stringHasBoldEnabled = traits.contains(.traitBold) + stringHasItalicEnabled = traits.contains(.traitItalic) + } + + let preprocessedString = (self.string as NSString).substring(with: range) + let processedString = preprocessedString.characters.reduce("") { resultString, character in + var stringToAppend = "" + + switch character { + case "\\", "`", "*", "_", "{", "}", "[", "]", "(", ")", "#", "+", "-", "!": + stringToAppend = "\\\(character)" + case "\n", "\u{2028}": + stringToAppend = "\(closingString)\(character)" + if !characterOnBulletedListLine && !characterOnNumberedListLine { + stringToAppend += String(closingString.characters.reversed()) + } + + characterOnBulletedListLine = false + characterOnNumberedListLine = false + case "1", "2", "3", "4", "5", "6", "7", "8", "9", "0": + if previousCharacter == "\n" || previousCharacter == nil || previousCharacter == nonBreakingSpaceCharacter { + openedNumberedListStarter = true + } + + numberedListIsFirstLine = previousCharacter == nil ? true : numberedListIsFirstLine + stringToAppend = "\(character)" + case bulletCharacter: + characterOnBulletedListLine = true + stringToAppend = "+ \(previousCharacter != nil ? String(closingString.characters.reversed()) : markdownString)" + markdownString = previousCharacter == nil ? "" : markdownString + case ".": + if openedNumberedListStarter { + openedNumberedListStarter = false + characterOnNumberedListLine = true + + stringToAppend = "\(character) \(!numberedListIsFirstLine ? String(closingString.characters.reversed()) : markdownString)" + + if numberedListIsFirstLine { + markdownString = "" + numberedListIsFirstLine = false + } + break + } + stringToAppend = "\\\(character)" + case nonBreakingSpaceCharacter: + if characterOnBulletedListLine || characterOnNumberedListLine { + break + } + stringToAppend = " " + default: + if (previousCharacter == "\n" || previousCharacter == "\u{2028}") && characterOnBulletedListLine { + characterOnBulletedListLine = false + stringToAppend = "\(String(closingString.characters.reversed()))\(character)" + } else { + stringToAppend = "\(character)" + } + } + + previousCharacter = character + return "\(resultString)\(stringToAppend)" + } + markdownString += processedString + } + markdownString += closingString + markdownString = markdownString.replacingOccurrences(of: "**__**", with: "").replacingOccurrences(of: "****", with: "") + .replacingOccurrences(of: "__", with: "") + // Help the user because they probably didn't intend to have empty bullets and it will make markdown have a + if we leave them + markdownString = markdownString.replacingOccurrences(of: "+ \n", with: "") + if markdownString.hasSuffix("+ ") { + markdownString = (markdownString as NSString).substring(to: markdownString.characters.count - 2) + } + + return markdownString + } + +} diff --git a/Pods/RCMarkdownParser/Pod/Classes/RCBaseParser.swift b/Pods/RCMarkdownParser/Pod/Classes/RCBaseParser.swift new file mode 100644 index 0000000000..4beeb0eb68 --- /dev/null +++ b/Pods/RCMarkdownParser/Pod/Classes/RCBaseParser.swift @@ -0,0 +1,53 @@ +import Foundation + +open class RCBaseParser { + + public typealias RCMarkdownParserMatchBlock = ((NSTextCheckingResult, NSMutableAttributedString) -> Void) + + struct RCExpressionBlockPair { + var regularExpression: NSRegularExpression + var block: RCMarkdownParserMatchBlock + } + + open var defaultAttributes = [String: Any]() + + fileprivate var parsingPairs = [RCExpressionBlockPair]() + + open func attributedStringFromMarkdown(_ markdown: String) -> NSAttributedString? { + return attributedStringFromMarkdown(markdown, attributes: defaultAttributes) + } + + open func attributedStringFromMarkdown(_ markdown: String, attributes: [String: Any]?) -> NSAttributedString? { + return attributedStringFromAttributedMarkdownString(NSAttributedString(string: markdown, attributes: attributes)) + } + + open func attributedStringFromAttributedMarkdownString(_ attributedString: NSAttributedString) -> NSAttributedString { + let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString) + + for expressionBlockPair in parsingPairs { + parseExpressionBlockPairForMutableString(mutableAttributedString, expressionBlockPair: expressionBlockPair) + } + + return mutableAttributedString + } + + func parseExpressionBlockPairForMutableString(_ mutableAttributedString: NSMutableAttributedString, expressionBlockPair: RCExpressionBlockPair) { + parseExpressionForMutableString(mutableAttributedString, expression: expressionBlockPair.regularExpression, block: expressionBlockPair.block) + } + + func parseExpressionForMutableString(_ mutableAttributedString: NSMutableAttributedString, expression: NSRegularExpression, block: RCMarkdownParserMatchBlock) { + var location = 0 + + while let match = expression.firstMatch(in: mutableAttributedString.string, options: .withoutAnchoringBounds, range: NSRange(location: location, length: mutableAttributedString.length - location)) { + let oldLength = mutableAttributedString.length + block(match, mutableAttributedString) + let newLength = mutableAttributedString.length + location = match.range.location + match.range.length + newLength - oldLength + } + } + + open func addParsingRuleWithRegularExpression(_ regularExpression: NSRegularExpression, block: @escaping RCMarkdownParserMatchBlock) { + parsingPairs.append(RCExpressionBlockPair(regularExpression: regularExpression, block: block)) + } + +} diff --git a/Pods/RCMarkdownParser/Pod/Classes/RCMarkdownParser.swift b/Pods/RCMarkdownParser/Pod/Classes/RCMarkdownParser.swift new file mode 100644 index 0000000000..cd57bde3c7 --- /dev/null +++ b/Pods/RCMarkdownParser/Pod/Classes/RCMarkdownParser.swift @@ -0,0 +1,394 @@ +import Foundation +import UIKit + +private let nonBreakingSpaceCharacter = Character("\u{00A0}") + +public struct RCMarkdownRegex { + public static let CodeEscaping = "(?)(.*)$" + public static let QuoteOptions: NSRegularExpression.Options = [.anchorsMatchLines] + public static let QuoteBlock = "(>>>)\n+([\\s\\S]*?)\n+(<<<)" + public static let QuoteBlockOptions: NSRegularExpression.Options = [.anchorsMatchLines] + + public static var allowedSchemes = ["http", "https"] + fileprivate static var _allowedSchemes: String { + return allowedSchemes.joined(separator: "|") + } + + public static let Image = "!\\[([^\\]]+)\\]\\(((?:\(_allowedSchemes)):\\/\\/[^\\)]+)\\)" + public static let ImageOptions: NSRegularExpression.Options = [.anchorsMatchLines] + public static let Link = "(?|>)(?:>|>)" + public static let AlternateLinkOptions: NSRegularExpression.Options = [.anchorsMatchLines] + + public static let InlineCode = "(?:^|>|[ >_*~])(\\`)([^`\r\n]+)(\\`)(?:[<_*~]|\\B|\\b|$)" + public static let InlineCodeOptions: NSRegularExpression.Options = [.anchorsMatchLines] + public static let Code = "(```)(?:[a-zA-Z]+)?((?:.|\r|\n)*?)(```)" + public static let CodeOptions: NSRegularExpression.Options = [.anchorsMatchLines] + + public static let Strong = "(?:^|>|[ >_~`])(\\*{1,2})([^\\*\r\n]+)(\\*{1,2})(?:[<_~`]|\\B|\\b|$)" + public static let StrongOptions: NSRegularExpression.Options = [.anchorsMatchLines] + public static let Italic = "(?:^|>|[ >*~`])(\\_{1,2})([^\\_\r\n]+)(\\_{1,2})(?:[<*~`]|\\B|\\b|$)" + public static let ItalicOptions: NSRegularExpression.Options = [.anchorsMatchLines] + public static let Strike = "(?:^|>|[ >_*`])(\\~{1,2})([^~\r\n]+)(\\~{1,2})(?:[<_*`]|\\B|\\b|$)" + public static let StrikeOptions: NSRegularExpression.Options = [.anchorsMatchLines] + + public static func regexForString(_ regexString: String, options: NSRegularExpression.Options = []) -> NSRegularExpression? { + do { + return try NSRegularExpression(pattern: regexString, options: options) + } catch { + return nil + } + } +} + +open class RCMarkdownParser: RCBaseParser { + + public typealias RCMarkdownParserFormattingBlock = ((NSMutableAttributedString, NSRange) -> Void) + public typealias RCMarkdownParserLevelFormattingBlock = ((NSMutableAttributedString, NSRange, Int) -> Void) + + open var headerAttributes = [UInt: [String: Any]]() + open var listAttributes = [[String: Any]]() + open var numberedListAttributes = [[String: Any]]() + open var quoteAttributes = [String: Any]() + open var quoteBlockAttributes = [String: Any]() + + open var imageAttributes = [String: Any]() + open var linkAttributes = [String: Any]() + + open var inlineCodeAttributes = [String: Any]() + open var codeAttributes = [String: Any]() + + open var strongAttributes = [String: Any]() + open var italicAttributes = [String: Any]() + open var strongAndItalicAttributes = [String: Any]() + open var strikeAttributes = [String: Any]() + + public typealias DownloadImageClosure = (UIImage?)->Void + open var downloadImage: (_ path: String, _ completion: DownloadImageClosure?) -> Void = { + _,completion in + completion?(nil) + } + + open static var standardParser = RCMarkdownParser() + + class func addAttributes(_ attributesArray: [[String: Any]], atIndex level: Int, toString attributedString: NSMutableAttributedString, range: NSRange) { + guard !attributesArray.isEmpty else { return } + + guard let newAttributes = level < attributesArray.count && level >= 0 ? attributesArray[level] : attributesArray.last else { return } + + attributedString.addAttributes(newAttributes, range: range) + } + + public init(withDefaultParsing: Bool = true) { + super.init() + + strongAttributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12)] + italicAttributes = [NSFontAttributeName: UIFont.italicSystemFont(ofSize: 12)] + + var strongAndItalicFont = UIFont.systemFont(ofSize: 12) + strongAndItalicFont = UIFont(descriptor: strongAndItalicFont.fontDescriptor.withSymbolicTraits([.traitItalic, .traitBold])!, size: strongAndItalicFont.pointSize) + strongAndItalicAttributes = [NSFontAttributeName: strongAndItalicFont] + + if withDefaultParsing { + + addNumberedListParsingWithLeadFormattingBlock({ (attributedString, range, level) in + RCMarkdownParser.addAttributes(self.numberedListAttributes, atIndex: level - 1, toString: attributedString, range: range) + let substring = attributedString.attributedSubstring(from: range).string.replacingOccurrences(of: " ", with: "\(nonBreakingSpaceCharacter)") + attributedString.replaceCharacters(in: range, with: "\(substring)") + }, textFormattingBlock: { attributedString, range, level in + RCMarkdownParser.addAttributes(self.numberedListAttributes, atIndex: level - 1, toString: attributedString, range: range) + }) + + addHeaderParsingWithLeadFormattingBlock({ attributedString, range, level in + attributedString.replaceCharacters(in: range, with: "") + }, textFormattingBlock: { attributedString, range, level in + if let attributes = self.headerAttributes[UInt(level)] { + attributedString.addAttributes(attributes, range: range) + } + }) + + addListParsingWithLeadFormattingBlock({ attributedString, range, level in + RCMarkdownParser.addAttributes(self.listAttributes, atIndex: level - 1, toString: attributedString, range: range) + let indentString = String(repeating: String(nonBreakingSpaceCharacter), count: level) + attributedString.replaceCharacters(in: range, with: "\(indentString)\u{2022}\u{00A0}") + }, textFormattingBlock: { attributedString, range, level in + RCMarkdownParser.addAttributes(self.listAttributes, atIndex: level - 1, toString: attributedString, range: range) + }) + + addQuoteBlockParsingWithFormattingBlock { attributedString, range in + attributedString.addAttributes(self.quoteBlockAttributes, range: range) + } + + addQuoteParsingWithLeadFormattingBlock({ attributedString, range, level in + attributedString.replaceCharacters(in: range, with: "") + }, textFormattingBlock: { attributedString, range, level in + attributedString.addAttributes(self.quoteAttributes, range: range) + }) + + addInlineCodeParsingWithFormattingBlock { attributedString, range in + attributedString.addAttributes(self.inlineCodeAttributes, range: range) + } + + addCodeParsingWithFormattingBlock { attributedString, range in + attributedString.addAttributes(self.codeAttributes, range: range) + } + + addStrongParsingWithFormattingBlock { attributedString, range in + attributedString.enumerateAttributes(in: range, options: []) { attributes, range, _ in + if let font = attributes[NSFontAttributeName] as? UIFont, let italicFont = self.italicAttributes[NSFontAttributeName] as? UIFont, font == italicFont { + attributedString.addAttributes(self.strongAndItalicAttributes, range: range) + } else { + attributedString.addAttributes(self.strongAttributes, range: range) + } + } + } + + addItalicParsingWithFormattingBlock { attributedString, range in + attributedString.enumerateAttributes(in: range, options: []) { attributes, range, _ in + if let font = attributes[NSFontAttributeName] as? UIFont, let boldFont = self.strongAttributes[NSFontAttributeName] as? UIFont, font == boldFont { + attributedString.addAttributes(self.strongAndItalicAttributes, range: range) + } else { + attributedString.addAttributes(self.italicAttributes, range: range) + } + } + } + + addStrikeParsingWithFormattingBlock { attributedString, range in + attributedString.addAttributes(self.strikeAttributes, range: range) + } + + addImageParsingWithImageFormattingBlock({ attributedString, range in + attributedString.addAttributes(self.imageAttributes, range: range) + }, alternativeTextFormattingBlock: { attributedString, range in + attributedString.addAttributes(self.imageAttributes, range: range) + }) + + addLinkParsingWithFormattingBlock { attributedString, range in + attributedString.addAttributes(self.linkAttributes, range: range) + } + + addAlternateLinkParsingWithFormattingBlock { attributedString, range in + attributedString.addAttributes(self.linkAttributes, range: range) + } + } + } + + open func addEscapingParsing() { + guard let escapingRegex = RCMarkdownRegex.regexForString(RCMarkdownRegex.Escaping) else { return } + + addParsingRuleWithRegularExpression(escapingRegex) { match, attributedString in + let range = NSRange(location: match.range.location + 1, length: 1) + let matchString = attributedString.attributedSubstring(from: range).string as NSString + let escapedString = NSString(format: "%04x", matchString.character(at: 0)) as String + attributedString.replaceCharacters(in: range, with: escapedString) + } + } + + open func addCodeEscapingParsing() { + guard let codingParsingRegex = RCMarkdownRegex.regexForString(RCMarkdownRegex.CodeEscaping) else { return } + + addParsingRuleWithRegularExpression(codingParsingRegex) { match, attributedString in + let range = match.rangeAt(2) + let matchString = attributedString.attributedSubstring(from: range).string as NSString + + var escapedString = "" + for index in 0.. 0 ? "\(maxLevel)" : "") as String + }() + + guard let regex = RCMarkdownRegex.regexForString(regexString, options: .anchorsMatchLines) else { return } + + addParsingRuleWithRegularExpression(regex) { match, attributedString in + let level = match.rangeAt(1).length + formattingBlock?(attributedString, match.rangeAt(2), level) + leadFormattingBlock(attributedString, NSRange(location: match.rangeAt(1).location, length: match.rangeAt(2).location - match.rangeAt(1).location), level) + } + } + + open func addHeaderParsingWithLeadFormattingBlock(_ leadFormattingBlock: @escaping RCMarkdownParserLevelFormattingBlock, maxLevel: Int? = nil, textFormattingBlock formattingBlock: RCMarkdownParserLevelFormattingBlock?) { + addLeadParsingWithPattern(RCMarkdownRegex.Header, maxLevel: maxLevel, leadFormattingBlock: leadFormattingBlock, formattingBlock: formattingBlock) + } + + open func addListParsingWithLeadFormattingBlock(_ leadFormattingBlock: @escaping RCMarkdownParserLevelFormattingBlock, maxLevel: Int? = nil, textFormattingBlock formattingBlock: RCMarkdownParserLevelFormattingBlock?) { + addLeadParsingWithPattern(RCMarkdownRegex.List, maxLevel: maxLevel, leadFormattingBlock: leadFormattingBlock, formattingBlock: formattingBlock) + } + + open func addNumberedListParsingWithLeadFormattingBlock(_ leadFormattingBlock: @escaping RCMarkdownParserLevelFormattingBlock, maxLevel: Int? = nil, textFormattingBlock formattingBlock: RCMarkdownParserLevelFormattingBlock?) { + addLeadParsingWithPattern(RCMarkdownRegex.NumberedList, maxLevel: maxLevel, leadFormattingBlock: leadFormattingBlock, formattingBlock: formattingBlock) + } + + open func addQuoteParsingWithLeadFormattingBlock(_ leadFormattingBlock: @escaping RCMarkdownParserLevelFormattingBlock, textFormattingBlock formattingBlock: RCMarkdownParserLevelFormattingBlock?) { + addLeadParsingWithPattern(RCMarkdownRegex.Quote, maxLevel: 1, leadFormattingBlock: leadFormattingBlock, formattingBlock: formattingBlock) + } + + open func addQuoteBlockParsingWithFormattingBlock(_ formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + addEnclosedParsingWithPattern(RCMarkdownRegex.QuoteBlock, formattingBlock: formattingBlock) + } + + open func addImageParsingWithImageFormattingBlock(_ formattingBlock: RCMarkdownParserFormattingBlock?, alternativeTextFormattingBlock alternateFormattingBlock: RCMarkdownParserFormattingBlock?) { + guard let headerRegex = RCMarkdownRegex.regexForString(RCMarkdownRegex.Image, options: RCMarkdownRegex.ImageOptions) else { return } + + addParsingRuleWithRegularExpression(headerRegex) { match, attributedString in + let imagePathStart = (attributedString.string as NSString).range(of: "(", options: [], range: match.range).location + let linkRange = NSRange(location: imagePathStart, length: match.range.length + match.range.location - imagePathStart - 1) + let imagePath = (attributedString.string as NSString).substring(with: NSRange(location: linkRange.location + 1, length: linkRange.length - 1)) + + let linkTextEndLocation = (attributedString.string as NSString).range(of: "]", options: [], range: match.range).location + let linkTextRange = NSRange(location: match.range.location + 2, length: linkTextEndLocation - match.range.location - 2) + let alternativeText = (attributedString.string as NSString).substring(with: linkTextRange) + attributedString.replaceCharacters(in: match.range, with: alternativeText) + + let alternativeRange = NSRange(location: match.range.location, length: (alternativeText as NSString).length) + attributedString.addAttribute(NSLinkAttributeName, value: imagePath, range: alternativeRange) + alternateFormattingBlock?(attributedString, alternativeRange) + + self.downloadImage(imagePath) { image in + if let image = image { + let imageAttatchment = NSTextAttachment() + imageAttatchment.image = image + imageAttatchment.bounds = CGRect(x: 0, y: -5, width: image.size.width, height: image.size.height) + let imageString = NSAttributedString(attachment: imageAttatchment) + attributedString.replaceCharacters(in: NSRange(location: match.range.location, length: alternativeText.count), with: imageString) + formattingBlock?(attributedString, NSRange(location: match.range.location, length: 1)) + } + } + } + } + + open func addLinkParsingWithFormattingBlock(_ formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + guard let linkRegex = RCMarkdownRegex.regexForString(RCMarkdownRegex.Link, options: RCMarkdownRegex.LinkOptions) else { return } + + addParsingRuleWithRegularExpression(linkRegex) { [weak self] match, attributedString in + let linkStartinResult = (attributedString.string as NSString).range(of: "(", options: .backwards, range: match.range).location + let linkRange = NSRange(location: linkStartinResult, length: match.range.length + match.range.location - linkStartinResult - 1) + let linkUrlString = (attributedString.string as NSString).substring(with: NSRange(location: linkRange.location + 1, length: linkRange.length - 1)) + + let linkTextRange = NSRange(location: match.range.location + 1, length: linkStartinResult - match.range.location - 2) + attributedString.deleteCharacters(in: NSRange(location: linkRange.location - 1, length: linkRange.length + 2)) + + if let linkUrlString = self?.unescaped(string: linkUrlString), let url = URL(string: linkUrlString) ?? URL(string: linkUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? linkUrlString) { + attributedString.addAttribute(NSLinkAttributeName, value: url, range: linkTextRange) + } + formattingBlock(attributedString, linkTextRange) + + attributedString.deleteCharacters(in: NSRange(location: match.range.location, length: 1)) + } + } + + open func addAlternateLinkParsingWithFormattingBlock(_ formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + guard let linkRegex = RCMarkdownRegex.regexForString(RCMarkdownRegex.AlternateLink, options: RCMarkdownRegex.AlternateLinkOptions) + else { return } + + addParsingRuleWithRegularExpression(linkRegex) { [weak self] match, attributedString in + func string() -> NSString { return attributedString.string as NSString } + let linkEnd = string().range(of: "|", options: .backwards, range: match.range) + let linkStart = string().range(of: "<", options: .backwards, range: NSRange(location: match.range.location, length: linkEnd.location - match.range.location)) + let linkRange = NSRange(location: linkStart.location, length: linkEnd.location - linkStart.location + 1) + let linkUrlRange = NSRange(location: linkRange.location + 1, length: linkRange.length - 2) + let linkUrlString = string().substring(with: linkUrlRange) + + let linkTextLength = match.range.length + match.range.location - linkEnd.location - 1 + let linkTextRange = NSRange(location: linkEnd.location + 1, length: linkTextLength) + + let linkTextString = string().substring(with: linkTextRange) + + attributedString.deleteCharacters(in: NSRange(location: linkRange.location, length: linkRange.length)) + + if let linkUrlString = self?.unescaped(string: linkUrlString), let url = URL(string: linkUrlString) ?? URL(string: linkUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? linkUrlString) { + attributedString.addAttribute(NSLinkAttributeName, value: url, range: string().range(of: linkTextString)) + } + + attributedString.deleteCharacters(in: string().range(of: ">", options: .backwards)) + } + } + + fileprivate func addEnclosedParsingWithPattern(_ pattern: String, options: NSRegularExpression.Options = [], formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + guard let regex = RCMarkdownRegex.regexForString(pattern, options: options) else { return } + + addParsingRuleWithRegularExpression(regex) { match, attributedString in + attributedString.deleteCharacters(in: match.rangeAt(3)) + formattingBlock(attributedString, match.rangeAt(2)) + attributedString.deleteCharacters(in: match.rangeAt(1)) + } + } + + open func addInlineCodeParsingWithFormattingBlock(_ formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + addEnclosedParsingWithPattern(RCMarkdownRegex.InlineCode, options: RCMarkdownRegex.InlineCodeOptions, formattingBlock: formattingBlock) + } + + open func addCodeParsingWithFormattingBlock(_ formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + addEnclosedParsingWithPattern(RCMarkdownRegex.Code, formattingBlock: formattingBlock) + } + + open func addStrongParsingWithFormattingBlock(_ formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + addEnclosedParsingWithPattern(RCMarkdownRegex.Strong, options: RCMarkdownRegex.StrongOptions, formattingBlock: formattingBlock) + } + + open func addItalicParsingWithFormattingBlock(_ formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + addEnclosedParsingWithPattern(RCMarkdownRegex.Italic, options: RCMarkdownRegex.ItalicOptions, formattingBlock: formattingBlock) + } + + open func addStrikeParsingWithFormattingBlock(_ formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + addEnclosedParsingWithPattern(RCMarkdownRegex.Strike, options: RCMarkdownRegex.StrikeOptions, formattingBlock: formattingBlock) + } + + open func addLinkDetectionWithFormattingBlock(_ formattingBlock: @escaping RCMarkdownParserFormattingBlock) { + do { + let linkDataDetector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) + addParsingRuleWithRegularExpression(linkDataDetector) { [weak self] match, attributedString in + if let urlString = match.url?.absoluteString.removingPercentEncoding, let unescapedUrlString = self?.unescaped(string: urlString), let url = URL(string: unescapedUrlString) { + attributedString.addAttribute(NSLinkAttributeName, value: url, range: match.range) + } + formattingBlock(attributedString, match.range) + } + } catch { } + } + + func unescaped(string: String) -> String? { + guard let unescapingRegex = RCMarkdownRegex.regexForString(RCMarkdownRegex.Unescaping, options: .dotMatchesLineSeparators) else { return nil } + + var location = 0 + let unescapedMutableString = NSMutableString(string: string) + while let match = unescapingRegex.firstMatch(in: unescapedMutableString as String, options: .withoutAnchoringBounds, range: NSRange(location: location, length: unescapedMutableString.length - location)) { + let oldLength = unescapedMutableString.length + let range = NSRange(location: match.range.location + 1, length: 4) + let matchString = unescapedMutableString.substring(with: range) + let unescapedString = RCMarkdownParser.stringWithHexaString(matchString, atIndex: 0) + unescapedMutableString.replaceCharacters(in: match.range, with: unescapedString) + let newLength = unescapedMutableString.length + location = match.range.location + match.range.length + newLength - oldLength + } + + return unescapedMutableString as String + } + + fileprivate class func stringWithHexaString(_ hexaString: String, atIndex index: Int) -> String { + let range = hexaString.characters.index(hexaString.startIndex, offsetBy: index).. () + public typealias NetworkUnreachable = (Reachability) -> () + + @available(*, unavailable, renamed: "Connection") + public enum NetworkStatus: CustomStringConvertible { + case notReachable, reachableViaWiFi, reachableViaWWAN + public var description: String { + switch self { + case .reachableViaWWAN: return "Cellular" + case .reachableViaWiFi: return "WiFi" + case .notReachable: return "No Connection" + } + } + } + + public enum Connection: CustomStringConvertible { + case none, wifi, cellular + public var description: String { + switch self { + case .cellular: return "Cellular" + case .wifi: return "WiFi" + case .none: return "No Connection" + } + } + } + + public var whenReachable: NetworkReachable? + public var whenUnreachable: NetworkUnreachable? + + @available(*, deprecated: 4.0, renamed: "allowsCellularConnection") + public let reachableOnWWAN: Bool = true + + /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`) + public var allowsCellularConnection: Bool + + // The notification center on which "reachability changed" events are being posted + public var notificationCenter: NotificationCenter = NotificationCenter.default + + @available(*, deprecated: 4.0, renamed: "connection.description") + public var currentReachabilityString: String { + return "\(connection)" + } + + @available(*, unavailable, renamed: "connection") + public var currentReachabilityStatus: Connection { + return connection + } + + public var connection: Connection { + if flags == nil { + try? setReachabilityFlags() + } + + switch flags?.connection { + case .none?, nil: return .none + case .cellular?: return allowsCellularConnection ? .cellular : .none + case .wifi?: return .wifi + } + } + + fileprivate var isRunningOnDevice: Bool = { + #if targetEnvironment(simulator) + return false + #else + return true + #endif + }() + + fileprivate var notifierRunning = false + fileprivate let reachabilityRef: SCNetworkReachability + fileprivate let reachabilitySerialQueue: DispatchQueue + fileprivate(set) var flags: SCNetworkReachabilityFlags? { + didSet { + guard flags != oldValue else { return } + reachabilityChanged() + } + } + + required public init(reachabilityRef: SCNetworkReachability, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { + self.allowsCellularConnection = true + self.reachabilityRef = reachabilityRef + self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue) + } + + public convenience init?(hostname: String, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { + guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } + self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) + } + + public convenience init?(queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { + var zeroAddress = sockaddr() + zeroAddress.sa_len = UInt8(MemoryLayout.size) + zeroAddress.sa_family = sa_family_t(AF_INET) + + guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil } + + self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) + } + + deinit { + stopNotifier() + } +} + +public extension Reachability { + + // MARK: - *** Notifier methods *** + func startNotifier() throws { + guard !notifierRunning else { return } + + let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in + guard let info = info else { return } + + let reachability = Unmanaged.fromOpaque(info).takeUnretainedValue() + reachability.flags = flags + } + + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) + if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { + stopNotifier() + throw ReachabilityError.UnableToSetCallback + } + + if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { + stopNotifier() + throw ReachabilityError.UnableToSetDispatchQueue + } + + // Perform an initial check + try setReachabilityFlags() + + notifierRunning = true + } + + func stopNotifier() { + defer { notifierRunning = false } + + SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) + } + + // MARK: - *** Connection test methods *** + @available(*, deprecated: 4.0, message: "Please use `connection != .none`") + var isReachable: Bool { + return connection != .none + } + + @available(*, deprecated: 4.0, message: "Please use `connection == .cellular`") + var isReachableViaWWAN: Bool { + // Check we're not on the simulator, we're REACHABLE and check we're on WWAN + return connection == .cellular + } + + @available(*, deprecated: 4.0, message: "Please use `connection == .wifi`") + var isReachableViaWiFi: Bool { + return connection == .wifi + } + + var description: String { + guard let flags = flags else { return "unavailable flags" } + let W = isRunningOnDevice ? (flags.isOnWWANFlagSet ? "W" : "-") : "X" + let R = flags.isReachableFlagSet ? "R" : "-" + let c = flags.isConnectionRequiredFlagSet ? "c" : "-" + let t = flags.isTransientConnectionFlagSet ? "t" : "-" + let i = flags.isInterventionRequiredFlagSet ? "i" : "-" + let C = flags.isConnectionOnTrafficFlagSet ? "C" : "-" + let D = flags.isConnectionOnDemandFlagSet ? "D" : "-" + let l = flags.isLocalAddressFlagSet ? "l" : "-" + let d = flags.isDirectFlagSet ? "d" : "-" + + return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" + } +} + +fileprivate extension Reachability { + + func setReachabilityFlags() throws { + try reachabilitySerialQueue.sync { [unowned self] in + var flags = SCNetworkReachabilityFlags() + if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) { + self.stopNotifier() + throw ReachabilityError.UnableToGetInitialFlags + } + + self.flags = flags + } + } + + func reachabilityChanged() { + let block = connection != .none ? whenReachable : whenUnreachable + + DispatchQueue.main.async { [weak self] in + guard let strongSelf = self else { return } + block?(strongSelf) + strongSelf.notificationCenter.post(name: .reachabilityChanged, object: strongSelf) + } + } +} + +extension SCNetworkReachabilityFlags { + + typealias Connection = Reachability.Connection + + var connection: Connection { + guard isReachableFlagSet else { return .none } + + // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi + #if targetEnvironment(simulator) + return .wifi + #else + var connection = Connection.none + + if !isConnectionRequiredFlagSet { + connection = .wifi + } + + if isConnectionOnTrafficOrDemandFlagSet { + if !isInterventionRequiredFlagSet { + connection = .wifi + } + } + + if isOnWWANFlagSet { + connection = .cellular + } + + return connection + #endif + } + + var isOnWWANFlagSet: Bool { + #if os(iOS) + return contains(.isWWAN) + #else + return false + #endif + } + var isReachableFlagSet: Bool { + return contains(.reachable) + } + var isConnectionRequiredFlagSet: Bool { + return contains(.connectionRequired) + } + var isInterventionRequiredFlagSet: Bool { + return contains(.interventionRequired) + } + var isConnectionOnTrafficFlagSet: Bool { + return contains(.connectionOnTraffic) + } + var isConnectionOnDemandFlagSet: Bool { + return contains(.connectionOnDemand) + } + var isConnectionOnTrafficOrDemandFlagSet: Bool { + return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty + } + var isTransientConnectionFlagSet: Bool { + return contains(.transientConnection) + } + var isLocalAddressFlagSet: Bool { + return contains(.isLocalAddress) + } + var isDirectFlagSet: Bool { + return contains(.isDirect) + } + var isConnectionRequiredAndTransientFlagSet: Bool { + return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] + } +} diff --git a/Pods/Realm/LICENSE b/Pods/Realm/LICENSE new file mode 100644 index 0000000000..57a0e0b24a --- /dev/null +++ b/Pods/Realm/LICENSE @@ -0,0 +1,248 @@ +TABLE OF CONTENTS + +1. Apache License version 2.0 +2. Realm Components +3. Export Compliance + +1. ------------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +2. ------------------------------------------------------------------------------- + +REALM COMPONENTS + +This software contains components with separate copyright and license terms. +Your use of these components is subject to the terms and conditions of the +following licenses. + +For the Realm Platform Extensions component + + Realm Platform Extensions License + + Copyright (c) 2011-2017 Realm Inc All rights reserved + + Redistribution and use in binary form, with or without modification, is + permitted provided that the following conditions are met: + + 1. You agree not to attempt to decompile, disassemble, reverse engineer or + otherwise discover the source code from which the binary code was derived. + You may, however, access and obtain a separate license for most of the + source code from which this Software was created, at + http://realm.io/pricing/. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + +3. ------------------------------------------------------------------------------- + +EXPORT COMPLIANCE + +You understand that the Software may contain cryptographic functions that may be +subject to export restrictions, and you represent and warrant that you are not +(i) located in a jurisdiction that is subject to United States economic +sanctions (“Prohibited Jurisdiction”), including Cuba, Iran, North Korea, +Sudan, Syria or the Crimea region, (ii) a person listed on any U.S. government +blacklist (to include the List of Specially Designated Nationals and Blocked +Persons or the Consolidated Sanctions List administered by the U.S. Department +of the Treasury’s Office of Foreign Assets Control, or the Denied Persons List +or Entity List administered by the U.S. Department of Commerce) +(“Sanctioned Person”), or (iii) controlled or 50% or more owned by a Sanctioned +Person. + +You agree to comply with all export, re-export and import restrictions and +regulations of the U.S. Department of Commerce or other agency or authority of +the United States or other applicable countries. You also agree not to transfer, +or authorize the transfer of, directly or indirectly, of the Software to any +Prohibited Jurisdiction, or otherwise in violation of any such restrictions or +regulations. diff --git a/Pods/Realm/README.md b/Pods/Realm/README.md new file mode 100644 index 0000000000..ae255b289e --- /dev/null +++ b/Pods/Realm/README.md @@ -0,0 +1,74 @@ +![Realm](https://github.com/realm/realm-cocoa/raw/master/logo.png) + +Realm is a mobile database that runs directly inside phones, tablets or wearables. +This repository holds the source code for the iOS, macOS, tvOS & watchOS versions of Realm Swift & Realm Objective-C. + +## Features + +* **Mobile-first:** Realm is the first database built from the ground up to run directly inside phones, tablets and wearables. +* **Simple:** Data is directly [exposed as objects](https://realm.io/docs/objc/latest/#models) and [queryable by code](https://realm.io/docs/objc/latest/#queries), removing the need for ORM's riddled with performance & maintenance issues. Most of our users pick it up intuitively, getting simple apps up & running in minutes. +* **Modern:** Realm supports relationships, generics, vectorization and Swift. +* **Fast:** Realm is faster than even raw SQLite on common operations, while maintaining an extremely rich feature set. + +## Getting Started + +Please see the detailed instructions in our docs to add [Realm Objective-C](https://realm.io/docs/objc/latest/#installation) _or_ [Realm Swift](https://realm.io/docs/swift/latest/#installation) to your Xcode project. + +## Documentation + +### Realm Objective-C + +The documentation can be found at [realm.io/docs/objc/latest](https://realm.io/docs/objc/latest). +The API reference is located at [realm.io/docs/objc/latest/api](https://realm.io/docs/objc/latest/api). + +### Realm Swift + +The documentation can be found at [realm.io/docs/swift/latest](https://realm.io/docs/swift/latest). +The API reference is located at [realm.io/docs/swift/latest/api](https://realm.io/docs/swift/latest/api). + +## Getting Help + +- **Need help with your code?**: Look for previous questions on the [#realm tag](https://stackoverflow.com/questions/tagged/realm?sort=newest) — or [ask a new question](https://stackoverflow.com/questions/ask?tags=realm). We actively monitor & answer questions on SO! +- **Have a bug to report?** [Open an issue](https://github.com/realm/realm-cocoa/issues/new). If possible, include the version of Realm, a full log, the Realm file, and a project that shows the issue. +- **Have a feature request?** [Open an issue](https://github.com/realm/realm-cocoa/issues/new). Tell us what the feature should do, and why you want the feature. +- Sign up for our [**Community Newsletter**](https://realm.io/realm-news-subscribe) to get regular tips, learn about other use-cases and get alerted of blogposts and tutorials about Realm. + +## Building Realm + +In case you don't want to use the precompiled version, you can build Realm yourself from source. + +Prerequisites: + +* Building Realm requires Xcode 8.x. +* If cloning from git, submodules are required: `git submodule update --init --recursive`. +* Building Realm documentation requires [jazzy](https://github.com/realm/jazzy) + +Once you have all the necessary prerequisites, building Realm.framework just takes a single command: `sh build.sh build`. You'll need an internet connection the first time you build Realm to download the core binary. + +Run `sh build.sh help` to see all the actions you can perform (build ios/osx, generate docs, test, etc.). + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md) for more details! + +This project adheres to the [Contributor Covenant Code of Conduct](https://realm.io/conduct). +By participating, you are expected to uphold this code. Please report +unacceptable behavior to [info@realm.io](mailto:info@realm.io). + +## License + +Realm Objective-C & Realm Swift are published under the Apache 2.0 license. +Realm Core is also published under the Apache 2.0 license and is available +[here](https://github.com/realm/realm-core). + +**This product is not being made available to any person located in Cuba, Iran, +North Korea, Sudan, Syria or the Crimea region, or to any other person that is +not eligible to receive the product under U.S. law.** + +## Feedback + +**_If you use Realm and are happy with it, all we ask is that you please consider sending out a tweet mentioning [@realm](https://twitter.com/realm) to share your thoughts!_** + +**_And if you don't like it, please let us know what you would like improved, so we can fix it!_** + +![analytics](https://ga-beacon.appspot.com/UA-50247013-2/realm-cocoa/README?pixel) diff --git a/Pods/Realm/Realm/NSError+RLMSync.m b/Pods/Realm/Realm/NSError+RLMSync.m new file mode 100644 index 0000000000..e8c25903eb --- /dev/null +++ b/Pods/Realm/Realm/NSError+RLMSync.m @@ -0,0 +1,43 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "NSError+RLMSync.h" + +#import "RLMSyncUtil.h" + +@implementation NSError (RLMSync) + +- (RLMSyncErrorActionToken *)rlmSync_errorActionToken { + if (self.domain != RLMSyncErrorDomain) { + return nil; + } + if (self.code == RLMSyncErrorClientResetError + || self.code == RLMSyncErrorPermissionDeniedError) { + return (RLMSyncErrorActionToken *)self.userInfo[kRLMSyncErrorActionTokenKey]; + } + return nil; +} + +- (NSString *)rlmSync_clientResetBackedUpRealmPath { + if (self.domain == RLMSyncErrorDomain && self.code == RLMSyncErrorClientResetError) { + return self.userInfo[kRLMSyncPathOfRealmBackupCopyKey]; + } + return nil; +} + +@end diff --git a/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp b/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp new file mode 100644 index 0000000000..0c388d0686 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp @@ -0,0 +1,23 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "binding_callback_thread_observer.hpp" + +namespace realm { +BindingCallbackThreadObserver* g_binding_callback_thread_observer = nullptr; +} diff --git a/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp b/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp new file mode 100644 index 0000000000..03fad73f14 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp @@ -0,0 +1,61 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "collection_notifications.hpp" + +#include "impl/collection_notifier.hpp" + +using namespace realm; +using namespace realm::_impl; + +NotificationToken::NotificationToken(std::shared_ptr<_impl::CollectionNotifier> notifier, uint64_t token) +: m_notifier(std::move(notifier)), m_token(token) +{ +} + +NotificationToken::~NotificationToken() +{ + // m_notifier itself (and not just the pointed-to thing) needs to be accessed + // atomically to ensure that there are no data races when the token is + // destroyed after being modified on a different thread. + // This is needed despite the token not being thread-safe in general as + // users find it very surprising for obj-c objects to care about what + // thread they are deallocated on. + if (auto notifier = m_notifier.exchange({})) { + notifier->remove_callback(m_token); + } +} + +NotificationToken::NotificationToken(NotificationToken&&) = default; + +NotificationToken& NotificationToken::operator=(realm::NotificationToken&& rgt) +{ + if (this != &rgt) { + if (auto notifier = m_notifier.exchange({})) { + notifier->remove_callback(m_token); + } + m_notifier = std::move(rgt.m_notifier); + m_token = rgt.m_token; + } + return *this; +} + +void NotificationToken::suppress_next() +{ + m_notifier.load()->suppress_next_notification(m_token); +} diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp new file mode 100644 index 0000000000..60f7a660a4 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp @@ -0,0 +1,229 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/external_commit_helper.hpp" + +#include "impl/realm_coordinator.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace realm; +using namespace realm::_impl; + +namespace { +// Write a byte to a pipe to notify anyone waiting for data on the pipe +void notify_fd(int fd, int read_fd) +{ + while (true) { + char c = 0; + ssize_t ret = write(fd, &c, 1); + if (ret == 1) { + break; + } + + // If the pipe's buffer is full, we need to read some of the old data in + // it to make space. We don't just read in the code waiting for + // notifications so that we can notify multiple waiters with a single + // write. + assert(ret == -1 && errno == EAGAIN); + char buff[1024]; + read(read_fd, buff, sizeof buff); + } +} +} // anonymous namespace + +void ExternalCommitHelper::FdHolder::close() +{ + if (m_fd != -1) { + ::close(m_fd); + } + m_fd = -1; +} + +// Inter-thread and inter-process notifications of changes are done using a +// named pipe in the filesystem next to the Realm file. Everyone who wants to be +// notified of commits waits for data to become available on the pipe, and anyone +// who commits a write transaction writes data to the pipe after releasing the +// write lock. Note that no one ever actually *reads* from the pipe: the data +// actually written is meaningless, and trying to read from a pipe from multiple +// processes at once is fraught with race conditions. + +// When a RLMRealm instance is created, we add a CFRunLoopSource to the current +// thread's runloop. On each cycle of the run loop, the run loop checks each of +// its sources for work to do, which in the case of CFRunLoopSource is just +// checking if CFRunLoopSourceSignal has been called since the last time it ran, +// and if so invokes the function pointer supplied when the source is created, +// which in our case just invokes `[realm handleExternalChange]`. + +// Listening for external changes is done using kqueue() on a background thread. +// kqueue() lets us efficiently wait until the amount of data which can be read +// from one or more file descriptors has changed, and tells us which of the file +// descriptors it was that changed. We use this to wait on both the shared named +// pipe, and a local anonymous pipe. When data is written to the named pipe, we +// signal the runloop source and wake up the target runloop, and when data is +// written to the anonymous pipe the background thread removes the runloop +// source from the runloop and and shuts down. +ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent) +: m_parent(parent) +{ + m_kq = kqueue(); + if (m_kq == -1) { + throw std::system_error(errno, std::system_category()); + } + +#if !TARGET_OS_TV + auto path = parent.get_path() + ".note"; + + // Create and open the named pipe + int ret = mkfifo(path.c_str(), 0600); + if (ret == -1) { + int err = errno; + if (err == ENOTSUP) { + // Filesystem doesn't support named pipes, so try putting it in tmp instead + // Hash collisions are okay here because they just result in doing + // extra work, as opposed to correctness problems + std::ostringstream ss; + ss << getenv("TMPDIR"); + ss << "realm_" << std::hash()(path) << ".note"; + path = ss.str(); + ret = mkfifo(path.c_str(), 0600); + err = errno; + } + // the fifo already existing isn't an error + if (ret == -1 && err != EEXIST) { + throw std::system_error(err, std::system_category()); + } + } + + m_notify_fd = open(path.c_str(), O_RDWR); + if (m_notify_fd == -1) { + throw std::system_error(errno, std::system_category()); + } + + // Make writing to the pipe return -1 when the pipe's buffer is full + // rather than blocking until there's space available + ret = fcntl(m_notify_fd, F_SETFL, O_NONBLOCK); + if (ret == -1) { + throw std::system_error(errno, std::system_category()); + } + +#else // !TARGET_OS_TV + + // tvOS does not support named pipes, so use an anonymous pipe instead + int notification_pipe[2]; + int ret = pipe(notification_pipe); + if (ret == -1) { + throw std::system_error(errno, std::system_category()); + } + + m_notify_fd = notification_pipe[0]; + m_notify_fd_write = notification_pipe[1]; + +#endif // TARGET_OS_TV + + // Create the anonymous pipe for shutdown notifications + int shutdown_pipe[2]; + ret = pipe(shutdown_pipe); + if (ret == -1) { + throw std::system_error(errno, std::system_category()); + } + + m_shutdown_read_fd = shutdown_pipe[0]; + m_shutdown_write_fd = shutdown_pipe[1]; + + m_thread = std::async(std::launch::async, [=] { + try { + listen(); + } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + catch (std::exception const& e) { + fprintf(stderr, "uncaught exception in notifier thread: %s: %s\n", typeid(e).name(), e.what()); + asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "uncaught exception in notifier thread: %s: %s", typeid(e).name(), e.what()); + throw; + } + catch (...) { + fprintf(stderr, "uncaught exception in notifier thread\n"); + asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "uncaught exception in notifier thread"); + throw; + } +#pragma clang diagnostic pop + }); +} + +ExternalCommitHelper::~ExternalCommitHelper() +{ + notify_fd(m_shutdown_write_fd, m_shutdown_read_fd); + m_thread.wait(); // Wait for the thread to exit +} + +void ExternalCommitHelper::listen() +{ + pthread_setname_np("RLMRealm notification listener"); + + // Set up the kqueue + // EVFILT_READ indicates that we care about data being available to read + // on the given file descriptor. + // EV_CLEAR makes it wait for the amount of data available to be read to + // change rather than just returning when there is any data to read. + struct kevent ke[2]; + EV_SET(&ke[0], m_notify_fd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, 0); + EV_SET(&ke[1], m_shutdown_read_fd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, 0); + int ret = kevent(m_kq, ke, 2, nullptr, 0, nullptr); + assert(ret == 0); + + while (true) { + struct kevent event; + // Wait for data to become on either fd + // Return code is number of bytes available or -1 on error + ret = kevent(m_kq, nullptr, 0, &event, 1, nullptr); + assert(ret >= 0); + if (ret == 0) { + // Spurious wakeup; just wait again + continue; + } + + // Check which file descriptor had activity: if it's the shutdown + // pipe, then someone called -stop; otherwise it's the named pipe + // and someone committed a write transaction + if (event.ident == (uint32_t)m_shutdown_read_fd) { + return; + } + assert(event.ident == (uint32_t)m_notify_fd); + + m_parent.on_change(); + } +} + +void ExternalCommitHelper::notify_others() +{ + if (m_notify_fd_write != -1) { + notify_fd(m_notify_fd_write, m_notify_fd); + } + else { + notify_fd(m_notify_fd, m_notify_fd); + } +} diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp new file mode 100644 index 0000000000..8c9000cd18 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp @@ -0,0 +1,143 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/apple/keychain_helper.hpp" + + +#include +#include + +#include + +#include + +using realm::util::CFPtr; +using realm::util::adoptCF; +using realm::util::retainCF; + +namespace realm { +namespace keychain { + +KeychainAccessException::KeychainAccessException(int32_t error_code) +: std::runtime_error(util::format("Keychain returned unexpected status code: %1", error_code)) { } + +namespace { + +constexpr size_t key_size = 64; + +#if !TARGET_IPHONE_SIMULATOR +CFPtr convert_string(const std::string& string) +{ + auto result = adoptCF(CFStringCreateWithBytes(nullptr, reinterpret_cast(string.data()), + string.size(), kCFStringEncodingASCII, false)); + if (!result) { + throw std::bad_alloc(); + } + return result; +} +#endif + +CFPtr build_search_dictionary(CFStringRef account, CFStringRef service, + __unused util::Optional group) +{ + auto d = adoptCF(CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); + if (!d) + throw std::bad_alloc(); + + CFDictionaryAddValue(d.get(), kSecClass, kSecClassGenericPassword); + CFDictionaryAddValue(d.get(), kSecReturnData, kCFBooleanTrue); + CFDictionaryAddValue(d.get(), kSecAttrAccessible, kSecAttrAccessibleAlways); + CFDictionaryAddValue(d.get(), kSecAttrAccount, account); + CFDictionaryAddValue(d.get(), kSecAttrService, service); +#if !TARGET_IPHONE_SIMULATOR + if (group) + CFDictionaryAddValue(d.get(), kSecAttrAccessGroup, convert_string(*group).get()); +#endif + return d; +} + +/// Get the encryption key for a given service, returning it only if it exists. +util::Optional> get_key(CFStringRef account, CFStringRef service) +{ + auto search_dictionary = build_search_dictionary(account, service, none); + CFDataRef retained_key_data; + if (OSStatus status = SecItemCopyMatching(search_dictionary.get(), (CFTypeRef *)&retained_key_data)) { + if (status != errSecItemNotFound) + throw KeychainAccessException(status); + + // Key was not found. + return none; + } + + // Key was previously stored. Extract it. + CFPtr key_data = adoptCF(retained_key_data); + if (key_size != CFDataGetLength(key_data.get())) + throw std::runtime_error("Password stored in keychain was not expected size."); + + auto key_bytes = reinterpret_cast(CFDataGetBytePtr(key_data.get())); + return std::vector(key_bytes, key_bytes + key_size); +} + +void set_key(const std::vector& key, CFStringRef account, CFStringRef service) +{ + auto search_dictionary = build_search_dictionary(account, service, none); + auto key_data = adoptCF(CFDataCreate(nullptr, reinterpret_cast(key.data()), key_size)); + if (!key_data) + throw std::bad_alloc(); + + CFDictionaryAddValue(search_dictionary.get(), kSecValueData, key_data.get()); + if (OSStatus status = SecItemAdd(search_dictionary.get(), nullptr)) + throw KeychainAccessException(status); +} + +} // anonymous namespace + +std::vector metadata_realm_encryption_key(bool check_legacy_service) +{ + CFStringRef account = CFSTR("metadata"); + CFStringRef legacy_service = CFSTR("io.realm.sync.keychain"); + + CFPtr service; + if (CFStringRef bundle_id = CFBundleGetIdentifier(CFBundleGetMainBundle())) + service = adoptCF(CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ - Realm Sync Metadata Key"), bundle_id)); + else { + service = retainCF(legacy_service); + check_legacy_service = false; + } + + // Try retrieving the key. + if (auto existing_key = get_key(account, service.get())) { + return *existing_key; + } else if (check_legacy_service) { + // See if there's a key stored using the legacy shared keychain item. + if (auto existing_legacy_key = get_key(account, legacy_service)) { + // If so, copy it to the per-app keychain item before returning it. + set_key(*existing_legacy_key, account, service.get()); + return *existing_legacy_key; + } + } + // Make a completely new key. + std::vector key(key_size); + arc4random_buf(key.data(), key_size); + set_key(key, account, service.get()); + return key; +} + +} // keychain +} // realm diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp new file mode 100644 index 0000000000..40b5754e60 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp @@ -0,0 +1,887 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/collection_change_builder.hpp" + +#include +#include + +#include + +using namespace realm; +using namespace realm::_impl; + +CollectionChangeBuilder::CollectionChangeBuilder(IndexSet deletions, + IndexSet insertions, + IndexSet modifications, + std::vector moves) +: CollectionChangeSet({std::move(deletions), std::move(insertions), std::move(modifications), {}, std::move(moves)}) +{ + for (auto&& move : this->moves) { + this->deletions.add(move.from); + this->insertions.add(move.to); + } +} + +void CollectionChangeBuilder::merge(CollectionChangeBuilder&& c) +{ + if (c.empty()) + return; + if (empty()) { + *this = std::move(c); + return; + } + + verify(); + c.verify(); + + auto for_each_col = [&](auto&& f) { + f(modifications, c.modifications); + if (m_track_columns) { + if (columns.size() < c.columns.size()) + columns.resize(c.columns.size()); + else if (columns.size() > c.columns.size()) + c.columns.resize(columns.size()); + for (size_t i = 0; i < columns.size(); ++i) + f(columns[i], c.columns[i]); + } + }; + + // First update any old moves + if (!c.moves.empty() || !c.deletions.empty() || !c.insertions.empty()) { + auto it = std::remove_if(begin(moves), end(moves), [&](auto& old) { + // Check if the moved row was moved again, and if so just update the destination + auto it = find_if(begin(c.moves), end(c.moves), [&](auto const& m) { + return old.to == m.from; + }); + if (it != c.moves.end()) { + for_each_col([&](auto& col, auto& other) { + if (col.contains(it->from)) + other.add(it->to); + }); + old.to = it->to; + *it = c.moves.back(); + c.moves.pop_back(); + return false; + } + + // Check if the destination was deleted + // Removing the insert for this move will happen later + if (c.deletions.contains(old.to)) + return true; + + // Update the destination to adjust for any new insertions and deletions + old.to = c.insertions.shift(c.deletions.unshift(old.to)); + return false; + }); + moves.erase(it, end(moves)); + } + + // Ignore new moves of rows which were previously inserted (the implicit + // delete from the move will remove the insert) + if (!insertions.empty() && !c.moves.empty()) { + c.moves.erase(std::remove_if(begin(c.moves), end(c.moves), + [&](auto const& m) { return insertions.contains(m.from); }), + end(c.moves)); + } + + // Ensure that any previously modified rows which were moved are still modified + if (!modifications.empty() && !c.moves.empty()) { + for (auto const& move : c.moves) { + for_each_col([&](auto& col, auto& other) { + if (col.contains(move.from)) + other.add(move.to); + }); + } + } + + // Update the source position of new moves to compensate for the changes made + // in the old changeset + if (!deletions.empty() || !insertions.empty()) { + for (auto& move : c.moves) + move.from = deletions.shift(insertions.unshift(move.from)); + } + + moves.insert(end(moves), begin(c.moves), end(c.moves)); + + // New deletion indices have been shifted by the insertions, so unshift them + // before adding + deletions.add_shifted_by(insertions, c.deletions); + + // Drop any inserted-then-deleted rows, then merge in new insertions + insertions.erase_at(c.deletions); + insertions.insert_at(c.insertions); + + clean_up_stale_moves(); + + for_each_col([&](auto& col, auto& other) { + col.erase_at(c.deletions); + col.shift_for_insert_at(c.insertions); + col.add(other); + }); + + c = {}; + verify(); +} + +void CollectionChangeBuilder::clean_up_stale_moves() +{ + // Look for moves which are now no-ops, and remove them plus the associated + // insert+delete. Note that this isn't just checking for from == to due to + // that rows can also be shifted by other inserts and deletes + moves.erase(std::remove_if(begin(moves), end(moves), [&](auto const& move) { + if (move.from - deletions.count(0, move.from) != move.to - insertions.count(0, move.to)) + return false; + deletions.remove(move.from); + insertions.remove(move.to); + return true; + }), end(moves)); +} + +void CollectionChangeBuilder::parse_complete() +{ + moves.reserve(m_move_mapping.size()); + for (auto move : m_move_mapping) { + REALM_ASSERT_DEBUG(deletions.contains(move.second)); + REALM_ASSERT_DEBUG(insertions.contains(move.first)); + if (move.first == move.second) { + deletions.remove(move.second); + insertions.remove(move.first); + } + else + moves.push_back({move.second, move.first}); + } + m_move_mapping.clear(); + std::sort(begin(moves), end(moves), + [](auto const& a, auto const& b) { return a.from < b.from; }); +} + +void CollectionChangeBuilder::modify(size_t ndx, size_t col) +{ + modifications.add(ndx); + if (!m_track_columns || col == IndexSet::npos) + return; + + if (col >= columns.size()) + columns.resize(col + 1); + columns[col].add(ndx); +} + +template +void CollectionChangeBuilder::for_each_col(Func&& f) +{ + f(modifications); + if (m_track_columns) { + for (auto& col : columns) + f(col); + } +} + +void CollectionChangeBuilder::insert(size_t index, size_t count, bool track_moves) +{ + REALM_ASSERT(count != 0); + + for_each_col([=](auto& col) { col.shift_for_insert_at(index, count); }); + if (!track_moves) + return; + + insertions.insert_at(index, count); + + for (auto& move : moves) { + if (move.to >= index) + move.to += count; + } + + if (m_move_mapping.empty()) + return; + + // m_move_mapping is new_ndx -> old_ndx, so updating the keys requires + // deleting and re-inserting at the new index + std::vector> shifted; + for (auto it = m_move_mapping.begin(); it != m_move_mapping.end(); ) { + if (it->first >= index) { + shifted.emplace_back(it->first + count, it->second); + it = m_move_mapping.erase(it); + } + else { + ++it; + } + } + for (auto& pair : shifted) + m_move_mapping.insert(pair); +} + +void CollectionChangeBuilder::erase(size_t index) +{ + for_each_col([=](auto& col) { col.erase_at(index); }); + size_t unshifted = insertions.erase_or_unshift(index); + if (unshifted != IndexSet::npos) + deletions.add_shifted(unshifted); + + for (size_t i = 0; i < moves.size(); ++i) { + auto& move = moves[i]; + if (move.to == index) { + moves.erase(moves.begin() + i); + --i; + } + else if (move.to > index) + --move.to; + } +} + +void CollectionChangeBuilder::clear(size_t old_size) +{ + if (old_size != std::numeric_limits::max()) { + for (auto range : deletions) + old_size += range.second - range.first; + for (auto range : insertions) + old_size -= range.second - range.first; + } + + modifications.clear(); + insertions.clear(); + moves.clear(); + m_move_mapping.clear(); + columns.clear(); + deletions.set(old_size); +} + +void CollectionChangeBuilder::move(size_t from, size_t to) +{ + REALM_ASSERT(from != to); + + bool updated_existing_move = false; + for (auto& move : moves) { + if (move.to != from) { + // Shift other moves if this row is moving from one side of them + // to the other + if (move.to >= to && move.to < from) + ++move.to; + else if (move.to <= to && move.to > from) + --move.to; + continue; + } + REALM_ASSERT(!updated_existing_move); + + // Collapse A -> B, B -> C into a single A -> C move + move.to = to; + updated_existing_move = true; + + insertions.erase_at(from); + insertions.insert_at(to); + } + + if (!updated_existing_move) { + auto shifted_from = insertions.erase_or_unshift(from); + insertions.insert_at(to); + + // Don't report deletions/moves for newly inserted rows + if (shifted_from != IndexSet::npos) { + shifted_from = deletions.add_shifted(shifted_from); + moves.push_back({shifted_from, to}); + } + } + + for_each_col([=](auto& col) { + bool modified = col.contains(from); + col.erase_at(from); + + if (modified) + col.insert_at(to); + else + col.shift_for_insert_at(to); + }); +} + +void CollectionChangeBuilder::move_over(size_t row_ndx, size_t last_row, bool track_moves) +{ + REALM_ASSERT(row_ndx <= last_row); + REALM_ASSERT(insertions.empty() || prev(insertions.end())->second - 1 <= last_row); + REALM_ASSERT(modifications.empty() || prev(modifications.end())->second - 1 <= last_row); + + if (row_ndx == last_row) { + if (track_moves) { + auto shifted_from = insertions.erase_or_unshift(row_ndx); + if (shifted_from != IndexSet::npos) + deletions.add_shifted(shifted_from); + m_move_mapping.erase(row_ndx); + } + for_each_col([=](auto& col) { col.remove(row_ndx); }); + return; + } + + for_each_col([=](auto& col) { + bool modified = col.contains(last_row); + if (modified) { + col.remove(last_row); + col.add(row_ndx); + } + else + col.remove(row_ndx); + }); + + if (!track_moves) + return; + + bool row_is_insertion = insertions.contains(row_ndx); + bool last_is_insertion = !insertions.empty() && prev(insertions.end())->second == last_row + 1; + REALM_ASSERT_DEBUG(insertions.empty() || prev(insertions.end())->second <= last_row + 1); + + // Collapse A -> B, B -> C into a single A -> C move + bool last_was_already_moved = false; + if (last_is_insertion) { + auto it = m_move_mapping.find(last_row); + if (it != m_move_mapping.end() && it->first == last_row) { + m_move_mapping[row_ndx] = it->second; + m_move_mapping.erase(it); + last_was_already_moved = true; + } + } + + // Remove moves to the row being deleted + if (row_is_insertion && !last_was_already_moved) { + auto it = m_move_mapping.find(row_ndx); + if (it != m_move_mapping.end() && it->first == row_ndx) + m_move_mapping.erase(it); + } + + // Don't report deletions/moves if last_row is newly inserted + if (last_is_insertion) { + insertions.remove(last_row); + } + // If it was previously moved, the unshifted source row has already been marked as deleted + else if (!last_was_already_moved) { + auto shifted_last_row = insertions.unshift(last_row); + shifted_last_row = deletions.add_shifted(shifted_last_row); + m_move_mapping[row_ndx] = shifted_last_row; + } + + // Don't mark the moved-over row as deleted if it was a new insertion + if (!row_is_insertion) { + deletions.add_shifted(insertions.unshift(row_ndx)); + insertions.add(row_ndx); + } + verify(); +} + +void CollectionChangeBuilder::swap(size_t ndx_1, size_t ndx_2, bool track_moves) +{ + REALM_ASSERT(ndx_1 != ndx_2); + // The order of the two indices doesn't matter semantically, but making them + // consistent simplifies the logic + if (ndx_1 > ndx_2) + std::swap(ndx_1, ndx_2); + + for_each_col([=](auto& col) { + bool row_1_modified = col.contains(ndx_1); + bool row_2_modified = col.contains(ndx_2); + if (row_1_modified != row_2_modified) { + if (row_1_modified) { + col.remove(ndx_1); + col.add(ndx_2); + } + else { + col.remove(ndx_2); + col.add(ndx_1); + } + } + }); + + if (!track_moves) + return; + + auto update_move = [&](auto existing_it, auto ndx_1, auto ndx_2) { + // update the existing move to ndx_2 to point at ndx_1 + auto original = existing_it->second; + m_move_mapping.erase(existing_it); + m_move_mapping[ndx_1] = original; + + // add a move from 1 -> 2 unless 1 was a new insertion + if (!insertions.contains(ndx_1)) { + m_move_mapping[ndx_2] = deletions.add_shifted(insertions.unshift(ndx_1)); + insertions.add(ndx_1); + } + REALM_ASSERT_DEBUG(insertions.contains(ndx_2)); + }; + + auto move_1 = m_move_mapping.find(ndx_1); + auto move_2 = m_move_mapping.find(ndx_2); + bool have_move_1 = move_1 != end(m_move_mapping) && move_1->first == ndx_1; + bool have_move_2 = move_2 != end(m_move_mapping) && move_2->first == ndx_2; + if (have_move_1 && have_move_2) { + // both are already moves, so just swap the destinations + std::swap(move_1->second, move_2->second); + } + else if (have_move_1) { + update_move(move_1, ndx_2, ndx_1); + } + else if (have_move_2) { + update_move(move_2, ndx_1, ndx_2); + } + else { + // ndx_2 needs to be done before 1 to avoid incorrect shifting + if (!insertions.contains(ndx_2)) { + m_move_mapping[ndx_1] = deletions.add_shifted(insertions.unshift(ndx_2)); + insertions.add(ndx_2); + } + if (!insertions.contains(ndx_1)) { + m_move_mapping[ndx_2] = deletions.add_shifted(insertions.unshift(ndx_1)); + insertions.add(ndx_1); + } + } +} + +void CollectionChangeBuilder::subsume(size_t old_ndx, size_t new_ndx, bool track_moves) +{ + REALM_ASSERT(old_ndx != new_ndx); + + for_each_col([=](auto& col) { + if (col.contains(old_ndx)) { + col.add(new_ndx); + } + }); + + if (!track_moves) + return; + + REALM_ASSERT_DEBUG(insertions.contains(new_ndx)); + REALM_ASSERT_DEBUG(!m_move_mapping.count(new_ndx)); + + // If the source row was already moved, update the existing move + auto it = m_move_mapping.find(old_ndx); + if (it != m_move_mapping.end() && it->first == old_ndx) { + m_move_mapping[new_ndx] = it->second; + m_move_mapping.erase(it); + } + // otherwise add a new move unless it was a new insertion + else if (!insertions.contains(old_ndx)) { + m_move_mapping[new_ndx] = deletions.shift(insertions.unshift(old_ndx)); + } + + verify(); +} + +void CollectionChangeBuilder::verify() +{ +#ifdef REALM_DEBUG + for (auto&& move : moves) { + REALM_ASSERT(deletions.contains(move.from)); + REALM_ASSERT(insertions.contains(move.to)); + } +#endif +} + +void CollectionChangeBuilder::insert_column(size_t ndx) +{ + if (ndx < columns.size()) + columns.insert(columns.begin() + ndx, IndexSet{}); +} + +void CollectionChangeBuilder::move_column(size_t from, size_t to) +{ + if (from >= columns.size() && to >= columns.size()) + return; + if (from >= columns.size() || to >= columns.size()) + columns.resize(std::max(from, to) + 1); + if (from < to) + std::rotate(begin(columns) + from, begin(columns) + from + 1, begin(columns) + to + 1); + else + std::rotate(begin(columns) + to, begin(columns) + from, begin(columns) + from + 1); +} + +namespace { +struct RowInfo { + size_t row_index; + size_t prev_tv_index; + size_t tv_index; + size_t shifted_tv_index; +}; + +// Calculates the insertions/deletions required for a query on a table without +// a sort, where `removed` includes the rows which were modified to no longer +// match the query (but not outright deleted rows, which are filtered out long +// before any of this logic), and `move_candidates` tracks the rows which may +// be the result of a move. +// +// This function is not strictly required, as calculate_moves_sorted() will +// produce correct results even for the scenarios where this function is used. +// However, this function has asymptotically better worst-case performance and +// extremely cheap best-case performance, and is guaranteed to produce a minimal +// diff when the only row moves are due to move_last_over(). +void calculate_moves_unsorted(std::vector& new_rows, IndexSet& removed, + IndexSet const& move_candidates, + CollectionChangeSet& changeset) +{ + // Here we track which row we expect to see, which in the absence of swap() + // is always the row immediately after the last row which was not moved. + size_t expected = 0; + for (auto& row : new_rows) { + if (row.shifted_tv_index == expected) { + ++expected; + continue; + } + + // We didn't find the row we were expecting to find, which means that + // either a row was moved forward to here, the row we were expecting was + // removed, or the row we were expecting moved back. + + // First check if this row even could have moved. If it can't, just + // treat it as a match and move on, and we'll handle the row we were + // expecting when we hit it later. + if (!move_candidates.contains(row.row_index)) { + expected = row.shifted_tv_index + 1; + continue; + } + + // Next calculate where we expect this row to be based on the insertions + // and removals (i.e. rows changed to not match the query), as it could + // be that the row actually ends up in this spot due to the rows before + // it being removed. + size_t calc_expected = row.tv_index - changeset.insertions.count(0, row.tv_index) + removed.count(0, row.prev_tv_index); + if (row.shifted_tv_index == calc_expected) { + expected = calc_expected + 1; + continue; + } + + // The row still isn't the expected one, so record it as a move + changeset.moves.push_back({row.prev_tv_index, row.tv_index}); + changeset.insertions.add(row.tv_index); + removed.add(row.prev_tv_index); + } +} + +class LongestCommonSubsequenceCalculator { +public: + // A pair of an index in the table and an index in the table view + struct Row { + size_t row_index; + size_t tv_index; + }; + + struct Match { + // The index in `a` at which this match begins + size_t i; + // The index in `b` at which this match begins + size_t j; + // The length of this match + size_t size; + // The number of rows in this block which were modified + size_t modified; + }; + std::vector m_longest_matches; + + LongestCommonSubsequenceCalculator(std::vector& a, std::vector& b, + size_t start_index, + IndexSet const& modifications) + : m_modified(modifications) + , a(a), b(b) + { + find_longest_matches(start_index, a.size(), + start_index, b.size()); + m_longest_matches.push_back({a.size(), b.size(), 0}); + } + +private: + IndexSet const& m_modified; + + // The two arrays of rows being diffed + // a is sorted by tv_index, b is sorted by row_index + std::vector &a, &b; + + // Find the longest matching range in (a + begin1, a + end1) and (b + begin2, b + end2) + // "Matching" is defined as "has the same row index"; the TV index is just + // there to let us turn an index in a/b into an index which can be reported + // in the output changeset. + // + // This is done with the O(N) space variant of the dynamic programming + // algorithm for longest common subsequence, where N is the maximum number + // of the most common row index (which for everything but linkview-derived + // TVs will be 1). + Match find_longest_match(size_t begin1, size_t end1, size_t begin2, size_t end2) + { + struct Length { + size_t j, len; + }; + // The length of the matching block for each `j` for the previously checked row + std::vector prev; + // The length of the matching block for each `j` for the row currently being checked + std::vector cur; + + // Calculate the length of the matching block *ending* at b[j], which + // is 1 if b[j - 1] did not match, and b[j - 1] + 1 otherwise. + auto length = [&](size_t j) -> size_t { + for (auto const& pair : prev) { + if (pair.j + 1 == j) + return pair.len + 1; + } + return 1; + }; + + // Iterate over each `j` which has the same row index as a[i] and falls + // within the range begin2 <= j < end2 + auto for_each_b_match = [&](size_t i, auto&& f) { + size_t ai = a[i].row_index; + // Find the TV indicies at which this row appears in the new results + // There should always be at least one (or it would have been + // filtered out earlier), but there can be multiple if there are dupes + auto it = lower_bound(begin(b), end(b), ai, + [](auto lft, auto rgt) { return lft.row_index < rgt; }); + REALM_ASSERT(it != end(b) && it->row_index == ai); + for (; it != end(b) && it->row_index == ai; ++it) { + size_t j = it->tv_index; + if (j < begin2) + continue; + if (j >= end2) + break; // b is sorted by tv_index so this can't transition from false to true + f(j); + } + }; + + Match best = {begin1, begin2, 0, 0}; + for (size_t i = begin1; i < end1; ++i) { + // prev = std::move(cur), but avoids discarding prev's heap allocation + cur.swap(prev); + cur.clear(); + + for_each_b_match(i, [&](size_t j) { + size_t size = length(j); + + cur.push_back({j, size}); + + // If the matching block ending at a[i] and b[j] is longer than + // the previous one, select it as the best + if (size > best.size) + best = {i - size + 1, j - size + 1, size, IndexSet::npos}; + // Given two equal-length matches, prefer the one with fewer modified rows + else if (size == best.size) { + if (best.modified == IndexSet::npos) + best.modified = m_modified.count(best.j - size + 1, best.j + 1); + auto count = m_modified.count(j - size + 1, j + 1); + if (count < best.modified) + best = {i - size + 1, j - size + 1, size, count}; + } + + // The best block should always fall within the range being searched + REALM_ASSERT(best.i >= begin1 && best.i + best.size <= end1); + REALM_ASSERT(best.j >= begin2 && best.j + best.size <= end2); + }); + } + return best; + } + + void find_longest_matches(size_t begin1, size_t end1, size_t begin2, size_t end2) + { + // FIXME: recursion could get too deep here + // recursion depth worst case is currently O(N) and each recursion uses 320 bytes of stack + // could reduce worst case to O(sqrt(N)) (and typical case to O(log N)) + // biasing equal selections towards the middle, but that's still + // insufficient for Android's 8 KB stacks + auto m = find_longest_match(begin1, end1, begin2, end2); + if (!m.size) + return; + if (m.i > begin1 && m.j > begin2) + find_longest_matches(begin1, m.i, begin2, m.j); + m_longest_matches.push_back(m); + if (m.i + m.size < end2 && m.j + m.size < end2) + find_longest_matches(m.i + m.size, end1, m.j + m.size, end2); + } +}; + +void calculate_moves_sorted(std::vector& rows, CollectionChangeSet& changeset) +{ + // The RowInfo array contains information about the old and new TV indices of + // each row, which we need to turn into two sequences of rows, which we'll + // then find matches in + std::vector a, b; + + a.reserve(rows.size()); + for (auto& row : rows) { + a.push_back({row.row_index, row.prev_tv_index}); + } + std::sort(begin(a), end(a), [](auto lft, auto rgt) { + return std::tie(lft.tv_index, lft.row_index) < std::tie(rgt.tv_index, rgt.row_index); + }); + + // Before constructing `b`, first find the first index in `a` which will + // actually differ in `b`, and skip everything else if there aren't any + size_t first_difference = IndexSet::npos; + for (size_t i = 0; i < a.size(); ++i) { + if (a[i].row_index != rows[i].row_index) { + first_difference = i; + break; + } + } + if (first_difference == IndexSet::npos) + return; + + // Note that `b` is sorted by row_index, while `a` is sorted by tv_index + b.reserve(rows.size()); + for (size_t i = 0; i < rows.size(); ++i) + b.push_back({rows[i].row_index, i}); + std::sort(begin(b), end(b), [](auto lft, auto rgt) { + return std::tie(lft.row_index, lft.tv_index) < std::tie(rgt.row_index, rgt.tv_index); + }); + + // Calculate the LCS of the two sequences + auto matches = LongestCommonSubsequenceCalculator(a, b, first_difference, + changeset.modifications).m_longest_matches; + + // And then insert and delete rows as needed to align them + size_t i = first_difference, j = first_difference; + for (auto match : matches) { + for (; i < match.i; ++i) + changeset.deletions.add(a[i].tv_index); + for (; j < match.j; ++j) + changeset.insertions.add(rows[j].tv_index); + i += match.size; + j += match.size; + } +} + +} // Anonymous namespace + +CollectionChangeBuilder CollectionChangeBuilder::calculate(std::vector const& prev_rows, + std::vector const& next_rows, + std::function row_did_change, + util::Optional const& move_candidates) +{ + REALM_ASSERT_DEBUG(!move_candidates || std::is_sorted(begin(next_rows), end(next_rows))); + + CollectionChangeBuilder ret; + + size_t deleted = 0; + std::vector old_rows; + old_rows.reserve(prev_rows.size()); + for (size_t i = 0; i < prev_rows.size(); ++i) { + if (prev_rows[i] == IndexSet::npos) { + ++deleted; + ret.deletions.add(i); + } + else + old_rows.push_back({prev_rows[i], IndexSet::npos, i, i - deleted}); + } + std::sort(begin(old_rows), end(old_rows), [](auto& lft, auto& rgt) { + return lft.row_index < rgt.row_index; + }); + + std::vector new_rows; + new_rows.reserve(next_rows.size()); + for (size_t i = 0; i < next_rows.size(); ++i) { + new_rows.push_back({next_rows[i], IndexSet::npos, i, 0}); + } + std::sort(begin(new_rows), end(new_rows), [](auto& lft, auto& rgt) { + return lft.row_index < rgt.row_index; + }); + + // Don't add rows which were modified to not match the query to `deletions` + // immediately because the unsorted move logic needs to be able to + // distinguish them from rows which were outright deleted + IndexSet removed; + + // Now that our old and new sets of rows are sorted by row index, we can + // iterate over them and either record old+new TV indices for rows present + // in both, or mark them as inserted/deleted if they appear only in one + size_t i = 0, j = 0; + while (i < old_rows.size() && j < new_rows.size()) { + auto old_index = old_rows[i]; + auto new_index = new_rows[j]; + if (old_index.row_index == new_index.row_index) { + new_rows[j].prev_tv_index = old_rows[i].tv_index; + new_rows[j].shifted_tv_index = old_rows[i].shifted_tv_index; + ++i; + ++j; + } + else if (old_index.row_index < new_index.row_index) { + removed.add(old_index.tv_index); + ++i; + } + else { + ret.insertions.add(new_index.tv_index); + ++j; + } + } + + for (; i < old_rows.size(); ++i) + removed.add(old_rows[i].tv_index); + for (; j < new_rows.size(); ++j) + ret.insertions.add(new_rows[j].tv_index); + + // Filter out the new insertions since we don't need them for any of the + // further calculations + new_rows.erase(std::remove_if(begin(new_rows), end(new_rows), + [](auto& row) { return row.prev_tv_index == IndexSet::npos; }), + end(new_rows)); + std::sort(begin(new_rows), end(new_rows), + [](auto& lft, auto& rgt) { return lft.tv_index < rgt.tv_index; }); + + for (auto& row : new_rows) { + if (row_did_change(row.row_index)) { + ret.modifications.add(row.tv_index); + } + } + + if (move_candidates) { + calculate_moves_unsorted(new_rows, removed, *move_candidates, ret); + } + else { + calculate_moves_sorted(new_rows, ret); + } + ret.deletions.add(removed); + ret.verify(); + +#ifdef REALM_DEBUG + { // Verify that applying the calculated change to prev_rows actually produces next_rows + auto rows = prev_rows; + auto it = util::make_reverse_iterator(ret.deletions.end()); + auto end = util::make_reverse_iterator(ret.deletions.begin()); + for (; it != end; ++it) { + rows.erase(rows.begin() + it->first, rows.begin() + it->second); + } + + for (auto i : ret.insertions.as_indexes()) { + rows.insert(rows.begin() + i, next_rows[i]); + } + + REALM_ASSERT(rows == next_rows); + } +#endif + + return ret; +} + +CollectionChangeSet CollectionChangeBuilder::finalize() && +{ + // Calculate which indices in the old collection were modified + auto modifications_in_old = modifications; + modifications_in_old.erase_at(insertions); + modifications_in_old.shift_for_insert_at(deletions); + + // During changeset calculation we allow marking a row as both inserted and + // modified in case changeset merging results in it no longer being an insert, + // but we don't want inserts in the final modification set + modifications.remove(insertions); + + return { + std::move(deletions), + std::move(insertions), + std::move(modifications_in_old), + std::move(modifications), + std::move(moves), + std::move(columns) + }; +} diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp new file mode 100644 index 0000000000..8fa94d37a9 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp @@ -0,0 +1,497 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/collection_notifier.hpp" + +#include "impl/realm_coordinator.hpp" +#include "shared_realm.hpp" + +#include +#include + +using namespace realm; +using namespace realm::_impl; + +std::function +CollectionNotifier::get_modification_checker(TransactionChangeInfo const& info, + Table const& root_table) +{ + if (info.schema_changed) + set_table(root_table); + + // First check if any of the tables accessible from the root table were + // actually modified. This can be false if there were only insertions, or + // deletions which were not linked to by any row in the linking table + auto table_modified = [&](auto& tbl) { + return tbl.table_ndx < info.tables.size() + && !info.tables[tbl.table_ndx].modifications.empty(); + }; + if (!any_of(begin(m_related_tables), end(m_related_tables), table_modified)) { + return [](size_t) { return false; }; + } + if (m_related_tables.size() == 1) { + auto& modifications = info.tables[m_related_tables[0].table_ndx].modifications; + return [&](size_t row) { return modifications.contains(row); }; + } + + return DeepChangeChecker(info, root_table, m_related_tables); +} + +void DeepChangeChecker::find_related_tables(std::vector& out, Table const& table) +{ + auto table_ndx = table.get_index_in_group(); + if (table_ndx == npos) + return; + if (any_of(begin(out), end(out), [=](auto& tbl) { return tbl.table_ndx == table_ndx; })) + return; + + // We need to add this table to `out` before recurring so that the check + // above works, but we can't store a pointer to the thing being populated + // because the recursive calls may resize `out`, so instead look it up by + // index every time + size_t out_index = out.size(); + out.push_back({table_ndx, {}}); + + for (size_t i = 0, count = table.get_column_count(); i != count; ++i) { + auto type = table.get_column_type(i); + if (type == type_Link || type == type_LinkList) { + out[out_index].links.push_back({i, type == type_LinkList}); + find_related_tables(out, *table.get_link_target(i)); + } + } +} + +DeepChangeChecker::DeepChangeChecker(TransactionChangeInfo const& info, + Table const& root_table, + std::vector const& related_tables) +: m_info(info) +, m_root_table(root_table) +, m_root_table_ndx(root_table.get_index_in_group()) +, m_root_modifications(m_root_table_ndx < info.tables.size() ? &info.tables[m_root_table_ndx].modifications : nullptr) +, m_related_tables(related_tables) +{ +} + +bool DeepChangeChecker::check_outgoing_links(size_t table_ndx, + Table const& table, + size_t row_ndx, size_t depth) +{ + auto it = find_if(begin(m_related_tables), end(m_related_tables), + [&](auto&& tbl) { return tbl.table_ndx == table_ndx; }); + if (it == m_related_tables.end()) + return false; + + // Check if we're already checking if the destination of the link is + // modified, and if not add it to the stack + auto already_checking = [&](size_t col) { + auto end = m_current_path.begin() + depth; + auto match = std::find_if(m_current_path.begin(), end, [&](auto& p) { + return p.table == table_ndx && p.row == row_ndx && p.col == col; + }); + if (match != end) { + for (; match < end; ++match) match->depth_exceeded = true; + return true; + } + m_current_path[depth] = {table_ndx, row_ndx, col, false}; + return false; + }; + + auto linked_object_changed = [&](OutgoingLink const& link) { + if (already_checking(link.col_ndx)) + return false; + if (!link.is_list) { + if (table.is_null_link(link.col_ndx, row_ndx)) + return false; + auto dst = table.get_link(link.col_ndx, row_ndx); + return check_row(*table.get_link_target(link.col_ndx), dst, depth + 1); + } + + auto& target = *table.get_link_target(link.col_ndx); + auto lvr = table.get_linklist(link.col_ndx, row_ndx); + for (size_t j = 0, size = lvr->size(); j < size; ++j) { + size_t dst = lvr->get(j).get_index(); + if (check_row(target, dst, depth + 1)) + return true; + } + return false; + }; + + return std::any_of(begin(it->links), end(it->links), linked_object_changed); +} + +bool DeepChangeChecker::check_row(Table const& table, size_t idx, size_t depth) +{ + // Arbitrary upper limit on the maximum depth to search + if (depth >= m_current_path.size()) { + // Don't mark any of the intermediate rows checked along the path as + // not modified, as a search starting from them might hit a modification + for (size_t i = 0; i < m_current_path.size(); ++i) + m_current_path[i].depth_exceeded = true; + return false; + } + + size_t table_ndx = table.get_index_in_group(); + if (depth > 0 && table_ndx < m_info.tables.size() && m_info.tables[table_ndx].modifications.contains(idx)) + return true; + + if (m_not_modified.size() <= table_ndx) + m_not_modified.resize(table_ndx + 1); + if (m_not_modified[table_ndx].contains(idx)) + return false; + + bool ret = check_outgoing_links(table_ndx, table, idx, depth); + if (!ret && (depth == 0 || !m_current_path[depth - 1].depth_exceeded)) + m_not_modified[table_ndx].add(idx); + return ret; +} + +bool DeepChangeChecker::operator()(size_t ndx) +{ + if (m_root_modifications && m_root_modifications->contains(ndx)) + return true; + return check_row(m_root_table, ndx, 0); +} + +CollectionNotifier::CollectionNotifier(std::shared_ptr realm) +: m_realm(std::move(realm)) +, m_sg_version(Realm::Internal::get_shared_group(*m_realm)->get_version_of_current_transaction()) +{ +} + +CollectionNotifier::~CollectionNotifier() +{ + // Need to do this explicitly to ensure m_realm is destroyed with the mutex + // held to avoid potential double-deletion + unregister(); +} + +uint64_t CollectionNotifier::add_callback(CollectionChangeCallback callback) +{ + m_realm->verify_thread(); + + std::lock_guard lock(m_callback_mutex); + auto token = m_next_token++; + m_callbacks.push_back({std::move(callback), {}, {}, token, false, false}); + if (m_callback_index == npos) { // Don't need to wake up if we're already sending notifications + Realm::Internal::get_coordinator(*m_realm).wake_up_notifier_worker(); + m_have_callbacks = true; + } + return token; +} + +void CollectionNotifier::remove_callback(uint64_t token) +{ + // the callback needs to be destroyed after releasing the lock as destroying + // it could cause user code to be called + Callback old; + { + std::lock_guard lock(m_callback_mutex); + auto it = find_callback(token); + if (it == end(m_callbacks)) { + return; + } + + size_t idx = distance(begin(m_callbacks), it); + if (m_callback_index != npos) { + if (m_callback_index >= idx) + --m_callback_index; + } + --m_callback_count; + + old = std::move(*it); + m_callbacks.erase(it); + + m_have_callbacks = !m_callbacks.empty(); + } +} + +void CollectionNotifier::suppress_next_notification(uint64_t token) +{ + { + std::lock_guard lock(m_realm_mutex); + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + m_realm->verify_in_write(); + } + + std::lock_guard lock(m_callback_mutex); + auto it = find_callback(token); + if (it != end(m_callbacks)) { + it->skip_next = true; + } +} + +std::vector::iterator CollectionNotifier::find_callback(uint64_t token) +{ + REALM_ASSERT(m_error || m_callbacks.size() > 0); + + auto it = find_if(begin(m_callbacks), end(m_callbacks), + [=](const auto& c) { return c.token == token; }); + // We should only fail to find the callback if it was removed due to an error + REALM_ASSERT(m_error || it != end(m_callbacks)); + return it; +} + +void CollectionNotifier::unregister() noexcept +{ + std::lock_guard lock(m_realm_mutex); + m_realm = nullptr; +} + +bool CollectionNotifier::is_alive() const noexcept +{ + std::lock_guard lock(m_realm_mutex); + return m_realm != nullptr; +} + +std::unique_lock CollectionNotifier::lock_target() +{ + return std::unique_lock{m_realm_mutex}; +} + +void CollectionNotifier::set_table(Table const& table) +{ + m_related_tables.clear(); + DeepChangeChecker::find_related_tables(m_related_tables, table); +} + +void CollectionNotifier::add_required_change_info(TransactionChangeInfo& info) +{ + if (!do_add_required_change_info(info) || m_related_tables.empty()) { + return; + } + + auto max = max_element(begin(m_related_tables), end(m_related_tables), + [](auto&& a, auto&& b) { return a.table_ndx < b.table_ndx; }); + + if (max->table_ndx >= info.table_modifications_needed.size()) + info.table_modifications_needed.resize(max->table_ndx + 1, false); + for (auto& tbl : m_related_tables) { + info.table_modifications_needed[tbl.table_ndx] = true; + } +} + +void CollectionNotifier::prepare_handover() +{ + REALM_ASSERT(m_sg); + m_sg_version = m_sg->get_version_of_current_transaction(); + do_prepare_handover(*m_sg); + m_has_run = true; + +#ifdef REALM_DEBUG + std::lock_guard lock(m_callback_mutex); + for (auto& callback : m_callbacks) + REALM_ASSERT(!callback.skip_next); +#endif +} + +void CollectionNotifier::before_advance() +{ + for_each_callback([&](auto& lock, auto& callback) { + if (callback.changes_to_deliver.empty()) { + return; + } + + auto changes = callback.changes_to_deliver; + // acquire a local reference to the callback so that removing the + // callback from within it can't result in a dangling pointer + auto cb = callback.fn; + lock.unlock(); + cb.before(changes); + }); +} + +void CollectionNotifier::after_advance() +{ + for_each_callback([&](auto& lock, auto& callback) { + if (callback.initial_delivered && callback.changes_to_deliver.empty()) { + return; + } + callback.initial_delivered = true; + + auto changes = std::move(callback.changes_to_deliver); + // acquire a local reference to the callback so that removing the + // callback from within it can't result in a dangling pointer + auto cb = callback.fn; + lock.unlock(); + cb.after(changes); + }); +} + +void CollectionNotifier::deliver_error(std::exception_ptr error) +{ + // Don't complain about double-unregistering callbacks + m_error = true; + + m_callback_count = m_callbacks.size(); + for_each_callback([this, &error](auto& lock, auto& callback) { + // acquire a local reference to the callback so that removing the + // callback from within it can't result in a dangling pointer + auto cb = std::move(callback.fn); + auto token = callback.token; + lock.unlock(); + cb.error(error); + + // We never want to call the callback again after this, so just remove it + this->remove_callback(token); + }); +} + +bool CollectionNotifier::is_for_realm(Realm& realm) const noexcept +{ + std::lock_guard lock(m_realm_mutex); + return m_realm.get() == &realm; +} + +bool CollectionNotifier::package_for_delivery() +{ + if (!prepare_to_deliver()) + return false; + std::lock_guard l(m_callback_mutex); + for (auto& callback : m_callbacks) + callback.changes_to_deliver = std::move(callback.accumulated_changes).finalize(); + m_callback_count = m_callbacks.size(); + return true; +} + +template +void CollectionNotifier::for_each_callback(Fn&& fn) +{ + std::unique_lock callback_lock(m_callback_mutex); + REALM_ASSERT_DEBUG(m_callback_count <= m_callbacks.size()); + for (++m_callback_index; m_callback_index < m_callback_count; ++m_callback_index) { + fn(callback_lock, m_callbacks[m_callback_index]); + if (!callback_lock.owns_lock()) + callback_lock.lock(); + } + + m_callback_index = npos; +} + +void CollectionNotifier::attach_to(SharedGroup& sg) +{ + REALM_ASSERT(!m_sg); + + m_sg = &sg; + do_attach_to(sg); +} + +void CollectionNotifier::detach() +{ + REALM_ASSERT(m_sg); + do_detach_from(*m_sg); + m_sg = nullptr; +} + +SharedGroup& CollectionNotifier::source_shared_group() +{ + return *Realm::Internal::get_shared_group(*m_realm); +} + +void CollectionNotifier::add_changes(CollectionChangeBuilder change) +{ + std::lock_guard lock(m_callback_mutex); + for (auto& callback : m_callbacks) { + if (callback.skip_next) { + REALM_ASSERT_DEBUG(callback.accumulated_changes.empty()); + callback.skip_next = false; + } + else { + if (&callback == &m_callbacks.back()) + callback.accumulated_changes.merge(std::move(change)); + else + callback.accumulated_changes.merge(CollectionChangeBuilder(change)); + } + } +} + +NotifierPackage::NotifierPackage(std::exception_ptr error, + std::vector> notifiers, + RealmCoordinator* coordinator) +: m_notifiers(std::move(notifiers)) +, m_coordinator(coordinator) +, m_error(std::move(error)) +{ +} + +void NotifierPackage::package_and_wait(util::Optional target_version) +{ + if (!m_coordinator || m_error || !*this) + return; + + auto lock = m_coordinator->wait_for_notifiers([&] { + if (!target_version) + return true; + return std::all_of(begin(m_notifiers), end(m_notifiers), [&](auto const& n) { + return !n->have_callbacks() || (n->has_run() && n->version().version >= *target_version); + }); + }); + + // Package the notifiers for delivery and remove any which don't have anything to deliver + auto package = [&](auto& notifier) { + if (notifier->has_run() && notifier->package_for_delivery()) { + m_version = notifier->version(); + return false; + } + return true; + }; + m_notifiers.erase(std::remove_if(begin(m_notifiers), end(m_notifiers), package), end(m_notifiers)); + if (m_version && target_version && m_version->version < *target_version) { + m_notifiers.clear(); + m_version = util::none; + } + REALM_ASSERT(m_version || m_notifiers.empty()); + + m_coordinator = nullptr; +} + +void NotifierPackage::before_advance() +{ + if (m_error) + return; + for (auto& notifier : m_notifiers) + notifier->before_advance(); +} + +void NotifierPackage::deliver(SharedGroup& sg) +{ + if (m_error) { + for (auto& notifier : m_notifiers) + notifier->deliver_error(m_error); + return; + } + // Can't deliver while in a write transaction + if (sg.get_transact_stage() != SharedGroup::transact_Reading) + return; + for (auto& notifier : m_notifiers) + notifier->deliver(sg); +} + +void NotifierPackage::after_advance() +{ + if (m_error) + return; + for (auto& notifier : m_notifiers) + notifier->after_advance(); +} + +void NotifierPackage::add_notifier(std::shared_ptr notifier) +{ + m_notifiers.push_back(notifier); + m_coordinator->register_notifier(notifier); +} diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp new file mode 100644 index 0000000000..a2b459cf8f --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp @@ -0,0 +1,109 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/list_notifier.hpp" + +#include "shared_realm.hpp" + +#include + +using namespace realm; +using namespace realm::_impl; + +ListNotifier::ListNotifier(LinkViewRef lv, std::shared_ptr realm) +: CollectionNotifier(std::move(realm)) +, m_prev_size(lv->size()) +{ + set_table(lv->get_target_table()); + m_lv_handover = source_shared_group().export_linkview_for_handover(lv); +} + +void ListNotifier::release_data() noexcept +{ + m_lv.reset(); +} + +void ListNotifier::do_attach_to(SharedGroup& sg) +{ + REALM_ASSERT(m_lv_handover); + REALM_ASSERT(!m_lv); + m_lv = sg.import_linkview_from_handover(std::move(m_lv_handover)); +} + +void ListNotifier::do_detach_from(SharedGroup& sg) +{ + REALM_ASSERT(!m_lv_handover); + if (m_lv) { + m_lv_handover = sg.export_linkview_for_handover(m_lv); + m_lv = {}; + } +} + +bool ListNotifier::do_add_required_change_info(TransactionChangeInfo& info) +{ + REALM_ASSERT(!m_lv_handover); + if (!m_lv || !m_lv->is_attached()) { + return false; // origin row was deleted after the notification was added + } + + auto& table = m_lv->get_origin_table(); + size_t row_ndx = m_lv->get_origin_row_index(); + size_t col_ndx = find_container_column(table, row_ndx, m_lv, type_LinkList, &Table::get_linklist); + info.lists.push_back({table.get_index_in_group(), row_ndx, col_ndx, &m_change}); + + m_info = &info; + return true; +} + +void ListNotifier::run() +{ + if (!m_lv || !m_lv->is_attached()) { + // LV was deleted, so report all of the rows being removed if this is + // the first run after that + if (m_prev_size) { + m_change.deletions.set(m_prev_size); + m_prev_size = 0; + } + else { + m_change = {}; + } + return; + } + + auto row_did_change = get_modification_checker(*m_info, m_lv->get_target_table()); + for (size_t i = 0; i < m_lv->size(); ++i) { + if (m_change.modifications.contains(i)) + continue; + if (row_did_change(m_lv->get(i).get_index())) + m_change.modifications.add(i); + } + + for (auto const& move : m_change.moves) { + if (m_change.modifications.contains(move.to)) + continue; + if (row_did_change(m_lv->get(move.to).get_index())) + m_change.modifications.add(move.to); + } + + m_prev_size = m_lv->size(); +} + +void ListNotifier::do_prepare_handover(SharedGroup&) +{ + add_changes(std::move(m_change)); +} diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp new file mode 100644 index 0000000000..cb310654a4 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp @@ -0,0 +1,97 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/object_notifier.hpp" + +#include "shared_realm.hpp" + +using namespace realm; +using namespace realm::_impl; + +ObjectNotifier::ObjectNotifier(Row const& row, std::shared_ptr realm) +: CollectionNotifier(std::move(realm)) +{ + REALM_ASSERT(row.get_table()); + set_table(*row.get_table()); + + m_handover = source_shared_group().export_for_handover(row); +} + +void ObjectNotifier::release_data() noexcept +{ + m_row = nullptr; +} + +void ObjectNotifier::do_attach_to(SharedGroup& sg) +{ + REALM_ASSERT(m_handover); + REALM_ASSERT(!m_row); + m_row = sg.import_from_handover(std::move(m_handover)); +} + +void ObjectNotifier::do_detach_from(SharedGroup& sg) +{ + REALM_ASSERT(!m_handover); + if (m_row) { + m_handover = sg.export_for_handover(*m_row); + m_row = nullptr; + } +} + +bool ObjectNotifier::do_add_required_change_info(TransactionChangeInfo& info) +{ + REALM_ASSERT(!m_handover); + m_info = &info; + if (m_row && m_row->is_attached()) { + size_t table_ndx = m_row->get_table()->get_index_in_group(); + if (table_ndx >= info.table_modifications_needed.size()) + info.table_modifications_needed.resize(table_ndx + 1); + info.table_modifications_needed[table_ndx] = true; + } + return false; +} + +void ObjectNotifier::run() +{ + if (!m_row) + return; + if (!m_row->is_attached()) { + m_change.deletions.add(0); + m_row = nullptr; + return; + } + + size_t table_ndx = m_row->get_table()->get_index_in_group(); + if (table_ndx >= m_info->tables.size()) + return; + auto& change = m_info->tables[table_ndx]; + if (!change.modifications.contains(m_row->get_index())) + return; + m_change.modifications.add(0); + m_change.columns.reserve(change.columns.size()); + for (auto& col : change.columns) { + m_change.columns.emplace_back(); + if (col.contains(m_row->get_index())) + m_change.columns.back().add(0); + } +} + +void ObjectNotifier::do_prepare_handover(SharedGroup&) +{ + add_changes(std::move(m_change)); +} diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp new file mode 100644 index 0000000000..9be9acb11c --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp @@ -0,0 +1,99 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/primitive_list_notifier.hpp" + +#include "shared_realm.hpp" + +#include + +using namespace realm; +using namespace realm::_impl; + +PrimitiveListNotifier::PrimitiveListNotifier(TableRef table, std::shared_ptr realm) +: CollectionNotifier(std::move(realm)) +, m_prev_size(table->size()) +{ + set_table(*table->get_parent_table()); + m_table_handover = source_shared_group().export_table_for_handover(table); +} + +void PrimitiveListNotifier::release_data() noexcept +{ + m_table.reset(); +} + +void PrimitiveListNotifier::do_attach_to(SharedGroup& sg) +{ + REALM_ASSERT(m_table_handover); + REALM_ASSERT(!m_table); + m_table = sg.import_table_from_handover(std::move(m_table_handover)); +} + +void PrimitiveListNotifier::do_detach_from(SharedGroup& sg) +{ + REALM_ASSERT(!m_table_handover); + if (m_table) { + m_table_handover = sg.export_table_for_handover(m_table); + m_table = {}; + } +} + +bool PrimitiveListNotifier::do_add_required_change_info(TransactionChangeInfo& info) +{ + REALM_ASSERT(!m_table_handover); + if (!m_table || !m_table->is_attached()) { + return false; // origin row was deleted after the notification was added + } + + auto& table = *m_table->get_parent_table(); + size_t row_ndx = m_table->get_parent_row_index(); + size_t col_ndx = find_container_column(table, row_ndx, m_table, type_Table, &Table::get_subtable); + info.lists.push_back({table.get_index_in_group(), row_ndx, col_ndx, &m_change}); + + m_info = &info; + return true; +} + +void PrimitiveListNotifier::run() +{ + if (!m_table || !m_table->is_attached()) { + // Table was deleted entirely, so report all of the rows being removed + // if this is the first run after that + if (m_prev_size) { + m_change.deletions.set(m_prev_size); + m_prev_size = 0; + } + else { + m_change = {}; + } + return; + } + + if (!m_change.deletions.empty() && m_change.deletions.begin()->second == std::numeric_limits::max()) { + // Table was cleared, so set the deletions to the actual previous size + m_change.deletions.set(m_prev_size); + } + + m_prev_size = m_table->size(); +} + +void PrimitiveListNotifier::do_prepare_handover(SharedGroup&) +{ + add_changes(std::move(m_change)); +} diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp new file mode 100644 index 0000000000..343193a479 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp @@ -0,0 +1,919 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/realm_coordinator.hpp" + +#include "impl/collection_notifier.hpp" +#include "impl/external_commit_helper.hpp" +#include "impl/transact_log_handler.hpp" +#include "impl/weak_realm_notifier.hpp" +#include "binding_context.hpp" +#include "object_schema.hpp" +#include "object_store.hpp" +#include "schema.hpp" + +#if REALM_ENABLE_SYNC +#include "sync/impl/work_queue.hpp" +#include "sync/sync_config.hpp" +#include "sync/sync_manager.hpp" +#include "sync/sync_session.hpp" +#endif + +#include +#include +#include + +#include +#include + +using namespace realm; +using namespace realm::_impl; + +static auto& s_coordinator_mutex = *new std::mutex; +static auto& s_coordinators_per_path = *new std::unordered_map>; + +std::shared_ptr RealmCoordinator::get_coordinator(StringData path) +{ + std::lock_guard lock(s_coordinator_mutex); + + auto& weak_coordinator = s_coordinators_per_path[path]; + if (auto coordinator = weak_coordinator.lock()) { + return coordinator; + } + + auto coordinator = std::make_shared(); + weak_coordinator = coordinator; + return coordinator; +} + +std::shared_ptr RealmCoordinator::get_coordinator(const Realm::Config& config) +{ + auto coordinator = get_coordinator(config.path); + std::lock_guard lock(coordinator->m_realm_mutex); + coordinator->set_config(config); + return coordinator; +} + +std::shared_ptr RealmCoordinator::get_existing_coordinator(StringData path) +{ + std::lock_guard lock(s_coordinator_mutex); + auto it = s_coordinators_per_path.find(path); + return it == s_coordinators_per_path.end() ? nullptr : it->second.lock(); +} + +void RealmCoordinator::create_sync_session() +{ +#if REALM_ENABLE_SYNC + if (m_sync_session) + return; + + if (!m_config.encryption_key.empty() && !m_config.sync_config->realm_encryption_key) { + throw std::logic_error("A realm encryption key was specified in Realm::Config but not in SyncConfig"); + } else if (m_config.sync_config->realm_encryption_key && m_config.encryption_key.empty()) { + throw std::logic_error("A realm encryption key was specified in SyncConfig but not in Realm::Config"); + } else if (m_config.sync_config->realm_encryption_key && + !std::equal(m_config.sync_config->realm_encryption_key->begin(), m_config.sync_config->realm_encryption_key->end(), + m_config.encryption_key.begin(), m_config.encryption_key.end())) { + throw std::logic_error("The realm encryption key specified in SyncConfig does not match the one in Realm::Config"); + } + + auto sync_config = *m_config.sync_config; + sync_config.validate_sync_history = false; + m_sync_session = SyncManager::shared().get_session(m_config.path, sync_config); + + std::weak_ptr weak_self = shared_from_this(); + SyncSession::Internal::set_sync_transact_callback(*m_sync_session, + [weak_self](VersionID old_version, VersionID new_version) { + if (auto self = weak_self.lock()) { + if (self->m_transaction_callback) + self->m_transaction_callback(old_version, new_version); + if (self->m_notifier) + self->m_notifier->notify_others(); + } + }); +#endif +} + +void RealmCoordinator::set_config(const Realm::Config& config) +{ + if (config.encryption_key.data() && config.encryption_key.size() != 64) + throw InvalidEncryptionKeyException(); + if (config.schema_mode == SchemaMode::Immutable && config.sync_config) + throw std::logic_error("Synchronized Realms cannot be opened in immutable mode"); + if (config.schema_mode == SchemaMode::Additive && config.migration_function) + throw std::logic_error("Realms opened in Additive-only schema mode do not use a migration function"); + if (config.schema_mode == SchemaMode::Immutable && config.migration_function) + throw std::logic_error("Realms opened in immutable mode do not use a migration function"); + if (config.schema_mode == SchemaMode::ReadOnlyAlternative && config.migration_function) + throw std::logic_error("Realms opened in read-only mode do not use a migration function"); + if (config.schema_mode == SchemaMode::Immutable && config.initialization_function) + throw std::logic_error("Realms opened in immutable mode do not use an initialization function"); + if (config.schema_mode == SchemaMode::ReadOnlyAlternative && config.initialization_function) + throw std::logic_error("Realms opened in read-only mode do not use an initialization function"); + if (config.schema && config.schema_version == ObjectStore::NotVersioned) + throw std::logic_error("A schema version must be specified when the schema is specified"); + if (!config.realm_data.is_null() && (!config.immutable() || !config.in_memory)) + throw std::logic_error("In-memory realms initialized from memory buffers can only be opened in read-only mode"); + if (!config.realm_data.is_null() && !config.path.empty()) + throw std::logic_error("Specifying both memory buffer and path is invalid"); + if (!config.realm_data.is_null() && !config.encryption_key.empty()) + throw std::logic_error("Memory buffers do not support encryption"); + // ResetFile also won't use the migration function, but specifying one is + // allowed to simplify temporarily switching modes during development + + bool no_existing_realm = std::all_of(begin(m_weak_realm_notifiers), end(m_weak_realm_notifiers), + [](auto& notifier) { return notifier.expired(); }); + if (no_existing_realm) { + m_config = config; + } + else { + if (m_config.immutable() != config.immutable()) { + throw MismatchedConfigException("Realm at path '%1' already opened with different read permissions.", config.path); + } + if (m_config.in_memory != config.in_memory) { + throw MismatchedConfigException("Realm at path '%1' already opened with different inMemory settings.", config.path); + } + if (m_config.encryption_key != config.encryption_key) { + throw MismatchedConfigException("Realm at path '%1' already opened with a different encryption key.", config.path); + } + if (m_config.schema_mode != config.schema_mode) { + throw MismatchedConfigException("Realm at path '%1' already opened with a different schema mode.", config.path); + } + if (config.schema && m_schema_version != ObjectStore::NotVersioned && m_schema_version != config.schema_version) { + throw MismatchedConfigException("Realm at path '%1' already opened with different schema version.", config.path); + } + +#if REALM_ENABLE_SYNC + if (bool(m_config.sync_config) != bool(config.sync_config)) { + throw MismatchedConfigException("Realm at path '%1' already opened with different sync configurations.", config.path); + } + + if (config.sync_config) { + if (m_config.sync_config->user != config.sync_config->user) { + throw MismatchedConfigException("Realm at path '%1' already opened with different sync user.", config.path); + } + if (m_config.sync_config->realm_url() != config.sync_config->realm_url()) { + throw MismatchedConfigException("Realm at path '%1' already opened with different sync server URL.", config.path); + } + if (m_config.sync_config->transformer != config.sync_config->transformer) { + throw MismatchedConfigException("Realm at path '%1' already opened with different transformer.", config.path); + } + if (m_config.sync_config->realm_encryption_key != config.sync_config->realm_encryption_key) { + throw MismatchedConfigException("Realm at path '%1' already opened with sync session encryption key.", config.path); + } + } +#endif + + // Realm::update_schema() handles complaining about schema mismatches + } +} + +std::shared_ptr RealmCoordinator::get_realm(Realm::Config config) +{ + // realm must be declared before lock so that the mutex is released before + // we release the strong reference to realm, as Realm's destructor may want + // to acquire the same lock + std::shared_ptr realm; + std::unique_lock lock(m_realm_mutex); + + set_config(config); + + auto schema = std::move(config.schema); + auto migration_function = std::move(config.migration_function); + auto initialization_function = std::move(config.initialization_function); + config.schema = {}; + + if (config.cache) { + AnyExecutionContextID execution_context(config.execution_context); + for (auto& cached_realm : m_weak_realm_notifiers) { + if (!cached_realm.is_cached_for_execution_context(execution_context)) + continue; + // can be null if we jumped in between ref count hitting zero and + // unregister_realm() getting the lock + if ((realm = cached_realm.realm())) { + // If the file is uninitialized and was opened without a schema, + // do the normal schema init + if (realm->schema_version() == ObjectStore::NotVersioned) + break; + + // Otherwise if we have a realm schema it needs to be an exact + // match (even having the same properties but in different + // orders isn't good enough) + if (schema && realm->schema() != *schema) + throw MismatchedConfigException("Realm at path '%1' already opened on current thread with different schema.", config.path); + + return realm; + } + } + } + + if (!realm) { + bool should_initialize_notifier = !config.immutable() && config.automatic_change_notifications; + realm = Realm::make_shared_realm(std::move(config), shared_from_this()); + if (!m_notifier && should_initialize_notifier) { + try { + m_notifier = std::make_unique(*this); + } + catch (std::system_error const& ex) { + throw RealmFileException(RealmFileException::Kind::AccessError, get_path(), ex.code().message(), ""); + } + } + m_weak_realm_notifiers.emplace_back(realm, realm->config().cache); + } + + if (realm->config().sync_config) + create_sync_session(); + + if (schema) { + lock.unlock(); + realm->update_schema(std::move(*schema), config.schema_version, std::move(migration_function), + std::move(initialization_function)); + } + + return realm; +} + +std::shared_ptr RealmCoordinator::get_realm() +{ + return get_realm(m_config); +} + +bool RealmCoordinator::get_cached_schema(Schema& schema, uint64_t& schema_version, + uint64_t& transaction) const noexcept +{ + std::lock_guard lock(m_schema_cache_mutex); + if (!m_cached_schema) + return false; + schema = *m_cached_schema; + schema_version = m_schema_version; + transaction = m_schema_transaction_version_max; + return true; +} + +void RealmCoordinator::cache_schema(Schema const& new_schema, uint64_t new_schema_version, + uint64_t transaction_version) +{ + std::lock_guard lock(m_schema_cache_mutex); + if (transaction_version < m_schema_transaction_version_max) + return; + if (new_schema.empty() || new_schema_version == ObjectStore::NotVersioned) + return; + + m_cached_schema = new_schema; + m_schema_version = new_schema_version; + m_schema_transaction_version_min = transaction_version; + m_schema_transaction_version_max = transaction_version; +} + +void RealmCoordinator::clear_schema_cache_and_set_schema_version(uint64_t new_schema_version) +{ + std::lock_guard lock(m_schema_cache_mutex); + m_cached_schema = util::none; + m_schema_version = new_schema_version; +} + +void RealmCoordinator::advance_schema_cache(uint64_t previous, uint64_t next) +{ + std::lock_guard lock(m_schema_cache_mutex); + if (!m_cached_schema) + return; + REALM_ASSERT(previous <= m_schema_transaction_version_max); + if (next < m_schema_transaction_version_min) + return; + m_schema_transaction_version_min = std::min(previous, m_schema_transaction_version_min); + m_schema_transaction_version_max = std::max(next, m_schema_transaction_version_max); +} + +RealmCoordinator::RealmCoordinator() +#if REALM_ENABLE_SYNC +: m_partial_sync_work_queue(std::make_unique()) +#endif +{ +} + +RealmCoordinator::~RealmCoordinator() +{ + std::lock_guard coordinator_lock(s_coordinator_mutex); + for (auto it = s_coordinators_per_path.begin(); it != s_coordinators_per_path.end(); ) { + if (it->second.expired()) { + it = s_coordinators_per_path.erase(it); + } + else { + ++it; + } + } +} + +void RealmCoordinator::unregister_realm(Realm* realm) +{ + std::lock_guard lock(m_realm_mutex); + auto new_end = remove_if(begin(m_weak_realm_notifiers), end(m_weak_realm_notifiers), + [=](auto& notifier) { return notifier.expired() || notifier.is_for_realm(realm); }); + m_weak_realm_notifiers.erase(new_end, end(m_weak_realm_notifiers)); +} + +void RealmCoordinator::clear_cache() +{ + std::vector realms_to_close; + { + std::lock_guard lock(s_coordinator_mutex); + + for (auto& weak_coordinator : s_coordinators_per_path) { + auto coordinator = weak_coordinator.second.lock(); + if (!coordinator) { + continue; + } + + coordinator->m_notifier = nullptr; + + // Gather a list of all of the realms which will be removed + for (auto& weak_realm_notifier : coordinator->m_weak_realm_notifiers) { + if (auto realm = weak_realm_notifier.realm()) { + realms_to_close.push_back(realm); + } + } + } + + s_coordinators_per_path.clear(); + } + + // Close all of the previously cached Realms. This can't be done while + // s_coordinator_mutex is held as it may try to re-lock it. + for (auto& weak_realm : realms_to_close) { + if (auto realm = weak_realm.lock()) { + realm->close(); + } + } +} + +void RealmCoordinator::clear_all_caches() +{ + std::vector> to_clear; + { + std::lock_guard lock(s_coordinator_mutex); + for (auto iter : s_coordinators_per_path) { + to_clear.push_back(iter.second); + } + } + for (auto weak_coordinator : to_clear) { + if (auto coordinator = weak_coordinator.lock()) { + coordinator->clear_cache(); + } + } +} + +void RealmCoordinator::assert_no_open_realms() noexcept +{ +#ifdef REALM_DEBUG + std::lock_guard lock(s_coordinator_mutex); + REALM_ASSERT(s_coordinators_per_path.empty()); +#endif +} + +void RealmCoordinator::wake_up_notifier_worker() +{ + if (m_notifier) { + // FIXME: this wakes up the notification workers for all processes and + // not just us. This might be worth optimizing in the future. + m_notifier->notify_others(); + } +} + +void RealmCoordinator::commit_write(Realm& realm) +{ + REALM_ASSERT(!m_config.immutable()); + REALM_ASSERT(realm.is_in_transaction()); + + { + // Need to acquire this lock before committing or another process could + // perform a write and notify us before we get the chance to set the + // skip version + std::lock_guard l(m_notifier_mutex); + + transaction::commit(*Realm::Internal::get_shared_group(realm)); + + // Don't need to check m_new_notifiers because those don't skip versions + bool have_notifiers = std::any_of(m_notifiers.begin(), m_notifiers.end(), + [&](auto&& notifier) { return notifier->is_for_realm(realm); }); + if (have_notifiers) { + m_notifier_skip_version = Realm::Internal::get_shared_group(realm)->get_version_of_current_transaction(); + } + } + +#if REALM_ENABLE_SYNC + // Realm could be closed in did_change. So send sync notification first before did_change. + if (m_sync_session) { + auto& sg = Realm::Internal::get_shared_group(realm); + auto version = LangBindHelper::get_version_of_latest_snapshot(*sg); + SyncSession::Internal::nonsync_transact_notify(*m_sync_session, version); + } +#endif + if (realm.m_binding_context) { + realm.m_binding_context->did_change({}, {}); + } + + if (m_notifier) { + m_notifier->notify_others(); + } +} + +void RealmCoordinator::pin_version(VersionID versionid) +{ + REALM_ASSERT_DEBUG(!m_notifier_mutex.try_lock()); + if (m_async_error) { + return; + } + + if (!m_advancer_sg) { + try { + std::unique_ptr read_only_group; + Realm::open_with_config(m_config, m_advancer_history, m_advancer_sg, read_only_group, nullptr); + REALM_ASSERT(!read_only_group); + m_advancer_sg->begin_read(versionid); + } + catch (...) { + m_async_error = std::current_exception(); + m_advancer_sg = nullptr; + m_advancer_history = nullptr; + } + } + else if (m_new_notifiers.empty()) { + // If this is the first notifier then we don't already have a read transaction + REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Ready); + m_advancer_sg->begin_read(versionid); + } + else { + REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Reading); + if (versionid < m_advancer_sg->get_version_of_current_transaction()) { + // Ensure we're holding a readlock on the oldest version we have a + // handover object for, as handover objects don't + m_advancer_sg->end_read(); + m_advancer_sg->begin_read(versionid); + } + } +} + +void RealmCoordinator::register_notifier(std::shared_ptr notifier) +{ + auto version = notifier->version(); + auto& self = Realm::Internal::get_coordinator(*notifier->get_realm()); + { + std::lock_guard lock(self.m_notifier_mutex); + self.pin_version(version); + self.m_new_notifiers.push_back(std::move(notifier)); + } +} + +void RealmCoordinator::clean_up_dead_notifiers() +{ + auto swap_remove = [&](auto& container) { + bool did_remove = false; + for (size_t i = 0; i < container.size(); ++i) { + if (container[i]->is_alive()) + continue; + + // Ensure the notifier is destroyed here even if there's lingering refs + // to the async notifier elsewhere + container[i]->release_data(); + + if (container.size() > i + 1) + container[i] = std::move(container.back()); + container.pop_back(); + --i; + did_remove = true; + } + return did_remove; + }; + + if (swap_remove(m_notifiers)) { + // Make sure we aren't holding on to read versions needlessly if there + // are no notifiers left, but don't close them entirely as opening shared + // groups is expensive + if (m_notifiers.empty() && m_notifier_sg) { + REALM_ASSERT_3(m_notifier_sg->get_transact_stage(), ==, SharedGroup::transact_Reading); + m_notifier_sg->end_read(); + m_notifier_skip_version = {0, 0}; + } + } + if (swap_remove(m_new_notifiers) && m_advancer_sg) { + REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Reading); + if (m_new_notifiers.empty()) { + m_advancer_sg->end_read(); + } + } +} + +void RealmCoordinator::on_change() +{ + run_async_notifiers(); + + std::lock_guard lock(m_realm_mutex); + for (auto& realm : m_weak_realm_notifiers) { + realm.notify(); + } +} + +namespace { +class IncrementalChangeInfo { +public: + IncrementalChangeInfo(SharedGroup& sg, + std::vector>& notifiers) + : m_sg(sg) + { + if (notifiers.empty()) + return; + + auto cmp = [&](auto&& lft, auto&& rgt) { + return lft->version() < rgt->version(); + }; + + // Sort the notifiers by their source version so that we can pull them + // all forward to the latest version in a single pass over the transaction log + std::sort(notifiers.begin(), notifiers.end(), cmp); + + // Preallocate the required amount of space in the vector so that we can + // safely give out pointers to within the vector + size_t count = 1; + for (auto it = notifiers.begin(), next = it + 1; next != notifiers.end(); ++it, ++next) { + if (cmp(*it, *next)) + ++count; + } + m_info.reserve(count); + m_info.resize(1); + m_current = &m_info[0]; + } + + TransactionChangeInfo& current() const { return *m_current; } + + bool advance_incremental(VersionID version) + { + if (version != m_sg.get_version_of_current_transaction()) { + transaction::advance(m_sg, *m_current, version); + m_info.push_back({ + m_current->table_modifications_needed, + m_current->table_moves_needed, + std::move(m_current->lists)}); + m_current = &m_info.back(); + return true; + } + return false; + } + + void advance_to_final(VersionID version) + { + if (!m_current) { + transaction::advance(m_sg, nullptr, version); + return; + } + + transaction::advance(m_sg, *m_current, version); + + // We now need to combine the transaction change info objects so that all of + // the notifiers see the complete set of changes from their first version to + // the most recent one + for (size_t i = m_info.size() - 1; i > 0; --i) { + auto& cur = m_info[i]; + if (cur.tables.empty()) + continue; + auto& prev = m_info[i - 1]; + if (prev.tables.empty()) { + prev.tables = cur.tables; + continue; + } + + for (size_t j = 0; j < prev.tables.size() && j < cur.tables.size(); ++j) { + prev.tables[j].merge(CollectionChangeBuilder{cur.tables[j]}); + } + prev.tables.reserve(cur.tables.size()); + while (prev.tables.size() < cur.tables.size()) { + prev.tables.push_back(cur.tables[prev.tables.size()]); + } + } + + // Copy the list change info if there are multiple LinkViews for the same LinkList + auto id = [](auto const& list) { return std::tie(list.table_ndx, list.col_ndx, list.row_ndx); }; + for (size_t i = 1; i < m_current->lists.size(); ++i) { + for (size_t j = i; j > 0; --j) { + if (id(m_current->lists[i]) == id(m_current->lists[j - 1])) { + m_current->lists[j - 1].changes->merge(CollectionChangeBuilder{*m_current->lists[i].changes}); + } + } + } + } + +private: + std::vector m_info; + TransactionChangeInfo* m_current = nullptr; + SharedGroup& m_sg; +}; +} // anonymous namespace + +void RealmCoordinator::run_async_notifiers() +{ + std::unique_lock lock(m_notifier_mutex); + + clean_up_dead_notifiers(); + + if (m_notifiers.empty() && m_new_notifiers.empty()) { + return; + } + + if (!m_async_error) { + open_helper_shared_group(); + } + + if (m_async_error) { + std::move(m_new_notifiers.begin(), m_new_notifiers.end(), std::back_inserter(m_notifiers)); + m_new_notifiers.clear(); + return; + } + + VersionID version; + + // Advance all of the new notifiers to the most recent version, if any + auto new_notifiers = std::move(m_new_notifiers); + IncrementalChangeInfo new_notifier_change_info(*m_advancer_sg, new_notifiers); + + if (!new_notifiers.empty()) { + REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Reading); + REALM_ASSERT_3(m_advancer_sg->get_version_of_current_transaction().version, + <=, new_notifiers.front()->version().version); + + // The advancer SG can be at an older version than the oldest new notifier + // if a notifier was added and then removed before it ever got the chance + // to run, as we don't move the pin forward when removing dead notifiers + transaction::advance(*m_advancer_sg, nullptr, new_notifiers.front()->version()); + + // Advance each of the new notifiers to the latest version, attaching them + // to the SG at their handover version. This requires a unique + // TransactionChangeInfo for each source version, so that things don't + // see changes from before the version they were handed over from. + // Each Info has all of the changes between that source version and the + // next source version, and they'll be merged together later after + // releasing the lock + for (auto& notifier : new_notifiers) { + new_notifier_change_info.advance_incremental(notifier->version()); + notifier->attach_to(*m_advancer_sg); + notifier->add_required_change_info(new_notifier_change_info.current()); + } + new_notifier_change_info.advance_to_final(VersionID{}); + + for (auto& notifier : new_notifiers) { + notifier->detach(); + } + + // We want to advance the non-new notifiers to the same version as the + // new notifiers to avoid having to merge changes from any new + // transaction that happen immediately after this into the new notifier + // changes + version = m_advancer_sg->get_version_of_current_transaction(); + m_advancer_sg->end_read(); + } + else { + // If we have no new notifiers we want to just advance to the latest + // version, but we have to pick a "latest" version while holding the + // notifier lock to avoid advancing over a transaction which should be + // skipped + m_advancer_sg->begin_read(); + version = m_advancer_sg->get_version_of_current_transaction(); + m_advancer_sg->end_read(); + } + REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Ready); + + auto skip_version = m_notifier_skip_version; + m_notifier_skip_version = {0, 0}; + + // Make a copy of the notifiers vector and then release the lock to avoid + // blocking other threads trying to register or unregister notifiers while we run them + auto notifiers = m_notifiers; + m_notifiers.insert(m_notifiers.end(), new_notifiers.begin(), new_notifiers.end()); + lock.unlock(); + + if (skip_version.version) { + REALM_ASSERT(!notifiers.empty()); + REALM_ASSERT(version >= skip_version); + IncrementalChangeInfo change_info(*m_notifier_sg, notifiers); + for (auto& notifier : notifiers) + notifier->add_required_change_info(change_info.current()); + change_info.advance_to_final(skip_version); + + for (auto& notifier : notifiers) + notifier->run(); + + lock.lock(); + for (auto& notifier : notifiers) + notifier->prepare_handover(); + lock.unlock(); + } + + // Advance the non-new notifiers to the same version as we advanced the new + // ones to (or the latest if there were no new ones) + IncrementalChangeInfo change_info(*m_notifier_sg, notifiers); + for (auto& notifier : notifiers) { + notifier->add_required_change_info(change_info.current()); + } + change_info.advance_to_final(version); + + // Attach the new notifiers to the main SG and move them to the main list + for (auto& notifier : new_notifiers) { + notifier->attach_to(*m_notifier_sg); + notifier->run(); + } + + // Change info is now all ready, so the notifiers can now perform their + // background work + for (auto& notifier : notifiers) { + notifier->run(); + } + + // Reacquire the lock while updating the fields that are actually read on + // other threads + lock.lock(); + for (auto& notifier : new_notifiers) { + notifier->prepare_handover(); + } + for (auto& notifier : notifiers) { + notifier->prepare_handover(); + } + clean_up_dead_notifiers(); + m_notifier_cv.notify_all(); +} + +void RealmCoordinator::open_helper_shared_group() +{ + if (!m_notifier_sg) { + try { + std::unique_ptr read_only_group; + Realm::open_with_config(m_config, m_notifier_history, m_notifier_sg, read_only_group, nullptr); + REALM_ASSERT(!read_only_group); + m_notifier_sg->begin_read(); + } + catch (...) { + // Store the error to be passed to the async notifiers + m_async_error = std::current_exception(); + m_notifier_sg = nullptr; + m_notifier_history = nullptr; + } + } + else if (m_notifiers.empty()) { + m_notifier_sg->begin_read(); + } +} + +void RealmCoordinator::advance_to_ready(Realm& realm) +{ + std::unique_lock lock(m_notifier_mutex); + _impl::NotifierPackage notifiers(m_async_error, notifiers_for_realm(realm), this); + lock.unlock(); + notifiers.package_and_wait(util::none); + + auto& sg = Realm::Internal::get_shared_group(realm); + if (notifiers) { + auto version = notifiers.version(); + if (version) { + auto current_version = sg->get_version_of_current_transaction(); + // Notifications are out of date, so just discard + // This should only happen if begin_read() was used to change the + // read version outside of our control + if (*version < current_version) + return; + // While there is a newer version, notifications are for the current + // version so just deliver them without advancing + if (*version == current_version) { + if (realm.m_binding_context) + realm.m_binding_context->will_send_notifications(); + notifiers.deliver(*sg); + notifiers.after_advance(); + if (realm.m_binding_context) + realm.m_binding_context->did_send_notifications(); + return; + } + } + } + + transaction::advance(sg, realm.m_binding_context.get(), notifiers); +} + +std::vector> RealmCoordinator::notifiers_for_realm(Realm& realm) +{ + std::vector> ret; + for (auto& notifier : m_new_notifiers) { + if (notifier->is_for_realm(realm)) + ret.push_back(notifier); + } + for (auto& notifier : m_notifiers) { + if (notifier->is_for_realm(realm)) + ret.push_back(notifier); + } + return ret; +} + +bool RealmCoordinator::advance_to_latest(Realm& realm) +{ + using sgf = SharedGroupFriend; + + auto& sg = Realm::Internal::get_shared_group(realm); + std::unique_lock lock(m_notifier_mutex); + _impl::NotifierPackage notifiers(m_async_error, notifiers_for_realm(realm), this); + lock.unlock(); + notifiers.package_and_wait(sgf::get_version_of_latest_snapshot(*sg)); + + auto version = sg->get_version_of_current_transaction(); + transaction::advance(sg, realm.m_binding_context.get(), notifiers); + + // Realm could be closed in the callbacks. + if (realm.is_closed()) + return false; + + return version != sg->get_version_of_current_transaction(); +} + +void RealmCoordinator::promote_to_write(Realm& realm) +{ + REALM_ASSERT(!realm.is_in_transaction()); + + std::unique_lock lock(m_notifier_mutex); + _impl::NotifierPackage notifiers(m_async_error, notifiers_for_realm(realm), this); + lock.unlock(); + + auto& sg = Realm::Internal::get_shared_group(realm); + transaction::begin(sg, realm.m_binding_context.get(), notifiers); +} + +void RealmCoordinator::process_available_async(Realm& realm) +{ + REALM_ASSERT(!realm.is_in_transaction()); + + std::unique_lock lock(m_notifier_mutex); + auto notifiers = notifiers_for_realm(realm); + if (notifiers.empty()) + return; + + if (realm.m_binding_context) + realm.m_binding_context->will_send_notifications(); + + if (auto error = m_async_error) { + lock.unlock(); + for (auto& notifier : notifiers) + notifier->deliver_error(m_async_error); + if (realm.m_binding_context) + realm.m_binding_context->did_send_notifications(); + return; + } + + bool in_read = realm.is_in_read_transaction(); + auto& sg = Realm::Internal::get_shared_group(realm); + if (!sg) // i.e. the Realm was closed in a callback above + return; + auto version = sg->get_version_of_current_transaction(); + auto package = [&](auto& notifier) { + return !(notifier->has_run() && (!in_read || notifier->version() == version) && notifier->package_for_delivery()); + }; + notifiers.erase(std::remove_if(begin(notifiers), end(notifiers), package), end(notifiers)); + lock.unlock(); + + // no before advance because the Realm is already at the given version, + // because we're either sending initial notifications or the write was + // done on this Realm instance + + // Skip delivering if the Realm isn't in a read transaction + if (in_read) { + for (auto& notifier : notifiers) + notifier->deliver(*sg); + } + + // but still call the change callbacks + for (auto& notifier : notifiers) + notifier->after_advance(); + + if (realm.m_binding_context) + realm.m_binding_context->did_send_notifications(); +} + +void RealmCoordinator::set_transaction_callback(std::function fn) +{ + create_sync_session(); + m_transaction_callback = std::move(fn); +} + +#if REALM_ENABLE_SYNC +partial_sync::WorkQueue& RealmCoordinator::partial_sync_work_queue() +{ + return *m_partial_sync_work_queue; +} +#endif diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp new file mode 100644 index 0000000000..4a711d3d4c --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp @@ -0,0 +1,252 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/results_notifier.hpp" + +#include "shared_realm.hpp" + +using namespace realm; +using namespace realm::_impl; + +ResultsNotifier::ResultsNotifier(Results& target) +: CollectionNotifier(target.get_realm()) +, m_target_results(&target) +, m_target_is_in_table_order(target.is_in_table_order()) +{ + Query q = target.get_query(); + set_table(*q.get_table()); + m_query_handover = source_shared_group().export_for_handover(q, MutableSourcePayload::Move); + DescriptorOrdering::generate_patch(target.get_descriptor_ordering(), m_ordering_handover); +} + +void ResultsNotifier::target_results_moved(Results& old_target, Results& new_target) +{ + auto lock = lock_target(); + + REALM_ASSERT(m_target_results == &old_target); + m_target_results = &new_target; +} + +void ResultsNotifier::release_data() noexcept +{ + m_query = nullptr; +} + +// Most of the inter-thread synchronization for run(), prepare_handover(), +// attach_to(), detach(), release_data() and deliver() is done by +// RealmCoordinator external to this code, which has some potentially +// non-obvious results on which members are and are not safe to use without +// holding a lock. +// +// add_required_change_info(), attach_to(), detach(), run(), +// prepare_handover(), and release_data() are all only ever called on a single +// background worker thread. call_callbacks() and deliver() are called on the +// target thread. Calls to prepare_handover() and deliver() are guarded by a +// lock. +// +// In total, this means that the safe data flow is as follows: +// - add_Required_change_info(), prepare_handover(), attach_to(), detach() and +// release_data() can read members written by each other +// - deliver() can read members written to in prepare_handover(), deliver(), +// and call_callbacks() +// - call_callbacks() and read members written to in deliver() +// +// Separately from the handover data flow, m_target_results is guarded by the target lock + +bool ResultsNotifier::do_add_required_change_info(TransactionChangeInfo& info) +{ + REALM_ASSERT(m_query); + m_info = &info; + + auto& table = *m_query->get_table(); + if (!table.is_attached()) + return false; + + auto table_ndx = table.get_index_in_group(); + if (table_ndx == npos) { // is a subtable + auto& parent = *table.get_parent_table(); + size_t row_ndx = table.get_parent_row_index(); + size_t col_ndx = find_container_column(parent, row_ndx, &table, type_Table, &Table::get_subtable); + info.lists.push_back({parent.get_index_in_group(), row_ndx, col_ndx, &m_changes}); + } + else { // is a top-level table + if (info.table_moves_needed.size() <= table_ndx) + info.table_moves_needed.resize(table_ndx + 1); + info.table_moves_needed[table_ndx] = true; + } + + return has_run() && have_callbacks(); +} + +bool ResultsNotifier::need_to_run() +{ + REALM_ASSERT(m_info); + REALM_ASSERT(!m_tv.is_attached()); + + { + auto lock = lock_target(); + // Don't run the query if the results aren't actually going to be used + if (!get_realm() || (!have_callbacks() && !m_target_results->wants_background_updates())) { + return false; + } + } + + // If we've run previously, check if we need to rerun + if (has_run() && m_query->sync_view_if_needed() == m_last_seen_version) { + return false; + } + + return true; +} + +void ResultsNotifier::calculate_changes() +{ + size_t table_ndx = m_query->get_table()->get_index_in_group(); + if (has_run() && have_callbacks()) { + CollectionChangeBuilder* changes = nullptr; + if (table_ndx == npos) + changes = &m_changes; + else if (table_ndx < m_info->tables.size()) + changes = &m_info->tables[table_ndx]; + + std::vector next_rows; + next_rows.reserve(m_tv.size()); + for (size_t i = 0; i < m_tv.size(); ++i) + next_rows.push_back(m_tv[i].get_index()); + + util::Optional move_candidates; + if (changes) { + auto const& moves = changes->moves; + for (auto& idx : m_previous_rows) { + if (changes->deletions.contains(idx)) { + // check if this deletion was actually a move + auto it = lower_bound(begin(moves), end(moves), idx, + [](auto const& a, auto b) { return a.from < b; }); + idx = it != moves.end() && it->from == idx ? it->to : npos; + } + else + idx = changes->insertions.shift(changes->deletions.unshift(idx)); + } + if (m_target_is_in_table_order && !m_descriptor_ordering.will_apply_sort()) + move_candidates = changes->insertions; + } + + m_changes = CollectionChangeBuilder::calculate(m_previous_rows, next_rows, + get_modification_checker(*m_info, *m_query->get_table()), + move_candidates); + + m_previous_rows = std::move(next_rows); + } + else { + m_previous_rows.resize(m_tv.size()); + for (size_t i = 0; i < m_tv.size(); ++i) + m_previous_rows[i] = m_tv[i].get_index(); + } +} + +void ResultsNotifier::run() +{ + // Table's been deleted, so report all rows as deleted + if (!m_query->get_table()->is_attached()) { + m_changes = {}; + m_changes.deletions.set(m_previous_rows.size()); + m_previous_rows.clear(); + return; + } + + if (!need_to_run()) + return; + + m_query->sync_view_if_needed(); + m_tv = m_query->find_all(); + m_tv.apply_descriptor_ordering(m_descriptor_ordering); + m_last_seen_version = m_tv.sync_if_needed(); + + calculate_changes(); +} + +void ResultsNotifier::do_prepare_handover(SharedGroup& sg) +{ + if (!m_tv.is_attached()) { + // if the table version didn't change we can just reuse the same handover + // object and bump its version to the current SG version + if (m_tv_handover) + m_tv_handover->version = sg.get_version_of_current_transaction(); + + // add_changes() needs to be called even if there are no changes to + // clear the skip flag on the callbacks + add_changes(std::move(m_changes)); + return; + } + + REALM_ASSERT(m_tv.is_in_sync()); + + m_tv_handover = sg.export_for_handover(m_tv, MutableSourcePayload::Move); + + add_changes(std::move(m_changes)); + REALM_ASSERT(m_changes.empty()); + + // detach the TableView as we won't need it again and keeping it around + // makes advance_read() much more expensive + m_tv = {}; +} + +void ResultsNotifier::deliver(SharedGroup& sg) +{ + auto lock = lock_target(); + + // Target realm being null here indicates that we were unregistered while we + // were in the process of advancing the Realm version and preparing for + // delivery, i.e. the results was destroyed from the "wrong" thread + if (!get_realm()) { + return; + } + + REALM_ASSERT(!m_query_handover); + if (m_tv_to_deliver) { + Results::Internal::set_table_view(*m_target_results, + std::move(*sg.import_from_handover(std::move(m_tv_to_deliver)))); + } + REALM_ASSERT(!m_tv_to_deliver); +} + +bool ResultsNotifier::prepare_to_deliver() +{ + auto lock = lock_target(); + if (!get_realm()) + return false; + m_tv_to_deliver = std::move(m_tv_handover); + return true; +} + +void ResultsNotifier::do_attach_to(SharedGroup& sg) +{ + REALM_ASSERT(m_query_handover); + m_query = sg.import_from_handover(std::move(m_query_handover)); + m_descriptor_ordering = DescriptorOrdering::create_from_and_consume_patch(m_ordering_handover, *m_query->get_table()); +} + +void ResultsNotifier::do_detach_from(SharedGroup& sg) +{ + REALM_ASSERT(m_query); + REALM_ASSERT(!m_tv.is_attached()); + + DescriptorOrdering::generate_patch(m_descriptor_ordering, m_ordering_handover); + m_query_handover = sg.export_for_handover(*m_query, MutableSourcePayload::Move); + m_query = nullptr; +} diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp new file mode 100644 index 0000000000..2b3ff2723a --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp @@ -0,0 +1,875 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/transact_log_handler.hpp" + +#include "binding_context.hpp" +#include "impl/collection_notifier.hpp" +#include "index_set.hpp" +#include "shared_realm.hpp" + +#include +#include + +#include +#include + +using namespace realm; + +namespace { + +class KVOAdapter : public _impl::TransactionChangeInfo { +public: + KVOAdapter(std::vector& observers, BindingContext* context); + + void before(SharedGroup& sg); + void after(SharedGroup& sg); + +private: + BindingContext* m_context; + std::vector& m_observers; + std::vector m_invalidated; + + struct ListInfo { + BindingContext::ObserverState* observer; + _impl::CollectionChangeBuilder builder; + size_t col; + size_t initial_size; + }; + std::vector m_lists; + VersionID m_version; + + size_t new_table_ndx(size_t ndx) const { return ndx < table_indices.size() ? table_indices[ndx] : ndx; } +}; + +KVOAdapter::KVOAdapter(std::vector& observers, BindingContext* context) +: _impl::TransactionChangeInfo{} +, m_context(context) +, m_observers(observers) +{ + if (m_observers.empty()) + return; + + std::vector tables_needed; + for (auto& observer : observers) { + tables_needed.push_back(observer.table_ndx); + } + std::sort(begin(tables_needed), end(tables_needed)); + tables_needed.erase(std::unique(begin(tables_needed), end(tables_needed)), end(tables_needed)); + + auto realm = context->realm.lock(); + auto& group = realm->read_group(); + for (auto& observer : observers) { + auto table = group.get_table(observer.table_ndx); + for (size_t i = 0, count = table->get_column_count(); i < count; ++i) { + auto type = table->get_column_type(i); + if (type == type_LinkList) + m_lists.push_back({&observer, {}, i, size_t(-1)}); + else if (type == type_Table) + m_lists.push_back({&observer, {}, i, table->get_subtable_size(i, observer.row_ndx)}); + } + } + + auto max = std::max_element(begin(tables_needed), end(tables_needed)); + if (*max >= table_modifications_needed.size()) + table_modifications_needed.resize(*max + 1, false); + if (*max >= table_moves_needed.size()) + table_moves_needed.resize(*max + 1, false); + for (auto& tbl : tables_needed) { + table_modifications_needed[tbl] = true; + table_moves_needed[tbl] = true; + } + for (auto& list : m_lists) + lists.push_back({list.observer->table_ndx, list.observer->row_ndx, list.col, &list.builder}); +} + +void KVOAdapter::before(SharedGroup& sg) +{ + if (!m_context) + return; + + m_version = sg.get_version_of_current_transaction(); + if (tables.empty()) + return; + + for (auto& observer : m_observers) { + size_t table_ndx = new_table_ndx(observer.table_ndx); + if (table_ndx >= tables.size()) + continue; + + auto const& table = tables[table_ndx]; + auto const& moves = table.moves; + auto idx = observer.row_ndx; + auto it = lower_bound(begin(moves), end(moves), idx, + [](auto const& a, auto b) { return a.from < b; }); + if (it != moves.end() && it->from == idx) + idx = it->to; + else if (table.deletions.contains(idx)) { + m_invalidated.push_back(observer.info); + continue; + } + else + idx = table.insertions.shift(table.deletions.unshift(idx)); + if (table.modifications.contains(idx)) { + observer.changes.resize(table.columns.size()); + size_t i = 0; + for (auto& c : table.columns) { + auto& change = observer.changes[i]; + if (table_ndx >= column_indices.size() || column_indices[table_ndx].empty()) + change.initial_column_index = i; + else if (i >= column_indices[table_ndx].size()) + change.initial_column_index = i - column_indices[table_ndx].size() + column_indices[table_ndx].back() + 1; + else + change.initial_column_index = column_indices[table_ndx][i]; + if (change.initial_column_index != npos && c.contains(idx)) + change.kind = BindingContext::ColumnInfo::Kind::Set; + ++i; + } + } + } + + for (auto& list : m_lists) { + if (list.builder.empty()) { + // We may have pre-emptively marked the column as modified if the + // LinkList was selected but the actual changes made ended up being + // a no-op + if (list.col < list.observer->changes.size()) + list.observer->changes[list.col].kind = BindingContext::ColumnInfo::Kind::None; + continue; + } + // If the containing row was deleted then changes will be empty + if (list.observer->changes.empty()) { + REALM_ASSERT_DEBUG(tables[new_table_ndx(list.observer->table_ndx)].deletions.contains(list.observer->row_ndx)); + continue; + } + // otherwise the column should have been marked as modified + REALM_ASSERT(list.col < list.observer->changes.size()); + auto& builder = list.builder; + auto& changes = list.observer->changes[list.col]; + + builder.modifications.remove(builder.insertions); + + // KVO can't express moves (becaue NSArray doesn't have them), so + // transform them into a series of sets on each affected index when possible + if (!builder.moves.empty() && builder.insertions.count() == builder.moves.size() && builder.deletions.count() == builder.moves.size()) { + changes.kind = BindingContext::ColumnInfo::Kind::Set; + changes.indices = builder.modifications; + changes.indices.add(builder.deletions); + + // Iterate over each of the rows which may have been shifted by + // the moves and check if it actually has been, or if it's ended + // up in the same place as it started (either because the moves were + // actually a swap that doesn't effect the rows in between, or the + // combination of moves happen to leave some intermediate rows in + // the same place) + auto in_range = [](auto& it, auto end, size_t i) { + if (it != end && i >= it->second) + ++it; + return it != end && i >= it->first && i < it->second; + }; + + auto del_it = builder.deletions.begin(), del_end = builder.deletions.end(); + auto ins_it = builder.insertions.begin(), ins_end = builder.insertions.end(); + size_t start = std::min(ins_it->first, del_it->first); + size_t end = std::max(std::prev(ins_end)->second, std::prev(del_end)->second); + ptrdiff_t shift = 0; + for (size_t i = start; i < end; ++i) { + if (in_range(del_it, del_end, i)) + --shift; + else if (in_range(ins_it, ins_end, i + shift)) + ++shift; + if (shift != 0) + changes.indices.add(i); + } + } + // KVO can't express multiple types of changes at once + else if (builder.insertions.empty() + builder.modifications.empty() + builder.deletions.empty() < 2) { + changes.kind = BindingContext::ColumnInfo::Kind::SetAll; + } + else if (!builder.insertions.empty()) { + changes.kind = BindingContext::ColumnInfo::Kind::Insert; + changes.indices = builder.insertions; + } + else if (!builder.modifications.empty()) { + changes.kind = BindingContext::ColumnInfo::Kind::Set; + changes.indices = builder.modifications; + } + else { + REALM_ASSERT(!builder.deletions.empty()); + changes.kind = BindingContext::ColumnInfo::Kind::Remove; + // Table clears don't come with the size, so we need to fix up the + // notification to make it just delete all rows that actually existed + if (std::prev(builder.deletions.end())->second > list.initial_size) + changes.indices.set(list.initial_size); + else + changes.indices = builder.deletions; + } + } + m_context->will_change(m_observers, m_invalidated); +} + +void KVOAdapter::after(SharedGroup& sg) +{ + if (!m_context) + return; + m_context->did_change(m_observers, m_invalidated, + m_version != VersionID{} && + m_version != sg.get_version_of_current_transaction()); +} + +template +struct MarkDirtyMixin { + bool mark_dirty(size_t row, size_t col, _impl::Instruction instr=_impl::instr_Set) + { + // Ignore SetDefault and SetUnique as those conceptually cannot be + // changes to existing rows + if (instr == _impl::instr_Set) + static_cast(this)->mark_dirty(row, col); + return true; + } + + bool set_int(size_t c, size_t r, int_fast64_t, _impl::Instruction i, size_t) { return mark_dirty(r, c, i); } + bool set_bool(size_t c, size_t r, bool, _impl::Instruction i) { return mark_dirty(r, c, i); } + bool set_float(size_t c, size_t r, float, _impl::Instruction i) { return mark_dirty(r, c, i); } + bool set_double(size_t c, size_t r, double, _impl::Instruction i) { return mark_dirty(r, c, i); } + bool set_string(size_t c, size_t r, StringData, _impl::Instruction i, size_t) { return mark_dirty(r, c, i); } + bool set_binary(size_t c, size_t r, BinaryData, _impl::Instruction i) { return mark_dirty(r, c, i); } + bool set_olddatetime(size_t c, size_t r, OldDateTime, _impl::Instruction i) { return mark_dirty(r, c, i); } + bool set_timestamp(size_t c, size_t r, Timestamp, _impl::Instruction i) { return mark_dirty(r, c, i); } + bool set_table(size_t c, size_t r, _impl::Instruction i) { return mark_dirty(r, c, i); } + bool set_mixed(size_t c, size_t r, const Mixed&, _impl::Instruction i) { return mark_dirty(r, c, i); } + bool set_link(size_t c, size_t r, size_t, size_t, _impl::Instruction i) { return mark_dirty(r, c, i); } + bool set_null(size_t c, size_t r, _impl::Instruction i, size_t) { return mark_dirty(r, c, i); } + + bool add_int(size_t col, size_t row, int_fast64_t) { return mark_dirty(row, col); } + bool nullify_link(size_t col, size_t row, size_t) { return mark_dirty(row, col); } + bool insert_substring(size_t col, size_t row, size_t, StringData) { return mark_dirty(row, col); } + bool erase_substring(size_t col, size_t row, size_t, size_t) { return mark_dirty(row, col); } + + bool set_int_unique(size_t, size_t, size_t, int_fast64_t) { return true; } + bool set_string_unique(size_t, size_t, size_t, StringData) { return true; } + + bool add_row_with_key(size_t, size_t, size_t, int64_t) { return true; } +}; + +class TransactLogValidationMixin { + // Index of currently selected table + size_t m_current_table = 0; + + REALM_NORETURN + REALM_NOINLINE + void schema_error() + { + throw _impl::UnsupportedSchemaChange(); + } + +protected: + size_t current_table() const noexcept { return m_current_table; } + +public: + + bool select_table(size_t group_level_ndx, int, const size_t*) noexcept + { + m_current_table = group_level_ndx; + return true; + } + + // Removing or renaming things while a Realm is open is never supported + bool erase_group_level_table(size_t, size_t) { schema_error(); } + bool rename_group_level_table(size_t, StringData) { schema_error(); } + bool erase_column(size_t) { schema_error(); } + bool erase_link_column(size_t, size_t, size_t) { schema_error(); } + bool rename_column(size_t, StringData) { schema_error(); } + + // Schema changes which don't involve a change in the schema version are + // allowed + bool add_search_index(size_t) { return true; } + bool remove_search_index(size_t) { return true; } + + // Additive changes and reorderings are supported + bool insert_group_level_table(size_t, size_t, StringData) { return true; } + bool insert_column(size_t, DataType, StringData, bool) { return true; } + bool insert_link_column(size_t, DataType, StringData, size_t, size_t) { return true; } + bool set_link_type(size_t, LinkType) { return true; } + bool move_column(size_t, size_t) { return true; } + bool move_group_level_table(size_t, size_t) { return true; } + + // Non-schema changes are all allowed + void parse_complete() { } + bool select_descriptor(int, const size_t*) { return true; } + bool select_link_list(size_t, size_t, size_t) { return true; } + bool insert_empty_rows(size_t, size_t, size_t, bool) { return true; } + bool erase_rows(size_t, size_t, size_t, bool) { return true; } + bool swap_rows(size_t, size_t) { return true; } + bool move_row(size_t, size_t) { return true; } + bool clear_table(size_t=0) noexcept { return true; } + bool link_list_set(size_t, size_t, size_t) { return true; } + bool link_list_insert(size_t, size_t, size_t) { return true; } + bool link_list_erase(size_t, size_t) { return true; } + bool link_list_nullify(size_t, size_t) { return true; } + bool link_list_clear(size_t) { return true; } + bool link_list_move(size_t, size_t) { return true; } + bool link_list_swap(size_t, size_t) { return true; } + bool merge_rows(size_t, size_t) { return true; } + bool optimize_table() { return true; } +}; + + +// A transaction log handler that just validates that all operations made are +// ones supported by the object store +struct TransactLogValidator : public TransactLogValidationMixin, public MarkDirtyMixin { + void mark_dirty(size_t, size_t) { } +}; + +// Move the value at container[from] to container[to], shifting everything in +// between, or do nothing if either are out of bounds +template +void rotate(Container& container, size_t from, size_t to) +{ + REALM_ASSERT(from != to); + if (from >= container.size() && to >= container.size()) + return; + if (from >= container.size() || to >= container.size()) + container.resize(std::max(from, to) + 1); + if (from < to) + std::rotate(begin(container) + from, begin(container) + from + 1, begin(container) + to + 1); + else + std::rotate(begin(container) + to, begin(container) + from, begin(container) + from + 1); +} + +// Insert a default-initialized value at pos if there is anything after pos in the container. +template +void insert_empty_at(Container& container, size_t pos) +{ + if (pos < container.size()) + container.emplace(container.begin() + pos); +} + +// Shift `value` to reflect a move from `from` to `to` +void adjust_for_move(size_t& value, size_t from, size_t to) +{ + if (value == from) + value = to; + else if (value > from && value <= to) + --value; + else if (value < from && value >= to) + ++value; +} + +void adjust_for_move(std::vector& values, size_t from, size_t to) +{ + for (auto& value : values) + adjust_for_move(value, from, to); +} + +void expand_to(std::vector& cols, size_t i) +{ + auto old_size = cols.size(); + if (old_size > i) + return; + + cols.resize(std::max(old_size * 2, i + 1)); + std::iota(begin(cols) + old_size, end(cols), old_size == 0 ? 0 : cols[old_size - 1] + 1); +} + +void adjust_ge(std::vector& values, size_t i) +{ + for (auto& value : values) { + if (value >= i) + ++value; + } +} + +// Extends TransactLogValidator to track changes made to LinkViews +class TransactLogObserver : public TransactLogValidationMixin, public MarkDirtyMixin { + _impl::TransactionChangeInfo& m_info; + _impl::CollectionChangeBuilder* m_active_list = nullptr; + _impl::CollectionChangeBuilder* m_active_table = nullptr; + _impl::CollectionChangeBuilder* m_active_descriptor = nullptr; + + bool m_need_move_info = false; + bool m_is_top_level_table = true; + + _impl::CollectionChangeBuilder* find_list(size_t tbl, size_t col, size_t row) + { + // When there are multiple source versions there could be multiple + // change objects for a single LinkView, in which case we need to use + // the last one + for (auto it = m_info.lists.rbegin(), end = m_info.lists.rend(); it != end; ++it) { + if (it->table_ndx == tbl && it->row_ndx == row && it->col_ndx == col) + return it->changes; + } + return nullptr; + } + +public: + TransactLogObserver(_impl::TransactionChangeInfo& info) + : m_info(info) { } + + void mark_dirty(size_t row, size_t col) + { + if (m_active_table) + m_active_table->modify(row, col); + } + + void parse_complete() + { + for (auto& table : m_info.tables) + table.parse_complete(); + for (auto& list : m_info.lists) + list.changes->clean_up_stale_moves(); + } + + bool select_descriptor(int levels, const size_t*) noexcept + { + if (levels == 0) // schema of selected table is being modified + m_active_descriptor = m_active_table; + else // schema of subtable is being modified; currently don't need to track this + m_active_descriptor = nullptr; + return true; + } + + bool select_table(size_t group_level_ndx, int len, size_t const* path) noexcept + { + TransactLogValidationMixin::select_table(group_level_ndx, len, path); + m_active_table = nullptr; + m_is_top_level_table = true; + + // Nested subtables currently not supported + if (len > 1) { + m_is_top_level_table = false; + return true; + } + + auto tbl_ndx = current_table(); + if (!m_info.track_all && (tbl_ndx >= m_info.table_modifications_needed.size() || !m_info.table_modifications_needed[tbl_ndx])) + return true; + + m_need_move_info = m_info.track_all || (tbl_ndx < m_info.table_moves_needed.size() && + m_info.table_moves_needed[tbl_ndx]); + if (m_info.tables.size() <= tbl_ndx) + m_info.tables.resize(std::max(m_info.tables.size() * 2, tbl_ndx + 1)); + m_active_table = &m_info.tables[tbl_ndx]; + + if (len == 1) { + // Mark the cell containing the subtable as modified since selecting + // a table is always followed by a modification of some sort + size_t col = path[0]; + size_t row = path[1]; + mark_dirty(row, col); + + m_active_table = nullptr; + m_is_top_level_table = false; + if (auto table = find_list(current_table(), col, row)) { + m_active_table = table; + m_need_move_info = true; + } + } + return true; + } + + bool select_link_list(size_t col, size_t row, size_t) + { + mark_dirty(row, col); + m_active_list = find_list(current_table(), col, row); + return true; + } + + bool link_list_set(size_t index, size_t, size_t) + { + if (m_active_list) + m_active_list->modify(index); + return true; + } + + bool link_list_insert(size_t index, size_t, size_t) + { + if (m_active_list) + m_active_list->insert(index); + return true; + } + + bool link_list_erase(size_t index, size_t) + { + if (m_active_list) + m_active_list->erase(index); + return true; + } + + bool link_list_nullify(size_t index, size_t prior_size) + { + return link_list_erase(index, prior_size); + } + + bool link_list_swap(size_t index1, size_t index2) + { + link_list_set(index1, 0, npos); + link_list_set(index2, 0, npos); + return true; + } + + bool link_list_clear(size_t old_size) + { + if (m_active_list) + m_active_list->clear(old_size); + return true; + } + + bool link_list_move(size_t from, size_t to) + { + if (m_active_list) + m_active_list->move(from, to); + return true; + } + + bool insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t, bool) + { + if (m_active_table) + m_active_table->insert(row_ndx, num_rows_to_insert, m_need_move_info); + if (!m_is_top_level_table) + return true; + for (auto& list : m_info.lists) { + if (list.table_ndx == current_table() && list.row_ndx >= row_ndx) + list.row_ndx += num_rows_to_insert; + } + return true; + } + + bool add_row_with_key(size_t row_ndx, size_t prior_num_rows, size_t, int64_t) + { + insert_empty_rows(row_ndx, 1, prior_num_rows, false); + return true; + } + + bool erase_rows(size_t row_ndx, size_t, size_t prior_num_rows, bool unordered) + { + if (!unordered) { + if (m_active_table) + m_active_table->erase(row_ndx); + return true; + } + size_t last_row = prior_num_rows - 1; + if (m_active_table) + m_active_table->move_over(row_ndx, last_row, m_need_move_info); + + if (!m_is_top_level_table) + return true; + for (size_t i = 0; i < m_info.lists.size(); ++i) { + auto& list = m_info.lists[i]; + if (list.table_ndx != current_table()) + continue; + if (list.row_ndx == row_ndx) { + if (i + 1 < m_info.lists.size()) + m_info.lists[i] = std::move(m_info.lists.back()); + m_info.lists.pop_back(); + continue; + } + if (list.row_ndx == last_row) + list.row_ndx = row_ndx; + } + + return true; + } + + bool swap_rows(size_t row_ndx_1, size_t row_ndx_2) { + REALM_ASSERT(row_ndx_1 < row_ndx_2); + if (!m_is_top_level_table) { + if (m_active_table) { + m_active_table->move(row_ndx_1, row_ndx_2); + if (row_ndx_1 + 1 != row_ndx_2) + m_active_table->move(row_ndx_2 - 1, row_ndx_1); + } + return true; + } + + if (m_active_table) + m_active_table->swap(row_ndx_1, row_ndx_2, m_need_move_info); + for (auto& list : m_info.lists) { + if (list.table_ndx == current_table()) { + if (list.row_ndx == row_ndx_1) + list.row_ndx = row_ndx_2; + else if (list.row_ndx == row_ndx_2) + list.row_ndx = row_ndx_1; + } + } + return true; + } + + bool move_row(size_t from_ndx, size_t to_ndx) { + // Move row is not supported for top level tables: + REALM_ASSERT(!m_active_table || !m_is_top_level_table); + + if (m_active_table) + m_active_table->move(from_ndx, to_ndx); + return true; + } + + bool merge_rows(size_t from, size_t to) + { + if (m_active_table) + m_active_table->subsume(from, to, m_need_move_info); + if (!m_is_top_level_table) + return true; + for (auto& list : m_info.lists) { + if (list.table_ndx == current_table() && list.row_ndx == from) + list.row_ndx = to; + } + return true; + } + + bool clear_table(size_t=0) + { + auto tbl_ndx = current_table(); + if (m_active_table) + m_active_table->clear(std::numeric_limits::max()); + if (!m_is_top_level_table) + return true; + auto it = remove_if(begin(m_info.lists), end(m_info.lists), + [&](auto const& lv) { return lv.table_ndx == tbl_ndx; }); + m_info.lists.erase(it, end(m_info.lists)); + return true; + } + + bool insert_column(size_t ndx, DataType, StringData, bool) + { + m_info.schema_changed = true; + + if (m_active_descriptor) + m_active_descriptor->insert_column(ndx); + if (m_active_descriptor != m_active_table || !m_is_top_level_table) + return true; + for (auto& list : m_info.lists) { + if (list.table_ndx == current_table() && list.col_ndx >= ndx) + ++list.col_ndx; + } + if (m_info.column_indices.size() <= current_table()) + m_info.column_indices.resize(current_table() + 1); + auto& indices = m_info.column_indices[current_table()]; + expand_to(indices, ndx); + insert_empty_at(indices, ndx); + indices[ndx] = npos; + return true; + } + + void prepare_table_indices() + { + if (m_info.table_indices.empty() && !m_info.table_modifications_needed.empty()) { + m_info.table_indices.resize(m_info.table_modifications_needed.size()); + std::iota(begin(m_info.table_indices), end(m_info.table_indices), 0); + } + } + + bool insert_group_level_table(size_t ndx, size_t, StringData) + { + m_info.schema_changed = true; + + for (auto& list : m_info.lists) { + if (list.table_ndx >= ndx) + ++list.table_ndx; + } + prepare_table_indices(); + adjust_ge(m_info.table_indices, ndx); + insert_empty_at(m_info.tables, ndx); + insert_empty_at(m_info.table_moves_needed, ndx); + insert_empty_at(m_info.table_modifications_needed, ndx); + return true; + } + + bool move_column(size_t from, size_t to) + { + m_info.schema_changed = true; + + if (m_active_descriptor) + m_active_descriptor->move_column(from, to); + if (m_active_descriptor != m_active_table || !m_is_top_level_table) + return true; + for (auto& list : m_info.lists) { + if (list.table_ndx == current_table()) + adjust_for_move(list.col_ndx, from, to); + } + if (m_info.column_indices.size() <= current_table()) + m_info.column_indices.resize(current_table() + 1); + expand_to(m_info.column_indices[current_table()], std::max(from, to) + 1); + rotate(m_info.column_indices[current_table()], from, to); + return true; + } + + bool move_group_level_table(size_t from, size_t to) + { + m_info.schema_changed = true; + + for (auto& list : m_info.lists) + adjust_for_move(list.table_ndx, from, to); + + prepare_table_indices(); + adjust_for_move(m_info.table_indices, from, to); + rotate(m_info.tables, from, to); + rotate(m_info.table_modifications_needed, from, to); + rotate(m_info.table_moves_needed, from, to); + return true; + } + + bool insert_link_column(size_t ndx, DataType type, StringData name, size_t, size_t) { return insert_column(ndx, type, name, false); } +}; + +class KVOTransactLogObserver : public TransactLogObserver { + KVOAdapter m_adapter; + _impl::NotifierPackage& m_notifiers; + SharedGroup& m_sg; + +public: + KVOTransactLogObserver(std::vector& observers, + BindingContext* context, + _impl::NotifierPackage& notifiers, + SharedGroup& sg) + : TransactLogObserver(m_adapter) + , m_adapter(observers, context) + , m_notifiers(notifiers) + , m_sg(sg) + { + } + + ~KVOTransactLogObserver() + { + m_adapter.after(m_sg); + } + + void parse_complete() + { + TransactLogObserver::parse_complete(); + m_adapter.before(m_sg); + + using sgf = _impl::SharedGroupFriend; + m_notifiers.package_and_wait(sgf::get_version_of_latest_snapshot(m_sg)); + m_notifiers.before_advance(); + } +}; + +template +void advance_with_notifications(BindingContext* context, const std::unique_ptr& sg, + Func&& func, _impl::NotifierPackage& notifiers) +{ + auto old_version = sg->get_version_of_current_transaction(); + std::vector observers; + if (context) { + observers = context->get_observed_rows(); + } + + // Advancing to the latest version with notifiers requires using the full + // transaction log observer so that we have a point where we know what + // version we're going to before we actually advance to that version + if (observers.empty() && (!notifiers || notifiers.version())) { + notifiers.before_advance(); + func(TransactLogValidator()); + auto new_version = sg->get_version_of_current_transaction(); + if (context && old_version != new_version) + context->did_change({}, {}); + if (!sg) // did_change() could close the Realm. Just return if it does. + return; + if (context) + context->will_send_notifications(); + if (!sg) // will_send_notifications() could close the Realm. Just return if it does. + return; + // did_change() can change the read version, and if it does we can't + // deliver notifiers + if (new_version == sg->get_version_of_current_transaction()) + notifiers.deliver(*sg); + notifiers.after_advance(); + if (sg && context) + context->did_send_notifications(); + return; + } + + if (context) + context->will_send_notifications(); + func(KVOTransactLogObserver(observers, context, notifiers, *sg)); + notifiers.package_and_wait(sg->get_version_of_current_transaction().version); // is a no-op if parse_complete() was called + notifiers.deliver(*sg); + notifiers.after_advance(); + if (context) + context->did_send_notifications(); +} + +} // anonymous namespace + +namespace realm { +namespace _impl { + +UnsupportedSchemaChange::UnsupportedSchemaChange() +: std::logic_error("Schema mismatch detected: another process has modified the Realm file's schema in an incompatible way") +{ +} + +namespace transaction { +void advance(SharedGroup& sg, BindingContext*, VersionID version) +{ + LangBindHelper::advance_read(sg, TransactLogValidator(), version); +} + +void advance(const std::unique_ptr& sg, BindingContext* context, NotifierPackage& notifiers) +{ + advance_with_notifications(context, sg, [&](auto&&... args) { + LangBindHelper::advance_read(*sg, std::move(args)..., notifiers.version().value_or(VersionID{})); + }, notifiers); +} + +void begin_without_validation(SharedGroup& sg) +{ + LangBindHelper::promote_to_write(sg); +} + +void begin(const std::unique_ptr& sg, BindingContext* context, NotifierPackage& notifiers) +{ + advance_with_notifications(context, sg, [&](auto&&... args) { + LangBindHelper::promote_to_write(*sg, std::move(args)...); + }, notifiers); +} + +void commit(SharedGroup& sg) +{ + LangBindHelper::commit_and_continue_as_read(sg); +} + +void cancel(SharedGroup& sg, BindingContext* context) +{ + std::vector observers; + if (context) { + observers = context->get_observed_rows(); + } + if (observers.empty()) { + LangBindHelper::rollback_and_continue_as_read(sg); + return; + } + + _impl::NotifierPackage notifiers; + LangBindHelper::rollback_and_continue_as_read(sg, KVOTransactLogObserver(observers, context, notifiers, sg)); +} + +void advance(SharedGroup& sg, TransactionChangeInfo& info, VersionID version) +{ + if (!info.track_all && info.table_modifications_needed.empty() && info.lists.empty()) { + LangBindHelper::advance_read(sg, version); + } + else { + LangBindHelper::advance_read(sg, TransactLogObserver(info), version); + } +} + +} // namespace transaction +} // namespace _impl +} // namespace realm diff --git a/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp b/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp new file mode 100644 index 0000000000..1620eeab4f --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "impl/weak_realm_notifier.hpp" + +#include "shared_realm.hpp" +#include "util/event_loop_signal.hpp" + +using namespace realm; +using namespace realm::_impl; + + +WeakRealmNotifier::WeakRealmNotifier(const std::shared_ptr& realm, bool cache) +: m_realm(realm) +, m_execution_context(realm->config().execution_context) +, m_realm_key(realm.get()) +, m_cache(cache) +, m_signal(std::make_shared>(Callback{realm})) +{ +} + +WeakRealmNotifier::~WeakRealmNotifier() = default; + +void WeakRealmNotifier::Callback::operator()() const +{ + if (auto realm = weak_realm.lock()) { + realm->notify(); + } +} + +void WeakRealmNotifier::notify() +{ + m_signal->notify(); +} diff --git a/Pods/Realm/Realm/ObjectStore/src/index_set.cpp b/Pods/Realm/Realm/ObjectStore/src/index_set.cpp new file mode 100644 index 0000000000..e1a3b1071a --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/index_set.cpp @@ -0,0 +1,707 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "index_set.hpp" + +#include + +#include + +using namespace realm; +using namespace realm::_impl; + +const size_t IndexSet::npos; + +template +void MutableChunkedRangeVectorIterator::set(size_t front, size_t back) +{ + this->m_outer->count -= this->m_inner->second - this->m_inner->first; + if (this->offset() == 0) { + this->m_outer->begin = front; + } + if (this->m_inner == &this->m_outer->data.back()) { + this->m_outer->end = back; + } + this->m_outer->count += back - front; + this->m_inner->first = front; + this->m_inner->second = back; +} + +template +void MutableChunkedRangeVectorIterator::adjust(ptrdiff_t front, ptrdiff_t back) +{ + if (this->offset() == 0) { + this->m_outer->begin += front; + } + if (this->m_inner == &this->m_outer->data.back()) { + this->m_outer->end += back; + } + this->m_outer->count += -front + back; + this->m_inner->first += front; + this->m_inner->second += back; +} + +template +void MutableChunkedRangeVectorIterator::shift(ptrdiff_t distance) +{ + if (this->offset() == 0) { + this->m_outer->begin += distance; + } + if (this->m_inner == &this->m_outer->data.back()) { + this->m_outer->end += distance; + } + this->m_inner->first += distance; + this->m_inner->second += distance; +} + +void ChunkedRangeVector::push_back(value_type value) +{ + if (!empty() && m_data.back().data.size() < max_size) { + auto& range = m_data.back(); + REALM_ASSERT(range.end <= value.first); + + range.data.push_back(value); + range.count += value.second - value.first; + range.end = value.second; + } + else { + m_data.push_back({{value}, value.first, value.second, value.second - value.first}); + } + verify(); +} + +ChunkedRangeVector::iterator ChunkedRangeVector::insert(iterator pos, value_type value) +{ + if (pos.m_outer == m_data.end()) { + push_back(std::move(value)); + return std::prev(end()); + } + + pos = ensure_space(pos); + auto& chunk = *pos.m_outer; + pos.m_inner = &*chunk.data.insert(pos.m_outer->data.begin() + pos.offset(), value); + chunk.count += value.second - value.first; + chunk.begin = std::min(chunk.begin, value.first); + chunk.end = std::max(chunk.end, value.second); + + verify(); + return pos; +} + +ChunkedRangeVector::iterator ChunkedRangeVector::ensure_space(iterator pos) +{ + if (pos.m_outer->data.size() + 1 <= max_size) + return pos; + + auto offset = pos.offset(); + + // Split the chunk in half to make space for the new insertion + auto new_pos = m_data.insert(pos.m_outer + 1, Chunk{}); + auto prev = new_pos - 1; + auto to_move = max_size / 2; + new_pos->data.reserve(to_move); + new_pos->data.assign(prev->data.end() - to_move, prev->data.end()); + prev->data.resize(prev->data.size() - to_move); + + size_t moved_count = 0; + for (auto range : new_pos->data) + moved_count += range.second - range.first; + + prev->end = prev->data.back().second; + prev->count -= moved_count; + new_pos->begin = new_pos->data.front().first; + new_pos->end = new_pos->data.back().second; + new_pos->count = moved_count; + + if (offset >= to_move) { + pos.m_outer = new_pos; + offset -= to_move; + } + else { + pos.m_outer = prev; + } + pos.m_end = m_data.end(); + pos.m_inner = &pos.m_outer->data[offset]; + verify(); + return pos; +} + +ChunkedRangeVector::iterator ChunkedRangeVector::erase(iterator pos) noexcept +{ + auto offset = pos.offset(); + auto& chunk = *pos.m_outer; + chunk.count -= pos->second - pos->first; + chunk.data.erase(chunk.data.begin() + offset); + + if (chunk.data.size() == 0) { + pos.m_outer = m_data.erase(pos.m_outer); + pos.m_end = m_data.end(); + pos.m_inner = pos.m_outer == m_data.end() ? nullptr : &pos.m_outer->data.front(); + verify(); + return pos; + } + + chunk.begin = chunk.data.front().first; + chunk.end = chunk.data.back().second; + if (offset < chunk.data.size()) + pos.m_inner = &chunk.data[offset]; + else { + ++pos.m_outer; + pos.m_inner = pos.m_outer == pos.m_end ? nullptr : &pos.m_outer->data.front(); + } + + verify(); + return pos; +} + +void ChunkedRangeVector::verify() const noexcept +{ +#ifdef REALM_DEBUG + size_t prev_end = -1; + for (auto range : *this) { + REALM_ASSERT(range.first < range.second); + REALM_ASSERT(prev_end == size_t(-1) || range.first > prev_end); + prev_end = range.second; + } + + for (auto& chunk : m_data) { + REALM_ASSERT(!chunk.data.empty()); + REALM_ASSERT(chunk.data.front().first == chunk.begin); + REALM_ASSERT(chunk.data.back().second == chunk.end); + REALM_ASSERT(chunk.count <= chunk.end - chunk.begin); + size_t count = 0; + for (auto range : chunk.data) + count += range.second - range.first; + REALM_ASSERT(count == chunk.count); + } +#endif +} + +namespace { +class ChunkedRangeVectorBuilder { +public: + using value_type = std::pair; + + ChunkedRangeVectorBuilder(ChunkedRangeVector const& expected); + void push_back(size_t index); + void push_back(std::pair range); + std::vector finalize(); +private: + std::vector m_data; + size_t m_outer_pos = 0; +}; + +ChunkedRangeVectorBuilder::ChunkedRangeVectorBuilder(ChunkedRangeVector const& expected) +{ + size_t size = 0; + for (auto const& chunk : expected.m_data) + size += chunk.data.size(); + m_data.resize(size / ChunkedRangeVector::max_size + 1); + for (size_t i = 0; i < m_data.size() - 1; ++i) + m_data[i].data.reserve(ChunkedRangeVector::max_size); +} + +void ChunkedRangeVectorBuilder::push_back(size_t index) +{ + push_back({index, index + 1}); +} + +void ChunkedRangeVectorBuilder::push_back(std::pair range) +{ + auto& chunk = m_data[m_outer_pos]; + if (chunk.data.empty()) { + chunk.data.push_back(range); + chunk.count = range.second - range.first; + chunk.begin = range.first; + } + else if (range.first == chunk.data.back().second) { + chunk.data.back().second = range.second; + chunk.count += range.second - range.first; + } + else if (chunk.data.size() < ChunkedRangeVector::max_size) { + chunk.data.push_back(range); + chunk.count += range.second - range.first; + } + else { + chunk.end = chunk.data.back().second; + ++m_outer_pos; + if (m_outer_pos >= m_data.size()) + m_data.push_back({{range}, range.first, 0, 1}); + else { + auto& chunk = m_data[m_outer_pos]; + chunk.data.push_back(range); + chunk.begin = range.first; + chunk.count = range.second - range.first; + } + } +} + +std::vector ChunkedRangeVectorBuilder::finalize() +{ + if (!m_data.empty()) { + m_data.resize(m_outer_pos + 1); + if (m_data.back().data.empty()) + m_data.pop_back(); + else + m_data.back().end = m_data.back().data.back().second; + } + return std::move(m_data); +} +} + +IndexSet::IndexSet(std::initializer_list values) +{ + for (size_t v : values) + add(v); +} + +bool IndexSet::contains(size_t index) const noexcept +{ + auto it = const_cast(this)->find(index); + return it != end() && it->first <= index; +} + +size_t IndexSet::count(size_t start_index, size_t end_index) const noexcept +{ + auto it = const_cast(this)->find(start_index); + const auto end = this->end(); + if (it == end || it->first >= end_index) { + return 0; + } + if (it->second >= end_index) + return std::min(it->second, end_index) - std::max(it->first, start_index); + + size_t ret = 0; + + if (start_index > it->first || it.offset() != 0) { + // Start index is in the middle of a chunk, so start by counting the + // rest of that chunk + ret = it->second - std::max(it->first, start_index); + for (++it; it != end && it->second < end_index && it.offset() != 0; ++it) { + ret += it->second - it->first; + } + if (it != end && it->first < end_index && it.offset() != 0) + ret += end_index - it->first; + if (it == end || it->second >= end_index) + return ret; + } + + // Now count all complete chunks that fall within the range + while (it != end && it.outer()->end <= end_index) { + REALM_ASSERT_DEBUG(it.offset() == 0); + ret += it.outer()->count; + it.next_chunk(); + } + + // Cound all complete ranges within the last chunk + while (it != end && it->second <= end_index) { + ret += it->second - it->first; + ++it; + } + + // And finally add in the partial last range + if (it != end && it->first < end_index) + ret += end_index - it->first; + return ret; +} + +IndexSet::iterator IndexSet::find(size_t index) noexcept +{ + return find(index, begin()); +} + +IndexSet::iterator IndexSet::find(size_t index, iterator begin) noexcept +{ + auto it = std::find_if(begin.outer(), m_data.end(), + [&](auto const& lft) { return lft.end > index; }); + if (it == m_data.end()) + return end(); + if (index < it->begin) + return iterator(it, m_data.end(), &it->data[0]); + auto inner_begin = it->data.begin(); + if (it == begin.outer()) + inner_begin += begin.offset(); + auto inner = std::lower_bound(inner_begin, it->data.end(), index, + [&](auto const& lft, auto) { return lft.second <= index; }); + REALM_ASSERT_DEBUG(inner != it->data.end()); + + return iterator(it, m_data.end(), &*inner); +} + +void IndexSet::add(size_t index) +{ + do_add(find(index), index); +} + +void IndexSet::add(IndexSet const& other) +{ + auto it = begin(); + for (size_t index : other.as_indexes()) { + it = do_add(find(index, it), index); + } +} + +size_t IndexSet::add_shifted(size_t index) +{ + iterator it = begin(), end = this->end(); + + // Shift for any complete chunks before the target + for (; it != end && it.outer()->end <= index; it.next_chunk()) + index += it.outer()->count; + + // And any ranges within the last partial chunk + for (; it != end && it->first <= index; ++it) + index += it->second - it->first; + + do_add(it, index); + return index; +} + +void IndexSet::add_shifted_by(IndexSet const& shifted_by, IndexSet const& values) +{ + if (values.empty()) + return; + +#ifdef REALM_DEBUG + size_t expected = std::distance(as_indexes().begin(), as_indexes().end()); + for (auto index : values.as_indexes()) { + if (!shifted_by.contains(index)) + ++expected; + } +#endif + + ChunkedRangeVectorBuilder builder(*this); + + auto old_it = cbegin(), old_end = cend(); + auto shift_it = shifted_by.cbegin(), shift_end = shifted_by.cend(); + + size_t skip_until = 0; + size_t old_shift = 0; + size_t new_shift = 0; + for (size_t index : values.as_indexes()) { + for (; shift_it != shift_end && shift_it->first <= index; ++shift_it) { + new_shift += shift_it->second - shift_it->first; + skip_until = shift_it->second; + } + if (index < skip_until) + continue; + + for (; old_it != old_end && old_it->first <= index - new_shift + old_shift; ++old_it) { + for (size_t i = old_it->first; i < old_it->second; ++i) + builder.push_back(i); + old_shift += old_it->second - old_it->first; + } + + REALM_ASSERT(index >= new_shift); + builder.push_back(index - new_shift + old_shift); + } + + copy(old_it, old_end, std::back_inserter(builder)); + m_data = builder.finalize(); + +#ifdef REALM_DEBUG + REALM_ASSERT((size_t)std::distance(as_indexes().begin(), as_indexes().end()) == expected); +#endif +} + +void IndexSet::set(size_t len) +{ + clear(); + if (len) { + push_back({0, len}); + } +} + +void IndexSet::insert_at(size_t index, size_t count) +{ + REALM_ASSERT(count > 0); + + auto pos = find(index); + auto end = this->end(); + bool in_existing = false; + if (pos != end) { + if (pos->first <= index) { + in_existing = true; + pos.adjust(0, count); + } + else { + pos.shift(count); + } + for (auto it = std::next(pos); it != end; ++it) + it.shift(count); + } + if (!in_existing) { + for (size_t i = 0; i < count; ++i) + pos = std::next(do_add(pos, index + i)); + } + + verify(); +} + +void IndexSet::insert_at(IndexSet const& positions) +{ + if (positions.empty()) + return; + if (empty()) { + *this = positions; + return; + } + + IndexIterator begin1 = cbegin(), begin2 = positions.cbegin(); + IndexIterator end1 = cend(), end2 = positions.cend(); + + ChunkedRangeVectorBuilder builder(*this); + size_t shift = 0; + while (begin1 != end1 && begin2 != end2) { + if (*begin1 + shift < *begin2) { + builder.push_back(*begin1++ + shift); + } + else { + ++shift; + builder.push_back(*begin2++); + } + } + for (; begin1 != end1; ++begin1) + builder.push_back(*begin1 + shift); + for (; begin2 != end2; ++begin2) + builder.push_back(*begin2); + + m_data = builder.finalize(); +} + +void IndexSet::shift_for_insert_at(size_t index, size_t count) +{ + REALM_ASSERT(count > 0); + + auto it = find(index); + if (it == end()) + return; + + for (auto pos = it, end = this->end(); pos != end; ++pos) + pos.shift(count); + + // If the range contained the insertion point, split the range and move + // the part of it before the insertion point back + if (it->first < index + count) { + auto old_second = it->second; + it.set(it->first - count, index); + insert(std::next(it), {index + count, old_second}); + } + verify(); +} + +void IndexSet::shift_for_insert_at(realm::IndexSet const& values) +{ + if (empty() || values.empty()) + return; + if (values.m_data.front().begin >= m_data.back().end) + return; + + IndexIterator begin1 = cbegin(), begin2 = values.cbegin(); + IndexIterator end1 = cend(), end2 = values.cend(); + + ChunkedRangeVectorBuilder builder(*this); + size_t shift = 0; + while (begin1 != end1 && begin2 != end2) { + if (*begin1 + shift < *begin2) { + builder.push_back(*begin1++ + shift); + } + else { + ++shift; + begin2++; + } + } + for (; begin1 != end1; ++begin1) + builder.push_back(*begin1 + shift); + + m_data = builder.finalize(); +} + +void IndexSet::erase_at(size_t index) +{ + auto it = find(index); + if (it != end()) + do_erase(it, index); +} + +void IndexSet::erase_at(IndexSet const& positions) +{ + if (empty() || positions.empty()) + return; + + ChunkedRangeVectorBuilder builder(*this); + + IndexIterator begin1 = cbegin(), begin2 = positions.cbegin(); + IndexIterator end1 = cend(), end2 = positions.cend(); + + size_t shift = 0; + while (begin1 != end1 && begin2 != end2) { + if (*begin1 < *begin2) { + builder.push_back(*begin1++ - shift); + } + else if (*begin1 == *begin2) { + ++shift; + ++begin1; + ++begin2; + } + else { + ++shift; + ++begin2; + } + } + for (; begin1 != end1; ++begin1) + builder.push_back(*begin1 - shift); + + m_data = builder.finalize(); +} + +size_t IndexSet::erase_or_unshift(size_t index) +{ + auto shifted = index; + iterator it = begin(), end = this->end(); + + // Shift for any complete chunks before the target + for (; it != end && it.outer()->end <= index; it.next_chunk()) + shifted -= it.outer()->count; + + // And any ranges within the last partial chunk + for (; it != end && it->second <= index; ++it) + shifted -= it->second - it->first; + + if (it == end) + return shifted; + + if (it->first <= index) + shifted = npos; + + do_erase(it, index); + + return shifted; +} + +void IndexSet::do_erase(iterator it, size_t index) +{ + if (it->first <= index) { + if (it->first + 1 == it->second) { + it = erase(it); + } + else { + it.adjust(0, -1); + ++it; + } + } + else if (it != begin() && std::prev(it)->second + 1 == it->first) { + std::prev(it).adjust(0, it->second - it->first); + it = erase(it); + } + + for (; it != end(); ++it) + it.shift(-1); +} + +IndexSet::iterator IndexSet::do_remove(iterator it, size_t begin, size_t end) +{ + for (it = find(begin, it); it != this->end() && it->first < end; it = find(begin, it)) { + // Trim off any part of the range to remove that's before the matching range + begin = std::max(it->first, begin); + + // If the matching range extends to both sides of the range to remove, + // split it on the range to remove + if (it->first < begin && it->second > end) { + auto old_second = it->second; + it.set(it->first, begin); + it = std::prev(insert(std::next(it), {end, old_second})); + } + // Range to delete now coverages (at least) one end of the matching range + else if (begin == it->first && end >= it->second) + it = erase(it); + else if (begin == it->first) + it.set(end, it->second); + else + it.set(it->first, begin); + } + return it; +} + +void IndexSet::remove(size_t index, size_t count) +{ + do_remove(find(index), index, index + count); +} + +void IndexSet::remove(realm::IndexSet const& values) +{ + auto it = begin(); + for (auto range : values) { + it = do_remove(it, range.first, range.second); + if (it == end()) + return; + } +} + +size_t IndexSet::shift(size_t index) const noexcept +{ + // FIXME: optimize + for (auto range : *this) { + if (range.first > index) + break; + index += range.second - range.first; + } + return index; +} + +size_t IndexSet::unshift(size_t index) const noexcept +{ + REALM_ASSERT_DEBUG(!contains(index)); + return index - count(0, index); +} + +void IndexSet::clear() noexcept +{ + m_data.clear(); +} + +IndexSet::iterator IndexSet::do_add(iterator it, size_t index) +{ + verify(); + bool more_before = it != begin(), valid = it != end(); + REALM_ASSERT(!more_before || index >= std::prev(it)->second); + if (valid && it->first <= index && it->second > index) { + // index is already in set + return it; + } + if (more_before && std::prev(it)->second == index) { + auto prev = std::prev(it); + // index is immediately after an existing range + prev.adjust(0, 1); + + if (valid && prev->second == it->first) { + // index joins two existing ranges + prev.adjust(0, it->second - it->first); + return std::prev(erase(it)); + } + return prev; + } + if (valid && it->first == index + 1) { + // index is immediately before an existing range + it.adjust(-1, 0); + return it; + } + + // index is not next to an existing range + return insert(it, {index, index + 1}); +} diff --git a/Pods/Realm/Realm/ObjectStore/src/list.cpp b/Pods/Realm/Realm/ObjectStore/src/list.cpp new file mode 100644 index 0000000000..12b4082d61 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/list.cpp @@ -0,0 +1,468 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "list.hpp" + +#include "impl/list_notifier.hpp" +#include "impl/primitive_list_notifier.hpp" +#include "impl/realm_coordinator.hpp" +#include "object_schema.hpp" +#include "object_store.hpp" +#include "results.hpp" +#include "schema.hpp" +#include "shared_realm.hpp" + +#include + +namespace realm { +using namespace realm::_impl; + +List::List() noexcept = default; +List::~List() = default; + +List::List(const List&) = default; +List& List::operator=(const List&) = default; +List::List(List&&) = default; +List& List::operator=(List&&) = default; + +List::List(std::shared_ptr r, Table& parent_table, size_t col, size_t row) +: m_realm(std::move(r)) +{ + auto type = parent_table.get_column_type(col); + REALM_ASSERT(type == type_LinkList || type == type_Table); + if (type == type_LinkList) { + m_link_view = parent_table.get_linklist(col, row); + m_table.reset(&m_link_view->get_target_table()); + } + else { + m_table = parent_table.get_subtable(col, row); + } +} + +List::List(std::shared_ptr r, LinkViewRef l) noexcept +: m_realm(std::move(r)) +, m_link_view(std::move(l)) +{ + m_table.reset(&m_link_view->get_target_table()); +} + +List::List(std::shared_ptr r, TableRef t) noexcept +: m_realm(std::move(r)) +, m_table(std::move(t)) +{ +} + +static StringData object_name(Table const& table) +{ + return ObjectStore::object_type_for_table_name(table.get_name()); +} + +ObjectSchema const& List::get_object_schema() const +{ + verify_attached(); + REALM_ASSERT(m_link_view); + + if (!m_object_schema) { + REALM_ASSERT(get_type() == PropertyType::Object); + auto object_type = object_name(m_link_view->get_target_table()); + auto it = m_realm->schema().find(object_type); + REALM_ASSERT(it != m_realm->schema().end()); + m_object_schema = &*it; + } + return *m_object_schema; +} + +Query List::get_query() const +{ + verify_attached(); + return m_link_view ? m_table->where(m_link_view) : m_table->where(); +} + +size_t List::get_origin_row_index() const +{ + verify_attached(); + return m_link_view ? m_link_view->get_origin_row_index() : m_table->get_parent_row_index(); +} + +void List::verify_valid_row(size_t row_ndx, bool insertion) const +{ + size_t s = size(); + if (row_ndx > s || (!insertion && row_ndx == s)) { + throw OutOfBoundsIndexException{row_ndx, s + insertion}; + } +} + +void List::validate(RowExpr row) const +{ + if (!row.is_attached()) + throw std::invalid_argument("Object has been deleted or invalidated"); + if (row.get_table() != &m_link_view->get_target_table()) + throw std::invalid_argument(util::format("Object of type (%1) does not match List type (%2)", + object_name(*row.get_table()), + object_name(m_link_view->get_target_table()))); +} + +bool List::is_valid() const +{ + if (!m_realm) + return false; + m_realm->verify_thread(); + if (m_link_view) + return m_link_view->is_attached(); + return m_table && m_table->is_attached(); +} + +void List::verify_attached() const +{ + if (!is_valid()) { + throw InvalidatedException(); + } +} + +void List::verify_in_transaction() const +{ + verify_attached(); + m_realm->verify_in_write(); +} + +size_t List::size() const +{ + verify_attached(); + return m_link_view ? m_link_view->size() : m_table->size(); +} + +size_t List::to_table_ndx(size_t row) const noexcept +{ + return m_link_view ? m_link_view->get(row).get_index() : row; +} + +PropertyType List::get_type() const +{ + verify_attached(); + return m_link_view ? PropertyType::Object + : ObjectSchema::from_core_type(*m_table->get_descriptor(), 0); +} + +namespace { +template +auto get(Table& table, size_t row) +{ + return table.get(0, row); +} + +template<> +auto get(Table& table, size_t row) +{ + return table.get(row); +} +} + +template +T List::get(size_t row_ndx) const +{ + verify_valid_row(row_ndx); + return realm::get(*m_table, to_table_ndx(row_ndx)); +} + +template RowExpr List::get(size_t) const; + +template +size_t List::find(T const& value) const +{ + verify_attached(); + return m_table->find_first(0, value); +} + +template<> +size_t List::find(RowExpr const& row) const +{ + verify_attached(); + if (!row.is_attached()) + return not_found; + validate(row); + + return m_link_view ? m_link_view->find(row.get_index()) : row.get_index(); +} + +size_t List::find(Query&& q) const +{ + verify_attached(); + if (m_link_view) { + size_t index = get_query().and_query(std::move(q)).find(); + return index == not_found ? index : m_link_view->find(index); + } + return q.find(); +} + +template +void List::add(T value) +{ + verify_in_transaction(); + m_table->set(0, m_table->add_empty_row(), value); +} + +template<> +void List::add(size_t target_row_ndx) +{ + verify_in_transaction(); + m_link_view->add(target_row_ndx); +} + +template<> +void List::add(RowExpr row) +{ + validate(row); + add(row.get_index()); +} + +template<> +void List::add(int value) +{ + verify_in_transaction(); + if (m_link_view) + add(static_cast(value)); + else + add(static_cast(value)); +} + +template +void List::insert(size_t row_ndx, T value) +{ + verify_in_transaction(); + verify_valid_row(row_ndx, true); + m_table->insert_empty_row(row_ndx); + m_table->set(0, row_ndx, value); +} + +template<> +void List::insert(size_t row_ndx, size_t target_row_ndx) +{ + verify_in_transaction(); + verify_valid_row(row_ndx, true); + m_link_view->insert(row_ndx, target_row_ndx); +} + +template<> +void List::insert(size_t row_ndx, RowExpr row) +{ + validate(row); + insert(row_ndx, row.get_index()); +} + +void List::move(size_t source_ndx, size_t dest_ndx) +{ + verify_in_transaction(); + verify_valid_row(source_ndx); + verify_valid_row(dest_ndx); // Can't be one past end due to removing one earlier + if (source_ndx == dest_ndx) + return; + + if (m_link_view) + m_link_view->move(source_ndx, dest_ndx); + else + m_table->move_row(source_ndx, dest_ndx); +} + +void List::remove(size_t row_ndx) +{ + verify_in_transaction(); + verify_valid_row(row_ndx); + if (m_link_view) + m_link_view->remove(row_ndx); + else + m_table->remove(row_ndx); +} + +void List::remove_all() +{ + verify_in_transaction(); + if (m_link_view) + m_link_view->clear(); + else + m_table->clear(); +} + +template +void List::set(size_t row_ndx, T value) +{ + verify_in_transaction(); + verify_valid_row(row_ndx); + m_table->set(0, row_ndx, value); +} + +template<> +void List::set(size_t row_ndx, size_t target_row_ndx) +{ + verify_in_transaction(); + verify_valid_row(row_ndx); + m_link_view->set(row_ndx, target_row_ndx); +} + +template<> +void List::set(size_t row_ndx, RowExpr row) +{ + validate(row); + set(row_ndx, row.get_index()); +} + +void List::swap(size_t ndx1, size_t ndx2) +{ + verify_in_transaction(); + verify_valid_row(ndx1); + verify_valid_row(ndx2); + if (m_link_view) + m_link_view->swap(ndx1, ndx2); + else + m_table->swap_rows(ndx1, ndx2); +} + +void List::delete_at(size_t row_ndx) +{ + verify_in_transaction(); + verify_valid_row(row_ndx); + if (m_link_view) + m_link_view->remove_target_row(row_ndx); + else + m_table->remove(row_ndx); +} + +void List::delete_all() +{ + verify_in_transaction(); + if (m_link_view) + m_link_view->remove_all_target_rows(); + else + m_table->clear(); +} + +Results List::sort(SortDescriptor order) const +{ + verify_attached(); + if (m_link_view) + return Results(m_realm, m_link_view, util::none, std::move(order)); + + DescriptorOrdering new_order; + new_order.append_sort(std::move(order)); + return Results(m_realm, get_query(), std::move(new_order)); +} + +Results List::sort(std::vector> const& keypaths) const +{ + return as_results().sort(keypaths); +} + +Results List::filter(Query q) const +{ + verify_attached(); + if (m_link_view) + return Results(m_realm, m_link_view, get_query().and_query(std::move(q))); + return Results(m_realm, get_query().and_query(std::move(q))); +} + +Results List::as_results() const +{ + verify_attached(); + return m_link_view ? Results(m_realm, m_link_view) : Results(m_realm, *m_table); +} + +Results List::snapshot() const +{ + return as_results().snapshot(); +} + +util::Optional List::max(size_t column) +{ + return as_results().max(column); +} + +util::Optional List::min(size_t column) +{ + return as_results().min(column); +} + +Mixed List::sum(size_t column) +{ + // Results::sum() returns none only for Mode::Empty Results, so we can + // safely ignore that possibility here + return *as_results().sum(column); +} + +util::Optional List::average(size_t column) +{ + return as_results().average(column); +} + +// These definitions rely on that LinkViews and Tables are interned by core +bool List::operator==(List const& rgt) const noexcept +{ + return m_link_view == rgt.m_link_view && m_table.get() == rgt.m_table.get(); +} + +NotificationToken List::add_notification_callback(CollectionChangeCallback cb) & +{ + verify_attached(); + // Adding a new callback to a notifier which had all of its callbacks + // removed does not properly reinitialize the notifier. Work around this by + // recreating it instead. + // FIXME: The notifier lifecycle here is dumb (when all callbacks are removed + // from a notifier a zombie is left sitting around uselessly) and should be + // cleaned up. + if (m_notifier && !m_notifier->have_callbacks()) + m_notifier.reset(); + if (!m_notifier) { + if (get_type() == PropertyType::Object) + m_notifier = std::static_pointer_cast<_impl::CollectionNotifier>(std::make_shared(m_link_view, m_realm)); + else + m_notifier = std::static_pointer_cast<_impl::CollectionNotifier>(std::make_shared(m_table, m_realm)); + RealmCoordinator::register_notifier(m_notifier); + } + return {m_notifier, m_notifier->add_callback(std::move(cb))}; +} + +List::OutOfBoundsIndexException::OutOfBoundsIndexException(size_t r, size_t c) +: std::out_of_range(util::format("Requested index %1 greater than max %2", r, c - 1)) +, requested(r), valid_count(c) {} + +#define REALM_PRIMITIVE_LIST_TYPE(T) \ + template T List::get(size_t) const; \ + template size_t List::find(T const&) const; \ + template void List::add(T); \ + template void List::insert(size_t, T); \ + template void List::set(size_t, T); + +REALM_PRIMITIVE_LIST_TYPE(bool) +REALM_PRIMITIVE_LIST_TYPE(int64_t) +REALM_PRIMITIVE_LIST_TYPE(float) +REALM_PRIMITIVE_LIST_TYPE(double) +REALM_PRIMITIVE_LIST_TYPE(StringData) +REALM_PRIMITIVE_LIST_TYPE(BinaryData) +REALM_PRIMITIVE_LIST_TYPE(Timestamp) +REALM_PRIMITIVE_LIST_TYPE(util::Optional) +REALM_PRIMITIVE_LIST_TYPE(util::Optional) +REALM_PRIMITIVE_LIST_TYPE(util::Optional) +REALM_PRIMITIVE_LIST_TYPE(util::Optional) + +#undef REALM_PRIMITIVE_LIST_TYPE +} // namespace realm + +namespace std { +size_t hash::operator()(realm::List const& list) const +{ + return std::hash()(list.m_link_view ? list.m_link_view.get() : (void*)list.m_table.get()); +} +} diff --git a/Pods/Realm/Realm/ObjectStore/src/object.cpp b/Pods/Realm/Realm/ObjectStore/src/object.cpp new file mode 100644 index 0000000000..7fd6c745bd --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/object.cpp @@ -0,0 +1,116 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "object.hpp" + +#include "impl/object_notifier.hpp" +#include "impl/realm_coordinator.hpp" +#include "object_schema.hpp" +#include "object_store.hpp" + +using namespace realm; + +InvalidatedObjectException::InvalidatedObjectException(const std::string& object_type) +: std::logic_error("Accessing object of type " + object_type + " which has been invalidated or deleted") +, object_type(object_type) +{} + +InvalidPropertyException::InvalidPropertyException(const std::string& object_type, const std::string& property_name) +: std::logic_error(util::format("Property '%1.%2' does not exist", object_type, property_name)) +, object_type(object_type), property_name(property_name) +{} + +MissingPropertyValueException::MissingPropertyValueException(const std::string& object_type, const std::string& property_name) +: std::logic_error(util::format("Missing value for property '%1.%2'", object_type, property_name)) +, object_type(object_type), property_name(property_name) +{} + +MissingPrimaryKeyException::MissingPrimaryKeyException(const std::string& object_type) +: std::logic_error(util::format("'%1' does not have a primary key defined", object_type)) +, object_type(object_type) +{} + +ReadOnlyPropertyException::ReadOnlyPropertyException(const std::string& object_type, const std::string& property_name) +: std::logic_error(util::format("Cannot modify read-only property '%1.%2'", object_type, property_name)) +, object_type(object_type), property_name(property_name) {} + +Object::Object(SharedRealm r, ObjectSchema const& s, RowExpr const& o) +: m_realm(std::move(r)), m_object_schema(&s), m_row(o) { } + +Object::Object(SharedRealm r, StringData object_type, size_t ndx) +: m_realm(std::move(r)) +, m_object_schema(&*m_realm->schema().find(object_type)) +, m_row(ObjectStore::table_for_object_type(m_realm->read_group(), object_type)->get(ndx)) +{ } + +Object::Object() = default; +Object::~Object() = default; +Object::Object(Object const&) = default; +Object::Object(Object&&) = default; +Object& Object::operator=(Object const&) = default; +Object& Object::operator=(Object&&) = default; + +NotificationToken Object::add_notification_callback(CollectionChangeCallback callback) & +{ + verify_attached(); + if (!m_notifier) { + m_notifier = std::make_shared<_impl::ObjectNotifier>(m_row, m_realm); + _impl::RealmCoordinator::register_notifier(m_notifier); + } + return {m_notifier, m_notifier->add_callback(std::move(callback))}; +} + +void Object::verify_attached() const +{ + m_realm->verify_thread(); + if (!m_row.is_attached()) { + throw InvalidatedObjectException(m_object_schema->name); + } +} + +Property const& Object::property_for_name(StringData prop_name) const +{ + auto prop = m_object_schema->property_for_name(prop_name); + if (!prop) { + throw InvalidPropertyException(m_object_schema->name, prop_name); + } + return *prop; +} + +#if REALM_ENABLE_SYNC +void Object::ensure_user_in_everyone_role() +{ + auto role_table = m_realm->read_group().get_table("class___Role"); + if (!role_table) + return; + size_t ndx = role_table->find_first_string(role_table->get_column_index("name"), "everyone"); + if (ndx == npos) + return; + auto users = role_table->get_linklist(role_table->get_column_index("members"), ndx); + if (users->find(m_row.get_index()) != not_found) + return; + + users->add(m_row.get_index()); +} + +void Object::ensure_private_role_exists_for_user() +{ + auto user_id = m_row.get(m_row.get_table()->get_column_index("id")); + ObjectStore::ensure_private_role_exists_for_user(m_realm->read_group(), user_id); +} +#endif diff --git a/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp b/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp new file mode 100644 index 0000000000..e5082fb0d7 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp @@ -0,0 +1,237 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "object_schema.hpp" + +#include "feature_checks.hpp" +#include "object_store.hpp" +#include "property.hpp" +#include "schema.hpp" + + +#include +#include +#include +#include + +using namespace realm; + +ObjectSchema::ObjectSchema() = default; +ObjectSchema::~ObjectSchema() = default; + +ObjectSchema::ObjectSchema(std::string name, std::initializer_list persisted_properties) +: ObjectSchema(std::move(name), persisted_properties, {}) +{ +} + +ObjectSchema::ObjectSchema(std::string name, std::initializer_list persisted_properties, + std::initializer_list computed_properties) +: name(std::move(name)) +, persisted_properties(persisted_properties) +, computed_properties(computed_properties) +{ + for (auto const& prop : persisted_properties) { + if (prop.is_primary) { + primary_key = prop.name; + break; + } + } +} + +PropertyType ObjectSchema::from_core_type(Descriptor const& table, size_t col) +{ + auto optional = table.is_nullable(col) ? PropertyType::Nullable : PropertyType::Required; + switch (table.get_column_type(col)) { + case type_Int: return PropertyType::Int | optional; + case type_Float: return PropertyType::Float | optional; + case type_Double: return PropertyType::Double | optional; + case type_Bool: return PropertyType::Bool | optional; + case type_String: return PropertyType::String | optional; + case type_Binary: return PropertyType::Data | optional; + case type_Timestamp: return PropertyType::Date | optional; + case type_Mixed: return PropertyType::Any | optional; + case type_Link: return PropertyType::Object | PropertyType::Nullable; + case type_LinkList: return PropertyType::Object | PropertyType::Array; + case type_Table: return from_core_type(*table.get_subdescriptor(col), 0) | PropertyType::Array; + default: REALM_UNREACHABLE(); + } +} + +ObjectSchema::ObjectSchema(Group const& group, StringData name, size_t index) : name(name) { + ConstTableRef table; + if (index < group.size()) { + table = group.get_table(index); + } + else { + table = ObjectStore::table_for_object_type(group, name); + } + + size_t count = table->get_column_count(); + persisted_properties.reserve(count); + for (size_t col = 0; col < count; col++) { + if (auto property = ObjectStore::property_for_column_index(table, col)) { + persisted_properties.push_back(std::move(property.value())); + } + } + + primary_key = realm::ObjectStore::get_primary_key_for_object(group, name); + set_primary_key_property(); +} + +Property *ObjectSchema::property_for_name(StringData name) { + for (auto& prop : persisted_properties) { + if (StringData(prop.name) == name) { + return ∝ + } + } + for (auto& prop : computed_properties) { + if (StringData(prop.name) == name) { + return ∝ + } + } + return nullptr; +} + +const Property *ObjectSchema::property_for_name(StringData name) const { + return const_cast(this)->property_for_name(name); +} + +bool ObjectSchema::property_is_computed(Property const& property) const { + auto end = computed_properties.end(); + return std::find(computed_properties.begin(), end, property) != end; +} + +void ObjectSchema::set_primary_key_property() +{ + if (primary_key.length()) { + if (auto primary_key_prop = primary_key_property()) { + primary_key_prop->is_primary = true; + } + } +} + +static void validate_property(Schema const& schema, + std::string const& object_name, + Property const& prop, + Property const** primary, + std::vector& exceptions) +{ + if (prop.type == PropertyType::LinkingObjects && !is_array(prop.type)) { + exceptions.emplace_back("Linking Objects property '%1.%2' must be an array.", + object_name, prop.name); + } + + // check nullablity + if (is_nullable(prop.type) && !prop.type_is_nullable()) { + exceptions.emplace_back("Property '%1.%2' of type '%3' cannot be nullable.", + object_name, prop.name, string_for_property_type(prop.type)); + } + else if (prop.type == PropertyType::Object && !is_nullable(prop.type) && !is_array(prop.type)) { + exceptions.emplace_back("Property '%1.%2' of type 'object' must be nullable.", object_name, prop.name); + } + + // check primary keys + if (prop.is_primary) { + if (prop.type != PropertyType::Int && prop.type != PropertyType::String) { + exceptions.emplace_back("Property '%1.%2' of type '%3' cannot be made the primary key.", + object_name, prop.name, string_for_property_type(prop.type)); + } + if (*primary) { + exceptions.emplace_back("Properties '%1' and '%2' are both marked as the primary key of '%3'.", + prop.name, (*primary)->name, object_name); + } + *primary = ∝ + } + + // check indexable + if (prop.is_indexed && !prop.type_is_indexable()) { + exceptions.emplace_back("Property '%1.%2' of type '%3' cannot be indexed.", + object_name, prop.name, string_for_property_type(prop.type)); + } + + // check that only link properties have object types + if (prop.type != PropertyType::LinkingObjects && !prop.link_origin_property_name.empty()) { + exceptions.emplace_back("Property '%1.%2' of type '%3' cannot have an origin property name.", + object_name, prop.name, string_for_property_type(prop.type)); + } + else if (prop.type == PropertyType::LinkingObjects && prop.link_origin_property_name.empty()) { + exceptions.emplace_back("Property '%1.%2' of type '%3' must have an origin property name.", + object_name, prop.name, string_for_property_type(prop.type)); + } + + if (prop.type != PropertyType::Object && prop.type != PropertyType::LinkingObjects) { + if (!prop.object_type.empty()) { + exceptions.emplace_back("Property '%1.%2' of type '%3' cannot have an object type.", + object_name, prop.name, prop.type_string()); + } + return; + } + + + // check that the object_type is valid for link properties + auto it = schema.find(prop.object_type); + if (it == schema.end()) { + exceptions.emplace_back("Property '%1.%2' of type '%3' has unknown object type '%4'", + object_name, prop.name, string_for_property_type(prop.type), prop.object_type); + return; + } + if (prop.type != PropertyType::LinkingObjects) { + return; + } + + const Property *origin_property = it->property_for_name(prop.link_origin_property_name); + if (!origin_property) { + exceptions.emplace_back("Property '%1.%2' declared as origin of linking objects property '%3.%4' does not exist", + prop.object_type, prop.link_origin_property_name, + object_name, prop.name); + } + else if (origin_property->type != PropertyType::Object) { + exceptions.emplace_back("Property '%1.%2' declared as origin of linking objects property '%3.%4' is not a link", + prop.object_type, prop.link_origin_property_name, + object_name, prop.name); + } + else if (origin_property->object_type != object_name) { + exceptions.emplace_back("Property '%1.%2' declared as origin of linking objects property '%3.%4' links to type '%5'", + prop.object_type, prop.link_origin_property_name, + object_name, prop.name, origin_property->object_type); + } +} + +void ObjectSchema::validate(Schema const& schema, std::vector& exceptions) const +{ + const Property *primary = nullptr; + for (auto const& prop : persisted_properties) { + validate_property(schema, name, prop, &primary, exceptions); + } + for (auto const& prop : computed_properties) { + validate_property(schema, name, prop, &primary, exceptions); + } + + if (!primary_key.empty() && !primary && !primary_key_property()) { + exceptions.emplace_back("Specified primary key '%1.%2' does not exist.", name, primary_key); + } +} + +namespace realm { +bool operator==(ObjectSchema const& a, ObjectSchema const& b) +{ + return std::tie(a.name, a.primary_key, a.persisted_properties, a.computed_properties) + == std::tie(b.name, b.primary_key, b.persisted_properties, b.computed_properties); + +} +} diff --git a/Pods/Realm/Realm/ObjectStore/src/object_store.cpp b/Pods/Realm/Realm/ObjectStore/src/object_store.cpp new file mode 100644 index 0000000000..dde618a463 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/object_store.cpp @@ -0,0 +1,1051 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "object_store.hpp" + +#include "feature_checks.hpp" +#include "object_schema.hpp" +#include "schema.hpp" +#include "shared_realm.hpp" +#include "sync/partial_sync.hpp" + +#include +#include +#include +#include +#include + +#if REALM_ENABLE_SYNC +#include +#include +#include +#endif // REALM_ENABLE_SYNC + +#include + +using namespace realm; + +constexpr uint64_t ObjectStore::NotVersioned; + +namespace { +const char * const c_metadataTableName = "metadata"; +const char * const c_versionColumnName = "version"; +const size_t c_versionColumnIndex = 0; + +const char * const c_primaryKeyTableName = "pk"; +const char * const c_primaryKeyObjectClassColumnName = "pk_table"; +const size_t c_primaryKeyObjectClassColumnIndex = 0; +const char * const c_primaryKeyPropertyNameColumnName = "pk_property"; +const size_t c_primaryKeyPropertyNameColumnIndex = 1; + +const size_t c_zeroRowIndex = 0; + +const char c_object_table_prefix[] = "class_"; + +void create_metadata_tables(Group& group, bool partial_realm) { + // The tables 'pk' and 'metadata' are treated specially by Sync. The 'pk' table + // is populated by `sync::create_table` and friends, while the 'metadata' table + // is simply ignored. + TableRef pk_table = group.get_or_add_table(c_primaryKeyTableName); + TableRef metadata_table = group.get_or_add_table(c_metadataTableName); + + if (metadata_table->get_column_count() == 0) { + metadata_table->insert_column(c_versionColumnIndex, type_Int, c_versionColumnName); + metadata_table->add_empty_row(); + // set initial version + metadata_table->set_int(c_versionColumnIndex, c_zeroRowIndex, ObjectStore::NotVersioned); + } + + if (pk_table->get_column_count() == 0) { + pk_table->insert_column(c_primaryKeyObjectClassColumnIndex, type_String, c_primaryKeyObjectClassColumnName); + pk_table->insert_column(c_primaryKeyPropertyNameColumnIndex, type_String, c_primaryKeyPropertyNameColumnName); + } + pk_table->add_search_index(c_primaryKeyObjectClassColumnIndex); + +#if REALM_ENABLE_SYNC + // Only add __ResultSets if Realm is a partial Realm + if (partial_realm) + _impl::initialize_schema(group); +#else + (void)partial_realm; +#endif +} + +void set_schema_version(Group& group, uint64_t version) { + TableRef table = group.get_table(c_metadataTableName); + table->set_int(c_versionColumnIndex, c_zeroRowIndex, version); +} + +template +auto table_for_object_schema(Group& group, ObjectSchema const& object_schema) +{ + return ObjectStore::table_for_object_type(group, object_schema.name); +} + +DataType to_core_type(PropertyType type) +{ + REALM_ASSERT(type != PropertyType::Object); // Link columns have to be handled differently + REALM_ASSERT(type != PropertyType::Any); // Mixed columns can't be created + switch (type & ~PropertyType::Flags) { + case PropertyType::Int: return type_Int; + case PropertyType::Bool: return type_Bool; + case PropertyType::Float: return type_Float; + case PropertyType::Double: return type_Double; + case PropertyType::String: return type_String; + case PropertyType::Date: return type_Timestamp; + case PropertyType::Data: return type_Binary; + default: REALM_COMPILER_HINT_UNREACHABLE(); + } +} + +void insert_column(Group& group, Table& table, Property const& property, size_t col_ndx) +{ + // Cannot directly insert a LinkingObjects column (a computed property). + // LinkingObjects must be an artifact of an existing link column. + REALM_ASSERT(property.type != PropertyType::LinkingObjects); + + if (property.type == PropertyType::Object) { + auto target_name = ObjectStore::table_name_for_object_type(property.object_type); + TableRef link_table = group.get_table(target_name); + REALM_ASSERT(link_table); + table.insert_column_link(col_ndx, is_array(property.type) ? type_LinkList : type_Link, + property.name, *link_table); + } + else if (is_array(property.type)) { + DescriptorRef desc; + table.insert_column(col_ndx, type_Table, property.name, &desc); + desc->add_column(to_core_type(property.type & ~PropertyType::Flags), ObjectStore::ArrayColumnName, + nullptr, is_nullable(property.type)); + } + else { + table.insert_column(col_ndx, to_core_type(property.type), property.name, is_nullable(property.type)); + if (property.requires_index()) + table.add_search_index(col_ndx); + } +} + +void add_column(Group& group, Table& table, Property const& property) +{ + insert_column(group, table, property, table.get_column_count()); +} + +void replace_column(Group& group, Table& table, Property const& old_property, Property const& new_property) +{ + insert_column(group, table, new_property, old_property.table_column); + table.remove_column(old_property.table_column + 1); +} + +TableRef create_table(Group& group, ObjectSchema const& object_schema) +{ + auto name = ObjectStore::table_name_for_object_type(object_schema.name); + + TableRef table; +#if REALM_ENABLE_SYNC + if (auto* pk_property = object_schema.primary_key_property()) { + table = sync::create_table_with_primary_key(group, name, to_core_type(pk_property->type), + pk_property->name, is_nullable(pk_property->type)); + } + else { + table = sync::create_table(group, name); + } +#else + table = group.get_or_add_table(name); + ObjectStore::set_primary_key_for_object(group, object_schema.name, object_schema.primary_key); +#endif // REALM_ENABLE_SYNC + + return table; +} + +void add_initial_columns(Group& group, ObjectSchema const& object_schema) +{ + auto name = ObjectStore::table_name_for_object_type(object_schema.name); + TableRef table = group.get_table(name); + + for (auto const& prop : object_schema.persisted_properties) { +#if REALM_ENABLE_SYNC + // The sync::create_table* functions create the PK column for us. + if (prop.is_primary) + continue; +#endif // REALM_ENABLE_SYNC + add_column(group, *table, prop); + } +} + +void copy_property_values(Property const& prop, Table& table) +{ + auto copy_property_values = [&](auto getter, auto setter) { + for (size_t i = 0, count = table.size(); i < count; i++) { + bool is_default = false; + (table.*setter)(prop.table_column, i, (table.*getter)(prop.table_column + 1, i), + is_default); + } + }; + + switch (prop.type & ~PropertyType::Flags) { + case PropertyType::Int: + copy_property_values(&Table::get_int, &Table::set_int); + break; + case PropertyType::Bool: + copy_property_values(&Table::get_bool, &Table::set_bool); + break; + case PropertyType::Float: + copy_property_values(&Table::get_float, &Table::set_float); + break; + case PropertyType::Double: + copy_property_values(&Table::get_double, &Table::set_double); + break; + case PropertyType::String: + copy_property_values(&Table::get_string, &Table::set_string); + break; + case PropertyType::Data: + copy_property_values(&Table::get_binary, &Table::set_binary); + break; + case PropertyType::Date: + copy_property_values(&Table::get_timestamp, &Table::set_timestamp); + break; + default: + break; + } +} + +void make_property_optional(Group& group, Table& table, Property property) +{ + property.type |= PropertyType::Nullable; + insert_column(group, table, property, property.table_column); + copy_property_values(property, table); + table.remove_column(property.table_column + 1); +} + +void make_property_required(Group& group, Table& table, Property property) +{ + property.type &= ~PropertyType::Nullable; + insert_column(group, table, property, property.table_column); + table.remove_column(property.table_column + 1); +} + +void validate_primary_column_uniqueness(Group const& group, StringData object_type, StringData primary_property) +{ + auto table = ObjectStore::table_for_object_type(group, object_type); + if (table->get_distinct_view(table->get_column_index(primary_property)).size() != table->size()) { + throw DuplicatePrimaryKeyValueException(object_type, primary_property); + } +} + +void validate_primary_column_uniqueness(Group const& group) +{ + auto pk_table = group.get_table(c_primaryKeyTableName); + for (size_t i = 0, count = pk_table->size(); i < count; ++i) { + validate_primary_column_uniqueness(group, + pk_table->get_string(c_primaryKeyObjectClassColumnIndex, i), + pk_table->get_string(c_primaryKeyPropertyNameColumnIndex, i)); + } +} +} // anonymous namespace + +void ObjectStore::set_schema_version(Group& group, uint64_t version) { + ::create_metadata_tables(group, false); + ::set_schema_version(group, version); +} + +uint64_t ObjectStore::get_schema_version(Group const& group) { + ConstTableRef table = group.get_table(c_metadataTableName); + if (!table || table->get_column_count() == 0) { + return ObjectStore::NotVersioned; + } + return table->get_int(c_versionColumnIndex, c_zeroRowIndex); +} + +StringData ObjectStore::get_primary_key_for_object(Group const& group, StringData object_type) { + ConstTableRef table = group.get_table(c_primaryKeyTableName); + if (!table) { + return ""; + } + size_t row = table->find_first_string(c_primaryKeyObjectClassColumnIndex, object_type); + if (row == not_found) { + return ""; + } + return table->get_string(c_primaryKeyPropertyNameColumnIndex, row); +} + +void ObjectStore::set_primary_key_for_object(Group& group, StringData object_type, StringData primary_key) { + TableRef table = group.get_table(c_primaryKeyTableName); + + size_t row = table->find_first_string(c_primaryKeyObjectClassColumnIndex, object_type); + +#if REALM_ENABLE_SYNC + // sync::create_table* functions should have already updated the pk table. + if (sync::has_object_ids(group)) { + if (primary_key.size() == 0) + REALM_ASSERT(row == not_found); + else { + REALM_ASSERT(row != not_found); + REALM_ASSERT(table->get_string(c_primaryKeyPropertyNameColumnIndex, row) == primary_key); + } + return; + } +#endif // REALM_ENABLE_SYNC + + if (row == not_found && primary_key.size()) { + row = table->add_empty_row(); + table->set_string_unique(c_primaryKeyObjectClassColumnIndex, row, object_type); + table->set_string(c_primaryKeyPropertyNameColumnIndex, row, primary_key); + return; + } + // set if changing, or remove if setting to nil + if (primary_key.size() == 0) { + if (row != not_found) { + table->move_last_over(row); + } + } + else { + table->set_string(c_primaryKeyPropertyNameColumnIndex, row, primary_key); + } +} + +StringData ObjectStore::object_type_for_table_name(StringData table_name) { + if (table_name.begins_with(c_object_table_prefix)) { + return table_name.substr(sizeof(c_object_table_prefix) - 1); + } + return StringData(); +} + +std::string ObjectStore::table_name_for_object_type(StringData object_type) { + return std::string(c_object_table_prefix) + std::string(object_type); +} + +TableRef ObjectStore::table_for_object_type(Group& group, StringData object_type) { + auto name = table_name_for_object_type(object_type); + return group.get_table(name); +} + +ConstTableRef ObjectStore::table_for_object_type(Group const& group, StringData object_type) { + auto name = table_name_for_object_type(object_type); + return group.get_table(name); +} + +namespace { +struct SchemaDifferenceExplainer { + std::vector errors; + + void operator()(schema_change::AddTable op) + { + errors.emplace_back("Class '%1' has been added.", op.object->name); + } + + void operator()(schema_change::RemoveTable) + { + // We never do anything for RemoveTable + } + + void operator()(schema_change::AddInitialProperties) + { + // Nothing. Always preceded by AddTable. + } + + void operator()(schema_change::AddProperty op) + { + errors.emplace_back("Property '%1.%2' has been added.", op.object->name, op.property->name); + } + + void operator()(schema_change::RemoveProperty op) + { + errors.emplace_back("Property '%1.%2' has been removed.", op.object->name, op.property->name); + } + + void operator()(schema_change::ChangePropertyType op) + { + errors.emplace_back("Property '%1.%2' has been changed from '%3' to '%4'.", + op.object->name, op.new_property->name, + op.old_property->type_string(), + op.new_property->type_string()); + } + + void operator()(schema_change::MakePropertyNullable op) + { + errors.emplace_back("Property '%1.%2' has been made optional.", op.object->name, op.property->name); + } + + void operator()(schema_change::MakePropertyRequired op) + { + errors.emplace_back("Property '%1.%2' has been made required.", op.object->name, op.property->name); + } + + void operator()(schema_change::ChangePrimaryKey op) + { + if (op.property && !op.object->primary_key.empty()) { + errors.emplace_back("Primary Key for class '%1' has changed from '%2' to '%3'.", + op.object->name, op.object->primary_key, op.property->name); + } + else if (op.property) { + errors.emplace_back("Primary Key for class '%1' has been added.", op.object->name); + } + else { + errors.emplace_back("Primary Key for class '%1' has been removed.", op.object->name); + } + } + + void operator()(schema_change::AddIndex op) + { + errors.emplace_back("Property '%1.%2' has been made indexed.", op.object->name, op.property->name); + } + + void operator()(schema_change::RemoveIndex op) + { + errors.emplace_back("Property '%1.%2' has been made unindexed.", op.object->name, op.property->name); + } +}; + +class TableHelper { +public: + TableHelper(Group& g) : m_group(g) { } + + Table& operator()(const ObjectSchema* object_schema) + { + if (object_schema != m_current_object_schema) { + m_current_table = table_for_object_schema(m_group, *object_schema); + m_current_object_schema = object_schema; + } + REALM_ASSERT(m_current_table); + return *m_current_table; + } + +private: + Group& m_group; + const ObjectSchema* m_current_object_schema = nullptr; + TableRef m_current_table; +}; + +template +void verify_no_errors(Verifier&& verifier, std::vector const& changes) +{ + for (auto& change : changes) { + change.visit(verifier); + } + + if (!verifier.errors.empty()) { + throw ErrorType(verifier.errors); + } +} +} // anonymous namespace + +bool ObjectStore::needs_migration(std::vector const& changes) +{ + using namespace schema_change; + struct Visitor { + bool operator()(AddIndex) { return false; } + bool operator()(AddInitialProperties) { return false; } + bool operator()(AddProperty) { return true; } + bool operator()(AddTable) { return false; } + bool operator()(RemoveTable) { return false; } + bool operator()(ChangePrimaryKey) { return true; } + bool operator()(ChangePropertyType) { return true; } + bool operator()(MakePropertyNullable) { return true; } + bool operator()(MakePropertyRequired) { return true; } + bool operator()(RemoveIndex) { return false; } + bool operator()(RemoveProperty) { return true; } + }; + + return std::any_of(begin(changes), end(changes), + [](auto&& change) { return change.visit(Visitor()); }); +} + +void ObjectStore::verify_no_changes_required(std::vector const& changes) +{ + verify_no_errors(SchemaDifferenceExplainer(), changes); +} + +void ObjectStore::verify_no_migration_required(std::vector const& changes) +{ + using namespace schema_change; + struct Verifier : SchemaDifferenceExplainer { + using SchemaDifferenceExplainer::operator(); + + // Adding a table or adding/removing indexes can be done automatically. + // All other changes require migrations. + void operator()(AddTable) { } + void operator()(AddInitialProperties) { } + void operator()(AddIndex) { } + void operator()(RemoveIndex) { } + } verifier; + verify_no_errors(verifier, changes); +} + +bool ObjectStore::verify_valid_additive_changes(std::vector const& changes, bool update_indexes) +{ + using namespace schema_change; + struct Verifier : SchemaDifferenceExplainer { + using SchemaDifferenceExplainer::operator(); + + bool index_changes = false; + bool other_changes = false; + + // Additive mode allows adding things, extra columns, and adding/removing indexes + void operator()(AddTable) { other_changes = true; } + void operator()(AddInitialProperties) { other_changes = true; } + void operator()(AddProperty) { other_changes = true; } + void operator()(RemoveProperty) { } + void operator()(AddIndex) { index_changes = true; } + void operator()(RemoveIndex) { index_changes = true; } + } verifier; + verify_no_errors(verifier, changes); + return verifier.other_changes || (verifier.index_changes && update_indexes); +} + +void ObjectStore::verify_valid_external_changes(std::vector const& changes) +{ + using namespace schema_change; + struct Verifier : SchemaDifferenceExplainer { + using SchemaDifferenceExplainer::operator(); + + // Adding new things is fine + void operator()(AddTable) { } + void operator()(AddInitialProperties) { } + void operator()(AddProperty) { } + void operator()(AddIndex) { } + void operator()(RemoveIndex) { } + + // Deleting tables is not okay + void operator()(RemoveTable op) { + errors.emplace_back("Class '%1' has been removed.", op.object->name); + } + } verifier; + verify_no_errors(verifier, changes); +} + +void ObjectStore::verify_compatible_for_immutable_and_readonly(std::vector const& changes) +{ + using namespace schema_change; + struct Verifier : SchemaDifferenceExplainer { + using SchemaDifferenceExplainer::operator(); + + void operator()(AddTable) { } + void operator()(AddInitialProperties) { } + void operator()(RemoveProperty) { } + void operator()(AddIndex) { } + void operator()(RemoveIndex) { } + } verifier; + verify_no_errors(verifier, changes); +} + +static void apply_non_migration_changes(Group& group, std::vector const& changes) +{ + using namespace schema_change; + struct Applier : SchemaDifferenceExplainer { + Applier(Group& group) : group{group}, table{group} { } + Group& group; + TableHelper table; + + // Produce an exception listing the unsupported schema changes for + // everything but the explicitly supported ones + using SchemaDifferenceExplainer::operator(); + + void operator()(AddTable op) { create_table(group, *op.object); } + void operator()(AddInitialProperties op) { add_initial_columns(group, *op.object); } + void operator()(AddIndex op) { table(op.object).add_search_index(op.property->table_column); } + void operator()(RemoveIndex op) { table(op.object).remove_search_index(op.property->table_column); } + } applier{group}; + verify_no_errors(applier, changes); +} + +static void create_initial_tables(Group& group, std::vector const& changes) +{ + using namespace schema_change; + struct Applier { + Applier(Group& group) : group{group}, table{group} { } + Group& group; + TableHelper table; + + void operator()(AddTable op) { create_table(group, *op.object); } + void operator()(RemoveTable) { } + void operator()(AddInitialProperties op) { add_initial_columns(group, *op.object); } + + // Note that in normal operation none of these will be hit, as if we're + // creating the initial tables there shouldn't be anything to update. + // Implementing these makes us better able to handle weird + // not-quite-correct files produced by other things and has no obvious + // downside. + void operator()(AddProperty op) { add_column(group, table(op.object), *op.property); } + void operator()(RemoveProperty op) { table(op.object).remove_column(op.property->table_column); } + void operator()(MakePropertyNullable op) { make_property_optional(group, table(op.object), *op.property); } + void operator()(MakePropertyRequired op) { make_property_required(group, table(op.object), *op.property); } + void operator()(ChangePrimaryKey op) { ObjectStore::set_primary_key_for_object(group, op.object->name, op.property ? StringData{op.property->name} : ""); } + void operator()(AddIndex op) { table(op.object).add_search_index(op.property->table_column); } + void operator()(RemoveIndex op) { table(op.object).remove_search_index(op.property->table_column); } + + void operator()(ChangePropertyType op) + { + replace_column(group, table(op.object), *op.old_property, *op.new_property); + } + } applier{group}; + + for (auto& change : changes) { + change.visit(applier); + } +} + +void ObjectStore::apply_additive_changes(Group& group, std::vector const& changes, bool update_indexes) +{ + using namespace schema_change; + struct Applier { + Applier(Group& group, bool update_indexes) + : group{group}, table{group}, update_indexes{update_indexes} { } + Group& group; + TableHelper table; + bool update_indexes; + + void operator()(AddTable op) { create_table(group, *op.object); } + void operator()(RemoveTable) { } + void operator()(AddInitialProperties op) { add_initial_columns(group, *op.object); } + void operator()(AddProperty op) { add_column(group, table(op.object), *op.property); } + void operator()(AddIndex op) { if (update_indexes) table(op.object).add_search_index(op.property->table_column); } + void operator()(RemoveIndex op) { if (update_indexes) table(op.object).remove_search_index(op.property->table_column); } + void operator()(RemoveProperty) { } + + // No need for errors for these, as we've already verified that they aren't present + void operator()(ChangePrimaryKey) { } + void operator()(ChangePropertyType) { } + void operator()(MakePropertyNullable) { } + void operator()(MakePropertyRequired) { } + } applier{group, update_indexes}; + + for (auto& change : changes) { + change.visit(applier); + } +} + +static void apply_pre_migration_changes(Group& group, std::vector const& changes) +{ + using namespace schema_change; + struct Applier { + Applier(Group& group) : group{group}, table{group} { } + Group& group; + TableHelper table; + + void operator()(AddTable op) { create_table(group, *op.object); } + void operator()(RemoveTable) { } + void operator()(AddInitialProperties op) { add_initial_columns(group, *op.object); } + void operator()(AddProperty op) { add_column(group, table(op.object), *op.property); } + void operator()(RemoveProperty) { /* delayed until after the migration */ } + void operator()(ChangePropertyType op) { replace_column(group, table(op.object), *op.old_property, *op.new_property); } + void operator()(MakePropertyNullable op) { make_property_optional(group, table(op.object), *op.property); } + void operator()(MakePropertyRequired op) { make_property_required(group, table(op.object), *op.property); } + void operator()(ChangePrimaryKey op) { ObjectStore::set_primary_key_for_object(group, op.object->name.c_str(), op.property ? op.property->name.c_str() : ""); } + void operator()(AddIndex op) { table(op.object).add_search_index(op.property->table_column); } + void operator()(RemoveIndex op) { table(op.object).remove_search_index(op.property->table_column); } + } applier{group}; + + for (auto& change : changes) { + change.visit(applier); + } +} + +enum class DidRereadSchema { Yes, No }; + +static void apply_post_migration_changes(Group& group, std::vector const& changes, Schema const& initial_schema, + DidRereadSchema did_reread_schema) +{ + using namespace schema_change; + struct Applier { + Applier(Group& group, Schema const& initial_schema, DidRereadSchema did_reread_schema) + : group{group}, initial_schema(initial_schema), table(group) + , did_reread_schema(did_reread_schema == DidRereadSchema::Yes) + { } + Group& group; + Schema const& initial_schema; + TableHelper table; + bool did_reread_schema; + + void operator()(RemoveProperty op) + { + if (!initial_schema.empty() && !initial_schema.find(op.object->name)->property_for_name(op.property->name)) + throw std::logic_error(util::format("Renamed property '%1.%2' does not exist.", op.object->name, op.property->name)); + auto table = table_for_object_schema(group, *op.object); + table->remove_column(op.property->table_column); + } + + void operator()(ChangePrimaryKey op) + { + if (op.property) { + validate_primary_column_uniqueness(group, op.object->name, op.property->name); + } + } + + void operator()(AddTable op) { create_table(group, *op.object); } + + void operator()(AddInitialProperties op) { + if (did_reread_schema) + add_initial_columns(group, *op.object); + else { + // If we didn't re-read the schema then AddInitialProperties was already taken care of + // during apply_pre_migration_changes. + } + } + + void operator()(AddIndex op) { table(op.object).add_search_index(op.property->table_column); } + void operator()(RemoveIndex op) { table(op.object).remove_search_index(op.property->table_column); } + + void operator()(RemoveTable) { } + void operator()(ChangePropertyType) { } + void operator()(MakePropertyNullable) { } + void operator()(MakePropertyRequired) { } + void operator()(AddProperty) { } + } applier{group, initial_schema, did_reread_schema}; + + for (auto& change : changes) { + change.visit(applier); + } +} + +static void create_default_permissions(Group& group, std::vector const& changes, + std::string const& sync_user_id) +{ +#if !REALM_ENABLE_SYNC + static_cast(group); + static_cast(changes); + static_cast(sync_user_id); +#else + sync::set_up_basic_permissions(group, true); + + // Ensure that this user exists so that local privileges checks work immediately + sync::add_user_to_role(group, sync_user_id, "everyone"); + + // Ensure that the user's private role exists so that local privilege checks work immediately. + ObjectStore::ensure_private_role_exists_for_user(group, sync_user_id); + + // Mark all tables we just created as fully world-accessible + // This has to be done after the first pass of schema init is done so that we can be + // sure that the permissions tables actually exist. + using namespace schema_change; + struct Applier { + Group& group; + void operator()(AddTable op) + { + sync::set_class_permissions_for_role(group, op.object->name, "everyone", + static_cast(ComputedPrivileges::All)); + } + + void operator()(RemoveTable) { } + void operator()(AddInitialProperties) { } + void operator()(AddProperty) { } + void operator()(RemoveProperty) { } + void operator()(MakePropertyNullable) { } + void operator()(MakePropertyRequired) { } + void operator()(ChangePrimaryKey) { } + void operator()(AddIndex) { } + void operator()(RemoveIndex) { } + void operator()(ChangePropertyType) { } + } applier{group}; + + for (auto& change : changes) { + change.visit(applier); + } +#endif +} + +#if REALM_ENABLE_SYNC +void ObjectStore::ensure_private_role_exists_for_user(Group& group, StringData sync_user_id) +{ + std::string private_role_name = util::format("__User:%1", sync_user_id); + + TableRef roles = ObjectStore::table_for_object_type(group, "__Role"); + size_t private_role_ndx = roles->find_first_string(roles->get_column_index("name"), private_role_name); + if (private_role_ndx != npos) { + // The private role already exists, so there's nothing for us to do. + return; + } + + // Add the user to the private role, creating the private role in the process. + sync::add_user_to_role(group, sync_user_id, private_role_name); + + // Set the private role on the user. + private_role_ndx = roles->find_first_string(roles->get_column_index("name"), private_role_name); + TableRef users = ObjectStore::table_for_object_type(group, "__User"); + size_t user_ndx = users->find_first_string(users->get_column_index("id"), sync_user_id); + users->set_link(users->get_column_index("role"), user_ndx, private_role_ndx); +} +#endif + +void ObjectStore::apply_schema_changes(Group& group, uint64_t schema_version, + Schema& target_schema, uint64_t target_schema_version, + SchemaMode mode, std::vector const& changes, + util::Optional sync_user_id, + std::function migration_function) +{ + create_metadata_tables(group, sync_user_id != util::none); + + if (mode == SchemaMode::Additive) { + bool target_schema_is_newer = (schema_version < target_schema_version + || schema_version == ObjectStore::NotVersioned); + + // With sync v2.x, indexes are no longer synced, so there's no reason to avoid creating them. + bool update_indexes = true; + apply_additive_changes(group, changes, update_indexes); + + if (target_schema_is_newer) + set_schema_version(group, target_schema_version); + + if (sync_user_id) + create_default_permissions(group, changes, *sync_user_id); + + set_schema_columns(group, target_schema); + return; + } + + if (schema_version == ObjectStore::NotVersioned) { + create_initial_tables(group, changes); + set_schema_version(group, target_schema_version); + set_schema_columns(group, target_schema); + return; + } + + if (mode == SchemaMode::Manual) { + set_schema_columns(group, target_schema); + if (migration_function) { + migration_function(); + } + + verify_no_changes_required(schema_from_group(group).compare(target_schema)); + validate_primary_column_uniqueness(group); + set_schema_columns(group, target_schema); + set_schema_version(group, target_schema_version); + return; + } + + if (schema_version == target_schema_version) { + apply_non_migration_changes(group, changes); + set_schema_columns(group, target_schema); + return; + } + + auto old_schema = schema_from_group(group); + apply_pre_migration_changes(group, changes); + if (migration_function) { + set_schema_columns(group, target_schema); + migration_function(); + + // Migration function may have changed the schema, so we need to re-read it + auto schema = schema_from_group(group); + apply_post_migration_changes(group, schema.compare(target_schema), old_schema, DidRereadSchema::Yes); + validate_primary_column_uniqueness(group); + } + else { + apply_post_migration_changes(group, changes, {}, DidRereadSchema::No); + } + + set_schema_version(group, target_schema_version); + set_schema_columns(group, target_schema); +} + +Schema ObjectStore::schema_from_group(Group const& group) { + std::vector schema; + schema.reserve(group.size()); + for (size_t i = 0; i < group.size(); i++) { + auto object_type = object_type_for_table_name(group.get_table_name(i)); + if (object_type.size()) { + schema.emplace_back(group, object_type, i); + } + } + return schema; +} + +util::Optional ObjectStore::property_for_column_index(ConstTableRef& table, size_t column_index) +{ + StringData column_name = table->get_column_name(column_index); + +#if REALM_ENABLE_SYNC + // The object ID column is an implementation detail, and is omitted from the schema. + // FIXME: Consider filtering out all column names starting with `!`. + if (column_name == sync::object_id_column_name) + return util::none; +#endif + + if (table->get_column_type(column_index) == type_Table) { + auto subdesc = table->get_subdescriptor(column_index); + if (subdesc->get_column_count() != 1 || subdesc->get_column_name(0) != ObjectStore::ArrayColumnName) + return util::none; + } + + Property property; + property.name = column_name; + property.type = ObjectSchema::from_core_type(*table->get_descriptor(), column_index); + property.is_indexed = table->has_search_index(column_index); + property.table_column = column_index; + + if (property.type == PropertyType::Object) { + // set link type for objects and arrays + ConstTableRef linkTable = table->get_link_target(column_index); + property.object_type = ObjectStore::object_type_for_table_name(linkTable->get_name().data()); + } + return property; +} + +void ObjectStore::set_schema_columns(Group const& group, Schema& schema) +{ + for (auto& object_schema : schema) { + auto table = table_for_object_schema(group, object_schema); + if (!table) { + continue; + } + for (auto& property : object_schema.persisted_properties) { + property.table_column = table->get_column_index(property.name); + } + } +} + +void ObjectStore::delete_data_for_object(Group& group, StringData object_type) { + if (TableRef table = table_for_object_type(group, object_type)) { + group.remove_table(table->get_index_in_group()); + ObjectStore::set_primary_key_for_object(group, object_type, ""); + } +} + +bool ObjectStore::is_empty(Group const& group) { + for (size_t i = 0; i < group.size(); i++) { + ConstTableRef table = group.get_table(i); + auto object_type = object_type_for_table_name(table->get_name()); + if (object_type.size() == 0 || object_type.begins_with("__")) { + continue; + } + if (!table->is_empty()) { + return false; + } + } + return true; +} + +void ObjectStore::rename_property(Group& group, Schema& target_schema, StringData object_type, StringData old_name, StringData new_name) +{ + TableRef table = table_for_object_type(group, object_type); + if (!table) { + throw std::logic_error(util::format("Cannot rename properties for type '%1' because it does not exist.", object_type)); + } + + auto target_object_schema = target_schema.find(object_type); + if (target_object_schema == target_schema.end()) { + throw std::logic_error(util::format("Cannot rename properties for type '%1' because it has been removed from the Realm.", object_type)); + } + + if (target_object_schema->property_for_name(old_name)) { + throw std::logic_error(util::format("Cannot rename property '%1.%2' to '%3' because the source property still exists.", + object_type, old_name, new_name)); + } + + ObjectSchema table_object_schema(group, object_type); + Property *old_property = table_object_schema.property_for_name(old_name); + if (!old_property) { + throw std::logic_error(util::format("Cannot rename property '%1.%2' because it does not exist.", object_type, old_name)); + } + + Property *new_property = table_object_schema.property_for_name(new_name); + if (!new_property) { + // New property doesn't exist in the table, which means we're probably + // renaming to an intermediate property in a multi-version migration. + // This is safe because the migration will fail schema validation unless + // this property is renamed again to a valid name before the end. + table->rename_column(old_property->table_column, new_name); + return; + } + + if (old_property->type != new_property->type || old_property->object_type != new_property->object_type) { + throw std::logic_error(util::format("Cannot rename property '%1.%2' to '%3' because it would change from type '%4' to '%5'.", + object_type, old_name, new_name, old_property->type_string(), new_property->type_string())); + } + + if (is_nullable(old_property->type) && !is_nullable(new_property->type)) { + throw std::logic_error(util::format("Cannot rename property '%1.%2' to '%3' because it would change from optional to required.", + object_type, old_name, new_name)); + } + + size_t column_to_remove = new_property->table_column; + table->rename_column(old_property->table_column, new_name); + table->remove_column(column_to_remove); + + // update table_column for each property since it may have shifted + for (auto& current_prop : target_object_schema->persisted_properties) { + if (current_prop.table_column == column_to_remove) + current_prop.table_column = old_property->table_column; + else if (current_prop.table_column > column_to_remove) + --current_prop.table_column; + } + + // update nullability for column + if (is_nullable(new_property->type) && !is_nullable(old_property->type)) { + auto prop = *new_property; + prop.table_column = old_property->table_column; + make_property_optional(group, *table, prop); + } +} + +InvalidSchemaVersionException::InvalidSchemaVersionException(uint64_t old_version, uint64_t new_version) +: logic_error(util::format("Provided schema version %1 is less than last set version %2.", new_version, old_version)) +, m_old_version(old_version), m_new_version(new_version) +{ +} + +DuplicatePrimaryKeyValueException::DuplicatePrimaryKeyValueException(std::string object_type, std::string property) +: logic_error(util::format("Primary key property '%1.%2' has duplicate values after migration.", object_type, property)) +, m_object_type(object_type), m_property(property) +{ +} + +SchemaValidationException::SchemaValidationException(std::vector const& errors) +: std::logic_error([&] { + std::string message = "Schema validation failed due to the following errors:"; + for (auto const& error : errors) { + message += std::string("\n- ") + error.what(); + } + return message; +}()) +{ +} + +SchemaMismatchException::SchemaMismatchException(std::vector const& errors) +: std::logic_error([&] { + std::string message = "Migration is required due to the following errors:"; + for (auto const& error : errors) { + message += std::string("\n- ") + error.what(); + } + return message; +}()) +{ +} + +InvalidSchemaChangeException::InvalidSchemaChangeException(std::vector const& errors) +: std::logic_error([&] { + std::string message = "The following changes cannot be made in additive-only schema mode:"; + for (auto const& error : errors) { + message += std::string("\n- ") + error.what(); + } + return message; +}()) +{ +} + +InvalidExternalSchemaChangeException::InvalidExternalSchemaChangeException(std::vector const& errors) +: std::logic_error([&] { + std::string message = + "Unsupported schema changes were made by another client or process. For a " + "synchronized Realm, this may be due to the server reverting schema changes which " + "the local user did not have permission to make."; + for (auto const& error : errors) { + message += std::string("\n- ") + error.what(); + } + return message; +}()) +{ +} diff --git a/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp b/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp new file mode 100644 index 0000000000..8936534210 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp @@ -0,0 +1 @@ +// This file is intentionally left blank. diff --git a/Pods/Realm/Realm/ObjectStore/src/results.cpp b/Pods/Realm/Realm/ObjectStore/src/results.cpp new file mode 100644 index 0000000000..9d40ee7fc9 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/results.cpp @@ -0,0 +1,820 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "results.hpp" + +#include "impl/realm_coordinator.hpp" +#include "impl/results_notifier.hpp" +#include "object_schema.hpp" +#include "object_store.hpp" +#include "schema.hpp" + +#include + +namespace realm { + +Results::Results() = default; +Results::~Results() = default; + +Results::Results(SharedRealm r, Query q, DescriptorOrdering o) +: m_realm(std::move(r)) +, m_query(std::move(q)) +, m_table(m_query.get_table()) +, m_descriptor_ordering(std::move(o)) +, m_mode(Mode::Query) +{ +} + +Results::Results(SharedRealm r, Table& table) +: m_realm(std::move(r)) +, m_mode(Mode::Table) +{ + m_table.reset(&table); +} + +Results::Results(SharedRealm r, LinkViewRef lv, util::Optional q, SortDescriptor s) +: m_realm(std::move(r)) +, m_link_view(lv) +, m_mode(Mode::LinkView) +{ + m_table.reset(&lv->get_target_table()); + if (q) { + m_query = std::move(*q); + m_mode = Mode::Query; + } + m_descriptor_ordering.append_sort(std::move(s)); +} + +Results::Results(SharedRealm r, TableView tv, DescriptorOrdering o) +: m_realm(std::move(r)) +, m_table_view(std::move(tv)) +, m_descriptor_ordering(std::move(o)) +, m_mode(Mode::TableView) +{ + m_table.reset(&m_table_view.get_parent()); +} + +Results::Results(const Results&) = default; +Results& Results::operator=(const Results&) = default; + +Results::Results(Results&& other) +: m_realm(std::move(other.m_realm)) +, m_object_schema(std::move(other.m_object_schema)) +, m_query(std::move(other.m_query)) +, m_table_view(std::move(other.m_table_view)) +, m_link_view(std::move(other.m_link_view)) +, m_table(std::move(other.m_table)) +, m_descriptor_ordering(std::move(other.m_descriptor_ordering)) +, m_notifier(std::move(other.m_notifier)) +, m_mode(other.m_mode) +, m_update_policy(other.m_update_policy) +, m_has_used_table_view(other.m_has_used_table_view) +, m_wants_background_updates(other.m_wants_background_updates) +{ + if (m_notifier) { + m_notifier->target_results_moved(other, *this); + } +} + +Results& Results::operator=(Results&& other) +{ + this->~Results(); + new (this) Results(std::move(other)); + return *this; +} + +bool Results::is_valid() const +{ + if (m_realm) + m_realm->verify_thread(); + + if (m_table && !m_table->is_attached()) + return false; + + return true; +} + +void Results::validate_read() const +{ + // is_valid ensures that we're on the correct thread. + if (!is_valid()) + throw InvalidatedException(); +} + +void Results::validate_write() const +{ + validate_read(); + if (!m_realm || !m_realm->is_in_transaction()) + throw InvalidTransactionException("Must be in a write transaction"); +} + +size_t Results::size() +{ + validate_read(); + switch (m_mode) { + case Mode::Empty: return 0; + case Mode::Table: return m_table->size(); + case Mode::LinkView: return m_link_view->size(); + case Mode::Query: + m_query.sync_view_if_needed(); + if (!m_descriptor_ordering.will_apply_distinct()) + return m_query.count(m_descriptor_ordering); + REALM_FALLTHROUGH; + case Mode::TableView: + evaluate_query_if_needed(); + return m_table_view.size(); + } + REALM_COMPILER_HINT_UNREACHABLE(); +} + +const ObjectSchema& Results::get_object_schema() const +{ + validate_read(); + + if (!m_object_schema) { + REALM_ASSERT(m_realm); + auto it = m_realm->schema().find(get_object_type()); + REALM_ASSERT(it != m_realm->schema().end()); + m_object_schema = &*it; + } + + return *m_object_schema; +} + + +StringData Results::get_object_type() const noexcept +{ + if (!m_table) { + return StringData(); + } + + return ObjectStore::object_type_for_table_name(m_table->get_name()); +} + +namespace { +template +auto get(Table& table, size_t row) +{ + return table.get(0, row); +} + +template<> +auto get(Table& table, size_t row) +{ + return table.get(row); +} +} + +template +util::Optional Results::try_get(size_t row_ndx) +{ + validate_read(); + switch (m_mode) { + case Mode::Empty: break; + case Mode::Table: + if (row_ndx < m_table->size()) + return realm::get(*m_table, row_ndx); + break; + case Mode::LinkView: + if (update_linkview()) { + if (row_ndx < m_link_view->size()) + return realm::get(*m_table, m_link_view->get(row_ndx).get_index()); + break; + } + REALM_FALLTHROUGH; + case Mode::Query: + case Mode::TableView: + evaluate_query_if_needed(); + if (row_ndx >= m_table_view.size()) + break; + if (m_update_policy == UpdatePolicy::Never && !m_table_view.is_row_attached(row_ndx)) + return T{}; + return realm::get(*m_table, m_table_view.get(row_ndx).get_index()); + } + return util::none; +} + +template +T Results::get(size_t row_ndx) +{ + if (auto row = try_get(row_ndx)) + return *row; + throw OutOfBoundsIndexException{row_ndx, size()}; +} + +template +util::Optional Results::first() +{ + return try_get(0); +} + +template +util::Optional Results::last() +{ + validate_read(); + if (m_mode == Mode::Query) + evaluate_query_if_needed(); // avoid running the query twice (for size() and for get()) + return try_get(size() - 1); +} + +bool Results::update_linkview() +{ + REALM_ASSERT(m_update_policy == UpdatePolicy::Auto); + + if (!m_descriptor_ordering.is_empty()) { + m_query = get_query(); + m_mode = Mode::Query; + evaluate_query_if_needed(); + return false; + } + return true; +} + +void Results::evaluate_query_if_needed(bool wants_notifications) +{ + if (m_update_policy == UpdatePolicy::Never) { + REALM_ASSERT(m_mode == Mode::TableView); + return; + } + + switch (m_mode) { + case Mode::Empty: + case Mode::Table: + case Mode::LinkView: + return; + case Mode::Query: + m_query.sync_view_if_needed(); + m_table_view = m_query.find_all(m_descriptor_ordering); + m_mode = Mode::TableView; + REALM_FALLTHROUGH; + case Mode::TableView: + if (wants_notifications) + prepare_async(ForCallback{false}); + m_has_used_table_view = true; + m_table_view.sync_if_needed(); + break; + } +} + +template<> +size_t Results::index_of(RowExpr const& row) +{ + validate_read(); + if (!row) { + throw DetatchedAccessorException{}; + } + if (m_table && row.get_table() != m_table) { + throw IncorrectTableException( + ObjectStore::object_type_for_table_name(m_table->get_name()), + ObjectStore::object_type_for_table_name(row.get_table()->get_name()), + "Attempting to get the index of a Row of the wrong type" + ); + } + + switch (m_mode) { + case Mode::Empty: + return not_found; + case Mode::Table: + return row.get_index(); + case Mode::LinkView: + if (update_linkview()) + return m_link_view->find(row.get_index()); + REALM_FALLTHROUGH; + case Mode::Query: + case Mode::TableView: + evaluate_query_if_needed(); + return m_table_view.find_by_source_ndx(row.get_index()); + } + REALM_COMPILER_HINT_UNREACHABLE(); +} + +template +size_t Results::index_of(T const& value) +{ + validate_read(); + switch (m_mode) { + case Mode::Empty: + return not_found; + case Mode::Table: + return m_table->find_first(0, value); + case Mode::LinkView: + REALM_UNREACHABLE(); + case Mode::Query: + case Mode::TableView: + evaluate_query_if_needed(); + return m_table_view.find_first(0, value); + } + REALM_COMPILER_HINT_UNREACHABLE(); +} + +size_t Results::index_of(Query&& q) +{ + if (m_descriptor_ordering.will_apply_sort()) { + auto first = filter(std::move(q)).first(); + return first ? index_of(*first) : not_found; + } + + auto query = get_query().and_query(std::move(q)); + query.sync_view_if_needed(); + size_t row = query.find(); + return row != not_found ? index_of(m_table->get(row)) : row; +} + +void Results::prepare_for_aggregate(size_t column, const char* name) +{ + if (column > m_table->get_column_count()) + throw OutOfBoundsIndexException{column, m_table->get_column_count()}; + switch (m_mode) { + case Mode::Empty: break; + case Mode::Table: break; + case Mode::LinkView: + m_query = this->get_query(); + m_mode = Mode::Query; + REALM_FALLTHROUGH; + case Mode::Query: + case Mode::TableView: + evaluate_query_if_needed(); + break; + default: + REALM_COMPILER_HINT_UNREACHABLE(); + } + switch (m_table->get_column_type(column)) { + case type_Timestamp: case type_Double: case type_Float: case type_Int: break; + default: throw UnsupportedColumnTypeException{column, m_table.get(), name}; + } +} + +template +util::Optional Results::aggregate(size_t column, + const char* name, + Int agg_int, Float agg_float, + Double agg_double, Timestamp agg_timestamp) +{ + validate_read(); + if (!m_table) + return none; + prepare_for_aggregate(column, name); + + auto do_agg = [&](auto const& getter) { + return Mixed(m_mode == Mode::Table ? getter(*m_table) : getter(m_table_view)); + }; + switch (m_table->get_column_type(column)) { + case type_Timestamp: return do_agg(agg_timestamp); + case type_Double: return do_agg(agg_double); + case type_Float: return do_agg(agg_float); + case type_Int: return do_agg(agg_int); + default: REALM_COMPILER_HINT_UNREACHABLE(); + } +} + +util::Optional Results::max(size_t column) +{ + size_t return_ndx = npos; + auto results = aggregate(column, "max", + [&](auto const& table) { return table.maximum_int(column, &return_ndx); }, + [&](auto const& table) { return table.maximum_float(column, &return_ndx); }, + [&](auto const& table) { return table.maximum_double(column, &return_ndx); }, + [&](auto const& table) { return table.maximum_timestamp(column, &return_ndx); }); + return return_ndx == npos ? none : results; +} + +util::Optional Results::min(size_t column) +{ + size_t return_ndx = npos; + auto results = aggregate(column, "min", + [&](auto const& table) { return table.minimum_int(column, &return_ndx); }, + [&](auto const& table) { return table.minimum_float(column, &return_ndx); }, + [&](auto const& table) { return table.minimum_double(column, &return_ndx); }, + [&](auto const& table) { return table.minimum_timestamp(column, &return_ndx); }); + return return_ndx == npos ? none : results; +} + +util::Optional Results::sum(size_t column) +{ + return aggregate(column, "sum", + [=](auto const& table) { return table.sum_int(column); }, + [=](auto const& table) { return table.sum_float(column); }, + [=](auto const& table) { return table.sum_double(column); }, + [=](auto const&) -> Timestamp { throw UnsupportedColumnTypeException{column, m_table.get(), "sum"}; }); +} + +util::Optional Results::average(size_t column) +{ + size_t value_count = 0; + auto results = aggregate(column, "average", + [&](auto const& table) { return table.average_int(column, &value_count); }, + [&](auto const& table) { return table.average_float(column, &value_count); }, + [&](auto const& table) { return table.average_double(column, &value_count); }, + [&](auto const&) -> Timestamp { throw UnsupportedColumnTypeException{column, m_table.get(), "average"}; }); + return value_count == 0 ? none : util::make_optional(results->get_double()); +} + +void Results::clear() +{ + switch (m_mode) { + case Mode::Empty: + return; + case Mode::Table: + validate_write(); + if (m_realm->is_partial()) + Results(m_realm, m_table->where()).clear(); + else + m_table->clear(); + break; + case Mode::Query: + // Not using Query:remove() because building the tableview and + // clearing it is actually significantly faster + case Mode::TableView: + validate_write(); + evaluate_query_if_needed(); + + switch (m_update_policy) { + case UpdatePolicy::Auto: + m_table_view.clear(RemoveMode::unordered); + break; + case UpdatePolicy::Never: { + // Copy the TableView because a frozen Results shouldn't let its size() change. + TableView copy(m_table_view); + copy.clear(RemoveMode::unordered); + break; + } + } + break; + case Mode::LinkView: + validate_write(); + m_link_view->remove_all_target_rows(); + break; + } +} + +PropertyType Results::get_type() const +{ + validate_read(); + switch (m_mode) { + case Mode::Empty: + case Mode::LinkView: + return PropertyType::Object; + case Mode::Query: + case Mode::TableView: + case Mode::Table: + if (m_table->get_index_in_group() != npos) + return PropertyType::Object; + return ObjectSchema::from_core_type(*m_table->get_descriptor(), 0); + } + REALM_COMPILER_HINT_UNREACHABLE(); +} + +Query Results::get_query() const +{ + validate_read(); + switch (m_mode) { + case Mode::Empty: + case Mode::Query: + return m_query; + case Mode::TableView: { + // A TableView has an associated Query if it was produced by Query::find_all. This is indicated + // by TableView::get_query returning a Query with a non-null table. + Query query = m_table_view.get_query(); + if (query.get_table()) { + return query; + } + + // The TableView has no associated query so create one with no conditions that is restricted + // to the rows in the TableView. + if (m_update_policy == UpdatePolicy::Auto) { + m_table_view.sync_if_needed(); + } + return Query(*m_table, std::unique_ptr(new TableView(m_table_view))); + } + case Mode::LinkView: + return m_table->where(m_link_view); + case Mode::Table: + return m_table->where(); + } + REALM_COMPILER_HINT_UNREACHABLE(); +} + +TableView Results::get_tableview() +{ + validate_read(); + switch (m_mode) { + case Mode::Empty: + return {}; + case Mode::LinkView: + if (update_linkview()) + return m_table->where(m_link_view).find_all(); + REALM_FALLTHROUGH; + case Mode::Query: + case Mode::TableView: + evaluate_query_if_needed(); + return m_table_view; + case Mode::Table: + return m_table->where().find_all(); + } + REALM_COMPILER_HINT_UNREACHABLE(); +} + +static std::vector parse_keypath(StringData keypath, Schema const& schema, const ObjectSchema *object_schema) +{ + auto check = [&](bool condition, const char* fmt, auto... args) { + if (!condition) { + throw std::invalid_argument(util::format("Cannot sort on key path '%1': %2.", + keypath, util::format(fmt, args...))); + } + }; + auto is_sortable_type = [](PropertyType type) { + return !is_array(type) && type != PropertyType::LinkingObjects && type != PropertyType::Data; + }; + + const char* begin = keypath.data(); + const char* end = keypath.data() + keypath.size(); + check(begin != end, "missing property name"); + + std::vector indices; + while (begin != end) { + auto sep = std::find(begin, end, '.'); + check(sep != begin && sep + 1 != end, "missing property name"); + StringData key(begin, sep - begin); + begin = sep + (sep != end); + + auto prop = object_schema->property_for_name(key); + check(prop, "property '%1.%2' does not exist", object_schema->name, key); + check(is_sortable_type(prop->type), "property '%1.%2' is of unsupported type '%3'", + object_schema->name, key, string_for_property_type(prop->type)); + if (prop->type == PropertyType::Object) + check(begin != end, "property '%1.%2' of type 'object' cannot be the final property in the key path", + object_schema->name, key); + else + check(begin == end, "property '%1.%2' of type '%3' may only be the final property in the key path", + object_schema->name, key, prop->type_string()); + + indices.push_back(prop->table_column); + if (prop->type == PropertyType::Object) + object_schema = &*schema.find(prop->object_type); + } + return indices; +} + +Results Results::sort(std::vector> const& keypaths) const +{ + if (keypaths.empty()) + return *this; + if (get_type() != PropertyType::Object) { + if (keypaths.size() != 1) + throw std::invalid_argument(util::format("Cannot sort array of '%1' on more than one key path", + string_for_property_type(get_type()))); + if (keypaths[0].first != "self") + throw std::invalid_argument(util::format("Cannot sort on key path '%1': arrays of '%2' can only be sorted on 'self'", + keypaths[0].first, string_for_property_type(get_type()))); + return sort({*m_table, {{0}}, {keypaths[0].second}}); + } + + std::vector> column_indices; + std::vector ascending; + column_indices.reserve(keypaths.size()); + ascending.reserve(keypaths.size()); + + for (auto& keypath : keypaths) { + column_indices.push_back(parse_keypath(keypath.first, m_realm->schema(), &get_object_schema())); + ascending.push_back(keypath.second); + } + return sort({*m_table, std::move(column_indices), std::move(ascending)}); +} + +Results Results::sort(SortDescriptor&& sort) const +{ + if (m_mode == Mode::LinkView) + return Results(m_realm, m_link_view, util::none, std::move(sort)); + DescriptorOrdering new_order = m_descriptor_ordering; + new_order.append_sort(std::move(sort)); + return Results(m_realm, get_query(), std::move(new_order)); +} + +Results Results::filter(Query&& q) const +{ + if (m_descriptor_ordering.will_apply_limit()) + throw UnimplementedOperationException("Filtering a Results with a limit is not yet implemented"); + return Results(m_realm, get_query().and_query(std::move(q)), m_descriptor_ordering); +} + +Results Results::limit(size_t max_count) const +{ + auto new_order = m_descriptor_ordering; + new_order.append_limit(max_count); + return Results(m_realm, get_query(), std::move(new_order)); +} + +Results Results::apply_ordering(DescriptorOrdering&& ordering) +{ + DescriptorOrdering new_order = m_descriptor_ordering; + for (size_t i = 0; i < ordering.size(); ++i) { + auto desc = ordering[i]; + if (auto sort = dynamic_cast(desc)) + new_order.append_sort(std::move(*sort)); + else if (auto distinct = dynamic_cast(desc)) + new_order.append_distinct(std::move(*distinct)); + else if (auto limit = dynamic_cast(desc)) + new_order.append_limit(std::move(*limit)); + else + REALM_COMPILER_HINT_UNREACHABLE(); + } + return Results(m_realm, get_query(), std::move(new_order)); +} + +Results Results::distinct(DistinctDescriptor&& uniqueness) const +{ + DescriptorOrdering new_order = m_descriptor_ordering; + new_order.append_distinct(std::move(uniqueness)); + return Results(m_realm, get_query(), std::move(new_order)); +} + +Results Results::distinct(std::vector const& keypaths) const +{ + if (keypaths.empty()) + return *this; + if (get_type() != PropertyType::Object) { + if (keypaths.size() != 1) + throw std::invalid_argument(util::format("Cannot sort array of '%1' on more than one key path", + string_for_property_type(get_type()))); + if (keypaths[0] != "self") + throw std::invalid_argument(util::format("Cannot sort on key path '%1': arrays of '%2' can only be sorted on 'self'", + keypaths[0], string_for_property_type(get_type()))); + return distinct({*m_table, {{0}}}); + } + + std::vector> column_indices; + column_indices.reserve(keypaths.size()); + for (auto& keypath : keypaths) + column_indices.push_back(parse_keypath(keypath, m_realm->schema(), &get_object_schema())); + return distinct({*m_table, std::move(column_indices)}); +} + +Results Results::snapshot() const & +{ + validate_read(); + return Results(*this).snapshot(); +} + +Results Results::snapshot() && +{ + validate_read(); + + switch (m_mode) { + case Mode::Empty: + return Results(); + + case Mode::Table: + case Mode::LinkView: + m_query = get_query(); + m_mode = Mode::Query; + + REALM_FALLTHROUGH; + case Mode::Query: + case Mode::TableView: + evaluate_query_if_needed(false); + m_notifier.reset(); + m_update_policy = UpdatePolicy::Never; + return std::move(*this); + } + REALM_COMPILER_HINT_UNREACHABLE(); +} + +void Results::prepare_async(ForCallback force) +{ + if (m_notifier) { + return; + } + if (m_realm->config().immutable()) { + if (force) + throw InvalidTransactionException("Cannot create asynchronous query for immutable Realms"); + return; + } + if (m_realm->is_in_transaction()) { + if (force) + throw InvalidTransactionException("Cannot create asynchronous query while in a write transaction"); + return; + } + if (m_update_policy == UpdatePolicy::Never) { + if (force) + throw std::logic_error("Cannot create asynchronous query for snapshotted Results."); + return; + } + if (!force) { + // Don't do implicit background updates if we can't actually deliver them + if (!m_realm->can_deliver_notifications()) + return; + // Don't do implicit background updates if there isn't actually anything + // that needs to be run. + if (!m_query.get_table() && m_descriptor_ordering.is_empty()) + return; + } + + m_wants_background_updates = true; + m_notifier = std::make_shared<_impl::ResultsNotifier>(*this); + _impl::RealmCoordinator::register_notifier(m_notifier); +} + +NotificationToken Results::add_notification_callback(CollectionChangeCallback cb) & +{ + prepare_async(ForCallback{true}); + return {m_notifier, m_notifier->add_callback(std::move(cb))}; +} + +bool Results::is_in_table_order() const +{ + switch (m_mode) { + case Mode::Empty: + case Mode::Table: + return true; + case Mode::LinkView: + return false; + case Mode::Query: + return m_query.produces_results_in_table_order() && !m_descriptor_ordering.will_apply_sort(); + case Mode::TableView: + return m_table_view.is_in_table_order(); + } + REALM_COMPILER_HINT_UNREACHABLE(); +} + +void Results::Internal::set_table_view(Results& results, TableView &&tv) +{ + REALM_ASSERT(results.m_update_policy != UpdatePolicy::Never); + // If the previous TableView was never actually used, then stop generating + // new ones until the user actually uses the Results object again + if (results.m_mode == Mode::TableView) { + results.m_wants_background_updates = results.m_has_used_table_view; + } + + results.m_table_view = std::move(tv); + results.m_mode = Mode::TableView; + results.m_has_used_table_view = false; + REALM_ASSERT(results.m_table_view.is_in_sync()); + REALM_ASSERT(results.m_table_view.is_attached()); +} + +#define REALM_RESULTS_TYPE(T) \ + template T Results::get(size_t); \ + template util::Optional Results::first(); \ + template util::Optional Results::last(); \ + template size_t Results::index_of(T const&); + +template RowExpr Results::get(size_t); +template util::Optional Results::first(); +template util::Optional Results::last(); + +REALM_RESULTS_TYPE(bool) +REALM_RESULTS_TYPE(int64_t) +REALM_RESULTS_TYPE(float) +REALM_RESULTS_TYPE(double) +REALM_RESULTS_TYPE(StringData) +REALM_RESULTS_TYPE(BinaryData) +REALM_RESULTS_TYPE(Timestamp) +REALM_RESULTS_TYPE(util::Optional) +REALM_RESULTS_TYPE(util::Optional) +REALM_RESULTS_TYPE(util::Optional) +REALM_RESULTS_TYPE(util::Optional) + +#undef REALM_RESULTS_TYPE + +Results::OutOfBoundsIndexException::OutOfBoundsIndexException(size_t r, size_t c) +: std::out_of_range(util::format("Requested index %1 greater than max %2", r, c - 1)) +, requested(r), valid_count(c) {} + +static std::string unsupported_operation_msg(size_t column, const Table* table, const char* operation) +{ + const char* column_type = string_for_property_type(ObjectSchema::from_core_type(*table->get_descriptor(), column)); + if (table->is_group_level()) + return util::format("Cannot %1 property '%2': operation not supported for '%3' properties", + operation, table->get_column_name(column), column_type); + return util::format("Cannot %1 '%2' array: operation not supported", + operation, column_type); +} + +Results::UnsupportedColumnTypeException::UnsupportedColumnTypeException(size_t column, const Table* table, const char* operation) +: std::logic_error(unsupported_operation_msg(column, table, operation)) +, column_index(column) +, column_name(table->get_column_name(column)) +, property_type(ObjectSchema::from_core_type(*table->get_descriptor(), column)) +{ +} + +Results::UnimplementedOperationException::UnimplementedOperationException(const char* msg) +: std::logic_error(msg) +{ } + +} // namespace realm diff --git a/Pods/Realm/Realm/ObjectStore/src/schema.cpp b/Pods/Realm/Realm/ObjectStore/src/schema.cpp new file mode 100644 index 0000000000..7916fee577 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/schema.cpp @@ -0,0 +1,274 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "schema.hpp" + +#include "object_schema.hpp" +#include "object_store.hpp" +#include "object_schema.hpp" +#include "property.hpp" + +#include + +using namespace realm; + +namespace realm { +bool operator==(Schema const& a, Schema const& b) +{ + return static_cast(a) == static_cast(b); +} +} + +Schema::Schema() = default; +Schema::~Schema() = default; +Schema::Schema(Schema const&) = default; +Schema::Schema(Schema &&) = default; +Schema& Schema::operator=(Schema const&) = default; +Schema& Schema::operator=(Schema&&) = default; + +Schema::Schema(std::initializer_list types) : Schema(base(types)) { } + +Schema::Schema(base types) : base(std::move(types)) +{ + std::sort(begin(), end(), [](ObjectSchema const& lft, ObjectSchema const& rgt) { + return lft.name < rgt.name; + }); +} + +Schema::iterator Schema::find(StringData name) +{ + auto it = std::lower_bound(begin(), end(), name, [](ObjectSchema const& lft, StringData rgt) { + return lft.name < rgt; + }); + if (it != end() && it->name != name) { + it = end(); + } + return it; +} + +Schema::const_iterator Schema::find(StringData name) const +{ + return const_cast(this)->find(name); +} + +Schema::iterator Schema::find(ObjectSchema const& object) noexcept +{ + return find(object.name); +} + +Schema::const_iterator Schema::find(ObjectSchema const& object) const noexcept +{ + return const_cast(this)->find(object); +} + +void Schema::validate() const +{ + std::vector exceptions; + + auto find_next_duplicate = [&](const_iterator start) { + return std::adjacent_find(start, cend(), [](ObjectSchema const& lft, ObjectSchema const& rgt) { + return lft.name == rgt.name; + }); + }; + + for (auto it = find_next_duplicate(cbegin()); it != cend(); it = find_next_duplicate(++it)) { + exceptions.push_back(ObjectSchemaValidationException("Type '%1' appears more than once in the schema.", + it->name)); + } + + for (auto const& object : *this) { + object.validate(*this, exceptions); + } + + if (exceptions.size()) { + throw SchemaValidationException(exceptions); + } +} + +namespace { +struct IsNotRemoveProperty { + bool operator()(SchemaChange sc) const { return sc.visit(*this); } + bool operator()(schema_change::RemoveProperty) const { return false; } + template bool operator()(T) const { return true; } +}; +struct GetRemovedColumn { + size_t operator()(SchemaChange sc) const { return sc.visit(*this); } + size_t operator()(schema_change::RemoveProperty p) const { return p.property->table_column; } + template size_t operator()(T) const { REALM_COMPILER_HINT_UNREACHABLE(); } +}; +} + +static void compare(ObjectSchema const& existing_schema, + ObjectSchema const& target_schema, + std::vector& changes) +{ + for (auto& current_prop : existing_schema.persisted_properties) { + auto target_prop = target_schema.property_for_name(current_prop.name); + + if (!target_prop) { + changes.emplace_back(schema_change::RemoveProperty{&existing_schema, ¤t_prop}); + continue; + } + if (target_schema.property_is_computed(*target_prop)) { + changes.emplace_back(schema_change::RemoveProperty{&existing_schema, ¤t_prop}); + continue; + } + if (current_prop.type != target_prop->type || + current_prop.object_type != target_prop->object_type || + is_array(current_prop.type) != is_array(target_prop->type)) { + + changes.emplace_back(schema_change::ChangePropertyType{&existing_schema, ¤t_prop, target_prop}); + continue; + } + if (is_nullable(current_prop.type) != is_nullable(target_prop->type)) { + if (is_nullable(current_prop.type)) + changes.emplace_back(schema_change::MakePropertyRequired{&existing_schema, ¤t_prop}); + else + changes.emplace_back(schema_change::MakePropertyNullable{&existing_schema, ¤t_prop}); + } + if (target_prop->requires_index()) { + if (!current_prop.is_indexed) + changes.emplace_back(schema_change::AddIndex{&existing_schema, ¤t_prop}); + } + else if (current_prop.requires_index()) { + changes.emplace_back(schema_change::RemoveIndex{&existing_schema, ¤t_prop}); + } + } + + if (existing_schema.primary_key != target_schema.primary_key) { + changes.emplace_back(schema_change::ChangePrimaryKey{&existing_schema, target_schema.primary_key_property()}); + } + + for (auto& target_prop : target_schema.persisted_properties) { + if (!existing_schema.property_for_name(target_prop.name)) { + changes.emplace_back(schema_change::AddProperty{&existing_schema, &target_prop}); + } + } + + // Move all RemovePropertys to the end and sort in descending order of + // column index, as removing a column will shift all columns after that one + auto it = std::partition(begin(changes), end(changes), IsNotRemoveProperty{}); + std::sort(it, end(changes), + [](auto a, auto b) { return GetRemovedColumn()(a) > GetRemovedColumn()(b); }); +} + +template +void Schema::zip_matching(T&& a, U&& b, Func&& func) +{ + size_t i = 0, j = 0; + while (i < a.size() && j < b.size()) { + auto& object_schema = a[i]; + auto& matching_schema = b[j]; + int cmp = object_schema.name.compare(matching_schema.name); + if (cmp == 0) { + func(&object_schema, &matching_schema); + ++i; + ++j; + } + else if (cmp < 0) { + func(&object_schema, nullptr); + ++i; + } + else { + func(nullptr, &matching_schema); + ++j; + } + } + for (; i < a.size(); ++i) + func(&a[i], nullptr); + for (; j < b.size(); ++j) + func(nullptr, &b[j]); + +} + +std::vector Schema::compare(Schema const& target_schema, bool include_table_removals) const +{ + std::vector changes; + + // Add missing tables + zip_matching(target_schema, *this, [&](const ObjectSchema* target, const ObjectSchema* existing) { + if (target && !existing) { + changes.emplace_back(schema_change::AddTable{target}); + } + else if (include_table_removals && existing && !target) { + changes.emplace_back(schema_change::RemoveTable{existing}); + } + }); + + // Modify columns + zip_matching(target_schema, *this, [&](const ObjectSchema* target, const ObjectSchema* existing) { + if (target && existing) + ::compare(*existing, *target, changes); + else if (target) { + // Target is a new table -- add all properties + changes.emplace_back(schema_change::AddInitialProperties{target}); + } + // nothing for tables in existing but not target + }); + return changes; +} + +void Schema::copy_table_columns_from(realm::Schema const& other) +{ + zip_matching(*this, other, [&](ObjectSchema* existing, const ObjectSchema* other) { + if (!existing || !other) + return; + + for (auto& current_prop : other->persisted_properties) { + auto target_prop = existing->property_for_name(current_prop.name); + if (target_prop) { + target_prop->table_column = current_prop.table_column; + } + } + }); +} + +namespace realm { +bool operator==(SchemaChange const& lft, SchemaChange const& rgt) +{ + if (lft.m_kind != rgt.m_kind) + return false; + + using namespace schema_change; + struct Visitor { + SchemaChange const& value; + + #define REALM_SC_COMPARE(type, ...) \ + bool operator()(type rgt) const \ + { \ + auto cmp = [](auto&& v) { return std::tie(__VA_ARGS__); }; \ + return cmp(value.type) == cmp(rgt); \ + } + + REALM_SC_COMPARE(AddIndex, v.object, v.property) + REALM_SC_COMPARE(AddProperty, v.object, v.property) + REALM_SC_COMPARE(AddInitialProperties, v.object) + REALM_SC_COMPARE(AddTable, v.object) + REALM_SC_COMPARE(RemoveTable, v.object) + REALM_SC_COMPARE(ChangePrimaryKey, v.object, v.property) + REALM_SC_COMPARE(ChangePropertyType, v.object, v.old_property, v.new_property) + REALM_SC_COMPARE(MakePropertyNullable, v.object, v.property) + REALM_SC_COMPARE(MakePropertyRequired, v.object, v.property) + REALM_SC_COMPARE(RemoveIndex, v.object, v.property) + REALM_SC_COMPARE(RemoveProperty, v.object, v.property) + + #undef REALM_SC_COMPARE + } visitor{lft}; + return rgt.visit(visitor); +} +} // namespace realm diff --git a/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp b/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp new file mode 100644 index 0000000000..f40c4b0b0c --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp @@ -0,0 +1,1104 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "shared_realm.hpp" + +#include "impl/collection_notifier.hpp" +#include "impl/realm_coordinator.hpp" +#include "impl/transact_log_handler.hpp" + +#include "binding_context.hpp" +#include "list.hpp" +#include "object.hpp" +#include "object_schema.hpp" +#include "object_store.hpp" +#include "results.hpp" +#include "schema.hpp" +#include "thread_safe_reference.hpp" + +#include +#include + +#if REALM_ENABLE_SYNC +#include "sync/impl/sync_file.hpp" +#include "sync/sync_config.hpp" +#include "sync/sync_manager.hpp" + +#include +#include +#else +namespace realm { +namespace sync { + struct PermissionsCache {}; +} +} +#endif + +using namespace realm; +using namespace realm::_impl; + +Realm::Realm(Config config, std::shared_ptr<_impl::RealmCoordinator> coordinator) +: m_config(std::move(config)) +, m_execution_context(m_config.execution_context) +{ + open_with_config(m_config, m_history, m_shared_group, m_read_only_group, this); + + if (m_read_only_group) { + m_group = m_read_only_group.get(); + m_schema_version = ObjectStore::get_schema_version(*m_group); + m_schema = ObjectStore::schema_from_group(*m_group); + } + else if (!coordinator || !coordinator->get_cached_schema(m_schema, m_schema_version, m_schema_transaction_version)) { + if (m_config.should_compact_on_launch_function) { + size_t free_space = -1; + size_t used_space = -1; + // getting stats requires committing a write transaction beforehand. + Group* group = nullptr; + if (m_shared_group->try_begin_write(group)) { + m_shared_group->commit(); + m_shared_group->get_stats(free_space, used_space); + if (m_config.should_compact_on_launch_function(free_space + used_space, used_space)) + compact(); + } + } + read_group(); + if (coordinator) + coordinator->cache_schema(m_schema, m_schema_version, m_schema_transaction_version); + m_shared_group->end_read(); + m_group = nullptr; + } + + m_coordinator = std::move(coordinator); +} + +REALM_NOINLINE static void translate_file_exception(StringData path, bool immutable=false) +{ + try { + throw; + } + catch (util::File::PermissionDenied const& ex) { + throw RealmFileException(RealmFileException::Kind::PermissionDenied, ex.get_path(), + util::format("Unable to open a realm at path '%1'. Please use a path where your app has %2 permissions.", + ex.get_path(), immutable ? "read" : "read-write"), + ex.what()); + } + catch (util::File::Exists const& ex) { + throw RealmFileException(RealmFileException::Kind::Exists, ex.get_path(), + util::format("File at path '%1' already exists.", ex.get_path()), + ex.what()); + } + catch (util::File::NotFound const& ex) { + throw RealmFileException(RealmFileException::Kind::NotFound, ex.get_path(), + util::format("Directory at path '%1' does not exist.", ex.get_path()), ex.what()); + } + catch (util::File::AccessError const& ex) { + // Errors for `open()` include the path, but other errors don't. We + // don't want two copies of the path in the error, so strip it out if it + // appears, and then include it in our prefix. + std::string underlying = ex.what(); + RealmFileException::Kind error_kind = RealmFileException::Kind::AccessError; + // FIXME: Replace this with a proper specific exception type once Core adds support for it. + if (underlying == "Bad or incompatible history type") + error_kind = RealmFileException::Kind::BadHistoryError; + auto pos = underlying.find(ex.get_path()); + if (pos != std::string::npos && pos > 0) { + // One extra char at each end for the quotes + underlying.replace(pos - 1, ex.get_path().size() + 2, ""); + } + throw RealmFileException(error_kind, ex.get_path(), + util::format("Unable to open a realm at path '%1': %2.", ex.get_path(), underlying), ex.what()); + } + catch (IncompatibleLockFile const& ex) { + throw RealmFileException(RealmFileException::Kind::IncompatibleLockFile, path, + "Realm file is currently open in another process " + "which cannot share access with this process. " + "All processes sharing a single file must be the same architecture.", + ex.what()); + } + catch (FileFormatUpgradeRequired const& ex) { + throw RealmFileException(RealmFileException::Kind::FormatUpgradeRequired, path, + "The Realm file format must be allowed to be upgraded " + "in order to proceed.", + ex.what()); + } +} + +#if REALM_ENABLE_SYNC +static bool is_nonupgradable_history(IncompatibleHistories const& ex) +{ + // FIXME: Replace this with a proper specific exception type once Core adds support for it. + return ex.what() == std::string("Incompatible histories. Nonupgradable history schema"); +} +#endif + +void Realm::open_with_config(const Config& config, + std::unique_ptr& history, + std::unique_ptr& shared_group, + std::unique_ptr& read_only_group, + Realm* realm) +{ + bool server_synchronization_mode = bool(config.sync_config) || config.force_sync_history; + try { + if (config.immutable()) { + if (config.realm_data.is_null()) { + read_only_group = std::make_unique(config.path, config.encryption_key.data(), Group::mode_ReadOnly); + } + else { + // Create in-memory read-only realm from existing buffer (without taking ownership of the buffer) + read_only_group = std::make_unique(config.realm_data, false); + } + } + else { + if (server_synchronization_mode) { +#if REALM_ENABLE_SYNC + history = realm::sync::make_client_history(config.path); +#else + REALM_TERMINATE("Realm was not built with sync enabled"); +#endif + } + else { + history = realm::make_in_realm_history(config.path); + } + + SharedGroupOptions options; + options.durability = config.in_memory ? SharedGroupOptions::Durability::MemOnly : + SharedGroupOptions::Durability::Full; + options.encryption_key = config.encryption_key.data(); + options.allow_file_format_upgrade = !config.disable_format_upgrade && + config.schema_mode != SchemaMode::ResetFile; + options.upgrade_callback = [&](int from_version, int to_version) { + if (realm) { + realm->upgrade_initial_version = from_version; + realm->upgrade_final_version = to_version; + } + }; + shared_group = std::make_unique(*history, options); + } + } + catch (realm::FileFormatUpgradeRequired const&) { + if (config.schema_mode != SchemaMode::ResetFile) { + translate_file_exception(config.path, config.immutable()); + } + util::File::remove(config.path); + open_with_config(config, history, shared_group, read_only_group, realm); + } +#if REALM_ENABLE_SYNC + catch (IncompatibleHistories const& ex) { + if (!server_synchronization_mode || !is_nonupgradable_history(ex)) + translate_file_exception(config.path, config.immutable()); // Throws + + // Move the Realm file into the recovery directory. + std::string recovery_directory = SyncManager::shared().recovery_directory_path(); + std::string new_realm_path = util::reserve_unique_file_name(recovery_directory, "synced-realm-XXXXXXX"); + util::File::move(config.path, new_realm_path); + + const char* message = "The local copy of this synced Realm was created with an incompatible version of " + "Realm. It has been moved aside, and the Realm will be re-downloaded the next time it " + "is opened. You should write a handler for this error that uses the provided " + "configuration to open the old Realm in read-only mode to recover any pending changes " + "and then remove the Realm file."; + throw RealmFileException(RealmFileException::Kind::IncompatibleSyncedRealm, std::move(new_realm_path), + message, ex.what()); + } +#endif // REALM_ENABLE_SYNC + catch (...) { + translate_file_exception(config.path, config.immutable()); + } +} + +Realm::~Realm() +{ + if (m_coordinator) { + m_coordinator->unregister_realm(this); + } +} + +bool Realm::is_partial() const noexcept +{ +#if REALM_ENABLE_SYNC + return m_config.sync_config && m_config.sync_config->is_partial; +#else + return false; +#endif +} + +Group& Realm::read_group() +{ + verify_open(); + + if (!m_group) + begin_read(VersionID{}); + return *m_group; +} + +void Realm::Internal::begin_read(Realm& realm, VersionID version_id) +{ + realm.begin_read(version_id); +} + +void Realm::begin_read(VersionID version_id) +{ + REALM_ASSERT(!m_group); + m_group = &const_cast(m_shared_group->begin_read(version_id)); + add_schema_change_handler(); + read_schema_from_group_if_needed(); +} + +SharedRealm Realm::get_shared_realm(Config config) +{ + auto coordinator = RealmCoordinator::get_coordinator(config.path); + return coordinator->get_realm(std::move(config)); +} + +void Realm::set_schema(Schema const& reference, Schema schema) +{ + m_dynamic_schema = false; + schema.copy_table_columns_from(reference); + m_schema = std::move(schema); + notify_schema_changed(); +} + +void Realm::read_schema_from_group_if_needed() +{ + REALM_ASSERT(!m_read_only_group); + + Group& group = read_group(); + auto current_version = m_shared_group->get_version_of_current_transaction().version; + if (m_schema_transaction_version == current_version) + return; + + m_schema_transaction_version = current_version; + m_schema_version = ObjectStore::get_schema_version(group); + auto schema = ObjectStore::schema_from_group(group); + if (m_coordinator) + m_coordinator->cache_schema(schema, m_schema_version, + m_schema_transaction_version); + + if (m_dynamic_schema) { + if (m_schema == schema) { + // The structure of the schema hasn't changed. Bring the table column indices up to date. + m_schema.copy_table_columns_from(schema); + } + else { + // The structure of the schema has changed, so replace our copy of the schema. + // FIXME: This invalidates any pointers to the object schemas within the schema vector, + // which will cause problems for anyone that caches such a pointer. + m_schema = std::move(schema); + } + } + else { + ObjectStore::verify_valid_external_changes(m_schema.compare(schema)); + m_schema.copy_table_columns_from(schema); + } + notify_schema_changed(); +} + +bool Realm::reset_file(Schema& schema, std::vector& required_changes) +{ + // FIXME: this does not work if multiple processes try to open the file at + // the same time, or even multiple threads if there is not any external + // synchronization. The latter is probably fixable, but making it + // multi-process-safe requires some sort of multi-process exclusive lock + m_group = nullptr; + m_shared_group = nullptr; + m_history = nullptr; + util::File::remove(m_config.path); + + open_with_config(m_config, m_history, m_shared_group, m_read_only_group, this); + m_schema = ObjectStore::schema_from_group(read_group()); + m_schema_version = ObjectStore::get_schema_version(read_group()); + required_changes = m_schema.compare(schema); + m_coordinator->clear_schema_cache_and_set_schema_version(m_schema_version); + return false; +} + +bool Realm::schema_change_needs_write_transaction(Schema& schema, + std::vector& changes, + uint64_t version) +{ + if (version == m_schema_version && changes.empty()) + return false; + + switch (m_config.schema_mode) { + case SchemaMode::Automatic: + if (version < m_schema_version && m_schema_version != ObjectStore::NotVersioned) + throw InvalidSchemaVersionException(m_schema_version, version); + return true; + + case SchemaMode::Immutable: + if (version != m_schema_version) + throw InvalidSchemaVersionException(m_schema_version, version); + REALM_FALLTHROUGH; + case SchemaMode::ReadOnlyAlternative: + ObjectStore::verify_compatible_for_immutable_and_readonly(changes); + return false; + + case SchemaMode::ResetFile: + if (m_schema_version == ObjectStore::NotVersioned) + return true; + if (m_schema_version == version && !ObjectStore::needs_migration(changes)) + return true; + reset_file(schema, changes); + return true; + + case SchemaMode::Additive: { + bool will_apply_index_changes = version > m_schema_version; + if (ObjectStore::verify_valid_additive_changes(changes, will_apply_index_changes)) + return true; + return version != m_schema_version; + } + + case SchemaMode::Manual: + if (version < m_schema_version && m_schema_version != ObjectStore::NotVersioned) + throw InvalidSchemaVersionException(m_schema_version, version); + if (version == m_schema_version) { + ObjectStore::verify_no_changes_required(changes); + REALM_UNREACHABLE(); // changes is non-empty so above line always throws + } + return true; + } + REALM_COMPILER_HINT_UNREACHABLE(); +} + +Schema Realm::get_full_schema() +{ + if (!m_read_only_group) + refresh(); + + // If the user hasn't specified a schema previously then m_schema is always + // the full schema + if (m_dynamic_schema) + return m_schema; + + // Otherwise we may have a subset of the file's schema, so we need to get + // the complete thing to calculate what changes to make + if (m_read_only_group) + return ObjectStore::schema_from_group(read_group()); + + Schema actual_schema; + uint64_t actual_version; + uint64_t transaction = -1; + bool got_cached = m_coordinator->get_cached_schema(actual_schema, actual_version, transaction); + if (!got_cached || transaction != m_shared_group->get_version_of_current_transaction().version) + return ObjectStore::schema_from_group(read_group()); + return actual_schema; +} + +void Realm::set_schema_subset(Schema schema) +{ + REALM_ASSERT(m_dynamic_schema); + REALM_ASSERT(m_schema_version != ObjectStore::NotVersioned); + + std::vector changes = m_schema.compare(schema); + switch (m_config.schema_mode) { + case SchemaMode::Automatic: + case SchemaMode::ResetFile: + ObjectStore::verify_no_migration_required(changes); + break; + + case SchemaMode::Immutable: + case SchemaMode::ReadOnlyAlternative: + ObjectStore::verify_compatible_for_immutable_and_readonly(changes); + break; + + case SchemaMode::Additive: + ObjectStore::verify_valid_additive_changes(changes); + break; + + case SchemaMode::Manual: + ObjectStore::verify_no_changes_required(changes); + break; + } + + set_schema(m_schema, std::move(schema)); +} + +void Realm::update_schema(Schema schema, uint64_t version, MigrationFunction migration_function, + DataInitializationFunction initialization_function, bool in_transaction) +{ + schema.validate(); + + Schema actual_schema = get_full_schema(); + std::vector required_changes = actual_schema.compare(schema); + + if (!schema_change_needs_write_transaction(schema, required_changes, version)) { + set_schema(actual_schema, std::move(schema)); + return; + } + // Either the schema version has changed or we need to do non-migration changes + + if (!in_transaction) { + transaction::begin_without_validation(*m_shared_group); + + // Beginning the write transaction may have advanced the version and left + // us with nothing to do if someone else initialized the schema on disk + if (m_new_schema) { + actual_schema = *m_new_schema; + required_changes = actual_schema.compare(schema); + if (!schema_change_needs_write_transaction(schema, required_changes, version)) { + cancel_transaction(); + cache_new_schema(); + set_schema(actual_schema, std::move(schema)); + return; + } + } + cache_new_schema(); + } + + // Cancel the write transaction if we exit this function before committing it + auto cleanup = util::make_scope_exit([&]() noexcept { + // When in_transaction is true, caller is responsible to cancel the transaction. + if (!in_transaction && is_in_transaction()) + cancel_transaction(); + }); + + uint64_t old_schema_version = m_schema_version; + bool additive = m_config.schema_mode == SchemaMode::Additive; + if (migration_function && !additive) { + auto wrapper = [&] { + SharedRealm old_realm(new Realm(m_config, nullptr)); + // Need to open in read-write mode so that it uses a SharedGroup, but + // users shouldn't actually be able to write via the old realm + old_realm->m_config.schema_mode = SchemaMode::Immutable; + migration_function(old_realm, shared_from_this(), m_schema); + }; + + // migration function needs to see the target schema on the "new" Realm + std::swap(m_schema, schema); + std::swap(m_schema_version, version); + m_in_migration = true; + auto restore = util::make_scope_exit([&]() noexcept { + std::swap(m_schema, schema); + std::swap(m_schema_version, version); + m_in_migration = false; + }); + + ObjectStore::apply_schema_changes(read_group(), version, m_schema, m_schema_version, + m_config.schema_mode, required_changes, util::none, wrapper); + } + else { + util::Optional sync_user_id; +#if REALM_ENABLE_SYNC + if (m_config.sync_config && m_config.sync_config->is_partial) + sync_user_id = m_config.sync_config->user->identity(); +#endif + ObjectStore::apply_schema_changes(read_group(), m_schema_version, schema, version, + m_config.schema_mode, required_changes, std::move(sync_user_id)); + REALM_ASSERT_DEBUG(additive || (required_changes = ObjectStore::schema_from_group(read_group()).compare(schema)).empty()); + } + + if (initialization_function && old_schema_version == ObjectStore::NotVersioned) { + // Initialization function needs to see the latest schema + uint64_t temp_version = ObjectStore::get_schema_version(read_group()); + std::swap(m_schema, schema); + std::swap(m_schema_version, temp_version); + auto restore = util::make_scope_exit([&]() noexcept { + std::swap(m_schema, schema); + std::swap(m_schema_version, temp_version); + }); + initialization_function(shared_from_this()); + } + + if (!in_transaction) { + commit_transaction(); + } + + m_schema = std::move(schema); + m_schema_version = ObjectStore::get_schema_version(read_group()); + m_dynamic_schema = false; + m_coordinator->clear_schema_cache_and_set_schema_version(version); + notify_schema_changed(); +} + +void Realm::add_schema_change_handler() +{ + if (m_config.immutable()) + return; + m_group->set_schema_change_notification_handler([&] { + m_new_schema = ObjectStore::schema_from_group(read_group()); + m_schema_version = ObjectStore::get_schema_version(read_group()); + if (m_dynamic_schema) { + // FIXME: This invalidates any pointers to the object schemas within the schema vector, + // which will cause problems for anyone that caches such a pointer. + m_schema = *m_new_schema; + } + else + m_schema.copy_table_columns_from(*m_new_schema); + + notify_schema_changed(); + }); +} + +void Realm::cache_new_schema() +{ + if (!m_shared_group) + return; + + auto new_version = m_shared_group->get_version_of_current_transaction().version; + if (m_coordinator) { + if (m_new_schema) + m_coordinator->cache_schema(std::move(*m_new_schema), m_schema_version, new_version); + else + m_coordinator->advance_schema_cache(m_schema_transaction_version, new_version); + } + m_schema_transaction_version = new_version; + m_new_schema = util::none; +} + +void Realm::translate_schema_error() +{ + // Open another copy of the file to read the new (incompatible) schema without changing + // our read transaction + auto config = m_config; + config.schema = util::none; + auto realm = Realm::make_shared_realm(std::move(config), nullptr); + auto& new_schema = realm->schema(); + + // Should always throw + ObjectStore::verify_valid_external_changes(m_schema.compare(new_schema, true)); + + // Something strange happened so just rethrow the old exception + throw; +} + +void Realm::notify_schema_changed() +{ + if (m_binding_context) { + m_binding_context->schema_did_change(m_schema); + } +} + +static void check_read_write(Realm *realm) +{ + if (realm->config().immutable()) { + throw InvalidTransactionException("Can't perform transactions on read-only Realms."); + } +} + +static void check_write(Realm* realm) +{ + if (realm->config().immutable() || realm->config().read_only_alternative()) { + throw InvalidTransactionException("Can't perform transactions on read-only Realms."); + } +} + +void Realm::verify_thread() const +{ + if (!m_execution_context.contains()) + return; + + auto thread_id = m_execution_context.get(); + if (thread_id != std::this_thread::get_id()) + throw IncorrectThreadException(); +} + +void Realm::verify_in_write() const +{ + if (!is_in_transaction()) { + throw InvalidTransactionException("Cannot modify managed objects outside of a write transaction."); + } +} + +void Realm::verify_open() const +{ + if (is_closed()) { + throw ClosedRealmException(); + } +} + +bool Realm::is_in_transaction() const noexcept +{ + if (!m_shared_group) { + return false; + } + return m_shared_group->get_transact_stage() == SharedGroup::transact_Writing; +} + +void Realm::begin_transaction() +{ + check_write(this); + verify_thread(); + + if (is_in_transaction()) { + throw InvalidTransactionException("The Realm is already in a write transaction"); + } + + // Any of the callbacks to user code below could drop the last remaining + // strong reference to `this` + auto retain_self = shared_from_this(); + + // If we're already in the middle of sending notifications, just begin the + // write transaction without sending more notifications. If this actually + // advances the read version this could leave the user in an inconsistent + // state, but that's unavoidable. + if (m_is_sending_notifications) { + _impl::NotifierPackage notifiers; + transaction::begin(m_shared_group, m_binding_context.get(), notifiers); + return; + } + + // make sure we have a read transaction + read_group(); + + m_is_sending_notifications = true; + auto cleanup = util::make_scope_exit([this]() noexcept { m_is_sending_notifications = false; }); + + try { + m_coordinator->promote_to_write(*this); + } + catch (_impl::UnsupportedSchemaChange const&) { + translate_schema_error(); + } + cache_new_schema(); +} + +void Realm::commit_transaction() +{ + check_write(this); + verify_thread(); + + if (!is_in_transaction()) { + throw InvalidTransactionException("Can't commit a non-existing write transaction"); + } + + m_coordinator->commit_write(*this); + cache_new_schema(); + invalidate_permission_cache(); +} + +void Realm::cancel_transaction() +{ + check_write(this); + verify_thread(); + + if (!is_in_transaction()) { + throw InvalidTransactionException("Can't cancel a non-existing write transaction"); + } + + transaction::cancel(*m_shared_group, m_binding_context.get()); + invalidate_permission_cache(); +} + +void Realm::invalidate() +{ + verify_open(); + verify_thread(); + check_read_write(this); + + if (m_is_sending_notifications) { + return; + } + + if (is_in_transaction()) { + cancel_transaction(); + } + if (!m_group) { + return; + } + + m_permissions_cache = nullptr; + m_shared_group->end_read(); + m_group = nullptr; +} + +bool Realm::compact() +{ + verify_thread(); + + if (m_config.immutable() || m_config.read_only_alternative()) { + throw InvalidTransactionException("Can't compact a read-only Realm"); + } + if (is_in_transaction()) { + throw InvalidTransactionException("Can't compact a Realm within a write transaction"); + } + + verify_open(); + // FIXME: when enum columns are ready, optimise all tables in a write transaction + if (m_group) { + m_shared_group->end_read(); + } + m_group = nullptr; + + return m_shared_group->compact(); +} + +void Realm::write_copy(StringData path, BinaryData key) +{ + if (key.data() && key.size() != 64) { + throw InvalidEncryptionKeyException(); + } + verify_thread(); + try { + read_group().write(path, key.data()); + } + catch (...) { + translate_file_exception(path); + } +} + +OwnedBinaryData Realm::write_copy() +{ + verify_thread(); + BinaryData buffer = read_group().write_to_mem(); + + // Since OwnedBinaryData does not have a constructor directly taking + // ownership of BinaryData, we have to do this to avoid copying the buffer + return OwnedBinaryData(std::unique_ptr((char*)buffer.data()), buffer.size()); +} + +void Realm::notify() +{ + if (is_closed() || is_in_transaction()) { + return; + } + + verify_thread(); + invalidate_permission_cache(); + + // Any of the callbacks to user code below could drop the last remaining + // strong reference to `this` + auto retain_self = shared_from_this(); + + if (m_binding_context) { + m_binding_context->before_notify(); + } + + auto cleanup = util::make_scope_exit([this]() noexcept { m_is_sending_notifications = false; }); + if (!m_shared_group->has_changed()) { + m_is_sending_notifications = true; + m_coordinator->process_available_async(*this); + return; + } + + if (m_binding_context) { + m_binding_context->changes_available(); + + // changes_available() may have advanced the read version, and if + // so we don't need to do anything further + if (!m_shared_group->has_changed()) + return; + } + + m_is_sending_notifications = true; + if (m_auto_refresh) { + if (m_group) { + try { + m_coordinator->advance_to_ready(*this); + } + catch (_impl::UnsupportedSchemaChange const&) { + translate_schema_error(); + } + cache_new_schema(); + } + else { + if (m_binding_context) { + m_binding_context->did_change({}, {}); + } + if (!is_closed()) { + m_coordinator->process_available_async(*this); + } + } + } +} + +bool Realm::refresh() +{ + verify_thread(); + check_read_write(this); + + // can't be any new changes if we're in a write transaction + if (is_in_transaction()) { + return false; + } + // don't advance if we're already in the process of advancing as that just + // makes things needlessly complicated + if (m_is_sending_notifications) { + return false; + } + invalidate_permission_cache(); + + // Any of the callbacks to user code below could drop the last remaining + // strong reference to `this` + auto retain_self = shared_from_this(); + + m_is_sending_notifications = true; + auto cleanup = util::make_scope_exit([this]() noexcept { m_is_sending_notifications = false; }); + + if (m_binding_context) { + m_binding_context->before_notify(); + } + if (m_group) { + try { + bool version_changed = m_coordinator->advance_to_latest(*this); + cache_new_schema(); + return version_changed; + } + catch (_impl::UnsupportedSchemaChange const&) { + translate_schema_error(); + } + } + + // No current read transaction, so just create a new one + read_group(); + m_coordinator->process_available_async(*this); + return true; +} + +bool Realm::can_deliver_notifications() const noexcept +{ + if (m_config.immutable()) { + return false; + } + + if (m_binding_context && !m_binding_context->can_deliver_notifications()) { + return false; + } + + return true; +} + +uint64_t Realm::get_schema_version(const Realm::Config &config) +{ + auto coordinator = RealmCoordinator::get_existing_coordinator(config.path); + if (coordinator) { + return coordinator->get_schema_version(); + } + + return ObjectStore::get_schema_version(Realm(config, nullptr).read_group()); +} + +void Realm::close() +{ + if (m_coordinator) { + m_coordinator->unregister_realm(this); + } + + m_permissions_cache = nullptr; + m_group = nullptr; + m_shared_group = nullptr; + m_history = nullptr; + m_read_only_group = nullptr; + m_binding_context = nullptr; + m_coordinator = nullptr; +} + +util::Optional Realm::file_format_upgraded_from_version() const +{ + if (upgrade_initial_version != upgrade_final_version) { + return upgrade_initial_version; + } + return util::none; +} + +template +realm::ThreadSafeReference Realm::obtain_thread_safe_reference(T const& value) +{ + verify_thread(); + if (is_in_transaction()) { + throw InvalidTransactionException("Cannot obtain thread safe reference during a write transaction."); + } + return ThreadSafeReference(value); +} + +template ThreadSafeReference Realm::obtain_thread_safe_reference(Object const& value); +template ThreadSafeReference Realm::obtain_thread_safe_reference(List const& value); +template ThreadSafeReference Realm::obtain_thread_safe_reference(Results const& value); + +template +T Realm::resolve_thread_safe_reference(ThreadSafeReference reference) +{ + verify_thread(); + if (is_in_transaction()) { + throw InvalidTransactionException("Cannot resolve thread safe reference during a write transaction."); + } + if (reference.is_invalidated()) { + throw std::logic_error("Cannot resolve thread safe reference more than once."); + } + if (!reference.has_same_config(*this)) { + throw MismatchedRealmException("Cannot resolve thread safe reference in Realm with different configuration " + "than the source Realm."); + } + invalidate_permission_cache(); + + // Any of the callbacks to user code below could drop the last remaining + // strong reference to `this` + auto retain_self = shared_from_this(); + + // Ensure we're on the same version as the reference + if (!m_group) { + // A read transaction doesn't yet exist, so create at the reference's version + begin_read(reference.m_version_id); + } + else { + // A read transaction does exist, but let's make sure that its version matches the reference's + auto current_version = m_shared_group->get_version_of_current_transaction(); + VersionID reference_version(reference.m_version_id); + + if (reference_version == current_version) { + return std::move(reference).import_into_realm(shared_from_this()); + } + + refresh(); + + current_version = m_shared_group->get_version_of_current_transaction(); + + // If the reference's version is behind, advance it to our version + if (reference_version < current_version) { + // Duplicate config for uncached Realm so we don't advance the user's Realm + Realm::Config config = m_coordinator->get_config(); + config.automatic_change_notifications = false; + config.cache = false; + config.schema = util::none; + SharedRealm temporary_realm = m_coordinator->get_realm(config); + temporary_realm->begin_read(reference_version); + + // With reference imported, advance temporary Realm to our version + T imported_value = std::move(reference).import_into_realm(temporary_realm); + transaction::advance(*temporary_realm->m_shared_group, nullptr, current_version); + if (!imported_value.is_valid()) + return T{}; + reference = ThreadSafeReference(imported_value); + } + } + + return std::move(reference).import_into_realm(shared_from_this()); +} + +template Object Realm::resolve_thread_safe_reference(ThreadSafeReference reference); +template List Realm::resolve_thread_safe_reference(ThreadSafeReference reference); +template Results Realm::resolve_thread_safe_reference(ThreadSafeReference reference); + +#if REALM_ENABLE_SYNC +static_assert(static_cast(ComputedPrivileges::Read) == static_cast(sync::Privilege::Read), ""); +static_assert(static_cast(ComputedPrivileges::Update) == static_cast(sync::Privilege::Update), ""); +static_assert(static_cast(ComputedPrivileges::Delete) == static_cast(sync::Privilege::Delete), ""); +static_assert(static_cast(ComputedPrivileges::SetPermissions) == static_cast(sync::Privilege::SetPermissions), ""); +static_assert(static_cast(ComputedPrivileges::Query) == static_cast(sync::Privilege::Query), ""); +static_assert(static_cast(ComputedPrivileges::Create) == static_cast(sync::Privilege::Create), ""); +static_assert(static_cast(ComputedPrivileges::ModifySchema) == static_cast(sync::Privilege::ModifySchema), ""); + +static constexpr const uint8_t s_allRealmPrivileges = sync::Privilege::Read + | sync::Privilege::Update + | sync::Privilege::SetPermissions + | sync::Privilege::ModifySchema; +static constexpr const uint8_t s_allClassPrivileges = sync::Privilege::Read + | sync::Privilege::Update + | sync::Privilege::Create + | sync::Privilege::Query + | sync::Privilege::SetPermissions; +static constexpr const uint8_t s_allObjectPrivileges = sync::Privilege::Read + | sync::Privilege::Update + | sync::Privilege::Delete + | sync::Privilege::SetPermissions; + +bool Realm::init_permission_cache() +{ + verify_thread(); + + if (m_permissions_cache) { + // Rather than trying to track changes to permissions tables, just skip the caching + // entirely within write transactions for now + if (is_in_transaction()) + m_permissions_cache->clear(); + return true; + } + + // Admin users bypass permissions checks outside of the logic in PermissionsCache + if (m_config.sync_config && m_config.sync_config->is_partial && !m_config.sync_config->user->is_admin()) { + m_permissions_cache = std::make_unique(read_group(), m_config.sync_config->user->identity()); + return true; + } + return false; +} + +void Realm::invalidate_permission_cache() +{ + if (m_permissions_cache) + m_permissions_cache->clear(); +} + +ComputedPrivileges Realm::get_privileges() +{ + if (!init_permission_cache()) + return static_cast(s_allRealmPrivileges); + return static_cast(m_permissions_cache->get_realm_privileges() & s_allRealmPrivileges); +} + +static uint8_t inherited_mask(uint32_t privileges) +{ + uint8_t mask = ~0; + if (!(privileges & sync::Privilege::Read)) + mask = 0; + else if (!(privileges & sync::Privilege::Update)) + mask = static_cast(sync::Privilege::Read | sync::Privilege::Query); + return mask; +} + +ComputedPrivileges Realm::get_privileges(StringData object_type) +{ + if (!init_permission_cache()) + return static_cast(s_allClassPrivileges); + auto privileges = inherited_mask(m_permissions_cache->get_realm_privileges()) + & m_permissions_cache->get_class_privileges(object_type); + return static_cast(privileges & s_allClassPrivileges); +} + +ComputedPrivileges Realm::get_privileges(RowExpr row) +{ + if (!init_permission_cache()) + return static_cast(s_allObjectPrivileges); + + auto& table = *row.get_table(); + auto object_type = ObjectStore::object_type_for_table_name(table.get_name()); + sync::GlobalID global_id{object_type, sync::object_id_for_row(read_group(), table, row.get_index())}; + auto privileges = inherited_mask(m_permissions_cache->get_realm_privileges()) + & inherited_mask(m_permissions_cache->get_class_privileges(object_type)) + & m_permissions_cache->get_object_privileges(global_id); + return static_cast(privileges & s_allObjectPrivileges); +} +#else +void Realm::invalidate_permission_cache() { } +#endif + +MismatchedConfigException::MismatchedConfigException(StringData message, StringData path) +: std::logic_error(util::format(message.data(), path)) { } + +MismatchedRealmException::MismatchedRealmException(StringData message) +: std::logic_error(message.data()) { } + +// FIXME Those are exposed for Java async queries, mainly because of handover related methods. +SharedGroup& RealmFriend::get_shared_group(Realm& realm) +{ + return *realm.m_shared_group; +} + +Group& RealmFriend::read_group_to(Realm& realm, VersionID version) +{ + if (realm.m_group && realm.m_shared_group->get_version_of_current_transaction() == version) + return *realm.m_group; + + if (realm.m_group) + realm.m_shared_group->end_read(); + realm.begin_read(version); + return *realm.m_group; +} + +std::size_t Realm::compute_size() { + Group& group = read_group(); + return group.compute_aggregated_byte_size(); +} diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp new file mode 100644 index 0000000000..ad040a48b3 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp @@ -0,0 +1,127 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/impl/apple/network_reachability_observer.hpp" + +#if NETWORK_REACHABILITY_AVAILABLE + +using namespace realm; +using namespace realm::_impl; + +namespace { + +NetworkReachabilityStatus reachability_status_for_flags(SCNetworkReachabilityFlags flags) +{ + if (!(flags & kSCNetworkReachabilityFlagsReachable)) + return NotReachable; + + if (flags & kSCNetworkReachabilityFlagsConnectionRequired) { + if (!(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) || + (flags & kSCNetworkReachabilityFlagsInterventionRequired)) + return NotReachable; + } + + NetworkReachabilityStatus status = ReachableViaWiFi; + +#if TARGET_OS_IPHONE + if (flags & kSCNetworkReachabilityFlagsIsWWAN) + status = ReachableViaWWAN; +#endif + + return status; +} + +} // (anonymous namespace) + +NetworkReachabilityObserver::NetworkReachabilityObserver(util::Optional hostname, + std::function handler) +: m_callback_queue(dispatch_queue_create("io.realm.sync.reachability", DISPATCH_QUEUE_SERIAL)) +, m_change_handler(std::move(handler)) +{ + if (hostname) { + m_reachability_ref = util::adoptCF(SystemConfiguration::shared().network_reachability_create_with_name(nullptr, + hostname->c_str())); + } else { + struct sockaddr zeroAddress = {}; + zeroAddress.sa_len = sizeof(zeroAddress); + zeroAddress.sa_family = AF_INET; + + m_reachability_ref = util::adoptCF(SystemConfiguration::shared().network_reachability_create_with_address(nullptr, + &zeroAddress)); + } +} + +NetworkReachabilityObserver::~NetworkReachabilityObserver() +{ + stop_observing(); + dispatch_release(m_callback_queue); +} + +NetworkReachabilityStatus NetworkReachabilityObserver::reachability_status() const +{ + SCNetworkReachabilityFlags flags; + + if (SystemConfiguration::shared().network_reachability_get_flags(m_reachability_ref.get(), &flags)) + return reachability_status_for_flags(flags); + + return NotReachable; +} + +bool NetworkReachabilityObserver::start_observing() +{ + m_previous_status = reachability_status(); + + auto callback = [](SCNetworkReachabilityRef, SCNetworkReachabilityFlags, void* self) { + static_cast(self)->reachability_changed(); + }; + + SCNetworkReachabilityContext context = {0, this, nullptr, nullptr, nullptr}; + + if (!SystemConfiguration::shared().network_reachability_set_callback(m_reachability_ref.get(), callback, &context)) + return false; + + if (!SystemConfiguration::shared().network_reachability_set_dispatch_queue(m_reachability_ref.get(), m_callback_queue)) + return false; + + return true; +} + +void NetworkReachabilityObserver::stop_observing() +{ + SystemConfiguration::shared().network_reachability_set_dispatch_queue(m_reachability_ref.get(), nullptr); + SystemConfiguration::shared().network_reachability_set_callback(m_reachability_ref.get(), nullptr, nullptr); + + // Wait for all previously-enqueued blocks to execute to guarantee that + // no callback will be called after returning from this method + dispatch_sync(m_callback_queue, ^{}); +} + +void NetworkReachabilityObserver::reachability_changed() +{ + auto current_status = reachability_status(); + + // When observing reachability of the specific host the callback might be called + // several times (because of DNS queries) with the same reachability flags while + // the caller should be notified only when the reachability status is really changed. + if (current_status != m_previous_status) { + m_change_handler(current_status); + m_previous_status = current_status; + } +} + +#endif diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp new file mode 100644 index 0000000000..6c4c127a6c --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp @@ -0,0 +1,98 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/impl/apple/system_configuration.hpp" + +#if NETWORK_REACHABILITY_AVAILABLE + +#include +#include "dlfcn.h" + +using namespace realm; +using namespace realm::_impl; + +SystemConfiguration::SystemConfiguration() +{ + m_framework_handle = dlopen("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration", RTLD_LAZY); + + if (m_framework_handle) { + m_create_with_name = (create_with_name_t)dlsym(m_framework_handle, "SCNetworkReachabilityCreateWithName"); + m_create_with_address = (create_with_address_t)dlsym(m_framework_handle, "SCNetworkReachabilityCreateWithAddress"); + m_set_dispatch_queue = (set_dispatch_queue_t)dlsym(m_framework_handle, "SCNetworkReachabilitySetDispatchQueue"); + m_set_callback = (set_callback_t)dlsym(m_framework_handle, "SCNetworkReachabilitySetCallback"); + m_get_flags = (get_flags_t)dlsym(m_framework_handle, "SCNetworkReachabilityGetFlags"); + } else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + asl_log(nullptr, nullptr, ASL_LEVEL_WARNING, "network reachability is not available"); +#pragma clang diagnostic pop + } +} + +SystemConfiguration& SystemConfiguration::shared() +{ + static SystemConfiguration system_configuration; + + return system_configuration; +} + +SCNetworkReachabilityRef SystemConfiguration::network_reachability_create_with_name(CFAllocatorRef allocator, + const char *hostname) +{ + if (m_create_with_name) + return m_create_with_name(allocator, hostname); + + return nullptr; +} + +SCNetworkReachabilityRef SystemConfiguration::network_reachability_create_with_address(CFAllocatorRef allocator, + const sockaddr *address) +{ + if (m_create_with_address) + return m_create_with_address(allocator, address); + + return nullptr; +} + +bool SystemConfiguration::network_reachability_set_dispatch_queue(SCNetworkReachabilityRef target, dispatch_queue_t queue) +{ + if (m_set_dispatch_queue) + return m_set_dispatch_queue(target, queue); + + return false; +} + +bool SystemConfiguration::network_reachability_set_callback(SCNetworkReachabilityRef target, + SCNetworkReachabilityCallBack callback, + SCNetworkReachabilityContext *context) +{ + if (m_set_callback) + return m_set_callback(target, callback, context); + + return false; +} + +bool SystemConfiguration::network_reachability_get_flags(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags *flags) +{ + if (m_get_flags) + return m_get_flags(target, flags); + + return false; +} + +#endif // NETWORK_REACHABILITY_AVAILABLE diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp new file mode 100644 index 0000000000..8022847dca --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp @@ -0,0 +1,358 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/impl/sync_file.hpp" + +#include +#include +#include + +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include + +inline static int mkstemp(char* _template) { return _open(_mktemp(_template), _O_CREAT | _O_TEMPORARY, _S_IREAD | _S_IWRITE); } +#else +#include +#endif + + +using File = realm::util::File; + +namespace realm { + +namespace { + +uint8_t value_of_hex_digit(char hex_digit) +{ + if (hex_digit >= '0' && hex_digit <= '9') { + return hex_digit - '0'; + } else if (hex_digit >= 'A' && hex_digit <= 'F') { + return 10 + hex_digit - 'A'; + } else if (hex_digit >= 'a' && hex_digit <= 'f') { + return 10 + hex_digit - 'a'; + } else { + throw std::invalid_argument("Cannot get the value of a character that isn't a hex digit."); + } +} + +bool filename_is_reserved(const std::string& filename) { + return (filename == "." || filename == ".."); +} + +bool character_is_unreserved(char character) +{ + bool is_capital_letter = (character >= 'A' && character <= 'Z'); + bool is_lowercase_letter = (character >= 'a' && character <= 'z'); + bool is_number = (character >= '0' && character <= '9'); + bool is_allowed_symbol = (character == '-' || character == '_' || character == '.'); + return is_capital_letter || is_lowercase_letter || is_number || is_allowed_symbol; +} + +char decoded_char_for(const std::string& percent_encoding, size_t index) +{ + if (index+2 >= percent_encoding.length()) { + throw std::invalid_argument("Malformed string: not enough characters after '%' before end of string."); + } + REALM_ASSERT(percent_encoding[index] == '%'); + return (16*value_of_hex_digit(percent_encoding[index + 1])) + value_of_hex_digit(percent_encoding[index + 2]); +} + +} // (anonymous namespace) + +namespace util { + +std::string make_percent_encoded_string(const std::string& raw_string) +{ + std::string buffer; + buffer.reserve(raw_string.size()); + for (size_t i=0; i 0); + std::string escaped = util::make_percent_encoded_string(local_identity); + if (filename_is_reserved(escaped)) + throw std::invalid_argument("A user can't have an identifier reserved by the filesystem."); + + auto user_path = file_path_by_appending_component(get_base_sync_directory(), + escaped, + util::FilePathType::Directory); + util::try_make_dir(user_path); + return user_path; +} + +void SyncFileManager::remove_user_directory(const std::string& local_identity) const +{ + REALM_ASSERT(local_identity.length() > 0); + const auto& escaped = util::make_percent_encoded_string(local_identity); + if (filename_is_reserved(escaped)) + throw std::invalid_argument("A user can't have an identifier reserved by the filesystem."); + + auto user_path = file_path_by_appending_component(get_base_sync_directory(), + escaped, + util::FilePathType::Directory); + util::try_remove_dir_recursive(user_path); +} + +bool SyncFileManager::try_rename_user_directory(const std::string& old_name, const std::string& new_name) const +{ + REALM_ASSERT_DEBUG(old_name.length() > 0 && new_name.length() > 0); + const auto& old_name_escaped = util::make_percent_encoded_string(old_name); + const auto& new_name_escaped = util::make_percent_encoded_string(new_name); + const std::string& base = get_base_sync_directory(); + if (filename_is_reserved(old_name_escaped) || filename_is_reserved(new_name_escaped)) + throw std::invalid_argument("A user directory can't be renamed using a reserved identifier."); + + const auto& old_path = file_path_by_appending_component(base, old_name_escaped, util::FilePathType::Directory); + const auto& new_path = file_path_by_appending_component(base, new_name_escaped, util::FilePathType::Directory); + + try { + File::move(old_path, new_path); + } catch (File::NotFound const&) { + return false; + } + return true; +} + +bool SyncFileManager::remove_realm(const std::string& absolute_path) const +{ + REALM_ASSERT(absolute_path.length() > 0); + bool success = true; + // Remove the Realm file (e.g. "example.realm"). + success = File::try_remove(absolute_path); + // Remove the lock file (e.g. "example.realm.lock"). + auto lock_path = util::file_path_by_appending_extension(absolute_path, "lock"); + success = File::try_remove(lock_path); + // Remove the management directory (e.g. "example.realm.management"). + auto management_path = util::file_path_by_appending_extension(absolute_path, "management"); + try { + util::try_remove_dir_recursive(management_path); + } + catch (File::AccessError const&) { + success = false; + } + return success; +} + +bool SyncFileManager::copy_realm_file(const std::string& old_path, const std::string& new_path) const +{ + REALM_ASSERT(old_path.length() > 0); + try { + if (File::exists(new_path)) { + return false; + } + File::copy(old_path, new_path); + } + catch (File::NotFound const&) { + return false; + } + catch (File::AccessError const&) { + return false; + } + return true; +} + +bool SyncFileManager::remove_realm(const std::string& local_identity, const std::string& raw_realm_path) const +{ + REALM_ASSERT(local_identity.length() > 0); + REALM_ASSERT(raw_realm_path.length() > 0); + if (filename_is_reserved(local_identity) || filename_is_reserved(raw_realm_path)) + throw std::invalid_argument("A user or Realm can't have an identifier reserved by the filesystem."); + + auto escaped = util::make_percent_encoded_string(raw_realm_path); + auto realm_path = util::file_path_by_appending_component(user_directory(local_identity), escaped); + return remove_realm(realm_path); +} + +std::string SyncFileManager::path(const std::string& local_identity, const std::string& raw_realm_path) const +{ + REALM_ASSERT(local_identity.length() > 0); + REALM_ASSERT(raw_realm_path.length() > 0); + if (filename_is_reserved(local_identity) || filename_is_reserved(raw_realm_path)) + throw std::invalid_argument("A user or Realm can't have an identifier reserved by the filesystem."); + + auto escaped = util::make_percent_encoded_string(raw_realm_path); + return util::file_path_by_appending_component(user_directory(local_identity), escaped); +} + +std::string SyncFileManager::metadata_path() const +{ + auto dir_path = file_path_by_appending_component(get_utility_directory(), + c_metadata_directory, + util::FilePathType::Directory); + util::try_make_dir(dir_path); + return util::file_path_by_appending_component(dir_path, c_metadata_realm); +} + +bool SyncFileManager::remove_metadata_realm() const +{ + auto dir_path = file_path_by_appending_component(get_utility_directory(), + c_metadata_directory, + util::FilePathType::Directory); + try { + util::try_remove_dir_recursive(dir_path); + return true; + } + catch (File::AccessError const&) { + return false; + } +} + +} // realm diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp new file mode 100644 index 0000000000..5ac913421a --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp @@ -0,0 +1,473 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/impl/sync_metadata.hpp" + +#include "object_schema.hpp" +#include "object_store.hpp" +#include "property.hpp" +#include "results.hpp" +#include "schema.hpp" +#include "util/uuid.hpp" +#if REALM_PLATFORM_APPLE +#include "impl/apple/keychain_helper.hpp" +#endif + +#include +#include + +namespace { +static const char * const c_sync_userMetadata = "UserMetadata"; +static const char * const c_sync_marked_for_removal = "marked_for_removal"; +static const char * const c_sync_identity = "identity"; +static const char * const c_sync_local_uuid = "local_uuid"; +static const char * const c_sync_auth_server_url = "auth_server_url"; +static const char * const c_sync_user_token = "user_token"; +static const char * const c_sync_user_is_admin = "user_is_admin"; + +static const char * const c_sync_fileActionMetadata = "FileActionMetadata"; +static const char * const c_sync_original_name = "original_name"; +static const char * const c_sync_new_name = "new_name"; +static const char * const c_sync_action = "action"; +static const char * const c_sync_url = "url"; + +static const char * const c_sync_clientMetadata = "ClientMetadata"; +static const char * const c_sync_uuid = "uuid"; + +realm::Schema make_schema() +{ + using namespace realm; + return Schema{ + {c_sync_userMetadata, { + {c_sync_identity, PropertyType::String}, + {c_sync_local_uuid, PropertyType::String}, + {c_sync_marked_for_removal, PropertyType::Bool}, + {c_sync_user_token, PropertyType::String|PropertyType::Nullable}, + {c_sync_auth_server_url, PropertyType::String}, + {c_sync_user_is_admin, PropertyType::Bool}, + }}, + {c_sync_fileActionMetadata, { + {c_sync_original_name, PropertyType::String, Property::IsPrimary{true}}, + {c_sync_new_name, PropertyType::String|PropertyType::Nullable}, + {c_sync_action, PropertyType::Int}, + {c_sync_url, PropertyType::String}, + {c_sync_identity, PropertyType::String}, + }}, + {c_sync_clientMetadata, { + {c_sync_uuid, PropertyType::String}, + }} + }; +} + +} // anonymous namespace + +namespace realm { + +// MARK: - Sync metadata manager + +SyncMetadataManager::SyncMetadataManager(std::string path, + bool should_encrypt, + util::Optional> encryption_key) +{ + constexpr uint64_t SCHEMA_VERSION = 2; + + Realm::Config config; + config.path = path; + config.schema = make_schema(); + config.schema_version = SCHEMA_VERSION; + config.schema_mode = SchemaMode::Automatic; +#if REALM_PLATFORM_APPLE + if (should_encrypt && !encryption_key) { + encryption_key = keychain::metadata_realm_encryption_key(File::exists(path)); + } +#endif + if (should_encrypt) { + if (!encryption_key) { + throw std::invalid_argument("Metadata Realm encryption was specified, but no encryption key was provided."); + } + config.encryption_key = std::move(*encryption_key); + } + + config.migration_function = [](SharedRealm old_realm, SharedRealm realm, Schema&) { + if (old_realm->schema_version() < 2) { + TableRef old_table = ObjectStore::table_for_object_type(old_realm->read_group(), c_sync_userMetadata); + TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata); + + // Get all the SyncUserMetadata objects. + Results results(old_realm, *old_table); + + // Column indices. + size_t old_idx_identity = old_table->get_column_index(c_sync_identity); + size_t old_idx_url = old_table->get_column_index(c_sync_auth_server_url); + size_t idx_local_uuid = table->get_column_index(c_sync_local_uuid); + size_t idx_url = table->get_column_index(c_sync_auth_server_url); + + for (size_t i = 0; i < results.size(); i++) { + RowExpr entry = results.get(i); + // Set the UUID equal to the user identity for existing users. + auto identity = entry.get_string(old_idx_identity); + table->set_string(idx_local_uuid, entry.get_index(), identity); + // Migrate the auth server URLs to a non-nullable property. + auto url = entry.get_string(old_idx_url); + table->set_string(idx_url, entry.get_index(), url.is_null() ? "" : url); + } + } + }; + + SharedRealm realm = Realm::get_shared_realm(config); + + // Get data about the (hardcoded) schemas + auto object_schema = realm->schema().find(c_sync_userMetadata); + m_user_schema = { + object_schema->persisted_properties[0].table_column, + object_schema->persisted_properties[1].table_column, + object_schema->persisted_properties[2].table_column, + object_schema->persisted_properties[3].table_column, + object_schema->persisted_properties[4].table_column, + object_schema->persisted_properties[5].table_column, + }; + + object_schema = realm->schema().find(c_sync_fileActionMetadata); + m_file_action_schema = { + object_schema->persisted_properties[0].table_column, + object_schema->persisted_properties[1].table_column, + object_schema->persisted_properties[2].table_column, + object_schema->persisted_properties[3].table_column, + object_schema->persisted_properties[4].table_column, + }; + + object_schema = realm->schema().find(c_sync_clientMetadata); + m_client_schema = { + object_schema->persisted_properties[0].table_column, + }; + + m_metadata_config = std::move(config); + + m_client_uuid = [&]() -> std::string { + TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_clientMetadata); + if (table->is_empty()) { + realm->begin_transaction(); + if (table->is_empty()) { + size_t idx = table->add_empty_row(); + REALM_ASSERT_DEBUG(idx == 0); + auto uuid = uuid_string(); + table->set_string(m_client_schema.idx_uuid, idx, uuid); + realm->commit_transaction(); + return uuid; + } + realm->cancel_transaction(); + } + return table->get_string(m_client_schema.idx_uuid, 0); + }(); +} + +SyncUserMetadataResults SyncMetadataManager::all_unmarked_users() const +{ + return get_users(false); +} + +SyncUserMetadataResults SyncMetadataManager::all_users_marked_for_removal() const +{ + return get_users(true); +} + +SyncUserMetadataResults SyncMetadataManager::get_users(bool marked) const +{ + SharedRealm realm = Realm::get_shared_realm(m_metadata_config); + + TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata); + Query query = table->where().equal(m_user_schema.idx_marked_for_removal, marked); + + Results results(realm, std::move(query)); + return SyncUserMetadataResults(std::move(results), std::move(realm), m_user_schema); +} + +SyncFileActionMetadataResults SyncMetadataManager::all_pending_actions() const +{ + SharedRealm realm = Realm::get_shared_realm(m_metadata_config); + TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata); + Results results(realm, table->where()); + return SyncFileActionMetadataResults(std::move(results), std::move(realm), m_file_action_schema); +} + +bool SyncMetadataManager::delete_metadata_action(const std::string& original_name) const +{ + auto shared_realm = Realm::get_shared_realm(m_metadata_config); + + // Retrieve the row for this object. + TableRef table = ObjectStore::table_for_object_type(shared_realm->read_group(), c_sync_fileActionMetadata); + shared_realm->begin_transaction(); + size_t row_idx = table->find_first_string(m_file_action_schema.idx_original_name, original_name); + if (row_idx == not_found) { + shared_realm->cancel_transaction(); + return false; + } + table->move_last_over(row_idx); + shared_realm->commit_transaction(); + return true; +} + +util::Optional SyncMetadataManager::get_or_make_user_metadata(const std::string& identity, + const std::string& url, + bool make_if_absent) const +{ + auto realm = Realm::get_shared_realm(m_metadata_config); + auto& schema = m_user_schema; + + // Retrieve or create the row for this object. + TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata); + Query query = table->where().equal(schema.idx_identity, identity).equal(schema.idx_auth_server_url, url); + Results results(realm, std::move(query)); + REALM_ASSERT_DEBUG(results.size() < 2); + auto row = results.first(); + + if (!row) { + if (!make_if_absent) + return none; + + realm->begin_transaction(); + // Check the results again. + row = results.first(); + if (!row) { + auto row = table->get(table->add_empty_row()); + std::string uuid = util::uuid_string(); + row.set_string(schema.idx_identity, identity); + row.set_string(schema.idx_auth_server_url, url); + row.set_string(schema.idx_local_uuid, uuid); + row.set_bool(schema.idx_user_is_admin, false); + row.set_bool(schema.idx_marked_for_removal, false); + realm->commit_transaction(); + return SyncUserMetadata(schema, std::move(realm), std::move(row)); + } else { + // Someone beat us to adding this user. + if (row->get_bool(schema.idx_marked_for_removal)) { + // User is dead. Revive or return none. + if (make_if_absent) { + row->set_bool(schema.idx_marked_for_removal, false); + realm->commit_transaction(); + } else { + realm->cancel_transaction(); + return none; + } + } else { + // User is alive, nothing else to do. + realm->cancel_transaction(); + } + return SyncUserMetadata(schema, std::move(realm), std::move(*row)); + } + } + + // Got an existing user. + if (row->get_bool(schema.idx_marked_for_removal)) { + // User is dead. Revive or return none. + if (make_if_absent) { + realm->begin_transaction(); + row->set_bool(schema.idx_marked_for_removal, false); + realm->commit_transaction(); + } else { + return none; + } + } + return SyncUserMetadata(schema, std::move(realm), std::move(*row)); +} + +SyncFileActionMetadata SyncMetadataManager::make_file_action_metadata(const std::string &original_name, + const std::string &url, + const std::string &local_uuid, + SyncFileActionMetadata::Action action, + util::Optional new_name) const +{ + size_t raw_action = static_cast(action); + + // Open the Realm. + auto realm = Realm::get_shared_realm(m_metadata_config); + auto& schema = m_file_action_schema; + + // Retrieve or create the row for this object. + TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata); + realm->begin_transaction(); + size_t row_idx = table->find_first_string(schema.idx_original_name, original_name); + if (row_idx == not_found) { + row_idx = table->add_empty_row(); + table->set_string(schema.idx_original_name, row_idx, original_name); + } + table->set_string(schema.idx_new_name, row_idx, new_name); + table->set_int(schema.idx_action, row_idx, raw_action); + table->set_string(schema.idx_url, row_idx, url); + table->set_string(schema.idx_user_identity, row_idx, local_uuid); + realm->commit_transaction(); + return SyncFileActionMetadata(schema, std::move(realm), table->get(row_idx)); +} + +util::Optional SyncMetadataManager::get_file_action_metadata(const std::string& original_name) const +{ + auto realm = Realm::get_shared_realm(m_metadata_config); + auto schema = m_file_action_schema; + TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata); + size_t row_idx = table->find_first_string(schema.idx_original_name, original_name); + if (row_idx == not_found) + return none; + + return SyncFileActionMetadata(std::move(schema), std::move(realm), table->get(row_idx)); +} + +// MARK: - Sync user metadata + +SyncUserMetadata::SyncUserMetadata(Schema schema, SharedRealm realm, RowExpr row) +: m_realm(std::move(realm)) +, m_schema(std::move(schema)) +, m_row(row) +{ } + +std::string SyncUserMetadata::identity() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + return m_row.get_string(m_schema.idx_identity); +} + +std::string SyncUserMetadata::local_uuid() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + return m_row.get_string(m_schema.idx_local_uuid); +} + +util::Optional SyncUserMetadata::user_token() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + StringData result = m_row.get_string(m_schema.idx_user_token); + return result.is_null() ? util::none : util::make_optional(std::string(result)); +} + +std::string SyncUserMetadata::auth_server_url() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + return m_row.get_string(m_schema.idx_auth_server_url); +} + +bool SyncUserMetadata::is_admin() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + return m_row.get_bool(m_schema.idx_user_is_admin); +} + +void SyncUserMetadata::set_user_token(util::Optional user_token) +{ + if (m_invalid) + return; + + REALM_ASSERT_DEBUG(m_realm); + m_realm->verify_thread(); + m_realm->begin_transaction(); + m_row.set_string(m_schema.idx_user_token, *user_token); + m_realm->commit_transaction(); +} + +void SyncUserMetadata::set_is_admin(bool is_admin) +{ + if (m_invalid) + return; + + REALM_ASSERT_DEBUG(m_realm); + m_realm->verify_thread(); + m_realm->begin_transaction(); + m_row.set_bool(m_schema.idx_user_is_admin, is_admin); + m_realm->commit_transaction(); +} + +void SyncUserMetadata::mark_for_removal() +{ + if (m_invalid) + return; + + m_realm->verify_thread(); + m_realm->begin_transaction(); + m_row.set_bool(m_schema.idx_marked_for_removal, true); + m_realm->commit_transaction(); +} + +void SyncUserMetadata::remove() +{ + m_invalid = true; + m_realm->begin_transaction(); + TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata); + table->move_last_over(m_row.get_index()); + m_realm->commit_transaction(); + m_realm = nullptr; +} + +// MARK: - File action metadata + +SyncFileActionMetadata::SyncFileActionMetadata(Schema schema, SharedRealm realm, RowExpr row) +: m_realm(std::move(realm)) +, m_schema(std::move(schema)) +, m_row(row) +{ } + +std::string SyncFileActionMetadata::original_name() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + return m_row.get_string(m_schema.idx_original_name); +} + +util::Optional SyncFileActionMetadata::new_name() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + StringData result = m_row.get_string(m_schema.idx_new_name); + return result.is_null() ? util::none : util::make_optional(std::string(result)); +} + +std::string SyncFileActionMetadata::user_local_uuid() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + return m_row.get_string(m_schema.idx_user_identity); +} + +SyncFileActionMetadata::Action SyncFileActionMetadata::action() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + return static_cast(m_row.get_int(m_schema.idx_action)); +} + +std::string SyncFileActionMetadata::url() const +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + return m_row.get_string(m_schema.idx_url); +} + +void SyncFileActionMetadata::remove() +{ + REALM_ASSERT(m_realm); + m_realm->verify_thread(); + m_realm->begin_transaction(); + TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_fileActionMetadata); + table->move_last_over(m_row.get_index()); + m_realm->commit_transaction(); + m_realm = nullptr; +} + +} // namespace realm diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp new file mode 100644 index 0000000000..b11b397432 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp @@ -0,0 +1,80 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2018 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/impl/work_queue.hpp" + +#include + +namespace realm { +namespace _impl { +namespace partial_sync { + +WorkQueue::~WorkQueue() +{ + { + std::unique_lock lock(m_mutex); + m_stopping = true; + } + m_cv.notify_one(); + + if (m_thread.joinable()) + m_thread.join(); +} + +void WorkQueue::enqueue(std::function function) +{ + { + std::unique_lock lock(m_mutex); + m_queue.push_back(std::move(function)); + + if (m_stopped) + create_thread(); + } + m_cv.notify_one(); +} + +void WorkQueue::create_thread() +{ + if (m_thread.joinable()) + m_thread.join(); + + m_thread = std::thread([this] { + std::vector> queue; + + std::unique_lock lock(m_mutex); + while (!m_stopping && + m_cv.wait_for(lock, std::chrono::milliseconds(500), + [&] { return !m_queue.empty() || m_stopping; })) { + + swap(queue, m_queue); + + lock.unlock(); + for (auto& f : queue) + f(); + queue.clear(); + lock.lock(); + } + + m_stopped = true; + }); + m_stopped = false; +} + +} // namespace partial_sync +} // namespace _impl +} // namespace realm diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp new file mode 100644 index 0000000000..b5f0525b30 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp @@ -0,0 +1,652 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/partial_sync.hpp" + +#include "impl/collection_notifier.hpp" +#include "impl/notification_wrapper.hpp" +#include "impl/object_accessor_impl.hpp" +#include "impl/realm_coordinator.hpp" +#include "object_schema.hpp" +#include "results.hpp" +#include "shared_realm.hpp" +#include "sync/impl/work_queue.hpp" +#include "sync/subscription_state.hpp" +#include "sync/sync_config.hpp" +#include "sync/sync_session.hpp" + +#include +#include + +namespace { +constexpr const char* result_sets_type_name = "__ResultSets"; +} + +namespace realm { + +namespace _impl { + +void initialize_schema(Group& group) +{ + std::string result_sets_table_name = ObjectStore::table_name_for_object_type(result_sets_type_name); + TableRef table = group.get_table(result_sets_table_name); + if (!table) { + table = sync::create_table(group, result_sets_table_name); + table->add_column(type_String, "query"); + table->add_column(type_String, "matches_property"); + table->add_column(type_Int, "status"); + table->add_column(type_String, "error_message"); + table->add_column(type_Int, "query_parse_counter"); + } + else { + // The table already existed, so it should have all of the columns that are in the shared schema. + REALM_ASSERT(table->get_column_index("query") != npos); + REALM_ASSERT(table->get_column_index("matches_property") != npos); + REALM_ASSERT(table->get_column_index("status") != npos); + REALM_ASSERT(table->get_column_index("error_message") != npos); + REALM_ASSERT(table->get_column_index("query_parse_counter") != npos); + } + + // We may need to add the "name" column even if the __ResultSets table already existed + // as it's not added by the server when it creates the table. + if (table->get_column_index("name") == npos) { + size_t idx = table->add_column(type_String, "name"); + table->add_search_index(idx); + } +} + +// A stripped-down version of WriteTransaction that can promote an existing read transaction +// and that notifies the sync session after committing a change. +class WriteTransactionNotifyingSync { +public: + WriteTransactionNotifyingSync(Realm::Config const& config, SharedGroup& sg) + : m_config(config) + , m_shared_group(&sg) + { + if (m_shared_group->get_transact_stage() == SharedGroup::transact_Reading) + LangBindHelper::promote_to_write(*m_shared_group); + else + m_shared_group->begin_write(); + } + + ~WriteTransactionNotifyingSync() + { + if (m_shared_group) + m_shared_group->rollback(); + } + + SharedGroup::version_type commit() + { + REALM_ASSERT(m_shared_group); + auto version = m_shared_group->commit(); + m_shared_group = nullptr; + + auto session = SyncManager::shared().get_session(m_config.path, *m_config.sync_config); + SyncSession::Internal::nonsync_transact_notify(*session, version); + return version; + } + + void rollback() + { + REALM_ASSERT(m_shared_group); + m_shared_group->rollback(); + m_shared_group = nullptr; + } + + Group& get_group() const noexcept + { + REALM_ASSERT(m_shared_group); + return _impl::SharedGroupFriend::get_group(*m_shared_group); + } + +private: + Realm::Config const& m_config; + SharedGroup* m_shared_group; +}; + +// Provides a convenient way for code in this file to access private details of `Realm` +// without having to add friend declarations for each individual use. +class PartialSyncHelper { +public: + static decltype(auto) get_shared_group(Realm& realm) + { + return Realm::Internal::get_shared_group(realm); + } + + static decltype(auto) get_coordinator(Realm& realm) + { + return Realm::Internal::get_coordinator(realm); + } +}; + +struct RowHandover { + RowHandover(Realm& realm, Row row) + : source_shared_group(*PartialSyncHelper::get_shared_group(realm)) + , row(source_shared_group.export_for_handover(std::move(row))) + , version(source_shared_group.pin_version()) + { + } + + ~RowHandover() + { + // If the row isn't already null we've not been imported and the version pin will leak. + REALM_ASSERT(!row); + } + + SharedGroup& source_shared_group; + std::unique_ptr> row; + VersionID version; +}; + +} // namespace _impl + +namespace partial_sync { + +namespace { + +template +void with_open_shared_group(Realm::Config const& config, F&& function) +{ + std::unique_ptr history; + std::unique_ptr sg; + std::unique_ptr read_only_group; + Realm::open_with_config(config, history, sg, read_only_group, nullptr); + + function(*sg); +} +void update_schema(Group& group, Property matches_property) +{ + Schema current_schema; + std::string table_name = ObjectStore::table_name_for_object_type(result_sets_type_name); + if (group.has_table(table_name)) + current_schema = {ObjectSchema{group, result_sets_type_name}}; + + Schema desired_schema({ + ObjectSchema(result_sets_type_name, { + {"name", PropertyType::String, Property::IsPrimary{false}, Property::IsIndexed{true}}, + {"matches_property", PropertyType::String}, + {"query", PropertyType::String}, + {"status", PropertyType::Int}, + {"error_message", PropertyType::String}, + {"query_parse_counter", PropertyType::Int}, + std::move(matches_property) + }) + }); + auto required_changes = current_schema.compare(desired_schema); + if (!required_changes.empty()) + ObjectStore::apply_additive_changes(group, required_changes, true); +} + +struct ResultSetsColumns { + ResultSetsColumns(Table& table, std::string const& matches_property_name) + { + name = table.get_column_index("name"); + REALM_ASSERT(name != npos); + + query = table.get_column_index("query"); + REALM_ASSERT(query != npos); + + this->matches_property_name = table.get_column_index("matches_property"); + REALM_ASSERT(this->matches_property_name != npos); + + // This may be `npos` if the column does not yet exist. + matches_property = table.get_column_index(matches_property_name); + } + + size_t name; + size_t query; + size_t matches_property_name; + size_t matches_property; +}; + +bool validate_existing_subscription(Table& table, ResultSetsColumns const& columns, std::string const& name, + std::string const& query, std::string const& matches_property) +{ + auto existing_row_ndx = table.find_first_string(columns.name, name); + if (existing_row_ndx == npos) + return false; + + StringData existing_query = table.get_string(columns.query, existing_row_ndx); + if (existing_query != query) + throw std::runtime_error(util::format("An existing subscription exists with the same name, " + "but a different query ('%1' vs '%2').", + existing_query, query)); + + StringData existing_matches_property = table.get_string(columns.matches_property_name, existing_row_ndx); + if (existing_matches_property != matches_property) + throw std::runtime_error(util::format("An existing subscription exists with the same name, " + "but a different result type ('%1' vs '%2').", + existing_matches_property, matches_property)); + + return true; +} + +void enqueue_registration(Realm& realm, std::string object_type, std::string query, std::string name, + std::function callback) +{ + auto config = realm.config(); + + auto& work_queue = _impl::PartialSyncHelper::get_coordinator(realm).partial_sync_work_queue(); + work_queue.enqueue([object_type=std::move(object_type), query=std::move(query), name=std::move(name), + callback=std::move(callback), config=std::move(config)] { + try { + with_open_shared_group(config, [&](SharedGroup& sg) { + _impl::WriteTransactionNotifyingSync write(config, sg); + + auto matches_property = std::string(object_type) + "_matches"; + + auto table = ObjectStore::table_for_object_type(write.get_group(), result_sets_type_name); + ResultSetsColumns columns(*table, matches_property); + + // Update schema if needed. + if (columns.matches_property == npos) { + auto target_table = ObjectStore::table_for_object_type(write.get_group(), object_type); + columns.matches_property = table->add_column_link(type_LinkList, matches_property, *target_table); + } else { + // FIXME: Validate that the column type and link target are correct. + } + + if (!validate_existing_subscription(*table, columns, name, query, matches_property)) { + auto row_ndx = sync::create_object(write.get_group(), *table); + table->set_string(columns.name, row_ndx, name); + table->set_string(columns.query, row_ndx, query); + table->set_string(columns.matches_property_name, row_ndx, matches_property); + } + + write.commit(); + }); + } catch (...) { + callback(std::current_exception()); + return; + } + + callback(nullptr); + }); +} + +void enqueue_unregistration(Object result_set, std::function callback) +{ + auto realm = result_set.realm(); + auto config = realm->config(); + auto& work_queue = _impl::PartialSyncHelper::get_coordinator(*realm).partial_sync_work_queue(); + + // Export a reference to the __ResultSets row so we can hand it to the worker thread. + // We store it in a shared_ptr as it would otherwise prevent the lambda from being copyable, + // which `std::function` requires. + auto handover = std::make_shared<_impl::RowHandover>(*realm, result_set.row()); + + work_queue.enqueue([handover=std::move(handover), callback=std::move(callback), + config=std::move(config)] () { + with_open_shared_group(config, [&](SharedGroup& sg) { + // Import handed-over object. + sg.begin_read(handover->version); + Row row = *sg.import_from_handover(std::move(handover->row)); + sg.unpin_version(handover->version); + + _impl::WriteTransactionNotifyingSync write(config, sg); + if (row.is_attached()) { + row.move_last_over(); + write.commit(); + } + else { + write.rollback(); + } + }); + callback(); + }); +} + +std::string default_name_for_query(const std::string& query, const std::string& object_type) +{ + return util::format("[%1] %2", object_type, query); +} + +} // unnamed namespace + +void register_query(std::shared_ptr realm, const std::string &object_class, const std::string &query, + std::function callback) +{ + auto sync_config = realm->config().sync_config; + if (!sync_config || !sync_config->is_partial) + throw std::logic_error("A partial sync query can only be registered in a partially synced Realm"); + + if (realm->schema().find(object_class) == realm->schema().end()) + throw std::logic_error("A partial sync query can only be registered for a type that exists in the Realm's schema"); + + auto matches_property = object_class + "_matches"; + + // The object schema must outlive `object` below. + std::unique_ptr result_sets_schema; + Object raw_object; + { + realm->begin_transaction(); + auto cleanup = util::make_scope_exit([&]() noexcept { + if (realm->is_in_transaction()) + realm->cancel_transaction(); + }); + + update_schema(realm->read_group(), + Property(matches_property, PropertyType::Object|PropertyType::Array, object_class)); + + result_sets_schema = std::make_unique(realm->read_group(), result_sets_type_name); + + CppContext context; + raw_object = Object::create(context, realm, *result_sets_schema, + AnyDict{ + {"name", query}, + {"matches_property", matches_property}, + {"query", query}, + {"status", int64_t(0)}, + {"error_message", std::string()}, + {"query_parse_counter", int64_t(0)}, + }, false); + + realm->commit_transaction(); + } + + auto object = std::make_shared<_impl::NotificationWrapper>(std::move(raw_object)); + + // Observe the new object and notify listener when the results are complete (status != 0). + auto notification_callback = [object, matches_property, + result_sets_schema=std::move(result_sets_schema), + callback=std::move(callback)](CollectionChangeSet, std::exception_ptr error) mutable { + if (error) { + callback(Results(), error); + object.reset(); + return; + } + + CppContext context; + auto status = any_cast(object->get_property_value(context, "status")); + if (status == 0) { + // Still computing... + return; + } else if (status == 1) { + // Finished successfully. + auto list = any_cast(object->get_property_value(context, matches_property)); + callback(list.as_results(), nullptr); + } else { + // Finished with error. + auto message = any_cast(object->get_property_value(context, "error_message")); + callback(Results(), std::make_exception_ptr(std::runtime_error(std::move(message)))); + } + object.reset(); + }; + object->add_notification_callback(std::move(notification_callback)); +} + +struct Subscription::Notifier : public _impl::CollectionNotifier { + enum State { + Creating, + Complete, + Removed, + }; + + Notifier(std::shared_ptr realm) + : _impl::CollectionNotifier(std::move(realm)) + , m_coordinator(&_impl::PartialSyncHelper::get_coordinator(*get_realm())) + { + } + + void release_data() noexcept override { } + void run() override + { + std::unique_lock lock(m_mutex); + if (m_has_results_to_deliver) { + // Mark the object as being modified so that CollectionNotifier is aware + // that there are changes to deliver. + m_changes.modify(0); + } + } + + void deliver(SharedGroup&) override + { + std::unique_lock lock(m_mutex); + m_error = m_pending_error; + m_pending_error = nullptr; + + m_state = m_pending_state; + m_has_results_to_deliver = false; + } + + void finished_subscribing(std::exception_ptr error) + { + { + std::unique_lock lock(m_mutex); + m_pending_error = error; + m_pending_state = Complete; + m_has_results_to_deliver = true; + } + + // Trigger processing of change notifications. + m_coordinator->wake_up_notifier_worker(); + } + + void finished_unsubscribing() + { + { + std::unique_lock lock(m_mutex); + + m_pending_state = Removed; + m_has_results_to_deliver = true; + } + + // Trigger processing of change notifications. + m_coordinator->wake_up_notifier_worker(); + } + + std::exception_ptr error() const + { + std::unique_lock lock(m_mutex); + return m_error; + } + + State state() const + { + std::unique_lock lock(m_mutex); + return m_state; + } + +private: + void do_attach_to(SharedGroup&) override { } + void do_detach_from(SharedGroup&) override { } + + void do_prepare_handover(SharedGroup&) override + { + add_changes(std::move(m_changes)); + } + + bool do_add_required_change_info(_impl::TransactionChangeInfo&) override { return false; } + bool prepare_to_deliver() override { return m_has_results_to_deliver; } + + _impl::RealmCoordinator *m_coordinator; + + mutable std::mutex m_mutex; + _impl::CollectionChangeBuilder m_changes; + std::exception_ptr m_pending_error = nullptr; + std::exception_ptr m_error = nullptr; + bool m_has_results_to_deliver = false; + + State m_state = Creating; + State m_pending_state = Creating; +}; + +Subscription subscribe(Results const& results, util::Optional user_provided_name) +{ + auto realm = results.get_realm(); + + auto sync_config = realm->config().sync_config; + if (!sync_config || !sync_config->is_partial) + throw std::logic_error("A partial sync query can only be registered in a partially synced Realm"); + + auto query = results.get_query().get_description(); // Throws if the query cannot be serialized. + query += " " + results.get_descriptor_ordering().get_description(results.get_query().get_table()); + + std::string name = user_provided_name ? std::move(*user_provided_name) + : default_name_for_query(query, results.get_object_type()); + + Subscription subscription(name, results.get_object_type(), realm); + std::weak_ptr weak_notifier = subscription.m_notifier; + enqueue_registration(*realm, results.get_object_type(), std::move(query), std::move(name), + [weak_notifier=std::move(weak_notifier)](std::exception_ptr error) { + if (auto notifier = weak_notifier.lock()) + notifier->finished_subscribing(error); + }); + return subscription; +} + +void unsubscribe(Subscription& subscription) +{ + if (auto result_set_object = subscription.result_set_object()) { + // The subscription has its result set object, so we can queue up the unsubscription immediately. + std::weak_ptr weak_notifier = subscription.m_notifier; + enqueue_unregistration(*result_set_object, [weak_notifier=std::move(weak_notifier)]() { + if (auto notifier = weak_notifier.lock()) + notifier->finished_unsubscribing(); + }); + return; + } + + switch (subscription.state()) { + case SubscriptionState::Creating: { + // The result set object is in the process of being created. Try unsubscribing again once it exists. + auto token = std::make_shared(); + *token = subscription.add_notification_callback([token, &subscription] () { + if (subscription.state() == SubscriptionState::Creating) + return; + + unsubscribe(subscription); + + // Invalidate the notification token so we do not receive further callbacks. + *token = SubscriptionNotificationToken(); + }); + return; + } + + case SubscriptionState::Error: + // We encountered an error when creating the subscription. There's nothing to remove, so just + // mark the subscription as removed. + subscription.m_notifier->finished_unsubscribing(); + break; + + case SubscriptionState::Invalidated: + // Nothing to do. We have already removed the subscription. + break; + + case SubscriptionState::Pending: + case SubscriptionState::Complete: + // This should not be reachable as these states require the result set object to exist. + REALM_ASSERT(false); + break; + } +} + +Subscription::Subscription(std::string name, std::string object_type, std::shared_ptr realm) +: m_object_schema(realm->read_group(), result_sets_type_name) +{ + // FIXME: Why can't I do this in the initializer list? + m_notifier = std::make_shared(realm); + _impl::RealmCoordinator::register_notifier(m_notifier); + + auto matches_property = std::string(object_type) + "_matches"; + + TableRef table = ObjectStore::table_for_object_type(realm->read_group(), result_sets_type_name); + Query query = table->where(); + query.equal(m_object_schema.property_for_name("name")->table_column, name); + query.equal(m_object_schema.property_for_name("matches_property")->table_column, matches_property); + m_result_sets = Results(std::move(realm), std::move(query)); +} + +Subscription::~Subscription() = default; +Subscription::Subscription(Subscription&&) = default; +Subscription& Subscription::operator=(Subscription&&) = default; + +SubscriptionNotificationToken Subscription::add_notification_callback(std::function callback) +{ + auto result_sets_token = m_result_sets.add_notification_callback([callback] (CollectionChangeSet, std::exception_ptr) { + callback(); + }); + NotificationToken registration_token(m_notifier, m_notifier->add_callback([callback] (CollectionChangeSet, std::exception_ptr) { + callback(); + })); + return SubscriptionNotificationToken{std::move(registration_token), std::move(result_sets_token)}; +} + +util::Optional Subscription::result_set_object() const +{ + if (m_notifier->state() == Notifier::Complete) { + if (auto row = m_result_sets.first()) + return Object(m_result_sets.get_realm(), m_object_schema, *row); + } + + return util::none; +} + +SubscriptionState Subscription::state() const +{ + switch (m_notifier->state()) { + case Notifier::Creating: + return SubscriptionState::Creating; + case Notifier::Removed: + return SubscriptionState::Invalidated; + case Notifier::Complete: + break; + } + + if (m_notifier->error()) + return SubscriptionState::Error; + + if (auto object = result_set_object()) { + CppContext context; + auto value = any_cast(object->get_property_value(context, "status")); + return (SubscriptionState)value; + } + + // We may not have an object even if the subscription has completed if the completion callback fired + // but the result sets callback is yet to fire. + return SubscriptionState::Creating; +} + +std::exception_ptr Subscription::error() const +{ + if (auto error = m_notifier->error()) + return error; + + if (auto object = result_set_object()) { + CppContext context; + auto message = any_cast(object->get_property_value(context, "error_message")); + if (message.size()) + return make_exception_ptr(std::runtime_error(message)); + } + + return nullptr; +} + +Results Subscription::results() const +{ + auto object = result_set_object(); + REALM_ASSERT_RELEASE(object); + + CppContext context; + auto matches_property = any_cast(object->get_property_value(context, "matches_property")); + auto list = any_cast(object->get_property_value(context, matches_property)); + return list.as_results(); +} + +} // namespace partial_sync +} // namespace realm diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp new file mode 100644 index 0000000000..3adea0ae15 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp @@ -0,0 +1,65 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/sync_config.hpp" + +#include "sync/sync_manager.hpp" + +#include + +namespace realm { + +std::string SyncConfig::partial_sync_identifier(const SyncUser& user) +{ + std::string raw_identifier = SyncManager::shared().client_uuid() + "/" + user.local_identity(); + + // The type of the argument to sha1() changed in sync 3.11.1. Implicitly + // convert to either char or unsigned char so that both signatures work. + struct cast { + uint8_t* value; + operator uint8_t*() { return value; } + operator char*() { return reinterpret_cast(value); } + }; + uint8_t identifier[20]; + sync::crypto::sha1(raw_identifier.data(), raw_identifier.size(), cast{&identifier[0]}); + + std::stringstream ss; + ss << std::hex << std::setfill('0'); + for (uint8_t c : identifier) + ss << std::setw(2) << (unsigned)c; + return ss.str(); +} + +std::string SyncConfig::realm_url() const +{ + REALM_ASSERT(reference_realm_url.length() > 0); + REALM_ASSERT(user); + + if (!is_partial) + return reference_realm_url; + + std::string base_url = reference_realm_url; + if (base_url.back() == '/') + base_url.pop_back(); + + if (custom_partial_sync_identifier) + return util::format("%1/__partial/%2", base_url, *custom_partial_sync_identifier); + return util::format("%1/__partial/%2/%3", base_url, user->identity(), partial_sync_identifier(*user)); +} + +} // namespace realm diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp new file mode 100644 index 0000000000..43f97d9576 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp @@ -0,0 +1,515 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/sync_manager.hpp" + +#include "sync/impl/sync_client.hpp" +#include "sync/impl/sync_file.hpp" +#include "sync/impl/sync_metadata.hpp" +#include "sync/sync_session.hpp" +#include "sync/sync_user.hpp" + +using namespace realm; +using namespace realm::_impl; + +constexpr const char SyncManager::c_admin_identity[]; + +SyncManager& SyncManager::shared() +{ + // The singleton is heap-allocated in order to fix an issue when running unit tests where tests would crash after + // they were done running because the manager was destroyed too early. + static SyncManager& manager = *new SyncManager; + return manager; +} + +void SyncManager::configure_file_system(const std::string& base_file_path, + MetadataMode metadata_mode, + util::Optional> custom_encryption_key, + bool reset_metadata_on_error) +{ + struct UserCreationData { + std::string identity; + std::string user_token; + std::string server_url; + bool is_admin; + }; + + std::vector users_to_add; + { + std::lock_guard lock(m_file_system_mutex); + + // Set up the file manager. + if (m_file_manager) { + REALM_ASSERT(m_file_manager->base_path() == base_file_path); + } else { + m_file_manager = std::make_unique(base_file_path); + } + + // Set up the metadata manager, and perform initial loading/purging work. + if (m_metadata_manager) { + return; + } + switch (metadata_mode) { + case MetadataMode::NoEncryption: + m_metadata_manager = std::make_unique(m_file_manager->metadata_path(), + false); + break; + case MetadataMode::Encryption: + try { + m_metadata_manager = std::make_unique(m_file_manager->metadata_path(), + true, + custom_encryption_key); + } catch (RealmFileException const& ex) { + if (reset_metadata_on_error && m_file_manager->remove_metadata_realm()) { + m_metadata_manager = std::make_unique(m_file_manager->metadata_path(), + true, + std::move(custom_encryption_key)); + } else { + throw; + } + } + break; + case MetadataMode::NoMetadata: + return; + } + + REALM_ASSERT(m_metadata_manager); + m_client_uuid = m_metadata_manager->client_uuid(); + + // Perform any necessary file actions. + std::vector completed_actions; + SyncFileActionMetadataResults file_actions = m_metadata_manager->all_pending_actions(); + for (size_t i = 0; i < file_actions.size(); i++) { + auto file_action = file_actions.get(i); + if (run_file_action(file_action)) { + completed_actions.emplace_back(std::move(file_action)); + } + } + for (auto& action : completed_actions) { + action.remove(); + } + // Load persisted users into the users map. + SyncUserMetadataResults users = m_metadata_manager->all_unmarked_users(); + for (size_t i = 0; i < users.size(); i++) { + // Note that 'admin' style users are not persisted. + auto user_data = users.get(i); + auto user_token = user_data.user_token(); + auto identity = user_data.identity(); + auto server_url = user_data.auth_server_url(); + bool is_admin = user_data.is_admin(); + if (user_token) { + UserCreationData data = { + std::move(identity), + std::move(*user_token), + std::move(server_url), + is_admin, + }; + users_to_add.emplace_back(std::move(data)); + } + } + // Delete any users marked for death. + std::vector dead_users; + SyncUserMetadataResults users_to_remove = m_metadata_manager->all_users_marked_for_removal(); + dead_users.reserve(users_to_remove.size()); + for (size_t i = 0; i < users_to_remove.size(); i++) { + auto user = users_to_remove.get(i); + // FIXME: delete user data in a different way? (This deletes a logged-out user's data as soon as the app + // launches again, which might not be how some apps want to treat their data.) + try { + m_file_manager->remove_user_directory(user.local_uuid()); + dead_users.emplace_back(std::move(user)); + } catch (util::File::AccessError const&) { + continue; + } + } + for (auto& user : dead_users) { + user.remove(); + } + } + { + std::lock_guard lock(m_user_mutex); + for (auto& user_data : users_to_add) { + auto& identity = user_data.identity; + auto& server_url = user_data.server_url; + auto user = std::make_shared(user_data.user_token, identity, server_url); + user->set_is_admin(user_data.is_admin); + m_users.insert({ {identity, server_url}, std::move(user) }); + } + } +} + +bool SyncManager::immediately_run_file_actions(const std::string& realm_path) +{ + if (!m_metadata_manager) { + return false; + } + if (auto metadata = m_metadata_manager->get_file_action_metadata(realm_path)) { + if (run_file_action(*metadata)) { + metadata->remove(); + return true; + } + } + return false; +} + +// Perform a file action. Returns whether or not the file action can be removed. +bool SyncManager::run_file_action(const SyncFileActionMetadata& md) +{ + switch (md.action()) { + case SyncFileActionMetadata::Action::DeleteRealm: + // Delete all the files for the given Realm. + m_file_manager->remove_realm(md.original_name()); + return true; + case SyncFileActionMetadata::Action::BackUpThenDeleteRealm: + // Copy the primary Realm file to the recovery dir, and then delete the Realm. + auto new_name = md.new_name(); + auto original_name = md.original_name(); + if (!util::File::exists(original_name)) { + // The Realm file doesn't exist anymore. + return true; + } + if (new_name && !util::File::exists(*new_name) && m_file_manager->copy_realm_file(original_name, *new_name)) { + // We successfully copied the Realm file to the recovery directory. + m_file_manager->remove_realm(original_name); + return true; + } + return false; + } + return false; +} + +void SyncManager::reset_for_testing() +{ + std::lock_guard lock(m_file_system_mutex); + m_file_manager = nullptr; + m_metadata_manager = nullptr; + m_client_uuid = util::none; + + { + // Destroy all the users. + std::lock_guard lock(m_user_mutex); + m_users.clear(); + m_admin_token_users.clear(); + } + { + std::lock_guard lock(m_mutex); + + // Stop the client. This will abort any uploads that inactive sessions are waiting for. + if (m_sync_client) + m_sync_client->stop(); + + { + std::lock_guard lock(m_session_mutex); + + // Callers of `SyncManager::reset_for_testing` should ensure there are no active sessions + // prior to calling `reset_for_testing`. + auto no_active_sessions = std::none_of(m_sessions.begin(), m_sessions.end(), [](auto& element){ + return element.second->existing_external_reference(); + }); + REALM_ASSERT_RELEASE(no_active_sessions); + + // Destroy any inactive sessions. + // FIXME: We shouldn't have any inactive sessions at this point! Sessions are expected to + // remain inactive until their final upload completes, at which point they are unregistered + // and destroyed. Our call to `sync::Client::stop` above aborts all uploads, so all sessions + // should have already been destroyed. + m_sessions.clear(); + } + + // Destroy the client now that we have no remaining sessions. + m_sync_client = nullptr; + + // Reset even more state. + // NOTE: these should always match the defaults. + m_log_level = util::Logger::Level::info; + m_logger_factory = nullptr; + m_client_reconnect_mode = ReconnectMode::normal; + m_multiplex_sessions = false; + } +} + +void SyncManager::set_log_level(util::Logger::Level level) noexcept +{ + std::lock_guard lock(m_mutex); + m_log_level = level; +} + +void SyncManager::set_logger_factory(SyncLoggerFactory& factory) noexcept +{ + std::lock_guard lock(m_mutex); + m_logger_factory = &factory; +} + +void SyncManager::reconnect() +{ + std::lock_guard lock(m_session_mutex); + for (auto& it : m_sessions) { + it.second->handle_reconnect(); + } +} + +util::Logger::Level SyncManager::log_level() const noexcept +{ + std::lock_guard lock(m_mutex); + return m_log_level; +} + +bool SyncManager::perform_metadata_update(std::function update_function) const +{ + std::lock_guard lock(m_file_system_mutex); + if (!m_metadata_manager) { + return false; + } + update_function(*m_metadata_manager); + return true; +} + +std::shared_ptr SyncManager::get_user(const SyncUserIdentifier& identifier, std::string refresh_token) +{ + std::lock_guard lock(m_user_mutex); + auto it = m_users.find(identifier); + if (it == m_users.end()) { + // No existing user. + auto new_user = std::make_shared(std::move(refresh_token), + identifier.user_id, + identifier.auth_server_url, + none, + SyncUser::TokenType::Normal); + m_users.insert({ identifier, new_user }); + return new_user; + } else { + auto user = it->second; + if (user->state() == SyncUser::State::Error) { + return nullptr; + } + user->update_refresh_token(std::move(refresh_token)); + return user; + } +} + +std::shared_ptr SyncManager::get_admin_token_user_from_identity(const std::string& identity, + util::Optional server_url, + const std::string& token) +{ + if (server_url) + return get_admin_token_user(*server_url, token, identity); + + std::lock_guard lock(m_user_mutex); + // Look up the user based off the identity. + // No server URL, so no migration possible. + auto it = m_admin_token_users.find(identity); + if (it == m_admin_token_users.end()) { + // No existing user. + auto new_user = std::make_shared(token, + c_admin_identity, + std::move(server_url), + identity, + SyncUser::TokenType::Admin); + m_admin_token_users.insert({ identity, new_user }); + return new_user; + } else { + return it->second; + } +} + +std::shared_ptr SyncManager::get_admin_token_user(const std::string& server_url, + const std::string& token, + util::Optional old_identity) +{ + std::shared_ptr user; + { + std::lock_guard lock(m_user_mutex); + // Look up the user based off the server URL. + auto it = m_admin_token_users.find(server_url); + if (it != m_admin_token_users.end()) + return it->second; + + // No existing user. + user = std::make_shared(token, + c_admin_identity, + server_url, + c_admin_identity + server_url, + SyncUser::TokenType::Admin); + m_admin_token_users.insert({ server_url, user }); + } + if (old_identity) { + // Try renaming the user's directory to use our new naming standard, if applicable. + std::lock_guard fm_lock(m_file_system_mutex); + if (m_file_manager) + m_file_manager->try_rename_user_directory(*old_identity, c_admin_identity + server_url); + } + return user; +} + +std::vector> SyncManager::all_logged_in_users() const +{ + std::lock_guard lock(m_user_mutex); + std::vector> users; + users.reserve(m_users.size() + m_admin_token_users.size()); + for (auto& it : m_users) { + auto user = it.second; + if (user->state() == SyncUser::State::Active) { + users.emplace_back(std::move(user)); + } + } + for (auto& it : m_admin_token_users) { + users.emplace_back(std::move(it.second)); + } + return users; +} + +std::shared_ptr SyncManager::get_current_user() const +{ + std::lock_guard lock(m_user_mutex); + + auto is_active_user = [](auto& el) { return el.second->state() == SyncUser::State::Active; }; + auto it = std::find_if(m_users.begin(), m_users.end(), is_active_user); + if (it == m_users.end()) + return nullptr; + + if (std::find_if(std::next(it), m_users.end(), is_active_user) != m_users.end()) + throw std::logic_error("Current user is not valid if more that one valid, logged-in user exists."); + + return it->second; +} + +std::shared_ptr SyncManager::get_existing_logged_in_user(const SyncUserIdentifier& identifier) const +{ + std::lock_guard lock(m_user_mutex); + auto it = m_users.find(identifier); + if (it == m_users.end()) + return nullptr; + + auto user = it->second; + return user->state() == SyncUser::State::Active ? user : nullptr; +} + +std::string SyncManager::path_for_realm(const SyncUser& user, const std::string& raw_realm_url) const +{ + std::lock_guard lock(m_file_system_mutex); + REALM_ASSERT(m_file_manager); + return m_file_manager->path(user.local_identity(), raw_realm_url); +} + +std::string SyncManager::recovery_directory_path() const +{ + std::lock_guard lock(m_file_system_mutex); + REALM_ASSERT(m_file_manager); + return m_file_manager->recovery_directory_path(); +} + +std::shared_ptr SyncManager::get_existing_active_session(const std::string& path) const +{ + std::lock_guard lock(m_session_mutex); + if (auto session = get_existing_session_locked(path)) { + if (auto external_reference = session->existing_external_reference()) + return external_reference; + } + return nullptr; +} + +std::shared_ptr SyncManager::get_existing_session_locked(const std::string& path) const +{ + REALM_ASSERT(!m_session_mutex.try_lock()); + auto it = m_sessions.find(path); + return it == m_sessions.end() ? nullptr : it->second; +} + +std::shared_ptr SyncManager::get_existing_session(const std::string& path) const +{ + std::lock_guard lock(m_session_mutex); + if (auto session = get_existing_session_locked(path)) + return session->external_reference(); + + return nullptr; +} + +std::shared_ptr SyncManager::get_session(const std::string& path, const SyncConfig& sync_config) +{ + auto& client = get_sync_client(); // Throws + + std::lock_guard lock(m_session_mutex); + if (auto session = get_existing_session_locked(path)) { + sync_config.user->register_session(session); + return session->external_reference(); + } + + auto shared_session = SyncSession::create(client, path, sync_config); + m_sessions[path] = shared_session; + + // Create the external reference immediately to ensure that the session will become + // inactive if an exception is thrown in the following code. + auto external_reference = shared_session->external_reference(); + + sync_config.user->register_session(std::move(shared_session)); + + return external_reference; +} + +void SyncManager::unregister_session(const std::string& path) +{ + std::lock_guard lock(m_session_mutex); + auto it = m_sessions.find(path); + REALM_ASSERT(it != m_sessions.end()); + + // If the session has an active external reference, leave it be. This will happen if the session + // moves to an inactive state while still externally reference, for instance, as a result of + // the session's user being logged out. + if (it->second->existing_external_reference()) + return; + + m_sessions.erase(path); +} + +void SyncManager::enable_session_multiplexing() +{ + std::lock_guard lock(m_mutex); + if (m_sync_client) + throw std::logic_error("Cannot enable session multiplexing after creating the sync client"); + m_multiplex_sessions = true; +} + +SyncClient& SyncManager::get_sync_client() const +{ + std::lock_guard lock(m_mutex); + if (!m_sync_client) + m_sync_client = create_sync_client(); // Throws + return *m_sync_client; +} + +std::unique_ptr SyncManager::create_sync_client() const +{ + REALM_ASSERT(!m_mutex.try_lock()); + + std::unique_ptr logger; + if (m_logger_factory) { + logger = m_logger_factory->make_logger(m_log_level); // Throws + } + else { + auto stderr_logger = std::make_unique(); // Throws + stderr_logger->set_level_threshold(m_log_level); + logger = std::move(stderr_logger); + } + return std::make_unique(std::move(logger), m_client_reconnect_mode, m_multiplex_sessions); +} + +std::string SyncManager::client_uuid() const +{ + REALM_ASSERT(m_client_uuid); + return *m_client_uuid; +} diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp new file mode 100644 index 0000000000..d53dad0d92 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp @@ -0,0 +1,370 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/sync_permission.hpp" + +#include "impl/notification_wrapper.hpp" +#include "impl/object_accessor_impl.hpp" +#include "object_schema.hpp" +#include "property.hpp" + +#include "sync/sync_config.hpp" +#include "sync/sync_manager.hpp" +#include "sync/sync_session.hpp" +#include "sync/sync_user.hpp" +#include "util/event_loop_signal.hpp" +#include "util/uuid.hpp" + +#include + +using namespace realm; +using namespace std::chrono; + +// MARK: - Utility + +namespace { + +// Make a handler that extracts either an exception pointer, or the string value +// of the property with the specified name. +Permissions::AsyncOperationHandler make_handler_extracting_property(std::string property, + Permissions::PermissionOfferCallback callback) +{ + return [property=std::move(property), + callback=std::move(callback)](Object* object, std::exception_ptr exception) { + if (exception) { + callback(none, exception); + } else { + CppContext context; + auto token = any_cast(object->get_property_value(context, property)); + callback(util::make_optional(std::move(token)), nullptr); + } + }; +} + +AccessLevel extract_access_level(Object& permission, CppContext& context) +{ + auto may_manage = permission.get_property_value(context, "mayManage"); + if (may_manage.has_value() && any_cast(may_manage)) + return AccessLevel::Admin; + + auto may_write = permission.get_property_value(context, "mayWrite"); + if (may_write.has_value() && any_cast(may_write)) + return AccessLevel::Write; + + auto may_read = permission.get_property_value(context, "mayRead"); + if (may_read.has_value() && any_cast(may_read)) + return AccessLevel::Read; + + return AccessLevel::None; +} + +/// Turn a system time point value into the 64-bit integer representing ns since the Unix epoch. +int64_t ns_since_unix_epoch(const system_clock::time_point& point) +{ + tm unix_epoch{}; + unix_epoch.tm_year = 70; + time_t epoch_time = mktime(&unix_epoch); + auto epoch_point = system_clock::from_time_t(epoch_time); + return duration_cast(point - epoch_point).count(); +} + +} // anonymous namespace + +// MARK: - Permission + +Permission::Permission(Object& permission) +{ + CppContext context; + path = any_cast(permission.get_property_value(context, "path")); + access = extract_access_level(permission, context); + condition = Condition(any_cast(permission.get_property_value(context, "userId"))); + updated_at = any_cast(permission.get_property_value(context, "updatedAt")); +} + +Permission::Permission(std::string path, AccessLevel access, Condition condition, Timestamp updated_at) +: path(std::move(path)) +, access(access) +, condition(std::move(condition)) +, updated_at(std::move(updated_at)) +{ } + +std::string Permission::description_for_access_level(AccessLevel level) +{ + switch (level) { + case AccessLevel::None: return "none"; + case AccessLevel::Read: return "read"; + case AccessLevel::Write: return "write"; + case AccessLevel::Admin: return "admin"; + } + REALM_UNREACHABLE(); +} + +bool Permission::paths_are_equivalent(std::string path_1, std::string path_2, + const std::string& user_id_1, const std::string& user_id_2) +{ + REALM_ASSERT_DEBUG(path_1.length() > 0); + REALM_ASSERT_DEBUG(path_2.length() > 0); + if (path_1 == path_2) { + // If both paths are identical and contain `/~/`, the user IDs must match. + return (path_1.find("/~/") == std::string::npos) || (user_id_1 == user_id_2); + } + // Make substitutions for the first `/~/` in the string. + size_t index = path_1.find("/~/"); + if (index != std::string::npos) + path_1.replace(index + 1, 1, user_id_1); + + index = path_2.find("/~/"); + if (index != std::string::npos) + path_2.replace(index + 1, 1, user_id_2); + + return path_1 == path_2; +} + +// MARK: - Permissions + +void Permissions::get_permissions(std::shared_ptr user, + PermissionResultsCallback callback, + const ConfigMaker& make_config) +{ + auto realm = Permissions::permission_realm(user, make_config); + auto table = ObjectStore::table_for_object_type(realm->read_group(), "Permission"); + auto results = std::make_shared<_impl::NotificationWrapper>(std::move(realm), *table); + + // `get_permissions` works by temporarily adding an async notifier to the permission Realm. + // This notifier will run the `async` callback until the Realm contains permissions or + // an error happens. When either of these two things happen, the notifier will be + // unregistered by nulling out the `results_wrapper` container. + auto async = [results, callback=std::move(callback)](CollectionChangeSet, std::exception_ptr ex) mutable { + if (ex) { + callback(Results(), ex); + results.reset(); + return; + } + if (results->size() > 0) { + // We monitor the raw results. The presence of a `__management` Realm indicates + // that the permissions have been downloaded (hence, we wait until size > 0). + TableRef table = ObjectStore::table_for_object_type(results->get_realm()->read_group(), "Permission"); + size_t col_idx = table->get_descriptor()->get_column_index("path"); + auto query = !(table->column(col_idx).ends_with("/__permission") + || table->column(col_idx).ends_with("/__perm") + || table->column(col_idx).ends_with("/__management")); + // Call the callback with our new permissions object. This object will exclude the + // private Realms. + callback(results->filter(std::move(query)), nullptr); + results.reset(); + } + }; + results->add_notification_callback(std::move(async)); +} + +void Permissions::set_permission(std::shared_ptr user, + Permission permission, + PermissionChangeCallback callback, + const ConfigMaker& make_config) +{ + auto props = AnyDict{ + {"userId", permission.condition.user_id}, + {"realmUrl", user->server_url() + permission.path}, + {"mayRead", permission.access != AccessLevel::None}, + {"mayWrite", permission.access == AccessLevel::Write || permission.access == AccessLevel::Admin}, + {"mayManage", permission.access == AccessLevel::Admin}, + }; + if (permission.condition.type == Permission::Condition::Type::KeyValue) { + props.insert({"metadataKey", permission.condition.key_value.first}); + props.insert({"metadataValue", permission.condition.key_value.second}); + } + auto cb = [callback=std::move(callback)](Object*, std::exception_ptr exception) { + callback(exception); + }; + perform_async_operation("PermissionChange", std::move(user), std::move(cb), std::move(props), make_config); +} + +void Permissions::delete_permission(std::shared_ptr user, + Permission permission, + PermissionChangeCallback callback, + const ConfigMaker& make_config) +{ + permission.access = AccessLevel::None; + set_permission(std::move(user), std::move(permission), std::move(callback), make_config); +} + +void Permissions::make_offer(std::shared_ptr user, + PermissionOffer offer, + PermissionOfferCallback callback, + const ConfigMaker& make_config) +{ + auto props = AnyDict{ + {"expiresAt", std::move(offer.expiration)}, + {"userId", user->identity()}, + {"realmUrl", user->server_url() + offer.path}, + {"mayRead", offer.access != AccessLevel::None}, + {"mayWrite", offer.access == AccessLevel::Write || offer.access == AccessLevel::Admin}, + {"mayManage", offer.access == AccessLevel::Admin}, + }; + perform_async_operation("PermissionOffer", + std::move(user), + make_handler_extracting_property("token", std::move(callback)), + std::move(props), + make_config); +} + +void Permissions::accept_offer(std::shared_ptr user, + const std::string& token, + PermissionOfferCallback callback, + const ConfigMaker& make_config) +{ + perform_async_operation("PermissionOfferResponse", + std::move(user), + make_handler_extracting_property("realmUrl", std::move(callback)), + AnyDict{ {"token", token} }, + make_config); +} + +void Permissions::perform_async_operation(const std::string& object_type, + std::shared_ptr user, + AsyncOperationHandler handler, + AnyDict additional_props, + const ConfigMaker& make_config) +{; + auto realm = Permissions::management_realm(std::move(user), make_config); + CppContext context; + + // Get the current time. + int64_t ns_since_epoch = ns_since_unix_epoch(system_clock::now()); + int64_t s_arg = ns_since_epoch / (int64_t)Timestamp::nanoseconds_per_second; + int32_t ns_arg = ns_since_epoch % Timestamp::nanoseconds_per_second; + + auto props = AnyDict{ + {"id", util::uuid_string()}, + {"createdAt", Timestamp(s_arg, ns_arg)}, + {"updatedAt", Timestamp(s_arg, ns_arg)}, + }; + props.insert(additional_props.begin(), additional_props.end()); + + // Write the permission object. + realm->begin_transaction(); + auto raw = Object::create(context, realm, *realm->schema().find(object_type), std::move(props), false); + auto object = std::make_shared<_impl::NotificationWrapper>(std::move(raw)); + realm->commit_transaction(); + + // Observe the permission object until the permission change has been processed or failed. + // The notifier is automatically unregistered upon the completion of the permission + // change, one way or another. + auto block = [object, handler=std::move(handler)](CollectionChangeSet, std::exception_ptr ex) mutable { + if (ex) { + handler(nullptr, ex); + object.reset(); + return; + } + + CppContext context; + auto status_code = object->get_property_value(context, "statusCode"); + if (!status_code.has_value()) { + // Continue waiting for the sync server to complete the operation. + return; + } + + // Determine whether an error happened or not. + if (auto code = any_cast(status_code)) { + // The permission change failed because an error was returned from the server. + auto status = object->get_property_value(context, "statusMessage"); + std::string error_str = (status.has_value() + ? any_cast(status) + : util::format("Error code: %1", code)); + handler(nullptr, std::make_exception_ptr(PermissionActionException(error_str, code))); + } + else { + handler(object.get(), nullptr); + } + object.reset(); + }; + object->add_notification_callback(std::move(block)); +} + +SharedRealm Permissions::management_realm(std::shared_ptr user, const ConfigMaker& make_config) +{ + // FIXME: maybe we should cache the management Realm on the user, so we don't need to open it every time. + const auto realm_url = util::format("realm%1/~/__management", user->server_url().substr(4)); + Realm::Config config = make_config(user, std::move(realm_url)); + config.sync_config->stop_policy = SyncSessionStopPolicy::Immediately; + config.schema = Schema{ + {"PermissionChange", { + Property{"id", PropertyType::String, Property::IsPrimary{true}}, + Property{"createdAt", PropertyType::Date}, + Property{"updatedAt", PropertyType::Date}, + Property{"statusCode", PropertyType::Int|PropertyType::Nullable}, + Property{"statusMessage", PropertyType::String|PropertyType::Nullable}, + Property{"userId", PropertyType::String}, + Property{"metadataKey", PropertyType::String|PropertyType::Nullable}, + Property{"metadataValue", PropertyType::String|PropertyType::Nullable}, + Property{"metadataNameSpace", PropertyType::String|PropertyType::Nullable}, + Property{"realmUrl", PropertyType::String}, + Property{"mayRead", PropertyType::Bool|PropertyType::Nullable}, + Property{"mayWrite", PropertyType::Bool|PropertyType::Nullable}, + Property{"mayManage", PropertyType::Bool|PropertyType::Nullable}, + }}, + {"PermissionOffer", { + Property{"id", PropertyType::String, Property::IsPrimary{true}}, + Property{"createdAt", PropertyType::Date}, + Property{"updatedAt", PropertyType::Date}, + Property{"expiresAt", PropertyType::Date|PropertyType::Nullable}, + Property{"statusCode", PropertyType::Int|PropertyType::Nullable}, + Property{"statusMessage", PropertyType::String|PropertyType::Nullable}, + Property{"token", PropertyType::String|PropertyType::Nullable}, + Property{"realmUrl", PropertyType::String}, + Property{"mayRead", PropertyType::Bool}, + Property{"mayWrite", PropertyType::Bool}, + Property{"mayManage", PropertyType::Bool}, + }}, + {"PermissionOfferResponse", { + Property{"id", PropertyType::String, Property::IsPrimary{true}}, + Property{"createdAt", PropertyType::Date}, + Property{"updatedAt", PropertyType::Date}, + Property{"statusCode", PropertyType::Int|PropertyType::Nullable}, + Property{"statusMessage", PropertyType::String|PropertyType::Nullable}, + Property{"token", PropertyType::String}, + Property{"realmUrl", PropertyType::String|PropertyType::Nullable}, + }}, + }; + config.schema_version = 0; + auto shared_realm = Realm::get_shared_realm(std::move(config)); + user->register_management_session(shared_realm->config().path); + return shared_realm; +} + +SharedRealm Permissions::permission_realm(std::shared_ptr user, const ConfigMaker& make_config) +{ + // FIXME: maybe we should cache the permission Realm on the user, so we don't need to open it every time. + const auto realm_url = util::format("realm%1/~/__permission", user->server_url().substr(4)); + Realm::Config config = make_config(user, std::move(realm_url)); + config.sync_config->stop_policy = SyncSessionStopPolicy::Immediately; + config.schema = Schema{ + {"Permission", { + {"updatedAt", PropertyType::Date}, + {"userId", PropertyType::String}, + {"path", PropertyType::String}, + {"mayRead", PropertyType::Bool}, + {"mayWrite", PropertyType::Bool}, + {"mayManage", PropertyType::Bool}, + }} + }; + config.schema_version = 0; + auto shared_realm = Realm::get_shared_realm(std::move(config)); + user->register_permission_session(shared_realm->config().path); + return shared_realm; +} diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp new file mode 100644 index 0000000000..288362b916 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp @@ -0,0 +1,1029 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/sync_session.hpp" + +#include "sync/impl/sync_client.hpp" +#include "sync/impl/sync_file.hpp" +#include "sync/impl/sync_metadata.hpp" +#include "sync/sync_manager.hpp" +#include "sync/sync_user.hpp" + +#include +#include + +using namespace realm; +using namespace realm::_impl; +using namespace realm::_impl::sync_session_states; + +using SessionWaiterPointer = void(sync::Session::*)(std::function); + +constexpr const char SyncError::c_original_file_path_key[]; +constexpr const char SyncError::c_recovery_file_path_key[]; + +/// A state which a `SyncSession` can currently be within. State classes handle various actions +/// and state transitions. +/// +/// STATES: +/// +/// WAITING_FOR_ACCESS_TOKEN: upon entering this state, the binding is informed +/// that the session wants an access token. The session is now waiting for the +/// binding to provide the token. +/// From: INACTIVE +/// To: +/// * ACTIVE: when the binding successfully refreshes the token +/// * INACTIVE: if asked to log out, or if asked to close and the stop policy +/// is Immediate. +/// +/// ACTIVE: the session is connected to the Realm Object Server and is actively +/// transferring data. +/// From: WAITING_FOR_ACCESS_TOKEN, DYING +/// To: +/// * WAITING_FOR_ACCESS_TOKEN: if the session is informed (through the error +/// handler) that the token expired +/// * INACTIVE: if asked to log out, or if asked to close and the stop policy +/// is Immediate. +/// * DYING: if asked to close and the stop policy is AfterChangesUploaded +/// +/// DYING: the session is performing clean-up work in preparation to be destroyed. +/// From: ACTIVE +/// To: +/// * INACTIVE: when the clean-up work completes, if the session wasn't +/// revived, or if explicitly asked to log out before the +/// clean-up work begins +/// * ACTIVE: if the session is revived +/// +/// INACTIVE: the user owning this session has logged out, the `sync::Session` +/// owned by this session is destroyed, and the session is quiescent. +/// Note that a session briefly enters this state before being destroyed, but +/// it can also enter this state and stay there if the user has been logged out. +/// From: initial, WAITING_FOR_ACCESS_TOKEN, ACTIVE, DYING +/// To: +/// * WAITING_FOR_ACCESS_TOKEN: if the session is revived +/// +struct SyncSession::State { + virtual ~State() { } + + // Move the given session into this state. All state transitions MUST be carried out through this method. + virtual void enter_state(std::unique_lock&, SyncSession&) const { } + + virtual void refresh_access_token(std::unique_lock&, + SyncSession&, std::string, + const util::Optional&) const { } + + // Returns true iff the lock is still locked when the method returns. + virtual bool access_token_expired(std::unique_lock&, SyncSession&) const { return true; } + + virtual void nonsync_transact_notify(std::unique_lock&, SyncSession&, sync::version_type) const { } + + // Perform any work needed to reactivate a session that is not already active. + // Returns true iff the session should ask the binding to get a token for `bind()`. + virtual bool revive_if_needed(std::unique_lock&, SyncSession&) const { return false; } + + // Perform any work needed to respond to the application regaining network connectivity. + virtual void handle_reconnect(std::unique_lock&, SyncSession&) const { }; + + // The user that owns this session has been logged out, and the session should take appropriate action. + virtual void log_out(std::unique_lock&, SyncSession&) const { } + + // The session should be closed and moved to `inactive`, in accordance with its stop policy and other state. + virtual void close(std::unique_lock&, SyncSession&) const { } + + // Returns true iff the error has been fully handled and the error handler should immediately return. + virtual bool handle_error(std::unique_lock&, SyncSession&, const SyncError&) const { return false; } + + // Register a handler to wait for sync session uploads, downloads, or synchronization. + // PRECONDITION: the session state lock must be held at the time this method is called, until after it returns. + // Returns true iff the handler was registered, either immediately or placed in a queue for later registration. + virtual bool wait_for_completion(SyncSession&, + std::function, + SessionWaiterPointer) const { + return false; + } + + virtual void override_server(std::unique_lock&, SyncSession&, std::string, int) const { } + + static const State& waiting_for_access_token; + static const State& active; + static const State& dying; + static const State& inactive; +}; + +struct sync_session_states::WaitingForAccessToken : public SyncSession::State { + void enter_state(std::unique_lock&, SyncSession& session) const override + { + session.m_deferred_close = false; + } + + void refresh_access_token(std::unique_lock& lock, SyncSession& session, + std::string access_token, + const util::Optional& server_url) const override + { + session.create_sync_session(); + + // Since the sync session was previously unbound, it's safe to do this from the + // calling thread. + if (!session.m_server_url) { + session.m_server_url = server_url; + } + if (session.m_session_has_been_bound) { + session.m_session->refresh(std::move(access_token)); + session.m_session->cancel_reconnect_delay(); + } else { + session.m_session->bind(*session.m_server_url, std::move(access_token)); + session.m_session_has_been_bound = true; + } + + if (session.m_server_override) + session.m_session->override_server(session.m_server_override->address, session.m_server_override->port); + + // Register all the pending wait-for-completion blocks. + for (auto& package : session.m_completion_wait_packages) { + (*session.m_session.*package.waiter)(std::move(package.callback)); + } + session.m_completion_wait_packages.clear(); + + // Handle any deferred commit notification. + if (session.m_deferred_commit_notification) { + session.m_session->nonsync_transact_notify(*session.m_deferred_commit_notification); + session.m_deferred_commit_notification = util::none; + } + + session.advance_state(lock, active); + if (session.m_deferred_close) { + session.m_state->close(lock, session); + } + } + + void log_out(std::unique_lock& lock, SyncSession& session) const override + { + session.advance_state(lock, inactive); + } + + bool revive_if_needed(std::unique_lock&, SyncSession& session) const override + { + session.m_deferred_close = false; + return false; + } + + void handle_reconnect(std::unique_lock& lock, SyncSession& session) const override + { + // Ask the binding to retry getting the token for this session. + std::shared_ptr session_ptr = session.shared_from_this(); + lock.unlock(); + session.m_config.bind_session_handler(session_ptr->m_realm_path, session_ptr->m_config, session_ptr); + } + + void nonsync_transact_notify(std::unique_lock&, + SyncSession& session, + sync::version_type version) const override + { + // Notify at first available opportunity. + session.m_deferred_commit_notification = version; + } + + void close(std::unique_lock& lock, SyncSession& session) const override + { + switch (session.m_config.stop_policy) { + case SyncSessionStopPolicy::Immediately: + // Immediately kill the session. + session.advance_state(lock, inactive); + break; + case SyncSessionStopPolicy::LiveIndefinitely: + case SyncSessionStopPolicy::AfterChangesUploaded: + // Defer handling closing the session until after the login response succeeds. + session.m_deferred_close = true; + break; + } + } + + bool wait_for_completion(SyncSession& session, + std::function callback, + SessionWaiterPointer waiter) const override + { + session.m_completion_wait_packages.push_back({ waiter, std::move(callback) }); + return true; + } + + void override_server(std::unique_lock&, SyncSession& session, + std::string address, int port) const override + { + session.m_server_override = SyncSession::ServerOverride{address, port}; + } +}; + +struct sync_session_states::Active : public SyncSession::State { + void refresh_access_token(std::unique_lock&, SyncSession& session, + std::string access_token, + const util::Optional&) const override + { + session.m_session->refresh(std::move(access_token)); + // Cancel the session's reconnection delay. This is important if the + // token is being refreshed as a response to a 202 (token expired) + // error, or similar non-fatal sync errors. + session.m_session->cancel_reconnect_delay(); + } + + bool access_token_expired(std::unique_lock& lock, SyncSession& session) const override + { + session.advance_state(lock, waiting_for_access_token); + std::shared_ptr session_ptr = session.shared_from_this(); + lock.unlock(); + session.m_config.bind_session_handler(session_ptr->m_realm_path, session_ptr->m_config, session_ptr); + return false; + } + + void log_out(std::unique_lock& lock, SyncSession& session) const override + { + session.advance_state(lock, inactive); + } + + void nonsync_transact_notify(std::unique_lock&, SyncSession& session, + sync::version_type version) const override + { + // Fully ready sync session, notify immediately. + session.m_session->nonsync_transact_notify(version); + } + + void close(std::unique_lock& lock, SyncSession& session) const override + { + switch (session.m_config.stop_policy) { + case SyncSessionStopPolicy::Immediately: + session.advance_state(lock, inactive); + break; + case SyncSessionStopPolicy::LiveIndefinitely: + // Don't do anything; session lives forever. + break; + case SyncSessionStopPolicy::AfterChangesUploaded: + // Wait for all pending changes to upload. + session.advance_state(lock, dying); + break; + } + } + + bool wait_for_completion(SyncSession& session, + std::function callback, + SessionWaiterPointer waiter) const override + { + REALM_ASSERT(session.m_session); + (*session.m_session.*waiter)(std::move(callback)); + return true; + } + + void handle_reconnect(std::unique_lock&, SyncSession& session) const override + { + session.m_session->cancel_reconnect_delay(); + } + + void override_server(std::unique_lock&, SyncSession& session, + std::string address, int port) const override + { + session.m_server_override = SyncSession::ServerOverride{address, port}; + session.m_session->override_server(address, port); + } +}; + +struct sync_session_states::Dying : public SyncSession::State { + void enter_state(std::unique_lock& lock, SyncSession& session) const override + { + // If we have no session, we cannot possibly upload anything. + if (!session.m_session) { + session.advance_state(lock, inactive); + return; + } + + size_t current_death_count = ++session.m_death_count; + std::weak_ptr weak_session = session.shared_from_this(); + session.m_session->async_wait_for_upload_completion([weak_session, current_death_count](std::error_code) { + if (auto session = weak_session.lock()) { + std::unique_lock lock(session->m_state_mutex); + if (session->m_state == &State::dying && session->m_death_count == current_death_count) { + session->advance_state(lock, inactive); + } + } + }); + } + + bool handle_error(std::unique_lock& lock, SyncSession& session, const SyncError& error) const override + { + if (error.is_fatal) { + session.advance_state(lock, inactive); + } + // If the error isn't fatal, don't change state, but don't + // allow it to be reported either. + // FIXME: What if the token expires while a session is dying? + // Should we allow the token to be refreshed so that changes + // can finish being uploaded? + return true; + } + + bool revive_if_needed(std::unique_lock& lock, SyncSession& session) const override + { + // Revive. + session.advance_state(lock, active); + return false; + } + + void log_out(std::unique_lock& lock, SyncSession& session) const override + { + session.advance_state(lock, inactive); + } + + bool wait_for_completion(SyncSession& session, + std::function callback, + SessionWaiterPointer waiter) const override + { + REALM_ASSERT(session.m_session); + (*session.m_session.*waiter)(std::move(callback)); + return true; + } + + void override_server(std::unique_lock&, SyncSession& session, + std::string address, int port) const override + { + session.m_server_override = SyncSession::ServerOverride{address, port}; + session.m_session->override_server(address, port); + } +}; + +struct sync_session_states::Inactive : public SyncSession::State { + void enter_state(std::unique_lock& lock, SyncSession& session) const override + { + auto completion_wait_packages = std::move(session.m_completion_wait_packages); + session.m_completion_wait_packages.clear(); + session.m_session = nullptr; + session.unregister(lock); // releases lock + + // Send notifications after releasing the lock to prevent deadlocks in the callback. + + // Manually set the disconnected state. Sync would also do this, but since the underlying SyncSession object + // already have been destroyed, we are not able to get the callback. + SyncSession::ConnectionState old_state = session.connection_state(); + session.m_connection_state = realm::sync::Session::ConnectionState::disconnected; + SyncSession::ConnectionState new_state = session.connection_state(); + if (old_state != new_state) { + session.m_connection_change_notifier.invoke_callbacks(old_state, session.connection_state()); + } + + // Inform any queued-up completion handlers that they were cancelled. + for (auto& package : completion_wait_packages) + package.callback(util::error::operation_aborted); + } + + bool revive_if_needed(std::unique_lock& lock, SyncSession& session) const override + { + session.advance_state(lock, waiting_for_access_token); + return true; + } + + bool wait_for_completion(SyncSession& session, + std::function callback, + SessionWaiterPointer waiter) const override + { + session.m_completion_wait_packages.push_back({ waiter, std::move(callback) }); + return true; + } + + void override_server(std::unique_lock&, SyncSession& session, + std::string address, int port) const override + { + session.m_server_override = SyncSession::ServerOverride{address, port}; + } +}; + + +const SyncSession::State& SyncSession::State::waiting_for_access_token = WaitingForAccessToken(); +const SyncSession::State& SyncSession::State::active = Active(); +const SyncSession::State& SyncSession::State::dying = Dying(); +const SyncSession::State& SyncSession::State::inactive = Inactive(); + +SyncSession::SyncSession(SyncClient& client, std::string realm_path, SyncConfig config) +: m_state(&State::inactive) +, m_config(std::move(config)) +, m_realm_path(std::move(realm_path)) +, m_client(client) +{ + // Sync history validation ensures that the history within the Realm file is in a format that can be used + // by the version of realm-sync that we're using. Validation is enabled by default when the binding manually + // opens a sync session (via `SyncManager::get_session`), but is disabled when the sync session is opened + // as a side effect of opening a `Realm`. In that case, the sync history has already been validated by the + // act of opening the `Realm` so it's not necessary to repeat it here. + if (m_config.validate_sync_history) { + Realm::Config realm_config; + realm_config.path = m_realm_path; + realm_config.schema_mode = SchemaMode::Additive; + realm_config.force_sync_history = true; + realm_config.cache = false; + + if (m_config.realm_encryption_key) { + realm_config.encryption_key.resize(64); + std::copy(m_config.realm_encryption_key->begin(), m_config.realm_encryption_key->end(), + realm_config.encryption_key.begin()); + } + + // FIXME: Opening a Realm only to discard it is relatively expensive. It may be preferable to have + // realm-sync open the Realm when the `sync::Session` is created since it can continue to use it. + Realm::get_shared_realm(realm_config); // Throws + } +} + +std::string SyncSession::get_recovery_file_path() +{ + return util::reserve_unique_file_name(SyncManager::shared().recovery_directory_path(), + util::create_timestamped_template("recovered_realm")); +} + +void SyncSession::update_error_and_mark_file_for_deletion(SyncError& error, ShouldBackup should_backup) +{ + // Add a SyncFileActionMetadata marking the Realm as needing to be deleted. + std::string recovery_path; + auto original_path = path(); + error.user_info[SyncError::c_original_file_path_key] = original_path; + if (should_backup == ShouldBackup::yes) { + recovery_path = get_recovery_file_path(); + error.user_info[SyncError::c_recovery_file_path_key] = recovery_path; + } + using Action = SyncFileActionMetadata::Action; + auto action = should_backup == ShouldBackup::yes ? Action::BackUpThenDeleteRealm : Action::DeleteRealm; + SyncManager::shared().perform_metadata_update([this, + action, + original_path=std::move(original_path), + recovery_path=std::move(recovery_path)](const auto& manager) { + manager.make_file_action_metadata(original_path, m_config.realm_url(), m_config.user->identity(), + action, std::move(recovery_path)); + }); +} + +// This method should only be called from within the error handler callback registered upon the underlying `m_session`. +void SyncSession::handle_error(SyncError error) +{ + enum class NextStateAfterError { none, inactive, error }; + auto next_state = error.is_fatal ? NextStateAfterError::error : NextStateAfterError::none; + auto error_code = error.error_code; + + { + // See if the current state wishes to take responsibility for handling the error. + std::unique_lock lock(m_state_mutex); + if (m_state->handle_error(lock, *this, error)) { + return; + } + } + + if (error_code.category() == realm::sync::protocol_error_category()) { + using ProtocolError = realm::sync::ProtocolError; + switch (static_cast(error_code.value())) { + // Connection level errors + case ProtocolError::connection_closed: + case ProtocolError::other_error: + // Not real errors, don't need to be reported to the binding. + return; + case ProtocolError::unknown_message: + case ProtocolError::bad_syntax: + case ProtocolError::limits_exceeded: + case ProtocolError::wrong_protocol_version: + case ProtocolError::bad_session_ident: + case ProtocolError::reuse_of_session_ident: + case ProtocolError::bound_in_other_session: + case ProtocolError::bad_message_order: + case ProtocolError::bad_client_version: + case ProtocolError::illegal_realm_path: + case ProtocolError::no_such_realm: + case ProtocolError::bad_changeset: + case ProtocolError::bad_changeset_header_syntax: + case ProtocolError::bad_changeset_size: + case ProtocolError::bad_changesets: + case ProtocolError::bad_decompression: + case ProtocolError::partial_sync_disabled: + case ProtocolError::unsupported_session_feature: + break; + // Session errors + case ProtocolError::session_closed: + case ProtocolError::other_session_error: + case ProtocolError::disabled_session: + // The binding doesn't need to be aware of these because they are strictly informational, and do not + // represent actual errors. + return; + case ProtocolError::token_expired: { + std::unique_lock lock(m_state_mutex); + // This isn't an error from the binding's point of view. If we're connected we'll + // simply ask the binding to log in again. + m_state->access_token_expired(lock, *this); + return; + } + case ProtocolError::bad_authentication: { + std::shared_ptr user_to_invalidate; + next_state = NextStateAfterError::none; + { + std::unique_lock lock(m_state_mutex); + user_to_invalidate = user(); + cancel_pending_waits(lock); + } + if (user_to_invalidate) + user_to_invalidate->invalidate(); + break; + } + case ProtocolError::permission_denied: { + next_state = NextStateAfterError::inactive; + update_error_and_mark_file_for_deletion(error, ShouldBackup::no); + break; + } + case ProtocolError::bad_origin_file_ident: + case ProtocolError::bad_server_file_ident: + case ProtocolError::bad_client_file_ident: + case ProtocolError::bad_server_version: + case ProtocolError::diverging_histories: + next_state = NextStateAfterError::inactive; + update_error_and_mark_file_for_deletion(error, ShouldBackup::yes); + break; + } + } else if (error_code.category() == realm::sync::client_error_category()) { + using ClientError = realm::sync::Client::Error; + switch (static_cast(error_code.value())) { + case ClientError::connection_closed: + case ClientError::pong_timeout: + // Not real errors, don't need to be reported to the binding. + return; + case ClientError::bad_timestamp: + case ClientError::connect_timeout: + case ClientError::unknown_message: + case ClientError::bad_syntax: + case ClientError::limits_exceeded: + case ClientError::bad_session_ident: + case ClientError::bad_message_order: + case ClientError::bad_progress: + case ClientError::bad_changeset_header_syntax: + case ClientError::bad_changeset_size: + case ClientError::bad_origin_file_ident: + case ClientError::bad_server_version: + case ClientError::bad_changeset: + case ClientError::bad_request_ident: + case ClientError::bad_error_code: + case ClientError::bad_compression: + case ClientError::bad_client_version: + case ClientError::ssl_server_cert_rejected: + case ClientError::bad_file_ident: + case ClientError::bad_client_file_ident: + case ClientError::bad_client_file_ident_salt: + // Don't do anything special for these errors. + // Future functionality may require special-case handling for existing + // errors, or newly introduced error codes. + break; + } + } else { + // Unrecognized error code. + error.is_unrecognized_by_client = true; + } + switch (next_state) { + case NextStateAfterError::none: + break; + case NextStateAfterError::inactive: { + std::unique_lock lock(m_state_mutex); + advance_state(lock, State::inactive); + break; + } + case NextStateAfterError::error: { + std::unique_lock lock(m_state_mutex); + cancel_pending_waits(lock); + break; + } + } + if (m_config.error_handler) { + m_config.error_handler(shared_from_this(), std::move(error)); + } +} + +void SyncSession::cancel_pending_waits(std::unique_lock& lock) +{ + auto packages = std::move(m_completion_wait_packages); + lock.unlock(); + + // Inform any queued-up completion handlers that they were cancelled. + for (auto& package : packages) { + package.callback(util::error::operation_aborted); + } +} + +void SyncSession::handle_progress_update(uint64_t downloaded, uint64_t downloadable, + uint64_t uploaded, uint64_t uploadable, + uint64_t download_version, uint64_t snapshot_version) +{ + m_progress_notifier.update(downloaded, downloadable, uploaded, uploadable, download_version, snapshot_version); +} + +void SyncSession::create_sync_session() +{ + if (m_session) + return; + + sync::Session::Config session_config; + session_config.changeset_cooker = m_config.transformer; + session_config.encryption_key = m_config.realm_encryption_key; + session_config.verify_servers_ssl_certificate = m_config.client_validate_ssl; + session_config.ssl_trust_certificate_path = m_config.ssl_trust_certificate_path; + session_config.ssl_verify_callback = m_config.ssl_verify_callback; + session_config.multiplex_ident = m_multiplex_identity; + + if (m_config.authorization_header_name) { + session_config.authorization_header_name = *m_config.authorization_header_name; + } + session_config.custom_http_headers = m_config.custom_http_headers; + + if (m_config.url_prefix) { + session_config.url_prefix = *m_config.url_prefix; + } + + m_session = m_client.make_session(m_realm_path, std::move(session_config)); + + // The next time we get a token, call `bind()` instead of `refresh()`. + m_session_has_been_bound = false; + + std::weak_ptr weak_self = shared_from_this(); + + // Configure the sync transaction callback. + auto wrapped_callback = [this, weak_self](VersionID old_version, VersionID new_version) { + if (auto self = weak_self.lock()) { + if (m_sync_transact_callback) { + m_sync_transact_callback(old_version, new_version); + } + } + }; + m_session->set_sync_transact_callback(std::move(wrapped_callback)); + + // Set up the wrapped progress handler callback + m_session->set_progress_handler([weak_self](uint_fast64_t downloaded, uint_fast64_t downloadable, + uint_fast64_t uploaded, uint_fast64_t uploadable, + uint_fast64_t progress_version, uint_fast64_t snapshot_version) { + if (auto self = weak_self.lock()) { + self->handle_progress_update(downloaded, downloadable, uploaded, + uploadable, progress_version, snapshot_version); + } + }); + + // Sets up the connection state listener. This callback is used for both reporting errors as well as changes to the + // connection state. + m_session->set_connection_state_change_listener([weak_self](realm::sync::Session::ConnectionState state, const realm::sync::Session::ErrorInfo* error) { + // If the OS SyncSession object is destroyed, we ignore any events from the underlying Session as there is + // nothing useful we can do with them. + if (auto self = weak_self.lock()) { + ConnectionState last_state = self->connection_state(); + self->m_connection_state = state; + ConnectionState new_state = self->connection_state(); + self->m_connection_change_notifier.invoke_callbacks(last_state, new_state); + if (error) { + self->handle_error(SyncError{error->error_code, std::move(error->detailed_message), error->is_fatal}); + } + } + }); +} + +void SyncSession::set_sync_transact_callback(std::function callback) +{ + m_sync_transact_callback = std::move(callback); +} + +void SyncSession::advance_state(std::unique_lock& lock, const State& state) +{ + REALM_ASSERT(lock.owns_lock()); + REALM_ASSERT(&state != m_state); + m_state = &state; + m_state->enter_state(lock, *this); +} + +void SyncSession::nonsync_transact_notify(sync::version_type version) +{ + m_progress_notifier.set_local_version(version); + + std::unique_lock lock(m_state_mutex); + m_state->nonsync_transact_notify(lock, *this, version); +} + +void SyncSession::revive_if_needed() +{ + util::Optional&> handler; + { + std::unique_lock lock(m_state_mutex); + if (m_state->revive_if_needed(lock, *this)) + handler = m_config.bind_session_handler; + } + if (handler) + handler.value()(m_realm_path, m_config, shared_from_this()); +} + +void SyncSession::handle_reconnect() +{ + std::unique_lock lock(m_state_mutex); + m_state->handle_reconnect(lock, *this); +} + +void SyncSession::log_out() +{ + std::unique_lock lock(m_state_mutex); + m_state->log_out(lock, *this); +} + +void SyncSession::close() +{ + std::unique_lock lock(m_state_mutex); + m_state->close(lock, *this); +} + +void SyncSession::unregister(std::unique_lock& lock) +{ + REALM_ASSERT(lock.owns_lock()); + REALM_ASSERT(m_state == &State::inactive); // Must stop an active session before unregistering. + + lock.unlock(); + SyncManager::shared().unregister_session(m_realm_path); +} + +bool SyncSession::wait_for_upload_completion(std::function callback) +{ + std::unique_lock lock(m_state_mutex); + return m_state->wait_for_completion(*this, std::move(callback), &sync::Session::async_wait_for_upload_completion); +} + +bool SyncSession::wait_for_download_completion(std::function callback) +{ + std::unique_lock lock(m_state_mutex); + return m_state->wait_for_completion(*this, std::move(callback), &sync::Session::async_wait_for_download_completion); +} + +uint64_t SyncSession::register_progress_notifier(std::function notifier, + NotifierType direction, bool is_streaming) +{ + return m_progress_notifier.register_callback(std::move(notifier), direction, is_streaming); +} + +void SyncSession::unregister_progress_notifier(uint64_t token) +{ + m_progress_notifier.unregister_callback(token); +} + +uint64_t SyncSession::register_connection_change_callback(std::function callback) +{ + return m_connection_change_notifier.add_callback(callback); +} + +void SyncSession::unregister_connection_change_callback(uint64_t token) +{ + m_connection_change_notifier.remove_callback(token); +} + +void SyncSession::refresh_access_token(std::string access_token, util::Optional server_url) +{ + std::unique_lock lock(m_state_mutex); + if (!m_server_url && !server_url) { + // The first time this method is called, the server URL must be provided. + return; + } + m_state->refresh_access_token(lock, *this, std::move(access_token), server_url); +} + +void SyncSession::override_server(std::string address, int port) +{ + std::unique_lock lock(m_state_mutex); + m_state->override_server(lock, *this, std::move(address), port); +} + +void SyncSession::set_multiplex_identifier(std::string multiplex_identity) +{ + m_multiplex_identity = std::move(multiplex_identity); +} + + +SyncSession::PublicState SyncSession::get_public_state() const +{ + if (m_state == nullptr) { + return PublicState::Inactive; + } else if (m_state == &State::waiting_for_access_token) { + return PublicState::WaitingForAccessToken; + } else if (m_state == &State::active) { + return PublicState::Active; + } else if (m_state == &State::dying) { + return PublicState::Dying; + } else if (m_state == &State::inactive) { + return PublicState::Inactive; + } + REALM_UNREACHABLE(); +} + + +SyncSession::PublicState SyncSession::state() const +{ + std::unique_lock lock(m_state_mutex); + return get_public_state(); +} + +SyncSession::ConnectionState SyncSession::connection_state() const +{ + switch (m_connection_state) { + case realm::sync::Session::ConnectionState::disconnected: return ConnectionState::Disconnected; + case realm::sync::Session::ConnectionState::connecting: return ConnectionState::Connecting; + case realm::sync::Session::ConnectionState::connected: return ConnectionState::Connected; + default: + REALM_UNREACHABLE(); + } +} + +// Represents a reference to the SyncSession from outside of the sync subsystem. +// We attempt to keep the SyncSession in an active state as long as it has an external reference. +class SyncSession::ExternalReference { +public: + ExternalReference(std::shared_ptr session) : m_session(std::move(session)) + {} + + ~ExternalReference() + { + m_session->did_drop_external_reference(); + } + +private: + std::shared_ptr m_session; +}; + +std::shared_ptr SyncSession::external_reference() +{ + std::unique_lock lock(m_state_mutex); + + if (auto external_reference = m_external_reference.lock()) + return std::shared_ptr(external_reference, this); + + auto external_reference = std::make_shared(shared_from_this()); + m_external_reference = external_reference; + return std::shared_ptr(external_reference, this); +} + +std::shared_ptr SyncSession::existing_external_reference() +{ + std::unique_lock lock(m_state_mutex); + + if (auto external_reference = m_external_reference.lock()) + return std::shared_ptr(external_reference, this); + + return nullptr; +} + +void SyncSession::did_drop_external_reference() +{ + std::unique_lock lock(m_state_mutex); + + // If the session is being resurrected we should not close the session. + if (!m_external_reference.expired()) + return; + + m_state->close(lock, *this); +} + +uint64_t SyncProgressNotifier::register_callback(std::function notifier, + NotifierType direction, bool is_streaming) +{ + std::function invocation; + uint64_t token_value = 0; + { + std::lock_guard lock(m_mutex); + token_value = m_progress_notifier_token++; + NotifierPackage package{std::move(notifier), util::none, m_local_transaction_version, + is_streaming, direction == NotifierType::download}; + if (!m_current_progress) { + // Simply register the package, since we have no data yet. + m_packages.emplace(token_value, std::move(package)); + return token_value; + } + bool skip_registration = false; + invocation = package.create_invocation(*m_current_progress, skip_registration); + if (skip_registration) { + token_value = 0; + } else { + m_packages.emplace(token_value, std::move(package)); + } + } + invocation(); + return token_value; +} + +void SyncProgressNotifier::unregister_callback(uint64_t token) +{ + std::lock_guard lock(m_mutex); + m_packages.erase(token); +} + +void SyncProgressNotifier::update(uint64_t downloaded, uint64_t downloadable, + uint64_t uploaded, uint64_t uploadable, + uint64_t download_version, uint64_t snapshot_version) +{ + // Ignore progress messages from before we first receive a DOWNLOAD message + if (download_version == 0) + return; + + std::vector> invocations; + { + std::lock_guard lock(m_mutex); + m_current_progress = Progress{uploadable, downloadable, uploaded, downloaded, snapshot_version}; + + for (auto it = m_packages.begin(); it != m_packages.end(); ) { + bool should_delete = false; + invocations.emplace_back(it->second.create_invocation(*m_current_progress, should_delete)); + it = should_delete ? m_packages.erase(it) : std::next(it); + } + } + // Run the notifiers only after we've released the lock. + for (auto& invocation : invocations) + invocation(); +} + +void SyncProgressNotifier::set_local_version(uint64_t snapshot_version) +{ + std::lock_guard lock(m_mutex); + m_local_transaction_version = snapshot_version; +} + +std::function SyncProgressNotifier::NotifierPackage::create_invocation(Progress const& current_progress, bool& is_expired) +{ + uint64_t transferrable; + if (is_streaming) { + transferrable = is_download ? current_progress.downloadable : current_progress.uploadable; + } + else if (captured_transferrable) { + transferrable = *captured_transferrable; + } + else { + if (is_download) + captured_transferrable = current_progress.downloadable; + else { + // If the sync client has not yet processed all of the local + // transactions then the uploadable data is incorrect and we should + // not invoke the callback + if (snapshot_version > current_progress.snapshot_version) + return []{}; + captured_transferrable = current_progress.uploadable; + } + transferrable = *captured_transferrable; + } + + uint64_t transferred = is_download ? current_progress.downloaded : current_progress.uploaded; + // A notifier is expired if at least as many bytes have been transferred + // as were originally considered transferrable. + is_expired = !is_streaming && transferred >= transferrable; + return [=, notifier=notifier] { notifier(transferred, transferrable); }; +} + +uint64_t SyncSession::ConnectionChangeNotifier::add_callback(std::function callback) +{ + std::lock_guard lock(m_callback_mutex); + auto token = m_next_token++; + m_callbacks.push_back({std::move(callback), token}); + return token; +} + +void SyncSession::ConnectionChangeNotifier::remove_callback(uint64_t token) +{ + Callback old; + { + std::lock_guard lock(m_callback_mutex); + auto it = find_if(begin(m_callbacks), end(m_callbacks), + [=](const auto& c) { return c.token == token; }); + if (it == end(m_callbacks)) { + return; + } + + size_t idx = distance(begin(m_callbacks), it); + if (m_callback_index != npos) { + if (m_callback_index >= idx) + --m_callback_index; + } + --m_callback_count; + + old = std::move(*it); + m_callbacks.erase(it); + } +} + +void SyncSession::ConnectionChangeNotifier::invoke_callbacks(ConnectionState old_state, ConnectionState new_state) +{ + std::unique_lock lock(m_callback_mutex); + m_callback_count = m_callbacks.size(); + for (++m_callback_index; m_callback_index < m_callback_count; ++m_callback_index) { + // acquire a local reference to the callback so that removing the + // callback from within it can't result in a dangling pointer + auto cb = m_callbacks[m_callback_index].fn; + lock.unlock(); + cb(old_state, new_state); + lock.lock(); + } + m_callback_index = npos; +} diff --git a/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp b/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp new file mode 100644 index 0000000000..b06dcde435 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp @@ -0,0 +1,263 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "sync/sync_user.hpp" + +#include "sync/impl/sync_metadata.hpp" +#include "sync/sync_manager.hpp" +#include "sync/sync_session.hpp" + +namespace realm { + +SyncUserContextFactory SyncUser::s_binding_context_factory; +std::mutex SyncUser::s_binding_context_factory_mutex; + +SyncUser::SyncUser(std::string refresh_token, + std::string identity, + util::Optional server_url, + util::Optional local_identity, + TokenType token_type) +: m_state(State::Active) +, m_server_url(server_url.value_or("")) +, m_token_type(token_type) +, m_refresh_token(std::move(refresh_token)) +, m_identity(std::move(identity)) +{ + { + std::lock_guard lock(s_binding_context_factory_mutex); + if (s_binding_context_factory) { + m_binding_context = s_binding_context_factory(); + } + } + if (token_type == TokenType::Normal) { + REALM_ASSERT(m_server_url.length() > 0); + bool updated = SyncManager::shared().perform_metadata_update([=](const auto& manager) { + auto metadata = manager.get_or_make_user_metadata(m_identity, m_server_url); + metadata->set_user_token(m_refresh_token); + m_is_admin = metadata->is_admin(); + m_local_identity = metadata->local_uuid(); + }); + if (!updated) + m_local_identity = m_identity; + } else { + // Admin token users. The local identity serves as the directory path. + REALM_ASSERT(local_identity); + m_local_identity = std::move(*local_identity); + } +} + +std::vector> SyncUser::all_sessions() +{ + std::lock_guard lock(m_mutex); + std::vector> sessions; + if (m_state == State::Error) { + return sessions; + } + for (auto it = m_sessions.begin(); it != m_sessions.end();) { + if (auto ptr_to_session = it->second.lock()) { + sessions.emplace_back(std::move(ptr_to_session)); + it++; + continue; + } + // This session is bad, destroy it. + it = m_sessions.erase(it); + } + return sessions; +} + +std::shared_ptr SyncUser::session_for_on_disk_path(const std::string& path) +{ + std::lock_guard lock(m_mutex); + if (m_state == State::Error) { + return nullptr; + } + auto it = m_sessions.find(path); + if (it == m_sessions.end()) { + return nullptr; + } + auto locked = it->second.lock(); + if (!locked) { + // Remove the session from the map, because it has fatally errored out or the entry is invalid. + m_sessions.erase(it); + } + return locked; +} + +void SyncUser::update_refresh_token(std::string token) +{ + std::vector> sessions_to_revive; + { + std::unique_lock lock(m_mutex); + if (auto session = m_management_session.lock()) + sessions_to_revive.emplace_back(std::move(session)); + + if (auto session = m_permission_session.lock()) + sessions_to_revive.emplace_back(std::move(session)); + + switch (m_state) { + case State::Error: + return; + case State::Active: + m_refresh_token = token; + break; + case State::LoggedOut: { + sessions_to_revive.reserve(m_waiting_sessions.size()); + m_refresh_token = token; + m_state = State::Active; + for (auto& pair : m_waiting_sessions) { + if (auto ptr = pair.second.lock()) { + m_sessions[pair.first] = ptr; + sessions_to_revive.emplace_back(std::move(ptr)); + } + } + m_waiting_sessions.clear(); + break; + } + } + // Update persistent user metadata. + if (m_token_type != TokenType::Admin) { + SyncManager::shared().perform_metadata_update([=](const auto& manager) { + auto metadata = manager.get_or_make_user_metadata(m_identity, m_server_url); + metadata->set_user_token(token); + }); + } + } + // (Re)activate all pending sessions. + // Note that we do this after releasing the lock, since the session may + // need to access protected User state in the process of binding itself. + for (auto& session : sessions_to_revive) { + session->revive_if_needed(); + } +} + +void SyncUser::log_out() +{ + if (m_token_type == TokenType::Admin) { + // Admin-token users cannot be logged out. + return; + } + std::lock_guard lock(m_mutex); + if (m_state == State::LoggedOut) { + return; + } + m_state = State::LoggedOut; + // Move all active sessions into the waiting sessions pool. If the user is + // logged back in, they will automatically be reactivated. + for (auto& pair : m_sessions) { + if (auto ptr = pair.second.lock()) { + ptr->log_out(); + m_waiting_sessions[pair.first] = ptr; + } + } + m_sessions.clear(); + // Deactivate the sessions for the management and admin Realms. + if (auto session = m_management_session.lock()) + session->log_out(); + + if (auto session = m_permission_session.lock()) + session->log_out(); + + // Mark the user as 'dead' in the persisted metadata Realm. + SyncManager::shared().perform_metadata_update([=](const auto& manager) { + auto metadata = manager.get_or_make_user_metadata(m_identity, m_server_url, false); + if (metadata) + metadata->mark_for_removal(); + }); +} + +void SyncUser::set_is_admin(bool is_admin) +{ + if (m_token_type == TokenType::Admin) { + return; + } + m_is_admin = is_admin; + SyncManager::shared().perform_metadata_update([=](const auto& manager) { + auto metadata = manager.get_or_make_user_metadata(m_identity, m_server_url); + metadata->set_is_admin(is_admin); + }); +} + +void SyncUser::invalidate() +{ + std::lock_guard lock(m_mutex); + m_state = State::Error; +} + +std::string SyncUser::refresh_token() const +{ + std::lock_guard lock(m_mutex); + return m_refresh_token; +} + +SyncUser::State SyncUser::state() const +{ + std::lock_guard lock(m_mutex); + return m_state; +} + +void SyncUser::register_session(std::shared_ptr session) +{ + const std::string& path = session->path(); + std::unique_lock lock(m_mutex); + switch (m_state) { + case State::Active: + // Immediately ask the session to come online. + m_sessions[path] = session; + lock.unlock(); + session->revive_if_needed(); + break; + case State::LoggedOut: + m_waiting_sessions[path] = session; + break; + case State::Error: + break; + } +} + +void SyncUser::set_binding_context_factory(SyncUserContextFactory factory) +{ + std::lock_guard lock(s_binding_context_factory_mutex); + s_binding_context_factory = std::move(factory); +} + +void SyncUser::register_management_session(const std::string& path) +{ + std::lock_guard lock(m_mutex); + if (m_management_session.lock() || m_state == State::Error) + return; + + m_management_session = SyncManager::shared().get_existing_session(path); +} + +void SyncUser::register_permission_session(const std::string& path) +{ + std::lock_guard lock(m_mutex); + if (m_permission_session.lock() || m_state == State::Error) + return; + + m_permission_session = SyncManager::shared().get_existing_session(path); +} + +} + +namespace std { +size_t hash::operator()(const realm::SyncUserIdentifier& k) const +{ + return ((hash()(k.user_id) ^ (hash()(k.auth_server_url) << 1)) >> 1); +} +} diff --git a/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp b/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp new file mode 100644 index 0000000000..9469d892a2 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp @@ -0,0 +1,123 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "thread_safe_reference.hpp" + +#include "impl/realm_coordinator.hpp" +#include "list.hpp" +#include "object.hpp" +#include "object_schema.hpp" +#include "results.hpp" + +#include + +using namespace realm; + +ThreadSafeReferenceBase::ThreadSafeReferenceBase(SharedRealm source_realm) : m_source_realm(std::move(source_realm)) +{ + m_source_realm->verify_thread(); + if (m_source_realm->is_in_transaction()) { + throw InvalidTransactionException("Cannot obtain thread safe reference during a write transaction."); + } + + try { + m_version_id = get_source_shared_group().pin_version(); + } catch (...) { + invalidate(); + throw; + } +} + +ThreadSafeReferenceBase::~ThreadSafeReferenceBase() +{ + if (!is_invalidated()) + invalidate(); +} + +template +V ThreadSafeReferenceBase::invalidate_after_import(Realm& destination_realm, T construct_with_shared_group) { + destination_realm.verify_thread(); + REALM_ASSERT_DEBUG(!m_source_realm->is_in_transaction()); + REALM_ASSERT_DEBUG(!is_invalidated()); + + SharedGroup& destination_shared_group = *Realm::Internal::get_shared_group(destination_realm); + auto unpin_version = util::make_scope_exit([&]() noexcept { invalidate(); }); + + return construct_with_shared_group(destination_shared_group); +} + +SharedGroup& ThreadSafeReferenceBase::get_source_shared_group() const { + return *Realm::Internal::get_shared_group(*m_source_realm); +} + +bool ThreadSafeReferenceBase::has_same_config(Realm& realm) const { + return &Realm::Internal::get_coordinator(*m_source_realm) == &Realm::Internal::get_coordinator(realm); +} + +void ThreadSafeReferenceBase::invalidate() { + REALM_ASSERT_DEBUG(m_source_realm); + SharedRealm thread_local_realm = Realm::Internal::get_coordinator(*m_source_realm).get_realm(); + Realm::Internal::get_shared_group(*thread_local_realm)->unpin_version(m_version_id); + m_source_realm = nullptr; +} + +ThreadSafeReference::ThreadSafeReference(List const& list) +: ThreadSafeReferenceBase(list.get_realm()) +, m_link_view(get_source_shared_group().export_linkview_for_handover(list.m_link_view)) +, m_table(get_source_shared_group().export_table_for_handover(list.m_table)) +{ } + +List ThreadSafeReference::import_into_realm(SharedRealm realm) && { + return invalidate_after_import(*realm, [&](SharedGroup& shared_group) { + if (auto link_view = shared_group.import_linkview_from_handover(std::move(m_link_view))) + return List(std::move(realm), std::move(link_view)); + return List(std::move(realm), shared_group.import_table_from_handover(std::move(m_table))); + }); +} + +ThreadSafeReference::ThreadSafeReference(Object const& object) +: ThreadSafeReferenceBase(object.realm()) +, m_row(get_source_shared_group().export_for_handover(Row(object.row()))) +, m_object_schema_name(object.get_object_schema().name) { } + +Object ThreadSafeReference::import_into_realm(SharedRealm realm) && { + return invalidate_after_import(*realm, [&](SharedGroup& shared_group) { + Row row = *shared_group.import_from_handover(std::move(m_row)); + auto object_schema = realm->schema().find(m_object_schema_name); + REALM_ASSERT_DEBUG(object_schema != realm->schema().end()); + return Object(std::move(realm), *object_schema, row); + }); +} + +ThreadSafeReference::ThreadSafeReference(Results const& results) +: ThreadSafeReferenceBase(results.get_realm()) +, m_query(get_source_shared_group().export_for_handover(results.get_query(), ConstSourcePayload::Copy)) +, m_ordering_patch([&]() { + DescriptorOrdering::HandoverPatch ordering_patch; + DescriptorOrdering::generate_patch(results.get_descriptor_ordering(), ordering_patch); + return ordering_patch; +}()){ } + +Results ThreadSafeReference::import_into_realm(SharedRealm realm) && { + return invalidate_after_import(*realm, [&](SharedGroup& shared_group) { + Query query = *shared_group.import_from_handover(std::move(m_query)); + Table& table = *query.get_table(); + DescriptorOrdering descriptors = DescriptorOrdering::create_from_and_consume_patch(m_ordering_patch, table); + return Results(std::move(realm), std::move(query), std::move(descriptors)); + }); +} diff --git a/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp b/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp new file mode 100644 index 0000000000..0110002265 --- /dev/null +++ b/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp @@ -0,0 +1,80 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#include "util/uuid.hpp" + +#include +#include +#include +#include +#include + +namespace { + +// Seed `engine` with as much random state as it requires, based on the approach outlined in P0205R0. +// +template +T create_and_seed_engine() +{ + constexpr auto bytes_needed = T::state_size * sizeof(typename T::result_type); + + constexpr auto numbers_needed = sizeof(std::random_device::result_type) < sizeof(std::seed_seq::result_type) + ? (bytes_needed / sizeof(std::random_device::result_type)) + : (bytes_needed / sizeof(std::seed_seq::result_type)); + + std::array state; + std::random_device rd; + std::generate(begin(state), end(state), std::ref(rd)); + std::seed_seq seeds(begin(state), end(state)); + + T engine; + engine.seed(seeds); + return engine; +} + +} // unnamed namespace + +namespace realm { +namespace util { + +std::string uuid_string() +{ + static auto engine = create_and_seed_engine(); + + std::array uuid_bytes; + std::uniform_int_distribution distribution(0, std::numeric_limits::max()); + std::generate(begin(uuid_bytes), end(uuid_bytes), [&] { return distribution(engine); }); + + // Version 4 UUID. + uuid_bytes[6] = (uuid_bytes[6] & 0x0f) | 0x40; + // IETF variant. + uuid_bytes[8] = (uuid_bytes[8] & 0x3f) | 0x80; + + std::array uuid_formatted; + snprintf(uuid_formatted.data(), uuid_formatted.size(), + "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", + uuid_bytes[0], uuid_bytes[1], uuid_bytes[2], uuid_bytes[3], + uuid_bytes[4], uuid_bytes[5], uuid_bytes[6], uuid_bytes[7], + uuid_bytes[8], uuid_bytes[9], uuid_bytes[10], uuid_bytes[11], + uuid_bytes[12], uuid_bytes[13], uuid_bytes[14], uuid_bytes[15]); + + return std::string(uuid_formatted.data(), uuid_formatted.size() - 1); +} + +} // namespace util +} // namespace realm diff --git a/Pods/Realm/Realm/RLMAccessor.mm b/Pods/Realm/Realm/RLMAccessor.mm new file mode 100644 index 0000000000..83b808d48b --- /dev/null +++ b/Pods/Realm/Realm/RLMAccessor.mm @@ -0,0 +1,811 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMAccessor.hpp" + +#import "RLMArray_Private.hpp" +#import "RLMListBase.h" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObjectStore.h" +#import "RLMObject_Private.hpp" +#import "RLMObservation.hpp" +#import "RLMProperty_Private.h" +#import "RLMRealm_Private.hpp" +#import "RLMResults_Private.hpp" +#import "RLMSchema_Private.h" +#import "RLMUtil.hpp" +#import "results.hpp" +#import "property.hpp" + +#import +#import +#import + +#pragma mark - Helper functions + +namespace { +template +T get(__unsafe_unretained RLMObjectBase *const obj, NSUInteger index) { + RLMVerifyAttached(obj); + return obj->_row.get(obj->_info->objectSchema->persisted_properties[index].table_column); +} + +template +id getBoxed(__unsafe_unretained RLMObjectBase *const obj, NSUInteger index) { + RLMVerifyAttached(obj); + auto& prop = obj->_info->objectSchema->persisted_properties[index]; + auto col = prop.table_column; + if (obj->_row.is_null(col)) { + return nil; + } + + RLMAccessorContext ctx(obj, &prop); + return ctx.box(obj->_row.get(col)); +} + +template +void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, T val) { + RLMVerifyInWriteTransaction(obj); + obj->_row.set(colIndex, val); +} + +template +auto translateError(Fn&& fn) { + try { + return fn(); + } + catch (std::exception const& e) { + @throw RLMException(e); + } +} + +void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, + __unsafe_unretained NSString *const val) { + RLMVerifyInWriteTransaction(obj); + translateError([&] { + obj->_row.set(colIndex, RLMStringDataWithNSString(val)); + }); +} + +[[gnu::noinline]] +void setNull(realm::Row& row, size_t col) { + translateError([&] { row.set_null(col); }); +} + +void setValue(__unsafe_unretained RLMObjectBase *const obj, + NSUInteger colIndex, __unsafe_unretained NSDate *const date) { + RLMVerifyInWriteTransaction(obj); + if (date) { + obj->_row.set(colIndex, RLMTimestampForNSDate(date)); + } + else { + setNull(obj->_row, colIndex); + } +} + +void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, + __unsafe_unretained NSData *const data) { + RLMVerifyInWriteTransaction(obj); + translateError([&] { + obj->_row.set(colIndex, RLMBinaryDataForNSData(data)); + }); +} + +void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, + __unsafe_unretained RLMObjectBase *const val) { + RLMVerifyInWriteTransaction(obj); + if (!val) { + obj->_row.nullify_link(colIndex); + return; + } + + RLMAddObjectToRealm(val, obj->_realm, false); + + // make sure it is the correct type + if (val->_row.get_table() != obj->_row.get_table()->get_link_target(colIndex)) { + @throw RLMException(@"Can't set object of type '%@' to property of type '%@'", + val->_objectSchema.className, + obj->_info->propertyForTableColumn(colIndex).objectClassName); + } + obj->_row.set_link(colIndex, val->_row.get_index()); +} + +// array getter/setter +RLMArray *getArray(__unsafe_unretained RLMObjectBase *const obj, NSUInteger propIndex) { + RLMVerifyAttached(obj); + auto prop = obj->_info->rlmObjectSchema.properties[propIndex]; + return [[RLMManagedArray alloc] initWithParent:obj property:prop]; +} + +void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, + __unsafe_unretained id const value) { + RLMVerifyInWriteTransaction(obj); + auto prop = obj->_info->propertyForTableColumn(colIndex); + RLMValidateValueForProperty(value, obj->_info->rlmObjectSchema, prop, true); + + realm::List list(obj->_realm->_realm, *obj->_row.get_table(), colIndex, obj->_row.get_index()); + RLMClassInfo *info = obj->_info; + if (list.get_type() == realm::PropertyType::Object) { + info = &obj->_info->linkTargetType(prop.index); + } + RLMAccessorContext ctx(obj->_realm, *info); + translateError([&] { list.assign(ctx, value, false); }); +} + +void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, + __unsafe_unretained NSNumber *const intObject) { + RLMVerifyInWriteTransaction(obj); + + if (intObject) { + obj->_row.set(colIndex, intObject.longLongValue); + } + else { + setNull(obj->_row, colIndex); + } +} + +void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, + __unsafe_unretained NSNumber *const floatObject) { + RLMVerifyInWriteTransaction(obj); + + if (floatObject) { + obj->_row.set(colIndex, floatObject.floatValue); + } + else { + setNull(obj->_row, colIndex); + } +} + +void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, + __unsafe_unretained NSNumber *const doubleObject) { + RLMVerifyInWriteTransaction(obj); + + if (doubleObject) { + obj->_row.set(colIndex, doubleObject.doubleValue); + } + else { + setNull(obj->_row, colIndex); + } +} + +void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, + __unsafe_unretained NSNumber *const boolObject) { + RLMVerifyInWriteTransaction(obj); + + if (boolObject) { + obj->_row.set(colIndex, (bool)boolObject.boolValue); + } + else { + setNull(obj->_row, colIndex); + } +} + +RLMLinkingObjects *getLinkingObjects(__unsafe_unretained RLMObjectBase *const obj, + __unsafe_unretained RLMProperty *const property) { + RLMVerifyAttached(obj); + auto& objectInfo = obj->_realm->_info[property.objectClassName]; + auto& linkOrigin = obj->_info->objectSchema->computed_properties[property.index].link_origin_property_name; + auto linkingProperty = objectInfo.objectSchema->property_for_name(linkOrigin); + auto backlinkView = obj->_row.get_table()->get_backlink_view(obj->_row.get_index(), + objectInfo.table(), + linkingProperty->table_column); + realm::Results results(obj->_realm->_realm, std::move(backlinkView)); + return [RLMLinkingObjects resultsWithObjectInfo:objectInfo results:std::move(results)]; +} + +// any getter/setter +template +id makeGetter(NSUInteger index) { + return ^(__unsafe_unretained RLMObjectBase *const obj) { + return static_cast(get(obj, index)); + }; +} + +template +id makeBoxedGetter(NSUInteger index) { + return ^(__unsafe_unretained RLMObjectBase *const obj) { + return getBoxed(obj, index); + }; +} +template +id makeOptionalGetter(NSUInteger index) { + return ^(__unsafe_unretained RLMObjectBase *const obj) { + return getBoxed>(obj, index); + }; +} +template +id makeNumberGetter(NSUInteger index, bool boxed, bool optional) { + if (optional) { + return makeOptionalGetter(index); + } + if (boxed) { + return makeBoxedGetter(index); + } + return makeGetter(index); +} + +// dynamic getter with column closure +id managedGetter(RLMProperty *prop, const char *type) { + NSUInteger index = prop.index; + if (prop.array && prop.type != RLMPropertyTypeLinkingObjects) { + return ^id(__unsafe_unretained RLMObjectBase *const obj) { + return getArray(obj, index); + }; + } + + bool boxed = *type == '@'; + switch (prop.type) { + case RLMPropertyTypeInt: + if (prop.optional || boxed) { + return makeNumberGetter(index, boxed, prop.optional); + } + switch (*type) { + case 'c': return makeGetter(index); + case 's': return makeGetter(index); + case 'i': return makeGetter(index); + case 'l': return makeGetter(index); + case 'q': return makeGetter(index); + default: + @throw RLMException(@"Unexpected property type for Objective-C type code"); + } + case RLMPropertyTypeFloat: + return makeNumberGetter(index, boxed, prop.optional); + case RLMPropertyTypeDouble: + return makeNumberGetter(index, boxed, prop.optional); + case RLMPropertyTypeBool: + return makeNumberGetter(index, boxed, prop.optional); + case RLMPropertyTypeString: + return makeBoxedGetter(index); + case RLMPropertyTypeDate: + return makeBoxedGetter(index); + case RLMPropertyTypeData: + return makeBoxedGetter(index); + case RLMPropertyTypeObject: + return makeBoxedGetter(index); + case RLMPropertyTypeAny: + @throw RLMException(@"Cannot create accessor class for schema with Mixed properties"); + case RLMPropertyTypeLinkingObjects: + return ^(__unsafe_unretained RLMObjectBase *const obj) { + return getLinkingObjects(obj, prop); + }; + } +} + +template +id makeSetter(__unsafe_unretained RLMProperty *const prop) { + NSUInteger index = prop.index; + NSString *name = prop.name; + if (prop.isPrimary) { + return ^(__unused RLMObjectBase *obj, __unused ArgType val) { + @throw RLMException(@"Primary key can't be changed after an object is inserted."); + }; + } + + return ^(__unsafe_unretained RLMObjectBase *const obj, ArgType val) { + auto set = [&] { + setValue(obj, obj->_info->objectSchema->persisted_properties[index].table_column, + static_cast(val)); + }; + if (RLMObservationInfo *info = RLMGetObservationInfo(obj->_observationInfo, + obj->_row.get_index(), *obj->_info)) { + info->willChange(name); + set(); + info->didChange(name); + } + else { + set(); + } + }; +} + +// dynamic setter with column closure +id managedSetter(RLMProperty *prop, const char *type) { + if (prop.array && prop.type != RLMPropertyTypeLinkingObjects) { + return makeSetter>(prop); + } + + bool boxed = prop.optional || *type == '@'; + switch (prop.type) { + case RLMPropertyTypeInt: + if (boxed) { + return makeSetter *>(prop); + } + switch (*type) { + case 'c': return makeSetter(prop); + case 's': return makeSetter(prop); + case 'i': return makeSetter(prop); + case 'l': return makeSetter(prop); + case 'q': return makeSetter(prop); + default: + @throw RLMException(@"Unexpected property type for Objective-C type code"); + } + case RLMPropertyTypeFloat: + return boxed ? makeSetter *>(prop) : makeSetter(prop); + case RLMPropertyTypeDouble: + return boxed ? makeSetter *>(prop) : makeSetter(prop); + case RLMPropertyTypeBool: + return boxed ? makeSetter *>(prop) : makeSetter(prop); + case RLMPropertyTypeString: return makeSetter(prop); + case RLMPropertyTypeDate: return makeSetter(prop); + case RLMPropertyTypeData: return makeSetter(prop); + case RLMPropertyTypeAny: return nil; + case RLMPropertyTypeLinkingObjects: return nil; + case RLMPropertyTypeObject: return makeSetter(prop); + } +} + +// call getter for superclass for property at colIndex +id superGet(RLMObjectBase *obj, NSString *propName) { + typedef id (*getter_type)(RLMObjectBase *, SEL); + RLMProperty *prop = obj->_objectSchema[propName]; + Class superClass = class_getSuperclass(obj.class); + getter_type superGetter = (getter_type)[superClass instanceMethodForSelector:prop.getterSel]; + return superGetter(obj, prop.getterSel); +} + +// call setter for superclass for property at colIndex +void superSet(RLMObjectBase *obj, NSString *propName, id val) { + typedef void (*setter_type)(RLMObjectBase *, SEL, RLMArray *ar); + RLMProperty *prop = obj->_objectSchema[propName]; + Class superClass = class_getSuperclass(obj.class); + setter_type superSetter = (setter_type)[superClass instanceMethodForSelector:prop.setterSel]; + superSetter(obj, prop.setterSel, val); +} + +// getter/setter for unmanaged object +id unmanagedGetter(RLMProperty *prop, const char *) { + // only override getters for RLMArray and linking objects properties + if (prop.type == RLMPropertyTypeLinkingObjects) { + return ^(RLMObjectBase *) { return [RLMResults emptyDetachedResults]; }; + } + if (prop.array) { + NSString *propName = prop.name; + if (prop.type == RLMPropertyTypeObject) { + NSString *objectClassName = prop.objectClassName; + return ^(RLMObjectBase *obj) { + id val = superGet(obj, propName); + if (!val) { + val = [[RLMArray alloc] initWithObjectClassName:objectClassName]; + superSet(obj, propName, val); + } + return val; + }; + } + auto type = prop.type; + auto optional = prop.optional; + return ^(RLMObjectBase *obj) { + id val = superGet(obj, propName); + if (!val) { + val = [[RLMArray alloc] initWithObjectType:type optional:optional]; + superSet(obj, propName, val); + } + return val; + }; + } + return nil; +} + +id unmanagedSetter(RLMProperty *prop, const char *) { + // Only RLMArray needs special handling for the unmanaged setter + if (!prop.array) { + return nil; + } + + NSString *propName = prop.name; + return ^(RLMObjectBase *obj, id values) { + auto prop = obj->_objectSchema[propName]; + RLMValidateValueForProperty(values, obj->_objectSchema, prop, true); + + // make copy when setting (as is the case for all other variants) + RLMArray *ar; + if (prop.type == RLMPropertyTypeObject) + ar = [[RLMArray alloc] initWithObjectClassName:prop.objectClassName]; + else + ar = [[RLMArray alloc] initWithObjectType:prop.type optional:prop.optional]; + [ar addObjects:values]; + superSet(obj, propName, ar); + }; +} + +void addMethod(Class cls, __unsafe_unretained RLMProperty *const prop, + id (*getter)(RLMProperty *, const char *), + id (*setter)(RLMProperty *, const char *)) { + SEL sel = prop.getterSel; + auto getterMethod = class_getInstanceMethod(cls, sel); + if (!getterMethod) { + return; + } + + const char *getterType = method_getTypeEncoding(getterMethod); + if (id block = getter(prop, getterType)) { + class_addMethod(cls, sel, imp_implementationWithBlock(block), getterType); + } + + if (!(sel = prop.setterSel)) { + return; + } + auto setterMethod = class_getInstanceMethod(cls, sel); + if (!setterMethod) { + return; + } + if (id block = setter(prop, getterType)) { // note: deliberately getterType as it's easier to grab the relevant type from + class_addMethod(cls, sel, imp_implementationWithBlock(block), method_getTypeEncoding(setterMethod)); + } +} + +Class createAccessorClass(Class objectClass, + RLMObjectSchema *schema, + const char *accessorClassName, + id (*getterGetter)(RLMProperty *, const char *), + id (*setterGetter)(RLMProperty *, const char *)) { + REALM_ASSERT_DEBUG(RLMIsObjectOrSubclass(objectClass)); + + // create and register proxy class which derives from object class + Class accClass = objc_allocateClassPair(objectClass, accessorClassName, 0); + if (!accClass) { + // Class with that name already exists, so just return the pre-existing one + // This should only happen for our standalone "accessors" + return objc_lookUpClass(accessorClassName); + } + + // override getters/setters for each propery + for (RLMProperty *prop in schema.properties) { + addMethod(accClass, prop, getterGetter, setterGetter); + } + for (RLMProperty *prop in schema.computedProperties) { + addMethod(accClass, prop, getterGetter, setterGetter); + } + + objc_registerClassPair(accClass); + + return accClass; +} +} // anonymous namespace + +#pragma mark - Public Interface + +Class RLMManagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema, const char *name) { + return createAccessorClass(objectClass, schema, name, managedGetter, managedSetter); +} + +Class RLMUnmanagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema) { + return createAccessorClass(objectClass, schema, + [@"RLM:Unmanaged " stringByAppendingString:schema.className].UTF8String, + unmanagedGetter, unmanagedSetter); +} + +// implement the class method className on accessors to return the className of the +// base object +void RLMReplaceClassNameMethod(Class accessorClass, NSString *className) { + Class metaClass = object_getClass(accessorClass); + IMP imp = imp_implementationWithBlock(^(Class){ return className; }); + class_addMethod(metaClass, @selector(className), imp, "@@:"); +} + +// implement the shared schema method +void RLMReplaceSharedSchemaMethod(Class accessorClass, RLMObjectSchema *schema) { + Class metaClass = object_getClass(accessorClass); + IMP imp = imp_implementationWithBlock(^(Class cls) { + if (cls == accessorClass) { + return schema; + } + + // If we aren't being called directly on the class this was overriden + // for, the class is either a subclass which we haven't initialized yet, + // or it's a runtime-generated class which should use the parent's + // schema. We check for the latter by checking if the immediate + // descendent of the desired class is a class generated by us (there + // may be further subclasses not generated by us for things like KVO). + Class parent = class_getSuperclass(cls); + while (parent != accessorClass) { + cls = parent; + parent = class_getSuperclass(cls); + } + + static const char accessorClassPrefix[] = "RLM:"; + if (!strncmp(class_getName(cls), accessorClassPrefix, sizeof(accessorClassPrefix) - 1)) { + return schema; + } + + return [RLMSchema sharedSchemaForClass:cls]; + }); + class_addMethod(metaClass, @selector(sharedSchema), imp, "@@:"); +} + +void RLMDynamicValidatedSet(RLMObjectBase *obj, NSString *propName, id val) { + RLMVerifyAttached(obj); + RLMObjectSchema *schema = obj->_objectSchema; + RLMProperty *prop = schema[propName]; + if (!prop) { + @throw RLMException(@"Invalid property name '%@' for class '%@'.", + propName, obj->_objectSchema.className); + } + if (prop.isPrimary) { + @throw RLMException(@"Primary key can't be changed to '%@' after an object is inserted.", val); + } + RLMValidateValueForProperty(val, schema, prop, true); + RLMDynamicSet(obj, prop, RLMCoerceToNil(val)); +} + +// Precondition: the property is not a primary key +void RLMDynamicSet(__unsafe_unretained RLMObjectBase *const obj, + __unsafe_unretained RLMProperty *const prop, + __unsafe_unretained id const val) { + REALM_ASSERT_DEBUG(!prop.isPrimary); + realm::Object o(obj->_info->realm->_realm, *obj->_info->objectSchema, obj->_row); + RLMAccessorContext c(obj); + translateError([&] { + o.set_property_value(c, prop.columnName.UTF8String, val ?: NSNull.null, false); + }); +} + +id RLMDynamicGet(__unsafe_unretained RLMObjectBase *const obj, __unsafe_unretained RLMProperty *const prop) { + realm::Object o(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row); + RLMAccessorContext c(obj); + c.currentProperty = prop; + return translateError([&] { + return RLMCoerceToNil(o.get_property_value(c, prop.columnName.UTF8String)); + }); +} + +id RLMDynamicGetByName(__unsafe_unretained RLMObjectBase *const obj, + __unsafe_unretained NSString *const propName, bool asList) { + RLMProperty *prop = obj->_objectSchema[propName]; + if (!prop) { + @throw RLMException(@"Invalid property name '%@' for class '%@'.", + propName, obj->_objectSchema.className); + } + if (asList && prop.array && prop.swiftIvar) { + RLMListBase *list = object_getIvar(obj, prop.swiftIvar); + if (prop.type != RLMPropertyTypeLinkingObjects && !list._rlmArray) { + list._rlmArray = RLMDynamicGet(obj, prop); + } + return list; + } + + return RLMDynamicGet(obj, prop); +} + +RLMAccessorContext::RLMAccessorContext(RLMAccessorContext& parent, realm::Property const& property) +: _realm(parent._realm) +, _info(property.type == realm::PropertyType::Object ? parent._info.linkTargetType(property) : parent._info) +, _promote_existing(parent._promote_existing) +{ +} + +RLMAccessorContext::RLMAccessorContext(RLMRealm *realm, RLMClassInfo& info, bool promote) +: _realm(realm), _info(info), _promote_existing(promote) +{ +} + +RLMAccessorContext::RLMAccessorContext(__unsafe_unretained RLMObjectBase *const parent, + const realm::Property *prop) +: _realm(parent->_realm) +, _info(prop && prop->type == realm::PropertyType::Object ? parent->_info->linkTargetType(*prop) + : *parent->_info) +, _parentObject(parent) +{ +} + +id RLMAccessorContext::defaultValue(__unsafe_unretained NSString *const key) { + if (!_defaultValues) { + _defaultValues = RLMDefaultValuesForObjectSchema(_info.rlmObjectSchema); + } + return _defaultValues[key]; +} + +id RLMAccessorContext::propertyValue(__unsafe_unretained id const obj, size_t propIndex, + __unsafe_unretained RLMProperty *const prop) { + // Property value from an NSArray + if ([obj respondsToSelector:@selector(objectAtIndex:)]) { + return propIndex < [obj count] ? [obj objectAtIndex:propIndex] : nil; + } + + // Property value from an NSDictionary + if ([obj respondsToSelector:@selector(objectForKey:)]) { + return [obj objectForKey:prop.name]; + } + + // Property value from an instance of this object type + id value; + if ([obj isKindOfClass:_info.rlmObjectSchema.objectClass] && prop.swiftIvar) { + if (prop.array) { + return static_cast(object_getIvar(obj, prop.swiftIvar))._rlmArray; + } + else if (prop.swiftIvar == RLMDummySwiftIvar) { + // FIXME: An invalid property which we're pretending is nil until 4.0 + // https://github.com/realm/realm-cocoa/issues/5784 + return NSNull.null; + } + else { // optional + value = RLMGetOptional(static_cast(object_getIvar(obj, prop.swiftIvar))); + } + } + else { + // Property value from some object that's KVC-compatible + value = RLMValidatedValueForProperty(obj, [obj respondsToSelector:prop.getterSel] ? prop.getterName : prop.name, + _info.rlmObjectSchema.className); + } + return value ?: NSNull.null; +} + +id RLMAccessorContext::box(realm::List&& l) { + REALM_ASSERT(_parentObject); + REALM_ASSERT(currentProperty); + return [[RLMManagedArray alloc] initWithList:std::move(l) realm:_realm + parentInfo:_parentObject->_info + property:currentProperty]; +} + +id RLMAccessorContext::box(realm::Object&& o) { + REALM_ASSERT(currentProperty); + return RLMCreateObjectAccessor(_realm, _info.linkTargetType(currentProperty.index), o.row()); +} + +id RLMAccessorContext::box(realm::RowExpr r) { + return RLMCreateObjectAccessor(_realm, _info, r); +} + +id RLMAccessorContext::box(realm::Results&& r) { + REALM_ASSERT(currentProperty); + return [RLMResults resultsWithObjectInfo:_realm->_info[currentProperty.objectClassName] + results:std::move(r)]; +} + +template<> +realm::Timestamp RLMAccessorContext::unbox(__unsafe_unretained id const value, bool, bool) { + id v = RLMCoerceToNil(value); + return RLMTimestampForNSDate(v); +} + +template<> +bool RLMAccessorContext::unbox(__unsafe_unretained id const v, bool, bool) { + return [v boolValue]; +} +template<> +double RLMAccessorContext::unbox(__unsafe_unretained id const v, bool, bool) { + return [v doubleValue]; +} +template<> +float RLMAccessorContext::unbox(__unsafe_unretained id const v, bool, bool) { + return [v floatValue]; +} +template<> +long long RLMAccessorContext::unbox(__unsafe_unretained id const v, bool, bool) { + return [v longLongValue]; +} +template<> +realm::BinaryData RLMAccessorContext::unbox(id v, bool, bool) { + v = RLMCoerceToNil(v); + return RLMBinaryDataForNSData(v); +} +template<> +realm::StringData RLMAccessorContext::unbox(id v, bool, bool) { + v = RLMCoerceToNil(v); + return RLMStringDataWithNSString(v); +} + +template +static auto to_optional(__unsafe_unretained id const value, Fn&& fn) { + id v = RLMCoerceToNil(value); + return v && v != NSNull.null ? realm::util::make_optional(fn(v)) : realm::util::none; +} + +template<> +realm::util::Optional RLMAccessorContext::unbox(__unsafe_unretained id const v, bool, bool) { + return to_optional(v, [&](__unsafe_unretained id v) { return (bool)[v boolValue]; }); +} +template<> +realm::util::Optional RLMAccessorContext::unbox(__unsafe_unretained id const v, bool, bool) { + return to_optional(v, [&](__unsafe_unretained id v) { return [v doubleValue]; }); +} +template<> +realm::util::Optional RLMAccessorContext::unbox(__unsafe_unretained id const v, bool, bool) { + return to_optional(v, [&](__unsafe_unretained id v) { return [v floatValue]; }); +} +template<> +realm::util::Optional RLMAccessorContext::unbox(__unsafe_unretained id const v, bool, bool) { + return to_optional(v, [&](__unsafe_unretained id v) { return [v longLongValue]; }); +} + +template<> +realm::RowExpr RLMAccessorContext::unbox(__unsafe_unretained id const v, bool create, bool update) { + RLMObjectBase *link = RLMDynamicCast(v); + if (!link) { + if (!create) + return realm::RowExpr(); + return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, v, update)->_row; + } + + if (link.isInvalidated) { + if (create) { + @throw RLMException(@"Adding a deleted or invalidated object to a Realm is not permitted"); + } + else { + @throw RLMException(@"Object has been invalidated"); + } + } + + if (![link->_objectSchema.className isEqualToString:_info.rlmObjectSchema.className]) { + if (create && !_promote_existing) + return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, link, update)->_row; + return link->_row; + } + + if (!link->_realm) { + if (!create) + return realm::RowExpr(); + if (!_promote_existing) + return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, link, update)->_row; + RLMAddObjectToRealm(link, _realm, update); + } + else if (link->_realm != _realm) { + if (_promote_existing) + @throw RLMException(@"Object is already managed by another Realm. Use create instead to copy it into this Realm."); + return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, v, update)->_row; + } + return link->_row; +} + +void RLMAccessorContext::will_change(realm::Row const& row, realm::Property const& prop) { + _observationInfo = RLMGetObservationInfo(nullptr, row.get_index(), _info); + if (_observationInfo) { + _kvoPropertyName = _info.propertyForTableColumn(prop.table_column).name; + _observationInfo->willChange(_kvoPropertyName); + } +} + +void RLMAccessorContext::did_change() { + if (_observationInfo) { + _observationInfo->didChange(_kvoPropertyName); + _kvoPropertyName = nil; + _observationInfo = nullptr; + } +} + +RLMOptionalId RLMAccessorContext::value_for_property(__unsafe_unretained id const obj, + std::string const&, size_t propIndex) { + auto prop = _info.rlmObjectSchema.properties[propIndex]; + id value = propertyValue(obj, propIndex, prop); + if (value) { + RLMValidateValueForProperty(value, _info.rlmObjectSchema, prop); + } + + if (_promote_existing && [obj isKindOfClass:_info.rlmObjectSchema.objectClass] && !prop.swiftIvar) { + // set the ivars for object and array properties to nil as otherwise the + // accessors retain objects that are no longer accessible via the properties + // this is mainly an issue when the object graph being added has cycles, + // as it's not obvious that the user has to set the *ivars* to nil to + // avoid leaking memory + if (prop.type == RLMPropertyTypeObject) { + ((void(*)(id, SEL, id))objc_msgSend)(obj, prop.setterSel, nil); + } + } + + return RLMOptionalId{value}; +} + +RLMOptionalId RLMAccessorContext::default_value_for_property(realm::ObjectSchema const&, + std::string const& prop) +{ + return RLMOptionalId{defaultValue(@(prop.c_str()))}; +} + +bool RLMAccessorContext::is_same_list(realm::List const& list, __unsafe_unretained id const v) const noexcept { + return [v respondsToSelector:@selector(isBackedByList:)] && [v isBackedByList:list]; +} diff --git a/Pods/Realm/Realm/RLMAnalytics.mm b/Pods/Realm/Realm/RLMAnalytics.mm new file mode 100644 index 0000000000..b6d750ac48 --- /dev/null +++ b/Pods/Realm/Realm/RLMAnalytics.mm @@ -0,0 +1,243 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +// Asynchronously submits build information to Realm if running in an iOS +// simulator or on OS X if a debugger is attached. Does nothing if running on an +// iOS / watchOS device or if a debugger is *not* attached. +// +// To be clear: this does *not* run when your app is in production or on +// your end-user’s devices; it will only run in the simulator or when a debugger +// is attached. +// +// Why are we doing this? In short, because it helps us build a better product +// for you. None of the data personally identifies you, your employer or your +// app, but it *will* help us understand what language you use, what iOS +// versions you target, etc. Having this info will help prioritizing our time, +// adding new features and deprecating old features. Collecting an anonymized +// bundle & anonymized MAC is the only way for us to count actual usage of the +// other metrics accurately. If we don’t have a way to deduplicate the info +// reported, it will be useless, as a single developer building their Swift app +// 10 times would report 10 times more than a single Objective-C developer that +// only builds once, making the data all but useless. +// No one likes sharing data unless it’s necessary, we get it, and we’ve +// debated adding this for a long long time. Since Realm is a free product +// without an email signup, we feel this is a necessary step so we can collect +// relevant data to build a better product for you. If you truly, absolutely +// feel compelled to not send this data back to Realm, then you can set an env +// variable named REALM_DISABLE_ANALYTICS. Since Realm is free we believe +// letting these analytics run is a small price to pay for the product & support +// we give you. +// +// Currently the following information is reported: +// - What version of Realm is being used, and from which language (obj-c or Swift). +// - What version of OS X it's running on (in case Xcode aggressively drops +// support for older versions again, we need to know what we need to support). +// - The minimum iOS/OS X version that the application is targeting (again, to +// help us decide what versions we need to support). +// - An anonymous MAC address and bundle ID to aggregate the other information on. +// - What version of Swift is being used (if applicable). + +#import "RLMAnalytics.hpp" + +#import + +#if TARGET_IPHONE_SIMULATOR || TARGET_OS_MAC || (TARGET_OS_WATCH && TARGET_OS_SIMULATOR) || (TARGET_OS_TV && TARGET_OS_SIMULATOR) +#import "RLMRealm.h" +#import "RLMUtil.hpp" + +#import +#import +#import +#import +#import + +#import + +#ifndef REALM_COCOA_VERSION +#import "RLMVersion.h" +#endif + +#import + +// Declared for RealmSwiftObjectUtil +@interface NSObject (SwiftVersion) ++ (NSString *)swiftVersion; +@end + +// Wrapper for sysctl() that handles the memory management stuff +static auto RLMSysCtl(int *mib, u_int mibSize, size_t *bufferSize) { + std::unique_ptr buffer(nullptr, &free); + + int ret = sysctl(mib, mibSize, nullptr, bufferSize, nullptr, 0); + if (ret != 0) { + return buffer; + } + + buffer.reset(malloc(*bufferSize)); + if (!buffer) { + return buffer; + } + + ret = sysctl(mib, mibSize, buffer.get(), bufferSize, nullptr, 0); + if (ret != 0) { + buffer.reset(); + } + + return buffer; +} + +// Get the version of OS X we're running on (even in the simulator this gives +// the OS X version and not the simulated iOS version) +static NSString *RLMOSVersion() { + std::array mib = {{CTL_KERN, KERN_OSRELEASE}}; + size_t bufferSize; + auto buffer = RLMSysCtl(&mib[0], mib.size(), &bufferSize); + if (!buffer) { + return nil; + } + + return [[NSString alloc] initWithBytesNoCopy:buffer.release() + length:bufferSize - 1 + encoding:NSUTF8StringEncoding + freeWhenDone:YES]; +} + +// Hash the data in the given buffer and convert it to a hex-format string +static NSString *RLMHashData(const void *bytes, size_t length) { + unsigned char buffer[CC_SHA256_DIGEST_LENGTH]; + CC_SHA256(bytes, static_cast(length), buffer); + + char formatted[CC_SHA256_DIGEST_LENGTH * 2 + 1]; + for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i) { + sprintf(formatted + i * 2, "%02x", buffer[i]); + } + + return [[NSString alloc] initWithBytes:formatted + length:CC_SHA256_DIGEST_LENGTH * 2 + encoding:NSUTF8StringEncoding]; +} + +// Returns the hash of the MAC address of the first network adaptor since the +// vendorIdentifier isn't constant between iOS simulators. +static NSString *RLMMACAddress() { + int en0 = static_cast(if_nametoindex("en0")); + if (!en0) { + return nil; + } + + std::array mib = {{CTL_NET, PF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, en0}}; + size_t bufferSize; + auto buffer = RLMSysCtl(&mib[0], mib.size(), &bufferSize); + if (!buffer) { + return nil; + } + + // sockaddr_dl struct is immediately after the if_msghdr struct in the buffer + auto sockaddr = reinterpret_cast(static_cast(buffer.get()) + 1); + auto mac = reinterpret_cast(sockaddr->sdl_data + sockaddr->sdl_nlen); + + return RLMHashData(mac, 6); +} + +static NSDictionary *RLMAnalyticsPayload() { + NSBundle *appBundle = NSBundle.mainBundle; + NSString *hashedBundleID = appBundle.bundleIdentifier; + + // Main bundle isn't always the one of interest (e.g. when running tests + // it's xctest rather than the app's bundle), so look for one with a bundle ID + if (!hashedBundleID) { + for (NSBundle *bundle in NSBundle.allBundles) { + if ((hashedBundleID = bundle.bundleIdentifier)) { + appBundle = bundle; + break; + } + } + } + + // If we found a bundle ID anywhere, hash it as it could contain sensitive + // information (e.g. the name of an unnanounced product) + if (hashedBundleID) { + NSData *data = [hashedBundleID dataUsingEncoding:NSUTF8StringEncoding]; + hashedBundleID = RLMHashData(data.bytes, data.length); + } + + NSString *osVersionString = [[NSProcessInfo processInfo] operatingSystemVersionString]; + Class swiftObjectUtilClass = NSClassFromString(@"RealmSwiftObjectUtil"); + BOOL isSwift = swiftObjectUtilClass != nil; + NSString *swiftVersion = isSwift ? [swiftObjectUtilClass swiftVersion] : @"N/A"; + + static NSString *kUnknownString = @"unknown"; + NSString *hashedMACAddress = RLMMACAddress() ?: kUnknownString; + + return @{ + @"event": @"Run", + @"properties": @{ + // MixPanel properties + @"token": @"ce0fac19508f6c8f20066d345d360fd0", + + // Anonymous identifiers to deduplicate events + @"distinct_id": hashedMACAddress, + @"Anonymized MAC Address": hashedMACAddress, + @"Anonymized Bundle ID": hashedBundleID ?: kUnknownString, + + // Which version of Realm is being used + @"Binding": @"cocoa", + @"Language": isSwift ? @"swift" : @"objc", + @"Realm Version": REALM_COCOA_VERSION, + @"Sync Version": @(REALM_SYNC_VER_STRING), +#if TARGET_OS_WATCH + @"Target OS Type": @"watchos", +#elif TARGET_OS_TV + @"Target OS Type": @"tvos", +#elif TARGET_OS_IPHONE + @"Target OS Type": @"ios", +#else + @"Target OS Type": @"osx", +#endif + @"Swift Version": swiftVersion, + // Current OS version the app is targetting + @"Target OS Version": osVersionString, + // Minimum OS version the app is targetting + @"Target OS Minimum Version": appBundle.infoDictionary[@"MinimumOSVersion"] ?: kUnknownString, + + // Host OS version being built on + @"Host OS Type": @"osx", + @"Host OS Version": RLMOSVersion() ?: kUnknownString, + } + }; +} + +void RLMSendAnalytics() { + if (getenv("REALM_DISABLE_ANALYTICS") || !RLMIsDebuggerAttached() || RLMIsRunningInPlayground()) { + return; + } + + + NSData *payload = [NSJSONSerialization dataWithJSONObject:RLMAnalyticsPayload() options:0 error:nil]; + NSString *url = [NSString stringWithFormat:@"https://api.mixpanel.com/track/?data=%@&ip=1", [payload base64EncodedStringWithOptions:0]]; + + // No error handling or anything because logging errors annoyed people for no + // real benefit, and it's not clear what else we could do + [[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:url]] resume]; +} + +#else + +void RLMSendAnalytics() {} + +#endif diff --git a/Pods/Realm/Realm/RLMArray.mm b/Pods/Realm/Realm/RLMArray.mm new file mode 100644 index 0000000000..2262e783f5 --- /dev/null +++ b/Pods/Realm/Realm/RLMArray.mm @@ -0,0 +1,587 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMArray_Private.hpp" + +#import "RLMObjectSchema.h" +#import "RLMObjectStore.h" +#import "RLMObject_Private.h" +#import "RLMProperty_Private.h" +#import "RLMQueryUtil.hpp" +#import "RLMSchema_Private.h" +#import "RLMSwiftSupport.h" +#import "RLMThreadSafeReference_Private.hpp" +#import "RLMUtil.hpp" + +// See -countByEnumeratingWithState:objects:count +@interface RLMArrayHolder : NSObject { +@public + std::unique_ptr items; +} +@end +@implementation RLMArrayHolder +@end + +@interface RLMArray () +@end + +@implementation RLMArray { +@public + // Backing array when this instance is unmanaged + NSMutableArray *_backingArray; +} + +#pragma mark - Initializers + +- (instancetype)initWithObjectClassName:(__unsafe_unretained NSString *const)objectClassName { + REALM_ASSERT([objectClassName length] > 0); + self = [super init]; + if (self) { + _objectClassName = objectClassName; + _type = RLMPropertyTypeObject; + } + return self; +} + +- (instancetype)initWithObjectType:(RLMPropertyType)type optional:(BOOL)optional { + self = [super init]; + if (self) { + _type = type; + _optional = optional; + } + return self; +} + +#pragma mark - Convenience wrappers used for all RLMArray types + +- (void)addObjects:(id)objects { + for (id obj in objects) { + [self addObject:obj]; + } +} + +- (void)addObject:(id)object { + [self insertObject:object atIndex:self.count]; +} + +- (void)removeLastObject { + NSUInteger count = self.count; + if (count) { + [self removeObjectAtIndex:count-1]; + } +} + +- (id)objectAtIndexedSubscript:(NSUInteger)index { + return [self objectAtIndex:index]; +} + +- (void)setObject:(id)newValue atIndexedSubscript:(NSUInteger)index { + [self replaceObjectAtIndex:index withObject:newValue]; +} + +- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending { + return [self sortedResultsUsingDescriptors:@[[RLMSortDescriptor sortDescriptorWithKeyPath:keyPath ascending:ascending]]]; +} + +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ... { + va_list args; + va_start(args, predicateFormat); + NSUInteger index = [self indexOfObjectWhere:predicateFormat args:args]; + va_end(args); + return index; +} + +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args { + return [self indexOfObjectWithPredicate:[NSPredicate predicateWithFormat:predicateFormat + arguments:args]]; +} + +#pragma mark - Unmanaged RLMArray implementation + +- (RLMRealm *)realm { + return nil; +} + +- (id)firstObject { + if (self.count) { + return [self objectAtIndex:0]; + } + return nil; +} + +- (id)lastObject { + NSUInteger count = self.count; + if (count) { + return [self objectAtIndex:count-1]; + } + return nil; +} + +- (id)objectAtIndex:(NSUInteger)index { + validateArrayBounds(self, index); + return [_backingArray objectAtIndex:index]; +} + +- (NSUInteger)count { + return _backingArray.count; +} + +- (BOOL)isInvalidated { + return NO; +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state + objects:(__unused __unsafe_unretained id [])buffer + count:(__unused NSUInteger)len { + if (state->state != 0) { + return 0; + } + + // We need to enumerate a copy of the backing array so that it doesn't + // reflect changes made during enumeration. This copy has to be autoreleased + // (since there's nowhere for us to store a strong reference), and uses + // RLMArrayHolder rather than an NSArray because NSArray doesn't guarantee + // that it'll use a single contiguous block of memory, and if it doesn't + // we'd need to forward multiple calls to this method to the same NSArray, + // which would require holding a reference to it somewhere. + __autoreleasing RLMArrayHolder *copy = [[RLMArrayHolder alloc] init]; + copy->items = std::make_unique(self.count); + + NSUInteger i = 0; + for (id object in _backingArray) { + copy->items[i++] = object; + } + + state->itemsPtr = (__unsafe_unretained id *)(void *)copy->items.get(); + // needs to point to something valid, but the whole point of this is so + // that it can't be changed + state->mutationsPtr = state->extra; + state->state = i; + + return i; +} + + +template +static void changeArray(__unsafe_unretained RLMArray *const ar, + NSKeyValueChange kind, dispatch_block_t f, IndexSetFactory&& is) { + if (!ar->_backingArray) { + ar->_backingArray = [NSMutableArray new]; + } + + if (RLMObjectBase *parent = ar->_parentObject) { + NSIndexSet *indexes = is(); + [parent willChange:kind valuesAtIndexes:indexes forKey:ar->_key]; + f(); + [parent didChange:kind valuesAtIndexes:indexes forKey:ar->_key]; + } + else { + f(); + } +} + +static void changeArray(__unsafe_unretained RLMArray *const ar, NSKeyValueChange kind, + NSUInteger index, dispatch_block_t f) { + changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndex:index]; }); +} + +static void changeArray(__unsafe_unretained RLMArray *const ar, NSKeyValueChange kind, + NSRange range, dispatch_block_t f) { + changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndexesInRange:range]; }); +} + +static void changeArray(__unsafe_unretained RLMArray *const ar, NSKeyValueChange kind, + NSIndexSet *is, dispatch_block_t f) { + changeArray(ar, kind, f, [=] { return is; }); +} + +void RLMArrayValidateMatchingObjectType(__unsafe_unretained RLMArray *const array, + __unsafe_unretained id const value) { + if (!value && !array->_optional) { + @throw RLMException(@"Invalid nil value for array of '%@'.", + array->_objectClassName ?: RLMTypeToString(array->_type)); + } + if (array->_type != RLMPropertyTypeObject) { + if (!RLMValidateValue(value, array->_type, array->_optional, false, nil)) { + @throw RLMException(@"Invalid value '%@' of type '%@' for expected type '%@%s'.", + value, [value class], RLMTypeToString(array->_type), + array->_optional ? "?" : ""); + } + return; + } + + auto object = RLMDynamicCast(value); + if (!object) { + return; + } + if (!object->_objectSchema) { + @throw RLMException(@"Object cannot be inserted unless the schema is initialized. " + "This can happen if you try to insert objects into a RLMArray / List from a default value or from an overriden unmanaged initializer (`init()`)."); + } + if (![array->_objectClassName isEqualToString:object->_objectSchema.className]) { + @throw RLMException(@"Object of type '%@' does not match RLMArray type '%@'.", + object->_objectSchema.className, array->_objectClassName); + } +} + +static void validateArrayBounds(__unsafe_unretained RLMArray *const ar, + NSUInteger index, bool allowOnePastEnd=false) { + NSUInteger max = ar->_backingArray.count + allowOnePastEnd; + if (index >= max) { + @throw RLMException(@"Index %llu is out of bounds (must be less than %llu).", + (unsigned long long)index, (unsigned long long)max); + } +} + +- (void)addObjectsFromArray:(NSArray *)array { + for (id obj in array) { + RLMArrayValidateMatchingObjectType(self, obj); + } + changeArray(self, NSKeyValueChangeInsertion, NSMakeRange(_backingArray.count, array.count), ^{ + [_backingArray addObjectsFromArray:array]; + }); +} + +- (void)insertObject:(id)anObject atIndex:(NSUInteger)index { + RLMArrayValidateMatchingObjectType(self, anObject); + validateArrayBounds(self, index, true); + changeArray(self, NSKeyValueChangeInsertion, index, ^{ + [_backingArray insertObject:anObject atIndex:index]; + }); +} + +- (void)insertObjects:(id)objects atIndexes:(NSIndexSet *)indexes { + changeArray(self, NSKeyValueChangeInsertion, indexes, ^{ + NSUInteger currentIndex = [indexes firstIndex]; + for (RLMObject *obj in objects) { + RLMArrayValidateMatchingObjectType(self, obj); + [_backingArray insertObject:obj atIndex:currentIndex]; + currentIndex = [indexes indexGreaterThanIndex:currentIndex]; + } + }); +} + +- (void)removeObjectAtIndex:(NSUInteger)index { + validateArrayBounds(self, index); + changeArray(self, NSKeyValueChangeRemoval, index, ^{ + [_backingArray removeObjectAtIndex:index]; + }); +} + +- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes { + changeArray(self, NSKeyValueChangeRemoval, indexes, ^{ + [_backingArray removeObjectsAtIndexes:indexes]; + }); +} + +- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject { + RLMArrayValidateMatchingObjectType(self, anObject); + validateArrayBounds(self, index); + changeArray(self, NSKeyValueChangeReplacement, index, ^{ + [_backingArray replaceObjectAtIndex:index withObject:anObject]; + }); +} + +- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex { + validateArrayBounds(self, sourceIndex); + validateArrayBounds(self, destinationIndex); + id original = _backingArray[sourceIndex]; + + auto start = std::min(sourceIndex, destinationIndex); + auto len = std::max(sourceIndex, destinationIndex) - start + 1; + changeArray(self, NSKeyValueChangeReplacement, {start, len}, ^{ + [_backingArray removeObjectAtIndex:sourceIndex]; + [_backingArray insertObject:original atIndex:destinationIndex]; + }); +} + +- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 { + validateArrayBounds(self, index1); + validateArrayBounds(self, index2); + + changeArray(self, NSKeyValueChangeReplacement, ^{ + [_backingArray exchangeObjectAtIndex:index1 withObjectAtIndex:index2]; + }, [=] { + NSMutableIndexSet *set = [[NSMutableIndexSet alloc] initWithIndex:index1]; + [set addIndex:index2]; + return set; + }); +} + +- (NSUInteger)indexOfObject:(id)object { + RLMArrayValidateMatchingObjectType(self, object); + if (!_backingArray) { + return NSNotFound; + } + if (_type != RLMPropertyTypeObject) { + return [_backingArray indexOfObject:object]; + } + + NSUInteger index = 0; + for (RLMObjectBase *cmp in _backingArray) { + if (RLMObjectBaseAreEqual(object, cmp)) { + return index; + } + index++; + } + return NSNotFound; +} + +- (void)removeAllObjects { + changeArray(self, NSKeyValueChangeRemoval, NSMakeRange(0, _backingArray.count), ^{ + [_backingArray removeAllObjects]; + }); +} + +- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... { + va_list args; + va_start(args, predicateFormat); + RLMResults *results = [self objectsWhere:predicateFormat args:args]; + va_end(args); + return results; +} + +- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args { + return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; +} + +static bool canAggregate(RLMPropertyType type, bool allowDate) { + switch (type) { + case RLMPropertyTypeInt: + case RLMPropertyTypeFloat: + case RLMPropertyTypeDouble: + return true; + case RLMPropertyTypeDate: + return allowDate; + default: + return false; + } +} + +- (RLMPropertyType)typeForProperty:(NSString *)propertyName { + if ([propertyName isEqualToString:@"self"]) { + return _type; + } + + RLMObjectSchema *objectSchema; + if (_backingArray.count) { + objectSchema = [_backingArray[0] objectSchema]; + } + else { + objectSchema = [RLMSchema.partialPrivateSharedSchema schemaForClassName:_objectClassName]; + } + + return RLMValidatedProperty(objectSchema, propertyName).type; +} + +- (id)aggregateProperty:(NSString *)key operation:(NSString *)op method:(SEL)sel { + // Although delegating to valueForKeyPath: here would allow to support + // nested key paths as well, limiting functionality gives consistency + // between unmanaged and managed arrays. + if ([key rangeOfString:@"."].location != NSNotFound) { + @throw RLMException(@"Nested key paths are not supported yet for KVC collection operators."); + } + + bool allowDate = false; + bool sum = false; + if ([op isEqualToString:@"@min"] || [op isEqualToString:@"@max"]) { + allowDate = true; + } + else if ([op isEqualToString:@"@sum"]) { + sum = true; + } + else if (![op isEqualToString:@"@avg"]) { + // Just delegate to NSArray for all other operators + return [_backingArray valueForKeyPath:[op stringByAppendingPathExtension:key]]; + } + + RLMPropertyType type = [self typeForProperty:key]; + if (!canAggregate(type, allowDate)) { + NSString *method = sel ? NSStringFromSelector(sel) : op; + if (_type == RLMPropertyTypeObject) { + @throw RLMException(@"%@: is not supported for %@ property '%@.%@'", + method, RLMTypeToString(type), _objectClassName, key); + } + else { + @throw RLMException(@"%@ is not supported for %@%s array", + method, RLMTypeToString(_type), _optional ? "?" : ""); + } + } + + NSArray *values = [key isEqualToString:@"self"] ? _backingArray : [_backingArray valueForKey:key]; + if (_optional) { + // Filter out NSNull values to match our behavior on managed arrays + NSIndexSet *nonnull = [values indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger, BOOL *) { + return obj != NSNull.null; + }]; + if (nonnull.count < values.count) { + values = [values objectsAtIndexes:nonnull]; + } + } + id result = [values valueForKeyPath:[op stringByAppendingString:@".self"]]; + return sum && !result ? @0 : result; +} + +- (id)valueForKeyPath:(NSString *)keyPath { + if ([keyPath characterAtIndex:0] != '@') { + return _backingArray ? [_backingArray valueForKeyPath:keyPath] : [super valueForKeyPath:keyPath]; + } + + if (!_backingArray) { + _backingArray = [NSMutableArray new]; + } + + NSUInteger dot = [keyPath rangeOfString:@"."].location; + if (dot == NSNotFound) { + return [_backingArray valueForKeyPath:keyPath]; + } + + NSString *op = [keyPath substringToIndex:dot]; + NSString *key = [keyPath substringFromIndex:dot + 1]; + return [self aggregateProperty:key operation:op method:nil]; +} + +- (id)valueForKey:(NSString *)key { + if ([key isEqualToString:RLMInvalidatedKey]) { + return @NO; // Unmanaged arrays are never invalidated + } + if (!_backingArray) { + _backingArray = [NSMutableArray new]; + } + return [_backingArray valueForKey:key]; +} + +- (void)setValue:(id)value forKey:(NSString *)key { + if ([key isEqualToString:@"self"]) { + RLMArrayValidateMatchingObjectType(self, value); + for (NSUInteger i = 0, count = _backingArray.count; i < count; ++i) { + _backingArray[i] = value; + } + return; + } + else if (_type == RLMPropertyTypeObject) { + [_backingArray setValue:value forKey:key]; + } + else { + [self setValue:value forUndefinedKey:key]; + } +} + +- (id)minOfProperty:(NSString *)property { + return [self aggregateProperty:property operation:@"@min" method:_cmd]; +} + +- (id)maxOfProperty:(NSString *)property { + return [self aggregateProperty:property operation:@"@max" method:_cmd]; +} + +- (id)sumOfProperty:(NSString *)property { + return [self aggregateProperty:property operation:@"@sum" method:_cmd]; +} + +- (id)averageOfProperty:(NSString *)property { + return [self aggregateProperty:property operation:@"@avg" method:_cmd]; +} + +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate { + if (!_backingArray) { + return NSNotFound; + } + return [_backingArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger, BOOL *) { + return [predicate evaluateWithObject:obj]; + }]; +} + +- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes { + if (!_backingArray) { + _backingArray = [NSMutableArray new]; + } + return [_backingArray objectsAtIndexes:indexes]; +} + +- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath + options:(NSKeyValueObservingOptions)options context:(void *)context { + RLMValidateArrayObservationKey(keyPath, self); + [super addObserver:observer forKeyPath:keyPath options:options context:context]; +} + +#pragma mark - Methods unsupported on unmanaged RLMArray instances + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-parameter" + +- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate { + @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm"); +} + +- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties { + @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm"); +} + +// The compiler complains about the method's argument type not matching due to +// it not having the generic type attached, but it doesn't seem to be possible +// to actually include the generic type +// http://www.openradar.me/radar?id=6135653276319744 +#pragma clang diagnostic ignored "-Wmismatched-parameter-types" +- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *, RLMCollectionChange *, NSError *))block { + @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm"); +} + +#pragma mark - Thread Confined Protocol Conformance + +- (std::unique_ptr)makeThreadSafeReference { + REALM_TERMINATE("Unexpected handover of unmanaged `RLMArray`"); +} + +- (id)objectiveCMetadata { + REALM_TERMINATE("Unexpected handover of unmanaged `RLMArray`"); +} + ++ (instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference + metadata:(id)metadata + realm:(RLMRealm *)realm { + REALM_TERMINATE("Unexpected handover of unmanaged `RLMArray`"); +} + +#pragma clang diagnostic pop // unused parameter warning + +#pragma mark - Superclass Overrides + +- (NSString *)description { + return [self descriptionWithMaxDepth:RLMDescriptionMaxDepth]; +} + +- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth { + return RLMDescriptionWithMaxDepth(@"RLMArray", self, depth); +} +@end + +@implementation RLMSortDescriptor + ++ (instancetype)sortDescriptorWithKeyPath:(NSString *)keyPath ascending:(BOOL)ascending { + RLMSortDescriptor *desc = [[RLMSortDescriptor alloc] init]; + desc->_keyPath = keyPath; + desc->_ascending = ascending; + return desc; +} + +- (instancetype)reversedSortDescriptor { + return [self.class sortDescriptorWithKeyPath:_keyPath ascending:!_ascending]; +} + +@end diff --git a/Pods/Realm/Realm/RLMClassInfo.mm b/Pods/Realm/Realm/RLMClassInfo.mm new file mode 100644 index 0000000000..52b44f8580 --- /dev/null +++ b/Pods/Realm/Realm/RLMClassInfo.mm @@ -0,0 +1,131 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMClassInfo.hpp" + +#import "RLMRealm_Private.hpp" +#import "RLMObjectSchema_Private.h" +#import "RLMSchema.h" +#import "RLMProperty_Private.h" +#import "RLMQueryUtil.hpp" +#import "RLMUtil.hpp" + +#import "object_schema.hpp" +#import "object_store.hpp" +#import "schema.hpp" +#import "shared_realm.hpp" + +#import + +using namespace realm; + +RLMClassInfo::RLMClassInfo(RLMRealm *realm, RLMObjectSchema *rlmObjectSchema, + const realm::ObjectSchema *objectSchema) +: realm(realm), rlmObjectSchema(rlmObjectSchema), objectSchema(objectSchema) { } + +realm::Table *RLMClassInfo::table() const { + if (!m_table) { + m_table = ObjectStore::table_for_object_type(realm.group, objectSchema->name).get(); + } + return m_table; +} + +RLMProperty *RLMClassInfo::propertyForTableColumn(NSUInteger col) const noexcept { + auto const& props = objectSchema->persisted_properties; + for (size_t i = 0; i < props.size(); ++i) { + if (props[i].table_column == col) { + return rlmObjectSchema.properties[i]; + } + } + return nil; +} + +RLMProperty *RLMClassInfo::propertyForPrimaryKey() const noexcept { + return rlmObjectSchema.primaryKeyProperty; +} + +NSUInteger RLMClassInfo::tableColumn(NSString *propertyName) const { + return tableColumn(RLMValidatedProperty(rlmObjectSchema, propertyName)); +} + +NSUInteger RLMClassInfo::tableColumn(RLMProperty *property) const { + return objectSchema->persisted_properties[property.index].table_column; +} + +RLMClassInfo &RLMClassInfo::linkTargetType(size_t propertyIndex) { + if (propertyIndex < m_linkTargets.size() && m_linkTargets[propertyIndex]) { + return *m_linkTargets[propertyIndex]; + } + if (m_linkTargets.size() <= propertyIndex) { + m_linkTargets.resize(propertyIndex + 1); + } + m_linkTargets[propertyIndex] = &realm->_info[rlmObjectSchema.properties[propertyIndex].objectClassName]; + return *m_linkTargets[propertyIndex]; +} + +RLMClassInfo &RLMClassInfo::linkTargetType(realm::Property const& property) { + REALM_ASSERT(property.type == PropertyType::Object); + return linkTargetType(&property - &objectSchema->persisted_properties[0]); +} + +RLMSchemaInfo::impl::iterator RLMSchemaInfo::begin() noexcept { return m_objects.begin(); } +RLMSchemaInfo::impl::iterator RLMSchemaInfo::end() noexcept { return m_objects.end(); } +RLMSchemaInfo::impl::const_iterator RLMSchemaInfo::begin() const noexcept { return m_objects.begin(); } +RLMSchemaInfo::impl::const_iterator RLMSchemaInfo::end() const noexcept { return m_objects.end(); } + +RLMClassInfo& RLMSchemaInfo::operator[](NSString *name) { + auto it = m_objects.find(name); + if (it == m_objects.end()) { + @throw RLMException(@"Object type '%@' is not managed by the Realm. " + @"If using a custom `objectClasses` / `objectTypes` array in your configuration, " + @"add `%@` to the list of `objectClasses` / `objectTypes`.", + name, name); + } + return *&it->second; +} + +RLMSchemaInfo::RLMSchemaInfo(RLMRealm *realm) { + RLMSchema *rlmSchema = realm.schema; + realm::Schema const& schema = realm->_realm->schema(); + // rlmSchema can be larger due to multiple classes backed by one table + REALM_ASSERT(rlmSchema.objectSchema.count >= schema.size()); + + m_objects.reserve(schema.size()); + for (RLMObjectSchema *rlmObjectSchema in rlmSchema.objectSchema) { + m_objects.emplace(std::piecewise_construct, + std::forward_as_tuple(rlmObjectSchema.className), + std::forward_as_tuple(realm, rlmObjectSchema, + &*schema.find(rlmObjectSchema.objectName.UTF8String))); + } +} + +RLMSchemaInfo RLMSchemaInfo::clone(realm::Schema const& source_schema, + __unsafe_unretained RLMRealm *const target_realm) { + RLMSchemaInfo info; + info.m_objects.reserve(m_objects.size()); + + auto& schema = target_realm->_realm->schema(); + for (auto& pair : m_objects) { + size_t idx = pair.second.objectSchema - &*source_schema.begin(); + info.m_objects.emplace(std::piecewise_construct, + std::forward_as_tuple(pair.first), + std::forward_as_tuple(target_realm, pair.second.rlmObjectSchema, + &*schema.begin() + idx)); + } + return info; +} diff --git a/Pods/Realm/Realm/RLMCollection.mm b/Pods/Realm/Realm/RLMCollection.mm new file mode 100644 index 0000000000..360789a6bc --- /dev/null +++ b/Pods/Realm/Realm/RLMCollection.mm @@ -0,0 +1,423 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMCollection_Private.hpp" + +#import "RLMAccessor.hpp" +#import "RLMArray_Private.hpp" +#import "RLMListBase.h" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObjectStore.h" +#import "RLMObject_Private.hpp" +#import "RLMProperty_Private.h" + +#import "collection_notifications.hpp" +#import "list.hpp" +#import "results.hpp" + +static const int RLMEnumerationBufferSize = 16; + +@implementation RLMFastEnumerator { + // The buffer supplied by fast enumeration does not retain the objects given + // to it, but because we create objects on-demand and don't want them + // autoreleased (a table can have more rows than the device has memory for + // accessor objects) we need a thing to retain them. + id _strongBuffer[RLMEnumerationBufferSize]; + + RLMRealm *_realm; + RLMClassInfo *_info; + + // A pointer to either _snapshot or a Results from the source collection, + // to avoid having to copy the Results when not in a write transaction + realm::Results *_results; + realm::Results _snapshot; + + // A strong reference to the collection being enumerated to ensure it stays + // alive when we're holding a pointer to a member in it + id _collection; +} + +- (instancetype)initWithList:(realm::List&)list + collection:(id)collection + realm:(RLMRealm *)realm + classInfo:(RLMClassInfo&)info +{ + self = [super init]; + if (self) { + if (realm.inWriteTransaction) { + _snapshot = list.snapshot(); + } + else { + _snapshot = list.as_results(); + _collection = collection; + [realm registerEnumerator:self]; + } + _results = &_snapshot; + _realm = realm; + _info = &info; + } + return self; +} + +- (instancetype)initWithResults:(realm::Results&)results + collection:(id)collection + realm:(RLMRealm *)realm + classInfo:(RLMClassInfo&)info +{ + self = [super init]; + if (self) { + if (realm.inWriteTransaction) { + _snapshot = results.snapshot(); + _results = &_snapshot; + } + else { + _results = &results; + _collection = collection; + [realm registerEnumerator:self]; + } + _realm = realm; + _info = &info; + } + return self; +} + +- (void)dealloc { + if (_collection) { + [_realm unregisterEnumerator:self]; + } +} + +- (void)detach { + _snapshot = _results->snapshot(); + _results = &_snapshot; + _collection = nil; +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state + count:(NSUInteger)len { + [_realm verifyThread]; + if (!_results->is_valid()) { + @throw RLMException(@"Collection is no longer valid"); + } + // The fast enumeration buffer size is currently a hardcoded number in the + // compiler so this can't actually happen, but just in case it changes in + // the future... + if (len > RLMEnumerationBufferSize) { + len = RLMEnumerationBufferSize; + } + + NSUInteger batchCount = 0, count = state->extra[1]; + + @autoreleasepool { + RLMAccessorContext ctx(_realm, *_info); + for (NSUInteger index = state->state; index < count && batchCount < len; ++index) { + _strongBuffer[batchCount] = _results->get(ctx, index); + batchCount++; + } + } + + for (NSUInteger i = batchCount; i < len; ++i) { + _strongBuffer[i] = nil; + } + + if (batchCount == 0) { + // Release our data if we're done, as we're autoreleased and so may + // stick around for a while + if (_collection) { + _collection = nil; + [_realm unregisterEnumerator:self]; + } + _snapshot = {}; + } + + state->itemsPtr = (__unsafe_unretained id *)(void *)_strongBuffer; + state->state += batchCount; + state->mutationsPtr = state->extra+1; + + return batchCount; +} +@end + +NSUInteger RLMFastEnumerate(NSFastEnumerationState *state, NSUInteger len, id collection) { + __autoreleasing RLMFastEnumerator *enumerator; + if (state->state == 0) { + enumerator = collection.fastEnumerator; + state->extra[0] = (long)enumerator; + state->extra[1] = collection.count; + } + else { + enumerator = (__bridge id)(void *)state->extra[0]; + } + + return [enumerator countByEnumeratingWithState:state count:len]; +} + +template +NSArray *RLMCollectionValueForKey(Collection& collection, NSString *key, + RLMRealm *realm, RLMClassInfo& info) { + size_t count = collection.size(); + if (count == 0) { + return @[]; + } + + NSMutableArray *array = [NSMutableArray arrayWithCapacity:count]; + if ([key isEqualToString:@"self"]) { + RLMAccessorContext context(realm, info); + for (size_t i = 0; i < count; ++i) { + [array addObject:collection.get(context, i) ?: NSNull.null]; + } + return array; + } + + if (collection.get_type() != realm::PropertyType::Object) { + RLMAccessorContext context(realm, info); + for (size_t i = 0; i < count; ++i) { + [array addObject:[collection.get(context, i) valueForKey:key] ?: NSNull.null]; + } + return array; + } + + RLMObject *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, realm, &info); + + // List properties need to be handled specially since we need to create a + // new List each time + if (info.rlmObjectSchema.isSwiftClass) { + auto prop = info.rlmObjectSchema[key]; + if (prop && prop.array && prop.swiftIvar) { + // Grab the actual class for the generic List from an instance of it + // so that we can make instances of the List without creating a new + // object accessor each time + Class cls = [object_getIvar(accessor, prop.swiftIvar) class]; + RLMAccessorContext context(realm, info); + for (size_t i = 0; i < count; ++i) { + RLMListBase *list = [[cls alloc] init]; + list._rlmArray = [[RLMManagedArray alloc] initWithList:realm::List(realm->_realm, *info.table(), + info.tableColumn(prop), + collection.get(i).get_index()) + realm:realm parentInfo:&info + property:prop]; + [array addObject:list]; + } + return array; + } + } + + for (size_t i = 0; i < count; i++) { + accessor->_row = collection.get(i); + RLMInitializeSwiftAccessorGenerics(accessor); + [array addObject:[accessor valueForKey:key] ?: NSNull.null]; + } + return array; +} + +template NSArray *RLMCollectionValueForKey(realm::Results&, NSString *, RLMRealm *, RLMClassInfo&); +template NSArray *RLMCollectionValueForKey(realm::List&, NSString *, RLMRealm *, RLMClassInfo&); + +void RLMCollectionSetValueForKey(id collection, NSString *key, id value) { + realm::TableView tv = [collection tableView]; + if (tv.size() == 0) { + return; + } + + RLMRealm *realm = collection.realm; + RLMClassInfo *info = collection.objectInfo; + RLMObject *accessor = RLMCreateManagedAccessor(info->rlmObjectSchema.accessorClass, realm, info); + for (size_t i = 0; i < tv.size(); i++) { + accessor->_row = tv[i]; + RLMInitializeSwiftAccessorGenerics(accessor); + [accessor setValue:value forKey:key]; + } +} + +NSString *RLMDescriptionWithMaxDepth(NSString *name, + id collection, + NSUInteger depth) { + if (depth == 0) { + return @""; + } + + const NSUInteger maxObjects = 100; + auto str = [NSMutableString stringWithFormat:@"%@<%@> <%p> (\n", name, + [collection objectClassName] ?: RLMTypeToString([collection type]), + (void *)collection]; + size_t index = 0, skipped = 0; + for (id obj in collection) { + NSString *sub; + if ([obj respondsToSelector:@selector(descriptionWithMaxDepth:)]) { + sub = [obj descriptionWithMaxDepth:depth - 1]; + } + else { + sub = [obj description]; + } + + // Indent child objects + NSString *objDescription = [sub stringByReplacingOccurrencesOfString:@"\n" + withString:@"\n\t"]; + [str appendFormat:@"\t[%zu] %@,\n", index++, objDescription]; + if (index >= maxObjects) { + skipped = collection.count - maxObjects; + break; + } + } + + // Remove last comma and newline characters + if (collection.count > 0) { + [str deleteCharactersInRange:NSMakeRange(str.length-2, 2)]; + } + if (skipped) { + [str appendFormat:@"\n\t... %zu objects skipped.", skipped]; + } + [str appendFormat:@"\n)"]; + return str; +} + +std::vector> RLMSortDescriptorsToKeypathArray(NSArray *properties) { + std::vector> keypaths; + keypaths.reserve(properties.count); + for (RLMSortDescriptor *desc in properties) { + if ([desc.keyPath rangeOfString:@"@"].location != NSNotFound) { + @throw RLMException(@"Cannot sort on key path '%@': KVC collection operators are not supported.", desc.keyPath); + } + keypaths.push_back({desc.keyPath.UTF8String, desc.ascending}); + } + return keypaths; +} + +@implementation RLMCancellationToken { + realm::NotificationToken _token; + __unsafe_unretained RLMRealm *_realm; +} +- (instancetype)initWithToken:(realm::NotificationToken)token realm:(RLMRealm *)realm { + self = [super init]; + if (self) { + _token = std::move(token); + _realm = realm; + } + return self; +} + +- (RLMRealm *)realm { + return _realm; +} + +- (void)suppressNextNotification { + _token.suppress_next(); +} + +- (void)invalidate { + _token = {}; +} + +@end + +@implementation RLMCollectionChange { + realm::CollectionChangeSet _indices; +} + +- (instancetype)initWithChanges:(realm::CollectionChangeSet)indices { + self = [super init]; + if (self) { + _indices = std::move(indices); + } + return self; +} + +static NSArray *toArray(realm::IndexSet const& set) { + NSMutableArray *ret = [NSMutableArray new]; + for (auto index : set.as_indexes()) { + [ret addObject:@(index)]; + } + return ret; +} + +- (NSArray *)insertions { + return toArray(_indices.insertions); +} + +- (NSArray *)deletions { + return toArray(_indices.deletions); +} + +- (NSArray *)modifications { + return toArray(_indices.modifications); +} + +static NSArray *toIndexPathArray(realm::IndexSet const& set, NSUInteger section) { + NSMutableArray *ret = [NSMutableArray new]; + NSUInteger path[2] = {section, 0}; + for (auto index : set.as_indexes()) { + path[1] = index; + [ret addObject:[NSIndexPath indexPathWithIndexes:path length:2]]; + } + return ret; +} + +- (NSArray *)deletionsInSection:(NSUInteger)section { + return toIndexPathArray(_indices.deletions, section); +} + +- (NSArray *)insertionsInSection:(NSUInteger)section { + return toIndexPathArray(_indices.insertions, section); + +} + +- (NSArray *)modificationsInSection:(NSUInteger)section { + return toIndexPathArray(_indices.modifications, section); + +} +@end + +template +RLMNotificationToken *RLMAddNotificationBlock(id objcCollection, + Collection& collection, + void (^block)(id, RLMCollectionChange *, NSError *), + bool suppressInitialChange) { + auto skip = suppressInitialChange ? std::make_shared(true) : nullptr; + auto cb = [=, &collection](realm::CollectionChangeSet const& changes, + std::exception_ptr err) { + if (err) { + try { + rethrow_exception(err); + } + catch (...) { + NSError *error = nil; + RLMRealmTranslateException(&error); + block(nil, nil, error); + return; + } + } + + if (skip && *skip) { + *skip = false; + block(objcCollection, nil, nil); + } + else if (changes.empty()) { + block(objcCollection, nil, nil); + } + else { + block(objcCollection, [[RLMCollectionChange alloc] initWithChanges:changes], nil); + } + }; + + return [[RLMCancellationToken alloc] initWithToken:collection.add_notification_callback(cb) + realm:(RLMRealm *)[objcCollection realm]]; +} + +// Explicitly instantiate the templated function for the two types we'll use it on +template RLMNotificationToken *RLMAddNotificationBlock(id, realm::List&, void (^)(id, RLMCollectionChange *, NSError *), bool); +template RLMNotificationToken *RLMAddNotificationBlock(id, realm::Results&, void (^)(id, RLMCollectionChange *, NSError *), bool); diff --git a/Pods/Realm/Realm/RLMConstants.m b/Pods/Realm/Realm/RLMConstants.m new file mode 100644 index 0000000000..b45638f00d --- /dev/null +++ b/Pods/Realm/Realm/RLMConstants.m @@ -0,0 +1,36 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +RLMNotification const RLMRealmRefreshRequiredNotification = @"RLMRealmRefreshRequiredNotification"; +RLMNotification const RLMRealmDidChangeNotification = @"RLMRealmDidChangeNotification"; + +NSString * const RLMErrorDomain = @"io.realm"; + +NSString * const RLMUnknownSystemErrorDomain = @"io.realm.unknown"; + +NSString * const RLMExceptionName = @"RLMException"; + +NSString * const RLMRealmVersionKey = @"RLMRealmVersion"; + +NSString * const RLMRealmCoreVersionKey = @"RLMRealmCoreVersion"; + +NSString * const RLMInvalidatedKey = @"invalidated"; + +NSString * const RLMBackupRealmConfigurationErrorKey = @"RLMBackupRealmConfiguration"; diff --git a/Pods/Realm/Realm/RLMJSONModels.m b/Pods/Realm/Realm/RLMJSONModels.m new file mode 100644 index 0000000000..3dc03eade5 --- /dev/null +++ b/Pods/Realm/Realm/RLMJSONModels.m @@ -0,0 +1,232 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMJSONModels.h" +#import "RLMSyncUtil_Private.h" +#import "RLMSyncUser.h" + +#pragma mark - Constants + +static const NSString *const kRLMSyncAccessTokenKey = @"access_token"; +static const NSString *const kRLMSyncAccountsKey = @"accounts"; +static const NSString *const kRLMSyncErrorCodeKey = @"code"; +static const NSString *const kRLMSyncExpiresKey = @"expires"; +static const NSString *const kRLMSyncErrorHintKey = @"hint"; +static const NSString *const kRLMSyncIdKey = @"id"; +static const NSString *const kRLMSyncKeyKey = @"key"; +static const NSString *const kRLMSyncMetadataKey = @"metadata"; +static const NSString *const kRLMSyncRefreshTokenKey = @"refresh_token"; +static const NSString *const kRLMSyncErrorStatusKey = @"status"; +static const NSString *const kRLMSyncErrorTitleKey = @"title"; +static const NSString *const kRLMSyncTokenDataKey = @"token_data"; +static const NSString *const kRLMSyncUserKey = @"user"; +static const NSString *const kRLMSyncValueKey = @"value"; + +#pragma mark - RLMTokenDataModel + +@interface RLMTokenDataModel () + +@property (nonatomic, readwrite) NSString *identity; +@property (nonatomic, readwrite) NSString *appID; +@property (nonatomic, readwrite) NSString *path; +@property (nonatomic, readwrite) NSTimeInterval expires; +@property (nonatomic, readwrite) BOOL isAdmin; +//@property (nonatomic, readwrite) NSArray *access; + +@end + +@implementation RLMTokenDataModel + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { + if (self = [super init]) { + self.isAdmin = NO; + RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncIdentityKey, identity); + RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncAppIDKey, appID); + RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncPathKey, path); + RLM_SYNC_PARSE_OPTIONAL_BOOL(jsonDictionary, kRLMSyncIsAdminKey, isAdmin); + RLM_SYNC_PARSE_DOUBLE_OR_ABORT(jsonDictionary, kRLMSyncExpiresKey, expires); + return self; + } + return nil; +} + +@end + +#pragma mark - RLMTokenModel + +@interface RLMTokenModel () + +@property (nonatomic, readwrite) NSString *token; +@property (nonatomic, nullable, readwrite) NSString *path; +@property (nonatomic, readwrite) RLMTokenDataModel *tokenData; + +@end + +@implementation RLMTokenModel + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { + if (self = [super init]) { + RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncTokenKey, token); + RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncPathKey, path); + RLM_SYNC_PARSE_MODEL_OR_ABORT(jsonDictionary, kRLMSyncTokenDataKey, RLMTokenDataModel, tokenData); + return self; + } + return nil; +} + +@end + +#pragma mark - RLMAuthResponseModel + +@interface RLMAuthResponseModel () + +@property (nonatomic, readwrite) RLMTokenModel *accessToken; +@property (nonatomic, readwrite) RLMTokenModel *refreshToken; + +@end + +@implementation RLMAuthResponseModel + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary + requireAccessToken:(BOOL)requireAccessToken + requireRefreshToken:(BOOL)requireRefreshToken { + if (self = [super init]) { + // Get the access token. + if (requireAccessToken) { + RLM_SYNC_PARSE_MODEL_OR_ABORT(jsonDictionary, kRLMSyncAccessTokenKey, RLMTokenModel, accessToken); + } else { + RLM_SYNC_PARSE_OPTIONAL_MODEL(jsonDictionary, kRLMSyncAccessTokenKey, RLMTokenModel, accessToken); + } + // Get the refresh token. + if (requireRefreshToken) { + RLM_SYNC_PARSE_MODEL_OR_ABORT(jsonDictionary, kRLMSyncRefreshTokenKey, RLMTokenModel, refreshToken); + } else { + RLM_SYNC_PARSE_OPTIONAL_MODEL(jsonDictionary, kRLMSyncRefreshTokenKey, RLMTokenModel, refreshToken); + } + return self; + } + return nil; +} + +@end + +#pragma mark - RLMUserInfoResponseModel + +@interface RLMSyncUserAccountInfo () +@property (nonatomic, readwrite) NSString *provider; +@property (nonatomic, readwrite) NSString *providerUserIdentity; +@end + +@implementation RLMSyncUserAccountInfo + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { + if (self = [super init]) { + RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncProviderKey, provider); + RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncProviderIDKey, providerUserIdentity); + return self; + } + return nil; +} + +@end + +@interface RLMUserResponseModel () + +@property (nonatomic, readwrite) NSString *identity; +@property (nonatomic, readwrite) NSArray *accounts; +@property (nonatomic, readwrite) NSDictionary *metadata; +@property (nonatomic, readwrite) BOOL isAdmin; + +@end + +@implementation RLMUserResponseModel + +- (void)parseMetadataFromJSON:(NSDictionary *)jsonDictionary { + NSMutableDictionary *buffer = [NSMutableDictionary dictionary]; + NSArray *metadataArray = jsonDictionary[kRLMSyncMetadataKey]; + if (![metadataArray isKindOfClass:[NSArray class]]) { + self.metadata = @{}; + return; + } + for (NSDictionary *object in metadataArray) { + if (![object isKindOfClass:[NSDictionary class]]) { + continue; + } + NSString *key = object[kRLMSyncKeyKey]; + NSString *value = object[kRLMSyncValueKey]; + if (!key || !value) { + continue; + } + buffer[key] = value; + } + self.metadata = [buffer copy]; +} + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { + if (self = [super init]) { + self.isAdmin = NO; + RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncUserIDKey, identity); + RLM_SYNC_PARSE_OPTIONAL_BOOL(jsonDictionary, kRLMSyncIsAdminKey, isAdmin); + RLM_SYNC_PARSE_MODEL_ARRAY_OR_ABORT(jsonDictionary, kRLMSyncAccountsKey, RLMSyncUserAccountInfo, accounts); + [self parseMetadataFromJSON:jsonDictionary]; + return self; + } + return nil; +} + +@end + +#pragma mark - RLMSyncErrorResponseModel + +@interface RLMSyncErrorResponseModel () + +@property (nonatomic, readwrite) NSInteger status; +@property (nonatomic, readwrite) NSInteger code; +@property (nonatomic, readwrite) NSString *title; +@property (nonatomic, readwrite) NSString *hint; + +@end + +@implementation RLMSyncErrorResponseModel + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { + if (self = [super init]) { + RLM_SYNC_PARSE_DOUBLE_OR_ABORT(jsonDictionary, kRLMSyncErrorStatusKey, status); + RLM_SYNC_PARSE_DOUBLE_OR_ABORT(jsonDictionary, kRLMSyncErrorCodeKey, code); + RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncErrorTitleKey, title); + RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncErrorHintKey, hint); + + NSString *detail = jsonDictionary[@"detail"]; + if ([detail isKindOfClass:[NSString class]]) { + _title = detail; + } + + for (NSDictionary *problem in jsonDictionary[@"invalid_params"]) { + NSString *name = problem[@"name"]; + NSString *reason = problem[@"reason"]; + if (name && reason) { + _title = [NSString stringWithFormat:@"%@ %@: %@;", _title, name, reason]; + } + } + + return self; + } + return nil; +} + +@end diff --git a/Pods/Realm/Realm/RLMListBase.mm b/Pods/Realm/Realm/RLMListBase.mm new file mode 100644 index 0000000000..6988accbbc --- /dev/null +++ b/Pods/Realm/Realm/RLMListBase.mm @@ -0,0 +1,64 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMListBase.h" + +#import "RLMArray_Private.hpp" +#import "RLMObservation.hpp" + +@interface RLMArray (KVO) +- (NSArray *)objectsAtIndexes:(__unused NSIndexSet *)indexes; +@end + +@implementation RLMListBase { + std::unique_ptr _observationInfo; +} + +- (instancetype)initWithArray:(RLMArray *)array { + self = [super init]; + if (self) { + __rlmArray = array; + } + return self; +} + +- (id)valueForKey:(NSString *)key { + return [__rlmArray valueForKey:key]; +} + +- (id)valueForKeyPath:(NSString *)keyPath { + return [__rlmArray valueForKeyPath:keyPath]; +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len { + return [__rlmArray countByEnumeratingWithState:state objects:buffer count:len]; +} + +- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes { + return [__rlmArray objectsAtIndexes:indexes]; +} + +- (void)addObserver:(id)observer + forKeyPath:(NSString *)keyPath + options:(NSKeyValueObservingOptions)options + context:(void *)context { + RLMEnsureArrayObservationInfo(_observationInfo, keyPath, __rlmArray, self); + [super addObserver:observer forKeyPath:keyPath options:options context:context]; +} + +@end diff --git a/Pods/Realm/Realm/RLMManagedArray.mm b/Pods/Realm/Realm/RLMManagedArray.mm new file mode 100644 index 0000000000..25936181d2 --- /dev/null +++ b/Pods/Realm/Realm/RLMManagedArray.mm @@ -0,0 +1,545 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMArray_Private.hpp" + +#import "RLMAccessor.hpp" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObjectStore.h" +#import "RLMObject_Private.hpp" +#import "RLMObservation.hpp" +#import "RLMProperty_Private.h" +#import "RLMQueryUtil.hpp" +#import "RLMRealm_Private.hpp" +#import "RLMSchema.h" +#import "RLMThreadSafeReference_Private.hpp" +#import "RLMUtil.hpp" + +#import "list.hpp" +#import "results.hpp" +#import "shared_realm.hpp" + +#import +#import + +@interface RLMManagedArrayHandoverMetadata : NSObject +@property (nonatomic) NSString *parentClassName; +@property (nonatomic) NSString *key; +@end + +@implementation RLMManagedArrayHandoverMetadata +@end + +@interface RLMManagedArray () +@end + +// +// RLMArray implementation +// +@implementation RLMManagedArray { +@public + realm::List _backingList; + RLMRealm *_realm; + RLMClassInfo *_objectInfo; + RLMClassInfo *_ownerInfo; + std::unique_ptr _observationInfo; +} + +- (RLMManagedArray *)initWithList:(realm::List)list + realm:(__unsafe_unretained RLMRealm *const)realm + parentInfo:(RLMClassInfo *)parentInfo + property:(__unsafe_unretained RLMProperty *const)property { + if (property.type == RLMPropertyTypeObject) + self = [self initWithObjectClassName:property.objectClassName]; + else + self = [self initWithObjectType:property.type optional:property.optional]; + if (self) { + _realm = realm; + REALM_ASSERT(list.get_realm() == realm->_realm); + _backingList = std::move(list); + _ownerInfo = parentInfo; + if (property.type == RLMPropertyTypeObject) + _objectInfo = &parentInfo->linkTargetType(property.index); + else + _objectInfo = _ownerInfo; + _key = property.name; + } + return self; +} + +- (RLMManagedArray *)initWithParent:(__unsafe_unretained RLMObjectBase *const)parentObject + property:(__unsafe_unretained RLMProperty *const)property { + __unsafe_unretained RLMRealm *const realm = parentObject->_realm; + auto col = parentObject->_info->tableColumn(property); + auto& row = parentObject->_row; + return [self initWithList:realm::List(realm->_realm, *row.get_table(), col, row.get_index()) + realm:realm + parentInfo:parentObject->_info + property:property]; +} + +void RLMValidateArrayObservationKey(__unsafe_unretained NSString *const keyPath, + __unsafe_unretained RLMArray *const array) { + if (![keyPath isEqualToString:RLMInvalidatedKey]) { + @throw RLMException(@"[<%@ %p> addObserver:forKeyPath:options:context:] is not supported. Key path: %@", + [array class], array, keyPath); + } +} + +void RLMEnsureArrayObservationInfo(std::unique_ptr& info, + __unsafe_unretained NSString *const keyPath, + __unsafe_unretained RLMArray *const array, + __unsafe_unretained id const observed) { + RLMValidateArrayObservationKey(keyPath, array); + if (!info && array.class == [RLMManagedArray class]) { + auto lv = static_cast(array); + info = std::make_unique(*lv->_ownerInfo, + lv->_backingList.get_origin_row_index(), + observed); + } +} + +// +// validation helpers +// +[[gnu::noinline]] +[[noreturn]] +static void throwError(__unsafe_unretained RLMManagedArray *const ar, NSString *aggregateMethod) { + try { + throw; + } + catch (realm::InvalidTransactionException const&) { + @throw RLMException(@"Cannot modify managed RLMArray outside of a write transaction."); + } + catch (realm::IncorrectThreadException const&) { + @throw RLMException(@"Realm accessed from incorrect thread."); + } + catch (realm::List::InvalidatedException const&) { + @throw RLMException(@"RLMArray has been invalidated or the containing object has been deleted."); + } + catch (realm::List::OutOfBoundsIndexException const& e) { + @throw RLMException(@"Index %zu is out of bounds (must be less than %zu).", + e.requested, e.valid_count); + } + catch (realm::Results::UnsupportedColumnTypeException const& e) { + if (ar->_backingList.get_type() == realm::PropertyType::Object) { + @throw RLMException(@"%@: is not supported for %s%s property '%s'.", + aggregateMethod, + string_for_property_type(e.property_type), + is_nullable(e.property_type) ? "?" : "", + e.column_name.data()); + } + @throw RLMException(@"%@: is not supported for %s%s array '%@.%@'.", + aggregateMethod, + string_for_property_type(e.property_type), + is_nullable(e.property_type) ? "?" : "", + ar->_ownerInfo->rlmObjectSchema.className, ar->_key); + } + catch (std::logic_error const& e) { + @throw RLMException(e); + } +} + +template +static auto translateErrors(__unsafe_unretained RLMManagedArray *const ar, + Function&& f, NSString *aggregateMethod=nil) { + try { + return f(); + } + catch (...) { + throwError(ar, aggregateMethod); + } +} + +template +static auto translateErrors(Function&& f) { + try { + return f(); + } + catch (...) { + throwError(nil, nil); + } +} + +template +static void changeArray(__unsafe_unretained RLMManagedArray *const ar, + NSKeyValueChange kind, dispatch_block_t f, IndexSetFactory&& is) { + translateErrors([&] { ar->_backingList.verify_in_transaction(); }); + RLMObservationInfo *info = RLMGetObservationInfo(ar->_observationInfo.get(), + ar->_backingList.get_origin_row_index(), + *ar->_ownerInfo); + if (info) { + NSIndexSet *indexes = is(); + info->willChange(ar->_key, kind, indexes); + try { + f(); + } + catch (...) { + info->didChange(ar->_key, kind, indexes); + throwError(ar, nil); + } + info->didChange(ar->_key, kind, indexes); + } + else { + translateErrors([&] { f(); }); + } +} + +static void changeArray(__unsafe_unretained RLMManagedArray *const ar, NSKeyValueChange kind, NSUInteger index, dispatch_block_t f) { + changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndex:index]; }); +} + +static void changeArray(__unsafe_unretained RLMManagedArray *const ar, NSKeyValueChange kind, NSRange range, dispatch_block_t f) { + changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndexesInRange:range]; }); +} + +static void changeArray(__unsafe_unretained RLMManagedArray *const ar, NSKeyValueChange kind, NSIndexSet *is, dispatch_block_t f) { + changeArray(ar, kind, f, [=] { return is; }); +} + +// +// public method implementations +// +- (RLMRealm *)realm { + return _realm; +} + +- (NSUInteger)count { + return translateErrors([&] { return _backingList.size(); }); +} + +- (BOOL)isInvalidated { + return translateErrors([&] { return !_backingList.is_valid(); }); +} + +- (RLMClassInfo *)objectInfo { + return _objectInfo; +} + + +- (bool)isBackedByList:(realm::List const&)list { + return _backingList == list; +} + +- (BOOL)isEqual:(id)object { + return [object respondsToSelector:@selector(isBackedByList:)] && [object isBackedByList:_backingList]; +} + +- (NSUInteger)hash { + return std::hash()(_backingList); +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state + objects:(__unused __unsafe_unretained id [])buffer + count:(NSUInteger)len { + return RLMFastEnumerate(state, len, self); +} + +- (id)objectAtIndex:(NSUInteger)index { + return translateErrors([&] { + RLMAccessorContext context(_realm, *_objectInfo); + return _backingList.get(context, index); + }); +} + +static void RLMInsertObject(RLMManagedArray *ar, id object, NSUInteger index) { + RLMArrayValidateMatchingObjectType(ar, object); + if (index == NSUIntegerMax) { + index = translateErrors([&] { return ar->_backingList.size(); }); + } + + changeArray(ar, NSKeyValueChangeInsertion, index, ^{ + RLMAccessorContext context(ar->_realm, *ar->_objectInfo); + ar->_backingList.insert(context, index, object); + }); +} + +- (void)addObject:(id)object { + RLMInsertObject(self, object, NSUIntegerMax); +} + +- (void)insertObject:(id)object atIndex:(NSUInteger)index { + RLMInsertObject(self, object, index); +} + +- (void)insertObjects:(id)objects atIndexes:(NSIndexSet *)indexes { + changeArray(self, NSKeyValueChangeInsertion, indexes, ^{ + NSUInteger index = [indexes firstIndex]; + RLMAccessorContext context(_realm, *_objectInfo); + for (id obj in objects) { + RLMArrayValidateMatchingObjectType(self, obj); + _backingList.insert(context, index, obj); + index = [indexes indexGreaterThanIndex:index]; + } + }); +} + + +- (void)removeObjectAtIndex:(NSUInteger)index { + changeArray(self, NSKeyValueChangeRemoval, index, ^{ + _backingList.remove(index); + }); +} + +- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes { + changeArray(self, NSKeyValueChangeRemoval, indexes, ^{ + [indexes enumerateIndexesWithOptions:NSEnumerationReverse usingBlock:^(NSUInteger idx, BOOL *) { + _backingList.remove(idx); + }]; + }); +} + +- (void)addObjectsFromArray:(NSArray *)array { + changeArray(self, NSKeyValueChangeInsertion, NSMakeRange(self.count, array.count), ^{ + RLMAccessorContext context(_realm, *_objectInfo); + for (id obj in array) { + RLMArrayValidateMatchingObjectType(self, obj); + _backingList.add(context, obj); + } + }); +} + +- (void)removeAllObjects { + changeArray(self, NSKeyValueChangeRemoval, NSMakeRange(0, self.count), ^{ + _backingList.remove_all(); + }); +} + +- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { + RLMArrayValidateMatchingObjectType(self, object); + changeArray(self, NSKeyValueChangeReplacement, index, ^{ + RLMAccessorContext context(_realm, *_objectInfo); + _backingList.set(context, index, object); + }); +} + +- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex { + auto start = std::min(sourceIndex, destinationIndex); + auto len = std::max(sourceIndex, destinationIndex) - start + 1; + changeArray(self, NSKeyValueChangeReplacement, {start, len}, ^{ + _backingList.move(sourceIndex, destinationIndex); + }); +} + +- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 { + changeArray(self, NSKeyValueChangeReplacement, ^{ + _backingList.swap(index1, index2); + }, [=] { + NSMutableIndexSet *set = [[NSMutableIndexSet alloc] initWithIndex:index1]; + [set addIndex:index2]; + return set; + }); +} + +- (NSUInteger)indexOfObject:(id)object { + RLMArrayValidateMatchingObjectType(self, object); + return translateErrors([&] { + RLMAccessorContext context(_realm, *_objectInfo); + return RLMConvertNotFound(_backingList.find(context, object)); + }); +} + +- (id)valueForKeyPath:(NSString *)keyPath { + if ([keyPath hasPrefix:@"@"]) { + // Delegate KVC collection operators to RLMResults + return translateErrors([&] { + auto results = [RLMResults resultsWithObjectInfo:*_objectInfo results:_backingList.as_results()]; + return [results valueForKeyPath:keyPath]; + }); + } + return [super valueForKeyPath:keyPath]; +} + +- (id)valueForKey:(NSString *)key { + // Ideally we'd use "@invalidated" for this so that "invalidated" would use + // normal array KVC semantics, but observing @things works very oddly (when + // it's part of a key path, it's triggered automatically when array index + // changes occur, and can't be sent explicitly, but works normally when it's + // the entire key path), and an RLMManagedArray *can't* have objects where + // invalidated is true, so we're not losing much. + return translateErrors([&]() -> id { + if ([key isEqualToString:RLMInvalidatedKey]) { + return @(!_backingList.is_valid()); + } + + _backingList.verify_attached(); + return RLMCollectionValueForKey(_backingList, key, _realm, *_objectInfo); + }); +} + +- (void)setValue:(id)value forKey:(NSString *)key { + if ([key isEqualToString:@"self"]) { + RLMArrayValidateMatchingObjectType(self, value); + RLMAccessorContext context(_realm, *_objectInfo); + translateErrors([&] { + for (size_t i = 0, count = _backingList.size(); i < count; ++i) { + _backingList.set(context, i, value); + } + }); + return; + } + else if (_type == RLMPropertyTypeObject) { + RLMArrayValidateMatchingObjectType(self, value); + translateErrors([&] { _backingList.verify_in_transaction(); }); + RLMCollectionSetValueForKey(self, key, value); + } + else { + [self setValue:value forUndefinedKey:key]; + } +} + +- (size_t)columnForProperty:(NSString *)propertyName { + if (_backingList.get_type() == realm::PropertyType::Object) { + return _objectInfo->tableColumn(propertyName); + } + if (![propertyName isEqualToString:@"self"]) { + @throw RLMException(@"Arrays of '%@' can only be aggregated on \"self\"", RLMTypeToString(_type)); + } + return 0; +} + +- (id)minOfProperty:(NSString *)property { + size_t column = [self columnForProperty:property]; + auto value = translateErrors(self, [&] { return _backingList.min(column); }, @"minOfProperty"); + return value ? RLMMixedToObjc(*value) : nil; +} + +- (id)maxOfProperty:(NSString *)property { + size_t column = [self columnForProperty:property]; + auto value = translateErrors(self, [&] { return _backingList.max(column); }, @"maxOfProperty"); + return value ? RLMMixedToObjc(*value) : nil; +} + +- (id)sumOfProperty:(NSString *)property { + size_t column = [self columnForProperty:property]; + return RLMMixedToObjc(translateErrors(self, [&] { return _backingList.sum(column); }, @"sumOfProperty")); +} + +- (id)averageOfProperty:(NSString *)property { + size_t column = [self columnForProperty:property]; + auto value = translateErrors(self, [&] { return _backingList.average(column); }, @"averageOfProperty"); + return value ? @(*value) : nil; +} + +- (void)deleteObjectsFromRealm { + if (_type != RLMPropertyTypeObject) { + @throw RLMException(@"Cannot delete objects from RLMArray<%@>: only RLMObjects can be deleted.", RLMTypeToString(_type)); + } + // delete all target rows from the realm + RLMTrackDeletions(_realm, ^{ + translateErrors([&] { _backingList.delete_all(); }); + }); +} + +- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties { + return translateErrors([&] { + return [RLMResults resultsWithObjectInfo:*_objectInfo + results:_backingList.sort(RLMSortDescriptorsToKeypathArray(properties))]; + }); +} + +- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate { + if (_type != RLMPropertyTypeObject) { + @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects"); + } + auto query = RLMPredicateToQuery(predicate, _objectInfo->rlmObjectSchema, _realm.schema, _realm.group); + auto results = translateErrors([&] { return _backingList.filter(std::move(query)); }); + return [RLMResults resultsWithObjectInfo:*_objectInfo results:std::move(results)]; +} + +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate { + if (_type != RLMPropertyTypeObject) { + @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects"); + } + realm::Query query = RLMPredicateToQuery(predicate, _objectInfo->rlmObjectSchema, + _realm.schema, _realm.group); + + return translateErrors([&] { + return RLMConvertNotFound(_backingList.find(std::move(query))); + }); +} + +- (NSArray *)objectsAtIndexes:(__unused NSIndexSet *)indexes { + // FIXME: this is called by KVO when array changes are made. It's not clear + // why, and returning nil seems to work fine. + return nil; +} + +- (void)addObserver:(id)observer + forKeyPath:(NSString *)keyPath + options:(NSKeyValueObservingOptions)options + context:(void *)context { + RLMEnsureArrayObservationInfo(_observationInfo, keyPath, self, self); + [super addObserver:observer forKeyPath:keyPath options:options context:context]; +} + +- (realm::TableView)tableView { + return translateErrors([&] { return _backingList.get_query(); }).find_all(); +} + +- (RLMFastEnumerator *)fastEnumerator { + return translateErrors([&] { + return [[RLMFastEnumerator alloc] initWithList:_backingList collection:self + realm:_realm classInfo:*_objectInfo]; + }); +} + +// The compiler complains about the method's argument type not matching due to +// it not having the generic type attached, but it doesn't seem to be possible +// to actually include the generic type +// http://www.openradar.me/radar?id=6135653276319744 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wmismatched-parameter-types" +- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *, RLMCollectionChange *, NSError *))block { + [_realm verifyNotificationsAreSupported:true]; + return RLMAddNotificationBlock(self, _backingList, block); +} +#pragma clang diagnostic pop + +#pragma mark - Thread Confined Protocol Conformance + +- (std::unique_ptr)makeThreadSafeReference { + auto list_reference = _realm->_realm->obtain_thread_safe_reference(_backingList); + return std::make_unique>(std::move(list_reference)); +} + +- (RLMManagedArrayHandoverMetadata *)objectiveCMetadata { + RLMManagedArrayHandoverMetadata *metadata = [[RLMManagedArrayHandoverMetadata alloc] init]; + metadata.parentClassName = _ownerInfo->rlmObjectSchema.className; + metadata.key = _key; + return metadata; +} + ++ (instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference + metadata:(RLMManagedArrayHandoverMetadata *)metadata + realm:(RLMRealm *)realm { + REALM_ASSERT_DEBUG(dynamic_cast *>(reference.get())); + auto list_reference = static_cast *>(reference.get()); + + auto list = realm->_realm->resolve_thread_safe_reference(std::move(*list_reference)); + if (!list.is_valid()) { + return nil; + } + RLMClassInfo *parentInfo = &realm->_info[metadata.parentClassName]; + return [[RLMManagedArray alloc] initWithList:std::move(list) + realm:realm + parentInfo:parentInfo + property:parentInfo->rlmObjectSchema[metadata.key]]; +} + +@end diff --git a/Pods/Realm/Realm/RLMMigration.mm b/Pods/Realm/Realm/RLMMigration.mm new file mode 100644 index 0000000000..6c0c571add --- /dev/null +++ b/Pods/Realm/Realm/RLMMigration.mm @@ -0,0 +1,192 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMMigration_Private.h" + +#import "RLMAccessor.h" +#import "RLMObject_Private.h" +#import "RLMObject_Private.hpp" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObjectStore.h" +#import "RLMProperty_Private.h" +#import "RLMRealm_Dynamic.h" +#import "RLMRealm_Private.hpp" +#import "RLMResults_Private.hpp" +#import "RLMSchema_Private.hpp" +#import "RLMUtil.hpp" + +#import "object_store.hpp" +#import "shared_realm.hpp" +#import "schema.hpp" + +#import + +using namespace realm; + +// The source realm for a migration has to use a SharedGroup to be able to share +// the file with the destination realm, but we don't want to let the user call +// beginWriteTransaction on it as that would make no sense. +@interface RLMMigrationRealm : RLMRealm +@end + +@implementation RLMMigrationRealm +- (BOOL)readonly { + return YES; +} + +- (void)beginWriteTransaction { + @throw RLMException(@"Cannot modify the source Realm in a migration"); +} +@end + +@implementation RLMMigration { + realm::Schema *_schema; + std::unordered_map _deletedObjectIndices; +} + +- (instancetype)initWithRealm:(RLMRealm *)realm oldRealm:(RLMRealm *)oldRealm schema:(realm::Schema &)schema { + self = [super init]; + if (self) { + _realm = realm; + _oldRealm = oldRealm; + _schema = &schema; + object_setClass(_oldRealm, RLMMigrationRealm.class); + } + return self; +} + +- (RLMSchema *)oldSchema { + return self.oldRealm.schema; +} + +- (RLMSchema *)newSchema { + return self.realm.schema; +} + +- (void)enumerateObjects:(NSString *)className block:(__attribute__((noescape)) RLMObjectMigrationBlock)block { + RLMResults *objects = [_realm.schema schemaForClassName:className] ? [_realm allObjects:className] : nil; + RLMResults *oldObjects = [_oldRealm.schema schemaForClassName:className] ? [_oldRealm allObjects:className] : nil; + + // For whatever reason if this is a newly added table we enumerate the + // objects in it, while in all other cases we enumerate only the existing + // objects. It's unclear how this could be useful, but changing it would + // also be a pointless breaking change and it's unlikely to be hurting anyone. + if (objects && !oldObjects) { + for (auto i = objects.count; i > 0; --i) { + @autoreleasepool { + block(nil, objects[i - 1]); + } + } + return; + } + + auto count = oldObjects.count; + if (count == 0) { + return; + } + auto deletedObjects = _deletedObjectIndices.find(className); + for (auto i = count; i > 0; --i) { + auto index = i - 1; + if (deletedObjects != _deletedObjectIndices.end() && deletedObjects->second.contains(index)) { + continue; + } + @autoreleasepool { + block(oldObjects[index], objects[index]); + } + } +} + +- (void)execute:(RLMMigrationBlock)block { + @autoreleasepool { + // disable all primary keys for migration and use DynamicObject for all types + for (RLMObjectSchema *objectSchema in _realm.schema.objectSchema) { + objectSchema.accessorClass = RLMDynamicObject.class; + objectSchema.primaryKeyProperty.isPrimary = NO; + } + for (RLMObjectSchema *objectSchema in _oldRealm.schema.objectSchema) { + objectSchema.accessorClass = RLMDynamicObject.class; + } + + block(self, _oldRealm->_realm->schema_version()); + + [self deleteObjectsMarkedForDeletion]; + + _oldRealm = nil; + _realm = nil; + } +} + +- (RLMObject *)createObject:(NSString *)className withValue:(id)value { + return [_realm createObject:className withValue:value]; +} + +- (RLMObject *)createObject:(NSString *)className withObject:(id)object { + return [self createObject:className withValue:object]; +} + +- (void)deleteObject:(RLMObject *)object { + _deletedObjectIndices[object.objectSchema.className].add(object->_row.get_index()); +} + +- (void)deleteObjectsMarkedForDeletion { + for (auto& objectType : _deletedObjectIndices) { + TableRef table = ObjectStore::table_for_object_type(_realm.group, objectType.first.UTF8String); + if (!table) { + continue; + } + + auto& indices = objectType.second; + // Just clear the table if we're removing all of the rows + if (table->size() == indices.count()) { + table->clear(); + } + // Otherwise delete in reverse order to avoid invaliding any of the + // not-yet-deleted indices + else { + for (auto it = std::make_reverse_iterator(indices.end()), end = std::make_reverse_iterator(indices.begin()); it != end; ++it) { + for (size_t i = it->second; i > it->first; --i) { + table->move_last_over(i - 1); + } + } + } + } +} + +- (BOOL)deleteDataForClassName:(NSString *)name { + if (!name) { + return false; + } + + TableRef table = ObjectStore::table_for_object_type(_realm.group, name.UTF8String); + if (!table) { + return false; + } + _deletedObjectIndices[name].set(table->size()); + if (![_realm.schema schemaForClassName:name]) { + realm::ObjectStore::delete_data_for_object(_realm.group, name.UTF8String); + } + + return true; +} + +- (void)renamePropertyForClass:(NSString *)className oldName:(NSString *)oldName newName:(NSString *)newName { + realm::ObjectStore::rename_property(_realm.group, *_schema, className.UTF8String, + oldName.UTF8String, newName.UTF8String); +} + +@end diff --git a/Pods/Realm/Realm/RLMNetworkClient.mm b/Pods/Realm/Realm/RLMNetworkClient.mm new file mode 100644 index 0000000000..db1f67afbf --- /dev/null +++ b/Pods/Realm/Realm/RLMNetworkClient.mm @@ -0,0 +1,433 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMNetworkClient.h" + +#import "RLMRealmConfiguration.h" +#import "RLMJSONModels.h" +#import "RLMSyncUtil_Private.hpp" +#import "RLMUtil.hpp" + +#import + +typedef void(^RLMServerURLSessionCompletionBlock)(NSData *, NSURLResponse *, NSError *); + +static NSUInteger const kHTTPCodeRange = 100; + +typedef enum : NSUInteger { + Informational = 1, // 1XX + Success = 2, // 2XX + Redirection = 3, // 3XX + ClientError = 4, // 4XX + ServerError = 5, // 5XX +} RLMServerHTTPErrorCodeType; + +static NSRange rangeForErrorType(RLMServerHTTPErrorCodeType type) { + return NSMakeRange(type*100, kHTTPCodeRange); +} + +static std::atomic g_defaultTimeout{60.0}; + +@interface RLMSyncServerEndpoint () +- (instancetype)initPrivate NS_DESIGNATED_INITIALIZER; + +/// The HTTP method the endpoint expects. Defaults to POST. +- (NSString *)httpMethod; + +/// The URL to which the request should be made. Must be implemented. +- (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(NSDictionary *)json; + +/// The body for the request, if any. +- (NSData *)httpBodyForPayload:(NSDictionary *)json error:(NSError **)error; + +/// The HTTP headers to be added to the request, if any. +- (NSDictionary *)httpHeadersForPayload:(NSDictionary *)json + options:(nullable RLMNetworkRequestOptions *)options; +@end + +@implementation RLMSyncServerEndpoint + ++ (void)sendRequestToServer:(NSURL *)serverURL + JSON:(NSDictionary *)jsonDictionary + options:(nullable RLMNetworkRequestOptions *)options + completion:(void (^)(NSError *))completionBlock { + [RLMNetworkClient sendRequestToEndpoint:[self endpoint] + server:serverURL + JSON:jsonDictionary + timeout:g_defaultTimeout.load() + options:options + completion:^(NSError *error, NSDictionary *) { + completionBlock(error); + }]; +} + ++ (instancetype)endpoint { + return [[self alloc] initPrivate]; +} + +- (instancetype)initPrivate { + return (self = [super init]); +} + +- (NSString *)httpMethod { + return @"POST"; +} + +- (NSURL *)urlForAuthServer:(__unused NSURL *)authServerURL payload:(__unused NSDictionary *)json { + NSAssert(NO, @"This method must be overriden by concrete subclasses."); + return nil; +} + +- (NSData *)httpBodyForPayload:(NSDictionary *)json error:(NSError **)error { + NSError *localError = nil; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json + options:(NSJSONWritingOptions)0 + error:&localError]; + if (jsonData && !localError) { + return jsonData; + } + NSAssert(localError, @"If there isn't a converted data object there must be an error."); + if (error) { + *error = localError; + } + return nil; +} + +- (NSDictionary *)httpHeadersForPayload:(__unused NSDictionary *)json options:(nullable RLMNetworkRequestOptions *)options { + NSMutableDictionary *headers = [[NSMutableDictionary alloc] init]; + headers[@"Content-Type"] = @"application/json;charset=utf-8"; + headers[@"Accept"] = @"application/json"; + + if (NSDictionary *customHeaders = options.customHeaders) { + [headers addEntriesFromDictionary:customHeaders]; + } + + return headers; +} +@end + +@implementation RLMSyncAuthEndpoint +- (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { + return [authServerURL URLByAppendingPathComponent:@"auth"]; +} +@end + +@implementation RLMSyncChangePasswordEndpoint +- (NSString *)httpMethod { + return @"PUT"; +} + +- (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { + return [authServerURL URLByAppendingPathComponent:@"auth/password"]; +} + +- (NSDictionary *)httpHeadersForPayload:(NSDictionary *)json options:(nullable RLMNetworkRequestOptions *)options { + NSString *authToken = [json objectForKey:kRLMSyncTokenKey]; + if (!authToken) { + @throw RLMException(@"Malformed request; this indicates an internal error."); + } + NSMutableDictionary *headers = [[super httpHeadersForPayload:json options:options] mutableCopy]; + headers[options.authorizationHeaderName ?: @"Authorization"] = authToken; + return headers; +} +@end + +@implementation RLMSyncUpdateAccountEndpoint +- (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { + return [authServerURL URLByAppendingPathComponent:@"auth/password/updateAccount"]; +} +@end + +@implementation RLMSyncGetUserInfoEndpoint +- (NSString *)httpMethod { + return @"GET"; +} + +- (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(NSDictionary *)json { + NSString *provider = json[kRLMSyncProviderKey]; + NSString *providerID = json[kRLMSyncProviderIDKey]; + NSAssert([provider isKindOfClass:[NSString class]] && [providerID isKindOfClass:[NSString class]], + @"malformed request; this indicates a logic error in the binding."); + NSCharacterSet *allowed = [NSCharacterSet URLQueryAllowedCharacterSet]; + NSString *pathComponent = [NSString stringWithFormat:@"auth/users/%@/%@", + [provider stringByAddingPercentEncodingWithAllowedCharacters:allowed], + [providerID stringByAddingPercentEncodingWithAllowedCharacters:allowed]]; + return [authServerURL URLByAppendingPathComponent:pathComponent]; +} + +- (NSData *)httpBodyForPayload:(__unused NSDictionary *)json error:(__unused NSError **)error { + return nil; +} + +- (NSDictionary *)httpHeadersForPayload:(NSDictionary *)json options:(nullable RLMNetworkRequestOptions *)options { + NSString *authToken = [json objectForKey:kRLMSyncTokenKey]; + if (!authToken) { + @throw RLMException(@"Malformed request; this indicates an internal error."); + } + NSMutableDictionary *headers = [[super httpHeadersForPayload:json options:options] mutableCopy]; + headers[options.authorizationHeaderName ?: @"Authorization"] = authToken; + return headers; +} +@end + +@interface RLMSessionDelegate : NSObject +@end + +@implementation RLMSessionDelegate { + NSDictionary *_certificatePaths; + NSData *_data; + void (^_completionBlock)(NSError *, NSDictionary *); +} + ++ (instancetype)delegateWithCertificatePaths:(NSDictionary *)paths completion:(void (^)(NSError *, NSDictionary *))completion { + RLMSessionDelegate *delegate = [RLMSessionDelegate new]; + delegate->_certificatePaths = paths; + delegate->_completionBlock = completion; + return delegate; +} + +- (void)URLSession:(__unused NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { + auto protectionSpace = challenge.protectionSpace; + + // Just fall back to the default logic for HTTP basic auth + if (protectionSpace.authenticationMethod != NSURLAuthenticationMethodServerTrust || !protectionSpace.serverTrust) { + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + return; + } + + // If we have a pinned certificate for this hostname, we want to validate + // against that, and otherwise just do the default thing + auto certPath = _certificatePaths[protectionSpace.host]; + if (!certPath) { + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + return; + } + if ([certPath isKindOfClass:[NSString class]]) { + certPath = [NSURL fileURLWithPath:(id)certPath]; + } + + + // Reject the server auth and report an error if any errors occur along the way + CFArrayRef items = nil; + NSError *error; + auto reportStatus = realm::util::make_scope_exit([&]() noexcept { + if (items) { + CFRelease(items); + } + if (error) { + _completionBlock(error, nil); + // Don't also report errors about the connection itself failing later + _completionBlock = ^(NSError *, id) { }; + completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil); + } + }); + + NSData *data = [NSData dataWithContentsOfURL:certPath options:0 error:&error]; + if (!data) { + return; + } + + // Load our pinned certificate and add it to the anchor set +#if TARGET_OS_IPHONE + id certificate = (__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data); + if (!certificate) { + error = [NSError errorWithDomain:NSOSStatusErrorDomain code:errSecUnknownFormat userInfo:nil]; + return; + } + items = (CFArrayRef)CFBridgingRetain(@[certificate]); +#else + SecItemImportExportKeyParameters params{ + .version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION + }; + if (OSStatus status = SecItemImport((__bridge CFDataRef)data, (__bridge CFStringRef)certPath.absoluteString, + nullptr, nullptr, 0, ¶ms, nullptr, &items)) { + error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; + return; + } +#endif + SecTrustRef serverTrust = protectionSpace.serverTrust; + if (OSStatus status = SecTrustSetAnchorCertificates(serverTrust, items)) { + error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; + return; + } + + // Only use our certificate and not the ones from the default CA roots + if (OSStatus status = SecTrustSetAnchorCertificatesOnly(serverTrust, true)) { + error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; + return; + } + + // Verify that our pinned certificate is valid for this connection + SecTrustResultType trustResult; + if (OSStatus status = SecTrustEvaluate(serverTrust, &trustResult)) { + error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; + return; + } + if (trustResult != kSecTrustResultProceed && trustResult != kSecTrustResultUnspecified) { + completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil); + return; + } + + completionHandler(NSURLSessionAuthChallengeUseCredential, + [NSURLCredential credentialForTrust:protectionSpace.serverTrust]); +} + +- (void)URLSession:(__unused NSURLSession *)session + dataTask:(__unused NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data { + if (!_data) { + _data = data; + return; + } + if (![_data respondsToSelector:@selector(appendData:)]) { + _data = [_data mutableCopy]; + } + [(id)_data appendData:data]; +} + +- (void)URLSession:(__unused NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ + if (error) { + _completionBlock(error, nil); + return; + } + + if (![self validateResponse:task.response data:_data error:&error]) { + _completionBlock(error, nil); + return; + } + + id json = [NSJSONSerialization JSONObjectWithData:_data + options:(NSJSONReadingOptions)0 + error:&error]; + if (!json) { + _completionBlock(error, nil); + return; + } + if (![json isKindOfClass:[NSDictionary class]]) { + _completionBlock(make_auth_error_bad_response(json), nil); + return; + } + + _completionBlock(nil, (NSDictionary *)json); +} + +- (BOOL)validateResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError * __autoreleasing *)error { + if (![response isKindOfClass:[NSHTTPURLResponse class]]) { + // FIXME: Provide error message + *error = make_auth_error_bad_response(); + return NO; + } + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; + BOOL badResponse = (NSLocationInRange(httpResponse.statusCode, rangeForErrorType(ClientError)) + || NSLocationInRange(httpResponse.statusCode, rangeForErrorType(ServerError))); + if (badResponse) { + if (RLMSyncErrorResponseModel *responseModel = [self responseModelFromData:data]) { + switch (responseModel.code) { + case RLMSyncAuthErrorInvalidParameters: + case RLMSyncAuthErrorMissingPath: + case RLMSyncAuthErrorInvalidCredential: + case RLMSyncAuthErrorUserDoesNotExist: + case RLMSyncAuthErrorUserAlreadyExists: + case RLMSyncAuthErrorAccessDeniedOrInvalidPath: + case RLMSyncAuthErrorInvalidAccessToken: + case RLMSyncAuthErrorExpiredPermissionOffer: + case RLMSyncAuthErrorAmbiguousPermissionOffer: + case RLMSyncAuthErrorFileCannotBeShared: + *error = make_auth_error(responseModel); + break; + default: + // Right now we assume that any codes not described + // above are generic HTTP error codes. + *error = make_auth_error_http_status(responseModel.status); + break; + } + } else { + *error = make_auth_error_http_status(httpResponse.statusCode); + } + + return NO; + } + + if (!data) { + // FIXME: provide error message + *error = make_auth_error_bad_response(); + return NO; + } + + return YES; +} + +- (RLMSyncErrorResponseModel *)responseModelFromData:(NSData *)data { + if (data.length == 0) { + return nil; + } + id json = [NSJSONSerialization JSONObjectWithData:data + options:(NSJSONReadingOptions)0 + error:nil]; + if (!json || ![json isKindOfClass:[NSDictionary class]]) { + return nil; + } + return [[RLMSyncErrorResponseModel alloc] initWithDictionary:json]; +} + +@end + +@implementation RLMNetworkClient ++ (void)setDefaultTimeout:(NSTimeInterval)timeOut { + g_defaultTimeout = timeOut; +} + ++ (void)sendRequestToEndpoint:(RLMSyncServerEndpoint *)endpoint + server:(NSURL *)serverURL + JSON:(NSDictionary *)jsonDictionary + timeout:(NSTimeInterval)timeout + options:(nullable RLMNetworkRequestOptions *)options + completion:(RLMSyncCompletionBlock)completionBlock { + // Create the request + NSError *localError = nil; + NSURL *requestURL = [endpoint urlForAuthServer:serverURL payload:jsonDictionary]; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL]; + request.HTTPBody = [endpoint httpBodyForPayload:jsonDictionary error:&localError]; + if (localError) { + completionBlock(localError, nil); + return; + } + request.HTTPMethod = [endpoint httpMethod]; + request.timeoutInterval = MAX(timeout, 10); + NSDictionary *headers = [endpoint httpHeadersForPayload:jsonDictionary options:options]; + for (NSString *key in headers) { + [request addValue:headers[key] forHTTPHeaderField:key]; + } + id delegate = [RLMSessionDelegate delegateWithCertificatePaths:options.pinnedCertificatePaths + completion:completionBlock]; + auto session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration + delegate:delegate delegateQueue:nil]; + + // Add the request to a task and start it + [[session dataTaskWithRequest:request] resume]; +} +@end + +@implementation RLMNetworkRequestOptions + +@end diff --git a/Pods/Realm/Realm/RLMObject.mm b/Pods/Realm/Realm/RLMObject.mm new file mode 100644 index 0000000000..1ace411f46 --- /dev/null +++ b/Pods/Realm/Realm/RLMObject.mm @@ -0,0 +1,411 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMObject_Private.hpp" + +#import "RLMAccessor.h" +#import "RLMArray.h" +#import "RLMCollection_Private.hpp" +#import "RLMObjectBase_Private.h" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObjectStore.h" +#import "RLMProperty.h" +#import "RLMQueryUtil.hpp" +#import "RLMRealm_Private.hpp" +#import "RLMSchema_Private.h" + +#import "collection_notifications.hpp" +#import "object.hpp" + +@interface RLMPropertyChange () +@property (nonatomic, readwrite, strong) NSString *name; +@property (nonatomic, readwrite, strong, nullable) id previousValue; +@property (nonatomic, readwrite, strong, nullable) id value; +@end + +// We declare things in RLMObject which are actually implemented in RLMObjectBase +// for documentation's sake, which leads to -Wunimplemented-method warnings. +// Other alternatives to this would be to disable -Wunimplemented-method for this +// file (but then we could miss legitimately missing things), or declaring the +// inherited things in a category (but they currently aren't nicely grouped for +// that). +@implementation RLMObject + +// synthesized in RLMObjectBase +@dynamic invalidated, realm, objectSchema; + +#pragma mark - Designated Initializers + +- (instancetype)init { + return [super init]; +} + +- (instancetype)initWithValue:(id)value schema:(RLMSchema *)schema { + return [super initWithValue:value schema:schema]; +} + +- (instancetype)initWithRealm:(__unsafe_unretained RLMRealm *const)realm schema:(RLMObjectSchema *)schema { + return [super initWithRealm:realm schema:schema]; +} + +#pragma mark - Convenience Initializers + +- (instancetype)initWithValue:(id)value { + return [super initWithValue:value schema:RLMSchema.partialPrivateSharedSchema]; +} + +#pragma mark - Class-based Object Creation + ++ (instancetype)createInDefaultRealmWithValue:(id)value { + return (RLMObject *)RLMCreateObjectInRealmWithValue([RLMRealm defaultRealm], [self className], value, false); +} + ++ (instancetype)createInRealm:(RLMRealm *)realm withValue:(id)value { + return (RLMObject *)RLMCreateObjectInRealmWithValue(realm, [self className], value, false); +} + ++ (instancetype)createOrUpdateInDefaultRealmWithValue:(id)value { + return [self createOrUpdateInRealm:[RLMRealm defaultRealm] withValue:value]; +} + ++ (instancetype)createOrUpdateInRealm:(RLMRealm *)realm withValue:(id)value { + // verify primary key + RLMObjectSchema *schema = [self sharedSchema]; + if (!schema.primaryKeyProperty) { + NSString *reason = [NSString stringWithFormat:@"'%@' does not have a primary key and can not be updated", schema.className]; + @throw [NSException exceptionWithName:@"RLMExecption" reason:reason userInfo:nil]; + } + return (RLMObject *)RLMCreateObjectInRealmWithValue(realm, [self className], value, true); +} + +#pragma mark - Subscripting + +- (id)objectForKeyedSubscript:(NSString *)key { + return RLMObjectBaseObjectForKeyedSubscript(self, key); +} + +- (void)setObject:(id)obj forKeyedSubscript:(NSString *)key { + RLMObjectBaseSetObjectForKeyedSubscript(self, key, obj); +} + +#pragma mark - Getting & Querying + ++ (RLMResults *)allObjects { + return RLMGetObjects(RLMRealm.defaultRealm, self.className, nil); +} + ++ (RLMResults *)allObjectsInRealm:(__unsafe_unretained RLMRealm *const)realm { + return RLMGetObjects(realm, self.className, nil); +} + ++ (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... { + va_list args; + va_start(args, predicateFormat); + RLMResults *results = [self objectsWhere:predicateFormat args:args]; + va_end(args); + return results; +} + ++ (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args { + return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; +} + ++ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat, ... { + va_list args; + va_start(args, predicateFormat); + RLMResults *results = [self objectsInRealm:realm where:predicateFormat args:args]; + va_end(args); + return results; +} + ++ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat args:(va_list)args { + return [self objectsInRealm:realm withPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; +} + ++ (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate { + return RLMGetObjects(RLMRealm.defaultRealm, self.className, predicate); +} + ++ (RLMResults *)objectsInRealm:(RLMRealm *)realm withPredicate:(NSPredicate *)predicate { + return RLMGetObjects(realm, self.className, predicate); +} + ++ (instancetype)objectForPrimaryKey:(id)primaryKey { + return RLMGetObject(RLMRealm.defaultRealm, self.className, primaryKey); +} + ++ (instancetype)objectInRealm:(RLMRealm *)realm forPrimaryKey:(id)primaryKey { + return RLMGetObject(realm, self.className, primaryKey); +} + +#pragma mark - Other Instance Methods + +- (BOOL)isEqualToObject:(RLMObject *)object { + return [object isKindOfClass:RLMObject.class] && RLMObjectBaseAreEqual(self, object); +} + +- (RLMNotificationToken *)addNotificationBlock:(RLMObjectChangeBlock)block { + return RLMObjectAddNotificationBlock(self, ^(NSArray *propertyNames, + NSArray *oldValues, NSArray *newValues, NSError *error) { + if (error) { + block(false, nil, error); + } + else if (!propertyNames) { + block(true, nil, nil); + } + else { + auto properties = [NSMutableArray arrayWithCapacity:propertyNames.count]; + for (NSUInteger i = 0, count = propertyNames.count; i < count; ++i) { + auto prop = [RLMPropertyChange new]; + prop.name = propertyNames[i]; + prop.previousValue = RLMCoerceToNil(oldValues[i]); + prop.value = RLMCoerceToNil(newValues[i]); + [properties addObject:prop]; + } + block(false, properties, nil); + } + }); +} + ++ (NSString *)className { + return [super className]; +} + +#pragma mark - Default values for schema definition + ++ (NSArray *)indexedProperties { + return @[]; +} + ++ (NSDictionary *)linkingObjectsProperties { + return @{}; +} + ++ (NSDictionary *)defaultPropertyValues { + return nil; +} + ++ (NSString *)primaryKey { + return nil; +} + ++ (NSArray *)ignoredProperties { + return nil; +} + ++ (NSArray *)requiredProperties { + return @[]; +} + +@end + +@implementation RLMDynamicObject + ++ (BOOL)shouldIncludeInDefaultSchema { + return NO; +} + +- (id)valueForUndefinedKey:(NSString *)key { + return RLMDynamicGetByName(self, key, false); +} + +- (void)setValue:(id)value forUndefinedKey:(NSString *)key { + RLMDynamicValidatedSet(self, key, value); +} + +@end + +@implementation RLMWeakObjectHandle { + realm::Row _row; + RLMClassInfo *_info; + Class _objectClass; +} + +- (instancetype)initWithObject:(RLMObjectBase *)object { + if (!(self = [super init])) { + return nil; + } + + _row = object->_row; + _info = object->_info; + _objectClass = object.class; + + return self; +} + +- (RLMObjectBase *)object { + RLMObjectBase *object = RLMCreateManagedAccessor(_objectClass, _info->realm, _info); + object->_row = std::move(_row); + return object; +} + +- (id)copyWithZone:(__unused NSZone *)zone { + RLMWeakObjectHandle *copy = [[RLMWeakObjectHandle alloc] init]; + copy->_row = _row; + copy->_info = _info; + copy->_objectClass = _objectClass; + return copy; +} + +@end + +static bool treatFakeObjectAsRLMObject = false; +void RLMSetTreatFakeObjectAsRLMObject(BOOL flag) { + treatFakeObjectAsRLMObject = flag; +} + +BOOL RLMIsObjectOrSubclass(Class klass) { + if (RLMIsKindOfClass(klass, RLMObjectBase.class)) { + return YES; + } + + if (treatFakeObjectAsRLMObject) { + static Class FakeObjectClass = NSClassFromString(@"FakeObject"); + return RLMIsKindOfClass(klass, FakeObjectClass); + } + return NO; +} + +BOOL RLMIsObjectSubclass(Class klass) { + auto isSubclass = [](Class class1, Class class2) { + class1 = class_getSuperclass(class1); + return RLMIsKindOfClass(class1, class2); + }; + if (isSubclass(class_getSuperclass(klass), RLMObjectBase.class)) { + return YES; + } + + if (treatFakeObjectAsRLMObject) { + static Class FakeObjectClass = NSClassFromString(@"FakeObject"); + return isSubclass(klass, FakeObjectClass); + } + return NO; +} + +@interface RLMObjectNotificationToken : RLMCancellationToken +@end +@implementation RLMObjectNotificationToken { +@public + realm::Object _object; +} +@end + +RLMNotificationToken *RLMObjectAddNotificationBlock(RLMObjectBase *obj, RLMObjectNotificationCallback block) { + if (!obj->_realm) { + @throw RLMException(@"Only objects which are managed by a Realm support change notifications"); + } + [obj->_realm verifyNotificationsAreSupported:true]; + + struct { + void (^block)(NSArray *, NSArray *, NSArray *, NSError *); + RLMObjectBase *object; + + NSArray *propertyNames = nil; + NSArray *oldValues = nil; + bool deleted = false; + + void populateProperties(realm::CollectionChangeSet const& c) { + if (propertyNames) { + return; + } + if (!c.deletions.empty()) { + deleted = true; + return; + } + if (c.columns.empty()) { + return; + } + + auto properties = [NSMutableArray new]; + for (size_t i = 0; i < c.columns.size(); ++i) { + if (c.columns[i].empty()) { + continue; + } + if (auto prop = object->_info->propertyForTableColumn(i)) { + [properties addObject:prop.name]; + } + } + if (properties.count) { + propertyNames = properties; + } + } + + NSArray *readValues(realm::CollectionChangeSet const& c) { + if (c.empty()) { + return nil; + } + populateProperties(c); + if (!propertyNames) { + return nil; + } + + auto values = [NSMutableArray arrayWithCapacity:propertyNames.count]; + for (NSString *name in propertyNames) { + id value = [object valueForKey:name]; + if (!value || [value isKindOfClass:[RLMArray class]]) { + [values addObject:NSNull.null]; + } + else { + [values addObject:value]; + } + } + return values; + } + + void before(realm::CollectionChangeSet const& c) { + @autoreleasepool { + oldValues = readValues(c); + } + } + + void after(realm::CollectionChangeSet const& c) { + @autoreleasepool { + auto newValues = readValues(c); + if (deleted) { + block(nil, nil, nil, nil); + } + else if (newValues) { + block(propertyNames, oldValues, newValues, nil); + } + propertyNames = nil; + oldValues = nil; + } + } + + void error(std::exception_ptr err) { + @autoreleasepool { + try { + rethrow_exception(err); + } + catch (...) { + NSError *error = nil; + RLMRealmTranslateException(&error); + block(nil, nil, nil, error); + } + } + } + } callback{block, obj}; + + realm::Object object(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row); + auto token = [[RLMObjectNotificationToken alloc] initWithToken:object.add_notification_callback(callback) realm:obj->_realm]; + token->_object = std::move(object); + return token; +} + +@implementation RLMPropertyChange +@end diff --git a/Pods/Realm/Realm/RLMObjectBase.mm b/Pods/Realm/Realm/RLMObjectBase.mm new file mode 100644 index 0000000000..2e33a85663 --- /dev/null +++ b/Pods/Realm/Realm/RLMObjectBase.mm @@ -0,0 +1,542 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMObject_Private.hpp" + +#import "RLMAccessor.h" +#import "RLMArray_Private.hpp" +#import "RLMListBase.h" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObjectStore.h" +#import "RLMObservation.hpp" +#import "RLMOptionalBase.h" +#import "RLMProperty_Private.h" +#import "RLMRealm_Private.hpp" +#import "RLMSchema_Private.h" +#import "RLMSwiftSupport.h" +#import "RLMThreadSafeReference_Private.hpp" +#import "RLMUtil.hpp" + +#import "object.hpp" +#import "object_schema.hpp" +#import "shared_realm.hpp" + +using namespace realm; + +const NSUInteger RLMDescriptionMaxDepth = 5; + +static bool maybeInitObjectSchemaForUnmanaged(RLMObjectBase *obj) { + obj->_objectSchema = [obj.class sharedSchema]; + if (!obj->_objectSchema) { + return false; + } + + // set default values + if (!obj->_objectSchema.isSwiftClass) { + NSDictionary *dict = RLMDefaultValuesForObjectSchema(obj->_objectSchema); + for (NSString *key in dict) { + [obj setValue:dict[key] forKey:key]; + } + } + + // set unmanaged accessor class + object_setClass(obj, obj->_objectSchema.unmanagedClass); + return true; +} + +@interface RLMObjectBase () +@end + +@implementation RLMObjectBase +// unmanaged init +- (instancetype)init { + if ((self = [super init])) { + maybeInitObjectSchemaForUnmanaged(self); + } + return self; +} + +- (void)dealloc { + // This can't be a unique_ptr because associated objects are removed + // *after* c++ members are destroyed and dealloc is called, and we need it + // to be in a validish state when that happens + delete _observationInfo; + _observationInfo = nullptr; +} + +static id coerceToObjectType(id obj, Class cls, RLMSchema *schema) { + return [obj isKindOfClass:cls] ? obj : [[cls alloc] initWithValue:obj schema:schema]; +} + +static id validatedObjectForProperty(__unsafe_unretained id const obj, + __unsafe_unretained RLMObjectSchema *const objectSchema, + __unsafe_unretained RLMProperty *const prop, + __unsafe_unretained RLMSchema *const schema) { + RLMValidateValueForProperty(obj, objectSchema, prop); + if (!obj || obj == NSNull.null) { + return nil; + } + if (prop.type == RLMPropertyTypeObject) { + Class objectClass = schema[prop.objectClassName].objectClass; + if (prop.array) { + NSMutableArray *ret = [[NSMutableArray alloc] init]; + for (id el in obj) { + [ret addObject:coerceToObjectType(el, objectClass, schema)]; + } + return ret; + } + return coerceToObjectType(obj, objectClass, schema); + } + return obj; +} + +- (instancetype)initWithValue:(id)value schema:(RLMSchema *)schema { + if (!(self = [super init])) { + return self; + } + + if (!value || value == NSNull.null) { + @throw RLMException(@"Must provide a non-nil value."); + } + + if (!maybeInitObjectSchemaForUnmanaged(self)) { + // Don't populate fields from the passed-in object if we're called + // during schema init + return self; + } + + NSArray *properties = _objectSchema.properties; + if (NSArray *array = RLMDynamicCast(value)) { + if (array.count > properties.count) { + @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).", + (unsigned long long)array.count, (unsigned long long)properties.count); + } + NSUInteger i = 0; + for (id val in array) { + RLMProperty *prop = properties[i++]; + [self setValue:validatedObjectForProperty(RLMCoerceToNil(val), _objectSchema, prop, schema) + forKey:prop.name]; + } + } + else { + // assume our object is an NSDictionary or an object with kvc properties + for (RLMProperty *prop in properties) { + id obj = RLMValidatedValueForProperty(value, prop.name, _objectSchema.className); + + // don't set unspecified properties + if (!obj) { + continue; + } + + [self setValue:validatedObjectForProperty(RLMCoerceToNil(obj), _objectSchema, prop, schema) + forKey:prop.name]; + } + } + + return self; +} + +id RLMCreateManagedAccessor(Class cls, __unsafe_unretained RLMRealm *realm, RLMClassInfo *info) { + RLMObjectBase *obj = [[cls alloc] initWithRealm:realm schema:info->rlmObjectSchema]; + obj->_info = info; + return obj; +} + +- (instancetype)initWithRealm:(__unsafe_unretained RLMRealm *const)realm + schema:(RLMObjectSchema *)schema { + self = [super init]; + if (self) { + _realm = realm; + _objectSchema = schema; + } + return self; +} + +- (id)valueForKey:(NSString *)key { + if (_observationInfo) { + return _observationInfo->valueForKey(key); + } + return [super valueForKey:key]; +} + +// Generic Swift properties can't be dynamic, so KVO doesn't work for them by default +- (id)valueForUndefinedKey:(NSString *)key { + if (Ivar ivar = _objectSchema[key].swiftIvar) { + return RLMCoerceToNil(object_getIvar(self, ivar)); + } + return [super valueForUndefinedKey:key]; +} + +- (void)setValue:(id)value forUndefinedKey:(NSString *)key { + value = RLMCoerceToNil(value); + RLMProperty *property = _objectSchema[key]; + if (Ivar ivar = property.swiftIvar) { + if (property.array && (!value || [value conformsToProtocol:@protocol(NSFastEnumeration)])) { + RLMArray *array = [object_getIvar(self, ivar) _rlmArray]; + [array removeAllObjects]; + + if (value) { + [array addObjects:validatedObjectForProperty(value, _objectSchema, property, + RLMSchema.partialPrivateSharedSchema)]; + } + } + else if (property.optional) { + RLMSetOptional(object_getIvar(self, ivar), value); + } + return; + } + [super setValue:value forUndefinedKey:key]; +} + +// overridden at runtime per-class for performance ++ (NSString *)className { + NSString *className = NSStringFromClass(self); + if ([RLMSwiftSupport isSwiftClassName:className]) { + className = [RLMSwiftSupport demangleClassName:className]; + } + return className; +} + +// overridden at runtime per-class for performance ++ (RLMObjectSchema *)sharedSchema { + return [RLMSchema sharedSchemaForClass:self.class]; +} + ++ (void)initializeLinkedObjectSchemas { + for (RLMProperty *prop in self.sharedSchema.properties) { + if (prop.type == RLMPropertyTypeObject && !RLMSchema.partialPrivateSharedSchema[prop.objectClassName]) { + [[RLMSchema classForString:prop.objectClassName] initializeLinkedObjectSchemas]; + } + } +} + ++ (Class)objectUtilClass:(BOOL)isSwift { + return RLMObjectUtilClass(isSwift); +} + +- (NSString *)description +{ + if (self.isInvalidated) { + return @"[invalid object]"; + } + + return [self descriptionWithMaxDepth:RLMDescriptionMaxDepth]; +} + +- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth { + if (depth == 0) { + return @""; + } + + NSString *baseClassName = _objectSchema.className; + NSMutableString *mString = [NSMutableString stringWithFormat:@"%@ {\n", baseClassName]; + + for (RLMProperty *property in _objectSchema.properties) { + id object = [(id)self objectForKeyedSubscript:property.name]; + NSString *sub; + if ([object respondsToSelector:@selector(descriptionWithMaxDepth:)]) { + sub = [object descriptionWithMaxDepth:depth - 1]; + } + else if (property.type == RLMPropertyTypeData) { + static NSUInteger maxPrintedDataLength = 24; + NSData *data = object; + NSUInteger length = data.length; + if (length > maxPrintedDataLength) { + data = [NSData dataWithBytes:data.bytes length:maxPrintedDataLength]; + } + NSString *dataDescription = [data description]; + sub = [NSString stringWithFormat:@"<%@ — %lu total bytes>", [dataDescription substringWithRange:NSMakeRange(1, dataDescription.length - 2)], (unsigned long)length]; + } + else { + sub = [object description]; + } + [mString appendFormat:@"\t%@ = %@;\n", property.name, [sub stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]]; + } + [mString appendString:@"}"]; + + return [NSString stringWithString:mString]; +} + +- (RLMRealm *)realm { + return _realm; +} + +- (RLMObjectSchema *)objectSchema { + return _objectSchema; +} + +- (BOOL)isInvalidated { + // if not unmanaged and our accessor has been detached, we have been deleted + return self.class == _objectSchema.accessorClass && !_row.is_attached(); +} + +- (BOOL)isEqual:(id)object { + if (RLMObjectBase *other = RLMDynamicCast(object)) { + if (_objectSchema.primaryKeyProperty) { + return RLMObjectBaseAreEqual(self, other); + } + } + return [super isEqual:object]; +} + +- (NSUInteger)hash { + if (_objectSchema.primaryKeyProperty) { + id primaryProperty = [self valueForKey:_objectSchema.primaryKeyProperty.name]; + + // modify the hash of our primary key value to avoid potential (although unlikely) collisions + return [primaryProperty hash] ^ 1; + } + else { + return [super hash]; + } +} + ++ (BOOL)shouldIncludeInDefaultSchema { + return RLMIsObjectSubclass(self); +} + ++ (NSString *)_realmObjectName { + return nil; +} + ++ (NSDictionary *)_realmColumnNames { + return nil; +} + +- (id)mutableArrayValueForKey:(NSString *)key { + id obj = [self valueForKey:key]; + if ([obj isKindOfClass:[RLMArray class]]) { + return obj; + } + return [super mutableArrayValueForKey:key]; +} + +- (void)addObserver:(id)observer + forKeyPath:(NSString *)keyPath + options:(NSKeyValueObservingOptions)options + context:(void *)context { + if (!_observationInfo) { + _observationInfo = new RLMObservationInfo(self); + } + _observationInfo->recordObserver(_row, _info, _objectSchema, keyPath); + + [super addObserver:observer forKeyPath:keyPath options:options context:context]; +} + +- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath { + [super removeObserver:observer forKeyPath:keyPath]; + if (_observationInfo) + _observationInfo->removeObserver(); +} + ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { + const char *className = class_getName(self); + const char accessorClassPrefix[] = "RLM:Managed"; + if (!strncmp(className, accessorClassPrefix, sizeof(accessorClassPrefix) - 1)) { + if ([class_getSuperclass(self.class) sharedSchema][key]) { + return NO; + } + } + + return [super automaticallyNotifiesObserversForKey:key]; +} + +#pragma mark - Thread Confined Protocol Conformance + +- (std::unique_ptr)makeThreadSafeReference { + Object object(_realm->_realm, *_info->objectSchema, _row); + realm::ThreadSafeReference reference = _realm->_realm->obtain_thread_safe_reference(std::move(object)); + return std::make_unique>(std::move(reference)); +} + +- (id)objectiveCMetadata { + return nil; +} + ++ (instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference + metadata:(__unused id)metadata + realm:(RLMRealm *)realm { + REALM_ASSERT_DEBUG(dynamic_cast *>(reference.get())); + auto object_reference = static_cast *>(reference.get()); + + Object object = realm->_realm->resolve_thread_safe_reference(std::move(*object_reference)); + if (!object.is_valid()) { + return nil; + } + NSString *objectClassName = @(object.get_object_schema().name.c_str()); + + return RLMCreateObjectAccessor(realm, realm->_info[objectClassName], object.row().get_index()); +} + +@end + +RLMRealm *RLMObjectBaseRealm(__unsafe_unretained RLMObjectBase *object) { + return object ? object->_realm : nil; +} + +RLMObjectSchema *RLMObjectBaseObjectSchema(__unsafe_unretained RLMObjectBase *object) { + return object ? object->_objectSchema : nil; +} + +id RLMObjectBaseObjectForKeyedSubscript(RLMObjectBase *object, NSString *key) { + if (!object) { + return nil; + } + + if (object->_realm) { + return RLMDynamicGetByName(object, key, false); + } + else { + return [object valueForKey:key]; + } +} + +void RLMObjectBaseSetObjectForKeyedSubscript(RLMObjectBase *object, NSString *key, id obj) { + if (!object) { + return; + } + + if (object->_realm || object.class == object->_objectSchema.accessorClass) { + RLMDynamicValidatedSet(object, key, obj); + } + else { + [object setValue:obj forKey:key]; + } +} + + +BOOL RLMObjectBaseAreEqual(RLMObjectBase *o1, RLMObjectBase *o2) { + // if not the correct types throw + if ((o1 && ![o1 isKindOfClass:RLMObjectBase.class]) || (o2 && ![o2 isKindOfClass:RLMObjectBase.class])) { + @throw RLMException(@"Can only compare objects of class RLMObjectBase"); + } + // if identical object (or both are nil) + if (o1 == o2) { + return YES; + } + // if one is nil + if (o1 == nil || o2 == nil) { + return NO; + } + // if not in realm or differing realms + if (o1->_realm == nil || o1->_realm != o2->_realm) { + return NO; + } + // if either are detached + if (!o1->_row.is_attached() || !o2->_row.is_attached()) { + return NO; + } + // if table and index are the same + return o1->_row.get_table() == o2->_row.get_table() + && o1->_row.get_index() == o2->_row.get_index(); +} + +id RLMValidatedValueForProperty(id object, NSString *key, NSString *className) { + @try { + return [object valueForKey:key]; + } + @catch (NSException *e) { + if ([e.name isEqualToString:NSUndefinedKeyException]) { + @throw RLMException(@"Invalid value '%@' to initialize object of type '%@': missing key '%@'", + object, className, key); + } + @throw; + } +} + +Class RLMObjectUtilClass(BOOL isSwift) { + static Class objectUtilObjc = [RLMObjectUtil class]; + static Class objectUtilSwift = NSClassFromString(@"RealmSwiftObjectUtil"); + return isSwift && objectUtilSwift ? objectUtilSwift : objectUtilObjc; +} + +@implementation RLMObjectUtil + ++ (NSArray *)ignoredPropertiesForClass:(Class)cls { + return [cls ignoredProperties]; +} + ++ (NSArray *)indexedPropertiesForClass:(Class)cls { + return [cls indexedProperties]; +} + ++ (NSDictionary *)linkingObjectsPropertiesForClass:(Class)cls { + return [cls linkingObjectsProperties]; +} + ++ (NSDictionary *)linkingObjectProperties:(__unused id)object { + return nil; +} + ++ (NSArray *)getSwiftProperties:(__unused id)obj { + return nil; +} + ++ (NSDictionary *)getOptionalProperties:(__unused id)obj { + return nil; +} + ++ (NSArray *)requiredPropertiesForClass:(Class)cls { + return [cls requiredProperties]; +} + +@end + +@implementation RLMSwiftPropertyMetadata + ++ (instancetype)metadataForOtherProperty:(NSString *)propertyName { + RLMSwiftPropertyMetadata *md = [RLMSwiftPropertyMetadata new]; + md.propertyName = propertyName; + md.kind = RLMSwiftPropertyKindOther; + return md; +} + ++ (instancetype)metadataForListProperty:(NSString *)propertyName { + RLMSwiftPropertyMetadata *md = [RLMSwiftPropertyMetadata new]; + md.propertyName = propertyName; + md.kind = RLMSwiftPropertyKindList; + return md; +} + ++ (instancetype)metadataForLinkingObjectsProperty:(NSString *)propertyName + className:(NSString *)className + linkedPropertyName:(NSString *)linkedPropertyName { + RLMSwiftPropertyMetadata *md = [RLMSwiftPropertyMetadata new]; + md.propertyName = propertyName; + md.className = className; + md.linkedPropertyName = linkedPropertyName; + md.kind = RLMSwiftPropertyKindLinkingObjects; + return md; +} + ++ (instancetype)metadataForOptionalProperty:(NSString *)propertyName type:(RLMPropertyType)type { + RLMSwiftPropertyMetadata *md = [RLMSwiftPropertyMetadata new]; + md.propertyName = propertyName; + md.propertyType = type; + md.kind = RLMSwiftPropertyKindOptional; + return md; +} + ++ (instancetype)metadataForNilLiteralOptionalProperty:(NSString *)propertyName { + RLMSwiftPropertyMetadata *md = [RLMSwiftPropertyMetadata new]; + md.propertyName = propertyName; + md.kind = RLMSwiftPropertyKindNilLiteralOptional; + return md; +} + +@end diff --git a/Pods/Realm/Realm/RLMObjectSchema.mm b/Pods/Realm/Realm/RLMObjectSchema.mm new file mode 100644 index 0000000000..91d86f50cb --- /dev/null +++ b/Pods/Realm/Realm/RLMObjectSchema.mm @@ -0,0 +1,479 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMObjectSchema_Private.hpp" + +#import "RLMArray.h" +#import "RLMListBase.h" +#import "RLMObject_Private.h" +#import "RLMProperty_Private.hpp" +#import "RLMRealm_Dynamic.h" +#import "RLMRealm_Private.hpp" +#import "RLMSchema_Private.h" +#import "RLMSwiftSupport.h" +#import "RLMUtil.hpp" + +#import "object_schema.hpp" +#import "object_store.hpp" + +using namespace realm; + +const Ivar RLMDummySwiftIvar = []() { + static int dummy; + return reinterpret_cast(&dummy); +}(); + +// private properties +@interface RLMObjectSchema () +@property (nonatomic, readwrite) NSDictionary *allPropertiesByName; +@property (nonatomic, readwrite) NSString *className; +@end + +@implementation RLMObjectSchema { + NSArray *_swiftGenericProperties; +} + +- (instancetype)initWithClassName:(NSString *)objectClassName objectClass:(Class)objectClass properties:(NSArray *)properties { + self = [super init]; + self.className = objectClassName; + self.properties = properties; + self.objectClass = objectClass; + self.accessorClass = objectClass; + self.unmanagedClass = objectClass; + return self; +} + +// return properties by name +- (RLMProperty *)objectForKeyedSubscript:(__unsafe_unretained NSString *const)key { + return _allPropertiesByName[key]; +} + +// create property map when setting property array +- (void)setProperties:(NSArray *)properties { + _properties = properties; + [self _propertiesDidChange]; +} + +- (void)setComputedProperties:(NSArray *)computedProperties { + _computedProperties = computedProperties; + [self _propertiesDidChange]; +} + +- (void)_propertiesDidChange { + NSMutableDictionary *map = [NSMutableDictionary dictionaryWithCapacity:_properties.count + _computedProperties.count]; + NSUInteger index = 0; + for (RLMProperty *prop in _properties) { + prop.index = index++; + map[prop.name] = prop; + if (prop.isPrimary) { + self.primaryKeyProperty = prop; + } + } + index = 0; + for (RLMProperty *prop in _computedProperties) { + prop.index = index++; + map[prop.name] = prop; + } + _allPropertiesByName = map; +} + + +- (void)setPrimaryKeyProperty:(RLMProperty *)primaryKeyProperty { + _primaryKeyProperty.isPrimary = NO; + primaryKeyProperty.isPrimary = YES; + _primaryKeyProperty = primaryKeyProperty; +} + ++ (instancetype)schemaForObjectClass:(Class)objectClass { + RLMObjectSchema *schema = [RLMObjectSchema new]; + + // determine classname from objectclass as className method has not yet been updated + NSString *className = NSStringFromClass(objectClass); + bool hasSwiftName = [RLMSwiftSupport isSwiftClassName:className]; + if (hasSwiftName) { + className = [RLMSwiftSupport demangleClassName:className]; + } + + static Class s_swiftObjectClass = NSClassFromString(@"RealmSwiftObject"); + bool isSwift = hasSwiftName || [objectClass isSubclassOfClass:s_swiftObjectClass]; + + schema.className = className; + schema.objectClass = objectClass; + schema.accessorClass = objectClass; + schema.isSwiftClass = isSwift; + + // create array of RLMProperties, inserting properties of superclasses first + Class cls = objectClass; + Class superClass = class_getSuperclass(cls); + NSArray *allProperties = @[]; + while (superClass && superClass != RLMObjectBase.class) { + allProperties = [[RLMObjectSchema propertiesForClass:cls isSwift:isSwift] + arrayByAddingObjectsFromArray:allProperties]; + cls = superClass; + superClass = class_getSuperclass(superClass); + } + NSArray *persistedProperties = [allProperties filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(RLMProperty *property, NSDictionary *) { + return !RLMPropertyTypeIsComputed(property.type); + }]]; + schema.properties = persistedProperties; + + NSArray *computedProperties = [allProperties filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(RLMProperty *property, NSDictionary *) { + return RLMPropertyTypeIsComputed(property.type); + }]]; + schema.computedProperties = computedProperties; + + // verify that we didn't add any properties twice due to inheritance + if (allProperties.count != [NSSet setWithArray:[allProperties valueForKey:@"name"]].count) { + NSCountedSet *countedPropertyNames = [NSCountedSet setWithArray:[allProperties valueForKey:@"name"]]; + NSArray *duplicatePropertyNames = [countedPropertyNames filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *) { + return [countedPropertyNames countForObject:object] > 1; + }]].allObjects; + + if (duplicatePropertyNames.count == 1) { + @throw RLMException(@"Property '%@' is declared multiple times in the class hierarchy of '%@'", duplicatePropertyNames.firstObject, className); + } else { + @throw RLMException(@"Object '%@' has properties that are declared multiple times in its class hierarchy: '%@'", className, [duplicatePropertyNames componentsJoinedByString:@"', '"]); + } + } + + if (NSString *primaryKey = [objectClass primaryKey]) { + for (RLMProperty *prop in schema.properties) { + if ([primaryKey isEqualToString:prop.name]) { + prop.indexed = YES; + schema.primaryKeyProperty = prop; + break; + } + } + + if (!schema.primaryKeyProperty) { + @throw RLMException(@"Primary key property '%@' does not exist on object '%@'", primaryKey, className); + } + if (schema.primaryKeyProperty.type != RLMPropertyTypeInt && schema.primaryKeyProperty.type != RLMPropertyTypeString) { + @throw RLMException(@"Property '%@' cannot be made the primary key of '%@' because it is not a 'string' or 'int' property.", + primaryKey, className); + } + } + + for (RLMProperty *prop in schema.properties) { + if (prop.optional && prop.array && (prop.type == RLMPropertyTypeObject || prop.type == RLMPropertyTypeLinkingObjects)) { + // FIXME: message is awkward + @throw RLMException(@"Property '%@.%@' cannot be made optional because optional '%@' properties are not supported.", + className, prop.name, RLMTypeToString(prop.type)); + } + } + + return schema; +} + ++ (NSArray *)propertiesForClass:(Class)objectClass isSwift:(bool)isSwiftClass { + Class objectUtil = [objectClass objectUtilClass:isSwiftClass]; + NSArray *ignoredProperties = [objectUtil ignoredPropertiesForClass:objectClass]; + NSDictionary *linkingObjectsProperties = [objectUtil linkingObjectsPropertiesForClass:objectClass]; + NSDictionary *columnNameMap = [objectClass _realmColumnNames]; + + // For Swift classes we need an instance of the object when parsing properties + id swiftObjectInstance = isSwiftClass ? [[objectClass alloc] init] : nil; + + unsigned int count; + std::unique_ptr props(class_copyPropertyList(objectClass, &count), &free); + NSMutableArray *propArray = [NSMutableArray arrayWithCapacity:count]; + NSSet *indexed = [[NSSet alloc] initWithArray:[objectUtil indexedPropertiesForClass:objectClass]]; + for (unsigned int i = 0; i < count; i++) { + NSString *propertyName = @(property_getName(props[i])); + if ([ignoredProperties containsObject:propertyName]) { + continue; + } + + RLMProperty *prop = nil; + if (isSwiftClass) { + prop = [[RLMProperty alloc] initSwiftPropertyWithName:propertyName + indexed:[indexed containsObject:propertyName] + linkPropertyDescriptor:linkingObjectsProperties[propertyName] + property:props[i] + instance:swiftObjectInstance]; + } + else { + prop = [[RLMProperty alloc] initWithName:propertyName + indexed:[indexed containsObject:propertyName] + linkPropertyDescriptor:linkingObjectsProperties[propertyName] + property:props[i]]; + } + + if (prop) { + if (columnNameMap) { + prop.columnName = columnNameMap[prop.name]; + } + [propArray addObject:prop]; + } + } + + if (isSwiftClass) { + [self addSwiftProperties:propArray objectUtil:objectUtil instance:swiftObjectInstance + indexed:indexed nameMap:columnNameMap]; + } + + if (auto requiredProperties = [objectUtil requiredPropertiesForClass:objectClass]) { + for (RLMProperty *property in propArray) { + bool required = [requiredProperties containsObject:property.name]; + if (required && property.type == RLMPropertyTypeObject && !property.array) { + @throw RLMException(@"Object properties cannot be made required, " + "but '+[%@ requiredProperties]' included '%@'", objectClass, property.name); + } + property.optional &= !required; + } + } + + for (RLMProperty *property in propArray) { + if (!property.optional && property.type == RLMPropertyTypeObject && !property.array) { + @throw RLMException(@"The `%@.%@` property must be marked as being optional.", + [objectClass className], property.name); + } + } + + return propArray; +} + ++ (void)addSwiftProperties:(NSMutableArray *)propArray + objectUtil:(Class)objectUtil + instance:(id)instance + indexed:(NSSet *)indexed + nameMap:(NSDictionary *)columnNameMap { + // The property list reported to the obj-c runtime for Swift objects is + // incomplete and doesn't include Swift generics like List<> and + // RealmOptional<>, and is missing information for some properties that + // are reported, such as the difference between `String` and `String?`. To + // deal with this, we also get the properties from Swift reflection, and + // merge the results. + + NSArray *props = [objectUtil getSwiftProperties:instance]; + if (!props) { + // A Swift subclass of RLMObject, which operates under obj-c rules + return; + } + + // Track the index that we expect the next property to go in, for inserting + // generic properties into the correct place + NSUInteger nextIndex = 0; + for (RLMSwiftPropertyMetadata *md in props) { + // In theory existing should only ever be nextIndex or NSNotFound, and + // this search is just a waste of time. + // FIXME: verify if this is actually true + NSUInteger existing = [propArray indexOfObjectPassingTest:^(RLMProperty *obj, NSUInteger, BOOL *) { + return [obj.name isEqualToString:md.propertyName]; + }]; + + RLMProperty *prop; + switch (md.kind) { + case RLMSwiftPropertyKindList: // List<> + prop = [[RLMProperty alloc] initSwiftListPropertyWithName:md.propertyName instance:instance]; + break; + case RLMSwiftPropertyKindLinkingObjects: { // LinkingObjects<> + Ivar ivar = class_getInstanceVariable([instance class], md.propertyName.UTF8String); + prop = [[RLMProperty alloc] initSwiftLinkingObjectsPropertyWithName:md.propertyName + ivar:ivar + objectClassName:md.className + linkOriginPropertyName:md.linkedPropertyName]; + break; + } + case RLMSwiftPropertyKindOptional: { + if (existing != NSNotFound) { + // String?, Data?, Date? with a non-nil default value + // We already know about this property from obj-c and we + // defaulted to optional, so nothing to do + break; + } + + Ivar ivar; + if (md.propertyType == RLMPropertyTypeString) { + // FIXME: A non-@objc dynamic String? property which we + // can't actually read so we're always just going to pretend it's nil + // https://github.com/realm/realm-cocoa/issues/5784 + ivar = RLMDummySwiftIvar; + } + else { + // RealmOptional<> + ivar = class_getInstanceVariable([instance class], md.propertyName.UTF8String); + } + + prop = [[RLMProperty alloc] initSwiftOptionalPropertyWithName:md.propertyName + indexed:[indexed containsObject:md.propertyName] + ivar:ivar + propertyType:md.propertyType]; + break; + } + + case RLMSwiftPropertyKindOther: + case RLMSwiftPropertyKindNilLiteralOptional: + // This might be a property which wasn't reported to obj-c and + // isn't one of our supported generic types, in which case we + // ignore it + if (existing == NSNotFound) { + --nextIndex; + } + // or it might be a String?, Data?, Date? or object field with + // a nil default value + else if (md.kind == RLMSwiftPropertyKindNilLiteralOptional) { + propArray[existing].optional = true; + } + // or it may be some non-optional property which may have been + // previously marked as optional due to that being the default + // in obj-c + else { + propArray[existing].optional = false; + } + break; + } + + if (prop) { + if (columnNameMap) { + prop.columnName = columnNameMap[prop.name]; + } + [propArray insertObject:prop atIndex:nextIndex]; + } + + ++nextIndex; + } +} + +- (id)copyWithZone:(NSZone *)zone { + RLMObjectSchema *schema = [[RLMObjectSchema allocWithZone:zone] init]; + schema->_objectClass = _objectClass; + schema->_className = _className; + schema->_objectClass = _objectClass; + schema->_accessorClass = _objectClass; + schema->_unmanagedClass = _unmanagedClass; + schema->_isSwiftClass = _isSwiftClass; + + // call property setter to reset map and primary key + schema.properties = [[NSArray allocWithZone:zone] initWithArray:_properties copyItems:YES]; + schema.computedProperties = [[NSArray allocWithZone:zone] initWithArray:_computedProperties copyItems:YES]; + + return schema; +} + +- (BOOL)isEqualToObjectSchema:(RLMObjectSchema *)objectSchema { + if (objectSchema.properties.count != _properties.count) { + return NO; + } + + if (![_properties isEqualToArray:objectSchema.properties]) { + return NO; + } + if (![_computedProperties isEqualToArray:objectSchema.computedProperties]) { + return NO; + } + + return YES; +} + +- (NSString *)description { + NSMutableString *propertiesString = [NSMutableString string]; + for (RLMProperty *property in self.properties) { + [propertiesString appendFormat:@"\t%@\n", [property.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]]; + } + for (RLMProperty *property in self.computedProperties) { + [propertiesString appendFormat:@"\t%@\n", [property.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]]; + } + return [NSString stringWithFormat:@"%@ {\n%@}", self.className, propertiesString]; +} + +- (NSString *)objectName { + return [self.objectClass _realmObjectName] ?: _className; +} + +- (realm::ObjectSchema)objectStoreCopy:(RLMSchema *)schema { + ObjectSchema objectSchema; + objectSchema.name = self.objectName.UTF8String; + objectSchema.primary_key = _primaryKeyProperty ? _primaryKeyProperty.columnName.UTF8String : ""; + for (RLMProperty *prop in _properties) { + Property p = [prop objectStoreCopy:schema]; + p.is_primary = (prop == _primaryKeyProperty); + objectSchema.persisted_properties.push_back(std::move(p)); + } + for (RLMProperty *prop in _computedProperties) { + objectSchema.computed_properties.push_back([prop objectStoreCopy:schema]); + } + return objectSchema; +} + ++ (instancetype)objectSchemaForObjectStoreSchema:(realm::ObjectSchema const&)objectSchema { + RLMObjectSchema *schema = [RLMObjectSchema new]; + schema.className = @(objectSchema.name.c_str()); + + // create array of RLMProperties + NSMutableArray *properties = [NSMutableArray arrayWithCapacity:objectSchema.persisted_properties.size()]; + for (const Property &prop : objectSchema.persisted_properties) { + RLMProperty *property = [RLMProperty propertyForObjectStoreProperty:prop]; + property.isPrimary = (prop.name == objectSchema.primary_key); + [properties addObject:property]; + } + schema.properties = properties; + + NSMutableArray *computedProperties = [NSMutableArray arrayWithCapacity:objectSchema.computed_properties.size()]; + for (const Property &prop : objectSchema.computed_properties) { + [computedProperties addObject:[RLMProperty propertyForObjectStoreProperty:prop]]; + } + schema.computedProperties = computedProperties; + + // get primary key from realm metadata + if (objectSchema.primary_key.length()) { + NSString *primaryKeyString = [NSString stringWithUTF8String:objectSchema.primary_key.c_str()]; + schema.primaryKeyProperty = schema[primaryKeyString]; + if (!schema.primaryKeyProperty) { + @throw RLMException(@"No property matching primary key '%@'", primaryKeyString); + } + } + + // for dynamic schema use vanilla RLMDynamicObject accessor classes + schema.objectClass = RLMObject.class; + schema.accessorClass = RLMDynamicObject.class; + schema.unmanagedClass = RLMObject.class; + + return schema; +} + +- (NSArray *)swiftGenericProperties { + if (_swiftGenericProperties) { + return _swiftGenericProperties; + } + + // This check isn't semantically required, but avoiding accessing the local + // static helps perf in the obj-c case + if (!_isSwiftClass) { + return _swiftGenericProperties = @[]; + } + + // Check if it's a swift class using the obj-c API + static Class s_swiftObjectClass = NSClassFromString(@"RealmSwiftObject"); + if (![_accessorClass isSubclassOfClass:s_swiftObjectClass]) { + return _swiftGenericProperties = @[]; + } + + NSMutableArray *genericProperties = [NSMutableArray new]; + for (RLMProperty *prop in _properties) { + if (prop->_swiftIvar) { + [genericProperties addObject:prop]; + } + } + // Currently all computed properties are Swift generics + [genericProperties addObjectsFromArray:_computedProperties]; + + return _swiftGenericProperties = genericProperties; +} + +@end diff --git a/Pods/Realm/Realm/RLMObjectStore.mm b/Pods/Realm/Realm/RLMObjectStore.mm new file mode 100644 index 0000000000..4f9773f413 --- /dev/null +++ b/Pods/Realm/Realm/RLMObjectStore.mm @@ -0,0 +1,273 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMObjectStore.h" + +#import "RLMAccessor.hpp" +#import "RLMArray_Private.hpp" +#import "RLMListBase.h" +#import "RLMObservation.hpp" +#import "RLMObject_Private.hpp" +#import "RLMObjectSchema_Private.hpp" +#import "RLMOptionalBase.h" +#import "RLMProperty_Private.h" +#import "RLMQueryUtil.hpp" +#import "RLMRealm_Private.hpp" +#import "RLMSchema_Private.h" +#import "RLMSwiftSupport.h" +#import "RLMUtil.hpp" + +#import "object_store.hpp" +#import "results.hpp" +#import "shared_realm.hpp" + +#import + +using namespace realm; + +@interface LinkingObjectsBase : NSObject +@property (nonatomic, nullable) RLMWeakObjectHandle *object; +@property (nonatomic, nullable) RLMProperty *property; +@end + +void RLMRealmCreateAccessors(RLMSchema *schema) { + const size_t bufferSize = sizeof("RLM:Managed ") // includes null terminator + + std::numeric_limits::digits10 + + realm::Group::max_table_name_length; + + char className[bufferSize] = "RLM:Managed "; + char *const start = className + strlen(className); + + for (RLMObjectSchema *objectSchema in schema.objectSchema) { + if (objectSchema.accessorClass != objectSchema.objectClass) { + continue; + } + + static unsigned long long count = 0; + sprintf(start, "%llu %s", count++, objectSchema.className.UTF8String); + objectSchema.accessorClass = RLMManagedAccessorClassForObjectClass(objectSchema.objectClass, objectSchema, className); + } +} + +static inline void RLMVerifyRealmRead(__unsafe_unretained RLMRealm *const realm) { + if (!realm) { + @throw RLMException(@"Realm must not be nil"); + } + [realm verifyThread]; +} + +static inline void RLMVerifyInWriteTransaction(__unsafe_unretained RLMRealm *const realm) { + RLMVerifyRealmRead(realm); + // if realm is not writable throw + if (!realm.inWriteTransaction) { + @throw RLMException(@"Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first."); + } +} + +void RLMInitializeSwiftAccessorGenerics(__unsafe_unretained RLMObjectBase *const object) { + if (!object || !object->_row || !object->_objectSchema->_isSwiftClass) { + return; + } + if (![object isKindOfClass:object->_objectSchema.objectClass]) { + // It can be a different class if it's a dynamic object, and those don't + // require any init here (and would crash since they don't have the ivars) + return; + } + + for (RLMProperty *prop in object->_objectSchema.swiftGenericProperties) { + if (prop.swiftIvar == RLMDummySwiftIvar) { + // FIXME: this should actually be an error as it's the result of an + // invalid object definition, but that's a breaking change so + // instead preserve the old behavior until the next major version bump + // https://github.com/realm/realm-cocoa/issues/5784 + continue; + } + id ivar = object_getIvar(object, prop.swiftIvar); + if (prop.type == RLMPropertyTypeLinkingObjects) { + [ivar setObject:(id)[[RLMWeakObjectHandle alloc] initWithObject:object]]; + [ivar setProperty:prop]; + } + else if (prop.array) { + RLMArray *array = [[RLMManagedArray alloc] initWithParent:object property:prop]; + [ivar set_rlmArray:array]; + } + else { + RLMInitializeManagedOptional(ivar, object, prop); + } + } +} + +void RLMAddObjectToRealm(__unsafe_unretained RLMObjectBase *const object, + __unsafe_unretained RLMRealm *const realm, + bool createOrUpdate) { + RLMVerifyInWriteTransaction(realm); + + // verify that object is unmanaged + if (object.invalidated) { + @throw RLMException(@"Adding a deleted or invalidated object to a Realm is not permitted"); + } + if (object->_realm) { + if (object->_realm == realm) { + // Adding an object to the Realm it's already manged by is a no-op + return; + } + // for differing realms users must explicitly create the object in the second realm + @throw RLMException(@"Object is already managed by another Realm. Use create instead to copy it into this Realm."); + } + if (object->_observationInfo && object->_observationInfo->hasObservers()) { + @throw RLMException(@"Cannot add an object with observers to a Realm"); + } + + auto& info = realm->_info[object->_objectSchema.className]; + RLMAccessorContext c{realm, info, true}; + object->_info = &info; + object->_realm = realm; + object->_objectSchema = info.rlmObjectSchema; + try { + realm::Object::create(c, realm->_realm, *info.objectSchema, (id)object, + createOrUpdate, &object->_row); + } + catch (std::exception const& e) { + @throw RLMException(e); + } + object_setClass(object, info.rlmObjectSchema.accessorClass); + RLMInitializeSwiftAccessorGenerics(object); +} + +RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className, + id value, bool createOrUpdate = false) { + RLMVerifyInWriteTransaction(realm); + + if (createOrUpdate && RLMIsObjectSubclass([value class])) { + RLMObjectBase *obj = value; + if (obj->_realm == realm && [obj->_objectSchema.className isEqualToString:className]) { + // This is a no-op if value is an RLMObject of the same type already backed by the target realm. + return value; + } + } + + if (!value || value == NSNull.null) { + @throw RLMException(@"Must provide a non-nil value."); + } + + auto& info = realm->_info[className]; + if ([value isKindOfClass:[NSArray class]] && [value count] > info.objectSchema->persisted_properties.size()) { + @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).", + (unsigned long long)[value count], + (unsigned long long)info.objectSchema->persisted_properties.size()); + } + + RLMAccessorContext c{realm, info, false}; + RLMObjectBase *object = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, realm, &info); + try { + object->_row = realm::Object::create(c, realm->_realm, *info.objectSchema, + (id)value, createOrUpdate).row(); + } + catch (std::exception const& e) { + @throw RLMException(e); + } + RLMInitializeSwiftAccessorGenerics(object); + return object; +} + +void RLMDeleteObjectFromRealm(__unsafe_unretained RLMObjectBase *const object, + __unsafe_unretained RLMRealm *const realm) { + if (realm != object->_realm) { + @throw RLMException(@"Can only delete an object from the Realm it belongs to."); + } + + RLMVerifyInWriteTransaction(object->_realm); + + // move last row to row we are deleting + if (object->_row.is_attached()) { + RLMTrackDeletions(realm, ^{ + object->_row.move_last_over(); + }); + } + + // set realm to nil + object->_realm = nil; +} + +void RLMDeleteAllObjectsFromRealm(RLMRealm *realm) { + RLMVerifyInWriteTransaction(realm); + + // clear table for each object schema + for (auto& info : realm->_info) { + RLMClearTable(info.second); + } +} + +RLMResults *RLMGetObjects(__unsafe_unretained RLMRealm *const realm, + NSString *objectClassName, + NSPredicate *predicate) { + RLMVerifyRealmRead(realm); + + // create view from table and predicate + RLMClassInfo& info = realm->_info[objectClassName]; + if (!info.table()) { + // read-only realms may be missing tables since we can't add any + // missing ones on init + return [RLMResults resultsWithObjectInfo:info results:{}]; + } + + if (predicate) { + realm::Query query = RLMPredicateToQuery(predicate, info.rlmObjectSchema, realm.schema, realm.group); + return [RLMResults resultsWithObjectInfo:info + results:realm::Results(realm->_realm, std::move(query))]; + } + + return [RLMResults resultsWithObjectInfo:info + results:realm::Results(realm->_realm, *info.table())]; +} + +id RLMGetObject(RLMRealm *realm, NSString *objectClassName, id key) { + RLMVerifyRealmRead(realm); + + auto& info = realm->_info[objectClassName]; + if (RLMProperty *prop = info.propertyForPrimaryKey()) { + RLMValidateValueForProperty(key, info.rlmObjectSchema, prop); + } + try { + RLMAccessorContext c{realm, info}; + auto obj = realm::Object::get_for_primary_key(c, realm->_realm, *info.objectSchema, + key ?: NSNull.null); + if (!obj.is_valid()) + return nil; + return RLMCreateObjectAccessor(realm, info, obj.row()); + } + catch (std::exception const& e) { + @throw RLMException(e); + } +} + +RLMObjectBase *RLMCreateObjectAccessor(__unsafe_unretained RLMRealm *const realm, + RLMClassInfo& info, + NSUInteger index) { + return RLMCreateObjectAccessor(realm, info, (*info.table())[index]); +} + +// Create accessor and register with realm +RLMObjectBase *RLMCreateObjectAccessor(__unsafe_unretained RLMRealm *const realm, + RLMClassInfo& info, + realm::RowExpr row) { + RLMObjectBase *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, realm, &info); + accessor->_row = row; + RLMInitializeSwiftAccessorGenerics(accessor); + return accessor; +} diff --git a/Pods/Realm/Realm/RLMObservation.mm b/Pods/Realm/Realm/RLMObservation.mm new file mode 100644 index 0000000000..f8102ed49e --- /dev/null +++ b/Pods/Realm/Realm/RLMObservation.mm @@ -0,0 +1,499 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMObservation.hpp" + +#import "RLMAccessor.h" +#import "RLMArray_Private.hpp" +#import "RLMListBase.h" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObject_Private.hpp" +#import "RLMProperty_Private.h" +#import "RLMRealm_Private.hpp" + +#import + +using namespace realm; + +namespace { + template + struct IteratorPair { + Iterator first; + Iterator second; + }; + template + Iterator begin(IteratorPair const& p) { + return p.first; + } + template + Iterator end(IteratorPair const& p) { + return p.second; + } + + template + auto reverse(Container const& c) { + return IteratorPair{c.rbegin(), c.rend()}; + } +} + +RLMObservationInfo::RLMObservationInfo(RLMClassInfo &objectSchema, std::size_t row, id object) +: object(object) +, objectSchema(&objectSchema) +{ + setRow(*objectSchema.table(), row); +} + +RLMObservationInfo::RLMObservationInfo(id object) +: object(object) +{ +} + +RLMObservationInfo::~RLMObservationInfo() { + if (prev) { + // Not the head of the linked list, so just detach from the list + REALM_ASSERT_DEBUG(prev->next == this); + prev->next = next; + if (next) { + REALM_ASSERT_DEBUG(next->prev == this); + next->prev = prev; + } + } + else if (objectSchema) { + // The head of the list, so remove self from the object schema's array + // of observation info, either replacing self with the next info or + // removing entirely if there is no next + auto end = objectSchema->observedObjects.end(); + auto it = find(objectSchema->observedObjects.begin(), end, this); + if (it != end) { + if (next) { + *it = next; + next->prev = nullptr; + } + else { + iter_swap(it, std::prev(end)); + objectSchema->observedObjects.pop_back(); + } + } + } + // Otherwise the observed object was unmanaged, so nothing to do + +#ifdef DEBUG + // ensure that incorrect cleanup fails noisily + object = (__bridge id)(void *)-1; + prev = (RLMObservationInfo *)-1; + next = (RLMObservationInfo *)-1; +#endif +} + +NSString *RLMObservationInfo::columnName(size_t col) const noexcept { + return objectSchema->propertyForTableColumn(col).name; +} + +void RLMObservationInfo::willChange(NSString *key, NSKeyValueChange kind, NSIndexSet *indexes) const { + if (indexes) { + forEach([=](__unsafe_unretained auto o) { + [o willChange:kind valuesAtIndexes:indexes forKey:key]; + }); + } + else { + forEach([=](__unsafe_unretained auto o) { + [o willChangeValueForKey:key]; + }); + } +} + +void RLMObservationInfo::didChange(NSString *key, NSKeyValueChange kind, NSIndexSet *indexes) const { + if (indexes) { + forEach([=](__unsafe_unretained auto o) { + [o didChange:kind valuesAtIndexes:indexes forKey:key]; + }); + } + else { + forEach([=](__unsafe_unretained auto o) { + [o didChangeValueForKey:key]; + }); + } +} + +void RLMObservationInfo::prepareForInvalidation() { + REALM_ASSERT_DEBUG(objectSchema); + REALM_ASSERT_DEBUG(!prev); + for (auto info = this; info; info = info->next) + info->invalidated = true; +} + +void RLMObservationInfo::setRow(realm::Table &table, size_t newRow) { + REALM_ASSERT_DEBUG(!row); + REALM_ASSERT_DEBUG(objectSchema); + row = table[newRow]; + for (auto info : objectSchema->observedObjects) { + if (info->row && info->row.get_index() == row.get_index()) { + prev = info; + next = info->next; + if (next) + next->prev = this; + info->next = this; + return; + } + } + objectSchema->observedObjects.push_back(this); +} + +void RLMObservationInfo::recordObserver(realm::Row& objectRow, RLMClassInfo *objectInfo, + __unsafe_unretained RLMObjectSchema *const objectSchema, + __unsafe_unretained NSString *const keyPath) { + ++observerCount; + if (row) { + return; + } + + // add ourselves to the list of observed objects if this is the first time + // an observer is being added to a managed object + if (objectRow) { + this->objectSchema = objectInfo; + setRow(*objectRow.get_table(), objectRow.get_index()); + return; + } + + // Arrays need a reference to their containing object to avoid having to + // go through the awful proxy object from mutableArrayValueForKey. + // For managed objects we do this when the object is added or created + // (and have to to support notifications from modifying an object which + // was never observed), but for Swift classes (both RealmSwift and + // RLMObject) we can't do it then because we don't know what the parent + // object is. + + NSUInteger sep = [keyPath rangeOfString:@"."].location; + NSString *key = sep == NSNotFound ? keyPath : [keyPath substringToIndex:sep]; + RLMProperty *prop = objectSchema[key]; + if (prop && prop.array) { + id value = valueForKey(key); + RLMArray *array = [value isKindOfClass:[RLMListBase class]] ? [value _rlmArray] : value; + array->_key = key; + array->_parentObject = object; + } + else if (auto swiftIvar = prop.swiftIvar) { + if (auto optional = RLMDynamicCast(object_getIvar(object, swiftIvar))) { + RLMInitializeUnmanagedOptional(optional, object, prop); + } + } +} + +void RLMObservationInfo::removeObserver() { + --observerCount; +} + +id RLMObservationInfo::valueForKey(NSString *key) { + if (invalidated) { + if ([key isEqualToString:RLMInvalidatedKey]) { + return @YES; + } + return cachedObjects[key]; + } + + if (key != lastKey) { + lastKey = key; + lastProp = objectSchema ? objectSchema->rlmObjectSchema[key] : nil; + } + + static auto superValueForKey = reinterpret_cast([NSObject methodForSelector:@selector(valueForKey:)]); + if (!lastProp) { + // Not a managed property, so use NSObject's implementation of valueForKey: + return RLMCoerceToNil(superValueForKey(object, @selector(valueForKey:), key)); + } + + auto getSuper = [&] { + return row ? RLMDynamicGet(object, lastProp) : RLMCoerceToNil(superValueForKey(object, @selector(valueForKey:), key)); + }; + + // We need to return the same object each time for observing over keypaths + // to work, so we store a cache of them here. We can't just cache them on + // the object as that leads to retain cycles. + if (lastProp.array) { + RLMArray *value = cachedObjects[key]; + if (!value) { + value = getSuper(); + if (!cachedObjects) { + cachedObjects = [NSMutableDictionary new]; + } + cachedObjects[key] = value; + } + return value; + } + + if (lastProp.type == RLMPropertyTypeObject) { + size_t col = row.get_column_index(lastProp.name.UTF8String); + if (row.is_null_link(col)) { + [cachedObjects removeObjectForKey:key]; + return nil; + } + + RLMObjectBase *value = cachedObjects[key]; + if (value && value->_row.get_index() == row.get_link(col)) { + return value; + } + value = getSuper(); + if (!cachedObjects) { + cachedObjects = [NSMutableDictionary new]; + } + cachedObjects[key] = value; + return value; + } + + return getSuper(); +} + +RLMObservationInfo *RLMGetObservationInfo(RLMObservationInfo *info, size_t row, + RLMClassInfo& objectSchema) { + if (info) { + return info; + } + + for (RLMObservationInfo *info : objectSchema.observedObjects) { + if (info->isForRow(row)) { + return info; + } + } + + return nullptr; +} + +void RLMClearTable(RLMClassInfo &objectSchema) { + for (auto info : objectSchema.observedObjects) { + info->willChange(RLMInvalidatedKey); + } + + RLMTrackDeletions(objectSchema.realm, ^{ + Results(objectSchema.realm->_realm, *objectSchema.table()).clear(); + + for (auto info : objectSchema.observedObjects) { + info->prepareForInvalidation(); + } + }); + + for (auto info : reverse(objectSchema.observedObjects)) { + info->didChange(RLMInvalidatedKey); + } + + objectSchema.observedObjects.clear(); +} + +void RLMTrackDeletions(__unsafe_unretained RLMRealm *const realm, dispatch_block_t block) { + std::vector *> observers; + + // Build up an array of observation info arrays which is indexed by table + // index (the object schemata may be in an entirely different order) + for (auto& info : realm->_info) { + if (info.second.observedObjects.empty()) { + continue; + } + size_t ndx = info.second.table()->get_index_in_group(); + if (ndx >= observers.size()) { + observers.resize(std::max(observers.size() * 2, ndx + 1)); + } + observers[ndx] = &info.second.observedObjects; + } + + // No need for change tracking if no objects are observed + if (observers.empty()) { + block(); + return; + } + + struct change { + RLMObservationInfo *info; + __unsafe_unretained NSString *property; + NSMutableIndexSet *indexes; + }; + + std::vector changes; + std::vector invalidated; + + // This callback is called by core with a list of row deletions and + // resulting link nullifications immediately before things are deleted and nullified + realm.group.set_cascade_notification_handler([&](realm::Group::CascadeNotification const& cs) { + for (auto const& link : cs.links) { + size_t table_ndx = link.origin_table->get_index_in_group(); + if (table_ndx >= observers.size() || !observers[table_ndx]) { + // The modified table has no observers + continue; + } + + for (auto observer : *observers[table_ndx]) { + if (!observer->isForRow(link.origin_row_ndx)) { + continue; + } + + NSString *name = observer->columnName(link.origin_col_ndx); + if (observer->getRow().get_table()->get_column_type(link.origin_col_ndx) != type_LinkList) { + changes.push_back({observer, name}); + continue; + } + + auto c = find_if(begin(changes), end(changes), [&](auto const& c) { + return c.info == observer && c.property == name; + }); + if (c == end(changes)) { + changes.push_back({observer, name, [NSMutableIndexSet new]}); + c = prev(end(changes)); + } + + // We know what row index is being removed from the LinkView, + // but what we actually want is the indexes in the LinkView that + // are going away + auto linkview = observer->getRow().get_linklist(link.origin_col_ndx); + size_t start = 0, index; + while ((index = linkview->find(link.old_target_row_ndx, start)) != realm::not_found) { + [c->indexes addIndex:index]; + start = index + 1; + } + } + } + + for (auto const& row : cs.rows) { + if (row.table_ndx >= observers.size() || !observers[row.table_ndx]) { + // The modified table has no observers + continue; + } + + for (auto observer : *observers[row.table_ndx]) { + if (observer->isForRow(row.row_ndx)) { + invalidated.push_back(observer); + break; + } + } + } + + // The relative order of these loops is very important + for (auto info : invalidated) { + info->willChange(RLMInvalidatedKey); + } + for (auto const& change : changes) { + change.info->willChange(change.property, NSKeyValueChangeRemoval, change.indexes); + } + for (auto info : invalidated) { + info->prepareForInvalidation(); + } + }); + + try { + block(); + } + catch (...) { + realm.group.set_cascade_notification_handler(nullptr); + throw; + } + + for (auto const& change : reverse(changes)) { + change.info->didChange(change.property, NSKeyValueChangeRemoval, change.indexes); + } + for (auto info : reverse(invalidated)) { + info->didChange(RLMInvalidatedKey); + } + + realm.group.set_cascade_notification_handler(nullptr); +} + +namespace { +template +void forEach(realm::BindingContext::ObserverState const& state, Func&& func) { + for (size_t i = 0, size = state.changes.size(); i < size; ++i) { + if (state.changes[i].kind != realm::BindingContext::ColumnInfo::Kind::None) { + func(i, state.changes[i], static_cast(state.info)); + } + } +} +} + +std::vector RLMGetObservedRows(RLMSchemaInfo const& schema) { + std::vector observers; + for (auto& table : schema) { + for (auto info : table.second.observedObjects) { + auto const& row = info->getRow(); + if (!row.is_attached()) + continue; + observers.push_back({ + row.get_table()->get_index_in_group(), + row.get_index(), + info}); + } + } + sort(begin(observers), end(observers)); + return observers; +} + +static NSKeyValueChange convert(realm::BindingContext::ColumnInfo::Kind kind) { + switch (kind) { + case realm::BindingContext::ColumnInfo::Kind::None: + case realm::BindingContext::ColumnInfo::Kind::SetAll: + return NSKeyValueChangeSetting; + case realm::BindingContext::ColumnInfo::Kind::Set: + return NSKeyValueChangeReplacement; + case realm::BindingContext::ColumnInfo::Kind::Insert: + return NSKeyValueChangeInsertion; + case realm::BindingContext::ColumnInfo::Kind::Remove: + return NSKeyValueChangeRemoval; + } +} + +static NSIndexSet *convert(realm::IndexSet const& in, NSMutableIndexSet *out) { + if (in.empty()) { + return nil; + } + + [out removeAllIndexes]; + for (auto range : in) { + [out addIndexesInRange:{range.first, range.second - range.first}]; + } + return out; +} + +void RLMWillChange(std::vector const& observed, + std::vector const& invalidated) { + for (auto info : invalidated) { + static_cast(info)->willChange(RLMInvalidatedKey); + } + if (!observed.empty()) { + NSMutableIndexSet *indexes = [NSMutableIndexSet new]; + for (auto const& o : observed) { + forEach(o, [&](size_t, auto const& change, RLMObservationInfo *info) { + info->willChange(info->columnName(change.initial_column_index), + convert(change.kind), convert(change.indices, indexes)); + }); + } + } + for (auto info : invalidated) { + static_cast(info)->prepareForInvalidation(); + } +} + +void RLMDidChange(std::vector const& observed, + std::vector const& invalidated) { + if (!observed.empty()) { + // Loop in reverse order to avoid O(N^2) behavior in Foundation + NSMutableIndexSet *indexes = [NSMutableIndexSet new]; + for (auto const& o : reverse(observed)) { + forEach(o, [&](size_t i, auto const& change, RLMObservationInfo *info) { + info->didChange(info->columnName(i), convert(change.kind), convert(change.indices, indexes)); + }); + } + } + for (auto const& info : reverse(invalidated)) { + static_cast(info)->didChange(RLMInvalidatedKey); + } +} diff --git a/Pods/Realm/Realm/RLMOptionalBase.mm b/Pods/Realm/Realm/RLMOptionalBase.mm new file mode 100644 index 0000000000..ab7e0b2023 --- /dev/null +++ b/Pods/Realm/Realm/RLMOptionalBase.mm @@ -0,0 +1,163 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMOptionalBase.h" + +#import "RLMAccessor.hpp" +#import "RLMObject_Private.hpp" +#import "RLMProperty.h" +#import "RLMUtil.hpp" +#import "object.hpp" + +namespace { +struct OptionalBase { + virtual id get() = 0; + virtual void set(id) = 0; + virtual ~OptionalBase() = default; +}; + +class UnmanagedOptional : public OptionalBase { +public: + id get() override { + return _value; + } + + void set(__unsafe_unretained const id newValue) override { + @autoreleasepool { + RLMObjectBase *object = _parent; + [object willChangeValueForKey:_property]; + _value = newValue; + [object didChangeValueForKey:_property]; + } + } + + void attach(__unsafe_unretained RLMObjectBase *const obj, NSString *property) { + if (!_property) { + _property = property; + _parent = obj; + } + } + +private: + id _value; + NSString *_property; + __weak RLMObjectBase *_parent; + +}; + +class ManagedOptional : public OptionalBase { +public: + ManagedOptional(RLMObjectBase *obj, RLMProperty *prop) + : _realm(obj->_realm) + , _object(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row) + , _propertyName(prop.name.UTF8String) + , _ctx(obj->_realm, *obj->_info) + { + } + + id get() override { + return _object.get_property_value(_ctx, _propertyName); + } + + void set(__unsafe_unretained id const value) override { + _object.set_property_value(_ctx, _propertyName, value ?: NSNull.null, false); + } + +private: + // We have to hold onto a strong reference to the Realm as + // RLMAccessorContext holds a non-retaining one. + __unused RLMRealm *_realm; + realm::Object _object; + std::string _propertyName; + RLMAccessorContext _ctx; +}; +} // anonymous namespace + +@interface RLMOptionalBase () { + std::unique_ptr _impl; +} +@end + +@implementation RLMOptionalBase +- (instancetype)init { + return self; +} + +- (BOOL)isKindOfClass:(Class)aClass { + return [RLMGetOptional(self) isKindOfClass:aClass] || RLMIsKindOfClass(object_getClass(self), aClass); +} + +- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel { + return [RLMGetOptional(self) methodSignatureForSelector:sel]; +} + +- (void)forwardInvocation:(NSInvocation *)invocation { + [invocation invokeWithTarget:RLMGetOptional(self)]; +} + +- (id)forwardingTargetForSelector:(__unused SEL)sel { + return RLMGetOptional(self); +} + +- (BOOL)respondsToSelector:(SEL)aSelector { + return [RLMGetOptional(self) respondsToSelector:aSelector]; +} + +- (void)doesNotRecognizeSelector:(SEL)aSelector { + [RLMGetOptional(self) doesNotRecognizeSelector:aSelector]; +} + +id RLMGetOptional(__unsafe_unretained RLMOptionalBase *const self) { + try { + return self->_impl ? RLMCoerceToNil(self->_impl->get()) : nil; + } + catch (std::exception const& err) { + @throw RLMException(err); + } +} + +void RLMSetOptional(__unsafe_unretained RLMOptionalBase *const self, __unsafe_unretained const id value) { + try { + if (!self->_impl && value) { + self->_impl.reset(new UnmanagedOptional); + } + if (self->_impl) { + self->_impl->set(value); + } + } + catch (std::exception const& err) { + @throw RLMException(err); + } +} + +void RLMInitializeManagedOptional(__unsafe_unretained RLMOptionalBase *const self, + __unsafe_unretained RLMObjectBase *const parent, + __unsafe_unretained RLMProperty *const prop) { + REALM_ASSERT(parent->_realm); + self->_impl.reset(new ManagedOptional(parent, prop)); +} + +void RLMInitializeUnmanagedOptional(__unsafe_unretained RLMOptionalBase *const self, + __unsafe_unretained RLMObjectBase *const parent, + __unsafe_unretained RLMProperty *const prop) { + if (!self->_impl) { + self->_impl.reset(new UnmanagedOptional); + } + static_cast(*self->_impl).attach(parent, prop.name); +} +@end diff --git a/Pods/Realm/Realm/RLMPredicateUtil.mm b/Pods/Realm/Realm/RLMPredicateUtil.mm new file mode 100644 index 0000000000..830a9b2fdc --- /dev/null +++ b/Pods/Realm/Realm/RLMPredicateUtil.mm @@ -0,0 +1,127 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#import "RLMPredicateUtil.hpp" + +#include + +// NSConditionalExpressionType is new in OS X 10.11 and iOS 9.0 +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#define CONDITIONAL_EXPRESSION_DECLARED (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) +#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#define CONDITIONAL_EXPRESSION_DECLARED (__IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) +#else +#define CONDITIONAL_EXPRESSION_DECLARED 0 +#endif + +#if !CONDITIONAL_EXPRESSION_DECLARED + +#define NSConditionalExpressionType 20 + +@interface NSExpression (NewIn1011And90) ++ (NSExpression *)expressionForConditional:(NSPredicate *)predicate trueExpression:(NSExpression *)trueExpression falseExpression:(NSExpression *)falseExpression; +- (NSExpression *)trueExpression; +- (NSExpression *)falseExpression; +@end + +#endif + +namespace { + +struct PredicateExpressionTransformer { + PredicateExpressionTransformer(ExpressionVisitor visitor) : m_visitor(visitor) { } + + NSExpression *visit(NSExpression *expression) const; + NSPredicate *visit(NSPredicate *predicate) const; + + ExpressionVisitor m_visitor; +}; + +NSExpression *PredicateExpressionTransformer::visit(NSExpression *expression) const { + expression = m_visitor(expression); + + switch (expression.expressionType) { + case NSFunctionExpressionType: { + NSMutableArray *arguments = [NSMutableArray array]; + for (NSExpression *argument in expression.arguments) { + [arguments addObject:visit(argument)]; + } + if (expression.operand) { + return [NSExpression expressionForFunction:visit(expression.operand) selectorName:expression.function arguments:arguments]; + } else { + return [NSExpression expressionForFunction:expression.function arguments:arguments]; + } + } + + case NSUnionSetExpressionType: + return [NSExpression expressionForUnionSet:visit(expression.leftExpression) with:visit(expression.rightExpression)]; + case NSIntersectSetExpressionType: + return [NSExpression expressionForIntersectSet:visit(expression.leftExpression) with:visit(expression.rightExpression)]; + case NSMinusSetExpressionType: + return [NSExpression expressionForMinusSet:visit(expression.leftExpression) with:visit(expression.rightExpression)]; + + case NSSubqueryExpressionType: { + NSExpression *collection = expression.collection; + // NSExpression.collection is declared as id, but appears to always hold an NSExpression for subqueries. + REALM_ASSERT([collection isKindOfClass:[NSExpression class]]); + return [NSExpression expressionForSubquery:visit(collection) usingIteratorVariable:expression.variable predicate:visit(expression.predicate)]; + } + + case NSAggregateExpressionType: { + NSMutableArray *subexpressions = [NSMutableArray array]; + for (NSExpression *subexpression in expression.collection) { + [subexpressions addObject:visit(subexpression)]; + } + return [NSExpression expressionForAggregate:subexpressions]; + } + + case NSConditionalExpressionType: +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" + return [NSExpression expressionForConditional:visit(expression.predicate) trueExpression:visit(expression.trueExpression) falseExpression:visit(expression.falseExpression)]; +#pragma clang diagnostic pop + + default: + // The remaining expression types do not contain nested expressions or predicates. + return expression; + } +} + +NSPredicate *PredicateExpressionTransformer::visit(NSPredicate *predicate) const { + if ([predicate isKindOfClass:[NSCompoundPredicate class]]) { + NSCompoundPredicate *compoundPredicate = (NSCompoundPredicate *)predicate; + NSMutableArray *subpredicates = [NSMutableArray array]; + for (NSPredicate *subpredicate in compoundPredicate.subpredicates) { + [subpredicates addObject:visit(subpredicate)]; + } + return [[NSCompoundPredicate alloc] initWithType:compoundPredicate.compoundPredicateType subpredicates:subpredicates]; + } + if ([predicate isKindOfClass:[NSComparisonPredicate class]]) { + NSComparisonPredicate *comparisonPredicate = (NSComparisonPredicate *)predicate; + NSExpression *leftExpression = visit(comparisonPredicate.leftExpression); + NSExpression *rightExpression = visit(comparisonPredicate.rightExpression); + return [NSComparisonPredicate predicateWithLeftExpression:leftExpression rightExpression:rightExpression modifier:comparisonPredicate.comparisonPredicateModifier type:comparisonPredicate.predicateOperatorType options:comparisonPredicate.options]; + } + return predicate; +} + +} // anonymous namespace + +NSPredicate *transformPredicate(NSPredicate *predicate, ExpressionVisitor visitor) { + PredicateExpressionTransformer transformer(visitor); + return transformer.visit(predicate); +} diff --git a/Pods/Realm/Realm/RLMProperty.mm b/Pods/Realm/Realm/RLMProperty.mm new file mode 100644 index 0000000000..490fadced4 --- /dev/null +++ b/Pods/Realm/Realm/RLMProperty.mm @@ -0,0 +1,653 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMProperty_Private.hpp" + +#import "RLMArray_Private.hpp" +#import "RLMListBase.h" +#import "RLMObject.h" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObject_Private.h" +#import "RLMSchema_Private.h" +#import "RLMSwiftSupport.h" +#import "RLMUtil.hpp" + +#import "property.hpp" + +static_assert((int)RLMPropertyTypeInt == (int)realm::PropertyType::Int, ""); +static_assert((int)RLMPropertyTypeBool == (int)realm::PropertyType::Bool, ""); +static_assert((int)RLMPropertyTypeFloat == (int)realm::PropertyType::Float, ""); +static_assert((int)RLMPropertyTypeDouble == (int)realm::PropertyType::Double, ""); +static_assert((int)RLMPropertyTypeString == (int)realm::PropertyType::String, ""); +static_assert((int)RLMPropertyTypeData == (int)realm::PropertyType::Data, ""); +static_assert((int)RLMPropertyTypeDate == (int)realm::PropertyType::Date, ""); +static_assert((int)RLMPropertyTypeObject == (int)realm::PropertyType::Object, ""); + +BOOL RLMPropertyTypeIsComputed(RLMPropertyType propertyType) { + return propertyType == RLMPropertyTypeLinkingObjects; +} + +// Swift obeys the ARC naming conventions for method families (except for init) +// but the end result doesn't really work (using KVC on a method returning a +// retained value results in a leak, but not returning a retained value results +// in crashes). Objective-C makes properties with naming fitting the method +// families a compile error, so we just disallow them in Swift as well. +// http://clang.llvm.org/docs/AutomaticReferenceCounting.html#arc-method-families +void RLMValidateSwiftPropertyName(NSString *name) { + // To belong to a method family, the property name must begin with the family + // name followed by a non-lowercase letter (or nothing), with an optional + // leading underscore + const char *str = name.UTF8String; + if (str[0] == '_') + ++str; + auto nameSize = strlen(str); + + // Note that "init" is deliberately not in this list because Swift does not + // infer family membership for it. + for (auto family : {"alloc", "new", "copy", "mutableCopy"}) { + auto familySize = strlen(family); + if (nameSize < familySize || !std::equal(str, str + familySize, family)) { + continue; + } + if (familySize == nameSize || !islower(str[familySize])) { + @throw RLMException(@"Property names beginning with '%s' are not " + "supported. Swift follows ARC's ownership " + "rules for methods based on their name, which " + "results in memory leaks when accessing " + "properties which return retained values via KVC.", + family); + } + return; + } +} + +static bool rawTypeShouldBeTreatedAsComputedProperty(NSString *rawType) { + return [rawType isEqualToString:@"@\"RLMLinkingObjects\""] || [rawType hasPrefix:@"@\"RLMLinkingObjects<"]; +} + +@implementation RLMProperty + ++ (instancetype)propertyForObjectStoreProperty:(const realm::Property &)prop { + auto ret = [[RLMProperty alloc] initWithName:@(prop.name.c_str()) + type:static_cast(prop.type & ~realm::PropertyType::Flags) + objectClassName:prop.object_type.length() ? @(prop.object_type.c_str()) : nil + linkOriginPropertyName:prop.link_origin_property_name.length() ? @(prop.link_origin_property_name.c_str()) : nil + indexed:prop.is_indexed + optional:is_nullable(prop.type)]; + if (is_array(prop.type)) { + ret->_array = true; + } + return ret; +} + +- (instancetype)initWithName:(NSString *)name + type:(RLMPropertyType)type + objectClassName:(NSString *)objectClassName + linkOriginPropertyName:(NSString *)linkOriginPropertyName + indexed:(BOOL)indexed + optional:(BOOL)optional { + self = [super init]; + if (self) { + _name = name; + _type = type; + _objectClassName = objectClassName; + _linkOriginPropertyName = linkOriginPropertyName; + _indexed = indexed; + _optional = optional; + [self updateAccessors]; + } + + return self; +} + +- (void)setName:(NSString *)name { + _name = name; + [self updateAccessors]; +} + +- (void)updateAccessors { + // populate getter/setter names if generic + if (!_getterName) { + _getterName = _name; + } + if (!_setterName) { + // Objective-C setters only capitalize the first letter of the property name if it falls between 'a' and 'z' + int asciiCode = [_name characterAtIndex:0]; + BOOL shouldUppercase = asciiCode >= 'a' && asciiCode <= 'z'; + NSString *firstChar = [_name substringToIndex:1]; + firstChar = shouldUppercase ? firstChar.uppercaseString : firstChar; + _setterName = [NSString stringWithFormat:@"set%@%@:", firstChar, [_name substringFromIndex:1]]; + } + + _getterSel = NSSelectorFromString(_getterName); + _setterSel = NSSelectorFromString(_setterName); +} + +static realm::util::Optional typeFromProtocolString(const char *type) { + if (strncmp(type, "RLM", 3)) { + return realm::none; + } + type += 3; + if (strcmp(type, "Int>\"") == 0) { + return RLMPropertyTypeInt; + } + if (strcmp(type, "Float>\"") == 0) { + return RLMPropertyTypeFloat; + } + if (strcmp(type, "Double>\"") == 0) { + return RLMPropertyTypeDouble; + } + if (strcmp(type, "Bool>\"") == 0) { + return RLMPropertyTypeBool; + } + if (strcmp(type, "String>\"") == 0) { + return RLMPropertyTypeString; + } + if (strcmp(type, "Data>\"") == 0) { + return RLMPropertyTypeData; + } + if (strcmp(type, "Date>\"") == 0) { + return RLMPropertyTypeDate; + } + return realm::none; +} + +// determine RLMPropertyType from objc code - returns true if valid type was found/set +- (BOOL)setTypeFromRawType:(NSString *)rawType { + const char *code = rawType.UTF8String; + switch (*code) { + case 's': // short + case 'i': // int + case 'l': // long + case 'q': // long long + _type = RLMPropertyTypeInt; + return YES; + case 'f': + _type = RLMPropertyTypeFloat; + return YES; + case 'd': + _type = RLMPropertyTypeDouble; + return YES; + case 'c': // BOOL is stored as char - since rlm has no char type this is ok + case 'B': + _type = RLMPropertyTypeBool; + return YES; + case '@': + break; + default: + return NO; + } + + _optional = true; + static const char arrayPrefix[] = "@\"RLMArray<"; + static const int arrayPrefixLen = sizeof(arrayPrefix) - 1; + + static const char numberPrefix[] = "@\"NSNumber<"; + static const int numberPrefixLen = sizeof(numberPrefix) - 1; + + static const char linkingObjectsPrefix[] = "@\"RLMLinkingObjects"; + static const int linkingObjectsPrefixLen = sizeof(linkingObjectsPrefix) - 1; + + if (strcmp(code, "@\"NSString\"") == 0) { + _type = RLMPropertyTypeString; + } + else if (strcmp(code, "@\"NSDate\"") == 0) { + _type = RLMPropertyTypeDate; + } + else if (strcmp(code, "@\"NSData\"") == 0) { + _type = RLMPropertyTypeData; + } + else if (strncmp(code, arrayPrefix, arrayPrefixLen) == 0) { + _array = true; + if (auto type = typeFromProtocolString(code + arrayPrefixLen)) { + _type = *type; + return YES; + } + + // get object class from type string - @"RLMArray" + _objectClassName = [[NSString alloc] initWithBytes:code + arrayPrefixLen + length:strlen(code + arrayPrefixLen) - 2 // drop trailing >" + encoding:NSUTF8StringEncoding]; + + if ([RLMSchema classForString:_objectClassName]) { + _optional = false; + _type = RLMPropertyTypeObject; + return YES; + } + @throw RLMException(@"Property '%@' is of type 'RLMArray<%@>' which is not a supported RLMArray object type. " + @"RLMArrays can only contain instances of RLMObject subclasses. " + @"See https://realm.io/docs/objc/latest/#to-many for more information.", _name, _objectClassName); + } + else if (strncmp(code, numberPrefix, numberPrefixLen) == 0) { + auto type = typeFromProtocolString(code + numberPrefixLen); + if (type && (*type == RLMPropertyTypeInt || *type == RLMPropertyTypeFloat || *type == RLMPropertyTypeDouble || *type == RLMPropertyTypeBool)) { + _type = *type; + return YES; + } + @throw RLMException(@"Property '%@' is of type %s which is not a supported NSNumber object type. " + @"NSNumbers can only be RLMInt, RLMFloat, RLMDouble, and RLMBool at the moment. " + @"See https://realm.io/docs/objc/latest for more information.", _name, code + 1); + } + else if (strncmp(code, linkingObjectsPrefix, linkingObjectsPrefixLen) == 0 && + (code[linkingObjectsPrefixLen] == '"' || code[linkingObjectsPrefixLen] == '<')) { + _type = RLMPropertyTypeLinkingObjects; + _optional = false; + _array = true; + + if (!_objectClassName || !_linkOriginPropertyName) { + @throw RLMException(@"Property '%@' is of type RLMLinkingObjects but +linkingObjectsProperties did not specify the class " + "or property that is the origin of the link.", _name); + } + + // If the property was declared with a protocol indicating the contained type, validate that it matches + // the class from the dictionary returned by +linkingObjectsProperties. + if (code[linkingObjectsPrefixLen] == '<') { + NSString *classNameFromProtocol = [[NSString alloc] initWithBytes:code + linkingObjectsPrefixLen + 1 + length:strlen(code + linkingObjectsPrefixLen) - 3 // drop trailing >" + encoding:NSUTF8StringEncoding]; + if (![_objectClassName isEqualToString:classNameFromProtocol]) { + @throw RLMException(@"Property '%@' was declared with type RLMLinkingObjects<%@>, but a conflicting " + "class name of '%@' was returned by +linkingObjectsProperties.", _name, + classNameFromProtocol, _objectClassName); + } + } + } + else if (strcmp(code, "@\"NSNumber\"") == 0) { + @throw RLMException(@"Property '%@' requires a protocol defining the contained type - example: NSNumber.", _name); + } + else if (strcmp(code, "@\"RLMArray\"") == 0) { + @throw RLMException(@"Property '%@' requires a protocol defining the contained type - example: RLMArray.", _name); + } + else { + NSString *className; + Class cls = nil; + if (code[1] == '\0') { + className = @"id"; + } + else { + // for objects strip the quotes and @ + className = [rawType substringWithRange:NSMakeRange(2, rawType.length-3)]; + cls = [RLMSchema classForString:className]; + } + + if (!cls) { + @throw RLMException(@"Property '%@' is declared as '%@', which is not a supported RLMObject property type. " + @"All properties must be primitives, NSString, NSDate, NSData, NSNumber, RLMArray, RLMLinkingObjects, or subclasses of RLMObject. " + @"See https://realm.io/docs/objc/latest/api/Classes/RLMObject.html for more information.", _name, className); + } + + _type = RLMPropertyTypeObject; + _optional = true; + _objectClassName = [cls className] ?: className; + } + return YES; +} + +- (void)parseObjcProperty:(objc_property_t)property + readOnly:(bool *)readOnly + computed:(bool *)computed + rawType:(NSString **)rawType { + unsigned int count; + objc_property_attribute_t *attrs = property_copyAttributeList(property, &count); + + *computed = true; + for (size_t i = 0; i < count; ++i) { + switch (*attrs[i].name) { + case 'T': + *rawType = @(attrs[i].value); + break; + case 'R': + *readOnly = true; + break; + case 'N': + // nonatomic + break; + case 'D': + // dynamic + break; + case 'G': + _getterName = @(attrs[i].value); + break; + case 'S': + _setterName = @(attrs[i].value); + break; + case 'V': // backing ivar name + *computed = false; + break; + default: + break; + } + } + free(attrs); +} + +- (instancetype)initSwiftPropertyWithName:(NSString *)name + indexed:(BOOL)indexed + linkPropertyDescriptor:(RLMPropertyDescriptor *)linkPropertyDescriptor + property:(objc_property_t)property + instance:(RLMObject *)obj { + self = [super init]; + if (!self) { + return nil; + } + + RLMValidateSwiftPropertyName(name); + + _name = name; + _indexed = indexed; + + if (linkPropertyDescriptor) { + _objectClassName = [linkPropertyDescriptor.objectClass className]; + _linkOriginPropertyName = linkPropertyDescriptor.propertyName; + } + + NSString *rawType; + bool readOnly = false; + bool isComputed = false; + [self parseObjcProperty:property readOnly:&readOnly computed:&isComputed rawType:&rawType]; + if (!readOnly && isComputed) { + // Check for lazy property. + NSString *backingPropertyName = [NSString stringWithFormat:@"%@.storage", name]; + if (class_getInstanceVariable([obj class], backingPropertyName.UTF8String)) { + isComputed = false; + } + } + + if (readOnly || isComputed) { + return nil; + } + + id propertyValue = [obj valueForKey:_name]; + + // FIXME: temporarily workaround added since Objective-C generics used in Swift show up as `@` + // * broken starting in Swift 3.0 Xcode 8 b1 + // * tested to still be broken in Swift 3.0 Xcode 8 b6 + // * if the Realm Objective-C Swift tests pass with this removed, it's been fixed + // * once it has been fixed, remove this entire conditional block (contents included) entirely + // * Bug Report: SR-2031 https://bugs.swift.org/browse/SR-2031 + if ([rawType isEqualToString:@"@"]) { + if (propertyValue) { + rawType = [NSString stringWithFormat:@"@\"%@\"", [propertyValue class]]; + } else if (linkPropertyDescriptor) { + // we're going to naively assume that the user used the correct type since we can't check it + rawType = @"@\"RLMLinkingObjects\""; + } + } + + // convert array types to objc variant + if ([rawType isEqualToString:@"@\"RLMArray\""]) { + RLMArray *value = propertyValue; + _type = value.type; + _optional = value.optional; + _array = true; + _objectClassName = value.objectClassName; + if (_type == RLMPropertyTypeObject && ![RLMSchema classForString:_objectClassName]) { + @throw RLMException(@"Property '%@' is of type 'RLMArray<%@>' which is not a supported RLMArray object type. " + @"RLMArrays can only contain instances of RLMObject subclasses. " + @"See https://realm.io/docs/objc/latest/#to-many for more information.", _name, _objectClassName); + } + } + else if ([rawType isEqualToString:@"@\"NSNumber\""]) { + const char *numberType = [propertyValue objCType]; + if (!numberType) { + @throw RLMException(@"Can't persist NSNumber without default value: use a Swift-native number type or provide a default value."); + } + _optional = true; + switch (*numberType) { + case 'i': case 'l': case 'q': + _type = RLMPropertyTypeInt; + break; + case 'f': + _type = RLMPropertyTypeFloat; + break; + case 'd': + _type = RLMPropertyTypeDouble; + break; + case 'B': case 'c': + _type = RLMPropertyTypeBool; + break; + default: + @throw RLMException(@"Can't persist NSNumber of type '%s': only integers, floats, doubles, and bools are currently supported.", numberType); + } + } + else if (![self setTypeFromRawType:rawType]) { + @throw RLMException(@"Can't persist property '%@' with incompatible type. " + "Add to Object.ignoredProperties() class method to ignore.", + self.name); + } + + if ([rawType isEqualToString:@"c"]) { + // Check if it's a BOOL or Int8 by trying to set it to 2 and seeing if + // it actually sets it to 1. + [obj setValue:@2 forKey:name]; + NSNumber *value = [obj valueForKey:name]; + _type = value.intValue == 2 ? RLMPropertyTypeInt : RLMPropertyTypeBool; + } + + // update getter/setter names + [self updateAccessors]; + + return self; +} + +- (instancetype)initWithName:(NSString *)name + indexed:(BOOL)indexed + linkPropertyDescriptor:(RLMPropertyDescriptor *)linkPropertyDescriptor + property:(objc_property_t)property +{ + self = [super init]; + if (!self) { + return nil; + } + + _name = name; + _indexed = indexed; + + if (linkPropertyDescriptor) { + _objectClassName = [linkPropertyDescriptor.objectClass className]; + _linkOriginPropertyName = linkPropertyDescriptor.propertyName; + } + + NSString *rawType; + bool isReadOnly = false; + bool isComputed = false; + [self parseObjcProperty:property readOnly:&isReadOnly computed:&isComputed rawType:&rawType]; + bool shouldBeTreatedAsComputedProperty = rawTypeShouldBeTreatedAsComputedProperty(rawType); + if ((isReadOnly || isComputed) && !shouldBeTreatedAsComputedProperty) { + return nil; + } + + if (![self setTypeFromRawType:rawType]) { + @throw RLMException(@"Can't persist property '%@' with incompatible type. " + "Add to ignoredPropertyNames: method to ignore.", self.name); + } + + if (!isReadOnly && shouldBeTreatedAsComputedProperty) { + @throw RLMException(@"Property '%@' must be declared as readonly as %@ properties cannot be written to.", + self.name, RLMTypeToString(_type)); + } + + // update getter/setter names + [self updateAccessors]; + + return self; +} + +- (instancetype)initSwiftListPropertyWithName:(NSString *)name + instance:(id)object { + self = [super init]; + if (!self) { + return nil; + } + _name = name; + _array = true; + _swiftIvar = class_getInstanceVariable([object class], name.UTF8String); + + RLMArray *array = [object_getIvar(object, _swiftIvar) _rlmArray]; + _type = array.type; + _optional = array.optional; + _objectClassName = array.objectClassName; + + // no obj-c property for generic lists, and thus no getter/setter names + + return self; +} + +- (instancetype)initSwiftOptionalPropertyWithName:(NSString *)name + indexed:(BOOL)indexed + ivar:(Ivar)ivar + propertyType:(RLMPropertyType)propertyType { + self = [super init]; + if (!self) { + return nil; + } + + _name = name; + _type = propertyType; + _indexed = indexed; + _swiftIvar = ivar; + _optional = true; + + // no obj-c property for generic optionals, and thus no getter/setter names + + return self; +} + +- (instancetype)initSwiftLinkingObjectsPropertyWithName:(NSString *)name + ivar:(Ivar)ivar + objectClassName:(NSString *)objectClassName + linkOriginPropertyName:(NSString *)linkOriginPropertyName { + self = [super init]; + if (!self) { + return nil; + } + + _name = name; + _type = RLMPropertyTypeLinkingObjects; + _array = true; + _objectClassName = objectClassName; + _linkOriginPropertyName = linkOriginPropertyName; + _swiftIvar = ivar; + + // no obj-c property for generic linking objects properties, and thus no getter/setter names + + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + RLMProperty *prop = [[RLMProperty allocWithZone:zone] init]; + prop->_name = _name; + prop->_columnName = _columnName; + prop->_type = _type; + prop->_objectClassName = _objectClassName; + prop->_array = _array; + prop->_indexed = _indexed; + prop->_getterName = _getterName; + prop->_setterName = _setterName; + prop->_getterSel = _getterSel; + prop->_setterSel = _setterSel; + prop->_isPrimary = _isPrimary; + prop->_swiftIvar = _swiftIvar; + prop->_optional = _optional; + prop->_linkOriginPropertyName = _linkOriginPropertyName; + + return prop; +} + +- (RLMProperty *)copyWithNewName:(NSString *)name { + RLMProperty *prop = [self copy]; + prop.name = name; + return prop; +} + +- (BOOL)isEqual:(id)object { + if (![object isKindOfClass:[RLMProperty class]]) { + return NO; + } + + return [self isEqualToProperty:object]; +} + +- (BOOL)isEqualToProperty:(RLMProperty *)property { + return _type == property->_type + && _indexed == property->_indexed + && _isPrimary == property->_isPrimary + && _optional == property->_optional + && [_name isEqualToString:property->_name] + && (_objectClassName == property->_objectClassName || [_objectClassName isEqualToString:property->_objectClassName]) + && (_linkOriginPropertyName == property->_linkOriginPropertyName || + [_linkOriginPropertyName isEqualToString:property->_linkOriginPropertyName]); +} + +- (NSString *)description { + return [NSString stringWithFormat: + @"%@ {\n" + "\ttype = %@;\n" + "\tobjectClassName = %@;\n" + "\tlinkOriginPropertyName = %@;\n" + "\tindexed = %@;\n" + "\tisPrimary = %@;\n" + "\tarray = %@;\n" + "\toptional = %@;\n" + "}", + self.name, RLMTypeToString(self.type), self.objectClassName, + self.linkOriginPropertyName, + self.indexed ? @"YES" : @"NO", + self.isPrimary ? @"YES" : @"NO", + self.array ? @"YES" : @"NO", + self.optional ? @"YES" : @"NO"]; +} + +- (NSString *)columnName { + return _columnName ?: _name; +} + +- (realm::Property)objectStoreCopy:(RLMSchema *)schema { + realm::Property p; + p.name = self.columnName.UTF8String; + if (_objectClassName) { + RLMObjectSchema *targetSchema = schema[_objectClassName]; + p.object_type = (targetSchema.objectName ?: _objectClassName).UTF8String; + if (_linkOriginPropertyName) { + p.link_origin_property_name = (targetSchema[_linkOriginPropertyName].columnName ?: _linkOriginPropertyName).UTF8String; + } + } + p.is_indexed = static_cast(_indexed); + p.type = static_cast(_type); + if (_array) { + p.type |= realm::PropertyType::Array; + } + if (_optional) { + p.type |= realm::PropertyType::Nullable; + } + return p; +} + +@end + +@implementation RLMPropertyDescriptor + ++ (instancetype)descriptorWithClass:(Class)objectClass propertyName:(NSString *)propertyName +{ + RLMPropertyDescriptor *descriptor = [[RLMPropertyDescriptor alloc] init]; + descriptor->_objectClass = objectClass; + descriptor->_propertyName = propertyName; + return descriptor; +} + +@end diff --git a/Pods/Realm/Realm/RLMQueryUtil.mm b/Pods/Realm/Realm/RLMQueryUtil.mm new file mode 100644 index 0000000000..11e3884e68 --- /dev/null +++ b/Pods/Realm/Realm/RLMQueryUtil.mm @@ -0,0 +1,1490 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMQueryUtil.hpp" + +#import "RLMArray.h" +#import "RLMObjectSchema_Private.h" +#import "RLMObject_Private.hpp" +#import "RLMPredicateUtil.hpp" +#import "RLMProperty_Private.h" +#import "RLMSchema.h" +#import "RLMUtil.hpp" + +#import "object_store.hpp" +#import "results.hpp" + +#include +#include +#include +#include + +using namespace realm; + +NSString * const RLMPropertiesComparisonTypeMismatchException = @"RLMPropertiesComparisonTypeMismatchException"; +NSString * const RLMUnsupportedTypesFoundInPropertyComparisonException = @"RLMUnsupportedTypesFoundInPropertyComparisonException"; + +NSString * const RLMPropertiesComparisonTypeMismatchReason = @"Property type mismatch between %@ and %@"; +NSString * const RLMUnsupportedTypesFoundInPropertyComparisonReason = @"Comparison between %@ and %@"; + +// small helper to create the many exceptions thrown when parsing predicates +static NSException *RLMPredicateException(NSString *name, NSString *format, ...) { + va_list args; + va_start(args, format); + NSString *reason = [[NSString alloc] initWithFormat:format arguments:args]; + va_end(args); + + return [NSException exceptionWithName:name reason:reason userInfo:nil]; +} + +// check a precondition and throw an exception if it is not met +// this should be used iff the condition being false indicates a bug in the caller +// of the function checking its preconditions +static void RLMPrecondition(bool condition, NSString *name, NSString *format, ...) { + if (__builtin_expect(condition, 1)) { + return; + } + + va_list args; + va_start(args, format); + NSString *reason = [[NSString alloc] initWithFormat:format arguments:args]; + va_end(args); + + @throw [NSException exceptionWithName:name reason:reason userInfo:nil]; +} + +// return the property for a validated column name +RLMProperty *RLMValidatedProperty(RLMObjectSchema *desc, NSString *columnName) { + RLMProperty *prop = desc[columnName]; + RLMPrecondition(prop, @"Invalid property name", + @"Property '%@' not found in object of type '%@'", columnName, desc.className); + return prop; +} + +namespace { +BOOL RLMPropertyTypeIsNumeric(RLMPropertyType propertyType) { + switch (propertyType) { + case RLMPropertyTypeInt: + case RLMPropertyTypeFloat: + case RLMPropertyTypeDouble: + return YES; + default: + return NO; + } +} + +// Equal and ContainsSubstring are used by QueryBuilder::add_string_constraint as the comparator +// for performing diacritic-insensitive comparisons. + +bool equal(CFStringCompareFlags options, StringData v1, StringData v2) +{ + if (v1.is_null() || v2.is_null()) { + return v1.is_null() == v2.is_null(); + } + + auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(), + kCFStringEncodingUTF8, false, kCFAllocatorNull)); + auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(), + kCFStringEncodingUTF8, false, kCFAllocatorNull)); + + return CFStringCompare(s1.get(), s2.get(), options) == kCFCompareEqualTo; +} + +template +struct Equal { + using CaseSensitive = Equal; + using CaseInsensitive = Equal; + + bool operator()(StringData v1, StringData v2, bool v1_null, bool v2_null) const + { + REALM_ASSERT_DEBUG(v1_null == v1.is_null()); + REALM_ASSERT_DEBUG(v2_null == v2.is_null()); + + return equal(options, v1, v2); + } + + // FIXME: Consider the options. + static const char* description() { return "equal"; } +}; + +bool contains_substring(CFStringCompareFlags options, StringData v1, StringData v2) +{ + if (v2.is_null()) { + // Everything contains NULL + return true; + } + + if (v1.is_null()) { + // NULL contains nothing (except NULL, handled above) + return false; + } + + if (v2.size() == 0) { + // Everything (except NULL, handled above) contains the empty string + return true; + } + + auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(), + kCFStringEncodingUTF8, false, kCFAllocatorNull)); + auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(), + kCFStringEncodingUTF8, false, kCFAllocatorNull)); + + return CFStringFind(s1.get(), s2.get(), options).location != kCFNotFound; +} + +template +struct ContainsSubstring { + using CaseSensitive = ContainsSubstring; + using CaseInsensitive = ContainsSubstring; + + bool operator()(StringData v1, StringData v2, bool v1_null, bool v2_null) const + { + REALM_ASSERT_DEBUG(v1_null == v1.is_null()); + REALM_ASSERT_DEBUG(v2_null == v2.is_null()); + + return contains_substring(options, v1, v2); + } + + // FIXME: Consider the options. + static const char* description() { return "contains"; } +}; + + +NSString *operatorName(NSPredicateOperatorType operatorType) +{ + switch (operatorType) { + case NSLessThanPredicateOperatorType: + return @"<"; + case NSLessThanOrEqualToPredicateOperatorType: + return @"<="; + case NSGreaterThanPredicateOperatorType: + return @">"; + case NSGreaterThanOrEqualToPredicateOperatorType: + return @">="; + case NSEqualToPredicateOperatorType: + return @"=="; + case NSNotEqualToPredicateOperatorType: + return @"!="; + case NSMatchesPredicateOperatorType: + return @"MATCHES"; + case NSLikePredicateOperatorType: + return @"LIKE"; + case NSBeginsWithPredicateOperatorType: + return @"BEGINSWITH"; + case NSEndsWithPredicateOperatorType: + return @"ENDSWITH"; + case NSInPredicateOperatorType: + return @"IN"; + case NSContainsPredicateOperatorType: + return @"CONTAINS"; + case NSBetweenPredicateOperatorType: + return @"BETWEEN"; + case NSCustomSelectorPredicateOperatorType: + return @"custom selector"; + } + + return [NSString stringWithFormat:@"unknown operator %lu", (unsigned long)operatorType]; +} + +Table& get_table(Group& group, RLMObjectSchema *objectSchema) +{ + return *ObjectStore::table_for_object_type(group, objectSchema.objectName.UTF8String); +} + +// A reference to a column within a query. Can be resolved to a Columns for use in query expressions. +class ColumnReference { +public: + ColumnReference(Query& query, Group& group, RLMSchema *schema, RLMProperty* property, const std::vector& links = {}) + : m_links(links), m_property(property), m_schema(schema), m_group(&group), m_query(&query), m_table(query.get_table().get()) + { + auto& table = walk_link_chain([](Table&, size_t, RLMPropertyType) { }); + m_index = table.get_column_index(m_property.columnName.UTF8String); + } + + template + auto resolve(SubQuery&&... subquery) const + { + static_assert(sizeof...(SubQuery) < 2, "resolve() takes at most one subquery"); + set_link_chain_on_table(); + if (type() != RLMPropertyTypeLinkingObjects) { + return m_table->template column(index(), std::forward(subquery)...); + } + else { + return resolve_backlink(std::forward(subquery)...); + } + } + + RLMProperty *property() const { return m_property; } + size_t index() const { return m_index; } + RLMPropertyType type() const { return property().type; } + Group& group() const { return *m_group; } + + RLMObjectSchema *link_target_object_schema() const + { + switch (type()) { + case RLMPropertyTypeObject: + case RLMPropertyTypeLinkingObjects: + return m_schema[property().objectClassName]; + default: + REALM_UNREACHABLE(); + } + } + + bool has_links() const { return m_links.size(); } + + bool has_any_to_many_links() const { + return std::any_of(begin(m_links), end(m_links), + [](RLMProperty *property) { return property.array; }); + } + + ColumnReference last_link_column() const { + REALM_ASSERT(!m_links.empty()); + return {*m_query, *m_group, m_schema, m_links.back(), {m_links.begin(), m_links.end() - 1}}; + } + + ColumnReference column_ignoring_links(Query& query) const { + return {query, *m_group, m_schema, m_property}; + } + +private: + template + auto resolve_backlink(SubQuery&&... subquery) const + { + // We actually just want `if constexpr (std::is_same::value) { ... }`, + // so fake it by tag-dispatching on the conditional + return do_resolve_backlink(std::is_same(), std::forward(subquery)...); + } + + template + auto do_resolve_backlink(std::true_type, SubQuery&&... subquery) const + { + return with_link_origin(m_property, [&](Table& table, size_t col) { + return m_table->template column(table, col, std::forward(subquery)...); + }); + } + + template + Columns do_resolve_backlink(std::false_type, SubQuery&&...) const + { + // This can't actually happen as we only call resolve_backlink() if + // it's RLMPropertyTypeLinkingObjects + __builtin_unreachable(); + } + + template + Table& walk_link_chain(Func&& func) const + { + auto table = m_query->get_table().get(); + for (const auto& link : m_links) { + if (link.type != RLMPropertyTypeLinkingObjects) { + auto index = table->get_column_index(link.columnName.UTF8String); + func(*table, index, link.type); + table = table->get_link_target(index).get(); + } + else { + with_link_origin(link, [&](Table& link_origin_table, size_t link_origin_column) { + func(link_origin_table, link_origin_column, link.type); + table = &link_origin_table; + }); + } + } + return *table; + } + + template + auto with_link_origin(RLMProperty *prop, Func&& func) const + { + RLMObjectSchema *link_origin_schema = m_schema[prop.objectClassName]; + Table& link_origin_table = get_table(*m_group, link_origin_schema); + NSString *column_name = link_origin_schema[prop.linkOriginPropertyName].columnName; + size_t link_origin_column = link_origin_table.get_column_index(column_name.UTF8String); + return func(link_origin_table, link_origin_column); + } + + void set_link_chain_on_table() const + { + walk_link_chain([&](Table& current_table, size_t column, RLMPropertyType type) { + if (type == RLMPropertyTypeLinkingObjects) { + m_table->backlink(current_table, column); + } + else { + m_table->link(column); + } + }); + } + + std::vector m_links; + RLMProperty *m_property; + RLMSchema *m_schema; + Group *m_group; + Query *m_query; + Table *m_table; + size_t m_index; +}; + +class CollectionOperation { +public: + enum Type { + Count, + Minimum, + Maximum, + Sum, + Average, + }; + + CollectionOperation(Type type, ColumnReference link_column, util::Optional column) + : m_type(type) + , m_link_column(std::move(link_column)) + , m_column(std::move(column)) + { + RLMPrecondition(m_link_column.property().array, + @"Invalid predicate", @"Collection operation can only be applied to a property of type RLMArray."); + + switch (m_type) { + case Count: + RLMPrecondition(!m_column, @"Invalid predicate", @"Result of @count does not have any properties."); + break; + case Minimum: + case Maximum: + case Sum: + case Average: + RLMPrecondition(m_column && RLMPropertyTypeIsNumeric(m_column->type()), @"Invalid predicate", + @"%@ can only be applied to a numeric property.", name_for_type(m_type)); + break; + } + } + + CollectionOperation(NSString *operationName, ColumnReference link_column, util::Optional column = util::none) + : CollectionOperation(type_for_name(operationName), std::move(link_column), std::move(column)) + { + } + + Type type() const { return m_type; } + const ColumnReference& link_column() const { return m_link_column; } + const ColumnReference& column() const { return *m_column; } + + void validate_comparison(id value) const { + switch (m_type) { + case Count: + case Average: + RLMPrecondition([value isKindOfClass:[NSNumber class]], @"Invalid operand", + @"%@ can only be compared with a numeric value.", name_for_type(m_type)); + break; + case Minimum: + case Maximum: + case Sum: + RLMPrecondition(RLMIsObjectValidForProperty(value, m_column->property()), @"Invalid operand", + @"%@ on a property of type %@ cannot be compared with '%@'", + name_for_type(m_type), RLMTypeToString(m_column->type()), value); + break; + } + } + + void validate_comparison(const ColumnReference& column) const { + switch (m_type) { + case Count: + RLMPrecondition(RLMPropertyTypeIsNumeric(column.type()), @"Invalid operand", + @"%@ can only be compared with a numeric value.", name_for_type(m_type)); + break; + case Average: + case Minimum: + case Maximum: + case Sum: + RLMPrecondition(RLMPropertyTypeIsNumeric(column.type()), @"Invalid operand", + @"%@ on a property of type %@ cannot be compared with property of type '%@'", + name_for_type(m_type), RLMTypeToString(m_column->type()), RLMTypeToString(column.type())); + break; + } + } + +private: + static Type type_for_name(NSString *name) { + if ([name isEqualToString:@"@count"]) { + return Count; + } + if ([name isEqualToString:@"@min"]) { + return Minimum; + } + if ([name isEqualToString:@"@max"]) { + return Maximum; + } + if ([name isEqualToString:@"@sum"]) { + return Sum; + } + if ([name isEqualToString:@"@avg"]) { + return Average; + } + @throw RLMPredicateException(@"Invalid predicate", @"Unsupported collection operation '%@'", name); + } + + static NSString *name_for_type(Type type) { + switch (type) { + case Count: return @"@count"; + case Minimum: return @"@min"; + case Maximum: return @"@max"; + case Sum: return @"@sum"; + case Average: return @"@avg"; + } + } + + Type m_type; + ColumnReference m_link_column; + util::Optional m_column; +}; + +class QueryBuilder { +public: + QueryBuilder(Query& query, Group& group, RLMSchema *schema) + : m_query(query), m_group(group), m_schema(schema) { } + + void apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema); + + + void apply_collection_operator_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred); + void apply_value_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred); + void apply_column_expression(RLMObjectSchema *desc, NSString *leftKeyPath, NSString *rightKeyPath, NSComparisonPredicate *predicate); + void apply_subquery_count_expression(RLMObjectSchema *objectSchema, NSExpression *subqueryExpression, + NSPredicateOperatorType operatorType, NSExpression *right); + void apply_function_subquery_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression, + NSPredicateOperatorType operatorType, NSExpression *right); + void apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression, + NSPredicateOperatorType operatorType, NSExpression *right); + + + template + void add_numeric_constraint(RLMPropertyType datatype, + NSPredicateOperatorType operatorType, + A&& lhs, B&& rhs); + + template + void add_bool_constraint(NSPredicateOperatorType operatorType, A lhs, B rhs); + + void add_substring_constraint(null, Query condition); + template + void add_substring_constraint(const T& value, Query condition); + template + void add_substring_constraint(const Columns& value, Query condition); + + template + void add_string_constraint(NSPredicateOperatorType operatorType, + NSComparisonPredicateOptions predicateOptions, + Columns &&column, + T value); + + void add_string_constraint(NSPredicateOperatorType operatorType, + NSComparisonPredicateOptions predicateOptions, + StringData value, + Columns&& column); + + template + void add_constraint(RLMPropertyType type, + NSPredicateOperatorType operatorType, + NSComparisonPredicateOptions predicateOptions, + L lhs, R rhs); + template + void do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType, + NSComparisonPredicateOptions predicateOptions, T... values); + void do_add_constraint(RLMPropertyType, NSPredicateOperatorType, NSComparisonPredicateOptions, id, realm::null); + + void add_between_constraint(const ColumnReference& column, id value); + + void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, BinaryData value); + void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, id value); + void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, null); + void add_binary_constraint(NSPredicateOperatorType operatorType, id value, const ColumnReference& column); + void add_binary_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&); + + void add_link_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, RLMObject *obj); + void add_link_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, realm::null); + template + void add_link_constraint(NSPredicateOperatorType operatorType, T obj, const ColumnReference& column); + void add_link_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&); + + template + void add_collection_operation_constraint(RLMPropertyType propertyType, NSPredicateOperatorType operatorType, T... values); + template + void add_collection_operation_constraint(NSPredicateOperatorType operatorType, + CollectionOperation collectionOperation, T... values); + + + CollectionOperation collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath); + ColumnReference column_reference_from_key_path(RLMObjectSchema *objectSchema, NSString *keyPath, bool isAggregate); + +private: + Query& m_query; + Group& m_group; + RLMSchema *m_schema; +}; + +// add a clause for numeric constraints based on operator type +template +void QueryBuilder::add_numeric_constraint(RLMPropertyType datatype, + NSPredicateOperatorType operatorType, + A&& lhs, B&& rhs) +{ + switch (operatorType) { + case NSLessThanPredicateOperatorType: + m_query.and_query(lhs < rhs); + break; + case NSLessThanOrEqualToPredicateOperatorType: + m_query.and_query(lhs <= rhs); + break; + case NSGreaterThanPredicateOperatorType: + m_query.and_query(lhs > rhs); + break; + case NSGreaterThanOrEqualToPredicateOperatorType: + m_query.and_query(lhs >= rhs); + break; + case NSEqualToPredicateOperatorType: + m_query.and_query(lhs == rhs); + break; + case NSNotEqualToPredicateOperatorType: + m_query.and_query(lhs != rhs); + break; + default: + @throw RLMPredicateException(@"Invalid operator type", + @"Operator '%@' not supported for type %@", + operatorName(operatorType), RLMTypeToString(datatype)); + } +} + +template +void QueryBuilder::add_bool_constraint(NSPredicateOperatorType operatorType, A lhs, B rhs) { + switch (operatorType) { + case NSEqualToPredicateOperatorType: + m_query.and_query(lhs == rhs); + break; + case NSNotEqualToPredicateOperatorType: + m_query.and_query(lhs != rhs); + break; + default: + @throw RLMPredicateException(@"Invalid operator type", + @"Operator '%@' not supported for bool type", operatorName(operatorType)); + } +} + +void QueryBuilder::add_substring_constraint(null, Query) { + // Foundation always returns false for substring operations with a RHS of null or "". + m_query.and_query(std::unique_ptr(new FalseExpression)); +} + +template +void QueryBuilder::add_substring_constraint(const T& value, Query condition) { + // Foundation always returns false for substring operations with a RHS of null or "". + m_query.and_query(value.size() + ? std::move(condition) + : std::unique_ptr(new FalseExpression)); +} + +template +void QueryBuilder::add_substring_constraint(const Columns& value, Query condition) { + // Foundation always returns false for substring operations with a RHS of null or "". + // We don't need to concern ourselves with the possibility of value traversing a link list + // and producing multiple values per row as such expressions will have been rejected. + m_query.and_query(const_cast&>(value).size() != 0 && std::move(condition)); +} + +template +void QueryBuilder::add_string_constraint(NSPredicateOperatorType operatorType, + NSComparisonPredicateOptions predicateOptions, + Columns &&column, + T value) { + bool caseSensitive = !(predicateOptions & NSCaseInsensitivePredicateOption); + bool diacriticSensitive = !(predicateOptions & NSDiacriticInsensitivePredicateOption); + + if (diacriticSensitive) { + switch (operatorType) { + case NSBeginsWithPredicateOperatorType: + add_substring_constraint(value, column.begins_with(value, caseSensitive)); + break; + case NSEndsWithPredicateOperatorType: + add_substring_constraint(value, column.ends_with(value, caseSensitive)); + break; + case NSContainsPredicateOperatorType: + add_substring_constraint(value, column.contains(value, caseSensitive)); + break; + case NSEqualToPredicateOperatorType: + m_query.and_query(column.equal(value, caseSensitive)); + break; + case NSNotEqualToPredicateOperatorType: + m_query.and_query(column.not_equal(value, caseSensitive)); + break; + case NSLikePredicateOperatorType: + m_query.and_query(column.like(value, caseSensitive)); + break; + default: + @throw RLMPredicateException(@"Invalid operator type", + @"Operator '%@' not supported for string type", + operatorName(operatorType)); + } + return; + } + + auto as_subexpr = util::overload([](StringData value) { return make_subexpr(value); }, + [](const Columns& c) { return c.clone(); }); + auto left = as_subexpr(column); + auto right = as_subexpr(value); + + auto make_constraint = [&](auto comparator) { + using Comparator = decltype(comparator); + using CompareCS = Compare; + using CompareCI = Compare; + if (caseSensitive) { + return make_expression(std::move(left), std::move(right)); + } + else { + return make_expression(std::move(left), std::move(right)); + } + }; + + switch (operatorType) { + case NSBeginsWithPredicateOperatorType: { + using C = ContainsSubstring; + add_substring_constraint(value, make_constraint(C{})); + break; + } + case NSEndsWithPredicateOperatorType: { + using C = ContainsSubstring; + add_substring_constraint(value, make_constraint(C{})); + break; + } + case NSContainsPredicateOperatorType: { + using C = ContainsSubstring; + add_substring_constraint(value, make_constraint(C{})); + break; + } + case NSNotEqualToPredicateOperatorType: + m_query.Not(); + REALM_FALLTHROUGH; + case NSEqualToPredicateOperatorType: + m_query.and_query(make_constraint(Equal{})); + break; + case NSLikePredicateOperatorType: + @throw RLMPredicateException(@"Invalid operator type", + @"Operator 'LIKE' not supported with diacritic-insensitive modifier."); + default: + @throw RLMPredicateException(@"Invalid operator type", + @"Operator '%@' not supported for string type", operatorName(operatorType)); + } +} + +void QueryBuilder::add_string_constraint(NSPredicateOperatorType operatorType, + NSComparisonPredicateOptions predicateOptions, + StringData value, + Columns&& column) { + switch (operatorType) { + case NSEqualToPredicateOperatorType: + case NSNotEqualToPredicateOperatorType: + add_string_constraint(operatorType, predicateOptions, std::move(column), value); + break; + default: + @throw RLMPredicateException(@"Invalid operator type", + @"Operator '%@' is not supported for string type with key path on right side of operator", + operatorName(operatorType)); + } +} + +id value_from_constant_expression_or_value(id value) { + if (NSExpression *exp = RLMDynamicCast(value)) { + RLMPrecondition(exp.expressionType == NSConstantValueExpressionType, + @"Invalid value", + @"Expressions within predicate aggregates must be constant values"); + return exp.constantValue; + } + return value; +} + +void validate_and_extract_between_range(id value, RLMProperty *prop, id *from, id *to) { + NSArray *array = RLMDynamicCast(value); + RLMPrecondition(array, @"Invalid value", @"object must be of type NSArray for BETWEEN operations"); + RLMPrecondition(array.count == 2, @"Invalid value", @"NSArray object must contain exactly two objects for BETWEEN operations"); + + *from = value_from_constant_expression_or_value(array.firstObject); + *to = value_from_constant_expression_or_value(array.lastObject); + RLMPrecondition(RLMIsObjectValidForProperty(*from, prop) && RLMIsObjectValidForProperty(*to, prop), + @"Invalid value", + @"NSArray objects must be of type %@ for BETWEEN operations", RLMTypeToString(prop.type)); +} + +void QueryBuilder::add_between_constraint(const ColumnReference& column, id value) { + if (column.has_any_to_many_links()) { + auto link_column = column.last_link_column(); + Query subquery = get_table(m_group, link_column.link_target_object_schema()).where(); + QueryBuilder(subquery, m_group, m_schema).add_between_constraint(column.column_ignoring_links(subquery), value); + + m_query.and_query(link_column.resolve(std::move(subquery)).count() > 0); + return; + } + + id from, to; + validate_and_extract_between_range(value, column.property(), &from, &to); + + RLMPropertyType type = column.type(); + + m_query.group(); + add_constraint(type, NSGreaterThanOrEqualToPredicateOperatorType, 0, column, from); + add_constraint(type, NSLessThanOrEqualToPredicateOperatorType, 0, column, to); + m_query.end_group(); +} + +void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, + const ColumnReference& column, + BinaryData value) { + RLMPrecondition(!column.has_links(), @"Unsupported operator", @"NSData properties cannot be queried over an object link."); + + size_t index = column.index(); + Query query = m_query.get_table()->where(); + + switch (operatorType) { + case NSBeginsWithPredicateOperatorType: + add_substring_constraint(value, query.begins_with(index, value)); + break; + case NSEndsWithPredicateOperatorType: + add_substring_constraint(value, query.ends_with(index, value)); + break; + case NSContainsPredicateOperatorType: + add_substring_constraint(value, query.contains(index, value)); + break; + case NSEqualToPredicateOperatorType: + m_query.equal(index, value); + break; + case NSNotEqualToPredicateOperatorType: + m_query.not_equal(index, value); + break; + default: + @throw RLMPredicateException(@"Invalid operator type", + @"Operator '%@' not supported for binary type", operatorName(operatorType)); + } +} + +void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, id value) { + add_binary_constraint(operatorType, column, RLMBinaryDataForNSData(value)); +} + +void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, null) { + add_binary_constraint(operatorType, column, BinaryData()); +} + +void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, id value, const ColumnReference& column) { + switch (operatorType) { + case NSEqualToPredicateOperatorType: + case NSNotEqualToPredicateOperatorType: + add_binary_constraint(operatorType, column, value); + break; + default: + @throw RLMPredicateException(@"Invalid operator type", + @"Operator '%@' is not supported for binary type with key path on right side of operator", + operatorName(operatorType)); + } +} + +void QueryBuilder::add_binary_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&) { + @throw RLMPredicateException(@"Invalid predicate", @"Comparisons between two NSData properties are not supported"); +} + +void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType, + const ColumnReference& column, RLMObject *obj) { + RLMPrecondition(operatorType == NSEqualToPredicateOperatorType || operatorType == NSNotEqualToPredicateOperatorType, + @"Invalid operator type", @"Only 'Equal' and 'Not Equal' operators supported for object comparison"); + + if (operatorType == NSEqualToPredicateOperatorType) { + m_query.and_query(column.resolve() == obj->_row); + } + else { + m_query.and_query(column.resolve() != obj->_row); + } +} + +void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType, + const ColumnReference& column, + realm::null) { + RLMPrecondition(operatorType == NSEqualToPredicateOperatorType || operatorType == NSNotEqualToPredicateOperatorType, + @"Invalid operator type", @"Only 'Equal' and 'Not Equal' operators supported for object comparison"); + + if (operatorType == NSEqualToPredicateOperatorType) { + m_query.and_query(column.resolve() == null()); + } + else { + m_query.and_query(column.resolve() != null()); + } +} + +template +void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType, T obj, const ColumnReference& column) { + // Link constraints only support the equal-to and not-equal-to operators. The order of operands + // is not important for those comparisons so we can delegate to the other implementation. + add_link_constraint(operatorType, column, obj); +} + +void QueryBuilder::add_link_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&) { + // This is not actually reachable as this case is caught earlier, but this + // overload is needed for the code to compile + @throw RLMPredicateException(@"Invalid predicate", @"Comparisons between two RLMArray properties are not supported"); +} + + +// iterate over an array of subpredicates, using @func to build a query from each +// one and ORing them together +template +void process_or_group(Query &query, id array, Func&& func) { + RLMPrecondition([array conformsToProtocol:@protocol(NSFastEnumeration)], + @"Invalid value", @"IN clause requires an array of items"); + + query.group(); + + bool first = true; + for (id item in array) { + if (!first) { + query.Or(); + } + first = false; + + func(item); + } + + if (first) { + // Queries can't be empty, so if there's zero things in the OR group + // validation will fail. Work around this by adding an expression which + // will never find any rows in a table. + query.and_query(std::unique_ptr(new FalseExpression)); + } + + query.end_group(); +} + +template +RequestedType convert(id value); + +template <> +Timestamp convert(id value) { + return RLMTimestampForNSDate(value); +} + +template <> +bool convert(id value) { + return [value boolValue]; +} + +template <> +Double convert(id value) { + return [value doubleValue]; +} + +template <> +Float convert(id value) { + return [value floatValue]; +} + +template <> +Int convert(id value) { + return [value longLongValue]; +} + +template <> +String convert(id value) { + return RLMStringDataWithNSString(value); +} + +template +realm::null value_of_type(realm::null) { + return realm::null(); +} + +template +auto value_of_type(id value) { + return ::convert(value); +} + +template +auto value_of_type(const ColumnReference& column) { + return column.resolve(); +} + + +template +void QueryBuilder::do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType, + NSComparisonPredicateOptions predicateOptions, T... values) +{ + static_assert(sizeof...(T) == 2, "do_add_constraint accepts only two values as arguments"); + + switch (type) { + case RLMPropertyTypeBool: + add_bool_constraint(operatorType, value_of_type(values)...); + break; + case RLMPropertyTypeDate: + add_numeric_constraint(type, operatorType, value_of_type(values)...); + break; + case RLMPropertyTypeDouble: + add_numeric_constraint(type, operatorType, value_of_type(values)...); + break; + case RLMPropertyTypeFloat: + add_numeric_constraint(type, operatorType, value_of_type(values)...); + break; + case RLMPropertyTypeInt: + add_numeric_constraint(type, operatorType, value_of_type(values)...); + break; + case RLMPropertyTypeString: + add_string_constraint(operatorType, predicateOptions, value_of_type(values)...); + break; + case RLMPropertyTypeData: + add_binary_constraint(operatorType, values...); + break; + case RLMPropertyTypeObject: + case RLMPropertyTypeLinkingObjects: + add_link_constraint(operatorType, values...); + break; + default: + @throw RLMPredicateException(@"Unsupported predicate value type", + @"Object type %@ not supported", RLMTypeToString(type)); + } +} + +void QueryBuilder::do_add_constraint(RLMPropertyType, NSPredicateOperatorType, NSComparisonPredicateOptions, id, realm::null) +{ + // This is not actually reachable as this case is caught earlier, but this + // overload is needed for the code to compile + @throw RLMPredicateException(@"Invalid predicate expressions", + @"Predicate expressions must compare a keypath and another keypath or a constant value"); +} + +bool is_nsnull(id value) { + return !value || value == NSNull.null; +} + +template +bool is_nsnull(T) { + return false; +} + +template +void QueryBuilder::add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType, + NSComparisonPredicateOptions predicateOptions, L lhs, R rhs) +{ + // The expression operators are only overloaded for realm::null on the rhs + RLMPrecondition(!is_nsnull(lhs), @"Unsupported operator", + @"Nil is only supported on the right side of operators"); + + if (is_nsnull(rhs)) { + do_add_constraint(type, operatorType, predicateOptions, lhs, realm::null()); + } + else { + do_add_constraint(type, operatorType, predicateOptions, lhs, rhs); + } +} + +struct KeyPath { + std::vector links; + RLMProperty *property; + bool containsToManyRelationship; +}; + +KeyPath key_path_from_string(RLMSchema *schema, RLMObjectSchema *objectSchema, NSString *keyPath) +{ + RLMProperty *property; + std::vector links; + + bool keyPathContainsToManyRelationship = false; + + NSUInteger start = 0, length = keyPath.length, end = NSNotFound; + do { + end = [keyPath rangeOfString:@"." options:0 range:{start, length - start}].location; + NSString *propertyName = [keyPath substringWithRange:{start, end == NSNotFound ? length - start : end - start}]; + property = objectSchema[propertyName]; + RLMPrecondition(property, @"Invalid property name", + @"Property '%@' not found in object of type '%@'", + propertyName, objectSchema.className); + + if (property.array) + keyPathContainsToManyRelationship = true; + + if (end != NSNotFound) { + RLMPrecondition(property.type == RLMPropertyTypeObject || property.type == RLMPropertyTypeLinkingObjects, + @"Invalid value", @"Property '%@' is not a link in object of type '%@'", + propertyName, objectSchema.className); + + links.push_back(property); + REALM_ASSERT(property.objectClassName); + objectSchema = schema[property.objectClassName]; + } + + start = end + 1; + } while (end != NSNotFound); + + return {std::move(links), property, keyPathContainsToManyRelationship}; +} + +ColumnReference QueryBuilder::column_reference_from_key_path(RLMObjectSchema *objectSchema, + NSString *keyPathString, bool isAggregate) +{ + auto keyPath = key_path_from_string(m_schema, objectSchema, keyPathString); + + if (isAggregate && !keyPath.containsToManyRelationship) { + @throw RLMPredicateException(@"Invalid predicate", + @"Aggregate operations can only be used on key paths that include an array property"); + } else if (!isAggregate && keyPath.containsToManyRelationship) { + @throw RLMPredicateException(@"Invalid predicate", + @"Key paths that include an array property must use aggregate operations"); + } + + return ColumnReference(m_query, m_group, m_schema, keyPath.property, std::move(keyPath.links)); +} + +void validate_property_value(const ColumnReference& column, + __unsafe_unretained id const value, + __unsafe_unretained NSString *const err, + __unsafe_unretained RLMObjectSchema *const objectSchema, + __unsafe_unretained NSString *const keyPath) { + RLMProperty *prop = column.property(); + if (prop.array) { + RLMPrecondition([RLMObjectBaseObjectSchema(RLMDynamicCast(value)).className isEqualToString:prop.objectClassName], + @"Invalid value", err, prop.objectClassName, keyPath, objectSchema.className, value); + } + else { + RLMPrecondition(RLMIsObjectValidForProperty(value, prop), + @"Invalid value", err, RLMTypeToString(prop.type), keyPath, objectSchema.className, value); + } + if (RLMObjectBase *obj = RLMDynamicCast(value)) { + RLMPrecondition(!obj->_row.is_attached() || &column.group() == &obj->_realm.group, + @"Invalid value origin", @"Object must be from the Realm being queried"); + } +} + +template +struct ValueOfTypeWithCollectionOperationHelper; + +template <> +struct ValueOfTypeWithCollectionOperationHelper { + static auto convert(const CollectionOperation& operation) + { + assert(operation.type() == CollectionOperation::Count); + return operation.link_column().resolve().count(); + } +}; + +#define VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(OperationType, function) \ +template \ +struct ValueOfTypeWithCollectionOperationHelper { \ + static auto convert(const CollectionOperation& operation) \ + { \ + REALM_ASSERT(operation.type() == OperationType); \ + auto targetColumn = operation.link_column().resolve().template column(operation.column().index()); \ + return targetColumn.function(); \ + } \ +} \ + +VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Minimum, min); +VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Maximum, max); +VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Sum, sum); +VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Average, average); +#undef VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER + +template +auto value_of_type_with_collection_operation(T&& value) { + return value_of_type(std::forward(value)); +} + +template +auto value_of_type_with_collection_operation(CollectionOperation operation) { + using helper = ValueOfTypeWithCollectionOperationHelper; + return helper::convert(operation); +} + +template +void QueryBuilder::add_collection_operation_constraint(RLMPropertyType propertyType, NSPredicateOperatorType operatorType, T... values) +{ + switch (propertyType) { + case RLMPropertyTypeInt: + add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation(values)...); + break; + case RLMPropertyTypeFloat: + add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation(values)...); + break; + case RLMPropertyTypeDouble: + add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation(values)...); + break; + default: + REALM_ASSERT(false && "Only numeric property types should hit this path."); + } +} + +template +void QueryBuilder::add_collection_operation_constraint(NSPredicateOperatorType operatorType, + CollectionOperation collectionOperation, T... values) +{ + static_assert(sizeof...(T) == 2, "add_collection_operation_constraint accepts only two values as arguments"); + + switch (collectionOperation.type()) { + case CollectionOperation::Count: + add_numeric_constraint(RLMPropertyTypeInt, operatorType, + value_of_type_with_collection_operation(values)...); + break; + case CollectionOperation::Minimum: + add_collection_operation_constraint(collectionOperation.column().type(), operatorType, values...); + break; + case CollectionOperation::Maximum: + add_collection_operation_constraint(collectionOperation.column().type(), operatorType, values...); + break; + case CollectionOperation::Sum: + add_collection_operation_constraint(collectionOperation.column().type(), operatorType, values...); + break; + case CollectionOperation::Average: + add_collection_operation_constraint(collectionOperation.column().type(), operatorType, values...); + break; + } +} + +bool key_path_contains_collection_operator(NSString *keyPath) { + return [keyPath rangeOfString:@"@"].location != NSNotFound; +} + +NSString *get_collection_operation_name_from_key_path(NSString *keyPath, NSString **leadingKeyPath, + NSString **trailingKey) { + NSRange at = [keyPath rangeOfString:@"@"]; + if (at.location == NSNotFound || at.location >= keyPath.length - 1) { + @throw RLMPredicateException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath); + } + + if (at.location == 0 || [keyPath characterAtIndex:at.location - 1] != '.') { + @throw RLMPredicateException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath); + } + + NSRange trailingKeyRange = [keyPath rangeOfString:@"." options:0 range:{at.location, keyPath.length - at.location} locale:nil]; + + *leadingKeyPath = [keyPath substringToIndex:at.location - 1]; + if (trailingKeyRange.location == NSNotFound) { + *trailingKey = nil; + return [keyPath substringFromIndex:at.location]; + } else { + *trailingKey = [keyPath substringFromIndex:trailingKeyRange.location + 1]; + return [keyPath substringWithRange:{at.location, trailingKeyRange.location - at.location}]; + } +} + +CollectionOperation QueryBuilder::collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath) { + NSString *leadingKeyPath; + NSString *trailingKey; + NSString *collectionOperationName = get_collection_operation_name_from_key_path(keyPath, &leadingKeyPath, &trailingKey); + + ColumnReference linkColumn = column_reference_from_key_path(desc, leadingKeyPath, true); + util::Optional column; + if (trailingKey) { + RLMPrecondition([trailingKey rangeOfString:@"."].location == NSNotFound, @"Invalid key path", + @"Right side of collection operator may only have a single level key"); + NSString *fullKeyPath = [leadingKeyPath stringByAppendingFormat:@".%@", trailingKey]; + column = column_reference_from_key_path(desc, fullKeyPath, true); + } + + return {collectionOperationName, std::move(linkColumn), std::move(column)}; +} + +void QueryBuilder::apply_collection_operator_expression(RLMObjectSchema *desc, + NSString *keyPath, id value, + NSComparisonPredicate *pred) { + CollectionOperation operation = collection_operation_from_key_path(desc, keyPath); + operation.validate_comparison(value); + + if (pred.leftExpression.expressionType == NSKeyPathExpressionType) { + add_collection_operation_constraint(pred.predicateOperatorType, operation, operation, value); + } else { + add_collection_operation_constraint(pred.predicateOperatorType, operation, value, operation); + } +} + +void QueryBuilder::apply_value_expression(RLMObjectSchema *desc, + NSString *keyPath, id value, + NSComparisonPredicate *pred) +{ + if (key_path_contains_collection_operator(keyPath)) { + apply_collection_operator_expression(desc, keyPath, value, pred); + return; + } + + bool isAny = pred.comparisonPredicateModifier == NSAnyPredicateModifier; + ColumnReference column = column_reference_from_key_path(desc, keyPath, isAny); + + // check to see if this is a between query + if (pred.predicateOperatorType == NSBetweenPredicateOperatorType) { + add_between_constraint(std::move(column), value); + return; + } + + // turn "key.path IN collection" into ored together ==. "collection IN key.path" is handled elsewhere. + if (pred.predicateOperatorType == NSInPredicateOperatorType) { + process_or_group(m_query, value, [&](id item) { + id normalized = value_from_constant_expression_or_value(item); + validate_property_value(column, normalized, + @"Expected object of type %@ in IN clause for property '%@' on object of type '%@', but received: %@", desc, keyPath); + add_constraint(column.type(), NSEqualToPredicateOperatorType, pred.options, column, normalized); + }); + return; + } + + validate_property_value(column, value, @"Expected object of type %@ for property '%@' on object of type '%@', but received: %@", desc, keyPath); + if (pred.leftExpression.expressionType == NSKeyPathExpressionType) { + add_constraint(column.type(), pred.predicateOperatorType, pred.options, std::move(column), value); + } else { + add_constraint(column.type(), pred.predicateOperatorType, pred.options, value, std::move(column)); + } +} + +void QueryBuilder::apply_column_expression(RLMObjectSchema *desc, + NSString *leftKeyPath, NSString *rightKeyPath, + NSComparisonPredicate *predicate) +{ + bool left_key_path_contains_collection_operator = key_path_contains_collection_operator(leftKeyPath); + bool right_key_path_contains_collection_operator = key_path_contains_collection_operator(rightKeyPath); + if (left_key_path_contains_collection_operator && right_key_path_contains_collection_operator) { + @throw RLMPredicateException(@"Unsupported predicate", @"Key paths including aggregate operations cannot be compared with other aggregate operations."); + } + + if (left_key_path_contains_collection_operator) { + CollectionOperation left = collection_operation_from_key_path(desc, leftKeyPath); + ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, false); + left.validate_comparison(right); + add_collection_operation_constraint(predicate.predicateOperatorType, left, left, std::move(right)); + return; + } + if (right_key_path_contains_collection_operator) { + ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, false); + CollectionOperation right = collection_operation_from_key_path(desc, rightKeyPath); + right.validate_comparison(left); + add_collection_operation_constraint(predicate.predicateOperatorType, right, std::move(left), right); + return; + } + + bool isAny = false; + ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, isAny); + ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, isAny); + + // NOTE: It's assumed that column type must match and no automatic type conversion is supported. + RLMPrecondition(left.type() == right.type(), + RLMPropertiesComparisonTypeMismatchException, + RLMPropertiesComparisonTypeMismatchReason, + RLMTypeToString(left.type()), + RLMTypeToString(right.type())); + + // TODO: Should we handle special case where left row is the same as right row (tautology) + add_constraint(left.type(), predicate.predicateOperatorType, predicate.options, + std::move(left), std::move(right)); +} + +// Identify expressions of the form [SELF valueForKeyPath:] +bool is_self_value_for_key_path_function_expression(NSExpression *expression) +{ + if (expression.expressionType != NSFunctionExpressionType) + return false; + + if (expression.operand.expressionType != NSEvaluatedObjectExpressionType) + return false; + + return [expression.function isEqualToString:@"valueForKeyPath:"]; +} + +// -[NSPredicate predicateWithSubtitutionVariables:] results in function expressions of the form [SELF valueForKeyPath:] +// that apply_predicate cannot handle. Replace such expressions with equivalent NSKeyPathExpressionType expressions. +NSExpression *simplify_self_value_for_key_path_function_expression(NSExpression *expression) { + if (is_self_value_for_key_path_function_expression(expression)) { + if (NSString *keyPath = [expression.arguments.firstObject keyPath]) { + return [NSExpression expressionForKeyPath:keyPath]; + } + } + return expression; +} + +void QueryBuilder::apply_subquery_count_expression(RLMObjectSchema *objectSchema, + NSExpression *subqueryExpression, NSPredicateOperatorType operatorType, NSExpression *right) { + if (right.expressionType != NSConstantValueExpressionType || ![right.constantValue isKindOfClass:[NSNumber class]]) { + @throw RLMPredicateException(@"Invalid predicate expression", @"SUBQUERY(…).@count is only supported when compared with a constant number."); + } + int64_t value = [right.constantValue integerValue]; + + ColumnReference collectionColumn = column_reference_from_key_path(objectSchema, [subqueryExpression.collection keyPath], true); + RLMObjectSchema *collectionMemberObjectSchema = m_schema[collectionColumn.property().objectClassName]; + + // Eliminate references to the iteration variable in the subquery. + NSPredicate *subqueryPredicate = [subqueryExpression.predicate predicateWithSubstitutionVariables:@{ subqueryExpression.variable : [NSExpression expressionForEvaluatedObject] }]; + subqueryPredicate = transformPredicate(subqueryPredicate, simplify_self_value_for_key_path_function_expression); + + Query subquery = RLMPredicateToQuery(subqueryPredicate, collectionMemberObjectSchema, m_schema, m_group); + add_numeric_constraint(RLMPropertyTypeInt, operatorType, + collectionColumn.resolve(std::move(subquery)).count(), value); +} + +void QueryBuilder::apply_function_subquery_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression, + NSPredicateOperatorType operatorType, NSExpression *right) { + if (![functionExpression.function isEqualToString:@"valueForKeyPath:"] || functionExpression.arguments.count != 1) { + @throw RLMPredicateException(@"Invalid predicate", @"The '%@' function is not supported on the result of a SUBQUERY.", functionExpression.function); + } + + NSExpression *keyPathExpression = functionExpression.arguments.firstObject; + if ([keyPathExpression.keyPath isEqualToString:@"@count"]) { + apply_subquery_count_expression(objectSchema, functionExpression.operand, operatorType, right); + } else { + @throw RLMPredicateException(@"Invalid predicate", @"SUBQUERY is only supported when immediately followed by .@count that is compared with a constant number."); + } +} + +void QueryBuilder::apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression, + NSPredicateOperatorType operatorType, NSExpression *right) { + if (functionExpression.operand.expressionType == NSSubqueryExpressionType) { + apply_function_subquery_expression(objectSchema, functionExpression, operatorType, right); + } else { + @throw RLMPredicateException(@"Invalid predicate", @"The '%@' function is not supported.", functionExpression.function); + } +} + + +void QueryBuilder::apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema) +{ + // Compound predicates. + if ([predicate isMemberOfClass:[NSCompoundPredicate class]]) { + NSCompoundPredicate *comp = (NSCompoundPredicate *)predicate; + + switch ([comp compoundPredicateType]) { + case NSAndPredicateType: + if (comp.subpredicates.count) { + // Add all of the subpredicates. + m_query.group(); + for (NSPredicate *subp in comp.subpredicates) { + apply_predicate(subp, objectSchema); + } + m_query.end_group(); + } else { + // NSCompoundPredicate's documentation states that an AND predicate with no subpredicates evaluates to TRUE. + m_query.and_query(std::unique_ptr(new TrueExpression)); + } + break; + + case NSOrPredicateType: { + // Add all of the subpredicates with ors inbetween. + process_or_group(m_query, comp.subpredicates, [&](__unsafe_unretained NSPredicate *const subp) { + apply_predicate(subp, objectSchema); + }); + break; + } + + case NSNotPredicateType: + // Add the negated subpredicate + m_query.Not(); + apply_predicate(comp.subpredicates.firstObject, objectSchema); + break; + + default: + @throw RLMPredicateException(@"Invalid compound predicate type", + @"Only support AND, OR and NOT predicate types"); + } + } + else if ([predicate isMemberOfClass:[NSComparisonPredicate class]]) { + NSComparisonPredicate *compp = (NSComparisonPredicate *)predicate; + + // check modifier + RLMPrecondition(compp.comparisonPredicateModifier != NSAllPredicateModifier, + @"Invalid predicate", @"ALL modifier not supported"); + + NSExpressionType exp1Type = compp.leftExpression.expressionType; + NSExpressionType exp2Type = compp.rightExpression.expressionType; + + if (compp.comparisonPredicateModifier == NSAnyPredicateModifier) { + // for ANY queries + RLMPrecondition(exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType, + @"Invalid predicate", + @"Predicate with ANY modifier must compare a KeyPath with RLMArray with a value"); + } + + if (compp.predicateOperatorType == NSBetweenPredicateOperatorType || compp.predicateOperatorType == NSInPredicateOperatorType) { + // Inserting an array via %@ gives NSConstantValueExpressionType, but including it directly gives NSAggregateExpressionType + if (exp1Type == NSKeyPathExpressionType && (exp2Type == NSAggregateExpressionType || exp2Type == NSConstantValueExpressionType)) { + // "key.path IN %@", "key.path IN {…}", "key.path BETWEEN %@", or "key.path BETWEEN {…}". + exp2Type = NSConstantValueExpressionType; + } + else if (compp.predicateOperatorType == NSInPredicateOperatorType && exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) { + // "%@ IN key.path" is equivalent to "ANY key.path IN %@". Rewrite the former into the latter. + compp = [NSComparisonPredicate predicateWithLeftExpression:compp.rightExpression rightExpression:compp.leftExpression + modifier:NSAnyPredicateModifier type:NSEqualToPredicateOperatorType options:0]; + exp1Type = NSKeyPathExpressionType; + exp2Type = NSConstantValueExpressionType; + } + else { + if (compp.predicateOperatorType == NSBetweenPredicateOperatorType) { + @throw RLMPredicateException(@"Invalid predicate", + @"Predicate with BETWEEN operator must compare a KeyPath with an aggregate with two values"); + } + else if (compp.predicateOperatorType == NSInPredicateOperatorType) { + @throw RLMPredicateException(@"Invalid predicate", + @"Predicate with IN operator must compare a KeyPath with an aggregate"); + } + } + } + + if (exp1Type == NSKeyPathExpressionType && exp2Type == NSKeyPathExpressionType) { + // both expression are KeyPaths + apply_column_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.keyPath, compp); + } + else if (exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType) { + // comparing keypath to value + apply_value_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.constantValue, compp); + } + else if (exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) { + // comparing value to keypath + apply_value_expression(objectSchema, compp.rightExpression.keyPath, compp.leftExpression.constantValue, compp); + } + else if (exp1Type == NSFunctionExpressionType) { + apply_function_expression(objectSchema, compp.leftExpression, compp.predicateOperatorType, compp.rightExpression); + } + else if (exp1Type == NSSubqueryExpressionType) { + // The subquery expressions that we support are handled by the NSFunctionExpressionType case above. + @throw RLMPredicateException(@"Invalid predicate expression", @"SUBQUERY is only supported when immediately followed by .@count."); + } + else { + @throw RLMPredicateException(@"Invalid predicate expressions", + @"Predicate expressions must compare a keypath and another keypath or a constant value"); + } + } + else if ([predicate isEqual:[NSPredicate predicateWithValue:YES]]) { + m_query.and_query(std::unique_ptr(new TrueExpression)); + } else if ([predicate isEqual:[NSPredicate predicateWithValue:NO]]) { + m_query.and_query(std::unique_ptr(new FalseExpression)); + } + else { + // invalid predicate type + @throw RLMPredicateException(@"Invalid predicate", + @"Only support compound, comparison, and constant predicates"); + } +} +} // namespace + +realm::Query RLMPredicateToQuery(NSPredicate *predicate, RLMObjectSchema *objectSchema, + RLMSchema *schema, Group &group) +{ + auto query = get_table(group, objectSchema).where(); + + // passing a nil predicate is a no-op + if (!predicate) { + return query; + } + + @autoreleasepool { + QueryBuilder(query, group, schema).apply_predicate(predicate, objectSchema); + } + + // Test the constructed query in core + std::string validateMessage = query.validate(); + RLMPrecondition(validateMessage.empty(), @"Invalid query", @"%.*s", + (int)validateMessage.size(), validateMessage.c_str()); + return query; +} diff --git a/Pods/Realm/Realm/RLMRealm+Sync.mm b/Pods/Realm/Realm/RLMRealm+Sync.mm new file mode 100644 index 0000000000..5cf9bc465f --- /dev/null +++ b/Pods/Realm/Realm/RLMRealm+Sync.mm @@ -0,0 +1,59 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMRealm+Sync.h" + +#import "RLMObjectBase.h" +#import "RLMObjectSchema.h" +#import "RLMRealm_Private.hpp" +#import "RLMResults_Private.hpp" +#import "RLMSchema.h" +#import "RLMSyncSession.h" + +#import "results.hpp" +#import "sync/partial_sync.hpp" +#import "shared_realm.hpp" + +using namespace realm; + +@implementation RLMRealm (Sync) + +- (void)subscribeToObjects:(Class)type where:(NSString *)query callback:(RLMPartialSyncFetchCallback)callback { + NSString *className = [type className]; + auto cb = [=](Results results, std::exception_ptr err) { + if (err) { + try { + rethrow_exception(err); + } + catch (...) { + NSError *error = nil; + RLMRealmTranslateException(&error); + callback(nil, error); + } + return; + } + callback([RLMResults resultsWithObjectInfo:_info[className] results:std::move(results)], nil); + }; + partial_sync::register_query(_realm, className.UTF8String, query.UTF8String, std::move(cb)); +} + +- (RLMSyncSession *)syncSession { + return [RLMSyncSession sessionForRealm:self]; +} + +@end diff --git a/Pods/Realm/Realm/RLMRealm.mm b/Pods/Realm/Realm/RLMRealm.mm new file mode 100644 index 0000000000..c5be182d90 --- /dev/null +++ b/Pods/Realm/Realm/RLMRealm.mm @@ -0,0 +1,925 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMRealm_Private.hpp" + +#import "RLMAnalytics.hpp" +#import "RLMArray_Private.hpp" +#import "RLMMigration_Private.h" +#import "RLMObject_Private.h" +#import "RLMObject_Private.hpp" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObjectStore.h" +#import "RLMObservation.hpp" +#import "RLMProperty.h" +#import "RLMProperty_Private.h" +#import "RLMQueryUtil.hpp" +#import "RLMRealmConfiguration_Private.hpp" +#import "RLMRealmUtil.hpp" +#import "RLMSchema_Private.hpp" +#import "RLMSyncManager_Private.h" +#import "RLMSyncUtil_Private.hpp" +#import "RLMThreadSafeReference_Private.hpp" +#import "RLMUpdateChecker.hpp" +#import "RLMUtil.hpp" + +#include "impl/realm_coordinator.hpp" +#include "object_store.hpp" +#include "schema.hpp" +#include "shared_realm.hpp" + +#include +#include +#include + +#import "sync/sync_session.hpp" + +using namespace realm; +using util::File; + +@interface RLMRealmNotificationToken : RLMNotificationToken +@property (nonatomic, strong) RLMRealm *realm; +@property (nonatomic, copy) RLMNotificationBlock block; +@end + +@interface RLMRealm () +@property (nonatomic, strong) NSHashTable *notificationHandlers; +- (void)sendNotifications:(RLMNotification)notification; +@end + +void RLMDisableSyncToDisk() { + realm::disable_sync_to_disk(); +} + +static void RLMAddSkipBackupAttributeToItemAtPath(std::string const& path) { + [[NSURL fileURLWithPath:@(path.c_str())] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; +} + +@implementation RLMRealmNotificationToken +- (void)invalidate { + [_realm verifyThread]; + [_realm.notificationHandlers removeObject:self]; + _realm = nil; + _block = nil; +} + +- (void)suppressNextNotification { + // Temporarily replace the block with one which restores the old block + // rather than producing a notification. + + // This briefly creates a retain cycle but it's fine because the block will + // be synchronously called shortly after this method is called. Unlike with + // collection notifications, this does not have to go through the object + // store or do fancy things to handle transaction coalescing because it's + // called synchronously by the obj-c code and not by the object store. + auto notificationBlock = _block; + _block = ^(RLMNotification, RLMRealm *) { + _block = notificationBlock; + }; +} + +- (void)dealloc { + if (_realm || _block) { + NSLog(@"RLMNotificationToken released without unregistering a notification. You must hold " + @"on to the RLMNotificationToken returned from addNotificationBlock and call " + @"-[RLMNotificationToken invalidate] when you no longer wish to receive RLMRealm notifications."); + } +} +@end + +static bool shouldForciblyDisableEncryption() { + static bool disableEncryption = getenv("REALM_DISABLE_ENCRYPTION"); + return disableEncryption; +} + +NSData *RLMRealmValidatedEncryptionKey(NSData *key) { + if (shouldForciblyDisableEncryption()) { + return nil; + } + + if (key && key.length != 64) { + @throw RLMException(@"Encryption key must be exactly 64 bytes long"); + } + + return key; +} + +@implementation RLMRealm { + NSHashTable *_collectionEnumerators; + bool _sendingNotifications; +} + ++ (BOOL)isCoreDebug { + return realm::Version::has_feature(realm::feature_Debug); +} + ++ (void)initialize { + static bool initialized; + if (initialized) { + return; + } + initialized = true; + + RLMCheckForUpdates(); + RLMSendAnalytics(); +} + +- (instancetype)initPrivate { + self = [super init]; + return self; +} + +- (BOOL)isEmpty { + return realm::ObjectStore::is_empty(self.group); +} + +- (void)verifyThread { + try { + _realm->verify_thread(); + } + catch (std::exception const& e) { + @throw RLMException(e); + } +} + +- (BOOL)inWriteTransaction { + return _realm->is_in_transaction(); +} + +- (realm::Group &)group { + return _realm->read_group(); +} + +- (BOOL)autorefresh { + return _realm->auto_refresh(); +} + +- (void)setAutorefresh:(BOOL)autorefresh { + _realm->set_auto_refresh(autorefresh); +} + ++ (instancetype)defaultRealm { + return [RLMRealm realmWithConfiguration:[RLMRealmConfiguration rawDefaultConfiguration] error:nil]; +} + ++ (instancetype)realmWithURL:(NSURL *)fileURL { + RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration]; + configuration.fileURL = fileURL; + return [RLMRealm realmWithConfiguration:configuration error:nil]; +} + ++ (void)asyncOpenWithConfiguration:(RLMRealmConfiguration *)configuration + callbackQueue:(dispatch_queue_t)callbackQueue + callback:(RLMAsyncOpenRealmCallback)callback { + RLMRealm *strongReferenceToSyncedRealm = nil; + if (configuration.config.sync_config) { + NSError *error = nil; + strongReferenceToSyncedRealm = [RLMRealm uncachedSchemalessRealmWithConfiguration:configuration error:&error]; + if (error) { + dispatch_async(callbackQueue, ^{ + callback(nil, error); + }); + return; + } + } + static dispatch_queue_t queue = dispatch_queue_create("io.realm.asyncOpenDispatchQueue", DISPATCH_QUEUE_CONCURRENT); + dispatch_async(queue, ^{ + @autoreleasepool { + if (strongReferenceToSyncedRealm) { + // Sync behavior: get the raw session, then wait for it to download. + if (auto session = sync_session_for_realm(strongReferenceToSyncedRealm)) { + // Wait for the session to download, then open it. + session->wait_for_download_completion([=](std::error_code error_code) { + dispatch_async(callbackQueue, ^{ + (void)strongReferenceToSyncedRealm; + NSError *error = nil; + if (error_code == std::error_code{}) { + // Success + @autoreleasepool { + // Try opening the Realm on the destination queue. + RLMRealm *localRealm = [RLMRealm realmWithConfiguration:configuration error:&error]; + callback(localRealm, error); + } + } else { + // Failure + callback(nil, make_sync_error(RLMSyncSystemErrorKindSession, + @(error_code.message().c_str()), + error_code.value(), + nil)); + } + }); + }); + } else { + dispatch_async(callbackQueue, ^{ + callback(nil, make_sync_error(RLMSyncSystemErrorKindSession, + @"Cannot asynchronously open synced Realm, because the associated session previously experienced a fatal error", + NSNotFound, + nil)); + }); + return; + } + } else { + // Default behavior: just dispatch onto the destination queue and open the Realm. + dispatch_async(callbackQueue, ^{ + @autoreleasepool { + NSError *error = nil; + RLMRealm *localRealm = [RLMRealm realmWithConfiguration:configuration error:&error]; + callback(localRealm, error); + } + }); + return; + } + } + }); +} + +// ARC tries to eliminate calls to autorelease when the value is then immediately +// returned, but this results in significantly different semantics between debug +// and release builds for RLMRealm, so force it to always autorelease. +static id RLMAutorelease(__unsafe_unretained id value) { + // +1 __bridge_retained, -1 CFAutorelease + return value ? (__bridge id)CFAutorelease((__bridge_retained CFTypeRef)value) : nil; +} + ++ (instancetype)realmWithSharedRealm:(SharedRealm)sharedRealm schema:(RLMSchema *)schema { + RLMRealm *realm = [[RLMRealm alloc] initPrivate]; + realm->_realm = sharedRealm; + realm->_dynamic = YES; + realm->_schema = schema; + realm->_info = RLMSchemaInfo(realm); + return RLMAutorelease(realm); +} + +REALM_NOINLINE void RLMRealmTranslateException(NSError **error) { + try { + throw; + } + catch (RealmFileException const& ex) { + switch (ex.kind()) { + case RealmFileException::Kind::PermissionDenied: + RLMSetErrorOrThrow(RLMMakeError(RLMErrorFilePermissionDenied, ex), error); + break; + case RealmFileException::Kind::IncompatibleLockFile: { + NSString *err = @"Realm file is currently open in another process " + "which cannot share access with this process. All " + "processes sharing a single file must be the same " + "architecture. For sharing files between the Realm " + "Browser and an iOS simulator, this means that you " + "must use a 64-bit simulator."; + RLMSetErrorOrThrow(RLMMakeError(RLMErrorIncompatibleLockFile, + File::PermissionDenied(err.UTF8String, ex.path())), error); + break; + } + case RealmFileException::Kind::NotFound: + RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileNotFound, ex), error); + break; + case RealmFileException::Kind::Exists: + RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileExists, ex), error); + break; + case RealmFileException::Kind::BadHistoryError: { + NSString *err = @"Realm file's history format is incompatible with the " + "settings in the configuration object being used to open " + "the Realm. Note that Realms configured for sync cannot be " + "opened as non-synced Realms, and vice versa. Otherwise, the " + "file may be corrupt."; + RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileAccess, + File::AccessError(err.UTF8String, ex.path())), error); + break; + } + case RealmFileException::Kind::AccessError: + RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileAccess, ex), error); + break; + case RealmFileException::Kind::FormatUpgradeRequired: + RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileFormatUpgradeRequired, ex), error); + break; + default: + RLMSetErrorOrThrow(RLMMakeError(RLMErrorFail, ex), error); + break; + } + } + catch (AddressSpaceExhausted const &ex) { + RLMSetErrorOrThrow(RLMMakeError(RLMErrorAddressSpaceExhausted, ex), error); + } + catch (SchemaMismatchException const& ex) { + RLMSetErrorOrThrow(RLMMakeError(RLMErrorSchemaMismatch, ex), error); + } + catch (std::system_error const& ex) { + RLMSetErrorOrThrow(RLMMakeError(ex), error); + } + catch (const std::exception &exp) { + RLMSetErrorOrThrow(RLMMakeError(RLMErrorFail, exp), error); + } +} + +REALM_NOINLINE static void translateSharedGroupOpenException(RLMRealmConfiguration *originalConfiguration, NSError **error) { + try { + throw; + } + catch (RealmFileException const& ex) { + switch (ex.kind()) { + case RealmFileException::Kind::IncompatibleSyncedRealm: { + RLMRealmConfiguration *configuration = [originalConfiguration copy]; + configuration.fileURL = [NSURL fileURLWithPath:@(ex.path().data())]; + configuration.readOnly = YES; + + NSError *intermediateError = RLMMakeError(RLMErrorIncompatibleSyncedFile, ex); + NSMutableDictionary *userInfo = [intermediateError.userInfo mutableCopy]; + userInfo[RLMBackupRealmConfigurationErrorKey] = configuration; + NSError *finalError = [NSError errorWithDomain:intermediateError.domain code:intermediateError.code + userInfo:userInfo]; + RLMSetErrorOrThrow(finalError, error); + break; + } + default: + RLMRealmTranslateException(error); + break; + } + } + catch (...) { + RLMRealmTranslateException(error); + } +} + + ++ (instancetype)realmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error { + bool dynamic = configuration.dynamic; + bool cache = configuration.cache; + bool readOnly = configuration.readOnly; + + { + Realm::Config& config = configuration.config; + + // try to reuse existing realm first + if (cache || dynamic) { + if (RLMRealm *realm = RLMGetThreadLocalCachedRealmForPath(config.path)) { + auto const& old_config = realm->_realm->config(); + if (old_config.immutable() != config.immutable() + || old_config.read_only_alternative() != config.read_only_alternative()) { + @throw RLMException(@"Realm at path '%s' already opened with different read permissions", config.path.c_str()); + } + if (old_config.in_memory != config.in_memory) { + @throw RLMException(@"Realm at path '%s' already opened with different inMemory settings", config.path.c_str()); + } + if (realm->_dynamic != dynamic) { + @throw RLMException(@"Realm at path '%s' already opened with different dynamic settings", config.path.c_str()); + } + if (old_config.encryption_key != config.encryption_key) { + @throw RLMException(@"Realm at path '%s' already opened with different encryption key", config.path.c_str()); + } + return RLMAutorelease(realm); + } + } + } + + configuration = [configuration copy]; + Realm::Config& config = configuration.config; + + RLMRealm *realm = [[RLMRealm alloc] initPrivate]; + realm->_dynamic = dynamic; + + // protects the realm cache and accessors cache + static std::mutex& initLock = *new std::mutex(); + std::lock_guard lock(initLock); + + try { + realm->_realm = Realm::get_shared_realm(config); + } + catch (...) { + translateSharedGroupOpenException(configuration, error); + return nil; + } + + // if we have a cached realm on another thread we can skip a few steps and + // just grab its schema + @autoreleasepool { + // ensure that cachedRealm doesn't end up in this thread's autorelease pool + if (auto cachedRealm = RLMGetAnyCachedRealmForPath(config.path)) { + realm->_realm->set_schema_subset(cachedRealm->_realm->schema()); + realm->_schema = cachedRealm.schema; + realm->_info = cachedRealm->_info.clone(cachedRealm->_realm->schema(), realm); + } + } + + if (realm->_schema) { } + else if (dynamic) { + realm->_schema = [RLMSchema dynamicSchemaFromObjectStoreSchema:realm->_realm->schema()]; + realm->_info = RLMSchemaInfo(realm); + } + else { + // set/align schema or perform migration if needed + RLMSchema *schema = configuration.customSchema ?: RLMSchema.sharedSchema; + + Realm::MigrationFunction migrationFunction; + auto migrationBlock = configuration.migrationBlock; + if (migrationBlock && configuration.schemaVersion > 0) { + migrationFunction = [=](SharedRealm old_realm, SharedRealm realm, Schema& mutableSchema) { + RLMSchema *oldSchema = [RLMSchema dynamicSchemaFromObjectStoreSchema:old_realm->schema()]; + RLMRealm *oldRealm = [RLMRealm realmWithSharedRealm:old_realm schema:oldSchema]; + + // The destination RLMRealm can't just use the schema from the + // SharedRealm because it doesn't have information about whether or + // not a class was defined in Swift, which effects how new objects + // are created + RLMRealm *newRealm = [RLMRealm realmWithSharedRealm:realm schema:schema.copy]; + + [[[RLMMigration alloc] initWithRealm:newRealm oldRealm:oldRealm schema:mutableSchema] execute:migrationBlock]; + + oldRealm->_realm = nullptr; + newRealm->_realm = nullptr; + }; + } + + try { + realm->_realm->update_schema(schema.objectStoreCopy, config.schema_version, + std::move(migrationFunction)); + } + catch (...) { + RLMRealmTranslateException(error); + return nil; + } + + realm->_schema = schema; + realm->_info = RLMSchemaInfo(realm); + RLMRealmCreateAccessors(realm.schema); + + if (!readOnly) { + // initializing the schema started a read transaction, so end it + [realm invalidate]; + } + } + + if (cache) { + RLMCacheRealm(config.path, realm); + } + + if (!readOnly) { + realm->_realm->m_binding_context = RLMCreateBindingContext(realm); + realm->_realm->m_binding_context->realm = realm->_realm; + + RLMAddSkipBackupAttributeToItemAtPath(config.path + ".management"); + RLMAddSkipBackupAttributeToItemAtPath(config.path + ".lock"); + RLMAddSkipBackupAttributeToItemAtPath(config.path + ".note"); + } + + return RLMAutorelease(realm); +} + ++ (instancetype)uncachedSchemalessRealmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error { + RLMRealm *realm = [[RLMRealm alloc] initPrivate]; + try { + realm->_realm = Realm::get_shared_realm(configuration.config); + } + catch (...) { + translateSharedGroupOpenException(configuration, error); + return nil; + } + return realm; +} + ++ (void)resetRealmState { + RLMClearRealmCache(); + realm::_impl::RealmCoordinator::clear_cache(); + [RLMRealmConfiguration resetRealmConfigurationState]; +} + +- (void)verifyNotificationsAreSupported:(bool)isCollection { + [self verifyThread]; + if (_realm->config().immutable()) { + @throw RLMException(@"Read-only Realms do not change and do not have change notifications"); + } + if (!_realm->can_deliver_notifications()) { + @throw RLMException(@"Can only add notification blocks from within runloops."); + } + if (isCollection && _realm->is_in_transaction()) { + @throw RLMException(@"Cannot register notification blocks from within write transactions."); + } +} + +- (RLMNotificationToken *)addNotificationBlock:(RLMNotificationBlock)block { + if (!block) { + @throw RLMException(@"The notification block should not be nil"); + } + [self verifyNotificationsAreSupported:false]; + + _realm->read_group(); + + if (!_notificationHandlers) { + _notificationHandlers = [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory]; + } + + RLMRealmNotificationToken *token = [[RLMRealmNotificationToken alloc] init]; + token.realm = self; + token.block = block; + [_notificationHandlers addObject:token]; + return token; +} + +- (void)sendNotifications:(RLMNotification)notification { + NSAssert(!_realm->config().immutable(), @"Read-only realms do not have notifications"); + if (_sendingNotifications) { + return; + } + NSUInteger count = _notificationHandlers.count; + if (count == 0) { + return; + } + + _sendingNotifications = true; + auto cleanup = realm::util::make_scope_exit([&]() noexcept { + _sendingNotifications = false; + }); + + // call this realm's notification blocks + if (count == 1) { + if (auto block = [_notificationHandlers.anyObject block]) { + block(notification, self); + } + } + else { + for (RLMRealmNotificationToken *token in _notificationHandlers.allObjects) { + if (auto block = token.block) { + block(notification, self); + } + } + } +} + +- (RLMRealmConfiguration *)configuration { + RLMRealmConfiguration *configuration = [[RLMRealmConfiguration alloc] init]; + configuration.config = _realm->config(); + configuration.dynamic = _dynamic; + configuration.customSchema = _schema; + return configuration; +} + +- (void)beginWriteTransaction { + try { + _realm->begin_transaction(); + } + catch (std::exception &ex) { + @throw RLMException(ex); + } +} + +- (void)commitWriteTransaction { + [self commitWriteTransaction:nil]; +} + +- (BOOL)commitWriteTransaction:(NSError **)outError { + try { + _realm->commit_transaction(); + return YES; + } + catch (...) { + RLMRealmTranslateException(outError); + return NO; + } +} + +- (BOOL)commitWriteTransactionWithoutNotifying:(NSArray *)tokens error:(NSError **)error { + for (RLMNotificationToken *token in tokens) { + if (token.realm != self) { + @throw RLMException(@"Incorrect Realm: only notifications for the Realm being modified can be skipped."); + } + [token suppressNextNotification]; + } + + try { + _realm->commit_transaction(); + return YES; + } + catch (...) { + RLMRealmTranslateException(error); + return NO; + } +} + +- (void)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block { + [self transactionWithBlock:block error:nil]; +} + +- (BOOL)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block error:(NSError **)outError { + [self beginWriteTransaction]; + block(); + if (_realm->is_in_transaction()) { + return [self commitWriteTransaction:outError]; + } + return YES; +} + +- (void)cancelWriteTransaction { + try { + _realm->cancel_transaction(); + } + catch (std::exception &ex) { + @throw RLMException(ex); + } +} + +- (void)invalidate { + if (_realm->is_in_transaction()) { + NSLog(@"WARNING: An RLMRealm instance was invalidated during a write " + "transaction and all pending changes have been rolled back."); + } + + [self detachAllEnumerators]; + + for (auto& objectInfo : _info) { + for (RLMObservationInfo *info : objectInfo.second.observedObjects) { + info->willChange(RLMInvalidatedKey); + } + } + + _realm->invalidate(); + + for (auto& objectInfo : _info) { + for (RLMObservationInfo *info : objectInfo.second.observedObjects) { + info->didChange(RLMInvalidatedKey); + } + objectInfo.second.releaseTable(); + } +} + +- (nullable id)resolveThreadSafeReference:(RLMThreadSafeReference *)reference { + return [reference resolveReferenceInRealm:self]; +} + +/** + Replaces all string columns in this Realm with a string enumeration column and compacts the + database file. + + Cannot be called from a write transaction. + + Compaction will not occur if other `RLMRealm` instances exist. + + While compaction is in progress, attempts by other threads or processes to open the database will + wait. + + Be warned that resource requirements for compaction is proportional to the amount of live data in + the database. + + Compaction works by writing the database contents to a temporary database file and then replacing + the database with the temporary one. The name of the temporary file is formed by appending + `.tmp_compaction_space` to the name of the database. + + @return YES if the compaction succeeded. + */ +- (BOOL)compact { + // compact() automatically ends the read transaction, but we need to clean + // up cached state and send invalidated notifications when that happens, so + // explicitly end it first unless we're in a write transaction (in which + // case compact() will throw an exception) + if (!_realm->is_in_transaction()) { + [self invalidate]; + } + + try { + return _realm->compact(); + } + catch (std::exception const& ex) { + @throw RLMException(ex); + } +} + +- (void)dealloc { + if (_realm) { + if (_realm->is_in_transaction()) { + [self cancelWriteTransaction]; + NSLog(@"WARNING: An RLMRealm instance was deallocated during a write transaction and all " + "pending changes have been rolled back. Make sure to retain a reference to the " + "RLMRealm for the duration of the write transaction."); + } + } +} + +- (BOOL)refresh { + return _realm->refresh(); +} + +- (void)addObject:(__unsafe_unretained RLMObject *const)object { + RLMAddObjectToRealm(object, self, false); +} + +- (void)addObjects:(id)objects { + for (RLMObject *obj in objects) { + if (![obj isKindOfClass:RLMObjectBase.class]) { + @throw RLMException(@"Cannot insert objects of type %@ with addObjects:. Only RLMObjects are supported.", + NSStringFromClass(obj.class)); + } + [self addObject:obj]; + } +} + +- (void)addOrUpdateObject:(RLMObject *)object { + // verify primary key + if (!object.objectSchema.primaryKeyProperty) { + @throw RLMException(@"'%@' does not have a primary key and can not be updated", object.objectSchema.className); + } + + RLMAddObjectToRealm(object, self, true); +} + +- (void)addOrUpdateObjects:(id)objects { + for (RLMObject *obj in objects) { + if (![obj isKindOfClass:RLMObjectBase.class]) { + @throw RLMException(@"Cannot add or update objects of type %@ with addOrUpdateObjects:. Only RLMObjects are" + " supported.", + NSStringFromClass(obj.class)); + } + [self addOrUpdateObject:obj]; + } +} + +- (void)deleteObject:(RLMObject *)object { + RLMDeleteObjectFromRealm(object, self); +} + +- (void)deleteObjects:(id)objects { + id idObjects = objects; + if ([idObjects respondsToSelector:@selector(realm)] + && [idObjects respondsToSelector:@selector(deleteObjectsFromRealm)]) { + if (self != (RLMRealm *)[idObjects realm]) { + @throw RLMException(@"Can only delete objects from the Realm they belong to."); + } + [idObjects deleteObjectsFromRealm]; + return; + } + if (auto array = RLMDynamicCast(objects)) { + if (array.type != RLMPropertyTypeObject) { + @throw RLMException(@"Cannot delete objects from RLMArray<%@>: only RLMObjects can be deleted.", + RLMTypeToString(array.type)); + } + } + for (RLMObject *obj in objects) { + if (![obj isKindOfClass:RLMObjectBase.class]) { + @throw RLMException(@"Cannot delete objects of type %@ with deleteObjects:. Only RLMObjects can be deleted.", + NSStringFromClass(obj.class)); + } + RLMDeleteObjectFromRealm(obj, self); + } +} + +- (void)deleteAllObjects { + RLMDeleteAllObjectsFromRealm(self); +} + +- (RLMResults *)allObjects:(NSString *)objectClassName { + return RLMGetObjects(self, objectClassName, nil); +} + +- (RLMResults *)objects:(NSString *)objectClassName where:(NSString *)predicateFormat, ... { + va_list args; + va_start(args, predicateFormat); + RLMResults *results = [self objects:objectClassName where:predicateFormat args:args]; + va_end(args); + return results; +} + +- (RLMResults *)objects:(NSString *)objectClassName where:(NSString *)predicateFormat args:(va_list)args { + return [self objects:objectClassName withPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; +} + +- (RLMResults *)objects:(NSString *)objectClassName withPredicate:(NSPredicate *)predicate { + return RLMGetObjects(self, objectClassName, predicate); +} + +- (RLMObject *)objectWithClassName:(NSString *)className forPrimaryKey:(id)primaryKey { + return RLMGetObject(self, className, primaryKey); +} + ++ (uint64_t)schemaVersionAtURL:(NSURL *)fileURL encryptionKey:(NSData *)key error:(NSError **)error { + RLMRealmConfiguration *config = [[RLMRealmConfiguration alloc] init]; + try { + config.fileURL = fileURL; + config.encryptionKey = RLMRealmValidatedEncryptionKey(key); + + uint64_t version = Realm::get_schema_version(config.config); + if (version == realm::ObjectStore::NotVersioned) { + RLMSetErrorOrThrow([NSError errorWithDomain:RLMErrorDomain code:RLMErrorFail userInfo:@{NSLocalizedDescriptionKey:@"Cannot open an uninitialized realm in read-only mode"}], error); + } + return version; + } + catch (...) { + translateSharedGroupOpenException(config, error); + return RLMNotVersioned; + } +} + ++ (BOOL)performMigrationForConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error { + if (RLMGetAnyCachedRealmForPath(configuration.config.path)) { + @throw RLMException(@"Cannot migrate Realms that are already open."); + } + + NSError *localError; // Prevents autorelease + BOOL success; + @autoreleasepool { + success = [RLMRealm realmWithConfiguration:configuration error:&localError] != nil; + } + if (!success && error) { + *error = localError; // Must set outside pool otherwise will free anyway + } + return success; +} + +- (RLMObject *)createObject:(NSString *)className withValue:(id)value { + return (RLMObject *)RLMCreateObjectInRealmWithValue(self, className, value, false); +} + +- (BOOL)writeCopyToURL:(NSURL *)fileURL encryptionKey:(NSData *)key error:(NSError **)error { + key = RLMRealmValidatedEncryptionKey(key); + NSString *path = fileURL.path; + + try { + _realm->write_copy(path.UTF8String, {static_cast(key.bytes), key.length}); + return YES; + } + catch (...) { + __autoreleasing NSError *dummyError; + if (!error) { + error = &dummyError; + } + RLMRealmTranslateException(error); + return NO; + } + + return NO; +} + +using Privilege = realm::ComputedPrivileges; +static bool hasPrivilege(realm::ComputedPrivileges actual, realm::ComputedPrivileges expected) { + return (static_cast(actual) & static_cast(expected)) == static_cast(expected); +} + +- (RLMRealmPrivileges)privilegesForRealm { + auto p = _realm->get_privileges(); + return { + .read = hasPrivilege(p, Privilege::Read), + .update = hasPrivilege(p, Privilege::Update), + .setPermissions = hasPrivilege(p, Privilege::SetPermissions), + .modifySchema = hasPrivilege(p, Privilege::ModifySchema), + }; +} + +- (RLMObjectPrivileges)privilegesForObject:(RLMObject *)object { + RLMVerifyAttached(object); + auto p = _realm->get_privileges(object->_row); + return { + .read = hasPrivilege(p, Privilege::Read), + .update = hasPrivilege(p, Privilege::Update), + .del = hasPrivilege(p, Privilege::Delete), + .setPermissions = hasPrivilege(p, Privilege::Delete), + }; +} + +- (RLMClassPrivileges)privilegesForClass:(Class)cls { + if (![cls respondsToSelector:@selector(_realmObjectName)]) { + @throw RLMException(@"Cannot get privileges for non-RLMObject class %@", cls); + } + return [self privilegesForClassNamed:[cls _realmObjectName] ?: [cls className]]; +} + +- (RLMClassPrivileges)privilegesForClassNamed:(NSString *)className { + auto p = _realm->get_privileges(className.UTF8String); + return { + .read = hasPrivilege(p, Privilege::Read), + .update = hasPrivilege(p, Privilege::Update), + .setPermissions = hasPrivilege(p, Privilege::SetPermissions), + .subscribe = hasPrivilege(p, Privilege::Query), + .create = hasPrivilege(p, Privilege::Create), + }; +} + +- (void)registerEnumerator:(RLMFastEnumerator *)enumerator { + if (!_collectionEnumerators) { + _collectionEnumerators = [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory]; + } + [_collectionEnumerators addObject:enumerator]; +} + +- (void)unregisterEnumerator:(RLMFastEnumerator *)enumerator { + [_collectionEnumerators removeObject:enumerator]; +} + +- (void)detachAllEnumerators { + for (RLMFastEnumerator *enumerator in _collectionEnumerators) { + [enumerator detach]; + } + _collectionEnumerators = nil; +} + +@end diff --git a/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm b/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm new file mode 100644 index 0000000000..36721d8821 --- /dev/null +++ b/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm @@ -0,0 +1,73 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMRealmConfiguration+Sync.h" + +#import "RLMRealmConfiguration_Private.hpp" +#import "RLMSyncConfiguration_Private.hpp" +#import "RLMSyncUser_Private.hpp" +#import "RLMSyncManager_Private.h" +#import "RLMSyncUtil_Private.hpp" +#import "RLMUtil.hpp" + +#import "sync/sync_config.hpp" +#import "sync/sync_manager.hpp" + +@implementation RLMRealmConfiguration (Sync) + +#pragma mark - API + +- (void)setSyncConfiguration:(RLMSyncConfiguration *)syncConfiguration { + if (self.config.should_compact_on_launch_function) { + @throw RLMException(@"Cannot set `syncConfiguration` when `shouldCompactOnLaunch` is set."); + } + RLMSyncUser *user = syncConfiguration.user; + if (user.state == RLMSyncUserStateError) { + @throw RLMException(@"Cannot set a sync configuration which has an errored-out user."); + } + + // Ensure sync manager is initialized, if it hasn't already been. + [RLMSyncManager sharedManager]; + NSAssert(user.identity, @"Cannot call this method on a user that doesn't have an identity."); + self.config.in_memory = false; + self.config.sync_config = std::make_shared([syncConfiguration rawConfiguration]); + self.config.schema_mode = realm::SchemaMode::Additive; + + if (syncConfiguration.customFileURL) { + self.config.path = syncConfiguration.customFileURL.path.UTF8String; + } else { + self.config.path = SyncManager::shared().path_for_realm(*[user _syncUser], + self.config.sync_config->realm_url()); + } + + if (!self.config.encryption_key.empty()) { + auto& sync_encryption_key = self.config.sync_config->realm_encryption_key; + sync_encryption_key = std::array(); + std::copy_n(self.config.encryption_key.begin(), 64, sync_encryption_key->begin()); + } +} + +- (RLMSyncConfiguration *)syncConfiguration { + if (!self.config.sync_config) { + return nil; + } + realm::SyncConfig& sync_config = *self.config.sync_config; + return [[RLMSyncConfiguration alloc] initWithRawConfig:sync_config]; +} + +@end diff --git a/Pods/Realm/Realm/RLMRealmConfiguration.mm b/Pods/Realm/Realm/RLMRealmConfiguration.mm new file mode 100644 index 0000000000..3635f819b7 --- /dev/null +++ b/Pods/Realm/Realm/RLMRealmConfiguration.mm @@ -0,0 +1,303 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMRealmConfiguration_Private.h" + +#import "RLMObjectSchema_Private.hpp" +#import "RLMRealm_Private.h" +#import "RLMSchema_Private.hpp" +#import "RLMUtil.hpp" + +#import "schema.hpp" +#import "shared_realm.hpp" +#import "sync/sync_config.hpp" + +static NSString *const c_RLMRealmConfigurationProperties[] = { + @"fileURL", + @"inMemoryIdentifier", + @"encryptionKey", + @"readOnly", + @"schemaVersion", + @"migrationBlock", + @"deleteRealmIfMigrationNeeded", + @"shouldCompactOnLaunch", + @"dynamic", + @"customSchema", +}; + +static NSString *const c_defaultRealmFileName = @"default.realm"; +RLMRealmConfiguration *s_defaultConfiguration; + +NSString *RLMRealmPathForFileAndBundleIdentifier(NSString *fileName, NSString *bundleIdentifier) { + return [RLMDefaultDirectoryForBundleIdentifier(bundleIdentifier) + stringByAppendingPathComponent:fileName]; +} + +NSString *RLMRealmPathForFile(NSString *fileName) { + static NSString *directory = RLMDefaultDirectoryForBundleIdentifier(nil); + return [directory stringByAppendingPathComponent:fileName]; +} + +@implementation RLMRealmConfiguration { + realm::Realm::Config _config; +} + +- (realm::Realm::Config&)config { + return _config; +} + ++ (instancetype)defaultConfiguration { + return [[self rawDefaultConfiguration] copy]; +} + ++ (void)setDefaultConfiguration:(RLMRealmConfiguration *)configuration { + if (!configuration) { + @throw RLMException(@"Cannot set the default configuration to nil."); + } + @synchronized(c_defaultRealmFileName) { + s_defaultConfiguration = [configuration copy]; + } +} + ++ (RLMRealmConfiguration *)rawDefaultConfiguration { + RLMRealmConfiguration *configuration; + @synchronized(c_defaultRealmFileName) { + if (!s_defaultConfiguration) { + s_defaultConfiguration = [[RLMRealmConfiguration alloc] init]; + } + configuration = s_defaultConfiguration; + } + return configuration; +} + ++ (void)resetRealmConfigurationState { + @synchronized(c_defaultRealmFileName) { + s_defaultConfiguration = nil; + } +} + +- (instancetype)init { + self = [super init]; + if (self) { + static NSURL *defaultRealmURL = [NSURL fileURLWithPath:RLMRealmPathForFile(c_defaultRealmFileName)]; + self.fileURL = defaultRealmURL; + self.schemaVersion = 0; + self.cache = YES; + + // We have our own caching of RLMRealm instances, so the ObjectStore + // cache is at best pointless, and may result in broken behavior when + // a realm::Realm instance outlives the RLMRealm (due to collection + // notifiers being in the middle of running when the RLMRealm is + // dealloced) and then reused for a new RLMRealm + _config.cache = false; + } + + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + RLMRealmConfiguration *configuration = [[[self class] allocWithZone:zone] init]; + configuration->_config = _config; + configuration->_cache = _cache; + configuration->_dynamic = _dynamic; + configuration->_migrationBlock = _migrationBlock; + configuration->_shouldCompactOnLaunch = _shouldCompactOnLaunch; + configuration->_customSchema = _customSchema; + return configuration; +} + +- (NSString *)description { + NSMutableString *string = [NSMutableString stringWithFormat:@"%@ {\n", self.class]; + for (NSString *key : c_RLMRealmConfigurationProperties) { + NSString *description = [[self valueForKey:key] description]; + description = [description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]; + + [string appendFormat:@"\t%@ = %@;\n", key, description]; + } + return [string stringByAppendingString:@"}"]; +} + +static void RLMNSStringToStdString(std::string &out, NSString *in) { + out.resize([in maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]); + if (out.empty()) { + return; + } + + NSUInteger size = out.size(); + [in getBytes:&out[0] + maxLength:size + usedLength:&size + encoding:NSUTF8StringEncoding + options:0 range:{0, in.length} remainingRange:nullptr]; + out.resize(size); +} + +- (NSURL *)fileURL { + if (_config.in_memory || _config.sync_config) { + return nil; + } + return [NSURL fileURLWithPath:@(_config.path.c_str())]; +} + +- (void)setFileURL:(NSURL *)fileURL { + NSString *path = fileURL.path; + if (path.length == 0) { + @throw RLMException(@"Realm path must not be empty"); + } + _config.sync_config = nullptr; + + RLMNSStringToStdString(_config.path, path); + _config.in_memory = false; +} + +- (NSString *)inMemoryIdentifier { + if (!_config.in_memory) { + return nil; + } + return [@(_config.path.c_str()) lastPathComponent]; +} + +- (void)setInMemoryIdentifier:(NSString *)inMemoryIdentifier { + if (inMemoryIdentifier.length == 0) { + @throw RLMException(@"In-memory identifier must not be empty"); + } + _config.sync_config = nullptr; + + RLMNSStringToStdString(_config.path, [NSTemporaryDirectory() stringByAppendingPathComponent:inMemoryIdentifier]); + _config.in_memory = true; +} + +- (NSData *)encryptionKey { + return _config.encryption_key.empty() ? nil : [NSData dataWithBytes:_config.encryption_key.data() length:_config.encryption_key.size()]; +} + +- (void)setEncryptionKey:(NSData * __nullable)encryptionKey { + if (NSData *key = RLMRealmValidatedEncryptionKey(encryptionKey)) { + auto bytes = static_cast(key.bytes); + _config.encryption_key.assign(bytes, bytes + key.length); + if (_config.sync_config) { + auto& sync_encryption_key = self.config.sync_config->realm_encryption_key; + sync_encryption_key = std::array(); + std::copy_n(_config.encryption_key.begin(), 64, sync_encryption_key->begin()); + } + } + else { + _config.encryption_key.clear(); + if (_config.sync_config) + _config.sync_config->realm_encryption_key = realm::util::none; + } +} + +- (BOOL)readOnly { + return _config.immutable(); +} + +- (void)setReadOnly:(BOOL)readOnly { + if (readOnly) { + if (self.deleteRealmIfMigrationNeeded) { + @throw RLMException(@"Cannot set `readOnly` when `deleteRealmIfMigrationNeeded` is set."); + } else if (self.shouldCompactOnLaunch) { + @throw RLMException(@"Cannot set `readOnly` when `shouldCompactOnLaunch` is set."); + } + _config.schema_mode = realm::SchemaMode::Immutable; + } + else if (self.readOnly) { + _config.schema_mode = realm::SchemaMode::Automatic; + } +} + +- (uint64_t)schemaVersion { + return _config.schema_version; +} + +- (void)setSchemaVersion:(uint64_t)schemaVersion { + if (schemaVersion == RLMNotVersioned) { + @throw RLMException(@"Cannot set schema version to %llu (RLMNotVersioned)", RLMNotVersioned); + } + _config.schema_version = schemaVersion; +} + +- (BOOL)deleteRealmIfMigrationNeeded { + return _config.schema_mode == realm::SchemaMode::ResetFile; +} + +- (void)setDeleteRealmIfMigrationNeeded:(BOOL)deleteRealmIfMigrationNeeded { + if (deleteRealmIfMigrationNeeded) { + if (self.readOnly) { + @throw RLMException(@"Cannot set `deleteRealmIfMigrationNeeded` when `readOnly` is set."); + } + _config.schema_mode = realm::SchemaMode::ResetFile; + } + else if (self.deleteRealmIfMigrationNeeded) { + _config.schema_mode = realm::SchemaMode::Automatic; + } +} + +- (NSArray *)objectClasses { + return [_customSchema.objectSchema valueForKeyPath:@"objectClass"]; +} + +- (void)setObjectClasses:(NSArray *)objectClasses { + self.customSchema = [RLMSchema schemaWithObjectClasses:objectClasses]; +} + +- (void)setDynamic:(bool)dynamic { + _dynamic = dynamic; + self.cache = !dynamic; +} + +- (bool)disableFormatUpgrade { + return _config.disable_format_upgrade; +} + +- (void)setDisableFormatUpgrade:(bool)disableFormatUpgrade { + _config.disable_format_upgrade = disableFormatUpgrade; +} + +- (realm::SchemaMode)schemaMode { + return _config.schema_mode; +} + +- (void)setSchemaMode:(realm::SchemaMode)mode { + _config.schema_mode = mode; +} + +- (NSString *)pathOnDisk { + return @(_config.path.c_str()); +} + +- (void)setShouldCompactOnLaunch:(RLMShouldCompactOnLaunchBlock)shouldCompactOnLaunch { + if (shouldCompactOnLaunch) { + if (self.readOnly) { + @throw RLMException(@"Cannot set `shouldCompactOnLaunch` when `readOnly` is set."); + } + _config.should_compact_on_launch_function = [=](size_t totalBytes, size_t usedBytes) { + return shouldCompactOnLaunch(totalBytes, usedBytes); + }; + } + else { + _config.should_compact_on_launch_function = nullptr; + } + _shouldCompactOnLaunch = shouldCompactOnLaunch; +} + +- (void)setCustomSchemaWithoutCopying:(RLMSchema *)schema { + _customSchema = schema; +} + +@end diff --git a/Pods/Realm/Realm/RLMRealmUtil.mm b/Pods/Realm/Realm/RLMRealmUtil.mm new file mode 100644 index 0000000000..10d6ff3662 --- /dev/null +++ b/Pods/Realm/Realm/RLMRealmUtil.mm @@ -0,0 +1,147 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMRealmUtil.hpp" + +#import "RLMObjectSchema_Private.hpp" +#import "RLMObservation.hpp" +#import "RLMRealm_Private.hpp" +#import "RLMUtil.hpp" + +#import +#import + +#import "binding_context.hpp" + +#import +#import +#import +#import +#import +#import + +// Global realm state +static std::mutex& s_realmCacheMutex = *new std::mutex(); +static std::map& s_realmsPerPath = *new std::map(); + +void RLMCacheRealm(std::string const& path, __unsafe_unretained RLMRealm *const realm) { + std::lock_guard lock(s_realmCacheMutex); + NSMapTable *realms = s_realmsPerPath[path]; + if (!realms) { + s_realmsPerPath[path] = realms = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsOpaquePersonality|NSPointerFunctionsOpaqueMemory + valueOptions:NSPointerFunctionsWeakMemory]; + } + [realms setObject:realm forKey:(__bridge id)pthread_self()]; +} + +RLMRealm *RLMGetAnyCachedRealmForPath(std::string const& path) { + std::lock_guard lock(s_realmCacheMutex); + return [s_realmsPerPath[path] objectEnumerator].nextObject; +} + +RLMRealm *RLMGetThreadLocalCachedRealmForPath(std::string const& path) { + std::lock_guard lock(s_realmCacheMutex); + return [s_realmsPerPath[path] objectForKey:(__bridge id)pthread_self()]; +} + +void RLMClearRealmCache() { + std::lock_guard lock(s_realmCacheMutex); + s_realmsPerPath.clear(); +} + +bool RLMIsInRunLoop() { + // The main thread may not be in a run loop yet if we're called from + // something like `applicationDidFinishLaunching:`, but it presumably will + // be in the future + if ([NSThread isMainThread]) { + return true; + } + // Current mode indicates why the current callout from the runloop was made, + // and is null if a runloop callout isn't currently being processed + if (auto mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent())) { + CFRelease(mode); + return true; + } + return false; +} + +namespace { +class RLMNotificationHelper : public realm::BindingContext { +public: + RLMNotificationHelper(RLMRealm *realm) : _realm(realm) { } + + bool can_deliver_notifications() const noexcept override { + return RLMIsInRunLoop(); + } + + void changes_available() override { + @autoreleasepool { + auto realm = _realm; + if (realm && !realm.autorefresh) { + [realm sendNotifications:RLMRealmRefreshRequiredNotification]; + } + } + } + + std::vector get_observed_rows() override { + @autoreleasepool { + if (auto realm = _realm) { + [realm detachAllEnumerators]; + return RLMGetObservedRows(realm->_info); + } + return {}; + } + } + + void will_change(std::vector const& observed, std::vector const& invalidated) override { + @autoreleasepool { + RLMWillChange(observed, invalidated); + } + } + + void did_change(std::vector const& observed, std::vector const& invalidated, bool version_changed) override { + try { + @autoreleasepool { + RLMDidChange(observed, invalidated); + if (version_changed) { + [_realm sendNotifications:RLMRealmDidChangeNotification]; + } + } + } + catch (...) { + // This can only be called during a write transaction if it was + // called due to the transaction beginning, so cancel it to ensure + // exceptions thrown here behave the same as exceptions thrown when + // actually beginning the write + if (_realm.inWriteTransaction) { + [_realm cancelWriteTransaction]; + } + throw; + } + } + +private: + // This is owned by the realm, so it needs to not retain the realm + __weak RLMRealm *const _realm; +}; +} // anonymous namespace + + +std::unique_ptr RLMCreateBindingContext(__unsafe_unretained RLMRealm *const realm) { + return std::unique_ptr(new RLMNotificationHelper(realm)); +} diff --git a/Pods/Realm/Realm/RLMResults.mm b/Pods/Realm/Realm/RLMResults.mm new file mode 100644 index 0000000000..956393c603 --- /dev/null +++ b/Pods/Realm/Realm/RLMResults.mm @@ -0,0 +1,516 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMResults_Private.hpp" + +#import "RLMAccessor.hpp" +#import "RLMArray_Private.hpp" +#import "RLMCollection_Private.hpp" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObjectStore.h" +#import "RLMObject_Private.hpp" +#import "RLMObservation.hpp" +#import "RLMProperty_Private.h" +#import "RLMQueryUtil.hpp" +#import "RLMRealm_Private.hpp" +#import "RLMSchema_Private.h" +#import "RLMThreadSafeReference_Private.hpp" +#import "RLMUtil.hpp" + +#import "results.hpp" +#import "shared_realm.hpp" + +#import +#import + +using namespace realm; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wincomplete-implementation" +@implementation RLMNotificationToken +@end +#pragma clang diagnostic pop + +@interface RLMResults () +@end + +// +// RLMResults implementation +// +@implementation RLMResults { + RLMRealm *_realm; + RLMClassInfo *_info; +} + +- (instancetype)initPrivate { + self = [super init]; + return self; +} + +- (instancetype)initWithResults:(Results)results { + if (self = [super init]) { + _results = std::move(results); + } + return self; +} + +static void assertKeyPathIsNotNested(NSString *keyPath) { + if ([keyPath rangeOfString:@"."].location != NSNotFound) { + @throw RLMException(@"Nested key paths are not supported yet for KVC collection operators."); + } +} + +void RLMThrowResultsError(NSString *aggregateMethod) { + try { + throw; + } + catch (realm::InvalidTransactionException const&) { + @throw RLMException(@"Cannot modify Results outside of a write transaction."); + } + catch (realm::IncorrectThreadException const&) { + @throw RLMException(@"Realm accessed from incorrect thread."); + } + catch (realm::Results::InvalidatedException const&) { + @throw RLMException(@"RLMResults has been invalidated."); + } + catch (realm::Results::DetatchedAccessorException const&) { + @throw RLMException(@"Object has been invalidated."); + } + catch (realm::Results::IncorrectTableException const& e) { + @throw RLMException(@"Object of type '%s' does not match RLMResults type '%s'.", + e.actual.data(), e.expected.data()); + } + catch (realm::Results::OutOfBoundsIndexException const& e) { + @throw RLMException(@"Index %zu is out of bounds (must be less than %zu).", + e.requested, e.valid_count); + } + catch (realm::Results::UnsupportedColumnTypeException const& e) { + @throw RLMException(@"%@ is not supported for %s%s property '%s'.", + aggregateMethod, + string_for_property_type(e.property_type), + is_nullable(e.property_type) ? "?" : "", + e.column_name.data()); + } + catch (std::exception const& e) { + @throw RLMException(e); + } +} + ++ (instancetype)resultsWithObjectInfo:(RLMClassInfo&)info + results:(realm::Results)results { + RLMResults *ar = [[self alloc] initPrivate]; + ar->_results = std::move(results); + ar->_realm = info.realm; + ar->_info = &info; + return ar; +} + ++ (instancetype)emptyDetachedResults { + return [[self alloc] initPrivate]; +} + +static inline void RLMResultsValidateInWriteTransaction(__unsafe_unretained RLMResults *const ar) { + ar->_realm->_realm->verify_thread(); + ar->_realm->_realm->verify_in_write(); +} + +- (BOOL)isInvalidated { + return translateRLMResultsErrors([&] { return !_results.is_valid(); }); +} + +- (NSUInteger)count { + return translateRLMResultsErrors([&] { return _results.size(); }); +} + +- (RLMPropertyType)type { + return translateRLMResultsErrors([&] { + return static_cast(_results.get_type() & ~realm::PropertyType::Nullable); + }); +} + +- (BOOL)isOptional { + return translateRLMResultsErrors([&] { + return is_nullable(_results.get_type()); + }); +} + +- (NSString *)objectClassName { + return translateRLMResultsErrors([&] { + if (_info && _results.get_type() == realm::PropertyType::Object) { + return _info->rlmObjectSchema.className; + } + return (NSString *)nil; + }); +} + +- (RLMClassInfo *)objectInfo { + return _info; +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state + objects:(__unused __unsafe_unretained id [])buffer + count:(NSUInteger)len { + if (!_info) { + return 0; + } + return RLMFastEnumerate(state, len, self); +} + +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ... { + va_list args; + va_start(args, predicateFormat); + NSUInteger index = [self indexOfObjectWhere:predicateFormat args:args]; + va_end(args); + return index; +} + +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args { + return [self indexOfObjectWithPredicate:[NSPredicate predicateWithFormat:predicateFormat + arguments:args]]; +} + +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate { + if (_results.get_mode() == Results::Mode::Empty) { + return NSNotFound; + } + + return translateRLMResultsErrors([&] { + if (_results.get_type() != realm::PropertyType::Object) { + @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects"); + } + return RLMConvertNotFound(_results.index_of(RLMPredicateToQuery(predicate, _info->rlmObjectSchema, _realm.schema, _realm.group))); + }); +} + +- (id)objectAtIndex:(NSUInteger)index { + RLMAccessorContext ctx(_realm, *_info); + return translateRLMResultsErrors([&] { + return _results.get(ctx, index); + }); +} + +- (id)firstObject { + if (!_info) { + return nil; + } + RLMAccessorContext ctx(_realm, *_info); + return translateRLMResultsErrors([&] { + return _results.first(ctx); + }); +} + +- (id)lastObject { + if (!_info) { + return nil; + } + RLMAccessorContext ctx(_realm, *_info); + return translateRLMResultsErrors([&] { + return _results.last(ctx); + }); +} + +- (NSUInteger)indexOfObject:(RLMObject *)object { + if (!_info || !object || (!object->_realm && !object.invalidated)) { + return NSNotFound; + } + RLMAccessorContext ctx(_realm, *_info); + return translateRLMResultsErrors([&] { + return RLMConvertNotFound(_results.index_of(ctx, object)); + }); +} + +- (id)valueForKeyPath:(NSString *)keyPath { + if ([keyPath characterAtIndex:0] != '@') { + return [super valueForKeyPath:keyPath]; + } + if ([keyPath isEqualToString:@"@count"]) { + return @(self.count); + } + + NSRange operatorRange = [keyPath rangeOfString:@"." options:NSLiteralSearch]; + NSUInteger keyPathLength = keyPath.length; + NSUInteger separatorIndex = operatorRange.location != NSNotFound ? operatorRange.location : keyPathLength; + NSString *operatorName = [keyPath substringWithRange:NSMakeRange(1, separatorIndex - 1)]; + SEL opSelector = NSSelectorFromString([NSString stringWithFormat:@"_%@ForKeyPath:", operatorName]); + if (![self respondsToSelector:opSelector]) { + @throw RLMException(@"Unsupported KVC collection operator found in key path '%@'", keyPath); + } + if (separatorIndex >= keyPathLength - 1) { + @throw RLMException(@"Missing key path for KVC collection operator %@ in key path '%@'", + operatorName, keyPath); + } + NSString *operatorKeyPath = [keyPath substringFromIndex:separatorIndex + 1]; + return ((id(*)(id, SEL, id))objc_msgSend)(self, opSelector, operatorKeyPath); +} + +- (id)valueForKey:(NSString *)key { + if (!_info) { + return @[]; + } + return translateRLMResultsErrors([&] { + return RLMCollectionValueForKey(_results, key, _realm, *_info); + }); +} + +- (void)setValue:(id)value forKey:(NSString *)key { + translateRLMResultsErrors([&] { RLMResultsValidateInWriteTransaction(self); }); + RLMCollectionSetValueForKey(self, key, value); +} + +- (NSNumber *)_aggregateForKeyPath:(NSString *)keyPath + method:(util::Optional (Results::*)(size_t))method + methodName:(NSString *)methodName returnNilForEmpty:(BOOL)returnNilForEmpty { + assertKeyPathIsNotNested(keyPath); + return [self aggregate:keyPath method:method methodName:methodName returnNilForEmpty:returnNilForEmpty]; +} + +- (NSNumber *)_minForKeyPath:(NSString *)keyPath { + return [self _aggregateForKeyPath:keyPath method:&Results::min methodName:@"@min" returnNilForEmpty:YES]; +} + +- (NSNumber *)_maxForKeyPath:(NSString *)keyPath { + return [self _aggregateForKeyPath:keyPath method:&Results::max methodName:@"@max" returnNilForEmpty:YES]; +} + +- (NSNumber *)_sumForKeyPath:(NSString *)keyPath { + return [self _aggregateForKeyPath:keyPath method:&Results::sum methodName:@"@sum" returnNilForEmpty:NO]; +} + +- (NSNumber *)_avgForKeyPath:(NSString *)keyPath { + assertKeyPathIsNotNested(keyPath); + return [self averageOfProperty:keyPath]; +} + +- (NSArray *)_unionOfObjectsForKeyPath:(NSString *)keyPath { + assertKeyPathIsNotNested(keyPath); + return translateRLMResultsErrors([&] { + return RLMCollectionValueForKey(_results, keyPath, _realm, *_info); + }); +} + +- (NSArray *)_distinctUnionOfObjectsForKeyPath:(NSString *)keyPath { + return [NSSet setWithArray:[self _unionOfObjectsForKeyPath:keyPath]].allObjects; +} + +- (NSArray *)_unionOfArraysForKeyPath:(NSString *)keyPath { + assertKeyPathIsNotNested(keyPath); + if ([keyPath isEqualToString:@"self"]) { + @throw RLMException(@"self is not a valid key-path for a KVC array collection operator as 'unionOfArrays'."); + } + + return translateRLMResultsErrors([&] { + NSMutableArray *flatArray = [NSMutableArray new]; + for (id array in RLMCollectionValueForKey(_results, keyPath, _realm, *_info)) { + for (id value in array) { + [flatArray addObject:value]; + } + } + return flatArray; + }); +} + +- (NSArray *)_distinctUnionOfArraysForKeyPath:(__unused NSString *)keyPath { + return [NSSet setWithArray:[self _unionOfArraysForKeyPath:keyPath]].allObjects; +} + +- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... { + va_list args; + va_start(args, predicateFormat); + RLMResults *results = [self objectsWhere:predicateFormat args:args]; + va_end(args); + return results; +} + +- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args { + return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; +} + +- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate { + return translateRLMResultsErrors([&] { + if (_results.get_mode() == Results::Mode::Empty) { + return self; + } + if (_results.get_type() != realm::PropertyType::Object) { + @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects"); + } + auto query = RLMPredicateToQuery(predicate, _info->rlmObjectSchema, _realm.schema, _realm.group); + return [RLMResults resultsWithObjectInfo:*_info results:_results.filter(std::move(query))]; + }); +} + +- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending { + return [self sortedResultsUsingDescriptors:@[[RLMSortDescriptor sortDescriptorWithKeyPath:keyPath ascending:ascending]]]; +} + +- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties { + if (properties.count == 0) { + return self; + } + return translateRLMResultsErrors([&] { + if (_results.get_mode() == Results::Mode::Empty) { + return self; + } + return [RLMResults resultsWithObjectInfo:*_info + results:_results.sort(RLMSortDescriptorsToKeypathArray(properties))]; + }); +} + +- (RLMResults *)distinctResultsUsingKeyPaths:(NSArray *)keyPaths { + for (NSString *keyPath in keyPaths) { + if ([keyPath rangeOfString:@"@"].location != NSNotFound) { + @throw RLMException(@"Cannot distinct on keypath '%@': KVC collection operators are not supported.", keyPath); + } + } + + return translateRLMResultsErrors([&] { + if (_results.get_mode() == Results::Mode::Empty) { + return self; + } + + std::vector keyPathsVector; + for (NSString *keyPath in keyPaths) { + keyPathsVector.push_back(keyPath.UTF8String); + } + + return [RLMResults resultsWithObjectInfo:*_info results:_results.distinct(keyPathsVector)]; + }); +} + +- (id)objectAtIndexedSubscript:(NSUInteger)index { + return [self objectAtIndex:index]; +} + +- (id)aggregate:(NSString *)property method:(util::Optional (Results::*)(size_t))method + methodName:(NSString *)methodName returnNilForEmpty:(BOOL)returnNilForEmpty { + if (_results.get_mode() == Results::Mode::Empty) { + return returnNilForEmpty ? nil : @0; + } + size_t column = 0; + if (self.type == RLMPropertyTypeObject || ![property isEqualToString:@"self"]) { + column = _info->tableColumn(property); + } + + auto value = translateRLMResultsErrors([&] { return (_results.*method)(column); }, methodName); + return value ? RLMMixedToObjc(*value) : nil; +} + +- (id)minOfProperty:(NSString *)property { + return [self aggregate:property method:&Results::min + methodName:@"minOfProperty" returnNilForEmpty:YES]; +} + +- (id)maxOfProperty:(NSString *)property { + return [self aggregate:property method:&Results::max + methodName:@"maxOfProperty" returnNilForEmpty:YES]; +} + +- (id)sumOfProperty:(NSString *)property { + return [self aggregate:property method:&Results::sum + methodName:@"sumOfProperty" returnNilForEmpty:NO]; +} + +- (id)averageOfProperty:(NSString *)property { + if (_results.get_mode() == Results::Mode::Empty) { + return nil; + } + size_t column = 0; + if (self.type == RLMPropertyTypeObject || ![property isEqualToString:@"self"]) { + column = _info->tableColumn(property); + } + auto value = translateRLMResultsErrors([&] { return _results.average(column); }, @"averageOfProperty"); + return value ? @(*value) : nil; +} + +- (void)deleteObjectsFromRealm { + if (self.type != RLMPropertyTypeObject) { + @throw RLMException(@"Cannot delete objects from RLMResults<%@>: only RLMObjects can be deleted.", + RLMTypeToString(self.type)); + } + return translateRLMResultsErrors([&] { + if (_results.get_mode() == Results::Mode::Table) { + RLMResultsValidateInWriteTransaction(self); + RLMClearTable(*_info); + } + else { + RLMTrackDeletions(_realm, [&] { _results.clear(); }); + } + }); +} + +- (NSString *)description { + return RLMDescriptionWithMaxDepth(@"RLMResults", self, RLMDescriptionMaxDepth); +} + +- (realm::TableView)tableView { + return translateRLMResultsErrors([&] { return _results.get_tableview(); }); +} + +- (RLMFastEnumerator *)fastEnumerator { + return translateRLMResultsErrors([&] { + return [[RLMFastEnumerator alloc] initWithResults:_results collection:self + realm:_realm classInfo:*_info]; + }); +} + +// The compiler complains about the method's argument type not matching due to +// it not having the generic type attached, but it doesn't seem to be possible +// to actually include the generic type +// http://www.openradar.me/radar?id=6135653276319744 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wmismatched-parameter-types" +- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults *, RLMCollectionChange *, NSError *))block { + [_realm verifyNotificationsAreSupported:true]; + return RLMAddNotificationBlock(self, _results, block, true); +} +#pragma clang diagnostic pop + +- (BOOL)isAttached +{ + return !!_realm; +} + +#pragma mark - Thread Confined Protocol Conformance + +- (std::unique_ptr)makeThreadSafeReference { + return std::make_unique>(_realm->_realm->obtain_thread_safe_reference(_results)); +} + +- (id)objectiveCMetadata { + return nil; +} + ++ (instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference + metadata:(__unused id)metadata + realm:(RLMRealm *)realm { + REALM_ASSERT_DEBUG(dynamic_cast *>(reference.get())); + auto results_reference = static_cast *>(reference.get()); + + Results results = realm->_realm->resolve_thread_safe_reference(std::move(*results_reference)); + + return [RLMResults resultsWithObjectInfo:realm->_info[RLMStringDataToNSString(results.get_object_type())] + results:std::move(results)]; +} + +@end + +@implementation RLMLinkingObjects +- (NSString *)description { + return RLMDescriptionWithMaxDepth(@"RLMLinkingObjects", self, RLMDescriptionMaxDepth); +} +@end + diff --git a/Pods/Realm/Realm/RLMSchema.mm b/Pods/Realm/Realm/RLMSchema.mm new file mode 100644 index 0000000000..d32440bed0 --- /dev/null +++ b/Pods/Realm/Realm/RLMSchema.mm @@ -0,0 +1,375 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSchema_Private.h" + +#import "RLMAccessor.h" +#import "RLMObjectBase_Private.h" +#import "RLMObject_Private.hpp" +#import "RLMObjectSchema_Private.hpp" +#import "RLMProperty_Private.h" +#import "RLMRealm_Private.hpp" +#import "RLMSwiftSupport.h" +#import "RLMUtil.hpp" + +#import "object_schema.hpp" +#import "object_store.hpp" +#import "schema.hpp" + +#import + +#import +#include + +using namespace realm; + +const uint64_t RLMNotVersioned = realm::ObjectStore::NotVersioned; + +// RLMSchema private properties +@interface RLMSchema () +@property (nonatomic, readwrite) NSMutableDictionary *objectSchemaByName; +@end + +// Private RLMSchema subclass that skips class registration on lookup +@interface RLMPrivateSchema : RLMSchema +@end +@implementation RLMPrivateSchema +- (RLMObjectSchema *)schemaForClassName:(NSString *)className { + return self.objectSchemaByName[className]; +} + +- (RLMObjectSchema *)objectForKeyedSubscript:(__unsafe_unretained NSString *const)className { + return [self schemaForClassName:className]; +} +@end + +static RLMSchema *s_sharedSchema = [[RLMSchema alloc] init]; +static NSMutableDictionary *s_localNameToClass = [[NSMutableDictionary alloc] init]; +static RLMSchema *s_privateSharedSchema = [[RLMPrivateSchema alloc] init]; + +static enum class SharedSchemaState { + Uninitialized, + Initializing, + Initialized +} s_sharedSchemaState = SharedSchemaState::Uninitialized; + +@implementation RLMSchema { + NSArray *_objectSchema; + realm::Schema _objectStoreSchema; +} + +// Caller must @synchronize on s_localNameToClass +static RLMObjectSchema *RLMRegisterClass(Class cls) { + if (RLMObjectSchema *schema = s_privateSharedSchema[[cls className]]) { + return schema; + } + + auto prevState = s_sharedSchemaState; + s_sharedSchemaState = SharedSchemaState::Initializing; + RLMObjectSchema *schema = [RLMObjectSchema schemaForObjectClass:cls]; + s_sharedSchemaState = prevState; + + // set unmanaged class on shared shema for unmanaged object creation + schema.unmanagedClass = RLMUnmanagedAccessorClassForObjectClass(schema.objectClass, schema); + + // override sharedSchema class methods for performance + RLMReplaceSharedSchemaMethod(cls, schema); + + s_privateSharedSchema.objectSchemaByName[schema.className] = schema; + if ([cls shouldIncludeInDefaultSchema] && prevState != SharedSchemaState::Initialized) { + s_sharedSchema.objectSchemaByName[schema.className] = schema; + } + + return schema; +} + +// Caller must @synchronize on s_localNameToClass +static void RLMRegisterClassLocalNames(Class *classes, NSUInteger count) { + for (NSUInteger i = 0; i < count; i++) { + Class cls = classes[i]; + if (!RLMIsObjectSubclass(cls)) { + continue; + } + + NSString *className = NSStringFromClass(cls); + if ([className hasPrefix:@"RLM:"] || [className hasPrefix:@"NSKVONotifying"]) { + continue; + } + + if ([RLMSwiftSupport isSwiftClassName:className]) { + className = [RLMSwiftSupport demangleClassName:className]; + } + // NSStringFromClass demangles the names for top-level Swift classes + // but not for nested classes. _T indicates it's a Swift symbol, t + // indicates it's a type, and C indicates it's a class. + else if ([className hasPrefix:@"_TtC"]) { + @throw RLMException(@"RLMObject subclasses cannot be nested within other declarations. Please move %@ to global scope.", className); + } + + if (Class existingClass = s_localNameToClass[className]) { + if (existingClass != cls) { + @throw RLMException(@"RLMObject subclasses with the same name cannot be included twice in the same target. " + @"Please make sure '%@' is only linked once to your current target.", className); + } + continue; + } + + s_localNameToClass[className] = cls; + RLMReplaceClassNameMethod(cls, className); + } +} + +- (instancetype)init { + self = [super init]; + if (self) { + _objectSchemaByName = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (NSArray *)objectSchema { + if (!_objectSchema) { + _objectSchema = [_objectSchemaByName allValues]; + } + return _objectSchema; +} + +- (void)setObjectSchema:(NSArray *)objectSchema { + _objectSchema = objectSchema; + _objectSchemaByName = [NSMutableDictionary dictionaryWithCapacity:objectSchema.count]; + for (RLMObjectSchema *object in objectSchema) { + [_objectSchemaByName setObject:object forKey:object.className]; + } +} + +- (RLMObjectSchema *)schemaForClassName:(NSString *)className { + if (RLMObjectSchema *schema = _objectSchemaByName[className]) { + return schema; // fast path for already-initialized schemas + } else if (Class cls = [RLMSchema classForString:className]) { + [cls sharedSchema]; // initialize the schema + return _objectSchemaByName[className]; // try again + } else { + return nil; + } +} + +- (RLMObjectSchema *)objectForKeyedSubscript:(__unsafe_unretained NSString *const)className { + RLMObjectSchema *schema = [self schemaForClassName:className]; + if (!schema) { + @throw RLMException(@"Object type '%@' not managed by the Realm", className); + } + return schema; +} + ++ (instancetype)schemaWithObjectClasses:(NSArray *)classes { + NSUInteger count = classes.count; + auto classArray = std::make_unique<__unsafe_unretained Class[]>(count); + [classes getObjects:classArray.get() range:NSMakeRange(0, count)]; + + RLMSchema *schema = [[self alloc] init]; + @synchronized(s_localNameToClass) { + RLMRegisterClassLocalNames(classArray.get(), count); + + schema->_objectSchemaByName = [NSMutableDictionary dictionaryWithCapacity:count]; + for (Class cls in classes) { + if (!RLMIsObjectSubclass(cls)) { + @throw RLMException(@"Can't add non-Object type '%@' to a schema.", cls); + } + schema->_objectSchemaByName[[cls className]] = RLMRegisterClass(cls); + } + } + + NSMutableArray *errors = [NSMutableArray new]; + // Verify that all of the targets of links are included in the class list + [schema->_objectSchemaByName enumerateKeysAndObjectsUsingBlock:^(id, RLMObjectSchema *objectSchema, BOOL *) { + for (RLMProperty *prop in objectSchema.properties) { + if (prop.type != RLMPropertyTypeObject) { + continue; + } + if (!schema->_objectSchemaByName[prop.objectClassName]) { + [errors addObject:[NSString stringWithFormat:@"- '%@.%@' links to class '%@', which is missing from the list of classes managed by the Realm", objectSchema.className, prop.name, prop.objectClassName]]; + } + } + }]; + if (errors.count) { + @throw RLMException(@"Invalid class subset list:\n%@", [errors componentsJoinedByString:@"\n"]); + } + + return schema; +} + ++ (RLMObjectSchema *)sharedSchemaForClass:(Class)cls { + @synchronized(s_localNameToClass) { + // We create instances of Swift objects during schema init, and they + // obviously need to not also try to initialize the schema + if (s_sharedSchemaState == SharedSchemaState::Initializing) { + return nil; + } + + RLMRegisterClassLocalNames(&cls, 1); + RLMObjectSchema *objectSchema = RLMRegisterClass(cls); + [cls initializeLinkedObjectSchemas]; + return objectSchema; + } +} + ++ (instancetype)partialSharedSchema { + return s_sharedSchema; +} + ++ (instancetype)partialPrivateSharedSchema { + return s_privateSharedSchema; +} + +// schema based on runtime objects ++ (instancetype)sharedSchema { + @synchronized(s_localNameToClass) { + // We replace this method with one which just returns s_sharedSchema + // once initialization is complete, but we still need to check if it's + // already complete because it may have been done by another thread + // while we were waiting for the lock + if (s_sharedSchemaState == SharedSchemaState::Initialized) { + return s_sharedSchema; + } + + if (s_sharedSchemaState == SharedSchemaState::Initializing) { + @throw RLMException(@"Illegal recursive call of +[%@ %@]. Note: Properties of Swift `Object` classes must not be prepopulated with queried results from a Realm.", self, NSStringFromSelector(_cmd)); + } + + s_sharedSchemaState = SharedSchemaState::Initializing; + try { + // Make sure we've discovered all classes + { + unsigned int numClasses; + using malloc_ptr = std::unique_ptr<__unsafe_unretained Class[], decltype(&free)>; + malloc_ptr classes(objc_copyClassList(&numClasses), &free); + RLMRegisterClassLocalNames(classes.get(), numClasses); + } + + [s_localNameToClass enumerateKeysAndObjectsUsingBlock:^(NSString *, Class cls, BOOL *) { + RLMRegisterClass(cls); + }]; + } + catch (...) { + s_sharedSchemaState = SharedSchemaState::Uninitialized; + throw; + } + + // Replace this method with one that doesn't need to acquire a lock + Class metaClass = objc_getMetaClass(class_getName(self)); + IMP imp = imp_implementationWithBlock(^{ return s_sharedSchema; }); + class_replaceMethod(metaClass, @selector(sharedSchema), imp, "@@:"); + + s_sharedSchemaState = SharedSchemaState::Initialized; + } + + return s_sharedSchema; +} + +// schema based on tables in a realm ++ (instancetype)dynamicSchemaFromObjectStoreSchema:(Schema const&)objectStoreSchema { + // cache descriptors for all subclasses of RLMObject + NSMutableArray *schemaArray = [NSMutableArray arrayWithCapacity:objectStoreSchema.size()]; + for (auto &objectSchema : objectStoreSchema) { + RLMObjectSchema *schema = [RLMObjectSchema objectSchemaForObjectStoreSchema:objectSchema]; + [schemaArray addObject:schema]; + } + + // set class array and mapping + RLMSchema *schema = [RLMSchema new]; + schema.objectSchema = schemaArray; + return schema; +} + ++ (Class)classForString:(NSString *)className { + if (Class cls = s_localNameToClass[className]) { + return cls; + } + + if (Class cls = NSClassFromString(className)) { + return RLMIsObjectSubclass(cls) ? cls : nil; + } + + // className might be the local name of a Swift class we haven't registered + // yet, so scan them all then recheck + { + unsigned int numClasses; + std::unique_ptr<__unsafe_unretained Class[], decltype(&free)> classes(objc_copyClassList(&numClasses), &free); + RLMRegisterClassLocalNames(classes.get(), numClasses); + } + + return s_localNameToClass[className]; +} + +- (id)copyWithZone:(NSZone *)zone { + RLMSchema *schema = [[RLMSchema allocWithZone:zone] init]; + schema->_objectSchemaByName = [[NSMutableDictionary allocWithZone:zone] + initWithDictionary:_objectSchemaByName copyItems:YES]; + return schema; +} + +- (BOOL)isEqualToSchema:(RLMSchema *)schema { + if (_objectSchemaByName.count != schema->_objectSchemaByName.count) { + return NO; + } + __block BOOL matches = YES; + [_objectSchemaByName enumerateKeysAndObjectsUsingBlock:^(NSString *name, RLMObjectSchema *objectSchema, BOOL *stop) { + if (![schema->_objectSchemaByName[name] isEqualToObjectSchema:objectSchema]) { + *stop = YES; + matches = NO; + } + }]; + return matches; +} + +- (NSString *)description { + NSMutableString *objectSchemaString = [NSMutableString string]; + NSArray *sort = @[[NSSortDescriptor sortDescriptorWithKey:@"className" ascending:YES]]; + for (RLMObjectSchema *objectSchema in [self.objectSchema sortedArrayUsingDescriptors:sort]) { + [objectSchemaString appendFormat:@"\t%@\n", + [objectSchema.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]]; + } + return [NSString stringWithFormat:@"Schema {\n%@}", objectSchemaString]; +} + +- (Schema)objectStoreCopy { + if (_objectStoreSchema.size() == 0) { + std::vector schema; + schema.reserve(_objectSchemaByName.count); + [_objectSchemaByName enumerateKeysAndObjectsUsingBlock:[&](NSString *, RLMObjectSchema *objectSchema, BOOL *) { + schema.push_back([objectSchema objectStoreCopy:self]); + }]; + + // Having both obj-c and Swift classes for the same tables results in + // duplicate ObjectSchemas that we need to filter out + std::sort(begin(schema), end(schema), [](auto&& a, auto&& b) { return a.name < b.name; }); + schema.erase(std::unique(begin(schema), end(schema), [](auto&& a, auto&& b) { + if (a.name == b.name) { + // If we make _realmObjectName public this needs to be turned into an exception + REALM_ASSERT_DEBUG(a.persisted_properties == b.persisted_properties); + return true; + } + return false; + }), end(schema)); + + _objectStoreSchema = std::move(schema); + } + return _objectStoreSchema; +} + +@end diff --git a/Pods/Realm/Realm/RLMSwiftSupport.m b/Pods/Realm/Realm/RLMSwiftSupport.m new file mode 100644 index 0000000000..e16c79ea4d --- /dev/null +++ b/Pods/Realm/Realm/RLMSwiftSupport.m @@ -0,0 +1,31 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSwiftSupport.h" + +@implementation RLMSwiftSupport + ++ (BOOL)isSwiftClassName:(NSString *)className { + return [className rangeOfString:@"."].location != NSNotFound; +} + ++ (NSString *)demangleClassName:(NSString *)className { + return [className substringFromIndex:[className rangeOfString:@"."].location + 1]; +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncConfiguration.mm b/Pods/Realm/Realm/RLMSyncConfiguration.mm new file mode 100644 index 0000000000..fa48291083 --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncConfiguration.mm @@ -0,0 +1,291 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncConfiguration_Private.hpp" + +#import "RLMRealmConfiguration+Sync.h" +#import "RLMSyncManager_Private.h" +#import "RLMSyncSession_Private.hpp" +#import "RLMSyncSessionRefreshHandle.hpp" +#import "RLMSyncUser_Private.hpp" +#import "RLMSyncUtil_Private.hpp" +#import "RLMUtil.hpp" + +#import "sync/sync_manager.hpp" +#import "sync/sync_config.hpp" + +#import + +using namespace realm; + +namespace { +using ProtocolError = realm::sync::ProtocolError; + +RLMSyncSystemErrorKind errorKindForSyncError(SyncError error) { + if (error.is_client_reset_requested()) { + return RLMSyncSystemErrorKindClientReset; + } else if (error.error_code == ProtocolError::permission_denied) { + return RLMSyncSystemErrorKindPermissionDenied; + } else if (error.error_code == ProtocolError::bad_authentication) { + return RLMSyncSystemErrorKindUser; + } else if (error.is_session_level_protocol_error()) { + return RLMSyncSystemErrorKindSession; + } else if (error.is_connection_level_protocol_error()) { + return RLMSyncSystemErrorKindConnection; + } else if (error.is_client_error()) { + return RLMSyncSystemErrorKindClient; + } else { + return RLMSyncSystemErrorKindUnknown; + } +} + +BOOL isValidRealmURL(NSURL *url) { + NSString *scheme = [url scheme]; + return [scheme isEqualToString:@"realm"] || [scheme isEqualToString:@"realms"]; +} +} + +@interface RLMSyncConfiguration () { + std::unique_ptr _config; +} + +- (instancetype)initWithUser:(RLMSyncUser *)user + realmURL:(NSURL *)url + customFileURL:(nullable NSURL *)customFileURL + isPartial:(BOOL)isPartial + stopPolicy:(RLMSyncStopPolicy)stopPolicy + errorHandler:(std::function)errorHandler; +@end + +@implementation RLMSyncConfiguration + +@dynamic stopPolicy; + +- (instancetype)initWithRawConfig:(realm::SyncConfig)config { + if (self = [super init]) { + _config = std::make_unique(std::move(config)); + } + return self; +} + +- (BOOL)isEqual:(id)object { + if (![object isKindOfClass:[RLMSyncConfiguration class]]) { + return NO; + } + RLMSyncConfiguration *that = (RLMSyncConfiguration *)object; + return [self.realmURL isEqual:that.realmURL] + && [self.user isEqual:that.user] + && self.stopPolicy == that.stopPolicy + && self.fullSynchronization == that.fullSynchronization; +} + +- (void)setEnableSSLValidation:(BOOL)enableSSLValidation { + _config->client_validate_ssl = (bool)enableSSLValidation; +} + +- (BOOL)enableSSLValidation { + return (BOOL)_config->client_validate_ssl; +} + +- (void)setIsPartial:(BOOL)isPartial { + _config->is_partial = (bool)isPartial; +} + +- (NSURL *)pinnedCertificateURL { + if (auto& path = _config->ssl_trust_certificate_path) { + return [NSURL fileURLWithPath:RLMStringDataToNSString(*path)]; + } + return nil; +} + +- (void)setPinnedCertificateURL:(NSURL *)pinnedCertificateURL { + if (pinnedCertificateURL) { + if ([pinnedCertificateURL respondsToSelector:@selector(UTF8String)]) { + _config->ssl_trust_certificate_path = std::string([(id)pinnedCertificateURL UTF8String]); + } + else { + _config->ssl_trust_certificate_path = std::string(pinnedCertificateURL.path.UTF8String); + } + } + else { + _config->ssl_trust_certificate_path = util::none; + } +} + + +- (BOOL)isPartial { + return (BOOL)_config->is_partial; +} + +- (void)setFullSynchronization:(BOOL)fullSynchronization { + _config->is_partial = !(bool)fullSynchronization; +} + +- (BOOL)fullSynchronization { + return !(BOOL)_config->is_partial; +} + +- (realm::SyncConfig)rawConfiguration { + return *_config; +} + +- (RLMSyncUser *)user { + return [[RLMSyncUser alloc] initWithSyncUser:_config->user]; +} + +- (RLMSyncStopPolicy)stopPolicy { + return translateStopPolicy(_config->stop_policy); +} + +- (void)setStopPolicy:(RLMSyncStopPolicy)stopPolicy { + _config->stop_policy = translateStopPolicy(stopPolicy); +} + +- (NSString *)urlPrefix { + if (_config->url_prefix) { + return @(_config->url_prefix->c_str()); + } + return nil; +} + +- (void)setUrlPrefix:(NSString *)urlPrefix { + if (urlPrefix) { + _config->url_prefix.emplace(urlPrefix.UTF8String); + } else { + _config->url_prefix = none; + } +} + +- (NSURL *)realmURL { + NSString *rawStringURL = @(_config->reference_realm_url.c_str()); + return [NSURL URLWithString:rawStringURL]; +} + +- (instancetype)initWithUser:(RLMSyncUser *)user realmURL:(NSURL *)url { + return [self initWithUser:user + realmURL:url + customFileURL:nil + isPartial:NO + stopPolicy:RLMSyncStopPolicyAfterChangesUploaded + errorHandler:nullptr]; +} + +- (instancetype)initWithUser:(RLMSyncUser *)user + realmURL:(NSURL *)url + isPartial:(BOOL)isPartial + urlPrefix:(NSString *)urlPrefix + stopPolicy:(RLMSyncStopPolicy)stopPolicy + enableSSLValidation:(BOOL)enableSSLValidation + certificatePath:(nullable NSURL *)certificatePath { + auto config = [self initWithUser:user + realmURL:url + customFileURL:nil + isPartial:isPartial + stopPolicy:stopPolicy + errorHandler:nullptr]; + config.urlPrefix = urlPrefix; + config.enableSSLValidation = enableSSLValidation; + config.pinnedCertificateURL = certificatePath; + return config; +} + +- (instancetype)initWithUser:(RLMSyncUser *)user + realmURL:(NSURL *)url + customFileURL:(nullable NSURL *)customFileURL + isPartial:(BOOL)isPartial + stopPolicy:(RLMSyncStopPolicy)stopPolicy + errorHandler:(std::function)errorHandler { + if (self = [super init]) { + if (!isValidRealmURL(url)) { + @throw RLMException(@"The provided URL (%@) was not a valid Realm URL.", [url absoluteString]); + } + auto bindHandler = [=](auto&, + const SyncConfig& config, + const std::shared_ptr& session) { + const std::shared_ptr& user = config.user; + NSURL *realmURL = [NSURL URLWithString:@(config.realm_url().c_str())]; + NSString *path = [realmURL path]; + REALM_ASSERT(realmURL && path); + RLMSyncSessionRefreshHandle *handle = [[RLMSyncSessionRefreshHandle alloc] initWithRealmURL:realmURL + user:user + session:std::move(session) + completionBlock:[RLMSyncManager sharedManager].sessionCompletionNotifier]; + context_for(user).register_refresh_handle([path UTF8String], handle); + }; + if (!errorHandler) { + errorHandler = [=](std::shared_ptr errored_session, + SyncError error) { + RLMSyncSession *session = [[RLMSyncSession alloc] initWithSyncSession:errored_session]; + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithCapacity:error.user_info.size()]; + for (auto& pair : error.user_info) { + userInfo[@(pair.first.c_str())] = @(pair.second.c_str()); + } + // FIXME: how should the binding respond if the `is_fatal` bool is true? + [[RLMSyncManager sharedManager] _fireErrorWithCode:error.error_code.value() + message:@(error.message.c_str()) + isFatal:error.is_fatal + session:session + userInfo:userInfo + errorClass:errorKindForSyncError(error)]; + }; + } + + _config = std::make_unique(SyncConfig{ + [user _syncUser], + [[url absoluteString] UTF8String] + }); + _config->stop_policy = translateStopPolicy(stopPolicy); + _config->bind_session_handler = std::move(bindHandler); + _config->error_handler = std::move(errorHandler); + _config->is_partial = isPartial; + + if (NSString *authorizationHeaderName = [RLMSyncManager sharedManager].authorizationHeaderName) { + _config->authorization_header_name.emplace(authorizationHeaderName.UTF8String); + } + if (NSDictionary *customRequestHeaders = [RLMSyncManager sharedManager].customRequestHeaders) { + for (NSString *key in customRequestHeaders) { + _config->custom_http_headers.emplace(key.UTF8String, customRequestHeaders[key].UTF8String); + } + } + + self.customFileURL = customFileURL; + return self; + } + return nil; +} + ++ (RLMRealmConfiguration *)automaticConfiguration { + if (RLMSyncUser.allUsers.count != 1) + @throw RLMException(@"The automatic configuration requires there be exactly one logged-in sync user."); + + return [RLMSyncConfiguration automaticConfigurationForUser:RLMSyncUser.currentUser]; +} + ++ (RLMRealmConfiguration *)automaticConfigurationForUser:(RLMSyncUser *)user { + RLMSyncConfiguration *syncConfig = [[RLMSyncConfiguration alloc] initWithUser:user + realmURL:user.defaultRealmURL + customFileURL:nil + isPartial:YES + stopPolicy:RLMSyncStopPolicyAfterChangesUploaded + errorHandler:nullptr]; + RLMRealmConfiguration *config = [[RLMRealmConfiguration alloc] init]; + config.syncConfiguration = syncConfig; + return config; +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncCredentials.m b/Pods/Realm/Realm/RLMSyncCredentials.m new file mode 100644 index 0000000000..a1521a2bad --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncCredentials.m @@ -0,0 +1,120 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncCredentials.h" +#import "RLMSyncUtil_Private.h" + +/// A Twitter account as an identity provider. +//extern RLMIdentityProvider const RLMIdentityProviderTwitter; + +RLMIdentityProvider const RLMIdentityProviderDebug = @"debug"; +RLMIdentityProvider const RLMIdentityProviderRealm = @"realm"; +RLMIdentityProvider const RLMIdentityProviderUsernamePassword = @"password"; +RLMIdentityProvider const RLMIdentityProviderFacebook = @"facebook"; +RLMIdentityProvider const RLMIdentityProviderTwitter = @"twitter"; +RLMIdentityProvider const RLMIdentityProviderGoogle = @"google"; +RLMIdentityProvider const RLMIdentityProviderCloudKit = @"cloudkit"; +RLMIdentityProvider const RLMIdentityProviderJWT = @"jwt"; +RLMIdentityProvider const RLMIdentityProviderAnonymous = @"anonymous"; +RLMIdentityProvider const RLMIdentityProviderNickname = @"nickname"; + +@interface RLMSyncCredentials () + +- (instancetype)initWithCustomToken:(RLMSyncCredentialsToken)token + provider:(RLMIdentityProvider)provider + userInfo:(NSDictionary *)userInfo NS_DESIGNATED_INITIALIZER; + +@property (nonatomic, readwrite) RLMSyncCredentialsToken token; +@property (nonatomic, readwrite) RLMIdentityProvider provider; +@property (nonatomic, readwrite) NSDictionary *userInfo; + +@end + +@implementation RLMSyncCredentials + ++ (instancetype)credentialsWithFacebookToken:(RLMSyncCredentialsToken)token { + return [[self alloc] initWithCustomToken:token provider:RLMIdentityProviderFacebook userInfo:nil]; +} + ++ (instancetype)credentialsWithGoogleToken:(RLMSyncCredentialsToken)token { + return [[self alloc] initWithCustomToken:token provider:RLMIdentityProviderGoogle userInfo:nil]; +} + ++ (instancetype)credentialsWithCloudKitToken:(RLMSyncCredentialsToken)token { + return [[self alloc] initWithCustomToken:token provider:RLMIdentityProviderCloudKit userInfo:nil]; +} + ++ (instancetype)credentialsWithUsername:(NSString *)username + password:(NSString *)password + register:(BOOL)shouldRegister { + return [[self alloc] initWithCustomToken:username + provider:RLMIdentityProviderUsernamePassword + userInfo:@{kRLMSyncPasswordKey: password, + kRLMSyncRegisterKey: @(shouldRegister)}]; +} + ++ (instancetype)credentialsWithJWT:(NSString *)token { + return [[self alloc] initWithCustomToken:token provider:RLMIdentityProviderJWT userInfo:nil]; +} + ++ (instancetype)anonymousCredentials { + return [[self alloc] initWithCustomToken:@"" provider:RLMIdentityProviderAnonymous userInfo:nil]; +} + ++ (instancetype)credentialsWithNickname:(NSString *)nickname isAdmin:(BOOL)isAdmin { + return [[self alloc] initWithCustomToken:nickname + provider:RLMIdentityProviderNickname + userInfo:@{kRLMSyncIsAdminKey: @(isAdmin), kRLMSyncDataKey: nickname}]; +} + +/// Intended only for testing use. Will only work if the ROS is started with the `debug` provider enabled. ++ (instancetype)credentialsWithDebugUserID:(NSString *)userID isAdmin:(BOOL)isAdmin { + return [[self alloc] initWithCustomToken:userID + provider:RLMIdentityProviderDebug + userInfo:@{kRLMSyncIsAdminKey: @(isAdmin)}]; +} + ++ (instancetype)credentialsWithAccessToken:(RLMServerToken)accessToken identity:(NSString *)identity { + return [[self alloc] initWithCustomToken:accessToken + provider:RLMIdentityProviderAccessToken + userInfo:@{kRLMSyncIdentityKey: identity}]; +} + +- (BOOL)isEqual:(id)object { + if (![object isKindOfClass:[RLMSyncCredentials class]]) { + return NO; + } + RLMSyncCredentials *that = (RLMSyncCredentials *)object; + return ([self.token isEqualToString:that.token] + && [self.provider isEqualToString:that.provider] + && [self.userInfo isEqual:that.userInfo]); +} + +- (instancetype)initWithCustomToken:(RLMSyncCredentialsToken)token + provider:(RLMIdentityProvider)provider + userInfo:(NSDictionary *)userInfo { + if (self = [super init]) { + self.token = token; + self.provider = provider; + self.userInfo = userInfo; + return self; + } + return nil; +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncManager.mm b/Pods/Realm/Realm/RLMSyncManager.mm new file mode 100644 index 0000000000..b12825949d --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncManager.mm @@ -0,0 +1,213 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncManager_Private.h" + +#import "RLMRealmConfiguration+Sync.h" +#import "RLMSyncConfiguration_Private.hpp" +#import "RLMSyncSession_Private.hpp" +#import "RLMSyncUser_Private.hpp" +#import "RLMSyncUtil_Private.hpp" +#import "RLMUtil.hpp" + +#import "sync/sync_config.hpp" +#import "sync/sync_manager.hpp" +#import "sync/sync_session.hpp" + +using namespace realm; +using Level = realm::util::Logger::Level; + +namespace { + +Level levelForSyncLogLevel(RLMSyncLogLevel logLevel) { + switch (logLevel) { + case RLMSyncLogLevelOff: return Level::off; + case RLMSyncLogLevelFatal: return Level::fatal; + case RLMSyncLogLevelError: return Level::error; + case RLMSyncLogLevelWarn: return Level::warn; + case RLMSyncLogLevelInfo: return Level::info; + case RLMSyncLogLevelDetail: return Level::detail; + case RLMSyncLogLevelDebug: return Level::debug; + case RLMSyncLogLevelTrace: return Level::trace; + case RLMSyncLogLevelAll: return Level::all; + } + REALM_UNREACHABLE(); // Unrecognized log level. +} + +RLMSyncLogLevel logLevelForLevel(Level logLevel) { + switch (logLevel) { + case Level::off: return RLMSyncLogLevelOff; + case Level::fatal: return RLMSyncLogLevelFatal; + case Level::error: return RLMSyncLogLevelError; + case Level::warn: return RLMSyncLogLevelWarn; + case Level::info: return RLMSyncLogLevelInfo; + case Level::detail: return RLMSyncLogLevelDetail; + case Level::debug: return RLMSyncLogLevelDebug; + case Level::trace: return RLMSyncLogLevelTrace; + case Level::all: return RLMSyncLogLevelAll; + } + REALM_UNREACHABLE(); // Unrecognized log level. +} + +struct CocoaSyncLogger : public realm::util::RootLogger { + void do_log(Level, std::string message) override { + NSLog(@"Sync: %@", RLMStringDataToNSString(message)); + } +}; + +struct CocoaSyncLoggerFactory : public realm::SyncLoggerFactory { + std::unique_ptr make_logger(realm::util::Logger::Level level) override { + auto logger = std::make_unique(); + logger->set_level_threshold(level); + return std::move(logger); + } +} s_syncLoggerFactory; + +} // anonymous namespace + +@interface RLMSyncManager () +- (instancetype)initWithCustomRootDirectory:(nullable NSURL *)rootDirectory NS_DESIGNATED_INITIALIZER; +@end + +@implementation RLMSyncManager + +static RLMSyncManager *s_sharedManager = nil; + ++ (instancetype)sharedManager { + static std::once_flag flag; + std::call_once(flag, [] { + try { + s_sharedManager = [[RLMSyncManager alloc] initWithCustomRootDirectory:nil]; + } + catch (std::exception const& e) { + @throw RLMException(e); + } + }); + return s_sharedManager; +} + +- (instancetype)initWithCustomRootDirectory:(NSURL *)rootDirectory { + if (self = [super init]) { + [RLMSyncUser _setUpBindingContextFactory]; + + // Initialize the sync engine. + SyncManager::shared().set_logger_factory(s_syncLoggerFactory); + bool should_encrypt = !getenv("REALM_DISABLE_METADATA_ENCRYPTION") && !RLMIsRunningInPlayground(); + auto mode = should_encrypt ? SyncManager::MetadataMode::Encryption : SyncManager::MetadataMode::NoEncryption; + rootDirectory = rootDirectory ?: [NSURL fileURLWithPath:RLMDefaultDirectoryForBundleIdentifier(nil)]; + SyncManager::shared().configure_file_system(rootDirectory.path.UTF8String, mode, none, true); + return self; + } + return nil; +} + +- (NSString *)appID { + if (!_appID) { + _appID = [[NSBundle mainBundle] bundleIdentifier] ?: @"(none)"; + } + return _appID; +} + +#pragma mark - Passthrough properties + +- (RLMSyncLogLevel)logLevel { + return logLevelForLevel(realm::SyncManager::shared().log_level()); +} + +- (void)setLogLevel:(RLMSyncLogLevel)logLevel { + realm::SyncManager::shared().set_log_level(levelForSyncLogLevel(logLevel)); +} + +#pragma mark - Private API + +- (void)_fireError:(NSError *)error { + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.errorHandler) { + self.errorHandler(error, nil); + } + }); +} + +- (void)_fireErrorWithCode:(int)errorCode + message:(NSString *)message + isFatal:(BOOL)fatal + session:(RLMSyncSession *)session + userInfo:(NSDictionary *)userInfo + errorClass:(RLMSyncSystemErrorKind)errorClass { + NSError *error = nil; + BOOL shouldMakeError = YES; + NSDictionary *custom = nil; + // Note that certain types of errors are 'interactive'; users have several options + // as to how to proceed after the error is reported. + switch (errorClass) { + case RLMSyncSystemErrorKindClientReset: { + std::string path = [userInfo[@(realm::SyncError::c_original_file_path_key)] UTF8String]; + custom = @{kRLMSyncPathOfRealmBackupCopyKey: + userInfo[@(realm::SyncError::c_recovery_file_path_key)], + kRLMSyncErrorActionTokenKey: + [[RLMSyncErrorActionToken alloc] initWithOriginalPath:std::move(path)] + };; + break; + } + case RLMSyncSystemErrorKindPermissionDenied: { + std::string path = [userInfo[@(realm::SyncError::c_original_file_path_key)] UTF8String]; + custom = @{kRLMSyncErrorActionTokenKey: + [[RLMSyncErrorActionToken alloc] initWithOriginalPath:std::move(path)] + }; + break; + } + case RLMSyncSystemErrorKindUser: + case RLMSyncSystemErrorKindSession: + break; + case RLMSyncSystemErrorKindConnection: + case RLMSyncSystemErrorKindClient: + case RLMSyncSystemErrorKindUnknown: + // Report the error. There's nothing the user can do about it, though. + shouldMakeError = fatal; + break; + } + error = shouldMakeError ? make_sync_error(errorClass, message, errorCode, custom) : nil; + dispatch_async(dispatch_get_main_queue(), ^{ + if (!self.errorHandler || !error) { + return; + } + self.errorHandler(error, session); + }); +} + +- (NSArray *)_allUsers { + NSMutableArray *buffer = [NSMutableArray array]; + for (auto user : SyncManager::shared().all_logged_in_users()) { + [buffer addObject:[[RLMSyncUser alloc] initWithSyncUser:std::move(user)]]; + } + return buffer; +} + ++ (void)resetForTesting { + SyncManager::shared().reset_for_testing(); +} + +- (RLMNetworkRequestOptions *)networkRequestOptions { + RLMNetworkRequestOptions *options = [[RLMNetworkRequestOptions alloc] init]; + options.authorizationHeaderName = self.authorizationHeaderName; + options.customHeaders = self.customRequestHeaders; + options.pinnedCertificatePaths = self.pinnedCertificatePaths; + return options; +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncPermission.mm b/Pods/Realm/Realm/RLMSyncPermission.mm new file mode 100644 index 0000000000..879a10742c --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncPermission.mm @@ -0,0 +1,382 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncPermission_Private.hpp" + +#import "RLMArray.h" +#import "RLMObjectSchema.h" +#import "RLMRealm_Dynamic.h" +#import "RLMSyncUtil_Private.hpp" +#import "RLMUtil.hpp" +#import "RLMResults.h" + +using namespace realm; + +using ConditionType = Permission::Condition::Type; + +static void verifyInWriteTransaction(__unsafe_unretained RLMRealm *const realm, SEL sel) { + if (!realm) { + @throw RLMException(@"Cannot call %@ on an unmanaged object.", NSStringFromSelector(sel)); + } + if (!realm.inWriteTransaction) { + @throw RLMException(@"Cannot call %@ outside of a write transaction.", NSStringFromSelector(sel)); + } +} + +id RLMPermissionForRole(RLMArray *array, id role) { + RLMResults *filtered = [array objectsWhere:@"role.name = %@", [role name]]; + RLMPermission *permission; + for (RLMPermission *p in filtered) { + if (permission == nil) { + permission = p; + } + // If there's more than one permission for the role, merge it into the first + // one and then delete it as otherwise revoking permissions won't actually work + else { + if (p.canRead && !permission.canRead) { + permission.canRead = true; + } + if (p.canUpdate && !permission.canUpdate) { + permission.canUpdate = true; + } + if (p.canDelete && !permission.canDelete) { + permission.canDelete = true; + } + if (p.canSetPermissions && !permission.canSetPermissions) { + permission.canSetPermissions = true; + } + if (p.canQuery && !permission.canQuery) { + permission.canQuery = true; + } + if (p.canCreate && !permission.canCreate) { + permission.canCreate = true; + } + if (p.canModifySchema && !permission.canModifySchema) { + permission.canModifySchema = true; + } + [array.realm deleteObject:p]; + } + } + if (!permission) { + // Use the dynamic API to create the appropriate Permission class for the array + permission = (id)[array.realm createObject:array.objectClassName withValue:@[role]]; + [array addObject:permission]; + } + return permission; +} + +@implementation RLMPermissionRole ++ (NSString *)_realmObjectName { + return @"__Role"; +} ++ (NSString *)primaryKey { + return @"name"; +} ++ (NSArray *)requiredProperties { + return @[@"name"]; +} ++ (NSDictionary *)_realmColumnNames { + return @{@"users": @"members"}; +} +@end + +@implementation RLMPermissionUser ++ (NSString *)_realmObjectName { + return @"__User"; +} ++ (NSString *)primaryKey { + return @"identity"; +} ++ (NSArray *)requiredProperties { + return @[@"identity"]; +} ++ (NSDictionary *)_realmColumnNames { + return @{@"identity": @"id", @"role": @"role"}; +} ++ (NSDictionary *)linkingObjectsProperties { + return @{@"roles": [RLMPropertyDescriptor descriptorWithClass:RLMPermissionRole.class propertyName:@"users"]}; +} + ++ (RLMPermissionUser *)userInRealm:(RLMRealm *)realm withIdentity:(NSString *)identity { + return [self createOrUpdateInRealm:realm withValue:@[identity]]; +} +@end + +@implementation RLMPermission ++ (NSString *)_realmObjectName { + return @"__Permission"; +} ++ (NSDictionary *)defaultPropertyValues { + return @{@"canRead": @NO, + @"canUpdate": @NO, + @"canDelete": @NO, + @"canSetPermissions": @NO, + @"canQuery": @NO, + @"canCreate": @NO, + @"canModifySchema": @NO}; +} + ++ (RLMPermission *)permissionForRole:(RLMPermissionRole *)role inArray:(RLMArray *)array { + verifyInWriteTransaction(array.realm, _cmd); + auto index = [array indexOfObjectWhere:@"role = %@", role]; + if (index != NSNotFound) { + return array[index]; + } + RLMPermission *permission = [RLMPermission createInRealm:role.realm withValue:@[role]]; + [array addObject:permission]; + return permission; +} + ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName inArray:(RLMArray *)array { + verifyInWriteTransaction(array.realm, _cmd); + return RLMPermissionForRole(array, [RLMPermissionRole createOrUpdateInRealm:array.realm withValue:@{@"name": roleName}]); +} + ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onRealm:(RLMRealm *)realm { + verifyInWriteTransaction(realm, _cmd); + return [self permissionForRoleNamed:roleName + inArray:[RLMRealmPermission objectInRealm:realm].permissions]; + +} + ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onClass:(Class)cls realm:(RLMRealm *)realm { + verifyInWriteTransaction(realm, _cmd); + return [self permissionForRoleNamed:roleName + inArray:[RLMClassPermission objectInRealm:realm forClass:cls].permissions]; +} + ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onClassNamed:(NSString *)className realm:(RLMRealm *)realm { + verifyInWriteTransaction(realm, _cmd); + return [self permissionForRoleNamed:roleName + inArray:[RLMClassPermission objectInRealm:realm forClassNamed:className].permissions]; +} + ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onObject:(RLMObject *)object { + verifyInWriteTransaction(object.realm, _cmd); + for (RLMProperty *prop in object.objectSchema.properties) { + if (prop.array && [prop.objectClassName isEqualToString:@"RLMPermission"]) { + return [self permissionForRoleNamed:roleName + inArray:[object valueForKey:prop.name]]; + } + } + @throw RLMException(@"Object %@ does not have a RLMArray property.", object); +} +@end + +@implementation RLMClassPermission ++ (NSString *)_realmObjectName { + return @"__Class"; +} ++ (NSString *)primaryKey { + return @"name"; +} ++ (NSArray *)requiredProperties { + return @[@"name"]; +} + ++ (instancetype)objectInRealm:(RLMRealm *)realm forClassNamed:(NSString *)name { + return [RLMClassPermission objectInRealm:realm forPrimaryKey:name]; +} ++ (instancetype)objectInRealm:(RLMRealm *)realm forClass:(Class)cls { + return [RLMClassPermission objectInRealm:realm forPrimaryKey:[cls _realmObjectName] ?: [cls className]]; +} +@end + +@interface RLMRealmPermission () +@property (nonatomic) int pk; +@end + +@implementation RLMRealmPermission ++ (NSString *)_realmObjectName { + return @"__Realm"; +} ++ (NSDictionary *)_realmColumnNames { + return @{@"pk": @"id"}; +} ++ (NSString *)primaryKey { + return @"pk"; +} + ++ (instancetype)objectInRealm:(RLMRealm *)realm { + return [RLMRealmPermission objectInRealm:realm forPrimaryKey:@0]; +} +@end + +#pragma mark - Permission + +@interface RLMSyncPermission () { +@private + NSString *_identity; + NSString *_key; + NSString *_value; + util::Optional _underlying; + RLMSyncAccessLevel _accessLevel; + NSString *_path; + NSDate *_updatedAt; +} +@end + +@implementation RLMSyncPermission + +- (instancetype)initWithRealmPath:(NSString *)path + identity:(NSString *)identity + accessLevel:(RLMSyncAccessLevel)accessLevel { + if (self = [super init]) { + _accessLevel = accessLevel; + _path = path; + _identity = identity; + if (!identity) { + @throw RLMException(@"A permission value cannot be created without a valid user ID"); + } + _updatedAt = [NSDate date]; + } + return self; +} + +- (instancetype)initWithRealmPath:(NSString *)path + username:(NSString *)username + accessLevel:(RLMSyncAccessLevel)accessLevel { + if (self = [super init]) { + _accessLevel = accessLevel; + _path = path; + _identity = nil; + _key = @"email"; + _value = username; + _updatedAt = [NSDate date]; + } + return self; +} + +- (instancetype)initWithPermission:(Permission)permission { + if (self = [super init]) { + _underlying = util::make_optional(std::move(permission)); + return self; + } + return nil; +} + +- (NSString *)path { + if (!_underlying) { + REALM_ASSERT(_path); + return _path; + } + return @(_underlying->path.c_str()); +} + +- (RLMSyncAccessLevel)accessLevel { + if (!_underlying) { + return _accessLevel; + } + return objCAccessLevelForAccessLevel(_underlying->access); +} + +- (BOOL)mayRead { + return self.accessLevel > RLMSyncAccessLevelNone; +} + +- (BOOL)mayWrite { + return self.accessLevel > RLMSyncAccessLevelRead; +} + +- (BOOL)mayManage { + return self.accessLevel == RLMSyncAccessLevelAdmin; +} + +- (NSString *)identity { + if (!_underlying) { + return _identity; + } + if (_underlying->condition.type == ConditionType::UserId) { + return @(_underlying->condition.user_id.c_str()); + } + return nil; +} + +- (NSString *)key { + if (!_underlying) { + return _key; + } + if (_underlying->condition.type == ConditionType::KeyValue) { + return @(_underlying->condition.key_value.first.c_str()); + } + return nil; +} + +- (NSString *)value { + if (!_underlying) { + return _value; + } + if (_underlying->condition.type == ConditionType::KeyValue) { + return @(_underlying->condition.key_value.second.c_str()); + } + return nil; +} + +- (NSDate *)updatedAt { + if (!_underlying) { + return _updatedAt; + } + return RLMTimestampToNSDate(_underlying->updated_at); +} + +- (realm::Permission)rawPermission { + if (_underlying) { + return *_underlying; + } + auto condition = (_identity + ? Permission::Condition([_identity UTF8String]) + : Permission::Condition([_key UTF8String], [_value UTF8String])); + return Permission{ + [_path UTF8String], + accessLevelForObjCAccessLevel(_accessLevel), + std::move(condition) + }; +} + +- (NSUInteger)hash { + return [self.identity hash] ^ self.accessLevel; +} + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if ([object isKindOfClass:[RLMSyncPermission class]]) { + RLMSyncPermission *that = (RLMSyncPermission *)object; + return (self.accessLevel == that.accessLevel + && Permission::paths_are_equivalent([self.path UTF8String], [that.path UTF8String], + [self.identity UTF8String], [that.identity UTF8String]) + && [self.identity isEqualToString:that.identity]); + } + return NO; +} + +- (NSString *)description { + NSString *typeDescription = nil; + if (self.identity) { + typeDescription = [NSString stringWithFormat:@"identity: %@", self.identity]; + } else { + typeDescription = [NSString stringWithFormat:@"key: %@, value: %@", self.key, self.value]; + } + return [NSString stringWithFormat:@" %@, path: %@, access level: %@", + typeDescription, + self.path, + @(Permission::description_for_access_level(accessLevelForObjCAccessLevel(self.accessLevel)).c_str())]; +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncPermissionResults.mm b/Pods/Realm/Realm/RLMSyncPermissionResults.mm new file mode 100644 index 0000000000..da3bcb9347 --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncPermissionResults.mm @@ -0,0 +1,258 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncPermissionResults.h" + +#import "RLMCollection_Private.hpp" +#import "RLMObjectSchema_Private.hpp" +#import "RLMQueryUtil.hpp" +#import "RLMResults_Private.hpp" +#import "RLMSchema_Private.hpp" +#import "RLMSyncPermission_Private.hpp" +#import "RLMSyncUtil_Private.hpp" +#import "RLMUtil.hpp" + +#import "object.hpp" + +using namespace realm; + +namespace { + +bool keypath_is_valid(NSString *keypath) +{ + static auto valid = [NSSet setWithArray:@[RLMSyncPermissionSortPropertyPath, + RLMSyncPermissionSortPropertyUserID, + RLMSyncPermissionSortPropertyUpdated]]; + return [valid containsObject:keypath]; +} + +} + +/// Sort by the Realm Object Server path to the Realm to which the permission applies. +RLMSyncPermissionSortProperty const RLMSyncPermissionSortPropertyPath = @"path"; +/// Sort by the identity of the user to whom the permission applies. +RLMSyncPermissionSortProperty const RLMSyncPermissionSortPropertyUserID = @"userId"; +/// Sort by the date the permissions were last updated. +RLMSyncPermissionSortProperty const RLMSyncPermissionSortPropertyUpdated = @"updatedAt"; + +@interface RLMSyncPermissionResults () +@property (nonatomic, strong) RLMSchema *schema; +@property (nonatomic, strong) RLMObjectSchema *objectSchema; +@end + +@implementation RLMSyncPermissionResults + +#pragma mark - Public API + +- (RLMPropertyType)type { + return RLMPropertyTypeObject; +} + +- (NSString *)objectClassName { + return NSStringFromClass([RLMSyncPermission class]); +} + +- (RLMRealm *)realm { + return nil; +} + +- (RLMSyncPermission *)objectAtIndex:(NSUInteger)index { + return translateRLMResultsErrors([&] { + Object permission(_results.get_realm(), _results.get_object_schema(), _results.get(index)); + return [[RLMSyncPermission alloc] initWithPermission:Permission(permission)]; + }); +} + +- (RLMSyncPermission *)firstObject { + return self.count == 0 ? nil : [self objectAtIndex:0]; +} + +- (RLMSyncPermission *)lastObject { + return self.count == 0 ? nil : [self objectAtIndex:(self.count - 1)]; +} + +- (NSUInteger)indexOfObject:(RLMSyncPermission *)object { + if (object.key) { + // Key-value permissions are only used for setting; they are never returned. + return NSNotFound; + } + // Canonicalize the path. + NSString *path = object.path; + if ([path rangeOfString:@"~"].location != NSNotFound) { + path = [path stringByReplacingOccurrencesOfString:@"~" withString:object.identity]; + } + NSString *topPrivilege; + switch (object.accessLevel) { + case RLMSyncAccessLevelNone: + // Deleted permissions are removed from the permissions Realm by ROS. + return NSNotFound; + case RLMSyncAccessLevelRead: + topPrivilege = @"mayRead"; + break; + case RLMSyncAccessLevelWrite: + topPrivilege = @"mayWrite"; + break; + case RLMSyncAccessLevelAdmin: + topPrivilege = @"mayManage"; + break; + } + // Build the predicate. + NSPredicate *p = [NSPredicate predicateWithFormat:@"%K = %@ AND %K = %@ AND %K == YES", + RLMSyncPermissionSortPropertyPath, path, + RLMSyncPermissionSortPropertyUserID, object.identity, + topPrivilege]; + return [self indexOfObjectWithPredicate:p]; +} + +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate { + return translateRLMResultsErrors([&] { + auto& group = _results.get_realm()->read_group(); + auto query = RLMPredicateToQuery(predicate, self.objectSchema, self.schema, group); + return RLMConvertNotFound(_results.index_of(std::move(query))); + }); +} + +- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate { + return translateRLMResultsErrors([&] { + auto query = RLMPredicateToQuery(predicate, self.objectSchema, self.schema, _results.get_realm()->read_group()); + return [[RLMSyncPermissionResults alloc] initWithResults:_results.filter(std::move(query))]; + }); +} + +- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties { + if (properties.count == 0) { + return self; + } + for (RLMSortDescriptor *descriptor in properties) { + if (!keypath_is_valid(descriptor.keyPath)) { + @throw RLMException(@"Invalid keypath specified. Use one of the constants defined in " + @" `RLMSyncPermissionSortProperty`."); + } + } + return translateRLMResultsErrors([&] { + auto sorted = _results.sort(RLMSortDescriptorsToKeypathArray(properties)); + return [[RLMSyncPermissionResults alloc] initWithResults:std::move(sorted)]; + }); +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wmismatched-parameter-types" +- (RLMNotificationToken *)addNotificationBlock:(void(^)(RLMSyncPermissionResults *results, + RLMCollectionChange *change, + NSError *error))block { + auto cb = [=](const realm::CollectionChangeSet& changes, std::exception_ptr ptr) { + if (ptr) { + NSError *error = translateSyncExceptionPtrToError(std::move(ptr), RLMPermissionActionTypeGet); + REALM_ASSERT(error); + block(nil, nil, error); + } else { + // Finished successfully + block(self, [[RLMCollectionChange alloc] initWithChanges:changes], nil); + } + }; + return [[RLMCancellationToken alloc] initWithToken:_results.add_notification_callback(std::move(cb)) realm:nil]; +} +#pragma clang diagnostic pop + +- (id)aggregate:(__unused NSString *)property + method:(__unused util::Optional (Results::*)(size_t))method + methodName:(__unused NSString *)methodName returnNilForEmpty:(__unused BOOL)returnNilForEmpty { + // We don't support any of the min/max/average/sum APIs; they don't make sense for this collection type. + return nil; +} + +- (id)valueForKey:(NSString *)key { + size_t count = self.count; + if (count == 0) { + return @[]; + } + NSMutableArray *results = [NSMutableArray arrayWithCapacity:count]; + if ([key isEqualToString:@"self"]) { + for (size_t i = 0; i < count; i++) { + [results addObject:[self objectAtIndex:i]]; + } + } else { + for (size_t i = 0; i < count; i++) { + [results addObject:[[self objectAtIndex:i] valueForKey:key] ?: NSNull.null]; + } + } + return results; +} + +- (void)setValue:(__unused id)value forKey:(__unused NSString *)key { + @throw RLMException(@"Cannot set values for the read-only type `RLMSyncPermission`."); +} + +#pragma mark - System + +- (RLMSchema *)schema { + if (!_schema) { + _schema = [RLMSchema dynamicSchemaFromObjectStoreSchema:_results.get_realm()->schema()]; + } + return _schema; +} + +- (RLMObjectSchema *)objectSchema { + if (!_objectSchema) { + _objectSchema = [RLMObjectSchema objectSchemaForObjectStoreSchema:_results.get_object_schema()]; + } + return _objectSchema; +} + +- (NSString *)description { + return RLMDescriptionWithMaxDepth(@"RLMSyncPermissionResults", self, 1); +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state + objects:(id __unsafe_unretained [])buffer + count:(NSUInteger)len { + // FIXME: It would be nice to have a shared fast enumeration implementation for `realm::Results`-only RLMResults. + NSUInteger thisSize = self.count; + if (state->state == 0) { + state->extra[0] = 0; + state->extra[1] = (long)thisSize; + state->state = 1; + } + NSUInteger objectsInBuffer = 0; + long idx = state->extra[0]; + if ((unsigned long)idx == thisSize) { + // finished + return 0; + } + state->itemsPtr = buffer; + state->mutationsPtr = state->extra + 1; + while (true) { + if (objectsInBuffer == len) { + // Buffer is full. + state->extra[0] = idx; + return objectsInBuffer; + } + if ((unsigned long)idx == thisSize) { + // finished + state->extra[0] = idx; + return objectsInBuffer; + } + // Otherwise, add an object and advance the index pointer. + RLMSyncPermission * __autoreleasing thisPermission = [self objectAtIndex:idx]; + buffer[objectsInBuffer] = thisPermission; + idx++; + objectsInBuffer++; + } +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncSession.mm b/Pods/Realm/Realm/RLMSyncSession.mm new file mode 100644 index 0000000000..ddfa0d1567 --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncSession.mm @@ -0,0 +1,246 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncSession_Private.hpp" + +#import "RLMRealm_Private.hpp" +#import "RLMSyncConfiguration_Private.hpp" +#import "RLMSyncUser_Private.hpp" +#import "RLMSyncUtil_Private.hpp" +#import "sync/sync_session.hpp" + +using namespace realm; + +@interface RLMSyncErrorActionToken () { +@public + std::string _originalPath; + BOOL _isValid; +} +@end + +@interface RLMProgressNotificationToken() { + uint64_t _token; + std::weak_ptr _session; +} +@end + +@implementation RLMProgressNotificationToken + +- (void)suppressNextNotification { + // No-op, but implemented in case this token is passed to + // `-[RLMRealm commitWriteTransactionWithoutNotifying:]`. +} + +- (void)invalidate { + if (auto session = _session.lock()) { + session->unregister_progress_notifier(_token); + _session.reset(); + _token = 0; + } +} + +- (void)dealloc { + if (_token != 0) { + NSLog(@"RLMProgressNotificationToken released without unregistering a notification. " + @"You must hold on to the RLMProgressNotificationToken and call " + @"-[RLMProgressNotificationToken invalidate] when you no longer wish to receive " + @"progress update notifications."); + } +} + +- (nullable instancetype)initWithTokenValue:(uint64_t)token + session:(std::shared_ptr)session { + if (token == 0) { + return nil; + } + if (self = [super init]) { + _token = token; + _session = session; + return self; + } + return nil; +} + +@end + +@interface RLMSyncSession () +@property (class, nonatomic, readonly) dispatch_queue_t notificationsQueue; +@property (atomic, readwrite) RLMSyncConnectionState connectionState; +@end + +@implementation RLMSyncSession + ++ (dispatch_queue_t)notificationsQueue { + static dispatch_queue_t queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + queue = dispatch_queue_create("io.realm.sync.sessionsNotificationQueue", DISPATCH_QUEUE_SERIAL); + }); + return queue; +} + +static RLMSyncConnectionState convertConnectionState(SyncSession::ConnectionState state) { + switch (state) { + case SyncSession::ConnectionState::Disconnected: return RLMSyncConnectionStateDisconnected; + case SyncSession::ConnectionState::Connecting: return RLMSyncConnectionStateConnecting; + case SyncSession::ConnectionState::Connected: return RLMSyncConnectionStateConnected; + } +} + +- (instancetype)initWithSyncSession:(std::shared_ptr const&)session { + if (self = [super init]) { + _session = session; + _connectionState = convertConnectionState(session->connection_state()); + // No need to save the token as RLMSyncSession always outlives the + // underlying SyncSession + session->register_connection_change_callback([=](auto, auto newState) { + self.connectionState = convertConnectionState(newState); + }); + return self; + } + return nil; +} + +- (RLMSyncConfiguration *)configuration { + if (auto session = _session.lock()) { + return [[RLMSyncConfiguration alloc] initWithRawConfig:session->config()]; + } + return nil; +} + +- (NSURL *)realmURL { + if (auto session = _session.lock()) { + if (auto url = session->full_realm_url()) { + return [NSURL URLWithString:@(url->c_str())]; + } + } + return nil; +} + +- (RLMSyncUser *)parentUser { + if (auto session = _session.lock()) { + return [[RLMSyncUser alloc] initWithSyncUser:session->user()]; + } + return nil; +} + +- (RLMSyncSessionState)state { + if (auto session = _session.lock()) { + if (session->state() == SyncSession::PublicState::Inactive) { + return RLMSyncSessionStateInactive; + } + return RLMSyncSessionStateActive; + } + return RLMSyncSessionStateInvalid; +} + +- (void)suspend { + if (auto session = _session.lock()) { + session->log_out(); + } +} + +- (void)resume { + if (auto session = _session.lock()) { + session->revive_if_needed(); + } +} + +- (BOOL)waitForUploadCompletionOnQueue:(dispatch_queue_t)queue callback:(void(^)(NSError *))callback { + if (auto session = _session.lock()) { + queue = queue ?: dispatch_get_main_queue(); + session->wait_for_upload_completion([=](std::error_code err) { + NSError *error = (err == std::error_code{}) ? nil : make_sync_error(err); + dispatch_async(queue, ^{ + callback(error); + }); + }); + return YES; + } + return NO; +} + +- (BOOL)waitForDownloadCompletionOnQueue:(dispatch_queue_t)queue callback:(void(^)(NSError *))callback { + if (auto session = _session.lock()) { + queue = queue ?: dispatch_get_main_queue(); + session->wait_for_download_completion([=](std::error_code err) { + NSError *error = (err == std::error_code{}) ? nil : make_sync_error(err); + dispatch_async(queue, ^{ + callback(error); + }); + }); + return YES; + } + return NO; +} + +- (RLMProgressNotificationToken *)addProgressNotificationForDirection:(RLMSyncProgressDirection)direction + mode:(RLMSyncProgressMode)mode + block:(RLMProgressNotificationBlock)block { + if (auto session = _session.lock()) { + dispatch_queue_t queue = RLMSyncSession.notificationsQueue; + auto notifier_direction = (direction == RLMSyncProgressDirectionUpload + ? SyncSession::NotifierType::upload + : SyncSession::NotifierType::download); + bool is_streaming = (mode == RLMSyncProgressModeReportIndefinitely); + uint64_t token = session->register_progress_notifier([=](uint64_t transferred, uint64_t transferrable) { + dispatch_async(queue, ^{ + block((NSUInteger)transferred, (NSUInteger)transferrable); + }); + }, notifier_direction, is_streaming); + return [[RLMProgressNotificationToken alloc] initWithTokenValue:token session:std::move(session)]; + } + return nil; +} + ++ (void)immediatelyHandleError:(RLMSyncErrorActionToken *)token { + if (!token->_isValid) { + return; + } + token->_isValid = NO; + SyncManager::shared().immediately_run_file_actions(std::move(token->_originalPath)); +} + ++ (nullable RLMSyncSession *)sessionForRealm:(RLMRealm *)realm { + auto& config = realm->_realm->config().sync_config; + if (!config) { + return nil; + } + auto path = SyncManager::shared().path_for_realm(*config->user, config->realm_url()); + if (auto session = config->user->session_for_on_disk_path(path)) { + return [[RLMSyncSession alloc] initWithSyncSession:session]; + } + return nil; +} + +@end + +// MARK: - Error action token + +@implementation RLMSyncErrorActionToken + +- (instancetype)initWithOriginalPath:(std::string)originalPath { + if (self = [super init]) { + _isValid = YES; + _originalPath = std::move(originalPath); + return self; + } + return nil; +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm b/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm new file mode 100644 index 0000000000..14ca9b33a4 --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm @@ -0,0 +1,274 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncSessionRefreshHandle.hpp" + +#import "RLMJSONModels.h" +#import "RLMNetworkClient.h" +#import "RLMSyncManager_Private.h" +#import "RLMSyncUser_Private.hpp" +#import "RLMSyncUtil_Private.hpp" +#import "RLMUtil.hpp" + +#import "sync/sync_session.hpp" + +using namespace realm; + +namespace { + +void unregisterRefreshHandle(const std::weak_ptr& user, const std::string& path) { + if (auto strong_user = user.lock()) { + context_for(strong_user).unregister_refresh_handle(path); + } +} + +void reportInvalidAccessToken(const std::weak_ptr& user, NSError *error) { + if (auto strong_user = user.lock()) { + if (RLMUserErrorReportingBlock block = context_for(strong_user).error_handler()) { + RLMSyncUser *theUser = [[RLMSyncUser alloc] initWithSyncUser:std::move(strong_user)]; + [theUser logOut]; + block(theUser, error); + } + } +} + +} + +static const NSTimeInterval RLMRefreshBuffer = 10; + +@interface RLMSyncSessionRefreshHandle () { + std::weak_ptr _user; + std::string _path; + std::weak_ptr _session; + std::shared_ptr _strongSession; +} + +@property (nonatomic) NSTimer *timer; + +@property (nonatomic) NSURL *realmURL; +@property (nonatomic) NSURL *authServerURL; +@property (nonatomic, copy) RLMSyncBasicErrorReportingBlock completionBlock; + +@end + +@implementation RLMSyncSessionRefreshHandle + +- (instancetype)initWithRealmURL:(NSURL *)realmURL + user:(std::shared_ptr)user + session:(std::shared_ptr)session + completionBlock:(RLMSyncBasicErrorReportingBlock)completionBlock { + if (self = [super init]) { + NSString *path = [realmURL path]; + _path = [path UTF8String]; + self.authServerURL = [NSURL URLWithString:@(user->server_url().c_str())]; + if (!self.authServerURL) { + @throw RLMException(@"User object isn't configured with an auth server URL."); + } + self.completionBlock = completionBlock; + self.realmURL = realmURL; + // For the initial bind, we want to prolong the session's lifetime. + _strongSession = std::move(session); + _session = _strongSession; + _user = user; + // Immediately fire off the network request. + [self _timerFired:nil]; + return self; + } + return nil; +} + +- (void)dealloc { + [self.timer invalidate]; +} + +- (void)invalidate { + _strongSession = nullptr; + [self.timer invalidate]; +} + ++ (NSDate *)fireDateForTokenExpirationDate:(NSDate *)date nowDate:(NSDate *)nowDate { + NSDate *fireDate = [date dateByAddingTimeInterval:-RLMRefreshBuffer]; + // Only fire times in the future are valid. + return ([fireDate compare:nowDate] == NSOrderedDescending ? fireDate : nil); +} + +- (void)scheduleRefreshTimer:(NSDate *)dateWhenTokenExpires { + // Schedule the timer on the main queue. + // It's very likely that this method will be run on a side thread, for example + // on the thread that runs `NSURLSession`'s completion blocks. We can't be + // guaranteed that there's an existing runloop on those threads, and we don't want + // to create and start a new one if one doesn't already exist. + dispatch_async(dispatch_get_main_queue(), ^{ + [self.timer invalidate]; + NSDate *fireDate = [RLMSyncSessionRefreshHandle fireDateForTokenExpirationDate:dateWhenTokenExpires + nowDate:[NSDate date]]; + if (!fireDate) { + unregisterRefreshHandle(_user, _path); + return; + } + self.timer = [[NSTimer alloc] initWithFireDate:fireDate + interval:0 + target:self + selector:@selector(_timerFired:) + userInfo:nil + repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode]; + }); +} + +/// Handler for network requests whose responses successfully parse into an auth response model. +- (BOOL)_handleSuccessfulRequest:(RLMAuthResponseModel *)model { + std::shared_ptr session = _session.lock(); + if (!session) { + // The session is dead or in a fatal error state. + unregisterRefreshHandle(_user, _path); + [self invalidate]; + return NO; + } + + // Calculate the resolved path. + NSString *resolvedURLString = nil; + RLMServerPath resolvedPath = model.accessToken.tokenData.path; + // Munge the path back onto the original URL, because the `sync` API expects an entire URL. + NSURLComponents *urlBuffer = [NSURLComponents componentsWithURL:self.realmURL + resolvingAgainstBaseURL:YES]; + urlBuffer.path = resolvedPath; + resolvedURLString = [[urlBuffer URL] absoluteString]; + if (!resolvedURLString) { + @throw RLMException(@"Resolved path returned from the server was invalid (%@).", resolvedPath); + } + // Pass the token and resolved path to the underlying sync subsystem. + session->refresh_access_token([model.accessToken.token UTF8String], {resolvedURLString.UTF8String}); + + // Schedule a refresh. If we're successful we must already have `bind()`ed the session + // initially, so we can null out the strong pointer. + _strongSession = nullptr; + NSDate *expires = [NSDate dateWithTimeIntervalSince1970:model.accessToken.tokenData.expires]; + [self scheduleRefreshTimer:expires]; + + if (self.completionBlock) { + self.completionBlock(nil); + } + return true; +} + +/// Handler for network requests that failed before the JSON parsing stage. +- (void)_handleFailedRequest:(NSError *)error { + NSError *authError; + if ([error.domain isEqualToString:RLMSyncAuthErrorDomain]) { + // Network client may return sync related error + authError = error; + // Try to report this error to the expiration callback. + reportInvalidAccessToken(_user, authError); + } else { + // Something else went wrong + authError = make_auth_error_bad_response(); + } + if (self.completionBlock) { + self.completionBlock(authError); + } + [[RLMSyncManager sharedManager] _fireError:make_sync_error(authError)]; + // Certain errors related to network connectivity should trigger a retry. + NSDate *nextTryDate = nil; + if ([error.domain isEqualToString:NSURLErrorDomain]) { + switch (error.code) { + case NSURLErrorCannotConnectToHost: + case NSURLErrorNotConnectedToInternet: + case NSURLErrorNetworkConnectionLost: + case NSURLErrorTimedOut: + case NSURLErrorDNSLookupFailed: + case NSURLErrorCannotFindHost: + // FIXME: 10 seconds is an arbitrarily chosen value, consider rationalizing it. + nextTryDate = [NSDate dateWithTimeIntervalSinceNow:RLMRefreshBuffer + 10]; + break; + default: + break; + } + } + if (!nextTryDate) { + // This error isn't a network failure error. Just invalidate the refresh handle and stop. + if (_strongSession) { + _strongSession->log_out(); + } + unregisterRefreshHandle(_user, _path); + [self invalidate]; + return; + } + // If we tried to initially bind the session and failed, we'll try again. However, each + // subsequent attempt will use a weak pointer to avoid prolonging the session's lifetime + // unnecessarily. + _strongSession = nullptr; + [self scheduleRefreshTimer:nextTryDate]; + return; +} + +/// Callback handler for network requests. +- (BOOL)_onRefreshCompletionWithError:(NSError *)error json:(NSDictionary *)json { + if (json && !error) { + RLMAuthResponseModel *model = [[RLMAuthResponseModel alloc] initWithDictionary:json + requireAccessToken:YES + requireRefreshToken:NO]; + if (model) { + return [self _handleSuccessfulRequest:model]; + } + // Otherwise, malformed JSON + unregisterRefreshHandle(_user, _path); + [self.timer invalidate]; + NSError *error = make_sync_error(make_auth_error_bad_response(json)); + if (self.completionBlock) { + self.completionBlock(error); + } + [[RLMSyncManager sharedManager] _fireError:error]; + } else { + REALM_ASSERT(error); + [self _handleFailedRequest:error]; + } + return NO; +} + +- (void)_timerFired:(__unused NSTimer *)timer { + RLMServerToken refreshToken = nil; + if (auto user = _user.lock()) { + refreshToken = @(user->refresh_token().c_str()); + } + if (!refreshToken) { + unregisterRefreshHandle(_user, _path); + [self.timer invalidate]; + return; + } + + NSDictionary *json = @{ + kRLMSyncProviderKey: @"realm", + kRLMSyncPathKey: @(_path.c_str()), + kRLMSyncDataKey: refreshToken, + kRLMSyncAppIDKey: [RLMSyncManager sharedManager].appID, + }; + + __weak RLMSyncSessionRefreshHandle *weakSelf = self; + RLMSyncCompletionBlock handler = ^(NSError *error, NSDictionary *json) { + [weakSelf _onRefreshCompletionWithError:error json:json]; + }; + [RLMNetworkClient sendRequestToEndpoint:[RLMSyncAuthEndpoint endpoint] + server:self.authServerURL + JSON:json + timeout:60 + options:[[RLMSyncManager sharedManager] networkRequestOptions] + completion:handler]; +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncSubscription.mm b/Pods/Realm/Realm/RLMSyncSubscription.mm new file mode 100644 index 0000000000..769fb95299 --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncSubscription.mm @@ -0,0 +1,106 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2018 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncSubscription.h" + +#import "RLMRealm_Private.hpp" +#import "RLMResults_Private.hpp" +#import "RLMUtil.hpp" + +#import "sync/partial_sync.hpp" + +using namespace realm; + +@interface RLMSyncSubscription () +- (instancetype)initWithName:(NSString *)name results:(Results const&)results realm:(RLMRealm *)realm; + +@property (nonatomic, readwrite) RLMSyncSubscriptionState state; +@property (nonatomic, readwrite, nullable) NSError *error; +@end + +@implementation RLMSyncSubscription { + partial_sync::SubscriptionNotificationToken _token; + util::Optional _subscription; + RLMRealm *_realm; +} + +- (instancetype)initWithName:(NSString *)name results:(Results const&)results realm:(RLMRealm *)realm { + if (!(self = [super init])) + return nil; + + _name = [name copy]; + _realm = realm; + _subscription = partial_sync::subscribe(results, name ? util::make_optional(name.UTF8String) : util::none); + self.state = (RLMSyncSubscriptionState)_subscription->state(); + __weak RLMSyncSubscription *weakSelf = self; + _token = _subscription->add_notification_callback([weakSelf] { + RLMSyncSubscription *self = weakSelf; + if (!self) + return; + + // Retrieve the current error and status. Update our properties only if the values have changed, + // since clients use KVO to observe these properties. + + if (auto error = self->_subscription->error()) { + try { + std::rethrow_exception(error); + } catch (...) { + NSError *nsError; + RLMRealmTranslateException(&nsError); + if (!self.error || ![self.error isEqual:nsError]) + self.error = nsError; + } + } + else if (self.error) { + self.error = nil; + } + + auto status = (RLMSyncSubscriptionState)self->_subscription->state(); + if (status != self.state) + self.state = (RLMSyncSubscriptionState)status; + }); + + return self; +} + +- (void)unsubscribe { + partial_sync::unsubscribe(*_subscription); +} + +- (RLMResults *)results { + auto results = _subscription->results(); + return [RLMResults resultsWithObjectInfo:_realm->_info[RLMStringDataToNSString(results.get_object_type())] + results:std::move(results)]; +} +@end + +@implementation RLMResults (SyncSubscription) + +- (RLMSyncSubscription *)subscribe { + return [[RLMSyncSubscription alloc] initWithName:nil results:_results realm:self.realm]; +} + +- (RLMSyncSubscription *)subscribeWithName:(NSString *)subscriptionName { + return [[RLMSyncSubscription alloc] initWithName:subscriptionName results:_results realm:self.realm]; +} + +- (RLMSyncSubscription *)subscribeWithName:(NSString *)subscriptionName limit:(NSUInteger)limit { + return [[RLMSyncSubscription alloc] initWithName:subscriptionName results:_results.limit(limit) realm:self.realm]; +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncUser.mm b/Pods/Realm/Realm/RLMSyncUser.mm new file mode 100644 index 0000000000..63d14ac628 --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncUser.mm @@ -0,0 +1,683 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncUser_Private.hpp" + +#import "RLMJSONModels.h" +#import "RLMNetworkClient.h" +#import "RLMRealmConfiguration+Sync.h" +#import "RLMRealmConfiguration_Private.hpp" +#import "RLMRealmUtil.hpp" +#import "RLMResults_Private.hpp" +#import "RLMSyncConfiguration.h" +#import "RLMSyncConfiguration_Private.hpp" +#import "RLMSyncManager_Private.h" +#import "RLMSyncPermissionResults.h" +#import "RLMSyncPermission_Private.hpp" +#import "RLMSyncSessionRefreshHandle.hpp" +#import "RLMSyncSession_Private.hpp" +#import "RLMSyncUtil_Private.hpp" +#import "RLMUtil.hpp" + +#import "sync/sync_manager.hpp" +#import "sync/sync_session.hpp" +#import "sync/sync_user.hpp" + +using namespace realm; +using ConfigMaker = std::function, std::string)>; + +namespace { + +std::function RLMWrapPermissionResultsCallback(RLMPermissionResultsBlock callback) { + return [callback](Results results, std::exception_ptr ptr) { + if (ptr) { + NSError *error = translateSyncExceptionPtrToError(std::move(ptr), RLMPermissionActionTypeGet); + REALM_ASSERT(error); + callback(nil, error); + } else { + // Finished successfully + callback([[RLMSyncPermissionResults alloc] initWithResults:std::move(results)], nil); + } + }; +} + +NSString *tildeSubstitutedPathForRealmURL(NSURL *url, NSString *identity) { + return [[url path] stringByReplacingOccurrencesOfString:@"~" withString:identity]; +} + +} + +void CocoaSyncUserContext::register_refresh_handle(const std::string& path, RLMSyncSessionRefreshHandle *handle) +{ + REALM_ASSERT(handle); + std::lock_guard lock(m_mutex); + auto it = m_refresh_handles.find(path); + if (it != m_refresh_handles.end()) { + [it->second invalidate]; + m_refresh_handles.erase(it); + } + m_refresh_handles.insert({path, handle}); +} + +void CocoaSyncUserContext::unregister_refresh_handle(const std::string& path) +{ + std::lock_guard lock(m_mutex); + m_refresh_handles.erase(path); +} + +void CocoaSyncUserContext::invalidate_all_handles() +{ + std::lock_guard lock(m_mutex); + for (auto& it : m_refresh_handles) { + [it.second invalidate]; + } + m_refresh_handles.clear(); +} + +RLMUserErrorReportingBlock CocoaSyncUserContext::error_handler() const +{ + std::lock_guard lock(m_error_handler_mutex); + return m_error_handler; +} + +void CocoaSyncUserContext::set_error_handler(RLMUserErrorReportingBlock block) +{ + std::lock_guard lock(m_error_handler_mutex); + m_error_handler = block; +} + +PermissionChangeCallback RLMWrapPermissionStatusCallback(RLMPermissionStatusBlock callback) { + return [callback](std::exception_ptr ptr) { + if (ptr) { + NSError *error = translateSyncExceptionPtrToError(std::move(ptr), RLMPermissionActionTypeChange); + REALM_ASSERT(error); + callback(error); + } else { + // Finished successfully + callback(nil); + } + }; +} + +@interface RLMSyncUserInfo () + +@property (nonatomic, readwrite) NSArray *accounts; +@property (nonatomic, readwrite) NSDictionary *metadata; +@property (nonatomic, readwrite) NSString *identity; +@property (nonatomic, readwrite) BOOL isAdmin; + ++ (instancetype)syncUserInfoWithModel:(RLMUserResponseModel *)model; + +@end + +@interface RLMSyncUser () { + std::shared_ptr _user; + // FIXME: remove this when the object store ConfigMaker goes away + std::unique_ptr _configMaker; +} + +- (instancetype)initPrivate NS_DESIGNATED_INITIALIZER; + +@end + +@implementation RLMSyncUser + +#pragma mark - static API + ++ (NSDictionary *)allUsers { + NSArray *allUsers = [[RLMSyncManager sharedManager] _allUsers]; + return [NSDictionary dictionaryWithObjects:allUsers + forKeys:[allUsers valueForKey:@"identity"]]; +} + ++ (RLMSyncUser *)currentUser { + NSArray *allUsers = [[RLMSyncManager sharedManager] _allUsers]; + if (allUsers.count > 1) { + @throw RLMException(@"+currentUser cannot be called if more that one valid, logged-in user exists."); + } + return allUsers.firstObject; +} + +#pragma mark - API + +- (instancetype)initPrivate { + if (self = [super init]) { + _configMaker = std::make_unique([](std::shared_ptr user, std::string url) { + NSURL *objCUrl = [NSURL URLWithString:@(url.c_str())]; + RLMSyncUser *objCUser = [[RLMSyncUser alloc] initWithSyncUser:std::move(user)]; + return [objCUser configurationWithURL:objCUrl fullSynchronization:true].config; + }); + return self; + } + return nil; +} + +- (instancetype)initWithSyncUser:(std::shared_ptr)user { + if (self = [self initPrivate]) { + _user = user; + return self; + } + return nil; +} + +- (BOOL)isEqual:(id)object { + if (![object isKindOfClass:[RLMSyncUser class]]) { + return NO; + } + return _user == ((RLMSyncUser *)object)->_user; +} + ++ (void)logInWithCredentials:(RLMSyncCredentials *)credential + authServerURL:(NSURL *)authServerURL + onCompletion:(RLMUserCompletionBlock)completion { + [self logInWithCredentials:credential + authServerURL:authServerURL + timeout:30 + callbackQueue:dispatch_get_main_queue() + onCompletion:completion]; +} + ++ (void)logInWithCredentials:(RLMSyncCredentials *)credential + authServerURL:(NSURL *)authServerURL + timeout:(NSTimeInterval)timeout + callbackQueue:(dispatch_queue_t)callbackQueue + onCompletion:(RLMUserCompletionBlock)completion { + RLMSyncUser *user = [[RLMSyncUser alloc] initPrivate]; + [RLMSyncUser _performLogInForUser:user + credentials:credential + authServerURL:authServerURL + timeout:timeout + callbackQueue:callbackQueue + completionBlock:completion]; +} + +- (RLMRealmConfiguration *)configuration { + return [self configurationWithURL:nil + fullSynchronization:NO + enableSSLValidation:YES + urlPrefix:nil]; +} + +- (RLMRealmConfiguration *)configurationWithURL:(NSURL *)url { + return [self configurationWithURL:url + fullSynchronization:NO + enableSSLValidation:YES + urlPrefix:nil]; +} + +- (RLMRealmConfiguration *)configurationWithURL:(NSURL *)url fullSynchronization:(bool)fullSynchronization { + return [self configurationWithURL:url + fullSynchronization:fullSynchronization + enableSSLValidation:YES + urlPrefix:nil]; +} + +- (RLMRealmConfiguration *)configurationWithURL:(NSURL *)url + fullSynchronization:(bool)fullSynchronization + enableSSLValidation:(bool)enableSSLValidation + urlPrefix:(NSString * _Nullable)urlPrefix { + auto syncConfig = [[RLMSyncConfiguration alloc] initWithUser:self + realmURL:url ?: self.defaultRealmURL + customFileURL:nil + isPartial:!fullSynchronization + stopPolicy:RLMSyncStopPolicyAfterChangesUploaded + errorHandler:nullptr]; + syncConfig.urlPrefix = urlPrefix; + syncConfig.enableSSLValidation = enableSSLValidation; + syncConfig.pinnedCertificateURL = RLMSyncManager.sharedManager.pinnedCertificatePaths[syncConfig.realmURL.host]; + RLMRealmConfiguration *config = [[RLMRealmConfiguration alloc] init]; + config.syncConfiguration = syncConfig; + return config; +} + +- (void)logOut { + if (!_user) { + return; + } + _user->log_out(); + context_for(_user).invalidate_all_handles(); +} + +- (RLMUserErrorReportingBlock)errorHandler { + if (!_user) { + return nil; + } + return context_for(_user).error_handler(); +} + +- (void)setErrorHandler:(RLMUserErrorReportingBlock)errorHandler { + if (!_user) { + return; + } + context_for(_user).set_error_handler([errorHandler copy]); +} + +- (nullable RLMSyncSession *)sessionForURL:(NSURL *)url { + if (!_user) { + return nil; + } + auto path = SyncManager::shared().path_for_realm(*_user, [url.absoluteString UTF8String]); + if (auto session = _user->session_for_on_disk_path(path)) { + return [[RLMSyncSession alloc] initWithSyncSession:session]; + } + return nil; +} + +- (NSArray *)allSessions { + if (!_user) { + return @[]; + } + NSMutableArray *buffer = [NSMutableArray array]; + auto sessions = _user->all_sessions(); + for (auto session : sessions) { + [buffer addObject:[[RLMSyncSession alloc] initWithSyncSession:std::move(session)]]; + } + return [buffer copy]; +} + +- (NSString *)identity { + if (!_user) { + return nil; + } + return @(_user->identity().c_str()); +} + +- (RLMSyncUserState)state { + if (!_user) { + return RLMSyncUserStateError; + } + switch (_user->state()) { + case SyncUser::State::Active: + return RLMSyncUserStateActive; + case SyncUser::State::LoggedOut: + return RLMSyncUserStateLoggedOut; + case SyncUser::State::Error: + return RLMSyncUserStateError; + } +} + +- (NSURL *)authenticationServer { + if (!_user || _user->token_type() == SyncUser::TokenType::Admin) { + return nil; + } + return [NSURL URLWithString:@(_user->server_url().c_str())]; +} + +- (BOOL)isAdmin { + if (!_user) { + return NO; + } + return _user->is_admin(); +} + +#pragma mark - Passwords + +- (void)changePassword:(NSString *)newPassword completion:(RLMPasswordChangeStatusBlock)completion { + [self changePassword:newPassword forUserID:self.identity completion:completion]; +} + +- (void)changePassword:(NSString *)newPassword forUserID:(NSString *)userID completion:(RLMPasswordChangeStatusBlock)completion { + if (self.state != RLMSyncUserStateActive) { + completion([NSError errorWithDomain:RLMSyncErrorDomain + code:RLMSyncErrorClientSessionError + userInfo:nil]); + return; + } + [RLMSyncChangePasswordEndpoint sendRequestToServer:self.authenticationServer + JSON:@{kRLMSyncTokenKey: self.refreshToken, + kRLMSyncUserIDKey: userID, + kRLMSyncDataKey: @{kRLMSyncNewPasswordKey: newPassword}} + options:[[RLMSyncManager sharedManager] networkRequestOptions] + completion:completion]; +} + ++ (void)requestPasswordResetForAuthServer:(NSURL *)serverURL + userEmail:(NSString *)email + completion:(RLMPasswordChangeStatusBlock)completion { + [RLMSyncUpdateAccountEndpoint sendRequestToServer:serverURL + JSON:@{@"provider_id": email, @"data": @{@"action": @"reset_password"}} + options:[[RLMSyncManager sharedManager] networkRequestOptions] + completion:completion]; +} + ++ (void)completePasswordResetForAuthServer:(NSURL *)serverURL + token:(NSString *)token + password:(NSString *)newPassword + completion:(RLMPasswordChangeStatusBlock)completion { + [RLMSyncUpdateAccountEndpoint sendRequestToServer:serverURL + JSON:@{@"data": @{@"action": @"complete_reset", + @"token": token, + @"new_password": newPassword}} + options:[[RLMSyncManager sharedManager] networkRequestOptions] + completion:completion]; +} + ++ (void)requestEmailConfirmationForAuthServer:(NSURL *)serverURL + userEmail:(NSString *)email + completion:(RLMPasswordChangeStatusBlock)completion { + [RLMSyncUpdateAccountEndpoint sendRequestToServer:serverURL + JSON:@{@"provider_id": email, @"data": @{@"action": @"request_email_confirmation"}} + options:[[RLMSyncManager sharedManager] networkRequestOptions] + completion:completion]; +} + ++ (void)confirmEmailForAuthServer:(NSURL *)serverURL + token:(NSString *)token + completion:(RLMPasswordChangeStatusBlock)completion { + [RLMSyncUpdateAccountEndpoint sendRequestToServer:serverURL + JSON:@{@"data": @{@"action": @"confirm_email", + @"token": token}} + options:[[RLMSyncManager sharedManager] networkRequestOptions] + completion:completion]; +} + +#pragma mark - Administrator API + +- (void)retrieveInfoForUser:(NSString *)providerUserIdentity + identityProvider:(RLMIdentityProvider)provider + completion:(RLMRetrieveUserBlock)completion { + [RLMNetworkClient sendRequestToEndpoint:[RLMSyncGetUserInfoEndpoint endpoint] + server:self.authenticationServer + JSON:@{ + kRLMSyncProviderKey: provider, + kRLMSyncProviderIDKey: providerUserIdentity, + kRLMSyncTokenKey: self.refreshToken + } + timeout:60 + options:[[RLMSyncManager sharedManager] networkRequestOptions] + completion:^(NSError *error, NSDictionary *json) { + if (error) { + completion(nil, error); + return; + } + RLMUserResponseModel *model = [[RLMUserResponseModel alloc] initWithDictionary:json]; + if (!model) { + completion(nil, make_auth_error_bad_response(json)); + return; + } + completion([RLMSyncUserInfo syncUserInfoWithModel:model], nil); + }]; +} + +#pragma mark - Permissions API + +static void verifyInRunLoop() { + if (!RLMIsInRunLoop()) { + @throw RLMException(@"Can only access or modify permissions from a thread which has a run loop (by default, only the main thread)."); + } +} + +- (void)retrievePermissionsWithCallback:(RLMPermissionResultsBlock)callback { + verifyInRunLoop(); + if (!_user || _user->state() == SyncUser::State::Error) { + callback(nullptr, make_permission_error_get(@"Permissions cannot be retrieved using an invalid user.")); + return; + } + Permissions::get_permissions(_user, RLMWrapPermissionResultsCallback(callback), *_configMaker); +} + +- (void)applyPermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback { + verifyInRunLoop(); + if (!_user || _user->state() == SyncUser::State::Error) { + callback(make_permission_error_change(@"Permissions cannot be applied using an invalid user.")); + return; + } + Permissions::set_permission(_user, + [permission rawPermission], + RLMWrapPermissionStatusCallback(callback), + *_configMaker); +} + +- (void)revokePermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback { + verifyInRunLoop(); + if (!_user || _user->state() == SyncUser::State::Error) { + callback(make_permission_error_change(@"Permissions cannot be revoked using an invalid user.")); + return; + } + Permissions::delete_permission(_user, + [permission rawPermission], + RLMWrapPermissionStatusCallback(callback), + *_configMaker); +} + +- (void)createOfferForRealmAtURL:(NSURL *)url + accessLevel:(RLMSyncAccessLevel)accessLevel + expiration:(NSDate *)expirationDate + callback:(RLMPermissionOfferStatusBlock)callback { + verifyInRunLoop(); + if (!_user || _user->state() == SyncUser::State::Error) { + callback(nil, make_permission_error_change(@"A permission offer cannot be created using an invalid user.")); + return; + } + auto cb = [callback](util::Optional token, std::exception_ptr ptr) { + if (ptr) { + NSError *error = translateSyncExceptionPtrToError(std::move(ptr), RLMPermissionActionTypeOffer); + REALM_ASSERT_DEBUG(error); + callback(nil, error); + } else { + REALM_ASSERT_DEBUG(token); + callback(@(token->c_str()), nil); + } + }; + auto offer = PermissionOffer{ + [tildeSubstitutedPathForRealmURL(url, self.identity) UTF8String], + accessLevelForObjCAccessLevel(accessLevel), + RLMTimestampForNSDate(expirationDate), + }; + Permissions::make_offer(_user, std::move(offer), std::move(cb), *_configMaker); +} + +- (void)acceptOfferForToken:(NSString *)token + callback:(RLMPermissionOfferResponseStatusBlock)callback { + verifyInRunLoop(); + if (!_user || _user->state() == SyncUser::State::Error) { + callback(nil, make_permission_error_change(@"A permission offer cannot be accepted by an invalid user.")); + return; + } + NSURLComponents *baseURL = [NSURLComponents componentsWithURL:self.authenticationServer + resolvingAgainstBaseURL:YES]; + if ([baseURL.scheme isEqualToString:@"http"]) { + baseURL.scheme = @"realm"; + } else if ([baseURL.scheme isEqualToString:@"https"]) { + baseURL.scheme = @"realms"; + } + auto cb = [baseURL, callback](util::Optional raw_path, std::exception_ptr ptr) { + if (ptr) { + NSError *error = translateSyncExceptionPtrToError(std::move(ptr), RLMPermissionActionTypeAcceptOffer); + REALM_ASSERT_DEBUG(error); + callback(nil, error); + } else { + // Note that ROS currently vends the path to the Realm, so we need to construct the full URL ourselves. + REALM_ASSERT_DEBUG(raw_path); + baseURL.path = @(raw_path->c_str()); + callback([baseURL URL], nil); + } + }; + Permissions::accept_offer(_user, [token UTF8String], std::move(cb), *_configMaker); +} + +#pragma mark - Private API + +- (NSURL *)defaultRealmURL +{ + NSURLComponents *components = [NSURLComponents componentsWithURL:self.authenticationServer resolvingAgainstBaseURL:YES]; + if ([components.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame) + components.scheme = @"realm"; + else if ([components.scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) + components.scheme = @"realms"; + else + @throw RLMException(@"The provided user's authentication server URL (%@) was not valid.", self.authenticationServer); + + components.path = @"/default"; + return components.URL; +} + ++ (void)_setUpBindingContextFactory { + SyncUser::set_binding_context_factory([] { + return std::make_shared(); + }); +} + +- (NSString *)refreshToken { + if (!_user) { + return nil; + } + return @(_user->refresh_token().c_str()); +} + +- (std::shared_ptr)_syncUser { + return _user; +} + ++ (void)_performLogInForUser:(RLMSyncUser *)user + credentials:(RLMSyncCredentials *)credentials + authServerURL:(NSURL *)authServerURL + timeout:(NSTimeInterval)timeout + callbackQueue:(dispatch_queue_t)callbackQueue + completionBlock:(RLMUserCompletionBlock)completion { + // Special credential login should be treated differently. + if (credentials.provider == RLMIdentityProviderAccessToken) { + [self _performLoginForDirectAccessTokenCredentials:credentials + user:user + authServerURL:authServerURL + completionBlock:completion]; + return; + } + if (!authServerURL) { + @throw RLMException(@"A user cannot be logged in without specifying an authentication server URL."); + } + + // Prepare login network request + NSMutableDictionary *json = [@{ + kRLMSyncProviderKey: credentials.provider, + kRLMSyncDataKey: credentials.token, + kRLMSyncAppIDKey: [RLMSyncManager sharedManager].appID, + } mutableCopy]; + NSMutableDictionary *info = [(credentials.userInfo ?: @{}) mutableCopy]; + + if ([info count] > 0) { + // Munge user info into the JSON request. + json[@"user_info"] = info; + } + + RLMSyncCompletionBlock handler = ^(NSError *error, NSDictionary *json) { + if (json && !error) { + RLMAuthResponseModel *model = [[RLMAuthResponseModel alloc] initWithDictionary:json + requireAccessToken:NO + requireRefreshToken:YES]; + if (!model) { + // Malformed JSON + NSError *badResponseError = make_auth_error_bad_response(json); + dispatch_async(callbackQueue, ^{ + completion(nil, badResponseError); + }); + return; + } else { + std::string server_url = authServerURL.absoluteString.UTF8String; + SyncUserIdentifier identity{[model.refreshToken.tokenData.identity UTF8String], std::move(server_url)}; + auto sync_user = SyncManager::shared().get_user(identity , [model.refreshToken.token UTF8String]); + if (!sync_user) { + NSError *authError = make_auth_error_client_issue(); + dispatch_async(callbackQueue, ^{ + completion(nil, authError); + }); + return; + } + sync_user->set_is_admin(model.refreshToken.tokenData.isAdmin); + user->_user = sync_user; + dispatch_async(callbackQueue, ^{ + completion(user, nil); + }); + } + } else { + // Something else went wrong + dispatch_async(callbackQueue, ^{ + completion(nil, error); + }); + } + }; + + [RLMNetworkClient sendRequestToEndpoint:[RLMSyncAuthEndpoint endpoint] + server:authServerURL + JSON:json + timeout:timeout + options:[[RLMSyncManager sharedManager] networkRequestOptions] + completion:^(NSError *error, NSDictionary *dictionary) { + dispatch_async(callbackQueue, ^{ + handler(error, dictionary); + }); + }]; +} + ++ (void)_performLoginForDirectAccessTokenCredentials:(RLMSyncCredentials *)credentials + user:(RLMSyncUser *)user + authServerURL:(NSURL *)serverURL + completionBlock:(nonnull RLMUserCompletionBlock)completion { + NSString *identity = credentials.userInfo[kRLMSyncIdentityKey]; + std::shared_ptr sync_user; + if (serverURL) { + NSString *scheme = serverURL.scheme; + if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) { + @throw RLMException(@"The Realm Object Server authentication URL provided for this user, \"%@\", " + @" is invalid. It must begin with http:// or https://.", serverURL); + } + // Retrieve the user based on the auth server URL. + util::Optional identity_string; + if (identity) { + identity_string = std::string(identity.UTF8String); + } + sync_user = SyncManager::shared().get_admin_token_user([serverURL absoluteString].UTF8String, + credentials.token.UTF8String, + std::move(identity_string)); + } else { + // Retrieve the user based on the identity. + if (!identity) { + @throw RLMException(@"A direct access credential must specify either an identity, a server URL, or both."); + } + sync_user = SyncManager::shared().get_admin_token_user_from_identity(identity.UTF8String, + none, + credentials.token.UTF8String); + } + if (!sync_user) { + completion(nil, make_auth_error_client_issue()); + return; + } + user->_user = sync_user; + completion(user, nil); +} + +@end + +#pragma mark - RLMSyncUserInfo + +@implementation RLMSyncUserInfo + +- (instancetype)initPrivate { + return [super init]; +} + ++ (instancetype)syncUserInfoWithModel:(RLMUserResponseModel *)model { + RLMSyncUserInfo *info = [[RLMSyncUserInfo alloc] initPrivate]; + info.accounts = model.accounts; + info.metadata = model.metadata; + info.isAdmin = model.isAdmin; + info.identity = model.identity; + return info; +} + +@end diff --git a/Pods/Realm/Realm/RLMSyncUtil.mm b/Pods/Realm/Realm/RLMSyncUtil.mm new file mode 100644 index 0000000000..46c90c597b --- /dev/null +++ b/Pods/Realm/Realm/RLMSyncUtil.mm @@ -0,0 +1,269 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncUtil_Private.hpp" + +#import "RLMJSONModels.h" +#import "RLMObject_Private.hpp" +#import "RLMRealmConfiguration+Sync.h" +#import "RLMRealmConfiguration_Private.hpp" +#import "RLMRealm_Private.hpp" +#import "RLMSyncConfiguration_Private.hpp" +#import "RLMSyncUser_Private.hpp" +#import "RLMUtil.hpp" + +#import "shared_realm.hpp" + +#import "sync/sync_permission.hpp" +#import "sync/sync_user.hpp" + +RLMIdentityProvider const RLMIdentityProviderAccessToken = @"_access_token"; + +NSString *const RLMSyncErrorDomain = @"io.realm.sync"; +NSString *const RLMSyncAuthErrorDomain = @"io.realm.sync.auth"; +NSString *const RLMSyncPermissionErrorDomain = @"io.realm.sync.permission"; + +NSString *const kRLMSyncPathOfRealmBackupCopyKey = @"recovered_realm_location_path"; +NSString *const kRLMSyncErrorActionTokenKey = @"error_action_token"; + +NSString *const kRLMSyncAppIDKey = @"app_id"; +NSString *const kRLMSyncDataKey = @"data"; +NSString *const kRLMSyncErrorJSONKey = @"json"; +NSString *const kRLMSyncErrorStatusCodeKey = @"statusCode"; +NSString *const kRLMSyncIdentityKey = @"identity"; +NSString *const kRLMSyncIsAdminKey = @"is_admin"; +NSString *const kRLMSyncNewPasswordKey = @"new_password"; +NSString *const kRLMSyncPasswordKey = @"password"; +NSString *const kRLMSyncPathKey = @"path"; +NSString *const kRLMSyncProviderKey = @"provider"; +NSString *const kRLMSyncProviderIDKey = @"provider_id"; +NSString *const kRLMSyncRegisterKey = @"register"; +NSString *const kRLMSyncTokenKey = @"token"; +NSString *const kRLMSyncUnderlyingErrorKey = @"underlying_error"; +NSString *const kRLMSyncUserIDKey = @"user_id"; + +uint8_t RLMGetComputedPermissions(RLMRealm *realm, id _Nullable object) { + if (!object) { + return static_cast(realm->_realm->get_privileges()); + } + if ([object isKindOfClass:[NSString class]]) { + return static_cast(realm->_realm->get_privileges([object UTF8String])); + } + if (auto obj = RLMDynamicCast(object)) { + RLMVerifyAttached(obj); + return static_cast(realm->_realm->get_privileges(obj->_row)); + } + return 0; +} + +#pragma mark - C++ APIs + +namespace { + +NSError *make_permission_error(NSString *description, util::Optional code, RLMSyncPermissionError type) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (description) { + userInfo[NSLocalizedDescriptionKey] = description; + } + if (code) { + userInfo[kRLMSyncErrorStatusCodeKey] = @(*code); + } + return [NSError errorWithDomain:RLMSyncPermissionErrorDomain code:type userInfo:userInfo]; +} + +} + +SyncSessionStopPolicy translateStopPolicy(RLMSyncStopPolicy stopPolicy) { + switch (stopPolicy) { + case RLMSyncStopPolicyImmediately: return SyncSessionStopPolicy::Immediately; + case RLMSyncStopPolicyLiveIndefinitely: return SyncSessionStopPolicy::LiveIndefinitely; + case RLMSyncStopPolicyAfterChangesUploaded: return SyncSessionStopPolicy::AfterChangesUploaded; + } + REALM_UNREACHABLE(); // Unrecognized stop policy. +} + +RLMSyncStopPolicy translateStopPolicy(SyncSessionStopPolicy stop_policy) { + switch (stop_policy) { + case SyncSessionStopPolicy::Immediately: return RLMSyncStopPolicyImmediately; + case SyncSessionStopPolicy::LiveIndefinitely: return RLMSyncStopPolicyLiveIndefinitely; + case SyncSessionStopPolicy::AfterChangesUploaded: return RLMSyncStopPolicyAfterChangesUploaded; + } + REALM_UNREACHABLE(); +} + +NSError *translateSyncExceptionPtrToError(std::exception_ptr ptr, RLMPermissionActionType type) { + NSError *error = nil; + try { + std::rethrow_exception(ptr); + } catch (PermissionActionException const& ex) { + switch (type) { + case RLMPermissionActionTypeGet: + error = make_permission_error_get(@(ex.what()), ex.code); + break; + case RLMPermissionActionTypeChange: + error = make_permission_error_change(@(ex.what()), ex.code); + break; + case RLMPermissionActionTypeOffer: + error = make_permission_error_offer(@(ex.what()), ex.code); + break; + case RLMPermissionActionTypeAcceptOffer: + error = make_permission_error_accept_offer(@(ex.what()), ex.code); + break; + } + } + catch (const std::exception &exp) { + RLMSetErrorOrThrow(RLMMakeError(RLMErrorFail, exp), &error); + } + return error; +} + +std::shared_ptr sync_session_for_realm(RLMRealm *realm) { + Realm::Config realmConfig = realm.configuration.config; + if (auto config = realmConfig.sync_config) { + std::shared_ptr user = config->user; + if (user && user->state() != SyncUser::State::Error) { + return user->session_for_on_disk_path(realmConfig.path); + } + } + return nullptr; +} + +CocoaSyncUserContext& context_for(const std::shared_ptr& user) +{ + return *std::static_pointer_cast(user->binding_context()); +} + +AccessLevel accessLevelForObjCAccessLevel(RLMSyncAccessLevel level) { + switch (level) { + case RLMSyncAccessLevelNone: + return AccessLevel::None; + case RLMSyncAccessLevelRead: + return AccessLevel::Read; + case RLMSyncAccessLevelWrite: + return AccessLevel::Write; + case RLMSyncAccessLevelAdmin: + return AccessLevel::Admin; + } + REALM_UNREACHABLE(); +} + +RLMSyncAccessLevel objCAccessLevelForAccessLevel(AccessLevel level) { + switch (level) { + case AccessLevel::None: + return RLMSyncAccessLevelNone; + case AccessLevel::Read: + return RLMSyncAccessLevelRead; + case AccessLevel::Write: + return RLMSyncAccessLevelWrite; + case AccessLevel::Admin: + return RLMSyncAccessLevelAdmin; + } + REALM_UNREACHABLE(); +} + +NSError *make_auth_error_bad_response(NSDictionary *json) { + return [NSError errorWithDomain:RLMSyncAuthErrorDomain + code:RLMSyncAuthErrorBadResponse + userInfo:json ? @{kRLMSyncErrorJSONKey: json} : nil]; +} + +NSError *make_auth_error_http_status(NSInteger status) { + return [NSError errorWithDomain:RLMSyncAuthErrorDomain + code:RLMSyncAuthErrorHTTPStatusCodeError + userInfo:@{kRLMSyncErrorStatusCodeKey: @(status)}]; +} + +NSError *make_auth_error_client_issue() { + return [NSError errorWithDomain:RLMSyncAuthErrorDomain + code:RLMSyncAuthErrorClientSessionError + userInfo:nil]; +} + +NSError *make_auth_error(RLMSyncErrorResponseModel *model) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithCapacity:2]; + if (NSString *description = model.title) { + [userInfo setObject:description forKey:NSLocalizedDescriptionKey]; + } + if (NSString *hint = model.hint) { + [userInfo setObject:hint forKey:NSLocalizedRecoverySuggestionErrorKey]; + } + return [NSError errorWithDomain:RLMSyncAuthErrorDomain code:model.code userInfo:userInfo]; +} + +NSError *make_permission_error_get(NSString *description, util::Optional code) { + return make_permission_error(description, std::move(code), RLMSyncPermissionErrorGetFailed); +} + +NSError *make_permission_error_change(NSString *description, util::Optional code) { + return make_permission_error(description, std::move(code), RLMSyncPermissionErrorChangeFailed); +} + +NSError *make_permission_error_offer(NSString *description, util::Optional code) { + return make_permission_error(description, std::move(code), RLMSyncPermissionErrorOfferFailed); +} + +NSError *make_permission_error_accept_offer(NSString *description, util::Optional code) { + return make_permission_error(description, std::move(code), RLMSyncPermissionErrorAcceptOfferFailed); +} + +NSError *make_sync_error(RLMSyncSystemErrorKind kind, NSString *description, NSInteger code, NSDictionary *custom) { + NSMutableDictionary *buffer = [custom ?: @{} mutableCopy]; + buffer[NSLocalizedDescriptionKey] = description; + if (code != NSNotFound) { + buffer[kRLMSyncErrorStatusCodeKey] = @(code); + } + + RLMSyncError errorCode; + switch (kind) { + case RLMSyncSystemErrorKindClientReset: + errorCode = RLMSyncErrorClientResetError; + break; + case RLMSyncSystemErrorKindPermissionDenied: + errorCode = RLMSyncErrorPermissionDeniedError; + break; + case RLMSyncSystemErrorKindUser: + errorCode = RLMSyncErrorClientUserError; + break; + case RLMSyncSystemErrorKindSession: + errorCode = RLMSyncErrorClientSessionError; + break; + case RLMSyncSystemErrorKindConnection: + case RLMSyncSystemErrorKindClient: + case RLMSyncSystemErrorKindUnknown: + errorCode = RLMSyncErrorClientInternalError; + break; + } + return [NSError errorWithDomain:RLMSyncErrorDomain + code:errorCode + userInfo:[buffer copy]]; +} + +NSError *make_sync_error(NSError *wrapped_auth_error) { + return [NSError errorWithDomain:RLMSyncErrorDomain + code:RLMSyncErrorUnderlyingAuthError + userInfo:@{kRLMSyncUnderlyingErrorKey: wrapped_auth_error}]; +} + +NSError *make_sync_error(std::error_code sync_error, RLMSyncSystemErrorKind kind) { + return [NSError errorWithDomain:RLMSyncErrorDomain + code:kind + userInfo:@{ + NSLocalizedDescriptionKey: @(sync_error.message().c_str()), + kRLMSyncErrorStatusCodeKey: @(sync_error.value()) + }]; +} diff --git a/Pods/Realm/Realm/RLMThreadSafeReference.mm b/Pods/Realm/Realm/RLMThreadSafeReference.mm new file mode 100644 index 0000000000..7149fa4785 --- /dev/null +++ b/Pods/Realm/Realm/RLMThreadSafeReference.mm @@ -0,0 +1,79 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMThreadSafeReference_Private.hpp" +#import "RLMUtil.hpp" + +template +static auto translateErrors(Function&& f) { + try { + return f(); + } + catch (std::exception const& e) { + @throw RLMException(e); + } +} + +@implementation RLMThreadSafeReference { + std::unique_ptr _reference; + id _metadata; + Class _type; +} + +- (instancetype)initWithThreadConfined:(id)threadConfined { + if (!(self = [super init])) { + return nil; + } + + REALM_ASSERT_DEBUG([threadConfined conformsToProtocol:@protocol(RLMThreadConfined)]); + if (![threadConfined conformsToProtocol:@protocol(RLMThreadConfined_Private)]) { + @throw RLMException(@"Illegal custom conformance to `RLMThreadConfined` by `%@`", threadConfined.class); + } else if (threadConfined.invalidated) { + @throw RLMException(@"Cannot construct reference to invalidated object"); + } else if (!threadConfined.realm) { + @throw RLMException(@"Cannot construct reference to unmanaged object, " + "which can be passed across threads directly"); + } + + translateErrors([&] { + _reference = [(id)threadConfined makeThreadSafeReference]; + _metadata = ((id)threadConfined).objectiveCMetadata; + }); + _type = threadConfined.class; + + return self; +} + ++ (instancetype)referenceWithThreadConfined:(id)threadConfined { + return [[self alloc] initWithThreadConfined:threadConfined]; +} + +- (id)resolveReferenceInRealm:(RLMRealm *)realm { + if (!_reference) { + @throw RLMException(@"Can only resolve a thread safe reference once."); + } + return translateErrors([&] { + return [_type objectWithThreadSafeReference:std::move(_reference) metadata:_metadata realm:realm]; + }); +} + +- (BOOL)isInvalidated { + return !_reference; +} + +@end diff --git a/Pods/Realm/Realm/RLMUpdateChecker.mm b/Pods/Realm/Realm/RLMUpdateChecker.mm new file mode 100644 index 0000000000..4ff0dd6a97 --- /dev/null +++ b/Pods/Realm/Realm/RLMUpdateChecker.mm @@ -0,0 +1,60 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMUpdateChecker.hpp" + +#import "RLMRealm.h" +#import "RLMUtil.hpp" + +#if TARGET_IPHONE_SIMULATOR && !defined(REALM_COCOA_VERSION) +#import "RLMVersion.h" +#endif + +void RLMCheckForUpdates() { +#if TARGET_IPHONE_SIMULATOR + if (getenv("REALM_DISABLE_UPDATE_CHECKER") || RLMIsRunningInPlayground()) { + return; + } + + NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"alpha|beta|rc" + options:(NSRegularExpressionOptions)0 + error:nil]; + NSUInteger numberOfMatches = [regex numberOfMatchesInString:REALM_COCOA_VERSION + options:(NSMatchingOptions)0 + range:NSMakeRange(0, REALM_COCOA_VERSION.length)]; + + if (numberOfMatches > 0) { + // pre-release version, skip update checking + return; + } + + auto handler = ^(NSData *data, NSURLResponse *response, NSError *error) { + if (error || ((NSHTTPURLResponse *)response).statusCode != 200) { + return; + } + + NSString *latestVersion = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + if (![REALM_COCOA_VERSION isEqualToString:latestVersion]) { + NSLog(@"Version %@ of Realm is now available: https://github.com/realm/realm-cocoa/blob/v%@/CHANGELOG.md", latestVersion, latestVersion); + } + }; + + NSString *url = [NSString stringWithFormat:@"https://static.realm.io/update/cocoa?%@", REALM_COCOA_VERSION]; + [[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:url] completionHandler:handler] resume]; +#endif +} diff --git a/Pods/Realm/Realm/RLMUtil.mm b/Pods/Realm/Realm/RLMUtil.mm new file mode 100644 index 0000000000..1298602193 --- /dev/null +++ b/Pods/Realm/Realm/RLMUtil.mm @@ -0,0 +1,418 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMUtil.hpp" + +#import "RLMArray_Private.hpp" +#import "RLMListBase.h" +#import "RLMObjectSchema_Private.hpp" +#import "RLMObjectStore.h" +#import "RLMObject_Private.hpp" +#import "RLMProperty_Private.h" +#import "RLMSchema_Private.h" +#import "RLMSwiftSupport.h" + +#import "shared_realm.hpp" + +#import +#import + +#include +#include + +#if !defined(REALM_COCOA_VERSION) +#import "RLMVersion.h" +#endif + +static inline bool numberIsInteger(__unsafe_unretained NSNumber *const obj) { + char data_type = [obj objCType][0]; + return data_type == *@encode(bool) || + data_type == *@encode(char) || + data_type == *@encode(short) || + data_type == *@encode(int) || + data_type == *@encode(long) || + data_type == *@encode(long long) || + data_type == *@encode(unsigned short) || + data_type == *@encode(unsigned int) || + data_type == *@encode(unsigned long) || + data_type == *@encode(unsigned long long); +} + +static inline bool numberIsBool(__unsafe_unretained NSNumber *const obj) { + // @encode(BOOL) is 'B' on iOS 64 and 'c' + // objcType is always 'c'. Therefore compare to "c". + if ([obj objCType][0] == 'c') { + return true; + } + + if (numberIsInteger(obj)) { + int value = [obj intValue]; + return value == 0 || value == 1; + } + + return false; +} + +static inline bool numberIsFloat(__unsafe_unretained NSNumber *const obj) { + char data_type = [obj objCType][0]; + return data_type == *@encode(float) || + data_type == *@encode(short) || + data_type == *@encode(int) || + data_type == *@encode(long) || + data_type == *@encode(long long) || + data_type == *@encode(unsigned short) || + data_type == *@encode(unsigned int) || + data_type == *@encode(unsigned long) || + data_type == *@encode(unsigned long long) || + // A double is like float if it fits within float bounds or is NaN. + (data_type == *@encode(double) && (ABS([obj doubleValue]) <= FLT_MAX || isnan([obj doubleValue]))); +} + +static inline bool numberIsDouble(__unsafe_unretained NSNumber *const obj) { + char data_type = [obj objCType][0]; + return data_type == *@encode(double) || + data_type == *@encode(float) || + data_type == *@encode(short) || + data_type == *@encode(int) || + data_type == *@encode(long) || + data_type == *@encode(long long) || + data_type == *@encode(unsigned short) || + data_type == *@encode(unsigned int) || + data_type == *@encode(unsigned long) || + data_type == *@encode(unsigned long long); +} + +static inline RLMArray *asRLMArray(__unsafe_unretained id const value) { + return RLMDynamicCast(value) ?: RLMDynamicCast(value)._rlmArray; +} + +static inline bool checkArrayType(__unsafe_unretained RLMArray *const array, + RLMPropertyType type, bool optional, + __unsafe_unretained NSString *const objectClassName) { + return array.type == type && array.optional == optional + && (type != RLMPropertyTypeObject || [array.objectClassName isEqualToString:objectClassName]); +} + +BOOL RLMValidateValue(__unsafe_unretained id const value, + RLMPropertyType type, bool optional, bool array, + __unsafe_unretained NSString *const objectClassName) { + if (optional && !RLMCoerceToNil(value)) { + return YES; + } + if (array) { + if (auto rlmArray = asRLMArray(value)) { + return checkArrayType(rlmArray, type, optional, objectClassName); + } + if ([value conformsToProtocol:@protocol(NSFastEnumeration)]) { + // check each element for compliance + for (id el in (id)value) { + if (!RLMValidateValue(el, type, optional, false, objectClassName)) { + return NO; + } + } + return YES; + } + if (!value || value == NSNull.null) { + return YES; + } + return NO; + } + + switch (type) { + case RLMPropertyTypeString: + return [value isKindOfClass:[NSString class]]; + case RLMPropertyTypeBool: + if ([value isKindOfClass:[NSNumber class]]) { + return numberIsBool(value); + } + return NO; + case RLMPropertyTypeDate: + return [value isKindOfClass:[NSDate class]]; + case RLMPropertyTypeInt: + if (NSNumber *number = RLMDynamicCast(value)) { + return numberIsInteger(number); + } + return NO; + case RLMPropertyTypeFloat: + if (NSNumber *number = RLMDynamicCast(value)) { + return numberIsFloat(number); + } + return NO; + case RLMPropertyTypeDouble: + if (NSNumber *number = RLMDynamicCast(value)) { + return numberIsDouble(number); + } + return NO; + case RLMPropertyTypeData: + return [value isKindOfClass:[NSData class]]; + case RLMPropertyTypeAny: + return NO; + case RLMPropertyTypeLinkingObjects: + return YES; + case RLMPropertyTypeObject: { + // only NSNull, nil, or objects which derive from RLMObject and match the given + // object class are valid + RLMObjectBase *objBase = RLMDynamicCast(value); + return objBase && [objBase->_objectSchema.className isEqualToString:objectClassName]; + } + } + @throw RLMException(@"Invalid RLMPropertyType specified"); +} + +void RLMThrowTypeError(__unsafe_unretained id const obj, + __unsafe_unretained RLMObjectSchema *const objectSchema, + __unsafe_unretained RLMProperty *const prop) { + @throw RLMException(@"Invalid value '%@' of type '%@' for '%@%s'%s property '%@.%@'.", + obj, [obj class], + prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "", + prop.array ? " array" : "", objectSchema.className, prop.name); +} + +void RLMValidateValueForProperty(__unsafe_unretained id const obj, + __unsafe_unretained RLMObjectSchema *const objectSchema, + __unsafe_unretained RLMProperty *const prop, + bool validateObjects) { + // This duplicates a lot of the checks in RLMIsObjectValidForProperty() + // for the sake of more specific error messages + if (prop.array) { + // nil is considered equivalent to an empty array for historical reasons + // since we don't support null arrays (only arrays containing null), + // it's not worth the BC break to change this + if (!obj || obj == NSNull.null) { + return; + } + if (![obj conformsToProtocol:@protocol(NSFastEnumeration)]) { + @throw RLMException(@"Invalid value (%@) for '%@%s' array property '%@.%@': value is not enumerable.", + obj, prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "", + objectSchema.className, prop.name); + } + if (!validateObjects && prop.type == RLMPropertyTypeObject) { + return; + } + + if (RLMArray *array = asRLMArray(obj)) { + if (!checkArrayType(array, prop.type, prop.optional, prop.objectClassName)) { + @throw RLMException(@"RLMArray<%@%s> does not match expected type '%@%s' for property '%@.%@'.", + array.objectClassName ?: RLMTypeToString(array.type), array.optional ? "?" : "", + prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "", + objectSchema.className, prop.name); + } + return; + } + + for (id value in obj) { + if (!RLMValidateValue(value, prop.type, prop.optional, false, prop.objectClassName)) { + RLMThrowTypeError(value, objectSchema, prop); + } + } + return; + } + + // For create() we want to skip the validation logic for objects because + // we allow much fuzzier matching (any KVC-compatible object with at least + // all the non-defaulted fields), and all the logic for that lives in the + // object store rather than here + if (prop.type == RLMPropertyTypeObject && !validateObjects) { + return; + } + if (RLMIsObjectValidForProperty(obj, prop)) { + return; + } + + RLMThrowTypeError(obj, objectSchema, prop); +} + +BOOL RLMIsObjectValidForProperty(__unsafe_unretained id const obj, + __unsafe_unretained RLMProperty *const property) { + return RLMValidateValue(obj, property.type, property.optional, property.array, property.objectClassName); +} + +NSDictionary *RLMDefaultValuesForObjectSchema(__unsafe_unretained RLMObjectSchema *const objectSchema) { + if (!objectSchema.isSwiftClass) { + return [objectSchema.objectClass defaultPropertyValues]; + } + + NSMutableDictionary *defaults = nil; + if ([objectSchema.objectClass isSubclassOfClass:RLMObject.class]) { + defaults = [NSMutableDictionary dictionaryWithDictionary:[objectSchema.objectClass defaultPropertyValues]]; + } + else { + defaults = [NSMutableDictionary dictionary]; + } + RLMObject *defaultObject = [[objectSchema.objectClass alloc] init]; + for (RLMProperty *prop in objectSchema.properties) { + if (!defaults[prop.name] && defaultObject[prop.name]) { + defaults[prop.name] = defaultObject[prop.name]; + } + } + return defaults; +} + +static NSException *RLMException(NSString *reason, NSDictionary *additionalUserInfo) { + NSMutableDictionary *userInfo = @{RLMRealmVersionKey: REALM_COCOA_VERSION, + RLMRealmCoreVersionKey: @REALM_VERSION}.mutableCopy; + if (additionalUserInfo != nil) { + [userInfo addEntriesFromDictionary:additionalUserInfo]; + } + NSException *e = [NSException exceptionWithName:RLMExceptionName + reason:reason + userInfo:userInfo]; + return e; +} + +NSException *RLMException(NSString *fmt, ...) { + va_list args; + va_start(args, fmt); + NSException *e = RLMException([[NSString alloc] initWithFormat:fmt arguments:args], @{}); + va_end(args); + return e; +} + +NSException *RLMException(std::exception const& exception) { + return RLMException(@"%s", exception.what()); +} + +NSError *RLMMakeError(RLMError code, std::exception const& exception) { + return [NSError errorWithDomain:RLMErrorDomain + code:code + userInfo:@{NSLocalizedDescriptionKey: @(exception.what()), + @"Error Code": @(code)}]; +} + +NSError *RLMMakeError(RLMError code, const realm::util::File::AccessError& exception) { + return [NSError errorWithDomain:RLMErrorDomain + code:code + userInfo:@{NSLocalizedDescriptionKey: @(exception.what()), + NSFilePathErrorKey: @(exception.get_path().c_str()), + @"Error Code": @(code)}]; +} + +NSError *RLMMakeError(RLMError code, const realm::RealmFileException& exception) { + NSString *underlying = @(exception.underlying().c_str()); + return [NSError errorWithDomain:RLMErrorDomain + code:code + userInfo:@{NSLocalizedDescriptionKey: @(exception.what()), + NSFilePathErrorKey: @(exception.path().c_str()), + @"Error Code": @(code), + @"Underlying": underlying.length == 0 ? @"n/a" : underlying}]; +} + +NSError *RLMMakeError(std::system_error const& exception) { + BOOL isGenericCategoryError = (exception.code().category() == std::generic_category()); + NSString *category = @(exception.code().category().name()); + NSString *errorDomain = isGenericCategoryError ? NSPOSIXErrorDomain : RLMUnknownSystemErrorDomain; + + return [NSError errorWithDomain:errorDomain + code:exception.code().value() + userInfo:@{NSLocalizedDescriptionKey: @(exception.what()), + @"Error Code": @(exception.code().value()), + @"Category": category}]; +} + +void RLMSetErrorOrThrow(NSError *error, NSError **outError) { + if (outError) { + *outError = error; + } + else { + NSString *msg = error.localizedDescription; + if (error.userInfo[NSFilePathErrorKey]) { + msg = [NSString stringWithFormat:@"%@: %@", error.userInfo[NSFilePathErrorKey], error.localizedDescription]; + } + @throw RLMException(msg, @{NSUnderlyingErrorKey: error}); + } +} + +BOOL RLMIsDebuggerAttached() +{ + int name[] = { + CTL_KERN, + KERN_PROC, + KERN_PROC_PID, + getpid() + }; + + struct kinfo_proc info; + size_t info_size = sizeof(info); + if (sysctl(name, sizeof(name)/sizeof(name[0]), &info, &info_size, NULL, 0) == -1) { + NSLog(@"sysctl() failed: %s", strerror(errno)); + return false; + } + + return (info.kp_proc.p_flag & P_TRACED) != 0; +} + +BOOL RLMIsRunningInPlayground() { + return [[NSBundle mainBundle].bundleIdentifier hasPrefix:@"com.apple.dt.playground."]; +} + +id RLMMixedToObjc(realm::Mixed const& mixed) { + switch (mixed.get_type()) { + case realm::type_String: + return RLMStringDataToNSString(mixed.get_string()); + case realm::type_Int: + return @(mixed.get_int()); + case realm::type_Float: + return @(mixed.get_float()); + case realm::type_Double: + return @(mixed.get_double()); + case realm::type_Bool: + return @(mixed.get_bool()); + case realm::type_Timestamp: + return RLMTimestampToNSDate(mixed.get_timestamp()); + case realm::type_Binary: + return RLMBinaryDataToNSData(mixed.get_binary()); + case realm::type_Link: + case realm::type_LinkList: + default: + @throw RLMException(@"Invalid data type for RLMPropertyTypeAny property."); + } +} + +NSString *RLMDefaultDirectoryForBundleIdentifier(NSString *bundleIdentifier) { +#if TARGET_OS_TV + (void)bundleIdentifier; + // tvOS prohibits writing to the Documents directory, so we use the Library/Caches directory instead. + return NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; +#elif TARGET_OS_IPHONE + (void)bundleIdentifier; + // On iOS the Documents directory isn't user-visible, so put files there + return NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; +#else + // On OS X it is, so put files in Application Support. If we aren't running + // in a sandbox, put it in a subdirectory based on the bundle identifier + // to avoid accidentally sharing files between applications + NSString *path = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)[0]; + if (![[NSProcessInfo processInfo] environment][@"APP_SANDBOX_CONTAINER_ID"]) { + if (!bundleIdentifier) { + bundleIdentifier = [NSBundle mainBundle].bundleIdentifier; + } + if (!bundleIdentifier) { + bundleIdentifier = [NSBundle mainBundle].executablePath.lastPathComponent; + } + + path = [path stringByAppendingPathComponent:bundleIdentifier]; + + // create directory + [[NSFileManager defaultManager] createDirectoryAtPath:path + withIntermediateDirectories:YES + attributes:nil + error:nil]; + } + return path; +#endif +} diff --git a/Pods/Realm/Realm/Realm.modulemap b/Pods/Realm/Realm/Realm.modulemap new file mode 100644 index 0000000000..42845f699c --- /dev/null +++ b/Pods/Realm/Realm/Realm.modulemap @@ -0,0 +1,31 @@ +framework module Realm { + umbrella header "Realm.h" + + export * + module * { export * } + + explicit module Private { + header "RLMAccessor.h" + header "RLMArray_Private.h" + header "RLMCollection_Private.h" + header "RLMListBase.h" + header "RLMObject_Private.h" + header "RLMObjectBase_Dynamic.h" + header "RLMObjectBase_Private.h" + header "RLMObjectSchema_Private.h" + header "RLMObjectStore.h" + header "RLMOptionalBase.h" + header "RLMProperty_Private.h" + header "RLMRealm_Private.h" + header "RLMRealmConfiguration_Private.h" + header "RLMResults_Private.h" + header "RLMSchema_Private.h" + header "RLMSyncConfiguration_Private.h" + header "RLMSyncUtil_Private.h" + } + + explicit module Dynamic { + header "RLMRealm_Dynamic.h" + header "RLMObjectBase_Dynamic.h" + } +} diff --git a/Pods/Realm/build.sh b/Pods/Realm/build.sh new file mode 100755 index 0000000000..9a3525f0b8 --- /dev/null +++ b/Pods/Realm/build.sh @@ -0,0 +1,1459 @@ +#!/bin/bash + +################################################################################## +# Custom build tool for Realm Objective-C binding. +# +# (C) Copyright 2011-2015 by realm.io. +################################################################################## + +# Warning: pipefail is not a POSIX compatible option, but on OS X it works just fine. +# OS X uses a POSIX complain version of bash as /bin/sh, but apparently it does +# not strip away this feature. Also, this will fail if somebody forces the script +# to be run with zsh. +set -o pipefail +set -e + +source_root="$(dirname "$0")" + +# You can override the version of the core library +: ${REALM_CORE_VERSION:=$(sed -n 's/^REALM_CORE_VERSION=\(.*\)$/\1/p' ${source_root}/dependencies.list)} # set to "current" to always use the current build + +: ${REALM_SYNC_VERSION:=$(sed -n 's/^REALM_SYNC_VERSION=\(.*\)$/\1/p' ${source_root}/dependencies.list)} + +: ${REALM_OBJECT_SERVER_VERSION:=$(sed -n 's/^REALM_OBJECT_SERVER_VERSION=\(.*\)$/\1/p' ${source_root}/dependencies.list)} + +# You can override the xcmode used +: ${XCMODE:=xcodebuild} # must be one of: xcodebuild (default), xcpretty, xctool + +# Provide a fallback value for TMPDIR, relevant for Xcode Bots +: ${TMPDIR:=$(getconf DARWIN_USER_TEMP_DIR)} + +PATH=/usr/libexec:$PATH + +if ! [ -z "${JENKINS_HOME}" ]; then + XCPRETTY_PARAMS="--no-utf --report junit --output build/reports/junit.xml" + CODESIGN_PARAMS="CODE_SIGN_IDENTITY= CODE_SIGNING_REQUIRED=NO" +fi + +usage() { +cat <= 10 )); then + destination="Apple Watch Series 3 - 42mm" + else + destination="Apple Watch - 42mm" + fi + elif [[ "$os" == "appletvos" ]]; then + os_name="tvos" + if (( $(xcode_version_major) >= 9 )); then + destination="Apple TV" + else + destination="Apple TV 1080p" + fi + fi + + # Derive build paths + local build_products_path="build/DerivedData/Realm/Build/Products" + local product_name="$module_name.framework" + local binary_path="$module_name" + local os_path="$build_products_path/$config-$os$scope_suffix/$product_name" + local simulator_path="$build_products_path/$config-$simulator$scope_suffix/$product_name" + local out_path="build/$os_name$scope_suffix$version_suffix" + + # Build for each platform + xc "-scheme '$scheme' -configuration $config -sdk $os" + xc "-scheme '$scheme' -configuration $config -sdk $simulator -destination 'name=$destination' ONLY_ACTIVE_ARCH=NO" + + # Combine .swiftmodule + if [ -d $simulator_path/Modules/$module_name.swiftmodule ]; then + cp $simulator_path/Modules/$module_name.swiftmodule/* $os_path/Modules/$module_name.swiftmodule/ + fi + + # Copy *.bcsymbolmap to .framework for submitting app with bitcode + copy_bcsymbolmap "$build_products_path/$config-$os$scope_suffix" "$os_path" + + # Retrieve build products + clean_retrieve $os_path $out_path $product_name + + # Combine ar archives + LIPO_OUTPUT="$out_path/$product_name/$module_name" + xcrun lipo -create "$simulator_path/$binary_path" "$os_path/$binary_path" -output "$LIPO_OUTPUT" + + # Verify that the combined library has bitcode and we didn't accidentally + # remove it somewhere along the line + if [[ "$destination" != "" && "$config" == "Release" ]]; then + sh build.sh binary-has-bitcode "$LIPO_OUTPUT" + fi +} + +clean_retrieve() { + mkdir -p "$2" + rm -rf "$2/$3" + cp -R "$1" "$2" +} + +move_to_clean_dir() { + rm -rf "$2" + mkdir -p "$2" + mv "$1" "$2" +} + +test_ios_static() { + destination="$1" + xc "-scheme 'Realm iOS static' -configuration $CONFIGURATION -sdk iphonesimulator -destination '$destination' build" + if (( $(xcode_version_major) < 9 )); then + xc "-scheme 'Realm iOS static' -configuration $CONFIGURATION -sdk iphonesimulator -destination '$destination' test 'ARCHS=\$(ARCHS_STANDARD_32_BIT)'" + fi + + # Xcode's depending tracking is lacking and it doesn't realize that the Realm static framework's static library + # needs to be recreated when the active architectures change. Help Xcode out by removing the static library. + settings=$(xcode "-scheme 'Realm iOS static' -configuration $CONFIGURATION -sdk iphonesimulator -destination '$destination' -showBuildSettings") + path=$(echo "$settings" | awk '/CONFIGURATION_BUILD_DIR/ { cbd = $3; } /EXECUTABLE_PATH/ { ep = $3; } END { printf "%s/%s\n", cbd, ep; }') + rm "$path" + + xc "-scheme 'Realm iOS static' -configuration $CONFIGURATION -sdk iphonesimulator -destination '$destination' test" +} + +###################################### +# Device Test Helper +###################################### + +test_devices() { + local serial_numbers=() + local awk_script=" + /^ +Vendor ID: / { is_apple = 0; } + /^ +Vendor ID: 0x05[aA][cC] / { is_apple = 1; } + /^ +Serial Number: / { + if (is_apple) { + match(\$0, /^ +Serial Number: /); + print substr(\$0, RLENGTH + 1); + } + } + " + local serial_numbers_text=$(/usr/sbin/system_profiler SPUSBDataType | /usr/bin/awk "$awk_script") + while read -r number; do + if [[ "$number" != "" ]]; then + serial_numbers+=("$number") + fi + done <<< "$serial_numbers_text" + if [[ ${#serial_numbers[@]} == 0 ]]; then + echo "At least one iOS/tvOS device must be connected to this computer to run device tests" + if [ -z "${JENKINS_HOME}" ]; then + # Don't fail if running locally and there's no device + exit 0 + fi + exit 1 + fi + local sdk="$1" + local scheme="$2" + local configuration="$3" + local failed=0 + for device in "${serial_numbers[@]}"; do + xc "-scheme '$scheme' -configuration $configuration -destination 'id=$device' -sdk $sdk test" || failed=1 + done + return $failed +} + +###################################### +# Docs +###################################### + +build_docs() { + local language="$1" + local version=$(sh build.sh get-version) + + local xcodebuild_arguments="--objc,Realm/Realm.h,--,-x,objective-c,-isysroot,$(xcrun --show-sdk-path),-I,$(pwd)" + local module="Realm" + local objc="--objc" + + if [[ "$language" == "swift" ]]; then + sh build.sh set-swift-version + xcodebuild_arguments="-scheme,RealmSwift" + module="RealmSwift" + objc="" + fi + + touch Realm/RLMPlatform.h # jazzy will fail if it can't find all public header files + jazzy \ + ${objc} \ + --clean \ + --author Realm \ + --author_url https://realm.io \ + --github_url https://github.com/realm/realm-cocoa \ + --github-file-prefix https://github.com/realm/realm-cocoa/tree/v${version} \ + --module-version ${version} \ + --xcodebuild-arguments ${xcodebuild_arguments} \ + --module ${module} \ + --root-url https://realm.io/docs/${language}/${version}/api/ \ + --output docs/${language}_output \ + --head "$(cat docs/custom_head.html)" + + rm Realm/RLMPlatform.h +} + +###################################### +# Input Validation +###################################### + +if [ "$#" -eq 0 -o "$#" -gt 3 ]; then + usage + exit 1 +fi + +###################################### +# Downloading +###################################### + +download_common() { + local download_type=$1 tries_left=3 version url error temp_dir temp_path tar_path + + if [ "$download_type" == "core" ]; then + version=$REALM_CORE_VERSION + url="https://static.realm.io/downloads/core/realm-core-${version}.tar.xz" + elif [ "$download_type" == "sync" ]; then + version=$REALM_SYNC_VERSION + url="https://static.realm.io/downloads/sync/realm-sync-cocoa-${version}.tar.xz" + else + echo "Unknown dowload_type: $download_type" + exit 1 + fi + + echo "Downloading dependency: ${download_type} ${version}" + + if [ -z "$TMPDIR" ]; then + TMPDIR='/tmp' + fi + temp_dir=$(dirname "$TMPDIR/waste")/${download_type}_bin + mkdir -p "$temp_dir" + tar_path="${temp_dir}/${download_type}-${version}.tar.xz" + temp_path="${tar_path}.tmp" + + while [ 0 -lt $tries_left ] && [ ! -f "$tar_path" ]; do + if ! error=$(/usr/bin/curl --fail --silent --show-error --location "$url" --output "$temp_path" 2>&1); then + tries_left=$[$tries_left-1] + else + mv "$temp_path" "$tar_path" + fi + done + + if [ ! -f "$tar_path" ]; then + printf "Downloading ${download_type} failed:\n\t$url\n\t$error\n" + exit 1 + fi + + ( + cd "$temp_dir" + rm -rf "$download_type" + tar xf "$tar_path" --xz + mv core "${download_type}-${version}" + ) + + rm -rf "${download_type}-${version}" core + mv "${temp_dir}/${download_type}-${version}" . + ln -s "${download_type}-${version}" core +} + +download_core() { + download_common "core" +} + +download_sync() { + download_common "sync" +} + +###################################### +# Variables +###################################### + +COMMAND="$1" + +# Use Debug config if command ends with -debug, otherwise default to Release +# Set IS_RUNNING_PACKAGING when running packaging steps to avoid running iOS static tests with Xcode 8.3.3 +case "$COMMAND" in + *-debug) + COMMAND="${COMMAND%-debug}" + CONFIGURATION="Debug" + ;; + package-*) + IS_RUNNING_PACKAGING=1 + ;; +esac +export CONFIGURATION=${CONFIGURATION:-Release} +export IS_RUNNING_PACKAGING=${IS_RUNNING_PACKAGING:-0} + +# Pre-choose Xcode and Swift versions for those operations that do not set them +REALM_XCODE_VERSION=${xcode_version:-$REALM_XCODE_VERSION} +REALM_SWIFT_VERSION=${swift_version:-$REALM_SWIFT_VERSION} +source "${source_root}/scripts/swift-version.sh" +set_xcode_and_swift_versions + +###################################### +# Commands +###################################### + +case "$COMMAND" in + + ###################################### + # Clean + ###################################### + "clean") + find . -type d -name build -exec rm -r "{}" + + exit 0 + ;; + + ###################################### + # Core + ###################################### + "download-core") + if [ "$REALM_CORE_VERSION" = "current" ]; then + echo "Using version of core already in core/ directory" + exit 0 + fi + if [ -d core -a -d ../realm-core -a ! -L core ]; then + # Allow newer versions than expected for local builds as testing + # with unreleased versions is one of the reasons to use a local build + if ! $(grep -i "${REALM_CORE_VERSION} Release notes" core/release_notes.txt >/dev/null); then + echo "Local build of core is out of date." + exit 1 + else + echo "The core library seems to be up to date." + fi + elif ! [ -L core ]; then + echo "core is not a symlink. Deleting..." + rm -rf core + download_core + # With a prebuilt version we only want to check the first non-empty + # line so that checking out an older commit will download the + # appropriate version of core if the already-present version is too new + elif ! $(grep -m 1 . core/release_notes.txt | grep -i "${REALM_CORE_VERSION} RELEASE NOTES" >/dev/null); then + download_core + else + echo "The core library seems to be up to date." + fi + exit 0 + ;; + + ###################################### + # Sync + ###################################### + "download-sync") + if [ "$REALM_SYNC_VERSION" = "current" ]; then + echo "Using version of core already in core/ directory" + exit 0 + fi + if [ -d core -a -d ../realm-core -a -d ../realm-sync -a ! -L core ]; then + echo "Using version of core already in core/ directory" + elif ! [ -L core ]; then + echo "core is not a symlink. Deleting..." + rm -rf core + download_sync + elif [[ "$(cat core/version.txt)" != "$REALM_SYNC_VERSION" ]]; then + download_sync + else + echo "The core library seems to be up to date." + fi + exit 0 + ;; + + ###################################### + # Swift versioning + ###################################### + "set-swift-version") + version=${2:-$REALM_SWIFT_VERSION} + + SWIFT_VERSION_FILE="RealmSwift/SwiftVersion.swift" + CONTENTS="let swiftLanguageVersion = \"$version\"" + if [ ! -f "$SWIFT_VERSION_FILE" ] || ! grep -q "$CONTENTS" "$SWIFT_VERSION_FILE"; then + echo "$CONTENTS" > "$SWIFT_VERSION_FILE" + fi + + exit 0 + ;; + + "prelaunch-simulator") + sh ${source_root}/scripts/reset-simulators.sh + ;; + + ###################################### + # Building + ###################################### + "build") + sh build.sh ios-static + sh build.sh ios-dynamic + sh build.sh ios-swift + sh build.sh watchos + sh build.sh watchos-swift + sh build.sh tvos + sh build.sh tvos-swift + sh build.sh osx + sh build.sh osx-swift + exit 0 + ;; + + "ios-static") + build_combined 'Realm iOS static' Realm iphoneos iphonesimulator "-static" + exit 0 + ;; + + "ios-dynamic") + build_combined Realm Realm iphoneos iphonesimulator + exit 0 + ;; + + "ios-swift") + sh build.sh ios-dynamic + build_combined RealmSwift RealmSwift iphoneos iphonesimulator '' "/swift-$REALM_SWIFT_VERSION" + cp -R build/ios/Realm.framework build/ios/swift-$REALM_SWIFT_VERSION + exit 0 + ;; + + "watchos") + build_combined Realm Realm watchos watchsimulator + exit 0 + ;; + + "watchos-swift") + sh build.sh watchos + build_combined RealmSwift RealmSwift watchos watchsimulator '' "/swift-$REALM_SWIFT_VERSION" + cp -R build/watchos/Realm.framework build/watchos/swift-$REALM_SWIFT_VERSION + exit 0 + ;; + + "tvos") + build_combined Realm Realm appletvos appletvsimulator + exit 0 + ;; + + "tvos-swift") + sh build.sh tvos + build_combined RealmSwift RealmSwift appletvos appletvsimulator '' "/swift-$REALM_SWIFT_VERSION" + cp -R build/tvos/Realm.framework build/tvos/swift-$REALM_SWIFT_VERSION + exit 0 + ;; + + "osx") + xc "-scheme Realm -configuration $CONFIGURATION" + clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION/Realm.framework" "build/osx" "Realm.framework" + exit 0 + ;; + + "osx-swift") + sh build.sh osx + xc "-scheme 'RealmSwift' -configuration $CONFIGURATION build" + destination="build/osx/swift-$REALM_SWIFT_VERSION" + clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION/RealmSwift.framework" "$destination" "RealmSwift.framework" + cp -R build/osx/Realm.framework "$destination" + exit 0 + ;; + + ###################################### + # Analysis + ###################################### + + "analyze-osx") + xc "-scheme Realm -configuration $CONFIGURATION analyze" + exit 0 + ;; + + ###################################### + # Testing + ###################################### + "test") + set +e # Run both sets of tests even if the first fails + failed=0 + sh build.sh test-ios-static || failed=1 + sh build.sh test-ios-dynamic || failed=1 + sh build.sh test-ios-swift || failed=1 + sh build.sh test-ios-devices || failed=1 + sh build.sh test-tvos-devices || failed=1 + sh build.sh test-osx || failed=1 + sh build.sh test-osx-swift || failed=1 + exit $failed + ;; + + "test-all") + set +e + failed=0 + sh build.sh test || failed=1 + sh build.sh test-debug || failed=1 + exit $failed + ;; + + "test-ios-static") + test_ios_static "name=iPhone 6" + exit 0 + ;; + + "test-ios-dynamic") + xc "-scheme Realm -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 6' build" + if (( $(xcode_version_major) < 9 )); then + xc "-scheme Realm -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 6' test 'ARCHS=\$(ARCHS_STANDARD_32_BIT)'" + fi + xc "-scheme Realm -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 6' test" + exit 0 + ;; + + "test-ios-swift") + xc "-scheme RealmSwift -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 6' build" + if (( $(xcode_version_major) < 9 )); then + xc "-scheme RealmSwift -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 6' test 'ARCHS=\$(ARCHS_STANDARD_32_BIT)'" + fi + xc "-scheme RealmSwift -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 6' test" + exit 0 + ;; + + "test-ios-devices") + failed=0 + trap "failed=1" ERR + sh build.sh test-ios-devices-objc + sh build.sh test-ios-devices-swift + exit $failed + ;; + + "test-ios-devices-objc") + test_devices iphoneos "Realm" "$CONFIGURATION" + exit $? + ;; + + "test-ios-devices-swift") + test_devices iphoneos "RealmSwift" "$CONFIGURATION" + exit $? + ;; + + "test-tvos") + if (( $(xcode_version_major) >= 9 )); then + destination="Apple TV" + else + destination="Apple TV 1080p" + fi + xctest "-scheme Realm -configuration $CONFIGURATION -sdk appletvsimulator -destination 'name=$destination'" + exit $? + ;; + + "test-tvos-swift") + if (( $(xcode_version_major) >= 9 )); then + destination="Apple TV" + else + destination="Apple TV 1080p" + fi + xctest "-scheme RealmSwift -configuration $CONFIGURATION -sdk appletvsimulator -destination 'name=$destination'" + exit $? + ;; + + "test-tvos-devices") + test_devices appletvos TestHost "$CONFIGURATION" + ;; + + "test-osx") + COVERAGE_PARAMS="" + if [[ "$CONFIGURATION" == "Debug" ]]; then + COVERAGE_PARAMS="GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES" + fi + xctest "-scheme Realm -configuration $CONFIGURATION $COVERAGE_PARAMS" + exit 0 + ;; + + "test-osx-swift") + xctest "-scheme RealmSwift -configuration $CONFIGURATION" + exit 0 + ;; + + "test-osx-object-server") + xctest "-scheme 'Object Server Tests' -configuration $CONFIGURATION -sdk macosx" + exit 0 + ;; + + ###################################### + # Full verification + ###################################### + "verify") + sh build.sh verify-cocoapods + sh build.sh verify-docs + sh build.sh verify-osx + sh build.sh verify-osx-debug + sh build.sh verify-osx-swift + sh build.sh verify-osx-swift-debug + sh build.sh verify-ios-static + sh build.sh verify-ios-static-debug + sh build.sh verify-ios-dynamic + sh build.sh verify-ios-dynamic-debug + sh build.sh verify-ios-swift + sh build.sh verify-ios-swift-debug + sh build.sh verify-ios-device-objc + sh build.sh verify-ios-device-swift + sh build.sh verify-watchos + sh build.sh verify-tvos + sh build.sh verify-tvos-debug + sh build.sh verify-tvos-device + sh build.sh verify-swiftlint + sh build.sh verify-osx-object-server + ;; + + "verify-cocoapods") + if [[ -d .git ]]; then + # Verify the current branch, unless one was already specified in the sha environment variable. + if [[ -z $sha ]]; then + export sha=$(git rev-parse --abbrev-ref HEAD) + fi + + if [[ $(git log -1 @{push}..) != "" ]] || ! git diff-index --quiet HEAD; then + echo "WARNING: verify-cocoapods will test the latest revision of $sha found on GitHub." + echo " Any unpushed local changes will not be tested." + echo "" + sleep 1 + fi + fi + + # https://github.com/CocoaPods/CocoaPods/issues/7708 + export EXPANDED_CODE_SIGN_IDENTITY='' + cd examples/installation + sh build.sh test-ios-objc-cocoapods + sh build.sh test-ios-objc-cocoapods-dynamic + sh build.sh test-ios-swift-cocoapods + sh build.sh test-osx-objc-cocoapods + sh build.sh test-osx-swift-cocoapods + sh build.sh test-watchos-objc-cocoapods + sh build.sh test-watchos-swift-cocoapods + ;; + + "verify-osx-encryption") + REALM_ENCRYPT_ALL=YES sh build.sh test-osx + exit 0 + ;; + + "verify-osx") + sh build.sh test-osx + sh build.sh analyze-osx + sh build.sh examples-osx + + ( + cd examples/osx/objc/build/DerivedData/RealmExamples/Build/Products/$CONFIGURATION + DYLD_FRAMEWORK_PATH=. ./JSONImport >/dev/null + ) + exit 0 + ;; + + "verify-osx-swift") + sh build.sh test-osx-swift + exit 0 + ;; + + "verify-ios-static") + sh build.sh test-ios-static + sh build.sh examples-ios + ;; + + "verify-ios-dynamic") + sh build.sh test-ios-dynamic + ;; + + "verify-ios-swift") + sh build.sh test-ios-swift + sh build.sh examples-ios-swift + ;; + + "verify-ios-device-objc") + sh build.sh test-ios-devices-objc + exit 0 + ;; + + "verify-ios-device-swift") + sh build.sh test-ios-devices-swift + exit 0 + ;; + + "verify-docs") + sh build.sh docs + for lang in swift objc; do + undocumented="docs/${lang}_output/undocumented.json" + if ruby -rjson -e "j = JSON.parse(File.read('docs/${lang}_output/undocumented.json')); exit j['warnings'].length != 0"; then + echo "Undocumented Realm $lang declarations:" + cat "$undocumented" + exit 1 + fi + done + exit 0 + ;; + + "verify-watchos") + sh build.sh watchos-swift + exit 0 + ;; + + "verify-tvos") + sh build.sh test-tvos + sh build.sh test-tvos-swift + sh build.sh examples-tvos + sh build.sh examples-tvos-swift + exit 0 + ;; + + "verify-tvos-device") + sh build.sh test-tvos-devices + exit 0 + ;; + + "verify-swiftlint") + swiftlint lint --strict + exit 0 + ;; + + "verify-osx-object-server") + sh build.sh test-osx-object-server + exit 0 + ;; + + ###################################### + # Docs + ###################################### + "docs") + build_docs objc + build_docs swift + exit 0 + ;; + + ###################################### + # Examples + ###################################### + "examples") + sh build.sh clean + sh build.sh examples-ios + sh build.sh examples-ios-swift + sh build.sh examples-osx + sh build.sh examples-tvos + sh build.sh examples-tvos-swift + exit 0 + ;; + + "examples-ios") + sh build.sh prelaunch-simulator + workspace="examples/ios/objc/RealmExamples.xcworkspace" + pod install --project-directory="$workspace/.." --no-repo-update + xc "-workspace $workspace -scheme Simple -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme TableView -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme Migration -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme Backlink -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme GroupedTableView -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme RACTableView -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme Encryption -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme Draw -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + + if [ ! -z "${JENKINS_HOME}" ]; then + xc "-workspace $workspace -scheme Extension -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + fi + + exit 0 + ;; + + "examples-ios-swift") + sh build.sh prelaunch-simulator + workspace="examples/ios/swift/RealmExamples.xcworkspace" + if [[ ! -d "$workspace" ]]; then + workspace="${workspace/swift/swift-$REALM_SWIFT_VERSION}" + fi + + xc "-workspace $workspace -scheme Simple -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme TableView -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme Migration -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme Encryption -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme Backlink -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme GroupedTableView -configuration $CONFIGURATION -destination 'name=iPhone 6' build ${CODESIGN_PARAMS}" + exit 0 + ;; + + "examples-osx") + xc "-workspace examples/osx/objc/RealmExamples.xcworkspace -scheme JSONImport -configuration ${CONFIGURATION} build ${CODESIGN_PARAMS}" + ;; + + "examples-tvos") + workspace="examples/tvos/objc/RealmExamples.xcworkspace" + if (( $(xcode_version_major) >= 9 )); then + destination="Apple TV" + else + destination="Apple TV 1080p" + fi + + xc "-workspace $workspace -scheme DownloadCache -configuration $CONFIGURATION -destination 'name=$destination' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme PreloadedData -configuration $CONFIGURATION -destination 'name=$destination' build ${CODESIGN_PARAMS}" + exit 0 + ;; + + "examples-tvos-swift") + workspace="examples/tvos/swift/RealmExamples.xcworkspace" + if [[ ! -d "$workspace" ]]; then + workspace="${workspace/swift/swift-$REALM_SWIFT_VERSION}" + fi + + if (( $(xcode_version_major) >= 9 )); then + destination="Apple TV" + else + destination="Apple TV 1080p" + fi + + xc "-workspace $workspace -scheme DownloadCache -configuration $CONFIGURATION -destination 'name=$destination' build ${CODESIGN_PARAMS}" + xc "-workspace $workspace -scheme PreloadedData -configuration $CONFIGURATION -destination 'name=$destination' build ${CODESIGN_PARAMS}" + exit 0 + ;; + + ###################################### + # Versioning + ###################################### + "get-version") + version_file="Realm/Realm-Info.plist" + echo "$(PlistBuddy -c "Print :CFBundleShortVersionString" "$version_file")" + exit 0 + ;; + + "set-version") + realm_version="$2" + version_files="Realm/Realm-Info.plist" + + if [ -z "$realm_version" ]; then + echo "You must specify a version." + exit 1 + fi + # The bundle version can contain only three groups of digits separated by periods, + # so strip off any -beta.x tag from the end of the version string. + bundle_version=$(echo "$realm_version" | cut -d - -f 1) + for version_file in $version_files; do + PlistBuddy -c "Set :CFBundleVersion $bundle_version" "$version_file" + PlistBuddy -c "Set :CFBundleShortVersionString $realm_version" "$version_file" + done + sed -i '' "s/^VERSION=.*/VERSION=$realm_version/" dependencies.list + exit 0 + ;; + + ###################################### + # Bitcode Detection + ###################################### + + "binary-has-bitcode") + # Disable pipefail as grep -q will make otool fail due to exiting + # before reading all the output + set +o pipefail + + BINARY="$2" + if otool -l "$BINARY" | grep -q "segname __LLVM"; then + exit 0 + fi + # Work around rdar://21826157 by checking for bitcode in thin binaries + + # Get architectures for binary + archs="$(lipo -info "$BINARY" | rev | cut -d ':' -f1 | rev)" + + archs_array=( $archs ) + if [[ ${#archs_array[@]} -lt 2 ]]; then + echo 'Error: Built library is not a fat binary' + exit 1 # Early exit if not a fat binary + fi + + TEMPDIR=$(mktemp -d $TMPDIR/realm-bitcode-check.XXXX) + + for arch in $archs; do + lipo -thin "$arch" "$BINARY" -output "$TEMPDIR/$arch" + if otool -l "$TEMPDIR/$arch" | grep -q "segname __LLVM"; then + exit 0 + fi + done + echo 'Error: Built library does not contain bitcode' + exit 1 + ;; + + ###################################### + # CocoaPods + ###################################### + "cocoapods-setup") + if [ ! -d core ]; then + sh build.sh download-sync + rm core + mv sync-* core + mv core/librealm-ios.a core/librealmcore-ios.a + mv core/librealm-macosx.a core/librealmcore-macosx.a + mv core/librealm-tvos.a core/librealmcore-tvos.a + mv core/librealm-watchos.a core/librealmcore-watchos.a + fi + + if [[ "$2" != "swift" ]]; then + if [ ! -d Realm/ObjectStore/src ]; then + cat >&2 < Realm/RLMPlatform.h + if [ -n "$COCOAPODS_VERSION" ]; then + # This variable is set for the prepare_command available + # from the 1.0 prereleases, which requires a different + # header layout within the header_mappings_dir. + cp Realm/*.h include + else + # For CocoaPods < 1.0, we need to scope the headers within + # the header_mappings_dir by another subdirectory to avoid + # Clang from complaining about non-modular headers. + mkdir -p include/Realm + cp Realm/*.h include/Realm + fi + else + sh build.sh set-swift-version + fi + ;; + + ###################################### + # Continuous Integration + ###################################### + + "ci-pr") + mkdir -p build/reports + export REALM_DISABLE_ANALYTICS=1 + export REALM_DISABLE_UPDATE_CHECKER=1 + # FIXME: Re-enable once CI can properly unlock the keychain + export REALM_DISABLE_METADATA_ENCRYPTION=1 + + # strip off the ios|tvos version specifier, e.g. the last part of: `ios-device-objc-ios8` + if [[ "$target" =~ ^((ios|tvos)-device(-(objc|swift))?)(-(ios|tvos)[[:digit:]]+)?$ ]]; then + export target=${BASH_REMATCH[1]} + fi + + if [ "$target" = "docs" ]; then + sh build.sh set-swift-version + sh build.sh verify-docs + elif [ "$target" = "swiftlint" ]; then + sh build.sh verify-swiftlint + else + export sha=$GITHUB_PR_SOURCE_BRANCH + export CONFIGURATION=$configuration + export REALM_EXTRA_BUILD_ARGUMENTS='GCC_GENERATE_DEBUGGING_SYMBOLS=NO' + sh build.sh prelaunch-simulator + + source $(brew --prefix nvm)/nvm.sh + export REALM_NODE_PATH="$(nvm which 8)" + + # Reset CoreSimulator.log + mkdir -p ~/Library/Logs/CoreSimulator + echo > ~/Library/Logs/CoreSimulator/CoreSimulator.log + + if [ -d ~/Library/Developer/CoreSimulator/Devices/ ]; then + # Verify that no Realm files still exist + ! find ~/Library/Developer/CoreSimulator/Devices/ -name '*.realm' | grep -q . + fi + + failed=0 + sh build.sh verify-$target 2>&1 | tee build/build.log | xcpretty -r junit -o build/reports/junit.xml || failed=1 + if [ "$failed" = "1" ] && cat build/build.log | grep -E 'DTXProxyChannel|DTXChannel|out of date and needs to be rebuilt|operation never finished bootstrapping'; then + echo "Known Xcode error detected. Running job again." + if cat build/build.log | grep -E 'out of date and needs to be rebuilt'; then + rm -rf build/DerivedData + fi + failed=0 + sh build.sh verify-$target | tee build/build.log | xcpretty -r junit -o build/reports/junit.xml || failed=1 + elif [ "$failed" = "1" ] && tail ~/Library/Logs/CoreSimulator/CoreSimulator.log | grep -E "Operation not supported|Failed to lookup com.apple.coreservices.lsuseractivity.simulatorsupport"; then + echo "Known Xcode error detected. Running job again." + failed=0 + sh build.sh verify-$target | tee build/build.log | xcpretty -r junit -o build/reports/junit.xml || failed=1 + fi + if [ "$failed" = "1" ]; then + echo "\n\n***\nbuild/build.log\n***\n\n" && cat build/build.log || true + echo "\n\n***\nCoreSimulator.log\n***\n\n" && cat ~/Library/Logs/CoreSimulator/CoreSimulator.log + exit 1 + fi + fi + + if [ "$target" = "osx" ] && [ "$configuration" = "Debug" ]; then + gcovr -r . -f ".*Realm.*" -e ".*Tests.*" -e ".*core.*" --xml > build/reports/coverage-report.xml + WS=$(pwd | sed "s/\//\\\\\//g") + sed -i ".bak" "s/\./${WS}/" build/reports/coverage-report.xml + fi + ;; + + ###################################### + # Release packaging + ###################################### + + "package-examples") + ./scripts/package_examples.rb + zip --symlinks -r realm-examples.zip examples -x "examples/installation/*" + ;; + + "package-test-examples") + if ! VERSION=$(echo realm-objc-*.zip | egrep -o '\d*\.\d*\.\d*-[a-z]*(\.\d*)?'); then + VERSION=$(echo realm-objc-*.zip | egrep -o '\d*\.\d*\.\d*') + fi + OBJC="realm-objc-${VERSION}" + SWIFT="realm-swift-${VERSION}" + unzip ${OBJC}.zip + + cp $0 ${OBJC} + cp -r ${source_root}/scripts ${OBJC} + cd ${OBJC} + sh build.sh examples-ios + sh build.sh examples-tvos + sh build.sh examples-osx + cd .. + rm -rf ${OBJC} + + unzip ${SWIFT}.zip + + cp $0 ${SWIFT} + cp -r ${source_root}/scripts ${SWIFT} + cd ${SWIFT} + sh build.sh examples-ios-swift + sh build.sh examples-tvos-swift + cd .. + rm -rf ${SWIFT} + ;; + + "package-ios-static") + sh build.sh prelaunch-simulator + sh build.sh ios-static + + cd build/ios-static + zip --symlinks -r realm-framework-ios-static.zip Realm.framework + ;; + + "package-ios") + sh build.sh prelaunch-simulator + sh build.sh ios-dynamic + cd build/ios + zip --symlinks -r realm-framework-ios.zip Realm.framework + ;; + + "package-osx") + sh build.sh osx + + cd build/DerivedData/Realm/Build/Products/Release + zip --symlinks -r realm-framework-osx.zip Realm.framework + ;; + + "package-watchos") + sh build.sh prelaunch-simulator + sh build.sh watchos + + # If we're building the obj-c library with an Xcode version older than + # 10, we need to also build the arm64_32 slice with Xcode 10 and lipo + # it in + if (( $(xcode_version_major) < 10 )); then + ( + REALM_XCODE_VERSION=10.0 + REALM_SWIFT_VERSION= + set_xcode_and_swift_versions + sh build.sh prelaunch-simulator + xc "-scheme Realm -configuration $CONFIGURATION -sdk watchos ARCHS='arm64_32'" + cp build/DerivedData/Realm/Build/Products/Release-watchos/Realm.framework/*.bcsymbolmap build/watchos/Realm.framework + xcrun lipo \ + -create build/watchos/Realm.framework/Realm build/DerivedData/Realm/Build/Products/Release-watchos/Realm.framework/Realm \ + -output build/watchos-tmp + mv build/watchos-tmp build/watchos/Realm.framework/Realm + ) + fi + + cd build/watchos + zip --symlinks -r realm-framework-watchos.zip Realm.framework + ;; + + "package-tvos") + sh build.sh prelaunch-simulator + sh build.sh tvos + + cd build/tvos + zip --symlinks -r realm-framework-tvos.zip Realm.framework + ;; + + package-*-swift) + PLATFORM=$(echo $COMMAND | cut -d - -f 2) + for version in 9.1 9.2 9.3 9.4 10.0; do + REALM_XCODE_VERSION=$version + REALM_SWIFT_VERSION= + set_xcode_and_swift_versions + sh build.sh prelaunch-simulator + sh build.sh $PLATFORM-swift + done + + cd build/$PLATFORM + ln -s swift-4.0.3 swift-3.2.3 + ln -s swift-4.1 swift-3.3 + ln -s swift-4.1.2 swift-3.3.2 + ln -s swift-4.2 swift-3.4 + zip --symlinks -r realm-swift-framework-$PLATFORM.zip swift-3.2.3 swift-3.3 swift-3.3.2 swift-3.4 swift-4.0.3 swift-4.1 swift-4.1.2 swift-4.2 + ;; + + package-*-swift-3.2.3) + PLATFORM=$(echo $COMMAND | cut -d - -f 2) + mkdir -p build/$PLATFORM + cd build/$PLATFORM + ln -s swift-4.0.2 swift-3.2.3 + zip --symlinks -r realm-swift-framework-$PLATFORM-swift-3.2.3.zip swift-3.2.3 + ;; + + package-*-swift-3.3) + PLATFORM=$(echo $COMMAND | cut -d - -f 2) + mkdir -p build/$PLATFORM + cd build/$PLATFORM + ln -s swift-4.1 swift-3.3 + zip --symlinks -r realm-swift-framework-$PLATFORM-swift-3.3.zip swift-3.3 + ;; + + package-*-swift-3.3.2) + PLATFORM=$(echo $COMMAND | cut -d - -f 2) + mkdir -p build/$PLATFORM + cd build/$PLATFORM + ln -s swift-4.1.2 swift-3.3.2 + zip --symlinks -r realm-swift-framework-$PLATFORM-swift-3.3.2.zip swift-3.3.2 + ;; + + package-*-swift-3.4) + PLATFORM=$(echo $COMMAND | cut -d - -f 2) + mkdir -p build/$PLATFORM + cd build/$PLATFORM + ln -s swift-4.2 swift-3.4 + zip --symlinks -r realm-swift-framework-$PLATFORM-swift-3.4.zip swift-3.4 + ;; + + package-*-swift-*) + PLATFORM=$(echo $COMMAND | cut -d - -f 2) + REALM_SWIFT_VERSION=$(echo $COMMAND | cut -d - -f 4) + REALM_XCODE_VERSION= + + set_xcode_and_swift_versions + sh build.sh prelaunch-simulator + sh build.sh $PLATFORM-swift + + cd build/$PLATFORM + zip --symlinks -r realm-swift-framework-$PLATFORM-swift-$REALM_SWIFT_VERSION.zip swift-$REALM_SWIFT_VERSION + ;; + + "package-release") + LANG="$2" + TEMPDIR=$(mktemp -d $TMPDIR/realm-release-package-${LANG}.XXXX) + + VERSION=$(sh build.sh get-version) + + FOLDER=${TEMPDIR}/realm-${LANG}-${VERSION} + + mkdir -p ${FOLDER}/osx ${FOLDER}/ios ${FOLDER}/watchos ${FOLDER}/tvos + + if [[ "${LANG}" == "objc" ]]; then + mkdir -p ${FOLDER}/ios/static + mkdir -p ${FOLDER}/ios/dynamic + mkdir -p ${FOLDER}/Swift + + ( + cd ${FOLDER}/osx + unzip ${WORKSPACE}/realm-framework-osx.zip + ) + + ( + cd ${FOLDER}/ios/static + unzip ${WORKSPACE}/realm-framework-ios-static.zip + ) + + ( + cd ${FOLDER}/ios/dynamic + unzip ${WORKSPACE}/realm-framework-ios.zip + ) + + ( + cd ${FOLDER}/watchos + unzip ${WORKSPACE}/realm-framework-watchos.zip + ) + + ( + cd ${FOLDER}/tvos + unzip ${WORKSPACE}/realm-framework-tvos.zip + ) + else + ( + cd ${FOLDER}/osx + for f in ${WORKSPACE}/realm-swift-framework-osx-swift-*.zip; do + unzip "$f" + done + ) + + ( + cd ${FOLDER}/ios + for f in ${WORKSPACE}/realm-swift-framework-ios-swift-*.zip; do + unzip "$f" + done + ) + + ( + cd ${FOLDER}/watchos + for f in ${WORKSPACE}/realm-swift-framework-watchos-swift-*.zip; do + unzip "$f" + done + ) + + ( + cd ${FOLDER}/tvos + for f in ${WORKSPACE}/realm-swift-framework-tvos-swift-*.zip; do + unzip "$f" + done + ) + fi + + ( + cd ${WORKSPACE} + cp -R plugin ${FOLDER} + cp LICENSE ${FOLDER}/LICENSE.txt + if [[ "${LANG}" == "objc" ]]; then + cp Realm/Swift/RLMSupport.swift ${FOLDER}/Swift/ + fi + ) + + ( + cd ${FOLDER} + unzip ${WORKSPACE}/realm-examples.zip + cd examples + if [[ "${LANG}" == "objc" ]]; then + rm -rf ios/swift-* tvos/swift-* + else + rm -rf ios/objc ios/rubymotion osx tvos/objc + fi + ) + + cat > ${FOLDER}/docs.webloc < + + + + URL + https://realm.io/docs/${LANG}/${VERSION} + + +EOF + + ( + cd ${TEMPDIR} + zip --symlinks -r realm-${LANG}-${VERSION}.zip realm-${LANG}-${VERSION} + mv realm-${LANG}-${VERSION}.zip ${WORKSPACE} + ) + ;; + + "test-package-release") + # Generate a release package locally for testing purposes + # Real releases should always be done via Jenkins + if [ -z "${WORKSPACE}" ]; then + echo 'WORKSPACE must be set to a directory to assemble the release in' + exit 1 + fi + if [ -d "${WORKSPACE}" ]; then + echo 'WORKSPACE directory should not already exist' + exit 1 + fi + + REALM_SOURCE="$(pwd)" + mkdir -p "$WORKSPACE" + WORKSPACE="$(cd "$WORKSPACE" && pwd)" + export WORKSPACE + cd $WORKSPACE + git clone --recursive $REALM_SOURCE realm-cocoa + cd realm-cocoa + + echo 'Packaging iOS' + sh build.sh package-ios-static + cp build/ios-static/realm-framework-ios-static.zip .. + sh build.sh package-ios + cp build/ios/realm-framework-ios.zip .. + sh build.sh package-ios-swift + cp build/ios/realm-swift-framework-ios.zip .. + + echo 'Packaging OS X' + sh build.sh package-osx + cp build/DerivedData/Realm/Build/Products/Release/realm-framework-osx.zip .. + sh build.sh package-osx-swift + cp build/osx/realm-swift-framework-osx.zip .. + + echo 'Packaging watchOS' + sh build.sh package-watchos + cp build/watchos/realm-framework-watchos.zip .. + sh build.sh package-watchos-swift + cp build/watchos/realm-swift-framework-watchos.zip .. + + echo 'Packaging tvOS' + sh build.sh package-tvos + cp build/tvos/realm-framework-tvos.zip .. + sh build.sh package-tvos-swift + cp build/tvos/realm-swift-framework-tvos.zip .. + + echo 'Packaging examples' + sh build.sh package-examples + cp realm-examples.zip .. + + echo 'Building final release packages' + sh build.sh package-release objc + sh build.sh package-release swift + + echo 'Testing packaged examples' + sh build.sh package-test-examples + ;; + + "github-release") + if [ -z "${GITHUB_ACCESS_TOKEN}" ]; then + echo 'GITHUB_ACCESS_TOKEN must be set to create GitHub releases' + exit 1 + fi + ./scripts/github_release.rb + ;; + + "add-empty-changelog") + empty_section=$(cat < ([#????](https://github.com/realm/realm-js/issues/????), since v?.?.?) +* None. + + + +### Compatibility +* File format: Generates Realms with format v9 (Reads and upgrades all previous formats) +* Realm Object Server: 3.11.0 or later. +* APIs are backwards compatible with all previous releases in the 3.x.y series. +EOS) + changelog=$(cat CHANGELOG.md) + echo "$empty_section" > CHANGELOG.md + echo >> CHANGELOG.md + echo "$changelog" >> CHANGELOG.md + ;; + + *) + echo "Unknown command '$COMMAND'" + usage + exit 1 + ;; +esac diff --git a/Pods/Realm/core/librealmcore-ios.a b/Pods/Realm/core/librealmcore-ios.a new file mode 100644 index 0000000000..40c54b89c6 Binary files /dev/null and b/Pods/Realm/core/librealmcore-ios.a differ diff --git a/Pods/Realm/include/NSError+RLMSync.h b/Pods/Realm/include/NSError+RLMSync.h new file mode 100644 index 0000000000..797db585de --- /dev/null +++ b/Pods/Realm/include/NSError+RLMSync.h @@ -0,0 +1,46 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMSyncErrorActionToken; + +/// NSError category extension providing methods to get data out of Realm's +/// "client reset" error. +@interface NSError (RLMSync) + +/** + Given an appropriate Realm Object Server error, return the token that + can be passed into `+[RLMSyncSession immediatelyHandleError:]` to + immediately perform error clean-up work, or nil if the error isn't of + a type that provides a token. + */ +- (nullable RLMSyncErrorActionToken *)rlmSync_errorActionToken NS_REFINED_FOR_SWIFT; + +/** + Given a Realm Object Server client reset error, return the path where the + backup copy of the Realm will be placed once the client reset process is + complete. + */ +- (nullable NSString *)rlmSync_clientResetBackedUpRealmPath NS_SWIFT_UNAVAILABLE(""); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMAccessor.h b/Pods/Realm/include/RLMAccessor.h new file mode 100644 index 0000000000..59c625a581 --- /dev/null +++ b/Pods/Realm/include/RLMAccessor.h @@ -0,0 +1,53 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMObjectSchema, RLMProperty, RLMObjectBase; + +NS_ASSUME_NONNULL_BEGIN + +// +// Accessors Class Creation/Caching +// + +// get accessor classes for an object class - generates classes if not cached +Class RLMManagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema, const char *name); +Class RLMUnmanagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema); + +// +// Dynamic getters/setters +// +FOUNDATION_EXTERN void RLMDynamicValidatedSet(RLMObjectBase *obj, NSString *propName, id __nullable val); +FOUNDATION_EXTERN id __nullable RLMDynamicGet(RLMObjectBase *obj, RLMProperty *prop); +FOUNDATION_EXTERN id __nullable RLMDynamicGetByName(RLMObjectBase *obj, NSString *propName, bool asList); + +// by property/column +void RLMDynamicSet(RLMObjectBase *obj, RLMProperty *prop, id val); + +// +// Class modification +// + +// Replace className method for the given class +void RLMReplaceClassNameMethod(Class accessorClass, NSString *className); + +// Replace sharedSchema method for the given class +void RLMReplaceSharedSchemaMethod(Class accessorClass, RLMObjectSchema * __nullable schema); + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMAccessor.hpp b/Pods/Realm/include/RLMAccessor.hpp new file mode 100644 index 0000000000..93d7e68055 --- /dev/null +++ b/Pods/Realm/include/RLMAccessor.hpp @@ -0,0 +1,116 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMAccessor.h" + +#import "object_accessor.hpp" + +#import "RLMUtil.hpp" + +@class RLMRealm; +class RLMClassInfo; +class RLMObservationInfo; + +// realm::util::Optional doesn't work because Objective-C types can't +// be members of unions with ARC, so this covers the subset of Optional that we +// actually need. +struct RLMOptionalId { + id value; + RLMOptionalId(id value) : value(value) { } + explicit operator bool() const noexcept { return value; } + id operator*() const noexcept { return value; } +}; + +class RLMAccessorContext { +public: + // Accessor context interface + RLMAccessorContext(RLMAccessorContext& parent, realm::Property const& property); + + id box(realm::List&&); + id box(realm::Results&&); + id box(realm::Object&&); + id box(realm::RowExpr); + + id box(bool v) { return @(v); } + id box(double v) { return @(v); } + id box(float v) { return @(v); } + id box(long long v) { return @(v); } + id box(realm::StringData v) { return RLMStringDataToNSString(v) ?: NSNull.null; } + id box(realm::BinaryData v) { return RLMBinaryDataToNSData(v) ?: NSNull.null; } + id box(realm::Timestamp v) { return RLMTimestampToNSDate(v) ?: NSNull.null; } + id box(realm::Mixed v) { return RLMMixedToObjc(v); } + + id box(realm::util::Optional v) { return v ? @(*v) : NSNull.null; } + id box(realm::util::Optional v) { return v ? @(*v) : NSNull.null; } + id box(realm::util::Optional v) { return v ? @(*v) : NSNull.null; } + id box(realm::util::Optional v) { return v ? @(*v) : NSNull.null; } + + void will_change(realm::Row const&, realm::Property const&); + void will_change(realm::Object& obj, realm::Property const& prop) { will_change(obj.row(), prop); } + void did_change(); + + RLMOptionalId value_for_property(id dict, std::string const&, size_t prop_index); + RLMOptionalId default_value_for_property(realm::ObjectSchema const&, + std::string const& prop); + + bool is_same_list(realm::List const& list, id v) const noexcept; + + template + void enumerate_list(__unsafe_unretained const id v, Func&& func) { + for (id value in v) { + func(value); + } + } + + template + T unbox(id v, bool create = false, bool update = false); + + bool is_null(id v) { return v == NSNull.null; } + id null_value() { return NSNull.null; } + id no_value() { return nil; } + bool allow_missing(id v) { return [v isKindOfClass:[NSArray class]]; } + + std::string print(id obj) { return [obj description].UTF8String; } + + // Internal API + RLMAccessorContext(RLMObjectBase *parentObject, const realm::Property *property = nullptr); + RLMAccessorContext(RLMRealm *realm, RLMClassInfo& info, bool promote=true); + + // The property currently being accessed; needed for KVO things for boxing + // List and Results + RLMProperty *currentProperty; + +private: + __unsafe_unretained RLMRealm *const _realm; + RLMClassInfo& _info; + // If true, promote unmanaged RLMObjects passed to box() with create=true + // rather than copying them + bool _promote_existing = true; + // Parent object of the thing currently being processed, for KVO purposes + __unsafe_unretained RLMObjectBase *const _parentObject = nil; + + // Cached default values dictionary to avoid having to call the class method + // for every property + NSDictionary *_defaultValues; + + RLMObservationInfo *_observationInfo = nullptr; + NSString *_kvoPropertyName = nil; + + id defaultValue(NSString *key); + id propertyValue(id obj, size_t propIndex, __unsafe_unretained RLMProperty *const prop); +}; diff --git a/Pods/Realm/include/RLMAnalytics.hpp b/Pods/Realm/include/RLMAnalytics.hpp new file mode 100644 index 0000000000..ccb4ea26b5 --- /dev/null +++ b/Pods/Realm/include/RLMAnalytics.hpp @@ -0,0 +1,55 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +// Asynchronously submits build information to Realm if running in an iOS +// simulator or on OS X if a debugger is attached. Does nothing if running on an +// iOS / watchOS device or if a debugger is *not* attached. +// +// To be clear: this does *not* run when your app is in production or on +// your end-user’s devices; it will only run in the simulator or when a debugger +// is attached. +// +// Why are we doing this? In short, because it helps us build a better product +// for you. None of the data personally identifies you, your employer or your +// app, but it *will* help us understand what language you use, what iOS +// versions you target, etc. Having this info will help prioritizing our time, +// adding new features and deprecating old features. Collecting an anonymized +// bundle & anonymized MAC is the only way for us to count actual usage of the +// other metrics accurately. If we don’t have a way to deduplicate the info +// reported, it will be useless, as a single developer building their Swift app +// 10 times would report 10 times more than a single Objective-C developer that +// only builds once, making the data all but useless. +// No one likes sharing data unless it’s necessary, we get it, and we’ve +// debated adding this for a long long time. Since Realm is a free product +// without an email signup, we feel this is a necessary step so we can collect +// relevant data to build a better product for you. If you truly, absolutely +// feel compelled to not send this data back to Realm, then you can set an env +// variable named REALM_DISABLE_ANALYTICS. Since Realm is free we believe +// letting these analytics run is a small price to pay for the product & support +// we give you. +// +// Currently the following information is reported: +// - What version of Realm is being used, and from which language (obj-c or Swift). +// - What version of OS X it's running on (in case Xcode aggressively drops +// support for older versions again, we need to know what we need to support). +// - The minimum iOS/OS X version that the application is targeting (again, to +// help us decide what versions we need to support). +// - An anonymous MAC address and bundle ID to aggregate the other information on. +// - What version of Swift is being used (if applicable). + +void RLMSendAnalytics(); diff --git a/Pods/Realm/include/RLMArray.h b/Pods/Realm/include/RLMArray.h new file mode 100644 index 0000000000..3ef38eb9bd --- /dev/null +++ b/Pods/Realm/include/RLMArray.h @@ -0,0 +1,440 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMObject, RLMResults; + +/** + `RLMArray` is the container type in Realm used to define to-many relationships. + + Unlike an `NSArray`, `RLMArray`s hold a single type, specified by the `objectClassName` property. + This is referred to in these docs as the “type” of the array. + + When declaring an `RLMArray` property, the type must be marked as conforming to a + protocol by the same name as the objects it should contain (see the + `RLM_ARRAY_TYPE` macro). In addition, the property can be declared using Objective-C + generics for better compile-time type safety. + + RLM_ARRAY_TYPE(ObjectType) + ... + @property RLMArray *arrayOfObjectTypes; + + `RLMArray`s can be queried with the same predicates as `RLMObject` and `RLMResult`s. + + `RLMArray`s cannot be created directly. `RLMArray` properties on `RLMObject`s are + lazily created when accessed, or can be obtained by querying a Realm. + + ### Key-Value Observing + + `RLMArray` supports array key-value observing on `RLMArray` properties on `RLMObject` + subclasses, and the `invalidated` property on `RLMArray` instances themselves is + key-value observing compliant when the `RLMArray` is attached to a managed + `RLMObject` (`RLMArray`s on unmanaged `RLMObject`s will never become invalidated). + + Because `RLMArray`s are attached to the object which they are a property of, they + do not require using the mutable collection proxy objects from + `-mutableArrayValueForKey:` or KVC-compatible mutation methods on the containing + object. Instead, you can call the mutation methods on the `RLMArray` directly. + */ + +@interface RLMArray : NSObject + +#pragma mark - Properties + +/** + The number of objects in the array. + */ +@property (nonatomic, readonly, assign) NSUInteger count; + +/** + The type of the objects in the array. + */ +@property (nonatomic, readonly, assign) RLMPropertyType type; + +/** + Indicates whether the objects in the collection can be `nil`. + */ +@property (nonatomic, readonly, getter = isOptional) BOOL optional; + +/** + The class name of the objects contained in the array. + + Will be `nil` if `type` is not RLMPropertyTypeObject. + */ +@property (nonatomic, readonly, copy, nullable) NSString *objectClassName; + +/** + The Realm which manages the array. Returns `nil` for unmanaged arrays. + */ +@property (nonatomic, readonly, nullable) RLMRealm *realm; + +/** + Indicates if the array can no longer be accessed. + */ +@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; + +#pragma mark - Accessing Objects from an Array + +/** + Returns the object at the index specified. + + @param index The index to look up. + + @return An object of the type contained in the array. + */ +- (RLMObjectType)objectAtIndex:(NSUInteger)index; + +/** + Returns the first object in the array. + + Returns `nil` if called on an empty array. + + @return An object of the type contained in the array. + */ +- (nullable RLMObjectType)firstObject; + +/** + Returns the last object in the array. + + Returns `nil` if called on an empty array. + + @return An object of the type contained in the array. + */ +- (nullable RLMObjectType)lastObject; + + + +#pragma mark - Adding, Removing, and Replacing Objects in an Array + +/** + Adds an object to the end of the array. + + @warning This method may only be called during a write transaction. + + @param object An object of the type contained in the array. + */ +- (void)addObject:(RLMObjectType)object; + +/** + Adds an array of objects to the end of the array. + + @warning This method may only be called during a write transaction. + + @param objects An enumerable object such as `NSArray` or `RLMResults` which contains objects of the + same class as the array. + */ +- (void)addObjects:(id)objects; + +/** + Inserts an object at the given index. + + Throws an exception if the index exceeds the bounds of the array. + + @warning This method may only be called during a write transaction. + + @param anObject An object of the type contained in the array. + @param index The index at which to insert the object. + */ +- (void)insertObject:(RLMObjectType)anObject atIndex:(NSUInteger)index; + +/** + Removes an object at the given index. + + Throws an exception if the index exceeds the bounds of the array. + + @warning This method may only be called during a write transaction. + + @param index The array index identifying the object to be removed. + */ +- (void)removeObjectAtIndex:(NSUInteger)index; + +/** + Removes the last object in the array. + + This is a no-op if the array is already empty. + + @warning This method may only be called during a write transaction. +*/ +- (void)removeLastObject; + +/** + Removes all objects from the array. + + @warning This method may only be called during a write transaction. + */ +- (void)removeAllObjects; + +/** + Replaces an object at the given index with a new object. + + Throws an exception if the index exceeds the bounds of the array. + + @warning This method may only be called during a write transaction. + + @param index The index of the object to be replaced. + @param anObject An object (of the same type as returned from the `objectClassName` selector). + */ +- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(RLMObjectType)anObject; + +/** + Moves the object at the given source index to the given destination index. + + Throws an exception if the index exceeds the bounds of the array. + + @warning This method may only be called during a write transaction. + + @param sourceIndex The index of the object to be moved. + @param destinationIndex The index to which the object at `sourceIndex` should be moved. + */ +- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex; + +/** + Exchanges the objects in the array at given indices. + + Throws an exception if either index exceeds the bounds of the array. + + @warning This method may only be called during a write transaction. + + @param index1 The index of the object which should replace the object at index `index2`. + @param index2 The index of the object which should replace the object at index `index1`. + */ +- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2; + +#pragma mark - Querying an Array + +/** + Returns the index of an object in the array. + + Returns `NSNotFound` if the object is not found in the array. + + @param object An object (of the same type as returned from the `objectClassName` selector). + */ +- (NSUInteger)indexOfObject:(RLMObjectType)object; + +/** + Returns the index of the first object in the array matching the predicate. + + @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. + + @return The index of the object, or `NSNotFound` if the object is not found in the array. + */ +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Returns the index of the first object in the array matching the predicate. + + @param predicate The predicate with which to filter the objects. + + @return The index of the object, or `NSNotFound` if the object is not found in the array. + */ +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate; + +/** + Returns all the objects matching the given predicate in the array. + + @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. + + @return An `RLMResults` of objects that match the given predicate. + */ +- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Returns all the objects matching the given predicate in the array. + + @param predicate The predicate with which to filter the objects. + + @return An `RLMResults` of objects that match the given predicate + */ +- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate; + +/** + Returns a sorted `RLMResults` from the array. + + @param keyPath The key path to sort by. + @param ascending The direction to sort in. + + @return An `RLMResults` sorted by the specified key path. + */ +- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending; + +/** + Returns a sorted `RLMResults` from the array. + + @param properties An array of `RLMSortDescriptor`s to sort by. + + @return An `RLMResults` sorted by the specified properties. + */ +- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties; + +/// :nodoc: +- (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index; + +/// :nodoc: +- (void)setObject:(RLMObjectType)newValue atIndexedSubscript:(NSUInteger)index; + +#pragma mark - Notifications + +/** + Registers a block to be called each time the array changes. + + The block will be asynchronously called with the initial array, and then + called again after each write transaction which changes any of the objects in + the array, which objects are in the results, or the order of the objects in the + array. + + The `changes` parameter will be `nil` the first time the block is called. + For each call after that, it will contain information about + which rows in the array were added, removed or modified. If a write transaction + did not modify any objects in the array, the block is not called at all. + See the `RLMCollectionChange` documentation for information on how the changes + are reported and an example of updating a `UITableView`. + + If an error occurs the block will be called with `nil` for the results + parameter and a non-`nil` error. Currently the only errors that can occur are + when opening the Realm on the background worker thread. + + Notifications are delivered via the standard run loop, and so can't be + delivered while the run loop is blocked by other activity. When + notifications can't be delivered instantly, multiple notifications may be + coalesced into a single notification. This can include the notification + with the initial results. For example, the following code performs a write + transaction immediately after adding the notification block, so there is no + opportunity for the initial notification to be delivered first. As a + result, the initial notification will reflect the state of the Realm after + the write transaction. + + Person *person = [[Person allObjectsInRealm:realm] firstObject]; + NSLog(@"person.dogs.count: %zu", person.dogs.count); // => 0 + self.token = [person.dogs addNotificationBlock(RLMArray *dogs, + RLMCollectionChange *changes, + NSError *error) { + // Only fired once for the example + NSLog(@"dogs.count: %zu", dogs.count) // => 1 + }]; + [realm transactionWithBlock:^{ + Dog *dog = [[Dog alloc] init]; + dog.name = @"Rex"; + [person.dogs addObject:dog]; + }]; + // end of run loop execution context + + You must retain the returned token for as long as you want updates to continue + to be sent to the block. To stop receiving updates, call `-invalidate` on the token. + + @warning This method cannot be called during a write transaction, or when the + containing Realm is read-only. + @warning This method may only be called on a managed array. + + @param block The block to be called each time the array changes. + @return A token which must be held for as long as you want updates to be delivered. + */ +- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *__nullable array, + RLMCollectionChange *__nullable changes, + NSError *__nullable error))block __attribute__((warn_unused_result)); + +#pragma mark - Aggregating Property Values + +/** + Returns the minimum (lowest) value of the given property among all the objects in the array. + + NSNumber *min = [object.arrayProperty minOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose minimum value is desired. Only properties of + types `int`, `float`, `double`, and `NSDate` are supported. + + @return The minimum value of the property, or `nil` if the array is empty. + */ +- (nullable id)minOfProperty:(NSString *)property; + +/** + Returns the maximum (highest) value of the given property among all the objects in the array. + + NSNumber *max = [object.arrayProperty maxOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose maximum value is desired. Only properties of + types `int`, `float`, `double`, and `NSDate` are supported. + + @return The maximum value of the property, or `nil` if the array is empty. + */ +- (nullable id)maxOfProperty:(NSString *)property; + +/** + Returns the sum of the values of a given property over all the objects in the array. + + NSNumber *sum = [object.arrayProperty sumOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose values should be summed. Only properties of + types `int`, `float`, and `double` are supported. + + @return The sum of the given property. + */ +- (NSNumber *)sumOfProperty:(NSString *)property; + +/** + Returns the average value of a given property over the objects in the array. + + NSNumber *average = [object.arrayProperty averageOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose average value should be calculated. Only + properties of types `int`, `float`, and `double` are supported. + + @return The average value of the given property, or `nil` if the array is empty. + */ +- (nullable NSNumber *)averageOfProperty:(NSString *)property; + + +#pragma mark - Unavailable Methods + +/** + `-[RLMArray init]` is not available because `RLMArray`s cannot be created directly. + `RLMArray` properties on `RLMObject`s are lazily created when accessed. + */ +- (instancetype)init __attribute__((unavailable("RLMArrays cannot be created directly"))); + +/** + `+[RLMArray new]` is not available because `RLMArray`s cannot be created directly. + `RLMArray` properties on `RLMObject`s are lazily created when accessed. + */ ++ (instancetype)new __attribute__((unavailable("RLMArrays cannot be created directly"))); + +@end + +/// :nodoc: +@interface RLMArray (Swift) +// for use only in Swift class definitions +- (instancetype)initWithObjectClassName:(NSString *)objectClassName; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMArray_Private.h b/Pods/Realm/include/RLMArray_Private.h new file mode 100644 index 0000000000..02b908ab98 --- /dev/null +++ b/Pods/Realm/include/RLMArray_Private.h @@ -0,0 +1,32 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMArray () +- (instancetype)initWithObjectClassName:(NSString *)objectClassName; +- (instancetype)initWithObjectType:(RLMPropertyType)type optional:(BOOL)optional; +- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth; +@end + +void RLMArrayValidateMatchingObjectType(RLMArray *array, id value); + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMArray_Private.hpp b/Pods/Realm/include/RLMArray_Private.hpp new file mode 100644 index 0000000000..08a4487e71 --- /dev/null +++ b/Pods/Realm/include/RLMArray_Private.hpp @@ -0,0 +1,73 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMArray_Private.h" + +#import "RLMCollection_Private.hpp" + +#import "RLMResults_Private.hpp" + +#import +#import + +namespace realm { + class Results; +} + +@class RLMObjectBase, RLMObjectSchema, RLMProperty; +class RLMClassInfo; +class RLMObservationInfo; + +@interface RLMArray () { +@protected + NSString *_objectClassName; + RLMPropertyType _type; + BOOL _optional; +@public + // The name of the property which this RLMArray represents + NSString *_key; + __weak RLMObjectBase *_parentObject; +} +@end + +@interface RLMManagedArray : RLMArray +- (instancetype)initWithParent:(RLMObjectBase *)parentObject property:(RLMProperty *)property; +- (RLMManagedArray *)initWithList:(realm::List)list + realm:(__unsafe_unretained RLMRealm *const)realm + parentInfo:(RLMClassInfo *)parentInfo + property:(__unsafe_unretained RLMProperty *const)property; + +- (bool)isBackedByList:(realm::List const&)list; + +// deletes all objects in the RLMArray from their containing realms +- (void)deleteObjectsFromRealm; +@end + +void RLMValidateArrayObservationKey(NSString *keyPath, RLMArray *array); + +// Initialize the observation info for an array if needed +void RLMEnsureArrayObservationInfo(std::unique_ptr& info, + NSString *keyPath, RLMArray *array, id observed); + + +// +// RLMResults private methods +// +@interface RLMResults () +- (void)deleteObjectsFromRealm; +@end diff --git a/Pods/Realm/include/RLMClassInfo.hpp b/Pods/Realm/include/RLMClassInfo.hpp new file mode 100644 index 0000000000..7d1d23e526 --- /dev/null +++ b/Pods/Realm/include/RLMClassInfo.hpp @@ -0,0 +1,113 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import +#import + +namespace realm { + class ObjectSchema; + class Schema; + class Table; + struct Property; +} + +class RLMObservationInfo; +@class RLMRealm, RLMSchema, RLMObjectSchema, RLMProperty; + +NS_ASSUME_NONNULL_BEGIN + +namespace std { +// Add specializations so that NSString can be used as the key for hash containers +template<> struct hash { + size_t operator()(__unsafe_unretained NSString *const str) const { + return [str hash]; + } +}; +template<> struct equal_to { + bool operator()(__unsafe_unretained NSString * lhs, __unsafe_unretained NSString *rhs) const { + return [lhs isEqualToString:rhs]; + } +}; +} + +// The per-RLMRealm object schema information which stores the cached table +// reference, handles table column lookups, and tracks observed objects +class RLMClassInfo { +public: + RLMClassInfo(RLMRealm *, RLMObjectSchema *, const realm::ObjectSchema *); + + __unsafe_unretained RLMRealm *const realm; + __unsafe_unretained RLMObjectSchema *const rlmObjectSchema; + const realm::ObjectSchema *const objectSchema; + + // Storage for the functionality in RLMObservation for handling indirect + // changes to KVO-observed things + std::vector observedObjects; + + // Get the table for this object type. Will return nullptr only if it's a + // read-only Realm that is missing the table entirely. + realm::Table *_Nullable table() const; + + // Get the RLMProperty for a given table column, or `nil` if it is a column + // not used by the current schema + RLMProperty *_Nullable propertyForTableColumn(NSUInteger) const noexcept; + + // Get the RLMProperty that's used as the primary key, or `nil` if there is + // no primary key for the current schema + RLMProperty *_Nullable propertyForPrimaryKey() const noexcept; + + // Get the table column for the given property. The property must be a valid + // persisted property. + NSUInteger tableColumn(NSString *propertyName) const; + NSUInteger tableColumn(RLMProperty *property) const; + + // Get the info for the target of the link at the given property index. + RLMClassInfo &linkTargetType(size_t propertyIndex); + + // Get the info for the target of the given property + RLMClassInfo &linkTargetType(realm::Property const& property); + + void releaseTable() { m_table = nullptr; } + +private: + mutable realm::Table *_Nullable m_table = nullptr; + std::vector m_linkTargets; +}; + +// A per-RLMRealm object schema map which stores RLMClassInfo keyed on the name +class RLMSchemaInfo { + using impl = std::unordered_map; +public: + RLMSchemaInfo() = default; + RLMSchemaInfo(RLMRealm *realm); + + RLMSchemaInfo clone(realm::Schema const& source_schema, RLMRealm *target_realm); + + // Look up by name, throwing if it's not present + RLMClassInfo& operator[](NSString *name); + + impl::iterator begin() noexcept; + impl::iterator end() noexcept; + impl::const_iterator begin() const noexcept; + impl::const_iterator end() const noexcept; +private: + std::unordered_map m_objects; +}; + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMCollection.h b/Pods/Realm/include/RLMCollection.h new file mode 100644 index 0000000000..9d3fa7e854 --- /dev/null +++ b/Pods/Realm/include/RLMCollection.h @@ -0,0 +1,400 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMRealm, RLMResults, RLMSortDescriptor, RLMNotificationToken, RLMCollectionChange; +typedef NS_ENUM(int32_t, RLMPropertyType); + +/** + A homogenous collection of Realm-managed objects. Examples of conforming types + include `RLMArray`, `RLMResults`, and `RLMLinkingObjects`. + */ +@protocol RLMCollection + +@required + +#pragma mark - Properties + +/** + The number of objects in the collection. + */ +@property (nonatomic, readonly, assign) NSUInteger count; + +/** + The type of the objects in the collection. + */ +@property (nonatomic, readonly, assign) RLMPropertyType type; + +/** + Indicates whether the objects in the collection can be `nil`. + */ +@property (nonatomic, readonly, getter = isOptional) BOOL optional; + +/** + The class name of the objects contained in the collection. + + Will be `nil` if `type` is not RLMPropertyTypeObject. + */ +@property (nonatomic, readonly, copy, nullable) NSString *objectClassName; + +/** + The Realm which manages the collection, or `nil` for unmanaged collections. + */ +@property (nonatomic, readonly) RLMRealm *realm; + +#pragma mark - Accessing Objects from a Collection + +/** + Returns the object at the index specified. + + @param index The index to look up. + + @return An object of the type contained in the collection. + */ +- (id)objectAtIndex:(NSUInteger)index; + +/** + Returns the first object in the collection. + + Returns `nil` if called on an empty collection. + + @return An object of the type contained in the collection. + */ +- (nullable id)firstObject; + +/** + Returns the last object in the collection. + + Returns `nil` if called on an empty collection. + + @return An object of the type contained in the collection. + */ +- (nullable id)lastObject; + +#pragma mark - Querying a Collection + +/** + Returns the index of an object in the collection. + + Returns `NSNotFound` if the object is not found in the collection. + + @param object An object (of the same type as returned from the `objectClassName` selector). + */ +- (NSUInteger)indexOfObject:(id)object; + +/** + Returns the index of the first object in the collection matching the predicate. + + @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. + + @return The index of the object, or `NSNotFound` if the object is not found in the collection. + */ +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Returns the index of the first object in the collection matching the predicate. + + @param predicate The predicate with which to filter the objects. + + @return The index of the object, or `NSNotFound` if the object is not found in the collection. + */ +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate; + +/** + Returns all objects matching the given predicate in the collection. + + @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. + + @return An `RLMResults` containing objects that match the given predicate. + */ +- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Returns all objects matching the given predicate in the collection. + + @param predicate The predicate with which to filter the objects. + + @return An `RLMResults` containing objects that match the given predicate. + */ +- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate; + +/** + Returns a sorted `RLMResults` from the collection. + + @param keyPath The keyPath to sort by. + @param ascending The direction to sort in. + + @return An `RLMResults` sorted by the specified key path. + */ +- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending; + +/** + Returns a sorted `RLMResults` from the collection. + + @param properties An array of `RLMSortDescriptor`s to sort by. + + @return An `RLMResults` sorted by the specified properties. + */ +- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties; + +/// :nodoc: +- (id)objectAtIndexedSubscript:(NSUInteger)index; + +/** + Returns an `NSArray` containing the results of invoking `valueForKey:` using `key` on each of the collection's objects. + + @param key The name of the property. + + @return An `NSArray` containing results. + */ +- (nullable id)valueForKey:(NSString *)key; + +/** + Invokes `setValue:forKey:` on each of the collection's objects using the specified `value` and `key`. + + @warning This method may only be called during a write transaction. + + @param value The object value. + @param key The name of the property. + */ +- (void)setValue:(nullable id)value forKey:(NSString *)key; + +#pragma mark - Notifications + +/** + Registers a block to be called each time the collection changes. + + The block will be asynchronously called with the initial collection, and then + called again after each write transaction which changes either any of the + objects in the collection, or which objects are in the collection. + + The `change` parameter will be `nil` the first time the block is called. + For each call after that, it will contain information about + which rows in the collection were added, removed or modified. If a write transaction + did not modify any objects in this collection, the block is not called at all. + See the `RLMCollectionChange` documentation for information on how the changes + are reported and an example of updating a `UITableView`. + + If an error occurs the block will be called with `nil` for the collection + parameter and a non-`nil` error. Currently the only errors that can occur are + when opening the Realm on the background worker thread. + + At the time when the block is called, the collection object will be fully + evaluated and up-to-date, and as long as you do not perform a write transaction + on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will + never perform blocking work. + + Notifications are delivered via the standard run loop, and so can't be + delivered while the run loop is blocked by other activity. When + notifications can't be delivered instantly, multiple notifications may be + coalesced into a single notification. This can include the notification + with the initial collection. For example, the following code performs a write + transaction immediately after adding the notification block, so there is no + opportunity for the initial notification to be delivered first. As a + result, the initial notification will reflect the state of the Realm after + the write transaction. + + id collection = [Dog allObjects]; + NSLog(@"dogs.count: %zu", dogs.count); // => 0 + self.token = [collection addNotificationBlock:^(id dogs, + RLMCollectionChange *changes, + NSError *error) { + // Only fired once for the example + NSLog(@"dogs.count: %zu", dogs.count); // => 1 + }]; + [realm transactionWithBlock:^{ + Dog *dog = [[Dog alloc] init]; + dog.name = @"Rex"; + [realm addObject:dog]; + }]; + // end of run loop execution context + + You must retain the returned token for as long as you want updates to continue + to be sent to the block. To stop receiving updates, call `-invalidate` on the token. + + @warning This method cannot be called during a write transaction, or when the + containing Realm is read-only. + + @param block The block to be called each time the collection changes. + @return A token which must be held for as long as you want collection notifications to be delivered. + */ +- (RLMNotificationToken *)addNotificationBlock:(void (^)(id __nullable collection, + RLMCollectionChange *__nullable change, + NSError *__nullable error))block __attribute__((warn_unused_result)); + +#pragma mark - Aggregating Property Values + +/** + Returns the minimum (lowest) value of the given property among all the objects + in the collection. + + NSNumber *min = [results minOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose minimum value is desired. Only properties of + types `int`, `float`, `double`, and `NSDate` are supported. + + @return The minimum value of the property, or `nil` if the Results are empty. + */ +- (nullable id)minOfProperty:(NSString *)property; + +/** + Returns the maximum (highest) value of the given property among all the objects + in the collection. + + NSNumber *max = [results maxOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose maximum value is desired. Only properties of + types `int`, `float`, `double`, and `NSDate` are supported. + + @return The maximum value of the property, or `nil` if the Results are empty. + */ +- (nullable id)maxOfProperty:(NSString *)property; + +/** + Returns the sum of the values of a given property over all the objects in the collection. + + NSNumber *sum = [results sumOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose values should be summed. Only properties of + types `int`, `float`, and `double` are supported. + + @return The sum of the given property. + */ +- (NSNumber *)sumOfProperty:(NSString *)property; + +/** + Returns the average value of a given property over the objects in the collection. + + NSNumber *average = [results averageOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose average value should be calculated. Only + properties of types `int`, `float`, and `double` are supported. + + @return The average value of the given property, or `nil` if the Results are empty. + */ +- (nullable NSNumber *)averageOfProperty:(NSString *)property; + +@end + +/** + An `RLMSortDescriptor` stores a property name and a sort order for use with + `sortedResultsUsingDescriptors:`. It is similar to `NSSortDescriptor`, but supports + only the subset of functionality which can be efficiently run by Realm's query + engine. + + `RLMSortDescriptor` instances are immutable. + */ +@interface RLMSortDescriptor : NSObject + +#pragma mark - Properties + +/** + The key path which the sort descriptor orders results by. + */ +@property (nonatomic, readonly) NSString *keyPath; + +/** + Whether the descriptor sorts in ascending or descending order. + */ +@property (nonatomic, readonly) BOOL ascending; + +#pragma mark - Methods + +/** + Returns a new sort descriptor for the given key path and sort direction. + */ ++ (instancetype)sortDescriptorWithKeyPath:(NSString *)keyPath ascending:(BOOL)ascending; + +/** + Returns a copy of the receiver with the sort direction reversed. + */ +- (instancetype)reversedSortDescriptor; + +@end + +/** + A `RLMCollectionChange` object encapsulates information about changes to collections + that are reported by Realm notifications. + + `RLMCollectionChange` is passed to the notification blocks registered with + `-addNotificationBlock` on `RLMArray` and `RLMResults`, and reports what rows in the + collection changed since the last time the notification block was called. + + The change information is available in two formats: a simple array of row + indices in the collection for each type of change, and an array of index paths + in a requested section suitable for passing directly to `UITableView`'s batch + update methods. A complete example of updating a `UITableView` named `tv`: + + [tv beginUpdates]; + [tv deleteRowsAtIndexPaths:[changes deletionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic]; + [tv insertRowsAtIndexPaths:[changes insertionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic]; + [tv reloadRowsAtIndexPaths:[changes modificationsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic]; + [tv endUpdates]; + + All of the arrays in an `RLMCollectionChange` are always sorted in ascending order. + */ +@interface RLMCollectionChange : NSObject +/// The indices of objects in the previous version of the collection which have +/// been removed from this one. +@property (nonatomic, readonly) NSArray *deletions; + +/// The indices in the new version of the collection which were newly inserted. +@property (nonatomic, readonly) NSArray *insertions; + +/** + The indices in the new version of the collection which were modified. + + For `RLMResults`, this means that one or more of the properties of the object at + that index were modified (or an object linked to by that object was + modified). + + For `RLMArray`, the array itself being modified to contain a + different object at that index will also be reported as a modification. + */ +@property (nonatomic, readonly) NSArray *modifications; + +/// Returns the index paths of the deletion indices in the given section. +- (NSArray *)deletionsInSection:(NSUInteger)section; + +/// Returns the index paths of the insertion indices in the given section. +- (NSArray *)insertionsInSection:(NSUInteger)section; + +/// Returns the index paths of the modification indices in the given section. +- (NSArray *)modificationsInSection:(NSUInteger)section; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMCollection_Private.h b/Pods/Realm/include/RLMCollection_Private.h new file mode 100644 index 0000000000..4c3f882cd2 --- /dev/null +++ b/Pods/Realm/include/RLMCollection_Private.h @@ -0,0 +1,26 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import + +@protocol RLMFastEnumerable; + +void RLMCollectionSetValueForKey(id collection, NSString *key, id value); +FOUNDATION_EXTERN NSString *RLMDescriptionWithMaxDepth(NSString *name, id collection, NSUInteger depth); diff --git a/Pods/Realm/include/RLMCollection_Private.hpp b/Pods/Realm/include/RLMCollection_Private.hpp new file mode 100644 index 0000000000..908c886718 --- /dev/null +++ b/Pods/Realm/include/RLMCollection_Private.hpp @@ -0,0 +1,87 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import + +namespace realm { + class List; + class Results; + class TableView; + struct CollectionChangeSet; + struct NotificationToken; +} +class RLMClassInfo; +@class RLMFastEnumerator; + +@protocol RLMFastEnumerable +@property (nonatomic, readonly) RLMRealm *realm; +@property (nonatomic, readonly) RLMClassInfo *objectInfo; +@property (nonatomic, readonly) NSUInteger count; + +- (realm::TableView)tableView; +- (RLMFastEnumerator *)fastEnumerator; +@end + +// An object which encapulates the shared logic for fast-enumerating RLMArray +// and RLMResults, and has a buffer to store strong references to the current +// set of enumerated items +@interface RLMFastEnumerator : NSObject +- (instancetype)initWithList:(realm::List&)list + collection:(id)collection + realm:(RLMRealm *)realm + classInfo:(RLMClassInfo&)info; +- (instancetype)initWithResults:(realm::Results&)results + collection:(id)collection + realm:(RLMRealm *)realm + classInfo:(RLMClassInfo&)info; + +// Detach this enumerator from the source collection. Must be called before the +// source collection is changed. +- (void)detach; + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state + count:(NSUInteger)len; +@end +NSUInteger RLMFastEnumerate(NSFastEnumerationState *state, NSUInteger len, id collection); + +@interface RLMNotificationToken () +- (void)suppressNextNotification; +- (RLMRealm *)realm; +@end + +@interface RLMCancellationToken : RLMNotificationToken +- (instancetype)initWithToken:(realm::NotificationToken)token realm:(RLMRealm *)realm; +@end + +@interface RLMCollectionChange () +- (instancetype)initWithChanges:(realm::CollectionChangeSet)indices; +@end + +template +RLMNotificationToken *RLMAddNotificationBlock(id objcCollection, + Collection& collection, + void (^block)(id, RLMCollectionChange *, NSError *), + bool suppressInitialChange=false); + +template +NSArray *RLMCollectionValueForKey(Collection& collection, NSString *key, + RLMRealm *realm, RLMClassInfo& info); + +std::vector> RLMSortDescriptorsToKeypathArray(NSArray *properties); diff --git a/Pods/Realm/include/RLMConstants.h b/Pods/Realm/include/RLMConstants.h new file mode 100644 index 0000000000..f73fe83874 --- /dev/null +++ b/Pods/Realm/include/RLMConstants.h @@ -0,0 +1,215 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +// For compatibility with Xcode 7, before extensible string enums were introduced, +#ifdef NS_EXTENSIBLE_STRING_ENUM +#define RLM_EXTENSIBLE_STRING_ENUM NS_EXTENSIBLE_STRING_ENUM +#define RLM_EXTENSIBLE_STRING_ENUM_CASE_SWIFT_NAME(_, extensible_string_enum) NS_SWIFT_NAME(extensible_string_enum) +#else +#define RLM_EXTENSIBLE_STRING_ENUM +#define RLM_EXTENSIBLE_STRING_ENUM_CASE_SWIFT_NAME(fully_qualified, _) NS_SWIFT_NAME(fully_qualified) +#endif + +#if __has_attribute(ns_error_domain) && (!defined(__cplusplus) || !__cplusplus || __cplusplus >= 201103L) +#define RLM_ERROR_ENUM(type, name, domain) \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Wignored-attributes\"") \ + NS_ENUM(type, __attribute__((ns_error_domain(domain))) name) \ + _Pragma("clang diagnostic pop") +#else +#define RLM_ERROR_ENUM(type, name, domain) NS_ENUM(type, name) +#endif + + +#pragma mark - Enums + +/** + `RLMPropertyType` is an enumeration describing all property types supported in Realm models. + + For more information, see [Realm Models](https://realm.io/docs/objc/latest/#models). + */ +typedef NS_ENUM(int32_t, RLMPropertyType) { + +#pragma mark - Primitive types + + /** Integers: `NSInteger`, `int`, `long`, `Int` (Swift) */ + RLMPropertyTypeInt = 0, + /** Booleans: `BOOL`, `bool`, `Bool` (Swift) */ + RLMPropertyTypeBool = 1, + /** Floating-point numbers: `float`, `Float` (Swift) */ + RLMPropertyTypeFloat = 5, + /** Double-precision floating-point numbers: `double`, `Double` (Swift) */ + RLMPropertyTypeDouble = 6, + +#pragma mark - Object types + + /** Strings: `NSString`, `String` (Swift) */ + RLMPropertyTypeString = 2, + /** Binary data: `NSData` */ + RLMPropertyTypeData = 3, + /** + Any object: `id`. + + This property type is no longer supported for new models. However, old files + with any-typed properties are still supported for migration purposes. + */ + RLMPropertyTypeAny = 9, + /** Dates: `NSDate` */ + RLMPropertyTypeDate = 4, + +#pragma mark - Linked object types + + /** Realm model objects. See [Realm Models](https://realm.io/docs/objc/latest/#models) for more information. */ + RLMPropertyTypeObject = 7, + /** Realm linking objects. See [Realm Models](https://realm.io/docs/objc/latest/#models) for more information. */ + RLMPropertyTypeLinkingObjects = 8, +}; + +/** An error domain identifying Realm-specific errors. */ +extern NSString * const RLMErrorDomain; + +/** An error domain identifying non-specific system errors. */ +extern NSString * const RLMUnknownSystemErrorDomain; + +/** + `RLMError` is an enumeration representing all recoverable errors. It is associated with the + Realm error domain specified in `RLMErrorDomain`. + */ +typedef RLM_ERROR_ENUM(NSInteger, RLMError, RLMErrorDomain) { + /** Denotes a general error that occurred when trying to open a Realm. */ + RLMErrorFail = 1, + + /** Denotes a file I/O error that occurred when trying to open a Realm. */ + RLMErrorFileAccess = 2, + + /** + Denotes a file permission error that ocurred when trying to open a Realm. + + This error can occur if the user does not have permission to open or create + the specified file in the specified access mode when opening a Realm. + */ + RLMErrorFilePermissionDenied = 3, + + /** Denotes an error where a file was to be written to disk, but another file with the same name already exists. */ + RLMErrorFileExists = 4, + + /** + Denotes an error that occurs if a file could not be found. + + This error may occur if a Realm file could not be found on disk when trying to open a + Realm as read-only, or if the directory part of the specified path was not found when + trying to write a copy. + */ + RLMErrorFileNotFound = 5, + + /** + Denotes an error that occurs if a file format upgrade is required to open the file, + but upgrades were explicitly disabled. + */ + RLMErrorFileFormatUpgradeRequired = 6, + + /** + Denotes an error that occurs if the database file is currently open in another + process which cannot share with the current process due to an + architecture mismatch. + + This error may occur if trying to share a Realm file between an i386 (32-bit) iOS + Simulator and the Realm Browser application. In this case, please use the 64-bit + version of the iOS Simulator. + */ + RLMErrorIncompatibleLockFile = 8, + + /** Denotes an error that occurs when there is insufficient available address space. */ + RLMErrorAddressSpaceExhausted = 9, + + /** Denotes an error that occurs if there is a schema version mismatch, so that a migration is required. */ + RLMErrorSchemaMismatch = 10, + + /** Denotes an error that occurs when attempting to open an incompatible synchronized Realm file. + + This error occurs when the Realm file was created with an older version of Realm and an automatic migration + to the current version is not possible. When such an error occurs, the original file is moved to a backup + location, and future attempts to open the synchronized Realm will result in a new file being created. + If you wish to migrate any data from the backup Realm, you can open it using the provided Realm configuration. + */ + RLMErrorIncompatibleSyncedFile = 11, +}; + +#pragma mark - Constants + +#pragma mark - Notification Constants + +/** + A notification indicating that changes were made to a Realm. +*/ +typedef NSString * RLMNotification RLM_EXTENSIBLE_STRING_ENUM; + +/** + This notification is posted by a Realm when the data in that Realm has changed. + + More specifically, this notification is posted after a Realm has been refreshed to + reflect a write transaction. This can happen when an autorefresh occurs, when + `-[RLMRealm refresh]` is called, after an implicit refresh from `-[RLMRealm beginWriteTransaction]`, + or after a local write transaction is completed. + */ +extern RLMNotification const RLMRealmRefreshRequiredNotification +RLM_EXTENSIBLE_STRING_ENUM_CASE_SWIFT_NAME(RLMRealmRefreshRequiredNotification, RefreshRequired); + +/** + This notification is posted by a Realm when a write transaction has been + committed to a Realm on a different thread for the same file. + + It is not posted if `-[RLMRealm autorefresh]` is enabled, or if the Realm is + refreshed before the notification has a chance to run. + + Realms with autorefresh disabled should normally install a handler for this + notification which calls `-[RLMRealm refresh]` after doing some work. Refreshing + the Realm is optional, but not refreshing the Realm may lead to large Realm + files. This is because Realm must keep an extra copy of the data for the stale + Realm. + */ +extern RLMNotification const RLMRealmDidChangeNotification +RLM_EXTENSIBLE_STRING_ENUM_CASE_SWIFT_NAME(RLMRealmDidChangeNotification, DidChange); + +#pragma mark - Error keys + +/** Key to identify the associated backup Realm configuration in an error's `userInfo` dictionary */ +extern NSString * const RLMBackupRealmConfigurationErrorKey; + +#pragma mark - Other Constants + +/** The schema version used for uninitialized Realms */ +extern const uint64_t RLMNotVersioned; + +/** The corresponding value is the name of an exception thrown by Realm. */ +extern NSString * const RLMExceptionName; + +/** The corresponding value is a Realm file version. */ +extern NSString * const RLMRealmVersionKey; + +/** The corresponding key is the version of the underlying database engine. */ +extern NSString * const RLMRealmCoreVersionKey; + +/** The corresponding key is the Realm invalidated property name. */ +extern NSString * const RLMInvalidatedKey; + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMJSONModels.h b/Pods/Realm/include/RLMJSONModels.h new file mode 100644 index 0000000000..9cc650b449 --- /dev/null +++ b/Pods/Realm/include/RLMJSONModels.h @@ -0,0 +1,103 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMSyncUtil_Private.h" + +NS_ASSUME_NONNULL_BEGIN + +@class RLMTokenDataModel, RLMSyncUserAccountInfo; + +#pragma mark - RLMTokenModel + +@interface RLMTokenModel : NSObject RLM_SYNC_UNINITIALIZABLE + +@property (nonatomic, readonly) NSString *token; +@property (nonatomic, nullable, readonly) NSString *path; +@property (nonatomic, readonly) RLMTokenDataModel *tokenData; + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary; + +@end + +#pragma mark - RLMTokenDataModel + +@interface RLMTokenDataModel : NSObject RLM_SYNC_UNINITIALIZABLE + +@property (nonatomic, readonly) NSString *identity; +@property (nonatomic, nullable, readonly) NSString *appID; +@property (nonatomic, nullable, readonly) NSString *path; +@property (nonatomic, readonly) NSTimeInterval expires; +@property (nonatomic, readonly) BOOL isAdmin; +//@property (nonatomic, readonly) NSArray *access; + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary; + +@end + +#pragma mark - RLMAuthResponseModel + +/** + An internal class representing a valid JSON response to an auth request. + + ``` + { + "access_token": { ... } // (optional), + "refresh_token": { ... } // (optional) + } + ``` + */ +@interface RLMAuthResponseModel : NSObject RLM_SYNC_UNINITIALIZABLE + +@property (nonatomic, readonly, nullable) RLMTokenModel *accessToken; +@property (nonatomic, readonly, nullable) RLMTokenModel *refreshToken; + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary + requireAccessToken:(BOOL)requireAccessToken + requireRefreshToken:(BOOL)requireRefreshToken; + +@end + +#pragma mark - RLMUserInfoResponseModel + +@interface RLMUserResponseModel : NSObject RLM_SYNC_UNINITIALIZABLE + +@property (nonatomic, readonly) NSString *identity; +@property (nonatomic, readonly) NSArray *accounts; +@property (nonatomic, readonly) NSDictionary *metadata; +@property (nonatomic, readonly) BOOL isAdmin; + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary; + +@end + +#pragma mark - RLMSyncErrorResponseModel + +@interface RLMSyncErrorResponseModel : NSObject RLM_SYNC_UNINITIALIZABLE + +@property (nonatomic, readonly) NSInteger status; +@property (nonatomic, readonly) NSInteger code; +@property (nullable, nonatomic, readonly) NSString *title; +@property (nullable, nonatomic, readonly) NSString *hint; + +- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMListBase.h b/Pods/Realm/include/RLMListBase.h new file mode 100644 index 0000000000..0151cfb7cf --- /dev/null +++ b/Pods/Realm/include/RLMListBase.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMArray; + +NS_ASSUME_NONNULL_BEGIN + +// A base class for Swift generic Lists to make it possible to interact with +// them from obj-c +@interface RLMListBase : NSObject +@property (nonatomic, strong) RLMArray *_rlmArray; + +- (instancetype)initWithArray:(RLMArray *)array; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMMigration.h b/Pods/Realm/include/RLMMigration.h new file mode 100644 index 0000000000..e910c4251e --- /dev/null +++ b/Pods/Realm/include/RLMMigration.h @@ -0,0 +1,127 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMSchema; +@class RLMArray; +@class RLMObject; + +/** + A block type which provides both the old and new versions of an object in the Realm. Object + properties can only be accessed using keyed subscripting. + + @see `-[RLMMigration enumerateObjects:block:]` + + @param oldObject The object from the original Realm (read-only). + @param newObject The object from the migrated Realm (read-write). +*/ +typedef void (^RLMObjectMigrationBlock)(RLMObject * __nullable oldObject, RLMObject * __nullable newObject); + +/** + `RLMMigration` instances encapsulate information intended to facilitate a schema migration. + + A `RLMMigration` instance is passed into a user-defined `RLMMigrationBlock` block when updating + the version of a Realm. This instance provides access to the old and new database schemas, the + objects in the Realm, and provides functionality for modifying the Realm during the migration. + */ +@interface RLMMigration : NSObject + +#pragma mark - Properties + +/** + Returns the old `RLMSchema`. This is the schema which describes the Realm before the + migration is applied. + */ +@property (nonatomic, readonly) RLMSchema *oldSchema; + +/** + Returns the new `RLMSchema`. This is the schema which describes the Realm after the + migration is applied. + */ +@property (nonatomic, readonly) RLMSchema *newSchema; + + +#pragma mark - Altering Objects during a Migration + +/** + Enumerates all the objects of a given type in the Realm, providing both the old and new versions + of each object. Within the block, object properties can only be accessed using keyed subscripting. + + @param className The name of the `RLMObject` class to enumerate. + + @warning All objects returned are of a type specific to the current migration and should not be cast + to `className`. Instead, treat them as `RLMObject`s and use keyed subscripting to access + properties. + */ +- (void)enumerateObjects:(NSString *)className block:(__attribute__((noescape)) RLMObjectMigrationBlock)block; + +/** + Creates and returns an `RLMObject` instance of type `className` in the Realm being migrated. + + The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or + dictionary returned from the methods in `NSJSONSerialization`, or an array containing one element for each managed + property. An exception will be thrown if any required properties are not present and those properties were not defined + with default values. + + When passing in an `NSArray` as the `value` argument, all properties must be present, valid and in the same order as + the properties defined in the model. + + @param className The name of the `RLMObject` class to create. + @param value The value used to populate the object. + */ +- (RLMObject *)createObject:(NSString *)className withValue:(id)value; + +/** + Deletes an object from a Realm during a migration. + + It is permitted to call this method from within the block passed to `-[enumerateObjects:block:]`. + + @param object Object to be deleted from the Realm being migrated. + */ +- (void)deleteObject:(RLMObject *)object; + +/** + Deletes the data for the class with the given name. + + All objects of the given class will be deleted. If the `RLMObject` subclass no longer exists in your program, + any remaining metadata for the class will be removed from the Realm file. + + @param name The name of the `RLMObject` class to delete. + + @return A Boolean value indicating whether there was any data to delete. + */ +- (BOOL)deleteDataForClassName:(NSString *)name; + +/** + Renames a property of the given class from `oldName` to `newName`. + + @param className The name of the class whose property should be renamed. This class must be present + in both the old and new Realm schemas. + @param oldName The old name for the property to be renamed. There must not be a property with this name in the + class as defined by the new Realm schema. + @param newName The new name for the property to be renamed. There must not be a property with this name in the + class as defined by the old Realm schema. + */ +- (void)renamePropertyForClass:(NSString *)className oldName:(NSString *)oldName newName:(NSString *)newName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMMigration_Private.h b/Pods/Realm/include/RLMMigration_Private.h new file mode 100644 index 0000000000..99699e5c15 --- /dev/null +++ b/Pods/Realm/include/RLMMigration_Private.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import +#import + +namespace realm { + class Schema; +} + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMMigration () + +@property (nonatomic, strong) RLMRealm *oldRealm; +@property (nonatomic, strong) RLMRealm *realm; + +- (instancetype)initWithRealm:(RLMRealm *)realm oldRealm:(RLMRealm *)oldRealm schema:(realm::Schema &)schema; + +- (void)execute:(RLMMigrationBlock)block; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMNetworkClient.h b/Pods/Realm/include/RLMNetworkClient.h new file mode 100644 index 0000000000..4e2a3ce763 --- /dev/null +++ b/Pods/Realm/include/RLMNetworkClient.h @@ -0,0 +1,73 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMSyncUtil_Private.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMNetworkRequestOptions : NSObject +@property (nonatomic, copy, nullable) NSString *authorizationHeaderName; +@property (nonatomic, copy, nullable) NSDictionary *customHeaders; +@property (nullable, nonatomic, copy) NSDictionary *pinnedCertificatePaths; +@end + +/// An abstract class representing a server endpoint. +@interface RLMSyncServerEndpoint : NSObject RLM_SYNC_UNINITIALIZABLE ++ (instancetype)endpoint; + ++ (void)sendRequestToServer:(NSURL *)serverURL + JSON:(NSDictionary *)jsonDictionary + options:(nullable RLMNetworkRequestOptions *)options + completion:(void (^)(NSError *))completionBlock; +@end + +/// The authentication endpoint. +@interface RLMSyncAuthEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE +@end + +/// The password change endpoint. +@interface RLMSyncChangePasswordEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE +@end + +@interface RLMSyncUpdateAccountEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE +@end + +/// The get user info endpoint. +@interface RLMSyncGetUserInfoEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE +@end + +/** + A simple Realm Object Server network client that wraps `NSURLSession`. + */ +@interface RLMNetworkClient : NSObject + +// Set the timeout in seconds for requests which do not take an explicit timeout. ++ (void)setDefaultTimeout:(NSTimeInterval)timeout; + ++ (void)sendRequestToEndpoint:(RLMSyncServerEndpoint *)endpoint + server:(NSURL *)serverURL + JSON:(NSDictionary *)jsonDictionary + timeout:(NSTimeInterval)timeout + options:(nullable RLMNetworkRequestOptions *)options + completion:(RLMSyncCompletionBlock)completionBlock; + +NS_ASSUME_NONNULL_END + +@end diff --git a/Pods/Realm/include/RLMObject.h b/Pods/Realm/include/RLMObject.h new file mode 100644 index 0000000000..2b55a3e9e1 --- /dev/null +++ b/Pods/Realm/include/RLMObject.h @@ -0,0 +1,555 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMNotificationToken; +@class RLMObjectSchema; +@class RLMPropertyChange; +@class RLMPropertyDescriptor; +@class RLMRealm; +@class RLMResults; + +/** + `RLMObject` is a base class for model objects representing data stored in Realms. + + Define your model classes by subclassing `RLMObject` and adding properties to be managed. + Then instantiate and use your custom subclasses instead of using the `RLMObject` class directly. + + // Dog.h + @interface Dog : RLMObject + @property NSString *name; + @property BOOL adopted; + @end + + // Dog.m + @implementation Dog + @end //none needed + + ### Supported property types + + - `NSString` + - `NSInteger`, `int`, `long`, `float`, and `double` + - `BOOL` or `bool` + - `NSDate` + - `NSData` + - `NSNumber`, where `X` is one of `RLMInt`, `RLMFloat`, `RLMDouble` or `RLMBool`, for optional number properties + - `RLMObject` subclasses, to model many-to-one relationships. + - `RLMArray`, where `X` is an `RLMObject` subclass, to model many-to-many relationships. + + ### Querying + + You can initiate queries directly via the class methods: `allObjects`, `objectsWhere:`, and `objectsWithPredicate:`. + These methods allow you to easily query a custom subclass for instances of that class in the default Realm. + + To search in a Realm other than the default Realm, use the `allObjectsInRealm:`, `objectsInRealm:where:`, + and `objectsInRealm:withPredicate:` class methods. + + @see `RLMRealm` + + ### Relationships + + See our [Cocoa guide](https://realm.io/docs/objc/latest#relationships) for more details. + + ### Key-Value Observing + + All `RLMObject` properties (including properties you create in subclasses) are + [Key-Value Observing compliant](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html), + except for `realm` and `objectSchema`. + + Keep the following tips in mind when observing Realm objects: + + 1. Unlike `NSMutableArray` properties, `RLMArray` properties do not require + using the proxy object returned from `-mutableArrayValueForKey:`, or defining + KVC mutation methods on the containing class. You can simply call methods on + the `RLMArray` directly; any changes will be automatically observed by the containing + object. + 2. Unmanaged `RLMObject` instances cannot be added to a Realm while they have any + observed properties. + 3. Modifying managed `RLMObject`s within `-observeValueForKeyPath:ofObject:change:context:` + is not recommended. Properties may change even when the Realm is not in a write + transaction (for example, when `-[RLMRealm refresh]` is called after changes + are made on a different thread), and notifications sent prior to the change + being applied (when `NSKeyValueObservingOptionPrior` is used) may be sent at + times when you *cannot* begin a write transaction. + */ + +@interface RLMObject : RLMObjectBase + +#pragma mark - Creating & Initializing Objects + +/** + Creates an unmanaged instance of a Realm object. + + Call `addObject:` on an `RLMRealm` instance to add an unmanaged object into that Realm. + + @see `[RLMRealm addObject:]` + */ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + + +/** + Creates an unmanaged instance of a Realm object. + + Pass in an `NSArray` or `NSDictionary` instance to set the values of the object's properties. + + Call `addObject:` on an `RLMRealm` instance to add an unmanaged object into that Realm. + + @see `[RLMRealm addObject:]` + */ +- (instancetype)initWithValue:(id)value NS_DESIGNATED_INITIALIZER; + + +/** + Returns the class name for a Realm object subclass. + + @warning Do not override. Realm relies on this method returning the exact class + name. + + @return The class name for the model class. + */ ++ (NSString *)className; + +/** + Creates an instance of a Realm object with a given value, and adds it to the default Realm. + + If nested objects are included in the argument, `createInDefaultRealmWithValue:` will be recursively called + on them. + + The `value` argument can be a key-value coding compliant object, an array or dictionary returned from the methods in + `NSJSONSerialization`, or an array containing one element for each managed property. + + An exception will be thrown if any required properties are not present and those properties + were not defined with default values. + + If the `value` argument is an array, all properties must be present, valid and in the same + order as the properties defined in the model. + + @param value The value used to populate the object. + + @see `defaultPropertyValues` + */ ++ (instancetype)createInDefaultRealmWithValue:(id)value; + +/** + Creates an instance of a Realm object with a given value, and adds it to the specified Realm. + + If nested objects are included in the argument, `createInRealm:withValue:` will be recursively called + on them. + + The `value` argument can be a key-value coding compliant object, an array or dictionary returned from the methods in + `NSJSONSerialization`, or an array containing one element for each managed property. + + An exception will be thrown if any required properties are not present and those properties + were not defined with default values. + + If the `value` argument is an array, all properties must be present, valid and in the same + order as the properties defined in the model. + + @param realm The Realm which should manage the newly-created object. + @param value The value used to populate the object. + + @see `defaultPropertyValues` + */ ++ (instancetype)createInRealm:(RLMRealm *)realm withValue:(id)value; + +/** + Creates or updates a Realm object within the default Realm. + + This method may only be called on Realm object types with a primary key defined. If there is already + an object with the same primary key value in the default Realm, its values are updated and the object + is returned. Otherwise, this method creates and populates a new instance of the object in the default Realm. + + If nested objects are included in the argument, `createOrUpdateInDefaultRealmWithValue:` will be + recursively called on them if they have primary keys, `createInDefaultRealmWithValue:` if they do not. + + The `value` argument is used to populate the object. It can be a Realm object, a key-value coding + compliant object, an array or dictionary returned from the methods in `NSJSONSerialization`, or an + array containing one element for each managed property. + + If the object is being created, an exception will be thrown if any required properties + are not present and those properties were not defined with default values. + + If the `value` argument is a Realm object already managed by the default Realm, the + argument's type is the same as the receiver, and the objects have identical values for + their managed properties, this method does nothing. + + If the object is being updated, all properties defined in its schema will be set by copying from + `value` using key-value coding. If the `value` argument does not respond to `valueForKey:` for a + given property name (or getter name, if defined), that value will remain untouched. + Nullable properties on the object can be set to nil by using `NSNull` as the updated value. + + If the `value` argument is an array, all properties must be present, valid and in the same + order as the properties defined in the model. + + @param value The value used to populate the object. + + @see `defaultPropertyValues`, `primaryKey` + */ ++ (instancetype)createOrUpdateInDefaultRealmWithValue:(id)value; + +/** + Creates or updates an Realm object within a specified Realm. + + This method may only be called on Realm object types with a primary key defined. If there is already + an object with the same primary key value in the given Realm, its values are updated and the object + is returned. Otherwise this method creates and populates a new instance of this object in the given Realm. + + If nested objects are included in the argument, `createOrUpdateInRealm:withValue:` will be + recursively called on them if they have primary keys, `createInRealm:withValue:` if they do not. + + The `value` argument is used to populate the object. It can be a Realm object, a key-value coding + compliant object, an array or dictionary returned from the methods in `NSJSONSerialization`, or an + array containing one element for each managed property. + + If the object is being created, an exception will be thrown if any required properties + are not present and those properties were not defined with default values. + + If the `value` argument is a Realm object already managed by the given Realm, the + argument's type is the same as the receiver, and the objects have identical values for + their managed properties, this method does nothing. + + If the object is being updated, all properties defined in its schema will be set by copying from + `value` using key-value coding. If the `value` argument does not respond to `valueForKey:` for a + given property name (or getter name, if defined), that value will remain untouched. + Nullable properties on the object can be set to nil by using `NSNull` as the updated value. + + If the `value` argument is an array, all properties must be present, valid and in the same + order as the properties defined in the model. + + @param realm The Realm which should own the object. + @param value The value used to populate the object. + + @see `defaultPropertyValues`, `primaryKey` + */ ++ (instancetype)createOrUpdateInRealm:(RLMRealm *)realm withValue:(id)value; + +#pragma mark - Properties + +/** + The Realm which manages the object, or `nil` if the object is unmanaged. + */ +@property (nonatomic, readonly, nullable) RLMRealm *realm; + +/** + The object schema which lists the managed properties for the object. + */ +@property (nonatomic, readonly) RLMObjectSchema *objectSchema; + +/** + Indicates if the object can no longer be accessed because it is now invalid. + + An object can no longer be accessed if the object has been deleted from the Realm that manages it, or + if `invalidate` is called on that Realm. + */ +@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; + + +#pragma mark - Customizing your Objects + +/** + Returns an array of property names for properties which should be indexed. + + Only string, integer, boolean, and `NSDate` properties are supported. + + @return An array of property names. + */ ++ (NSArray *)indexedProperties; + +/** + Override this method to specify the default values to be used for each property. + + @return A dictionary mapping property names to their default values. + */ ++ (nullable NSDictionary *)defaultPropertyValues; + +/** + Override this method to specify the name of a property to be used as the primary key. + + Only properties of types `RLMPropertyTypeString` and `RLMPropertyTypeInt` can be designated as the primary key. + Primary key properties enforce uniqueness for each value whenever the property is set, which incurs minor overhead. + Indexes are created automatically for primary key properties. + + @return The name of the property designated as the primary key. + */ ++ (nullable NSString *)primaryKey; + +/** + Override this method to specify the names of properties to ignore. These properties will not be managed by the Realm + that manages the object. + + @return An array of property names to ignore. + */ ++ (nullable NSArray *)ignoredProperties; + +/** + Override this method to specify the names of properties that are non-optional (i.e. cannot be assigned a `nil` value). + + By default, all properties of a type whose values can be set to `nil` are considered optional properties. + To require that an object in a Realm always store a non-`nil` value for a property, + add the name of the property to the array returned from this method. + + Properties of `RLMObject` type cannot be non-optional. Array and `NSNumber` properties + can be non-optional, but there is no reason to do so: arrays do not support storing nil, and + if you want a non-optional number you should instead use the primitive type. + + @return An array of property names that are required. + */ ++ (NSArray *)requiredProperties; + +/** + Override this method to provide information related to properties containing linking objects. + + Each property of type `RLMLinkingObjects` must have a key in the dictionary returned by this method consisting + of the property name. The corresponding value must be an instance of `RLMPropertyDescriptor` that describes the class + and property that the property is linked to. + + return @{ @"owners": [RLMPropertyDescriptor descriptorWithClass:Owner.class propertyName:@"dogs"] }; + + @return A dictionary mapping property names to `RLMPropertyDescriptor` instances. + */ ++ (NSDictionary *)linkingObjectsProperties; + + +#pragma mark - Getting & Querying Objects from the Default Realm + +/** + Returns all objects of this object type from the default Realm. + + @return An `RLMResults` containing all objects of this type in the default Realm. + */ ++ (RLMResults *)allObjects; + +/** + Returns all objects of this object type matching the given predicate from the default Realm. + + @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. + + @return An `RLMResults` containing all objects of this type in the default Realm that match the given predicate. + */ ++ (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: ++ (RLMResults<__kindof RLMObject *> *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + + +/** + Returns all objects of this object type matching the given predicate from the default Realm. + + @param predicate The predicate with which to filter the objects. + + @return An `RLMResults` containing all objects of this type in the default Realm that match the given predicate. + */ ++ (RLMResults *)objectsWithPredicate:(nullable NSPredicate *)predicate; + +/** + Retrieves the single instance of this object type with the given primary key from the default Realm. + + Returns the object from the default Realm which has the given primary key, or + `nil` if the object does not exist. This is slightly faster than the otherwise + equivalent `[[SubclassName objectsWhere:@"primaryKeyPropertyName = %@", key] firstObject]`. + + This method requires that `primaryKey` be overridden on the receiving subclass. + + @return An object of this object type, or `nil` if an object with the given primary key does not exist. + @see `-primaryKey` + */ ++ (nullable instancetype)objectForPrimaryKey:(nullable id)primaryKey NS_SWIFT_NAME(object(forPrimaryKey:)); + + +#pragma mark - Querying Specific Realms + +/** + Returns all objects of this object type from the specified Realm. + + @param realm The Realm to query. + + @return An `RLMResults` containing all objects of this type in the specified Realm. + */ ++ (RLMResults *)allObjectsInRealm:(RLMRealm *)realm; + +/** + Returns all objects of this object type matching the given predicate from the specified Realm. + + @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. + @param realm The Realm to query. + + @return An `RLMResults` containing all objects of this type in the specified Realm that match the given predicate. + */ ++ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat, ...; + +/// :nodoc: ++ (RLMResults<__kindof RLMObject *> *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat args:(va_list)args; + +/** + Returns all objects of this object type matching the given predicate from the specified Realm. + + @param predicate A predicate to use to filter the elements. + @param realm The Realm to query. + + @return An `RLMResults` containing all objects of this type in the specified Realm that match the given predicate. + */ ++ (RLMResults *)objectsInRealm:(RLMRealm *)realm withPredicate:(nullable NSPredicate *)predicate; + +/** + Retrieves the single instance of this object type with the given primary key from the specified Realm. + + Returns the object from the specified Realm which has the given primary key, or + `nil` if the object does not exist. This is slightly faster than the otherwise + equivalent `[[SubclassName objectsInRealm:realm where:@"primaryKeyPropertyName = %@", key] firstObject]`. + + This method requires that `primaryKey` be overridden on the receiving subclass. + + @return An object of this object type, or `nil` if an object with the given primary key does not exist. + @see `-primaryKey` + */ ++ (nullable instancetype)objectInRealm:(RLMRealm *)realm forPrimaryKey:(nullable id)primaryKey NS_SWIFT_NAME(object(in:forPrimaryKey:)); + +#pragma mark - Notifications + +/** + A callback block for `RLMObject` notifications. + + If the object is deleted from the managing Realm, the block is called with + `deleted` set to `YES` and the other two arguments are `nil`. The block will + never be called again after this. + + If the object is modified, the block will be called with `deleted` set to + `NO`, a `nil` error, and an array of `RLMPropertyChange` objects which + indicate which properties of the objects were modified. + + If an error occurs, `deleted` will be `NO`, `changes` will be `nil`, and + `error` will include information about the error. The block will never be + called again after an error occurs. + */ +typedef void (^RLMObjectChangeBlock)(BOOL deleted, + NSArray *_Nullable changes, + NSError *_Nullable error); + +/** + Registers a block to be called each time the object changes. + + The block will be asynchronously called after each write transaction which + deletes the object or modifies any of the managed properties of the object, + including self-assignments that set a property to its existing value. + + For write transactions performed on different threads or in differen + processes, the block will be called when the managing Realm is + (auto)refreshed to a version including the changes, while for local write + transactions it will be called at some point in the future after the write + transaction is committed. + + Notifications are delivered via the standard run loop, and so can't be + delivered while the run loop is blocked by other activity. When notifications + can't be delivered instantly, multiple notifications may be coalesced into a + single notification. + + Unlike with `RLMArray` and `RLMResults`, there is no "initial" callback made + after you add a new notification block. + + Only objects which are managed by a Realm can be observed in this way. You + must retain the returned token for as long as you want updates to be sent to + the block. To stop receiving updates, call `-invalidate` on the token. + + It is safe to capture a strong reference to the observed object within the + callback block. There is no retain cycle due to that the callback is retained + by the returned token and not by the object itself. + + @warning This method cannot be called during a write transaction, when the + containing Realm is read-only, or on an unmanaged object. + + @param block The block to be called whenever a change occurs. + @return A token which must be held for as long as you want updates to be delivered. + */ +- (RLMNotificationToken *)addNotificationBlock:(RLMObjectChangeBlock)block; + +#pragma mark - Other Instance Methods + +/** + Returns YES if another Realm object instance points to the same object as the receiver in the Realm managing + the receiver. + + For object types with a primary, key, `isEqual:` is overridden to use the same logic as this + method (along with a corresponding implementation for `hash`). + + @param object The object to compare the receiver to. + + @return Whether the object represents the same object as the receiver. + */ +- (BOOL)isEqualToObject:(RLMObject *)object; + +#pragma mark - Dynamic Accessors + +/// :nodoc: +- (nullable id)objectForKeyedSubscript:(NSString *)key; + +/// :nodoc: +- (void)setObject:(nullable id)obj forKeyedSubscript:(NSString *)key; + +@end + +/** + Information about a specific property which changed in an `RLMObject` change notification. + */ +@interface RLMPropertyChange : NSObject + +/** + The name of the property which changed. + */ +@property (nonatomic, readonly, strong) NSString *name; + +/** + The value of the property before the change occurred. This will always be `nil` + if the change happened on the same thread as the notification and for `RLMArray` + properties. + + For object properties this will give the object which was previously linked to, + but that object will have its new values and not the values it had before the + changes. This means that `previousValue` may be a deleted object, and you will + need to check `invalidated` before accessing any of its properties. + */ +@property (nonatomic, readonly, strong, nullable) id previousValue; + +/** + The value of the property after the change occurred. This will always be `nil` + for `RLMArray` properties. + */ +@property (nonatomic, readonly, strong, nullable) id value; +@end + +#pragma mark - RLMArray Property Declaration + +/** + Properties on `RLMObject`s of type `RLMArray` must have an associated type. A type is associated + with an `RLMArray` property by defining a protocol for the object type that the array should contain. + To define the protocol for an object, you can use the macro RLM_ARRAY_TYPE: + + RLM_ARRAY_TYPE(ObjectType) + ... + @property RLMArray *arrayOfObjectTypes; + */ +#define RLM_ARRAY_TYPE(RLM_OBJECT_SUBCLASS)\ +@protocol RLM_OBJECT_SUBCLASS \ +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMObjectBase.h b/Pods/Realm/include/RLMObjectBase.h new file mode 100644 index 0000000000..de40598ccd --- /dev/null +++ b/Pods/Realm/include/RLMObjectBase.h @@ -0,0 +1,44 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMRealm; +@class RLMSchema; +@class RLMObjectSchema; + +/// :nodoc: +@interface RLMObjectBase : NSObject + +@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; + +- (instancetype)init NS_DESIGNATED_INITIALIZER; + ++ (NSString *)className; + +// Returns whether the class is included in the default set of classes managed by a Realm. ++ (BOOL)shouldIncludeInDefaultSchema; + ++ (nullable NSString *)_realmObjectName; ++ (nullable NSDictionary *)_realmColumnNames; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMObjectBase_Dynamic.h b/Pods/Realm/include/RLMObjectBase_Dynamic.h new file mode 100644 index 0000000000..55f64ef3e5 --- /dev/null +++ b/Pods/Realm/include/RLMObjectBase_Dynamic.h @@ -0,0 +1,82 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMObjectSchema, RLMRealm; + +NS_ASSUME_NONNULL_BEGIN + +/** + Returns the Realm that manages the object, if one exists. + + @warning This function is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to retrieve the Realm that manages the object via `RLMObject`. + + @param object An `RLMObjectBase` obtained via a Swift `Object` or `RLMObject`. + + @return The Realm which manages this object. Returns `nil `for unmanaged objects. + */ +FOUNDATION_EXTERN RLMRealm * _Nullable RLMObjectBaseRealm(RLMObjectBase * _Nullable object); + +/** + Returns an `RLMObjectSchema` which describes the managed properties of the object. + + @warning This function is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to retrieve `objectSchema` via `RLMObject`. + + @param object An `RLMObjectBase` obtained via a Swift `Object` or `RLMObject`. + + @return The object schema which lists the managed properties for the object. + */ +FOUNDATION_EXTERN RLMObjectSchema * _Nullable RLMObjectBaseObjectSchema(RLMObjectBase * _Nullable object); + +/** + Returns the object corresponding to a key value. + + @warning This function is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to retrieve key values via `RLMObject`. + + @warning Will throw an `NSUndefinedKeyException` if `key` is not present on the object. + + @param object An `RLMObjectBase` obtained via a Swift `Object` or `RLMObject`. + @param key The name of the property. + + @return The object for the property requested. + */ +FOUNDATION_EXTERN id _Nullable RLMObjectBaseObjectForKeyedSubscript(RLMObjectBase * _Nullable object, NSString *key); + +/** + Sets a value for a key on the object. + + @warning This function is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to set key values via `RLMObject`. + + @warning Will throw an `NSUndefinedKeyException` if `key` is not present on the object. + + @param object An `RLMObjectBase` obtained via a Swift `Object` or `RLMObject`. + @param key The name of the property. + @param obj The object to set as the value of the key. + */ +FOUNDATION_EXTERN void RLMObjectBaseSetObjectForKeyedSubscript(RLMObjectBase * _Nullable object, NSString *key, id _Nullable obj); + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMObjectBase_Private.h b/Pods/Realm/include/RLMObjectBase_Private.h new file mode 100644 index 0000000000..c2d07221ff --- /dev/null +++ b/Pods/Realm/include/RLMObjectBase_Private.h @@ -0,0 +1,28 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +// RLMObjectBase private +@interface RLMObjectBase () ++ (void)initializeLinkedObjectSchemas; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMObjectSchema.h b/Pods/Realm/include/RLMObjectSchema.h new file mode 100644 index 0000000000..83a7d84ee7 --- /dev/null +++ b/Pods/Realm/include/RLMObjectSchema.h @@ -0,0 +1,72 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMProperty; + +/** + This class represents Realm model object schemas. + + When using Realm, `RLMObjectSchema` instances allow performing migrations and + introspecting the database's schema. + + Object schemas map to tables in the core database. + */ +@interface RLMObjectSchema : NSObject + +#pragma mark - Properties + +/** + An array of `RLMProperty` instances representing the managed properties of a class described by the schema. + + @see `RLMProperty` + */ +@property (nonatomic, readonly, copy) NSArray *properties; + +/** + The name of the class the schema describes. + */ +@property (nonatomic, readonly) NSString *className; + +/** + The property which serves as the primary key for the class the schema describes, if any. + */ +@property (nonatomic, readonly, nullable) RLMProperty *primaryKeyProperty; + +#pragma mark - Methods + +/** + Retrieves an `RLMProperty` object by the property name. + + @param propertyName The property's name. + + @return An `RLMProperty` object, or `nil` if there is no property with the given name. + */ +- (nullable RLMProperty *)objectForKeyedSubscript:(NSString *)propertyName; + +/** + Returns whether two `RLMObjectSchema` instances are equal. + */ +- (BOOL)isEqualToObjectSchema:(RLMObjectSchema *)objectSchema; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMObjectSchema_Private.h b/Pods/Realm/include/RLMObjectSchema_Private.h new file mode 100644 index 0000000000..deca77ddce --- /dev/null +++ b/Pods/Realm/include/RLMObjectSchema_Private.h @@ -0,0 +1,71 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import + +NS_ASSUME_NONNULL_BEGIN + +// RLMObjectSchema private +@interface RLMObjectSchema () { +@public + bool _isSwiftClass; +} + +/// The object type name reported to the object store and core. +@property (nonatomic, readonly) NSString *objectName; + +// writable redeclaration +@property (nonatomic, readwrite, copy) NSArray *properties; +@property (nonatomic, readwrite, assign) bool isSwiftClass; + +// class used for this object schema +@property (nonatomic, readwrite, assign) Class objectClass; +@property (nonatomic, readwrite, assign) Class accessorClass; +@property (nonatomic, readwrite, assign) Class unmanagedClass; + +@property (nonatomic, readwrite, nullable) RLMProperty *primaryKeyProperty; + +@property (nonatomic, copy) NSArray *computedProperties; +@property (nonatomic, readonly) NSArray *swiftGenericProperties; + +// returns a cached or new schema for a given object class ++ (instancetype)schemaForObjectClass:(Class)objectClass; +@end + +@interface RLMObjectSchema (Dynamic) +/** + This method is useful only in specialized circumstances, for example, when accessing objects + in a Realm produced externally. If you are simply building an app on Realm, it is not recommended + to use this method as an [RLMObjectSchema](RLMObjectSchema) is generated automatically for every [RLMObject](RLMObject) subclass. + + Initialize an RLMObjectSchema with classname, objectClass, and an array of properties + + @warning This method is useful only in specialized circumstances. + + @param objectClassName The name of the class used to refer to objects of this type. + @param objectClass The Objective-C class used when creating instances of this type. + @param properties An array of RLMProperty instances describing the managed properties for this type. + + @return An initialized instance of RLMObjectSchema. + */ +- (instancetype)initWithClassName:(NSString *)objectClassName objectClass:(Class)objectClass properties:(NSArray *)properties; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMObjectSchema_Private.hpp b/Pods/Realm/include/RLMObjectSchema_Private.hpp new file mode 100644 index 0000000000..7ccf177215 --- /dev/null +++ b/Pods/Realm/include/RLMObjectSchema_Private.hpp @@ -0,0 +1,36 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMObjectSchema_Private.h" + +namespace realm { + class ObjectSchema; +} +@class RLMSchema; + +@interface RLMObjectSchema () +// create realm::ObjectSchema copy +- (realm::ObjectSchema)objectStoreCopy:(RLMSchema *)schema; + +// initialize with realm::ObjectSchema ++ (instancetype)objectSchemaForObjectStoreSchema:(realm::ObjectSchema const&)objectSchema; +@end + +// An objc_ivar pointer which is guaranteed to not point to any actually-existing +// ivar. Used as part of https://github.com/realm/realm-cocoa/issues/5784 +extern const Ivar RLMDummySwiftIvar; diff --git a/Pods/Realm/include/RLMObjectStore.h b/Pods/Realm/include/RLMObjectStore.h new file mode 100644 index 0000000000..b44e7e68c4 --- /dev/null +++ b/Pods/Realm/include/RLMObjectStore.h @@ -0,0 +1,88 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#ifdef __cplusplus +extern "C" { +#endif + +@class RLMRealm, RLMSchema, RLMObjectBase, RLMResults, RLMProperty; + +NS_ASSUME_NONNULL_BEGIN + +// +// Accessor Creation +// + +// create or get cached accessors for the given schema +void RLMRealmCreateAccessors(RLMSchema *schema); + + +// +// Adding, Removing, Getting Objects +// + +// add an object to the given realm +void RLMAddObjectToRealm(RLMObjectBase *object, RLMRealm *realm, bool createOrUpdate); + +// delete an object from its realm +void RLMDeleteObjectFromRealm(RLMObjectBase *object, RLMRealm *realm); + +// deletes all objects from a realm +void RLMDeleteAllObjectsFromRealm(RLMRealm *realm); + +// get objects of a given class +RLMResults *RLMGetObjects(RLMRealm *realm, NSString *objectClassName, NSPredicate * _Nullable predicate) +NS_RETURNS_RETAINED; + +// get an object with the given primary key +id _Nullable RLMGetObject(RLMRealm *realm, NSString *objectClassName, id _Nullable key) NS_RETURNS_RETAINED; + +// create object from array or dictionary +RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className, + id _Nullable value, bool createOrUpdate) +NS_RETURNS_RETAINED; + + +// +// Accessor Creation +// + + +// switch List<> properties from being backed by unmanaged RLMArrays to RLMManagedArray +void RLMInitializeSwiftAccessorGenerics(RLMObjectBase *object); + +#ifdef __cplusplus +} + +namespace realm { + class Table; + template class BasicRowExpr; + using RowExpr = BasicRowExpr; +} +class RLMClassInfo; + +// Create accessors +RLMObjectBase *RLMCreateObjectAccessor(RLMRealm *realm, RLMClassInfo& info, + NSUInteger index) NS_RETURNS_RETAINED; +RLMObjectBase *RLMCreateObjectAccessor(RLMRealm *realm, RLMClassInfo& info, + realm::RowExpr row) NS_RETURNS_RETAINED; +#endif + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMObject_Private.h b/Pods/Realm/include/RLMObject_Private.h new file mode 100644 index 0000000000..33a13ae8bd --- /dev/null +++ b/Pods/Realm/include/RLMObject_Private.h @@ -0,0 +1,147 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMProperty, RLMArray, RLMSwiftPropertyMetadata; +typedef NS_ENUM(int32_t, RLMPropertyType); + +// RLMObject accessor and read/write realm +@interface RLMObjectBase () { +@public + RLMRealm *_realm; + __unsafe_unretained RLMObjectSchema *_objectSchema; +} + +// unmanaged initializer +- (instancetype)initWithValue:(id)value schema:(RLMSchema *)schema NS_DESIGNATED_INITIALIZER; + +// live accessor initializer +- (instancetype)initWithRealm:(__unsafe_unretained RLMRealm *const)realm + schema:(RLMObjectSchema *)schema NS_DESIGNATED_INITIALIZER; + +// shared schema for this class ++ (nullable RLMObjectSchema *)sharedSchema; + +// provide injection point for alternative Swift object util class ++ (Class)objectUtilClass:(BOOL)isSwift; + +@end + +@interface RLMObject () + +// unmanaged initializer +- (instancetype)initWithValue:(id)value schema:(RLMSchema *)schema NS_DESIGNATED_INITIALIZER; + +// live accessor initializer +- (instancetype)initWithRealm:(__unsafe_unretained RLMRealm *const)realm + schema:(RLMObjectSchema *)schema NS_DESIGNATED_INITIALIZER; + +@end + +@interface RLMDynamicObject : RLMObject + +@end + +// A reference to an object's row that doesn't keep the object accessor alive. +// Used by some Swift property types, such as LinkingObjects, to avoid retain cycles +// with their containing object. +@interface RLMWeakObjectHandle : NSObject + +- (instancetype)initWithObject:(RLMObjectBase *)object; + +// Consumes the row, so can only usefully be called once. +@property (nonatomic, readonly) RLMObjectBase *object; + +@end + +// Calls valueForKey: and re-raises NSUndefinedKeyExceptions +FOUNDATION_EXTERN id _Nullable RLMValidatedValueForProperty(id object, NSString *key, NSString *className); + +// Compare two RLObjectBases +FOUNDATION_EXTERN BOOL RLMObjectBaseAreEqual(RLMObjectBase * _Nullable o1, RLMObjectBase * _Nullable o2); + +typedef void (^RLMObjectNotificationCallback)(NSArray *_Nullable propertyNames, + NSArray *_Nullable oldValues, + NSArray *_Nullable newValues, + NSError *_Nullable error); +FOUNDATION_EXTERN RLMNotificationToken *RLMObjectAddNotificationBlock(RLMObjectBase *obj, RLMObjectNotificationCallback block); + +// Returns whether the class is a descendent of RLMObjectBase +FOUNDATION_EXTERN BOOL RLMIsObjectOrSubclass(Class klass); + +// Returns whether the class is an indirect descendant of RLMObjectBase +FOUNDATION_EXTERN BOOL RLMIsObjectSubclass(Class klass); + +// For unit testing purposes, allow an Objective-C class named FakeObject to also be used +// as the base class of managed objects. This allows for testing invalid schemas. +FOUNDATION_EXTERN void RLMSetTreatFakeObjectAsRLMObject(BOOL flag); + +// Get ObjectUil class for objc or swift +FOUNDATION_EXTERN Class RLMObjectUtilClass(BOOL isSwift); + +FOUNDATION_EXTERN const NSUInteger RLMDescriptionMaxDepth; + +@interface RLMObjectUtil : NSObject + ++ (nullable NSArray *)ignoredPropertiesForClass:(Class)cls; ++ (nullable NSArray *)indexedPropertiesForClass:(Class)cls; ++ (nullable NSDictionary *> *)linkingObjectsPropertiesForClass:(Class)cls; + +// Precondition: these must be returned in ascending order. ++ (nullable NSArray *)getSwiftProperties:(id)obj; + ++ (nullable NSDictionary *)getOptionalProperties:(id)obj; ++ (nullable NSArray *)requiredPropertiesForClass:(Class)cls; + +@end + +typedef NS_ENUM(NSUInteger, RLMSwiftPropertyKind) { + RLMSwiftPropertyKindList, + RLMSwiftPropertyKindLinkingObjects, + RLMSwiftPropertyKindOptional, + RLMSwiftPropertyKindNilLiteralOptional, // For Swift optional properties that reflect as nil + RLMSwiftPropertyKindOther, +}; + +// Metadata that describes a Swift generic property. +@interface RLMSwiftPropertyMetadata : NSObject + +@property (nonatomic, strong) NSString *propertyName; +@property (nullable, nonatomic, strong) NSString *className; +@property (nullable, nonatomic, strong) NSString *linkedPropertyName; +@property (nonatomic) RLMPropertyType propertyType; +@property (nonatomic) RLMSwiftPropertyKind kind; + ++ (instancetype)metadataForOtherProperty:(NSString *)propertyName; + ++ (instancetype)metadataForListProperty:(NSString *)propertyName; + ++ (instancetype)metadataForLinkingObjectsProperty:(NSString *)propertyName + className:(NSString *)className + linkedPropertyName:(NSString *)linkedPropertyName; + ++ (instancetype)metadataForOptionalProperty:(NSString *)propertyName type:(RLMPropertyType)type; + ++ (instancetype)metadataForNilLiteralOptionalProperty:(NSString *)propertyName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMObject_Private.hpp b/Pods/Realm/include/RLMObject_Private.hpp new file mode 100644 index 0000000000..7f79dd6df7 --- /dev/null +++ b/Pods/Realm/include/RLMObject_Private.hpp @@ -0,0 +1,58 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMObject_Private.h" + +#import "RLMRealm_Private.hpp" +#import "RLMUtil.hpp" + +#import // required by row.hpp +#import + +class RLMObservationInfo; + +// RLMObject accessor and read/write realm +@interface RLMObjectBase () { + @public + realm::Row _row; + RLMObservationInfo *_observationInfo; + RLMClassInfo *_info; +} +@end + +// FIXME-2.0: This should be folded into initWithRealm:schema:, but changing the +// signature of that is a breaking change for Swift +id RLMCreateManagedAccessor(Class cls, RLMRealm *realm, RLMClassInfo *info) NS_RETURNS_RETAINED; + +// throw an exception if the object is invalidated or on the wrong thread +static inline void RLMVerifyAttached(__unsafe_unretained RLMObjectBase *const obj) { + if (!obj->_row.is_attached()) { + @throw RLMException(@"Object has been deleted or invalidated."); + } + [obj->_realm verifyThread]; +} + +// throw an exception if the object can't be modified for any reason +static inline void RLMVerifyInWriteTransaction(__unsafe_unretained RLMObjectBase *const obj) { + // first verify is attached + RLMVerifyAttached(obj); + + if (!obj->_realm.inWriteTransaction) { + @throw RLMException(@"Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first."); + } +} diff --git a/Pods/Realm/include/RLMObservation.hpp b/Pods/Realm/include/RLMObservation.hpp new file mode 100644 index 0000000000..0f5b215005 --- /dev/null +++ b/Pods/Realm/include/RLMObservation.hpp @@ -0,0 +1,153 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "binding_context.hpp" + +#import +#import + +#import + +@class RLMObjectBase, RLMRealm, RLMSchema, RLMProperty, RLMObjectSchema; +class RLMClassInfo; +class RLMSchemaInfo; + +namespace realm { + class History; + class SharedGroup; +} + +// RLMObservationInfo stores all of the KVO-related data for RLMObjectBase and +// RLMArray. There is a one-to-one relationship between observed objects and +// RLMObservationInfo instances, so it could be folded into RLMObjectBase, and +// is a separate class mostly to avoid making all accessor objects far larger. +// +// RLMClassInfo stores a vector of pointers to the first observation info +// created for each row. If there are multiple observation infos for a single +// row (such as if there are multiple observed objects backed by a single row, +// or if both an object and an array property of that object are observed), +// they're stored in an intrusive doubly-linked-list in the `next` and `prev` +// members. This is done primarily to make it simpler and faster to loop over +// all of the observed objects for a single row, as that needs to be done for +// every change. +class RLMObservationInfo { +public: + RLMObservationInfo(id object); + RLMObservationInfo(RLMClassInfo &objectSchema, std::size_t row, id object); + ~RLMObservationInfo(); + + realm::Row const& getRow() const { + return row; + } + + NSString *columnName(size_t col) const noexcept; + + // Send willChange/didChange notifications to all observers for this object/row + // Sends the array versions if indexes is non-nil, normal versions otherwise + void willChange(NSString *key, NSKeyValueChange kind=NSKeyValueChangeSetting, NSIndexSet *indexes=nil) const; + void didChange(NSString *key, NSKeyValueChange kind=NSKeyValueChangeSetting, NSIndexSet *indexes=nil) const; + + bool isForRow(size_t ndx) const { + return row && row.get_index() == ndx; + } + + void recordObserver(realm::Row& row, RLMClassInfo *objectInfo, RLMObjectSchema *objectSchema, NSString *keyPath); + void removeObserver(); + bool hasObservers() const { return observerCount > 0; } + + // valueForKey: on observed object and array properties needs to return the + // same object each time for KVO to work at all. Doing this all the time + // requires some odd semantics to avoid reference cycles, so instead we do + // it only to the extent specifically required by KVO. In addition, we + // need to continue to return the same object even if this row is deleted, + // or deleting an object with active observers will explode horribly. + // Once prepareForInvalidation() is called, valueForKey() will always return + // the cached value for object and array properties without checking the + // backing row to verify it's up-to-date. + // + // prepareForInvalidation() must be called on the head of the linked list + // (i.e. on the object pointed to directly by the object schema) + id valueForKey(NSString *key); + + void prepareForInvalidation(); + +private: + // Doubly-linked-list of observed objects for the same row as this + RLMObservationInfo *next = nullptr; + RLMObservationInfo *prev = nullptr; + + // Row being observed + realm::Row row; + RLMClassInfo *objectSchema = nullptr; + + // Object doing the observing + __unsafe_unretained id object = nil; + + // valueForKey: hack + bool invalidated = false; + size_t observerCount = 0; + NSString *lastKey = nil; + __unsafe_unretained RLMProperty *lastProp = nil; + + // objects returned from valueForKey() to keep them alive in case observers + // are added and so that they can still be accessed after row is detached + NSMutableDictionary *cachedObjects; + + void setRow(realm::Table &table, size_t newRow); + + template + void forEach(F&& f) const { + // The user's observation handler may release their last reference to + // the object being observed, which will result in the RLMObservationInfo + // being destroyed. As a result, we need to retain the object which owns + // both `this` and the current info we're looking at. + __attribute__((objc_precise_lifetime)) id self = object, current; + for (auto info = prev; info; info = info->prev) { + current = info->object; + f(info->object); + } + for (auto info = this; info; info = info->next) { + current = info->object; + f(info->object); + } + } + + // Default move/copy constructors don't work due to the intrusive linked + // list and we don't need them + RLMObservationInfo(RLMObservationInfo const&) = delete; + RLMObservationInfo(RLMObservationInfo&&) = delete; + RLMObservationInfo& operator=(RLMObservationInfo const&) = delete; + RLMObservationInfo& operator=(RLMObservationInfo&&) = delete; +}; + +// Get the the observation info chain for the given row +// Will simply return info if it's non-null, and will search ojectSchema's array +// for a matching one otherwise, and return null if there are none +RLMObservationInfo *RLMGetObservationInfo(RLMObservationInfo *info, size_t row, RLMClassInfo& objectSchema); + +// delete all objects from a single table with change notifications +void RLMClearTable(RLMClassInfo &realm); + +// invoke the block, sending notifications for cascading deletes/link nullifications +void RLMTrackDeletions(RLMRealm *realm, dispatch_block_t block); + +std::vector RLMGetObservedRows(RLMSchemaInfo const& schema); +void RLMWillChange(std::vector const& observed, std::vector const& invalidated); +void RLMDidChange(std::vector const& observed, std::vector const& invalidated); diff --git a/Pods/Realm/include/RLMOptionalBase.h b/Pods/Realm/include/RLMOptionalBase.h new file mode 100644 index 0000000000..d5b2430e92 --- /dev/null +++ b/Pods/Realm/include/RLMOptionalBase.h @@ -0,0 +1,36 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMObjectBase, RLMProperty; + +@interface RLMOptionalBase : NSProxy +- (instancetype)init; +@end + +FOUNDATION_EXTERN id _Nullable RLMGetOptional(RLMOptionalBase *); +FOUNDATION_EXTERN void RLMSetOptional(RLMOptionalBase *, id _Nullable); + +void RLMInitializeManagedOptional(RLMOptionalBase *, RLMObjectBase *parent, RLMProperty *prop); +void RLMInitializeUnmanagedOptional(RLMOptionalBase *, RLMObjectBase *parent, RLMProperty *prop); + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMPlatform.h b/Pods/Realm/include/RLMPlatform.h new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/Pods/Realm/include/RLMPlatform.h @@ -0,0 +1 @@ + diff --git a/Pods/Realm/include/RLMPredicateUtil.hpp b/Pods/Realm/include/RLMPredicateUtil.hpp new file mode 100644 index 0000000000..71426de450 --- /dev/null +++ b/Pods/Realm/include/RLMPredicateUtil.hpp @@ -0,0 +1,22 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#import +#import + +using ExpressionVisitor = std::function; +NSPredicate *transformPredicate(NSPredicate *, ExpressionVisitor); diff --git a/Pods/Realm/include/RLMPrefix.h b/Pods/Realm/include/RLMPrefix.h new file mode 100644 index 0000000000..df08ce9e68 --- /dev/null +++ b/Pods/Realm/include/RLMPrefix.h @@ -0,0 +1,35 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifdef __OBJC__ +#import +#endif + +#ifdef __cplusplus +#import +#import +#import +#import +#import + +#import +#import +#import +#import +#import +#endif diff --git a/Pods/Realm/include/RLMProperty.h b/Pods/Realm/include/RLMProperty.h new file mode 100644 index 0000000000..a2bc89480c --- /dev/null +++ b/Pods/Realm/include/RLMProperty.h @@ -0,0 +1,126 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// :nodoc: +@protocol RLMInt @end +/// :nodoc: +@protocol RLMBool @end +/// :nodoc: +@protocol RLMDouble @end +/// :nodoc: +@protocol RLMFloat @end +/// :nodoc: +@protocol RLMString @end +/// :nodoc: +@protocol RLMDate @end +/// :nodoc: +@protocol RLMData @end + +/// :nodoc: +@interface NSNumber () +@end + +/** + `RLMProperty` instances represent properties managed by a Realm in the context + of an object schema. Such properties may be persisted to a Realm file or + computed from other data from the Realm. + + When using Realm, `RLMProperty` instances allow performing migrations and + introspecting the database's schema. + + These property instances map to columns in the core database. + */ +@interface RLMProperty : NSObject + +#pragma mark - Properties + +/** + The name of the property. + */ +@property (nonatomic, readonly) NSString *name; + +/** + The type of the property. + + @see `RLMPropertyType` + */ +@property (nonatomic, readonly) RLMPropertyType type; + +/** + Indicates whether this property is indexed. + + @see `RLMObject` + */ +@property (nonatomic, readonly) BOOL indexed; + +/** + For `RLMObject` and `RLMArray` properties, the name of the class of object stored in the property. + */ +@property (nonatomic, readonly, copy, nullable) NSString *objectClassName; + +/** + For linking objects properties, the property name of the property the linking objects property is linked to. + */ +@property (nonatomic, readonly, copy, nullable) NSString *linkOriginPropertyName; + +/** + Indicates whether this property is optional. + */ +@property (nonatomic, readonly) BOOL optional; + +/** + Indicates whether this property is an array. + */ +@property (nonatomic, readonly) BOOL array; + +#pragma mark - Methods + +/** + Returns whether a given property object is equal to the receiver. + */ +- (BOOL)isEqualToProperty:(RLMProperty *)property; + +@end + + +/** + An `RLMPropertyDescriptor` instance represents a specific property on a given class. + */ +@interface RLMPropertyDescriptor : NSObject + +/** + Creates and returns a property descriptor. + + @param objectClass The class of this property descriptor. + @param propertyName The name of this property descriptor. + */ ++ (instancetype)descriptorWithClass:(Class)objectClass propertyName:(NSString *)propertyName; + +/// The class of the property. +@property (nonatomic, readonly) Class objectClass; + +/// The name of the property. +@property (nonatomic, readonly) NSString *propertyName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMProperty_Private.h b/Pods/Realm/include/RLMProperty_Private.h new file mode 100644 index 0000000000..1e4e5ec441 --- /dev/null +++ b/Pods/Realm/include/RLMProperty_Private.h @@ -0,0 +1,136 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import + +@class RLMObjectBase; + +NS_ASSUME_NONNULL_BEGIN + +BOOL RLMPropertyTypeIsComputed(RLMPropertyType propertyType); +FOUNDATION_EXTERN void RLMValidateSwiftPropertyName(NSString *name); + +// Translate an rlmtype to a string representation +static inline NSString *RLMTypeToString(RLMPropertyType type) { + switch (type) { + case RLMPropertyTypeString: + return @"string"; + case RLMPropertyTypeInt: + return @"int"; + case RLMPropertyTypeBool: + return @"bool"; + case RLMPropertyTypeDate: + return @"date"; + case RLMPropertyTypeData: + return @"data"; + case RLMPropertyTypeDouble: + return @"double"; + case RLMPropertyTypeFloat: + return @"float"; + case RLMPropertyTypeAny: + return @"any"; + case RLMPropertyTypeObject: + return @"object"; + case RLMPropertyTypeLinkingObjects: + return @"linking objects"; + } + return @"Unknown"; +} + +// private property interface +@interface RLMProperty () { +@public + RLMPropertyType _type; + Ivar _swiftIvar; +} + +- (instancetype)initWithName:(NSString *)name + indexed:(BOOL)indexed + linkPropertyDescriptor:(nullable RLMPropertyDescriptor *)linkPropertyDescriptor + property:(objc_property_t)property; + +- (instancetype)initSwiftPropertyWithName:(NSString *)name + indexed:(BOOL)indexed + linkPropertyDescriptor:(nullable RLMPropertyDescriptor *)linkPropertyDescriptor + property:(objc_property_t)property + instance:(RLMObjectBase *)objectInstance; + +- (instancetype)initSwiftListPropertyWithName:(NSString *)name + instance:(id)object; + +- (instancetype)initSwiftOptionalPropertyWithName:(NSString *)name + indexed:(BOOL)indexed + ivar:(Ivar)ivar + propertyType:(RLMPropertyType)propertyType; + +- (instancetype)initSwiftLinkingObjectsPropertyWithName:(NSString *)name + ivar:(Ivar)ivar + objectClassName:(nullable NSString *)objectClassName + linkOriginPropertyName:(nullable NSString *)linkOriginPropertyName; + +// private setters +@property (nonatomic, readwrite) NSString *name; +@property (nonatomic, readwrite, assign) RLMPropertyType type; +@property (nonatomic, readwrite) BOOL indexed; +@property (nonatomic, readwrite) BOOL optional; +@property (nonatomic, copy, nullable) NSString *objectClassName; + +// private properties +@property (nonatomic, readwrite) NSString *columnName; +@property (nonatomic, assign) NSUInteger index; +@property (nonatomic, assign) BOOL isPrimary; +@property (nonatomic, assign) Ivar swiftIvar; + +// getter and setter names +@property (nonatomic, copy) NSString *getterName; +@property (nonatomic, copy) NSString *setterName; +@property (nonatomic) SEL getterSel; +@property (nonatomic) SEL setterSel; + +- (RLMProperty *)copyWithNewName:(NSString *)name; + +@end + +@interface RLMProperty (Dynamic) +/** + This method is useful only in specialized circumstances, for example, in conjunction with + +[RLMObjectSchema initWithClassName:objectClass:properties:]. If you are simply building an + app on Realm, it is not recommened to use this method. + + Initialize an RLMProperty + + @warning This method is useful only in specialized circumstances. + + @param name The property name. + @param type The property type. + @param objectClassName The object type used for Object and Array types. + @param linkOriginPropertyName The property name of the origin of a link. Used for linking objects properties. + + @return An initialized instance of RLMProperty. + */ +- (instancetype)initWithName:(NSString *)name + type:(RLMPropertyType)type + objectClassName:(nullable NSString *)objectClassName + linkOriginPropertyName:(nullable NSString *)linkOriginPropertyName + indexed:(BOOL)indexed + optional:(BOOL)optional; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMProperty_Private.hpp b/Pods/Realm/include/RLMProperty_Private.hpp new file mode 100644 index 0000000000..cf8b17a516 --- /dev/null +++ b/Pods/Realm/include/RLMProperty_Private.hpp @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +namespace realm { + struct Property; +} + +@class RLMSchema; + +@interface RLMProperty () + ++ (instancetype)propertyForObjectStoreProperty:(const realm::Property&)property; + +- (realm::Property)objectStoreCopy:(RLMSchema *)schema; + +@end diff --git a/Pods/Realm/include/RLMQueryUtil.hpp b/Pods/Realm/include/RLMQueryUtil.hpp new file mode 100644 index 0000000000..12df76e67f --- /dev/null +++ b/Pods/Realm/include/RLMQueryUtil.hpp @@ -0,0 +1,39 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import + +namespace realm { + class Group; + class Query; + class SortDescriptor; +} + +@class RLMObjectSchema, RLMProperty, RLMSchema, RLMSortDescriptor; +class RLMClassInfo; + +extern NSString * const RLMPropertiesComparisonTypeMismatchException; +extern NSString * const RLMUnsupportedTypesFoundInPropertyComparisonException; + +realm::Query RLMPredicateToQuery(NSPredicate *predicate, RLMObjectSchema *objectSchema, + RLMSchema *schema, realm::Group &group); + +// return property - throw for invalid column name +RLMProperty *RLMValidatedProperty(RLMObjectSchema *objectSchema, NSString *columnName); diff --git a/Pods/Realm/include/RLMRealm+Sync.h b/Pods/Realm/include/RLMRealm+Sync.h new file mode 100644 index 0000000000..ccfcb0202a --- /dev/null +++ b/Pods/Realm/include/RLMRealm+Sync.h @@ -0,0 +1,56 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMRealm.h" + +@class RLMResults, RLMSyncSession; + +/** + A callback used to vend the results of a partial sync fetch. + */ +typedef void(^RLMPartialSyncFetchCallback)(RLMResults * _Nullable results, NSError * _Nullable error); + +NS_ASSUME_NONNULL_BEGIN + +/// +@interface RLMRealm (Sync) + +/** + If the Realm is a partially synchronized Realm, fetch and synchronize the objects + of a given object type that match the given query (in string format). + + The results will be returned asynchronously in the callback. + Use `-[RLMResults addNotificationBlock:]` to be notified to changes to the set of + synchronized objects. + + @warning Partial synchronization is a tech preview. Its APIs are subject to change. +*/ +- (void)subscribeToObjects:(Class)type where:(NSString *)query callback:(RLMPartialSyncFetchCallback)callback +__deprecated_msg("Use -[RLMResults subscribe]"); + +/** + Get the RLMSyncSession used by this Realm. Will be nil if this is not a + synchronized Realm. +*/ +@property (nonatomic, nullable, readonly) RLMSyncSession *syncSession; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMRealm.h b/Pods/Realm/include/RLMRealm.h new file mode 100644 index 0000000000..aa554177d4 --- /dev/null +++ b/Pods/Realm/include/RLMRealm.h @@ -0,0 +1,736 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import "RLMConstants.h" + +@class RLMRealmConfiguration, RLMRealm, RLMObject, RLMSchema, RLMMigration, RLMNotificationToken, RLMThreadSafeReference; +struct RLMRealmPrivileges; +struct RLMClassPrivileges; +struct RLMObjectPrivileges; + +/** + A callback block for opening Realms asynchronously. + + Returns the Realm if the open was successful, or an error otherwise. + */ +typedef void(^RLMAsyncOpenRealmCallback)(RLMRealm * _Nullable realm, NSError * _Nullable error); + +NS_ASSUME_NONNULL_BEGIN + +/** + An `RLMRealm` instance (also referred to as "a Realm") represents a Realm + database. + + Realms can either be stored on disk (see `+[RLMRealm realmWithURL:]`) or in + memory (see `RLMRealmConfiguration`). + + `RLMRealm` instances are cached internally, and constructing equivalent `RLMRealm` + objects (for example, by using the same path or identifier) multiple times on a single thread + within a single iteration of the run loop will normally return the same + `RLMRealm` object. + + If you specifically want to ensure an `RLMRealm` instance is + destroyed (for example, if you wish to open a Realm, check some property, and + then possibly delete the Realm file and re-open it), place the code which uses + the Realm within an `@autoreleasepool {}` and ensure you have no other + strong references to it. + + @warning `RLMRealm` instances are not thread safe and cannot be shared across + threads or dispatch queues. Trying to do so will cause an exception to be thrown. + You must call this method on each thread you want + to interact with the Realm on. For dispatch queues, this means that you must + call it in each block which is dispatched, as a queue is not guaranteed to run + all of its blocks on the same thread. + */ + +@interface RLMRealm : NSObject + +#pragma mark - Creating & Initializing a Realm + +/** + Obtains an instance of the default Realm. + + The default Realm is used by the `RLMObject` class methods + which do not take an `RLMRealm` parameter, but is otherwise not special. The + default Realm is persisted as *default.realm* under the *Documents* directory of + your Application on iOS, and in your application's *Application Support* + directory on OS X. + + The default Realm is created using the default `RLMRealmConfiguration`, which + can be changed via `+[RLMRealmConfiguration setDefaultConfiguration:]`. + + @return The default `RLMRealm` instance for the current thread. + */ ++ (instancetype)defaultRealm; + +/** + Obtains an `RLMRealm` instance with the given configuration. + + @param configuration A configuration object to use when creating the Realm. + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return An `RLMRealm` instance. + */ ++ (nullable instancetype)realmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error; + +/** + Obtains an `RLMRealm` instance persisted at a specified file URL. + + @param fileURL The local URL of the file the Realm should be saved at. + + @return An `RLMRealm` instance. + */ ++ (instancetype)realmWithURL:(NSURL *)fileURL; + +/** + Asynchronously open a Realm and deliver it to a block on the given queue. + + Opening a Realm asynchronously will perform all work needed to get the Realm to + a usable state (such as running potentially time-consuming migrations) on a + background thread before dispatching to the given queue. In addition, + synchronized Realms wait for all remote content available at the time the + operation began to be downloaded and available locally. + + @param configuration A configuration object to use when opening the Realm. + @param callbackQueue The dispatch queue on which the callback should be run. + @param callback A callback block. If the Realm was successfully opened, + it will be passed in as an argument. + Otherwise, an `NSError` describing what went wrong will be + passed to the block instead. + + @note The returned Realm is confined to the thread on which it was created. + Because GCD does not guarantee that queues will always use the same + thread, accessing the returned Realm outside the callback block (even if + accessed from `callbackQueue`) is unsafe. + */ ++ (void)asyncOpenWithConfiguration:(RLMRealmConfiguration *)configuration + callbackQueue:(dispatch_queue_t)callbackQueue + callback:(RLMAsyncOpenRealmCallback)callback; + +/** + The `RLMSchema` used by the Realm. + */ +@property (nonatomic, readonly) RLMSchema *schema; + +/** + Indicates if the Realm is currently engaged in a write transaction. + + @warning Do not simply check this property and then start a write transaction whenever an object needs to be + created, updated, or removed. Doing so might cause a large number of write transactions to be created, + degrading performance. Instead, always prefer performing multiple updates during a single transaction. + */ +@property (nonatomic, readonly) BOOL inWriteTransaction; + +/** + The `RLMRealmConfiguration` object that was used to create this `RLMRealm` instance. + */ +@property (nonatomic, readonly) RLMRealmConfiguration *configuration; + +/** + Indicates if this Realm contains any objects. + */ +@property (nonatomic, readonly) BOOL isEmpty; + +#pragma mark - Notifications + +/** + The type of a block to run whenever the data within the Realm is modified. + + @see `-[RLMRealm addNotificationBlock:]` + */ +typedef void (^RLMNotificationBlock)(RLMNotification notification, RLMRealm *realm); + +#pragma mark - Receiving Notification when a Realm Changes + +/** + Adds a notification handler for changes in this Realm, and returns a notification token. + + Notification handlers are called after each write transaction is committed, + either on the current thread or other threads. + + Handler blocks are called on the same thread that they were added on, and may + only be added on threads which are currently within a run loop. Unless you are + specifically creating and running a run loop on a background thread, this will + normally only be the main thread. + + The block has the following definition: + + typedef void(^RLMNotificationBlock)(RLMNotification notification, RLMRealm *realm); + + It receives the following parameters: + + - `NSString` \***notification**: The name of the incoming notification. See + `RLMRealmNotification` for information on what + notifications are sent. + - `RLMRealm` \***realm**: The Realm for which this notification occurred. + + @param block A block which is called to process Realm notifications. + + @return A token object which must be retained as long as you wish to continue + receiving change notifications. + */ +- (RLMNotificationToken *)addNotificationBlock:(RLMNotificationBlock)block __attribute__((warn_unused_result)); + +#pragma mark - Transactions + + +#pragma mark - Writing to a Realm + +/** + Begins a write transaction on the Realm. + + Only one write transaction can be open at a time for each Realm file. Write + transactions cannot be nested, and trying to begin a write transaction on a + Realm which is already in a write transaction will throw an exception. Calls to + `beginWriteTransaction` from `RLMRealm` instances for the same Realm file in + other threads or other processes will block until the current write transaction + completes or is cancelled. + + Before beginning the write transaction, `beginWriteTransaction` updates the + `RLMRealm` instance to the latest Realm version, as if `refresh` had been + called, and generates notifications if applicable. This has no effect if the + Realm was already up to date. + + It is rarely a good idea to have write transactions span multiple cycles of + the run loop, but if you do wish to do so you will need to ensure that the + Realm participating in the write transaction is kept alive until the write + transaction is committed. + */ +- (void)beginWriteTransaction; + +/** + Commits all write operations in the current write transaction, and ends the + transaction. + + After saving the changes, all notification blocks registered on this specific + `RLMRealm` instance are invoked synchronously. Notification blocks registered + on other threads or on collections are invoked asynchronously. If you do not + want to receive a specific notification for this write tranaction, see + `commitWriteTransactionWithoutNotifying:error:`. + + This method can fail if there is insufficient disk space available to save the + writes made, or due to unexpected i/o errors. This version of the method throws + an exception when errors occur. Use the version with a `NSError` out parameter + instead if you wish to handle errors. + + @warning This method may only be called during a write transaction. + */ +- (void)commitWriteTransaction NS_SWIFT_UNAVAILABLE(""); + +/** + Commits all write operations in the current write transaction, and ends the + transaction. + + After saving the changes, all notification blocks registered on this specific + `RLMRealm` instance are invoked synchronously. Notification blocks registered + on other threads or on collections are invoked asynchronously. If you do not + want to receive a specific notification for this write tranaction, see + `commitWriteTransactionWithoutNotifying:error:`. + + This method can fail if there is insufficient disk space available to save the + writes made, or due to unexpected i/o errors. + + @warning This method may only be called during a write transaction. + + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return Whether the transaction succeeded. + */ +- (BOOL)commitWriteTransaction:(NSError **)error; + +/** + Commits all write operations in the current write transaction, without + notifying specific notification blocks of the changes. + + After saving the changes, all notification blocks registered on this specific + `RLMRealm` instance are invoked synchronously. Notification blocks registered + on other threads or on collections are scheduled to be invoked asynchronously. + + You can skip notifiying specific notification blocks about the changes made + in this write transaction by passing in their associated notification tokens. + This is primarily useful when the write transaction is saving changes already + made in the UI and you do not want to have the notification block attempt to + re-apply the same changes. + + The tokens passed to this method must be for notifications for this specific + `RLMRealm` instance. Notifications for different threads cannot be skipped + using this method. + + This method can fail if there is insufficient disk space available to save the + writes made, or due to unexpected i/o errors. + + @warning This method may only be called during a write transaction. + + @param tokens An array of notification tokens which were returned from adding + callbacks which you do not want to be notified for the changes + made in this write transaction. + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return Whether the transaction succeeded. + */ +- (BOOL)commitWriteTransactionWithoutNotifying:(NSArray *)tokens error:(NSError **)error; + +/** + Reverts all writes made during the current write transaction and ends the transaction. + + This rolls back all objects in the Realm to the state they were in at the + beginning of the write transaction, and then ends the transaction. + + This restores the data for deleted objects, but does not revive invalidated + object instances. Any `RLMObject`s which were added to the Realm will be + invalidated rather than becoming unmanaged. + Given the following code: + + ObjectType *oldObject = [[ObjectType objectsWhere:@"..."] firstObject]; + ObjectType *newObject = [[ObjectType alloc] init]; + + [realm beginWriteTransaction]; + [realm addObject:newObject]; + [realm deleteObject:oldObject]; + [realm cancelWriteTransaction]; + + Both `oldObject` and `newObject` will return `YES` for `isInvalidated`, + but re-running the query which provided `oldObject` will once again return + the valid object. + + KVO observers on any objects which were modified during the transaction will + be notified about the change back to their initial values, but no other + notifcations are produced by a cancelled write transaction. + + @warning This method may only be called during a write transaction. + */ +- (void)cancelWriteTransaction; + +/** + Performs actions contained within the given block inside a write transaction. + + @see `[RLMRealm transactionWithBlock:error:]` + */ +- (void)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block NS_SWIFT_UNAVAILABLE(""); + +/** + Performs actions contained within the given block inside a write transaction. + + Write transactions cannot be nested, and trying to execute a write transaction + on a Realm which is already participating in a write transaction will throw an + exception. Calls to `transactionWithBlock:` from `RLMRealm` instances in other + threads will block until the current write transaction completes. + + Before beginning the write transaction, `transactionWithBlock:` updates the + `RLMRealm` instance to the latest Realm version, as if `refresh` had been called, and + generates notifications if applicable. This has no effect if the Realm + was already up to date. + + @param block The block containing actions to perform. + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return Whether the transaction succeeded. + */ +- (BOOL)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block error:(NSError **)error; + +/** + Updates the Realm and outstanding objects managed by the Realm to point to the + most recent data. + + If the version of the Realm is actually changed, Realm and collection + notifications will be sent to reflect the changes. This may take some time, as + collection notifications are prepared on a background thread. As a result, + calling this method on the main thread is not advisable. + + @return Whether there were any updates for the Realm. Note that `YES` may be + returned even if no data actually changed. + */ +- (BOOL)refresh; + +/** + Set this property to `YES` to automatically update this Realm when changes + happen in other threads. + + If set to `YES` (the default), changes made on other threads will be reflected + in this Realm on the next cycle of the run loop after the changes are + committed. If set to `NO`, you must manually call `-refresh` on the Realm to + update it to get the latest data. + + Note that by default, background threads do not have an active run loop and you + will need to manually call `-refresh` in order to update to the latest version, + even if `autorefresh` is set to `YES`. + + Even with this property enabled, you can still call `-refresh` at any time to + update the Realm before the automatic refresh would occur. + + Write transactions will still always advance a Realm to the latest version and + produce local notifications on commit even if autorefresh is disabled. + + Disabling `autorefresh` on a Realm without any strong references to it will not + have any effect, and `autorefresh` will revert back to `YES` the next time the + Realm is created. This is normally irrelevant as it means that there is nothing + to refresh (as managed `RLMObject`s, `RLMArray`s, and `RLMResults` have strong + references to the Realm that manages them), but it means that setting + `RLMRealm.defaultRealm.autorefresh = NO` in + `application:didFinishLaunchingWithOptions:` and only later storing Realm + objects will not work. + + Defaults to `YES`. + */ +@property (nonatomic) BOOL autorefresh; + +/** + Writes a compacted and optionally encrypted copy of the Realm to the given local URL. + + The destination file cannot already exist. + + Note that if this method is called from within a write transaction, the + *current* data is written, not the data from the point when the previous write + transaction was committed. + + @param fileURL Local URL to save the Realm to. + @param key Optional 64-byte encryption key to encrypt the new file with. + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return `YES` if the Realm was successfully written to disk, `NO` if an error occurred. +*/ +- (BOOL)writeCopyToURL:(NSURL *)fileURL encryptionKey:(nullable NSData *)key error:(NSError **)error; + +/** + Invalidates all `RLMObject`s, `RLMResults`, `RLMLinkingObjects`, and `RLMArray`s managed by the Realm. + + A Realm holds a read lock on the version of the data accessed by it, so + that changes made to the Realm on different threads do not modify or delete the + data seen by this Realm. Calling this method releases the read lock, + allowing the space used on disk to be reused by later write transactions rather + than growing the file. This method should be called before performing long + blocking operations on a background thread on which you previously read data + from the Realm which you no longer need. + + All `RLMObject`, `RLMResults` and `RLMArray` instances obtained from this + `RLMRealm` instance on the current thread are invalidated. `RLMObject`s and `RLMArray`s + cannot be used. `RLMResults` will become empty. The Realm itself remains valid, + and a new read transaction is implicitly begun the next time data is read from the Realm. + + Calling this method multiple times in a row without reading any data from the + Realm, or before ever reading any data from the Realm, is a no-op. This method + may not be called on a read-only Realm. + */ +- (void)invalidate; + +#pragma mark - Accessing Objects + +/** + Returns the same object as the one referenced when the `RLMThreadSafeReference` was first created, + but resolved for the current Realm for this thread. Returns `nil` if this object was deleted after + the reference was created. + + @param reference The thread-safe reference to the thread-confined object to resolve in this Realm. + + @warning A `RLMThreadSafeReference` object must be resolved at most once. + Failing to resolve a `RLMThreadSafeReference` will result in the source version of the + Realm being pinned until the reference is deallocated. + An exception will be thrown if a reference is resolved more than once. + + @warning Cannot call within a write transaction. + + @note Will refresh this Realm if the source Realm was at a later version than this one. + + @see `+[RLMThreadSafeReference referenceWithThreadConfined:]` + */ +- (nullable id)resolveThreadSafeReference:(RLMThreadSafeReference *)reference +NS_REFINED_FOR_SWIFT; + +#pragma mark - Adding and Removing Objects from a Realm + +/** + Adds an object to the Realm. + + Once added, this object is considered to be managed by the Realm. It can be retrieved + using the `objectsWhere:` selectors on `RLMRealm` and on subclasses of `RLMObject`. + + When added, all child relationships referenced by this object will also be added to + the Realm if they are not already in it. + + If the object or any related objects are already being managed by a different Realm + an exception will be thrown. Use `-[RLMObject createInRealm:withObject:]` to insert a copy of a managed object + into a different Realm. + + The object to be added must be valid and cannot have been previously deleted + from a Realm (i.e. `isInvalidated` must be `NO`). + + @warning This method may only be called during a write transaction. + + @param object The object to be added to this Realm. + */ +- (void)addObject:(RLMObject *)object; + +/** + Adds all the objects in a collection to the Realm. + + This is the equivalent of calling `addObject:` for every object in a collection. + + @warning This method may only be called during a write transaction. + + @param objects An enumerable collection such as `NSArray`, `RLMArray`, or `RLMResults`, + containing Realm objects to be added to the Realm. + + @see `addObject:` + */ +- (void)addObjects:(id)objects; + +/** + Adds or updates an existing object into the Realm. + + The object provided must have a designated primary key. If no objects exist in the Realm + with the same primary key value, the object is inserted. Otherwise, the existing object is + updated with any changed values. + + As with `addObject:`, the object cannot already be managed by a different + Realm. Use `-[RLMObject createOrUpdateInRealm:withValue:]` to copy values to + a different Realm. + + If there is a property or KVC value on `object` whose value is nil, and it corresponds + to a nullable property on an existing object being updated, that nullable property will + be set to nil. + + @warning This method may only be called during a write transaction. + + @param object The object to be added or updated. + */ +- (void)addOrUpdateObject:(RLMObject *)object; + +/** + Adds or updates all the objects in a collection into the Realm. + + This is the equivalent of calling `addOrUpdateObject:` for every object in a collection. + + @warning This method may only be called during a write transaction. + + @param objects An enumerable collection such as `NSArray`, `RLMArray`, or `RLMResults`, + containing Realm objects to be added to or updated within the Realm. + + @see `addOrUpdateObject:` + */ +- (void)addOrUpdateObjects:(id)objects; + +/** + Deletes an object from the Realm. Once the object is deleted it is considered invalidated. + + @warning This method may only be called during a write transaction. + + @param object The object to be deleted. + */ +- (void)deleteObject:(RLMObject *)object; + +/** + Deletes one or more objects from the Realm. + + This is the equivalent of calling `deleteObject:` for every object in a collection. + + @warning This method may only be called during a write transaction. + + @param objects An enumerable collection such as `NSArray`, `RLMArray`, or `RLMResults`, + containing objects to be deleted from the Realm. + + @see `deleteObject:` + */ +- (void)deleteObjects:(id)objects; + +/** + Deletes all objects from the Realm. + + @warning This method may only be called during a write transaction. + + @see `deleteObject:` + */ +- (void)deleteAllObjects; + + +#pragma mark - Migrations + +/** + The type of a migration block used to migrate a Realm. + + @param migration A `RLMMigration` object used to perform the migration. The + migration object allows you to enumerate and alter any + existing objects which require migration. + + @param oldSchemaVersion The schema version of the Realm being migrated. + */ +typedef void (^RLMMigrationBlock)(RLMMigration *migration, uint64_t oldSchemaVersion); + +/** + Returns the schema version for a Realm at a given local URL. + + @param fileURL Local URL to a Realm file. + @param key 64-byte key used to encrypt the file, or `nil` if it is unencrypted. + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return The version of the Realm at `fileURL`, or `RLMNotVersioned` if the version cannot be read. + */ ++ (uint64_t)schemaVersionAtURL:(NSURL *)fileURL encryptionKey:(nullable NSData *)key error:(NSError **)error +NS_REFINED_FOR_SWIFT; + +/** + Performs the given Realm configuration's migration block on a Realm at the given path. + + This method is called automatically when opening a Realm for the first time and does + not need to be called explicitly. You can choose to call this method to control + exactly when and how migrations are performed. + + @param configuration The Realm configuration used to open and migrate the Realm. + @return The error that occurred while applying the migration, if any. + + @see RLMMigration + */ ++ (BOOL)performMigrationForConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error; + +#pragma mark - Privileges + +/** + Returns the computed privileges which the current user has for this Realm. + + This combines all privileges granted on the Realm by all Roles which the + current User is a member of into the final privileges which will be enforced by + the server. + + The privilege calculation is done locally using cached data, and inherently may + be stale. It is possible that this method may indicate that an operation is + permitted but the server will still reject it if permission is revoked before + the changes have been integrated on the server. + + Non-synchronized Realms always have permission to perform all operations. + + @warning This currently returns incorrect results for non-partially-synchronized read-only Realms. + @return The privileges which the current user has for the current Realm. + */ +- (struct RLMRealmPrivileges)privilegesForRealm; + +/** + Returns the computed privileges which the current user has for the given object. + + This combines all privileges granted on the object by all Roles which the + current User is a member of into the final privileges which will be enforced by + the server. + + The privilege calculation is done locally using cached data, and inherently may + be stale. It is possible that this method may indicate that an operation is + permitted but the server will still reject it if permission is revoked before + the changes have been integrated on the server. + + Non-synchronized Realms always have permission to perform all operations. + + The object must be a valid object managed by this Realm. Passing in an + invalidated object, an unmanaged object, or an object managed by a different + Realm will throw an exception. + + @warning This currently returns incorrect results for non-partially-synchronized read-only Realms. + @return The privileges which the current user has for the given object. + */ +- (struct RLMObjectPrivileges)privilegesForObject:(RLMObject *)object; + +/** + Returns the computed privileges which the current user has for the given class. + + This combines all privileges granted on the class by all Roles which the + current User is a member of into the final privileges which will be enforced by + the server. + + The privilege calculation is done locally using cached data, and inherently may + be stale. It is possible that this method may indicate that an operation is + permitted but the server will still reject it if permission is revoked before + the changes have been integrated on the server. + + Non-synchronized Realms always have permission to perform all operations. + + @warning This currently returns incorrect results for non-partially-synchronized read-only Realms. + @return The privileges which the current user has for the given object. + */ +- (struct RLMClassPrivileges)privilegesForClass:(Class)cls; + +/** + Returns the computed privileges which the current user has for the named class. + + This combines all privileges granted on the class by all Roles which the + current User is a member of into the final privileges which will be enforced by + the server. + + The privilege calculation is done locally using cached data, and inherently may + be stale. It is possible that this method may indicate that an operation is + permitted but the server will still reject it if permission is revoked before + the changes have been integrated on the server. + + Non-synchronized Realms always have permission to perform all operations. + + @warning This currently returns incorrect results for non-partially-synchronized read-only Realms. + @return The privileges which the current user has for the given object. + */ +- (struct RLMClassPrivileges)privilegesForClassNamed:(NSString *)className; + +#pragma mark - Unavailable Methods + +/** + RLMRealm instances are cached internally by Realm and cannot be created directly. + + Use `+[RLMRealm defaultRealm]`, `+[RLMRealm realmWithConfiguration:error:]` or + `+[RLMRealm realmWithURL]` to obtain a reference to an RLMRealm. + */ +- (instancetype)init __attribute__((unavailable("Use +defaultRealm, +realmWithConfiguration: or +realmWithURL:."))); + +/** + RLMRealm instances are cached internally by Realm and cannot be created directly. + + Use `+[RLMRealm defaultRealm]`, `+[RLMRealm realmWithConfiguration:error:]` or + `+[RLMRealm realmWithURL]` to obtain a reference to an RLMRealm. + */ ++ (instancetype)new __attribute__((unavailable("Use +defaultRealm, +realmWithConfiguration: or +realmWithURL:."))); + +/// :nodoc: +- (void)addOrUpdateObjectsFromArray:(id)array __attribute__((unavailable("Renamed to -addOrUpdateObjects:."))); + +@end + +// MARK: - RLMNotificationToken + +/** + A token which is returned from methods which subscribe to changes to a Realm. + + Change subscriptions in Realm return an `RLMNotificationToken` instance, + which can be used to unsubscribe from the changes. You must store a strong + reference to the token for as long as you want to continue to receive notifications. + When you wish to stop, call the `-invalidate` method. Notifications are also stopped if + the token is deallocated. + */ +@interface RLMNotificationToken : NSObject +/// Stops notifications for the change subscription that returned this token. +- (void)invalidate; + +/// Stops notifications for the change subscription that returned this token. +- (void)stop __attribute__((unavailable("Renamed to -invalidate."))) NS_REFINED_FOR_SWIFT; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMRealmConfiguration+Sync.h b/Pods/Realm/include/RLMRealmConfiguration+Sync.h new file mode 100644 index 0000000000..abd51bf594 --- /dev/null +++ b/Pods/Realm/include/RLMRealmConfiguration+Sync.h @@ -0,0 +1,43 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMSyncUtil.h" + +@class RLMSyncConfiguration; + +/// Realm configuration options related to Sync. +@interface RLMRealmConfiguration (Sync) + +NS_ASSUME_NONNULL_BEGIN + +/** + A configuration object representing configuration state for Realms intended + to sync with a Realm Object Server. + + This property is mutually exclusive with both `inMemoryIdentifier` and `fileURL`; + setting any one of the three properties will automatically nil out the other two. + + @see `RLMSyncConfiguration` + */ +@property (nullable, nonatomic) RLMSyncConfiguration *syncConfiguration; + +NS_ASSUME_NONNULL_END + +@end diff --git a/Pods/Realm/include/RLMRealmConfiguration.h b/Pods/Realm/include/RLMRealmConfiguration.h new file mode 100644 index 0000000000..3ec8fd55ca --- /dev/null +++ b/Pods/Realm/include/RLMRealmConfiguration.h @@ -0,0 +1,123 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + A block called when opening a Realm for the first time during the life + of a process to determine if it should be compacted before being returned + to the user. It is passed the total file size (data + free space) and the total + bytes used by data in the file. + + Return `YES` to indicate that an attempt to compact the file should be made. + The compaction will be skipped if another process is accessing it. + */ +typedef BOOL (^RLMShouldCompactOnLaunchBlock)(NSUInteger totalBytes, NSUInteger bytesUsed); + +/** + An `RLMRealmConfiguration` instance describes the different options used to + create an instance of a Realm. + + `RLMRealmConfiguration` instances are just plain `NSObject`s. Unlike `RLMRealm`s + and `RLMObject`s, they can be freely shared between threads as long as you do not + mutate them. + + Creating configuration objects for class subsets (by setting the + `objectClasses` property) can be expensive. Because of this, you will normally want to + cache and reuse a single configuration object for each distinct configuration rather than + creating a new object each time you open a Realm. + */ +@interface RLMRealmConfiguration : NSObject + +#pragma mark - Default Configuration + +/** + Returns the default configuration used to create Realms when no other + configuration is explicitly specified (i.e. `+[RLMRealm defaultRealm]`). + + @return The default Realm configuration. + */ ++ (instancetype)defaultConfiguration; + +/** + Sets the default configuration to the given `RLMRealmConfiguration`. + + @param configuration The new default Realm configuration. + */ ++ (void)setDefaultConfiguration:(RLMRealmConfiguration *)configuration; + +#pragma mark - Properties + +/// The local URL of the Realm file. Mutually exclusive with `inMemoryIdentifier` and `syncConfiguration`; +/// setting any one of the three properties will automatically nil out the other two. +@property (nonatomic, copy, nullable) NSURL *fileURL; + +/// A string used to identify a particular in-memory Realm. Mutually exclusive with `fileURL` and `syncConfiguration`; +/// setting any one of the three properties will automatically nil out the other two. +@property (nonatomic, copy, nullable) NSString *inMemoryIdentifier; + +/// A 64-byte key to use to encrypt the data, or `nil` if encryption is not enabled. +@property (nonatomic, copy, nullable) NSData *encryptionKey; + +/// Whether to open the Realm in read-only mode. +/// +/// This is required to be able to open Realm files which are not writeable or +/// are in a directory which is not writeable. This should only be used on files +/// which will not be modified by anyone while they are open, and not just to +/// get a read-only view of a file which may be written to by another thread or +/// process. Opening in read-only mode requires disabling Realm's reader/writer +/// coordination, so committing a write transaction from another process will +/// result in crashes. +@property (nonatomic) BOOL readOnly; + +/// The current schema version. +@property (nonatomic) uint64_t schemaVersion; + +/// The block which migrates the Realm to the current version. +@property (nonatomic, copy, nullable) RLMMigrationBlock migrationBlock; + +/** + Whether to recreate the Realm file with the provided schema if a migration is required. + This is the case when the stored schema differs from the provided schema or + the stored schema version differs from the version on this configuration. + Setting this property to `YES` deletes the file if a migration would otherwise be required or executed. + + @note Setting this property to `YES` doesn't disable file format migrations. + */ +@property (nonatomic) BOOL deleteRealmIfMigrationNeeded; + +/** + A block called when opening a Realm for the first time during the life + of a process to determine if it should be compacted before being returned + to the user. It is passed the total file size (data + free space) and the total + bytes used by data in the file. + + Return `YES` to indicate that an attempt to compact the file should be made. + The compaction will be skipped if another process is accessing it. + */ +@property (nonatomic, copy, nullable) RLMShouldCompactOnLaunchBlock shouldCompactOnLaunch; + +/// The classes managed by the Realm. +@property (nonatomic, copy, nullable) NSArray *objectClasses; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMRealmConfiguration_Private.h b/Pods/Realm/include/RLMRealmConfiguration_Private.h new file mode 100644 index 0000000000..b3e47846ad --- /dev/null +++ b/Pods/Realm/include/RLMRealmConfiguration_Private.h @@ -0,0 +1,45 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMSchema; + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMRealmConfiguration () + +@property (nonatomic, readwrite) bool cache; +@property (nonatomic, readwrite) bool dynamic; +@property (nonatomic, readwrite) bool disableFormatUpgrade; +@property (nonatomic, copy, nullable) RLMSchema *customSchema; +@property (nonatomic, copy) NSString *pathOnDisk; + +// Get the default confiugration without copying it ++ (RLMRealmConfiguration *)rawDefaultConfiguration; + ++ (void)resetRealmConfigurationState; + +- (void)setCustomSchemaWithoutCopying:(nullable RLMSchema *)schema; +@end + +// Get a path in the platform-appropriate documents directory with the given filename +FOUNDATION_EXTERN NSString *RLMRealmPathForFile(NSString *fileName); +FOUNDATION_EXTERN NSString *RLMRealmPathForFileAndBundleIdentifier(NSString *fileName, NSString *mainBundleIdentifier); + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMRealmConfiguration_Private.hpp b/Pods/Realm/include/RLMRealmConfiguration_Private.hpp new file mode 100644 index 0000000000..a89fb0fd3b --- /dev/null +++ b/Pods/Realm/include/RLMRealmConfiguration_Private.hpp @@ -0,0 +1,26 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMRealmConfiguration_Private.h" +#import "shared_realm.hpp" + +@interface RLMRealmConfiguration () +- (realm::Realm::Config&)config; + +@property (nonatomic) realm::SchemaMode schemaMode; +@end diff --git a/Pods/Realm/include/RLMRealmUtil.hpp b/Pods/Realm/include/RLMRealmUtil.hpp new file mode 100644 index 0000000000..4960b9c40a --- /dev/null +++ b/Pods/Realm/include/RLMRealmUtil.hpp @@ -0,0 +1,39 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +@class RLMRealm; + +namespace realm { + class BindingContext; +} + +// Add a Realm to the weak cache +void RLMCacheRealm(std::string const& path, RLMRealm *realm); +// Get a Realm for the given path which can be used on the current thread +RLMRealm *RLMGetThreadLocalCachedRealmForPath(std::string const& path); +// Get a Realm for the given path +RLMRealm *RLMGetAnyCachedRealmForPath(std::string const& path); +// Clear the weak cache of Realms +void RLMClearRealmCache(); +// Check if the current thread is currently within a running CFRunLoop +bool RLMIsInRunLoop(); + +std::unique_ptr RLMCreateBindingContext(RLMRealm *realm); diff --git a/Pods/Realm/include/RLMRealm_Dynamic.h b/Pods/Realm/include/RLMRealm_Dynamic.h new file mode 100644 index 0000000000..f796ed32e5 --- /dev/null +++ b/Pods/Realm/include/RLMRealm_Dynamic.h @@ -0,0 +1,118 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import +#import + +@class RLMResults; + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMRealm (Dynamic) + +#pragma mark - Getting Objects from a Realm + +/** + Returns all objects of a given type from the Realm. + + @warning This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. The preferred way to get objects of a single class is to use the class + methods on `RLMObject`. + + @param className The name of the `RLMObject` subclass to retrieve on (e.g. `MyClass.className`). + + @return An `RLMResults` containing all objects in the Realm of the given type. + + @see `+[RLMObject allObjects]` + */ +- (RLMResults *)allObjects:(NSString *)className; + +/** + Returns all objects matching the given predicate from the Realm. + + @warning This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. The preferred way to get objects of a single class is to use the class + methods on `RLMObject`. + + @param className The type of objects you are looking for (name of the class). + @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. + + @return An `RLMResults` containing results matching the given predicate. + + @see `+[RLMObject objectsWhere:]` + */ +- (RLMResults *)objects:(NSString *)className where:(NSString *)predicateFormat, ...; + +/** + Returns all objects matching the given predicate from the Realm. + + @warning This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. The preferred way to get objects of a single class is to use the class + methods on `RLMObject`. + + @param className The type of objects you are looking for (name of the class). + @param predicate The predicate with which to filter the objects. + + @return An `RLMResults` containing results matching the given predicate. + + @see `+[RLMObject objectsWhere:]` + */ +- (RLMResults *)objects:(NSString *)className withPredicate:(NSPredicate *)predicate; + +/** + Returns the object of the given type with the given primary key from the Realm. + + @warning This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. The preferred way to get an object of a single class is to use the class + methods on `RLMObject`. + + @param className The class name for the object you are looking for. + @param primaryKey The primary key value for the object you are looking for. + + @return An object, or `nil` if an object with the given primary key does not exist. + + @see `+[RLMObject objectForPrimaryKey:]` + */ +- (nullable RLMObject *)objectWithClassName:(NSString *)className forPrimaryKey:(id)primaryKey; + +/** + Creates an `RLMObject` instance of type `className` in the Realm, and populates it using a given object. + + The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or + dictionary returned from the methods in `NSJSONSerialization`, or an array containing one element for each managed + property. An exception will be thrown if any required properties are not present and those properties were not defined + with default values. + + When passing in an array as the `value` argument, all properties must be present, valid and in the same order as the + properties defined in the model. + + @warning This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is recommended to + use `[RLMObject createInDefaultRealmWithValue:]`. + + @param value The value used to populate the object. + + @return An `RLMObject` instance of type `className`. + */ +-(RLMObject *)createObject:(NSString *)className withValue:(id)value; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMRealm_Private.h b/Pods/Realm/include/RLMRealm_Private.h new file mode 100644 index 0000000000..59b7c6501c --- /dev/null +++ b/Pods/Realm/include/RLMRealm_Private.h @@ -0,0 +1,52 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMFastEnumerator; + +NS_ASSUME_NONNULL_BEGIN + +// Disable syncing files to disk. Cannot be re-enabled. Use only for tests. +FOUNDATION_EXTERN void RLMDisableSyncToDisk(void); + +FOUNDATION_EXTERN NSData * _Nullable RLMRealmValidatedEncryptionKey(NSData *key); + +// Translate an in-flight exception resulting from an operation on a SharedGroup to +// an NSError or NSException (if error is nil) +void RLMRealmTranslateException(NSError **error); + +// RLMRealm private members +@interface RLMRealm () + +@property (nonatomic, readonly) BOOL dynamic; +@property (nonatomic, readwrite) RLMSchema *schema; + ++ (void)resetRealmState; + +- (void)registerEnumerator:(RLMFastEnumerator *)enumerator; +- (void)unregisterEnumerator:(RLMFastEnumerator *)enumerator; +- (void)detachAllEnumerators; + +- (void)sendNotifications:(RLMNotification)notification; +- (void)verifyThread; +- (void)verifyNotificationsAreSupported:(bool)isCollection; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMRealm_Private.hpp b/Pods/Realm/include/RLMRealm_Private.hpp new file mode 100644 index 0000000000..a1bb294a9a --- /dev/null +++ b/Pods/Realm/include/RLMRealm_Private.hpp @@ -0,0 +1,36 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMRealm_Private.h" + +#import "RLMClassInfo.hpp" + +namespace realm { + class Group; + class Realm; +} + +@interface RLMRealm () { + @public + std::shared_ptr _realm; + RLMSchemaInfo _info; +} + +// FIXME - group should not be exposed +@property (nonatomic, readonly) realm::Group &group; +@end diff --git a/Pods/Realm/include/RLMResults.h b/Pods/Realm/include/RLMResults.h new file mode 100644 index 0000000000..d8d1cf6fda --- /dev/null +++ b/Pods/Realm/include/RLMResults.h @@ -0,0 +1,351 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMObject; + +/** + `RLMResults` is an auto-updating container type in Realm returned from object + queries. It represents the results of the query in the form of a collection of objects. + + `RLMResults` can be queried using the same predicates as `RLMObject` and `RLMArray`, + and you can chain queries to further filter results. + + `RLMResults` always reflect the current state of the Realm on the current thread, + including during write transactions on the current thread. The one exception to + this is when using `for...in` fast enumeration, which will always enumerate + over the objects which matched the query when the enumeration is begun, even if + some of them are deleted or modified to be excluded by the filter during the + enumeration. + + `RLMResults` are lazily evaluated the first time they are accessed; they only + run queries when the result of the query is requested. This means that + chaining several temporary `RLMResults` to sort and filter your data does not + perform any extra work processing the intermediate state. + + Once the results have been evaluated or a notification block has been added, + the results are eagerly kept up-to-date, with the work done to keep them + up-to-date done on a background thread whenever possible. + + `RLMResults` cannot be directly instantiated. + */ +@interface RLMResults : NSObject + +#pragma mark - Properties + +/** + The number of objects in the results collection. + */ +@property (nonatomic, readonly, assign) NSUInteger count; + +/** + The type of the objects in the results collection. + */ +@property (nonatomic, readonly, assign) RLMPropertyType type; + +/** + Indicates whether the objects in the collection can be `nil`. + */ +@property (nonatomic, readwrite, getter = isOptional) BOOL optional; + +/** + The class name of the objects contained in the results collection. + + Will be `nil` if `type` is not RLMPropertyTypeObject. + */ +@property (nonatomic, readonly, copy, nullable) NSString *objectClassName; + +/** + The Realm which manages this results collection. + */ +@property (nonatomic, readonly) RLMRealm *realm; + +/** + Indicates if the results collection is no longer valid. + + The results collection becomes invalid if `invalidate` is called on the containing `realm`. + An invalidated results collection can be accessed, but will always be empty. + */ +@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; + +#pragma mark - Accessing Objects from an RLMResults + +/** + Returns the object at the index specified. + + @param index The index to look up. + + @return An object of the type contained in the results collection. + */ +- (RLMObjectType)objectAtIndex:(NSUInteger)index; + +/** + Returns the first object in the results collection. + + Returns `nil` if called on an empty results collection. + + @return An object of the type contained in the results collection. + */ +- (nullable RLMObjectType)firstObject; + +/** + Returns the last object in the results collection. + + Returns `nil` if called on an empty results collection. + + @return An object of the type contained in the results collection. + */ +- (nullable RLMObjectType)lastObject; + +#pragma mark - Querying Results + +/** + Returns the index of an object in the results collection. + + Returns `NSNotFound` if the object is not found in the results collection. + + @param object An object (of the same type as returned from the `objectClassName` selector). + */ +- (NSUInteger)indexOfObject:(RLMObjectType)object; + +/** + Returns the index of the first object in the results collection matching the predicate. + + @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. + + @return The index of the object, or `NSNotFound` if the object is not found in the results collection. + */ +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Returns the index of the first object in the results collection matching the predicate. + + @param predicate The predicate with which to filter the objects. + + @return The index of the object, or `NSNotFound` if the object is not found in the results collection. + */ +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate; + +/** + Returns all the objects matching the given predicate in the results collection. + + @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. + + @return An `RLMResults` of objects that match the given predicate. + */ +- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Returns all the objects matching the given predicate in the results collection. + + @param predicate The predicate with which to filter the objects. + + @return An `RLMResults` of objects that match the given predicate. + */ +- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate; + +/** + Returns a sorted `RLMResults` from an existing results collection. + + @param keyPath The key path to sort by. + @param ascending The direction to sort in. + + @return An `RLMResults` sorted by the specified key path. + */ +- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending; + +/** + Returns a sorted `RLMResults` from an existing results collection. + + @param properties An array of `RLMSortDescriptor`s to sort by. + + @return An `RLMResults` sorted by the specified properties. + */ +- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties; + +/** + Returns a distinct `RLMResults` from an existing results collection. + + @param keyPaths The key paths used produce distinct results + + @return An `RLMResults` made distinct based on the specified key paths + */ +- (RLMResults *)distinctResultsUsingKeyPaths:(NSArray *)keyPaths; + +#pragma mark - Notifications + +/** + Registers a block to be called each time the results collection changes. + + The block will be asynchronously called with the initial results collection, + and then called again after each write transaction which changes either any + of the objects in the results, or which objects are in the results. + + The `change` parameter will be `nil` the first time the block is called. + For each call after that, it will contain information about + which rows in the results collection were added, removed or modified. If a + write transaction did not modify any objects in the results collection, + the block is not called at all. See the `RLMCollectionChange` documentation for + information on how the changes are reported and an example of updating a + `UITableView`. + + If an error occurs the block will be called with `nil` for the results + parameter and a non-`nil` error. Currently the only errors that can occur are + when opening the Realm on the background worker thread. + + At the time when the block is called, the `RLMResults` object will be fully + evaluated and up-to-date, and as long as you do not perform a write transaction + on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will + never perform blocking work. + + Notifications are delivered via the standard run loop, and so can't be + delivered while the run loop is blocked by other activity. When + notifications can't be delivered instantly, multiple notifications may be + coalesced into a single notification. This can include the notification + with the initial results. For example, the following code performs a write + transaction immediately after adding the notification block, so there is no + opportunity for the initial notification to be delivered first. As a + result, the initial notification will reflect the state of the Realm after + the write transaction. + + RLMResults *results = [Dog allObjects]; + NSLog(@"dogs.count: %zu", dogs.count); // => 0 + self.token = [results addNotificationBlock:^(RLMResults *dogs, + RLMCollectionChange *changes, + NSError *error) { + // Only fired once for the example + NSLog(@"dogs.count: %zu", dogs.count); // => 1 + }]; + [realm transactionWithBlock:^{ + Dog *dog = [[Dog alloc] init]; + dog.name = @"Rex"; + [realm addObject:dog]; + }]; + // end of run loop execution context + + You must retain the returned token for as long as you want updates to continue + to be sent to the block. To stop receiving updates, call `-invalidate` on the token. + + @warning This method cannot be called during a write transaction, or when the + containing Realm is read-only. + + @param block The block to be called whenever a change occurs. + @return A token which must be held for as long as you want updates to be delivered. + */ +- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults *__nullable results, + RLMCollectionChange *__nullable change, + NSError *__nullable error))block __attribute__((warn_unused_result)); + +#pragma mark - Aggregating Property Values + +/** + Returns the minimum (lowest) value of the given property among all the objects + represented by the results collection. + + NSNumber *min = [results minOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose minimum value is desired. Only properties of types `int`, `float`, `double`, and + `NSDate` are supported. + + @return The minimum value of the property, or `nil` if the Results are empty. + */ +- (nullable id)minOfProperty:(NSString *)property; + +/** + Returns the maximum (highest) value of the given property among all the objects represented by the results collection. + + NSNumber *max = [results maxOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose maximum value is desired. Only properties of + types `int`, `float`, `double`, and `NSDate` are supported. + + @return The maximum value of the property, or `nil` if the Results are empty. + */ +- (nullable id)maxOfProperty:(NSString *)property; + +/** + Returns the sum of the values of a given property over all the objects represented by the results collection. + + NSNumber *sum = [results sumOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose values should be summed. Only properties of + types `int`, `float`, and `double` are supported. + + @return The sum of the given property. + */ +- (NSNumber *)sumOfProperty:(NSString *)property; + +/** + Returns the average value of a given property over the objects represented by the results collection. + + NSNumber *average = [results averageOfProperty:@"age"]; + + @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. + + @param property The property whose average value should be calculated. Only + properties of types `int`, `float`, and `double` are supported. + + @return The average value of the given property, or `nil` if the Results are empty. + */ +- (nullable NSNumber *)averageOfProperty:(NSString *)property; + +/// :nodoc: +- (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index; + +#pragma mark - Unavailable Methods + +/** + `-[RLMResults init]` is not available because `RLMResults` cannot be created directly. + `RLMResults` can be obtained by querying a Realm. + */ +- (instancetype)init __attribute__((unavailable("RLMResults cannot be created directly"))); + +/** + `+[RLMResults new]` is not available because `RLMResults` cannot be created directly. + `RLMResults` can be obtained by querying a Realm. + */ ++ (instancetype)new __attribute__((unavailable("RLMResults cannot be created directly"))); + +@end + +/** + `RLMLinkingObjects` is an auto-updating container type. It represents a collection of objects that link to its + parent object. + + For more information, please see the "Inverse Relationships" section in the + [documentation](https://realm.io/docs/objc/latest/#relationships). + */ +@interface RLMLinkingObjects : RLMResults +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMResults_Private.h b/Pods/Realm/include/RLMResults_Private.h new file mode 100644 index 0000000000..f74b4fdad3 --- /dev/null +++ b/Pods/Realm/include/RLMResults_Private.h @@ -0,0 +1,32 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMObjectSchema; + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMResults () +@property (nonatomic, readonly, getter=isAttached) BOOL attached; + ++ (instancetype)emptyDetachedResults; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMResults_Private.hpp b/Pods/Realm/include/RLMResults_Private.hpp new file mode 100644 index 0000000000..a4f5abfed0 --- /dev/null +++ b/Pods/Realm/include/RLMResults_Private.hpp @@ -0,0 +1,63 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMResults_Private.h" + +#import "results.hpp" + +class RLMClassInfo; + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMResults () { +@protected + realm::Results _results; +} + +/** + Initialize a 'raw' `RLMResults` using only an object store level Results. + This is only meant for applications where a results collection is being backed + by an object store object class that has no binding-level equivalent. The + consumer is responsible for bridging between the underlying objects and whatever + binding-level class is being vended out. + */ +- (instancetype)initWithResults:(realm::Results)results; + ++ (instancetype)resultsWithObjectInfo:(RLMClassInfo&)info results:(realm::Results)results; +@end + +NS_ASSUME_NONNULL_END + +// Utility functions + +[[gnu::noinline]] +[[noreturn]] +void RLMThrowResultsError(NSString * _Nullable aggregateMethod); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnullability-completeness" +template +static auto translateRLMResultsErrors(Function&& f, NSString *aggregateMethod=nil) { + try { + return f(); + } + catch (...) { + RLMThrowResultsError(aggregateMethod); + } +} +#pragma clang diagnostic pop diff --git a/Pods/Realm/include/RLMSchema.h b/Pods/Realm/include/RLMSchema.h new file mode 100644 index 0000000000..30325e449d --- /dev/null +++ b/Pods/Realm/include/RLMSchema.h @@ -0,0 +1,77 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMObjectSchema; + +/** + `RLMSchema` instances represent collections of model object schemas managed by a Realm. + + When using Realm, `RLMSchema` instances allow performing migrations and + introspecting the database's schema. + + Schemas map to collections of tables in the core database. + */ +@interface RLMSchema : NSObject + +#pragma mark - Properties + +/** + An `NSArray` containing `RLMObjectSchema`s for all object types in the Realm. + + This property is intended to be used during migrations for dynamic introspection. + + @see `RLMObjectSchema` + */ +@property (nonatomic, readonly, copy) NSArray *objectSchema; + +#pragma mark - Methods + +/** + Returns an `RLMObjectSchema` for the given class name in the schema. + + @param className The object class name. + @return An `RLMObjectSchema` for the given class in the schema. + + @see `RLMObjectSchema` + */ +- (nullable RLMObjectSchema *)schemaForClassName:(NSString *)className; + +/** + Looks up and returns an `RLMObjectSchema` for the given class name in the Realm. + + If there is no object of type `className` in the schema, an exception will be thrown. + + @param className The object class name. + @return An `RLMObjectSchema` for the given class in this Realm. + + @see `RLMObjectSchema` + */ +- (RLMObjectSchema *)objectForKeyedSubscript:(NSString *)className; + +/** + Returns whether two `RLMSchema` instances are equivalent. + */ +- (BOOL)isEqualToSchema:(RLMSchema *)schema; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSchema_Private.h b/Pods/Realm/include/RLMSchema_Private.h new file mode 100644 index 0000000000..7ef4917958 --- /dev/null +++ b/Pods/Realm/include/RLMSchema_Private.h @@ -0,0 +1,58 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class RLMRealm; + +// +// RLMSchema private interface +// +@interface RLMSchema () + +/** + Returns an `RLMSchema` containing only the given `RLMObject` subclasses. + + @param classes The classes to be included in the schema. + + @return An `RLMSchema` containing only the given classes. + */ ++ (instancetype)schemaWithObjectClasses:(NSArray *)classes; + +@property (nonatomic, readwrite, copy) NSArray *objectSchema; + +// schema based on runtime objects ++ (instancetype)sharedSchema; + +// schema based upon all currently registered object classes ++ (instancetype)partialSharedSchema; + +// private schema based upon all currently registered object classes. +// includes classes that are excluded from the default schema. ++ (instancetype)partialPrivateSharedSchema; + +// class for string ++ (nullable Class)classForString:(NSString *)className; + ++ (nullable RLMObjectSchema *)sharedSchemaForClass:(Class)cls; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSchema_Private.hpp b/Pods/Realm/include/RLMSchema_Private.hpp new file mode 100644 index 0000000000..197ddeee2e --- /dev/null +++ b/Pods/Realm/include/RLMSchema_Private.hpp @@ -0,0 +1,31 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSchema_Private.h" + +#import + +namespace realm { + class Schema; + class ObjectSchema; +} + +@interface RLMSchema () ++ (instancetype)dynamicSchemaFromObjectStoreSchema:(realm::Schema const&)objectStoreSchema; +- (realm::Schema)objectStoreCopy; +@end diff --git a/Pods/Realm/include/RLMSwiftBridgingHeader.h b/Pods/Realm/include/RLMSwiftBridgingHeader.h new file mode 100644 index 0000000000..4758043796 --- /dev/null +++ b/Pods/Realm/include/RLMSwiftBridgingHeader.h @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +@interface RLMRealm (Swift) ++ (void)resetRealmState; +@end + +@interface RLMArray (Swift) + +- (instancetype)initWithObjectClassName:(NSString *)objectClassName; + +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; +- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + +@end + +@interface RLMResults (Swift) + +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; +- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + +@end + +@interface RLMObjectBase (Swift) + +- (instancetype)initWithRealm:(RLMRealm *)realm schema:(RLMObjectSchema *)schema defaultValues:(BOOL)useDefaults; + ++ (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; ++ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat args:(va_list)args; + +@end diff --git a/Pods/Realm/include/RLMSwiftSupport.h b/Pods/Realm/include/RLMSwiftSupport.h new file mode 100644 index 0000000000..6e45b65406 --- /dev/null +++ b/Pods/Realm/include/RLMSwiftSupport.h @@ -0,0 +1,30 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMSwiftSupport : NSObject + ++ (BOOL)isSwiftClassName:(NSString *)className; ++ (NSString *)demangleClassName:(NSString *)className; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncConfiguration.h b/Pods/Realm/include/RLMSyncConfiguration.h new file mode 100644 index 0000000000..7aaca81a58 --- /dev/null +++ b/Pods/Realm/include/RLMSyncConfiguration.h @@ -0,0 +1,127 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMRealmConfiguration; +@class RLMSyncUser; + +NS_ASSUME_NONNULL_BEGIN + +/** + A configuration object representing configuration state for a Realm which is intended to sync with a Realm Object + Server. + */ +@interface RLMSyncConfiguration : NSObject + +/// The user to which the remote Realm belongs. +@property (nonatomic, readonly) RLMSyncUser *user; + +/** + The URL of the remote Realm upon the Realm Object Server. + + @warning The URL cannot end with `.realm`, `.realm.lock` or `.realm.management`. + */ +@property (nonatomic, readonly) NSURL *realmURL; + +/** + A local path to a file containing the trust anchors for SSL connections. + + Only the certificates stored in the PEM file (or any certificates signed by it, + if the file contains a CA cert) will be accepted when initiating a connection + to a server. This prevents certain certain kinds of man-in-the-middle (MITM) + attacks, and can also be used to trust a self-signed certificate which would + otherwise be untrusted. + + On macOS, the file may be in any of the formats supported by SecItemImport(), + including PEM and .cer (see SecExternalFormat for a complete list of possible + formats). On iOS and other platforms, only DER .cer files are supported. + */ +@property (nonatomic, nullable) NSURL *pinnedCertificateURL; + +/** + Whether SSL certificate validation is enabled for the connection associated + with this configuration value. SSL certificate validation is ON by default. + + @warning NEVER disable certificate validation for clients and servers in production. + */ +@property (nonatomic) BOOL enableSSLValidation; + +/** + Whether this Realm should be opened in 'partial synchronization' mode. + Partial synchronization mode means that no objects are synchronized from the remote Realm + except those matching queries that the user explicitly specifies. + + @warning Partial synchronization is a tech preview. Its APIs are subject to change. + */ +@property (nonatomic) BOOL isPartial DEPRECATED_MSG_ATTRIBUTE("Use 'fullSynchronization' instead."); + +/** + Whether this Realm should be a fully synchronized Realm. + + Synchronized Realms comes in two flavors: Query-based and Fully synchronized. + A fully synchronized Realm will automatically synchronize the entire Realm in + the background while a query-based Realm will only synchronize the data being + subscribed to. Synchronized realms are by default query-based unless this + boolean is set. + */ +@property (nonatomic) BOOL fullSynchronization; + +/** + The prefix that is prepended to the path in the HTTP request that initiates a + sync connection. The value specified must match with the server's expectation. + Changing the value of `urlPrefix` should be matched with a corresponding + change of the server's configuration. + If no value is specified here then the default `/realm-sync` path is used. +*/ +@property (nonatomic, nullable, copy) NSString *urlPrefix; + +/** + Create a sync configuration instance. + + @param user A `RLMSyncUser` that owns the Realm at the given URL. + @param url The unresolved absolute URL to the Realm on the Realm Object Server, e.g. + `realm://example.org/~/path/to/realm`. "Unresolved" means the path should + contain the wildcard marker `~`, which will automatically be filled in with + the user identity by the Realm Object Server. + */ +- (instancetype)initWithUser:(RLMSyncUser *)user realmURL:(NSURL *)url __attribute__((deprecated("Use [RLMSyncUser configurationWithURL] instead"))); + +/** +Return a Realm configuration for syncing with the default Realm of the currently logged-in sync user. + +Partial synchronization is enabled in the returned configuration. + */ ++ (RLMRealmConfiguration *)automaticConfiguration __attribute__((deprecated("Use [RLMSyncUser configuration] instead"))); + +/** + Return a Realm configuration for syncing with the default Realm of the given sync user. + + Partial synchronization is enabled in the returned configuration. + */ ++ (RLMRealmConfiguration *)automaticConfigurationForUser:(RLMSyncUser *)user __attribute__((deprecated("Use [RLMSyncUser configuration] instead"))); + +/// :nodoc: +- (instancetype)init __attribute__((unavailable("This type cannot be created directly"))); + +/// :nodoc: ++ (instancetype)new __attribute__((unavailable("This type cannot be created directly"))); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncConfiguration_Private.h b/Pods/Realm/include/RLMSyncConfiguration_Private.h new file mode 100644 index 0000000000..b3c4a7e4d7 --- /dev/null +++ b/Pods/Realm/include/RLMSyncConfiguration_Private.h @@ -0,0 +1,46 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSUInteger, RLMSyncStopPolicy) { + RLMSyncStopPolicyImmediately, + RLMSyncStopPolicyLiveIndefinitely, + RLMSyncStopPolicyAfterChangesUploaded, +}; + +@interface RLMSyncConfiguration () + +- (instancetype)initWithUser:(RLMSyncUser *)user + realmURL:(NSURL *)url + isPartial:(BOOL)isPartial + urlPrefix:(nullable NSString *)urlPrefix + stopPolicy:(RLMSyncStopPolicy)stopPolicy + enableSSLValidation:(BOOL)enableSSLValidation + certificatePath:(nullable NSURL *)certificatePath; + +@property (nonatomic, readwrite) RLMSyncStopPolicy stopPolicy; + +// Internal-only APIs +@property (nullable, nonatomic) NSURL *customFileURL; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncConfiguration_Private.hpp b/Pods/Realm/include/RLMSyncConfiguration_Private.hpp new file mode 100644 index 0000000000..e80095ef46 --- /dev/null +++ b/Pods/Realm/include/RLMSyncConfiguration_Private.hpp @@ -0,0 +1,48 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncConfiguration_Private.h" + +#import +#import + +namespace realm { +class SyncSession; +struct SyncConfig; +struct SyncError; +using SyncSessionErrorHandler = void(std::shared_ptr, SyncError); +} + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMSyncConfiguration () + +- (instancetype)initWithUser:(RLMSyncUser *)user + realmURL:(NSURL *)url + customFileURL:(nullable NSURL *)customFileURL + isPartial:(BOOL)isPartial + stopPolicy:(RLMSyncStopPolicy)stopPolicy + errorHandler:(std::function)errorHandler; + +- (instancetype)initWithRawConfig:(realm::SyncConfig)config; + +- (realm::SyncConfig)rawConfiguration; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncCredentials.h b/Pods/Realm/include/RLMSyncCredentials.h new file mode 100644 index 0000000000..c90fb4c946 --- /dev/null +++ b/Pods/Realm/include/RLMSyncCredentials.h @@ -0,0 +1,140 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMSyncUtil.h" + +NS_ASSUME_NONNULL_BEGIN + +/// A token representing an identity provider's credentials. +typedef NSString *RLMSyncCredentialsToken; + +/// A type representing the unique identifier of a Realm Object Server identity provider. +typedef NSString *RLMIdentityProvider RLM_EXTENSIBLE_STRING_ENUM; + +/// The debug identity provider, which accepts any token string and creates a user associated with that token if one +/// does not yet exist. Not enabled for Realm Object Server configured for production. +extern RLMIdentityProvider const RLMIdentityProviderDebug; + +/// The username/password identity provider. User accounts are handled by the Realm Object Server directly without the +/// involvement of a third-party identity provider. +extern RLMIdentityProvider const RLMIdentityProviderUsernamePassword; + +/// A Facebook account as an identity provider. +extern RLMIdentityProvider const RLMIdentityProviderFacebook; + +/// A Google account as an identity provider. +extern RLMIdentityProvider const RLMIdentityProviderGoogle; + +/// A CloudKit account as an identity provider. +extern RLMIdentityProvider const RLMIdentityProviderCloudKit; + +/// A JSON Web Token as an identity provider. +extern RLMIdentityProvider const RLMIdentityProviderJWT; + +/// An Anonymous account as an identity provider. +extern RLMIdentityProvider const RLMIdentityProviderAnonymous; + +/// A Nickname account as an identity provider. +extern RLMIdentityProvider const RLMIdentityProviderNickname; + +/** + Opaque credentials representing a specific Realm Object Server user. + */ +@interface RLMSyncCredentials : NSObject + +/// An opaque credentials token containing information that uniquely identifies a Realm Object Server user. +@property (nonatomic, readonly) RLMSyncCredentialsToken token; + +/// The name of the identity provider which generated the credentials token. +@property (nonatomic, readonly) RLMIdentityProvider provider; + +/// A dictionary containing additional pertinent information. In most cases this is automatically configured. +@property (nonatomic, readonly) NSDictionary *userInfo; + +/** + Construct and return credentials from a Facebook account token. + */ ++ (instancetype)credentialsWithFacebookToken:(RLMSyncCredentialsToken)token; + +/** + Construct and return credentials from a Google account token. + */ ++ (instancetype)credentialsWithGoogleToken:(RLMSyncCredentialsToken)token; + +/** + Construct and return credentials from an CloudKit account token. + */ ++ (instancetype)credentialsWithCloudKitToken:(RLMSyncCredentialsToken)token; + +/** + Construct and return credentials from a Realm Object Server username and password. + */ ++ (instancetype)credentialsWithUsername:(NSString *)username + password:(NSString *)password + register:(BOOL)shouldRegister; + +/** + Construct and return credentials from a JSON Web Token. + */ ++ (instancetype)credentialsWithJWT:(NSString *)token; + +/** + Construct and return anonymous credentials + */ ++ (instancetype)anonymousCredentials; + +/** + Construct and return credentials from a nickname + */ ++ (instancetype)credentialsWithNickname:(NSString *)nickname isAdmin:(BOOL)isAdmin; + +/** + Construct and return special credentials representing a token that can + be directly used to open a Realm. The identity is used to uniquely identify + the user across application launches. + + @warning The custom user identity will be deprecated in a future release. + + @warning Do not specify a user identity that is the URL of an authentication + server. + + @warning When passing an access token credential into any of `RLMSyncUser`'s + login methods, you must always specify the same authentication server + URL, or none at all, every time you call the login method. + */ ++ (instancetype)credentialsWithAccessToken:(RLMServerToken)accessToken identity:(NSString *)identity; + +/** + Construct and return credentials with a custom token string, identity provider string, and optional user info. In most + cases, the convenience initializers should be used instead. + */ +- (instancetype)initWithCustomToken:(RLMSyncCredentialsToken)token + provider:(RLMIdentityProvider)provider + userInfo:(nullable NSDictionary *)userInfo NS_DESIGNATED_INITIALIZER; + +/// :nodoc: +- (instancetype)init __attribute__((unavailable("RLMSyncCredentials cannot be created directly"))); + +/// :nodoc: ++ (instancetype)new __attribute__((unavailable("RLMSyncCredentials cannot be created directly"))); + +NS_ASSUME_NONNULL_END + +@end diff --git a/Pods/Realm/include/RLMSyncManager.h b/Pods/Realm/include/RLMSyncManager.h new file mode 100644 index 0000000000..4d45a26bfb --- /dev/null +++ b/Pods/Realm/include/RLMSyncManager.h @@ -0,0 +1,142 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMSyncUtil.h" + +@class RLMSyncSession; + +/// An enum representing different levels of sync-related logging that can be configured. +typedef NS_ENUM(NSUInteger, RLMSyncLogLevel) { + /// Nothing will ever be logged. + RLMSyncLogLevelOff, + /// Only fatal errors will be logged. + RLMSyncLogLevelFatal, + /// Only errors will be logged. + RLMSyncLogLevelError, + /// Warnings and errors will be logged. + RLMSyncLogLevelWarn, + /// Information about sync events will be logged. Fewer events will be logged in order to avoid overhead. + RLMSyncLogLevelInfo, + /// Information about sync events will be logged. More events will be logged than with `RLMSyncLogLevelInfo`. + RLMSyncLogLevelDetail, + /// Log information that can aid in debugging. + /// + /// - warning: Will incur a measurable performance impact. + RLMSyncLogLevelDebug, + /// Log information that can aid in debugging. More events will be logged than with `RLMSyncLogLevelDebug`. + /// + /// - warning: Will incur a measurable performance impact. + RLMSyncLogLevelTrace, + /// Log information that can aid in debugging. More events will be logged than with `RLMSyncLogLevelTrace`. + /// + /// - warning: Will incur a measurable performance impact. + RLMSyncLogLevelAll +}; + +NS_ASSUME_NONNULL_BEGIN + +/// A block type representing a block which can be used to report a sync-related error to the application. If the error +/// pertains to a specific session, that session will also be passed into the block. +typedef void(^RLMSyncErrorReportingBlock)(NSError *, RLMSyncSession * _Nullable); + +/** + A singleton manager which serves as a central point for sync-related configuration. + */ +@interface RLMSyncManager : NSObject + +/** + A block which can optionally be set to report sync-related errors to your application. + + Any error reported through this block will be of the `RLMSyncError` type, and marked + with the `RLMSyncErrorDomain` domain. + + Errors reported through this mechanism are fatal, with several exceptions. Please consult + `RLMSyncError` for information about the types of errors that can be reported through + the block, and for for suggestions on handling recoverable error codes. + + @see `RLMSyncError` + */ +@property (nullable, nonatomic, copy) RLMSyncErrorReportingBlock errorHandler; + +/** + A reverse-DNS string uniquely identifying this application. In most cases this is automatically set by the SDK, and + does not have to be explicitly configured. + */ +@property (nonatomic, copy) NSString *appID; + +/** + The logging threshold which newly opened synced Realms will use. Defaults to + `RLMSyncLogLevelInfo`. + + Logging strings are output to Apple System Logger. + + @warning This property must be set before any synced Realms are opened. Setting it after + opening any synced Realm will do nothing. + */ +@property (nonatomic) RLMSyncLogLevel logLevel; + +/** + The name of the HTTP header to send authorization data in when making requests to a Realm Object Server which has + been configured to expect a custom authorization header. + */ +@property (nullable, nonatomic, copy) NSString *authorizationHeaderName; + +/** + Extra HTTP headers to append to every request to a Realm Object Server. + */ +@property (nullable, nonatomic, copy) NSDictionary *customRequestHeaders; + +/** + A map of hostname to file URL for pinned certificates to use for HTTPS requests. + + When initiating a HTTPS connection to a server, if this dictionary contains an + entry for the server's hostname, only the certificates stored in the file (or + any certificates signed by it, if the file contains a CA cert) will be accepted + when initiating a connection to a server. This prevents certain certain kinds + of man-in-the-middle (MITM) attacks, and can also be used to trust a self-signed + certificate which would otherwise be untrusted. + + On macOS, the certificate files may be in any of the formats supported by + SecItemImport(), including PEM and .cer (see SecExternalFormat for a complete + list of possible formats). On iOS and other platforms, only DER .cer files are + supported. + + For example, to pin example.com to a .cer file included in your bundle: + +
+ RLMSyncManager.sharedManager.pinnedCertificatePaths = @{
+    @"example.com": [NSBundle.mainBundle pathForResource:@"example.com" ofType:@"cer"]
+ };
+ 
+ */ +@property (nullable, nonatomic, copy) NSDictionary *pinnedCertificatePaths; + +/// The sole instance of the singleton. ++ (instancetype)sharedManager NS_REFINED_FOR_SWIFT; + +/// :nodoc: +- (instancetype)init __attribute__((unavailable("RLMSyncManager cannot be created directly"))); + +/// :nodoc: ++ (instancetype)new __attribute__((unavailable("RLMSyncManager cannot be created directly"))); + +NS_ASSUME_NONNULL_END + +@end diff --git a/Pods/Realm/include/RLMSyncManager_Private.h b/Pods/Realm/include/RLMSyncManager_Private.h new file mode 100644 index 0000000000..7cb660b06c --- /dev/null +++ b/Pods/Realm/include/RLMSyncManager_Private.h @@ -0,0 +1,52 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMSyncUtil_Private.h" +#import "RLMNetworkClient.h" + +@class RLMSyncUser, RLMSyncConfiguration; + +// All private API methods are threadsafe and synchronized, unless denoted otherwise. Since they are expected to be +// called very infrequently, this should pose no issues. + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMSyncManager () + +@property (nullable, nonatomic, copy) RLMSyncBasicErrorReportingBlock sessionCompletionNotifier; + +- (void)_fireError:(NSError *)error; + +- (void)_fireErrorWithCode:(int)errorCode + message:(NSString *)message + isFatal:(BOOL)fatal + session:(RLMSyncSession *)session + userInfo:(NSDictionary *)userInfo + errorClass:(RLMSyncSystemErrorKind)errorClass; + +- (NSArray *)_allUsers; + ++ (void)resetForTesting; + +- (RLMNetworkRequestOptions *)networkRequestOptions; + +NS_ASSUME_NONNULL_END + +@end diff --git a/Pods/Realm/include/RLMSyncPermission.h b/Pods/Realm/include/RLMSyncPermission.h new file mode 100644 index 0000000000..c0677a0d12 --- /dev/null +++ b/Pods/Realm/include/RLMSyncPermission.h @@ -0,0 +1,501 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@protocol RLMPermission, RLMPermissionUser; +@class RLMPermission, RLMPermissionUser, RLMPermissionRole, + RLMArray, RLMLinkingObjects; + +NS_ASSUME_NONNULL_BEGIN + +/** + A permission which can be applied to a Realm, Class, or specific Object. + + Permissions are applied by adding the permission to the RLMRealmPermission singleton + object, the RLMClassPermission object for the desired class, or to a user-defined + RLMArray property on a specific Object instance. The meaning of each of + the properties of RLMPermission depend on what the permission is applied to, and so are + left undocumented here. See `RLMRealmPrivileges`, `RLMClassPrivileges`, and + `RLMObjectPrivileges` for details about what each of the properties mean when applied to + that type. + */ +@interface RLMPermission : RLMObject +/// The Role which this Permission applies to. All users within the Role are +/// granted the permissions specified by the fields below any +/// objects/classes/realms which use this Permission. +/// +/// This property cannot be modified once set. +@property (nonatomic) RLMPermissionRole *role; + +/// Whether the user can read the object to which this Permission is attached. +@property (nonatomic) bool canRead; +/// Whether the user can modify the object to which this Permission is attached. +@property (nonatomic) bool canUpdate; +/// Whether the user can delete the object to which this Permission is attached. +/// +/// This field is only applicable to Permissions attached to Objects, and not +/// to Realms or Classes. +@property (nonatomic) bool canDelete; +/// Whether the user can add or modify Permissions for the object which this +/// Permission is attached to. +@property (nonatomic) bool canSetPermissions; +/// Whether the user can subscribe to queries for this object type. +/// +/// This field is only applicable to Permissions attached to Classes, and not +/// to Realms or Objects. +@property (nonatomic) bool canQuery; +/// Whether the user can create new objects of the type this Permission is attached to. +/// +/// This field is only applicable to Permissions attached to Classes, and not +/// to Realms or Objects. +@property (nonatomic) bool canCreate; +/// Whether the user can modify the schema of the Realm which this +/// Permission is attached to. +/// +/// This field is only applicable to Permissions attached to Realms, and not +/// to Realms or Objects. +@property (nonatomic) bool canModifySchema; + +/** + Returns the Permission object for the named Role in the array, creating it if needed. + + This function should be used in preference to manually querying the array for + the applicable Permission as it ensures that there is exactly one Permission + for the given Role in the array, merging duplicates or creating and adding new + ones as needed. +*/ ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName inArray:(RLMArray *)array; + +/** + Returns the Permission object for the named Role on the Realm, creating it if needed. + + This function should be used in preference to manually querying for the + applicable Permission as it ensures that there is exactly one Permission for + the given Role on the Realm, merging duplicates or creating and adding new ones + as needed. +*/ ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onRealm:(RLMRealm *)realm; + +/** + Returns the Permission object for the named Role on the Class, creating it if needed. + + This function should be used in preference to manually querying for the + applicable Permission as it ensures that there is exactly one Permission for + the given Role on the Class, merging duplicates or creating and adding new ones + as needed. +*/ ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onClass:(Class)cls realm:(RLMRealm *)realm; + +/** + Returns the Permission object for the named Role on the named class, creating it if needed. + + This function should be used in preference to manually querying for the + applicable Permission as it ensures that there is exactly one Permission for + the given Role on the Class, merging duplicates or creating and adding new ones + as needed. +*/ ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onClassNamed:(NSString *)className realm:(RLMRealm *)realm; + +/** + Returns the Permission object for the named Role on the object, creating it if needed. + + This function should be used in preference to manually querying for the + applicable Permission as it ensures that there is exactly one Permission for + the given Role on the Realm, merging duplicates or creating and adding new ones + as needed. + + The given object must have a RLMArray property defined on it. If + more than one such property is present, the first will be used. +*/ ++ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onObject:(RLMObject *)object; +@end + +/** + A Role within the permissions system. + + A Role consists of a name for the role and a list of users which are members of the role. + Roles are granted privileges on Realms, Classes and Objects, and in turn grant those + privileges to all users which are members of the role. + + A role named "everyone" is automatically created in new Realms, and all new users which + connect to the Realm are automatically added to it. Any other roles you wish to use are + managed as normal Realm objects. + */ +@interface RLMPermissionRole : RLMObject +/// The name of the Role +@property (nonatomic) NSString *name; +/// The users which belong to the role +@property (nonatomic) RLMArray *users; +@end + +/** + A representation of a sync user within the permissions system. + + RLMPermissionUser objects are created automatically for each sync user which connects to + a Realm, and can also be created manually if you wish to grant permissions to a user + which has not yet connected to this Realm. + */ +@interface RLMPermissionUser : RLMObject +/// The unique Realm Object Server user ID string identifying this user. This will have +/// the same value as `-[RLMSyncUser identity]`. +@property (nonatomic) NSString *identity; + +/// The user's private role. This will be initialized to a role named for the user's +/// identity that contains this user as its only member. +@property (nonatomic) RLMPermissionRole *role; + +/// Roles which this user belongs to. +@property (nonatomic, readonly) RLMLinkingObjects *roles; + +/// Get the user object in the given Realm, creating it if needed. ++ (RLMPermissionUser *)userInRealm:(RLMRealm *)realm withIdentity:(NSString *)identity; +@end + +/** + A singleton object which describes Realm-wide permissions. + + An object of this type is automatically created in the Realm for you, and more objects + cannot be created manually. Call `+[RLMRealmPermission objectInRealm:]` to obtain the + instance for a specific Realm. + + See `RLMRealmPrivileges` for the meaning of permissions applied to a Realm. + */ +@interface RLMRealmPermission : RLMObject +/// The permissions for the Realm. +@property (nonatomic) RLMArray *permissions; + +/// Retrieve the singleton object for the given Realm. This will return `nil` +/// for non-partial-sync Realms. ++ (nullable instancetype)objectInRealm:(RLMRealm *)realm; +@end + +/** + An object which describes class-wide permissions. + + An instance of this object is automatically created in the Realm for class in your schema, + and should not be created manually. Call `+[RLMClassPermission objectInRealm:forClassNamed:]` + or `+[RLMClassPermission objectInRealm:forClass:]` to obtain the existing instance, or + query `RLMClassPermission` as normal. + */ +@interface RLMClassPermission : RLMObject +/// The name of the class which these permissions apply to. +@property (nonatomic) NSString *name; +/// The permissions for this class. +@property (nonatomic) RLMArray *permissions; + +/// Retrieve the object for the named RLMObject subclass. This will return `nil` +/// for non-partial-sync Realms. ++ (nullable instancetype)objectInRealm:(RLMRealm *)realm forClassNamed:(NSString *)className; +/// Retrieve the object for the given RLMObject subclass. This will return `nil` +/// for non-partial-sync Realms. ++ (nullable instancetype)objectInRealm:(RLMRealm *)realm forClass:(Class)cls; +@end + +/** + A description of the actual privileges which apply to a Realm. + + This is a combination of all of the privileges granted to all of the Roles which the + current User is a member of, obtained by calling `-[RLMRealm privilegesForRealm]` on + the Realm. + + By default, all operations are permitted, and each privilege field indicates an operation + which may be forbidden. + */ +struct RLMRealmPrivileges { + /// If `false`, the current User is not permitted to see the Realm at all. This can + /// happen only if the Realm was created locally and has not yet been synchronized. + bool read : 1; + + /// If `false`, no modifications to the Realm are permitted. Write transactions can + /// be performed locally, but any changes made will be reverted by the server. + /// `setPermissions` and `modifySchema` will always be `false` when this is `false`. + bool update : 1; + + /// If `false`, no modifications to the permissions property of the RLMRealmPermissions + /// object for are permitted. Write transactions can be performed locally, but any + /// changes made will be reverted by the server. + /// + /// Note that if invalide privilege changes are made, `-[RLMRealm privilegesFor*:]` + /// will return results reflecting those invalid changes until synchronization occurs. + /// + /// Even if this field is `true`, note that the user will be unable to grant + /// privileges to a Role which they do not themselves have. + /// + /// Adding or removing Users from a Role is controlled by Update privileges on that + /// Role, and not by this value. + bool setPermissions : 1; + + /// If `false`, the user is not permitted to add new object types to the Realm or add + /// new properties to existing objec types. Defining new RLMObject subclasses (and not + /// excluding them from the schema with `-[RLMRealmConfiguration setObjectClasses:]`) + /// will result in the application crashing if the object types are not first added on + /// the server by a more privileged user. + bool modifySchema : 1; +}; + +/** + A description of the actual privileges which apply to a Class within a Realm. + + This is a combination of all of the privileges granted to all of the Roles which the + current User is a member of, obtained by calling `-[RLMRealm privilegesForClass:]` or + `-[RLMRealm privilegesForClassNamed:]` on the Realm. + + By default, all operations are permitted, and each privilege field indicates an operation + which may be forbidden. + */ +struct RLMClassPrivileges { + /// If `false`, the current User is not permitted to see objects of this type, and + /// attempting to query this class will always return empty results. + /// + /// Note that Read permissions are transitive, and so it may be possible to read an + /// object which the user does not directly have Read permissions for by following a + /// link to it from an object they do have Read permissions for. This does not apply + /// to any of the other permission types. + bool read : 1; + + /// If `false`, creating new objects of this type is not permitted. Write transactions + /// creating objects can be performed locally, but the objects will be deleted by the + /// server when synchronization occurs. + /// + /// For objects with Primary Keys, it may not be locally determinable if Create or + /// Update privileges are applicable. It may appear that you are creating a new object, + /// but an object with that Primary Key may already exist and simply not be visible to + /// you, in which case it is actually an Update operation. + bool create : 1; + + /// If `false`, no modifications to objects of this type are permitted. Write + /// transactions modifying the objects can be performed locally, but any changes made + /// will be reverted by the server. + /// + /// Deleting an object is considered a modification, and is governed by this privilege. + bool update : 1; + + /// If `false`, the User is not permitted to create new subscriptions for this class. + /// Local queries against the objects within the Realm will work, but new + /// subscriptions will never add objects to the Realm. + bool subscribe : 1; + + /// If `false`, no modifications to the permissions property of the RLMClassPermissions + /// object for this type are permitted. Write transactions can be performed locally, + /// but any changes made will be reverted by the server. + /// + /// Note that if invalid privilege changes are made, `-[RLMRealm privilegesFor*:]` + /// will return results reflecting those invalid changes until synchronization occurs. + /// + /// Even if this field is `true`, note that the user will be unable to grant + /// privileges to a Role which they do not themselves have. + bool setPermissions : 1; +}; + +/** + A description of the actual privileges which apply to a specific RLMObject. + + This is a combination of all of the privileges granted to all of the Roles which the + current User is a member of, obtained by calling `-[RLMRealm privilegesForObject:]` on + the Realm. + + By default, all operations are permitted, and each privilege field indicates an operation + which may be forbidden. + */ +struct RLMObjectPrivileges { + /// If `false`, the current User is not permitted to read this object directly. + /// + /// Objects which cannot be read by a user will appear in a Realm due to that read + /// permissions are transitive. All objects which a readable object links to are + /// themselves implicitly readable. If the link to an object with `read=false` is + /// removed, the object will be deleted from the local Realm. + bool read : 1; + + /// If `false`, modifying the fields of this type is not permitted. Write + /// transactions modifying the objects can be performed locally, but any changes made + /// will be reverted by the server. + /// + /// Note that even if this is `true`, the user may not be able to modify the + /// `RLMArray *` property of the object (if it exists), as that is + /// governed by `setPermissions`. + bool update : 1; + + /// If `false`, deleting this object is not permitted. Write transactions which delete + /// the object can be performed locally, but the server will restore it. + /// + /// It is possible to have `update` but not `delete` privileges, or vice versa. For + /// objects with primary keys, `delete` but not `update` is ill-advised, as an object + /// can be updated by deleting and recreating it. + bool del : 1; + + /// If `false`, modifying the privileges of this specific object is not permitted. + /// + /// Object-specific permissions are set by declaring a `RLMArray *` + /// property on the `RLMObject` subclass. Modifications to this property are + /// controlled by `setPermissions` rather than `update`. + /// + /// Even if this field is `true`, note that the user will be unable to grant + /// privileges to a Role which they do not themselves have. + bool setPermissions : 1; +}; + +/// :nodoc: +FOUNDATION_EXTERN id RLMPermissionForRole(RLMArray *array, id role); + +/** + Access levels which can be granted to Realm Mobile Platform users + for specific synchronized Realms, using the permissions APIs. + + Note that each access level guarantees all allowed actions provided + by less permissive access levels. Specifically, users with write + access to a Realm can always read from that Realm, and users with + administrative access can always read or write from the Realm. + */ +typedef NS_ENUM(NSUInteger, RLMSyncAccessLevel) { + /// No access whatsoever. + RLMSyncAccessLevelNone = 0, + /** + User can only read the contents of the Realm. + + @warning Users who have read-only access to a Realm should open the + Realm using `+[RLMRealm asyncOpenWithConfiguration:callbackQueue:callback:]`. + Attempting to directly open the Realm is an error; in this + case the Realm must be deleted and re-opened. + */ + RLMSyncAccessLevelRead = 1, + /// User can read and write the contents of the Realm. + RLMSyncAccessLevelWrite = 2, + /// User can read, write, and administer the Realm, including + /// granting permissions to other users. + RLMSyncAccessLevelAdmin = 3, +}; + +/** + A property on which a `RLMResults` can be queried or filtered. + + @warning If building `NSPredicate`s using format strings including these string + constants, use %K instead of %@ as the substitution parameter. + */ +typedef NSString * RLMSyncPermissionSortProperty NS_STRING_ENUM; + +/// Sort by the Realm Object Server path to the Realm to which the permission applies. +extern RLMSyncPermissionSortProperty const RLMSyncPermissionSortPropertyPath; +/// Sort by the identity of the user to whom the permission applies. +extern RLMSyncPermissionSortProperty const RLMSyncPermissionSortPropertyUserID; +/// Sort by the date the permissions were last updated. +extern RLMSyncPermissionSortProperty const RLMSyncPermissionSortPropertyUpdated; + +/** + A value representing a permission granted to the specified user(s) to access the specified Realm(s). + + `RLMSyncPermission` is immutable and can be accessed from any thread. + + See https://realm.io/docs/realm-object-server/#permissions for general documentation. + */ +@interface RLMSyncPermission : NSObject + +/** + The Realm Object Server path to the Realm to which this permission applies (e.g. "/path/to/realm"). + + Specify "*" if this permission applies to all Realms managed by the server. + */ +@property (nonatomic, readonly) NSString *path; + +/** + The access level described by this permission. + */ +@property (nonatomic, readonly) RLMSyncAccessLevel accessLevel; + +/// Whether the access level allows the user to read from the Realm. +@property (nonatomic, readonly) BOOL mayRead; + +/// Whether the access level allows the user to write to the Realm. +@property (nonatomic, readonly) BOOL mayWrite; + +/// Whether the access level allows the user to administer the Realm. +@property (nonatomic, readonly) BOOL mayManage; + +/** + Create a new sync permission value, for use with permission APIs. + + @param path The Realm Object Server path to the Realm whose permission should be modified + (e.g. "/path/to/realm"). Pass "*" to apply to all Realms managed by the user. + @param identity The Realm Object Server identity of the user who should be granted access to + the Realm at `path`. + Pass "*" to apply to all users managed by the server. + @param accessLevel The access level to grant. + */ +- (instancetype)initWithRealmPath:(NSString *)path + identity:(NSString *)identity + accessLevel:(RLMSyncAccessLevel)accessLevel; + +/** + Create a new sync permission value, for use with permission APIs. + + @param path The Realm Object Server path to the Realm whose permission should be modified + (e.g. "/path/to/realm"). Pass "*" to apply to all Realms managed by the user. + @param username The username (often an email address) of the user who should be granted access + to the Realm at `path`. + @param accessLevel The access level to grant. + */ +- (instancetype)initWithRealmPath:(NSString *)path + username:(NSString *)username + accessLevel:(RLMSyncAccessLevel)accessLevel; + +/** + The identity of the user to whom this permission is granted, or "*" + if all users are granted this permission. Nil if the permission is + defined in terms of a key-value pair. + */ +@property (nullable, nonatomic, readonly) NSString *identity; + +/** + If the permission is defined in terms of a key-value pair, the key + describing the type of criterion used to determine what users the + permission applies to. Otherwise, nil. + */ +@property (nullable, nonatomic, readonly) NSString *key; + +/** + If the permission is defined in terms of a key-value pair, a string + describing the criterion value used to determine what users the + permission applies to. Otherwise, nil. + */ +@property (nullable, nonatomic, readonly) NSString *value; + +/** + When this permission was last updated. + */ +@property (nonatomic, readonly) NSDate *updatedAt; + +/// :nodoc: +- (instancetype)init __attribute__((unavailable("Use the designated initializer"))); + +/// :nodoc: ++ (instancetype)new __attribute__((unavailable("Use the designated initializer"))); + +// MARK: - Migration assistance + +/// :nodoc: +@property (nullable, nonatomic, readonly) NSString *userId __attribute__((unavailable("Renamed to `identity`"))); + +/// :nodoc: +- (instancetype)initWithRealmPath:(NSString *)path + userID:(NSString *)identity + accessLevel:(RLMSyncAccessLevel)accessLevel +__attribute__((unavailable("Renamed to `-initWithRealmPath:identity:accessLevel:`"))); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncPermissionResults.h b/Pods/Realm/include/RLMSyncPermissionResults.h new file mode 100644 index 0000000000..461da2b36a --- /dev/null +++ b/Pods/Realm/include/RLMSyncPermissionResults.h @@ -0,0 +1,27 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMResults.h" + +@class RLMSyncPermission; + +// A private subclass of `RLMResults`. +@interface RLMSyncPermissionResults : RLMResults +@end diff --git a/Pods/Realm/include/RLMSyncPermission_Private.hpp b/Pods/Realm/include/RLMSyncPermission_Private.hpp new file mode 100644 index 0000000000..9d01adcc53 --- /dev/null +++ b/Pods/Realm/include/RLMSyncPermission_Private.hpp @@ -0,0 +1,29 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncPermission.h" + +#import "sync/sync_permission.hpp" + +@interface RLMSyncPermission () + +- (instancetype)initWithPermission:(realm::Permission)permission; + +- (realm::Permission)rawPermission; + +@end diff --git a/Pods/Realm/include/RLMSyncSession.h b/Pods/Realm/include/RLMSyncSession.h new file mode 100644 index 0000000000..0d809a44a5 --- /dev/null +++ b/Pods/Realm/include/RLMSyncSession.h @@ -0,0 +1,236 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMRealm.h" + +/** + The current state of the session represented by a session object. + */ +typedef NS_ENUM(NSUInteger, RLMSyncSessionState) { + /// The sync session is actively communicating or attempting to communicate + /// with the Realm Object Server. A session is considered Active even if + /// it is not currently connected. Check the connection state instead if you + /// wish to know if the connection is currently online. + RLMSyncSessionStateActive, + /// The sync session is not attempting to communicate with the Realm Object + /// Server, due to the user logging out or synchronization being paused. + RLMSyncSessionStateInactive, + /// The sync session encountered a fatal error and is permanently invalid; it should be discarded. + RLMSyncSessionStateInvalid +}; + +/** + The current state of a sync session's connection. Sessions which are not in + the Active state will always be Disconnected. + */ +typedef NS_ENUM(NSUInteger, RLMSyncConnectionState) { + /// The sync session is not connected to the server, and is not attempting + /// to connect, either because the session is inactive or because it is + /// waiting to retry after a failed connection. + RLMSyncConnectionStateDisconnected, + /// The sync session is attempting to connect to the Realm Object Server. + RLMSyncConnectionStateConnecting, + /// The sync session is currently connected to the Realm Object Server. + RLMSyncConnectionStateConnected, +}; + +/** + The transfer direction (upload or download) tracked by a given progress notification block. + + Progress notification blocks can be registered on sessions if your app wishes to be informed + how many bytes have been uploaded or downloaded, for example to show progress indicator UIs. + */ +typedef NS_ENUM(NSUInteger, RLMSyncProgressDirection) { + /// For monitoring upload progress. + RLMSyncProgressDirectionUpload, + /// For monitoring download progress. + RLMSyncProgressDirectionDownload, +}; + +/** + The desired behavior of a progress notification block. + + Progress notification blocks can be registered on sessions if your app wishes to be informed + how many bytes have been uploaded or downloaded, for example to show progress indicator UIs. + */ +typedef NS_ENUM(NSUInteger, RLMSyncProgressMode) { + /** + The block will be called indefinitely, or until it is unregistered by calling + `-[RLMProgressNotificationToken invalidate]`. + + Notifications will always report the latest number of transferred bytes, and the + most up-to-date number of total transferrable bytes. + */ + RLMSyncProgressModeReportIndefinitely, + /** + The block will, upon registration, store the total number of bytes + to be transferred. When invoked, it will always report the most up-to-date number + of transferrable bytes out of that original number of transferrable bytes. + + When the number of transferred bytes reaches or exceeds the + number of transferrable bytes, the block will be unregistered. + */ + RLMSyncProgressModeForCurrentlyOutstandingWork, +}; + +@class RLMSyncUser, RLMSyncConfiguration, RLMSyncErrorActionToken; + +/** + The type of a progress notification block intended for reporting a session's network + activity to the user. + + `transferredBytes` refers to the number of bytes that have been uploaded or downloaded. + `transferrableBytes` refers to the total number of bytes transferred, and pending transfer. + */ +typedef void(^RLMProgressNotificationBlock)(NSUInteger transferredBytes, NSUInteger transferrableBytes); + +NS_ASSUME_NONNULL_BEGIN + +/** + A token object corresponding to a progress notification block on a session object. + + To stop notifications manually, call `-invalidate` on it. Notifications should be stopped before + the token goes out of scope or is destroyed. + */ +@interface RLMProgressNotificationToken : RLMNotificationToken +@end + +/** + An object encapsulating a Realm Object Server "session". Sessions represent the + communication between the client (and a local Realm file on disk), and the server + (and a remote Realm at a given URL stored on a Realm Object Server). + + Sessions are always created by the SDK and vended out through various APIs. The + lifespans of sessions associated with Realms are managed automatically. Session + objects can be accessed from any thread. + */ +@interface RLMSyncSession : NSObject + +/// The session's current state. +/// +/// This property is not KVO-compliant. +@property (nonatomic, readonly) RLMSyncSessionState state; + +/// The session's current connection state. +/// +/// This property is KVO-compliant and can be observed to be notified of changes. +/// Be warned that KVO observers for this property may be called on a background +/// thread. +@property (atomic, readonly) RLMSyncConnectionState connectionState; + +/// The Realm Object Server URL of the remote Realm this session corresponds to. +@property (nullable, nonatomic, readonly) NSURL *realmURL; + +/// The user that owns this session. +- (nullable RLMSyncUser *)parentUser; + +/** + If the session is valid, return a sync configuration that can be used to open the Realm + associated with this session. + */ +- (nullable RLMSyncConfiguration *)configuration; + +/** + Temporarily suspend syncronization and disconnect from the server. + + The session will not attempt to connect to Realm Object Server until `resume` + is called or the Realm file is closed and re-opened. + */ +- (void)suspend; + +/** + Resume syncronization and reconnect to Realm Object Server after suspending. + + This is a no-op if the session was already active or if the session is invalid. + Newly created sessions begin in the Active state and do not need to be resumed. + */ +- (void)resume; + +/** + Register a progress notification block. + + Multiple blocks can be registered with the same session at once. Each block + will be invoked on a side queue devoted to progress notifications. + + If the session has already received progress information from the + synchronization subsystem, the block will be called immediately. Otherwise, it + will be called as soon as progress information becomes available. + + The token returned by this method must be retained as long as progress + notifications are desired, and the `-invalidate` method should be called on it + when notifications are no longer needed and before the token is destroyed. + + If no token is returned, the notification block will never be called again. + There are a number of reasons this might be true. If the session has previously + experienced a fatal error it will not accept progress notification blocks. If + the block was configured in the `RLMSyncProgressForCurrentlyOutstandingWork` + mode but there is no additional progress to report (for example, the number + of transferrable bytes and transferred bytes are equal), the block will not be + called again. + + @param direction The transfer direction (upload or download) to track in this progress notification block. + @param mode The desired behavior of this progress notification block. + @param block The block to invoke when notifications are available. + + @return A token which must be held for as long as you want notifications to be delivered. + + @see `RLMSyncProgressDirection`, `RLMSyncProgress`, `RLMProgressNotificationBlock`, `RLMProgressNotificationToken` + */ +- (nullable RLMProgressNotificationToken *)addProgressNotificationForDirection:(RLMSyncProgressDirection)direction + mode:(RLMSyncProgressMode)mode + block:(RLMProgressNotificationBlock)block +NS_REFINED_FOR_SWIFT; + +/** + Given an error action token, immediately handle the corresponding action. + + @see `RLMSyncErrorClientResetError`, `RLMSyncErrorPermissionDeniedError` + */ ++ (void)immediatelyHandleError:(RLMSyncErrorActionToken *)token; + +/** + Get the sync session for the given Realm if it is a synchronized Realm, or `nil` + if it is not. + */ ++ (nullable RLMSyncSession *)sessionForRealm:(RLMRealm *)realm; + +@end + +// MARK: - Error action token + +#pragma mark - Error action token + +/** + An opaque token returned as part of certain errors. It can be + passed into certain APIs to perform certain actions. + + @see `RLMSyncErrorClientResetError`, `RLMSyncErrorPermissionDeniedError` + */ +@interface RLMSyncErrorActionToken : NSObject + +/// :nodoc: +- (instancetype)init __attribute__((unavailable("This type cannot be created directly"))); + +/// :nodoc: ++ (instancetype)new __attribute__((unavailable("This type cannot be created directly"))); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncSessionRefreshHandle.h b/Pods/Realm/include/RLMSyncSessionRefreshHandle.h new file mode 100644 index 0000000000..78a278b478 --- /dev/null +++ b/Pods/Realm/include/RLMSyncSessionRefreshHandle.h @@ -0,0 +1,30 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMSyncUser; + +/// An object that handles refreshing a session's token periodically, as long +/// as the session remains live and valid. +@interface RLMSyncSessionRefreshHandle : NSObject + +- (void)scheduleRefreshTimer:(NSDate *)dateWhenTokenExpires; +- (void)invalidate; + +@end diff --git a/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp b/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp new file mode 100644 index 0000000000..26b5bea256 --- /dev/null +++ b/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp @@ -0,0 +1,43 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncSessionRefreshHandle.h" + +#import "RLMSyncUtil_Private.h" + +#import + +namespace realm { +class SyncSession; +class SyncUser; +} + +@class RLMSyncUser; + +@interface RLMSyncSessionRefreshHandle () + +NS_ASSUME_NONNULL_BEGIN + +- (instancetype)initWithRealmURL:(NSURL *)realmURL + user:(std::shared_ptr)user + session:(std::shared_ptr)session + completionBlock:(nullable RLMSyncBasicErrorReportingBlock)completionBlock; + +NS_ASSUME_NONNULL_END + +@end diff --git a/Pods/Realm/include/RLMSyncSession_Private.hpp b/Pods/Realm/include/RLMSyncSession_Private.hpp new file mode 100644 index 0000000000..76a06ad182 --- /dev/null +++ b/Pods/Realm/include/RLMSyncSession_Private.hpp @@ -0,0 +1,51 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncSession.h" + +#import "RLMSyncUtil_Private.h" +#import + +namespace realm { +class SyncSession; +} + +NS_ASSUME_NONNULL_BEGIN + +@interface RLMSyncSession () { +@public // So it's visible to tests + std::weak_ptr _session; +} RLM_SYNC_UNINITIALIZABLE + +- (instancetype)initWithSyncSession:(std::shared_ptr const&)session; + +/// Wait for pending uploads to complete or the session to expire, and dispatch the callback onto the specified queue. +- (BOOL)waitForUploadCompletionOnQueue:(nullable dispatch_queue_t)queue callback:(void(^)(NSError * _Nullable))callback; + +/// Wait for pending downloads to complete or the session to expire, and dispatch the callback onto the specified queue. +- (BOOL)waitForDownloadCompletionOnQueue:(nullable dispatch_queue_t)queue callback:(void(^)(NSError * _Nullable))callback; + +@end + +@interface RLMSyncErrorActionToken () + +- (instancetype)initWithOriginalPath:(std::string)originalPath; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncSubscription.h b/Pods/Realm/include/RLMSyncSubscription.h new file mode 100644 index 0000000000..a527ef7b5d --- /dev/null +++ b/Pods/Realm/include/RLMSyncSubscription.h @@ -0,0 +1,195 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2018 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + `RLMSyncSubscriptionState` is an enumeration representing the possible state of a sync subscription. + */ +typedef NS_ENUM(NSInteger, RLMSyncSubscriptionState) { + /** + An error occurred while creating the subscription or while the server was processing it. + */ + RLMSyncSubscriptionStateError = -1, + + /** + The subscription is being created, but has not yet been written to the synced Realm. + */ + RLMSyncSubscriptionStateCreating = 2, + + /** + The subscription has been created, and is waiting to be processed by the server. + */ + RLMSyncSubscriptionStatePending = 0, + + /** + The subscription has been processed by the server, and objects matching the subscription + are now being synchronized to this client. + */ + RLMSyncSubscriptionStateComplete = 1, + + /** + This subscription has been removed. + */ + RLMSyncSubscriptionStateInvalidated = 3, +}; + +/** + `RLMSyncSubscription` represents a subscription to a set of objects in a synced Realm. + + When partial sync is enabled for a synced Realm, the only objects that the server synchronizes to the + client are those that match a sync subscription registered by that client. A subscription consists of + of a query (represented by an `RLMResults`) and an optional name. + + The state of the subscription can be observed using [Key-Value Observing](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html) on the `state` property. + + Subscriptions are created using `-[RLMResults subscribe]` or `-[RLMResults subscribeWithName:]`. + */ +@interface RLMSyncSubscription : NSObject + +/** + The unique name for this subscription. + + This will be `nil` if a name was not provided when the subscription was created. + */ +@property (nonatomic, readonly, nullable) NSString *name; + +/** + The state of the subscription. See `RLMSyncSubscriptionState`. + */ +@property (nonatomic, readonly) RLMSyncSubscriptionState state; + +/** + The error associated with this subscription, if any. + + Will be non-nil only when `state` is `RLMSyncSubscriptionStateError`. + */ +@property (nonatomic, readonly, nullable) NSError *error; + +/** + Remove this subscription. + + Removing a subscription will delete all objects from the local Realm that were matched + only by that subscription and not any remaining subscriptions. The deletion is performed + by the server, and so has no immediate impact on the contents of the local Realm. If the + device is currently offline, the removal will not be processed until the device returns online. + */ +- (void)unsubscribe; + +#pragma mark - Unavailable Methods + +/** + `-[RLMSyncSubscription init]` is not available because `RLMSyncSubscription` cannot be created directly. + */ +- (instancetype)init __attribute__((unavailable("RLMSyncSubscription cannot be created directly"))); + +/** + `+[RLMSyncSubscription new]` is not available because `RLMSyncSubscription` cannot be created directly. + */ ++ (instancetype)new __attribute__((unavailable("RLMSyncSubscription cannot be created directly"))); + +@end + +/** + Support for subscribing to the results of object queries in a synced Realm. + */ +@interface RLMResults (SyncSubscription) + +/** + Subscribe to the query represented by this `RLMResults`. + + Subscribing to a query asks the server to synchronize all objects to the + client which match the query, along with all objects which are reachable + from those objects via links. This happens asynchronously, and the local + client Realm may not immediately have all objects which match the query. + Observe the `state` property of the returned subscription object to be + notified of when the subscription has been processed by the server and + all objects matching the query are available. + + The subscription will not be explicitly named. + + @return The subscription + + @see RLMSyncSubscription +*/ +- (RLMSyncSubscription *)subscribe; + +/** + Subscribe to the query represented by this `RLMResults`. + + Subscribing to a query asks the server to synchronize all objects to the + client which match the query, along with all objects which are reachable + from those objects via links. This happens asynchronously, and the local + client Realm may not immediately have all objects which match the query. + Observe the `state` property of the returned subscription object to be + notified of when the subscription has been processed by the server and + all objects matching the query are available. + + Creating a new subscription with the same name and query as an existing + subscription will not create a new subscription, but instead will return + an object referring to the existing sync subscription. This means that + performing the same subscription twice followed by removing it once will + result in no subscription existing. + + @param subscriptionName The name of the subscription + + @return The subscription + + @see RLMSyncSubscription +*/ +- (RLMSyncSubscription *)subscribeWithName:(nullable NSString *)subscriptionName; + +/** + Subscribe to a subset of the query represented by this `RLMResults`. + + Subscribing to a query asks the server to synchronize all objects to the + client which match the query, along with all objects which are reachable + from those objects via links. This happens asynchronously, and the local + client Realm may not immediately have all objects which match the query. + Observe the `state` property of the returned subscription object to be + notified of when the subscription has been processed by the server and + all objects matching the query are available. + + Creating a new subscription with the same name and query as an existing + subscription will not create a new subscription, but instead will return + an object referring to the existing sync subscription. This means that + performing the same subscription twice followed by removing it once will + result in no subscription existing. + + The number of top-level matches may optionally be limited. This limit + respects the sort and distinct order of the query being subscribed to, + if any. Please note that the limit does not count or apply to objects + which are added indirectly due to being linked to by the objects in the + subscription. If the limit is larger than the number of objects which + match the query, all objects will be included. Limiting a subscription + requires ROS 3.10.1 or newer, and will fail with an invalid predicate + error with older versions. + + @param subscriptionName The name of the subscription + @param limit The maximum number of objects to include in the subscription. + + @return The subscription + + @see RLMSyncSubscription + */ +- (RLMSyncSubscription *)subscribeWithName:(nullable NSString *)subscriptionName limit:(NSUInteger)limit; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncUser.h b/Pods/Realm/include/RLMSyncUser.h new file mode 100644 index 0000000000..a412b84f8b --- /dev/null +++ b/Pods/Realm/include/RLMSyncUser.h @@ -0,0 +1,526 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import "RLMRealmConfiguration.h" +#import "RLMResults.h" +#import "RLMSyncCredentials.h" +#import "RLMSyncPermission.h" + +@class RLMSyncUser, RLMSyncUserInfo, RLMSyncCredentials, RLMSyncPermission, RLMSyncSession, RLMRealm; + +/** + The state of the user object. + */ +typedef NS_ENUM(NSUInteger, RLMSyncUserState) { + /// The user is logged out. Call `logInWithCredentials:...` with valid credentials to log the user back in. + RLMSyncUserStateLoggedOut, + /// The user is logged in, and any Realms associated with it are syncing with the Realm Object Server. + RLMSyncUserStateActive, + /// The user has encountered a fatal error state, and cannot be used. + RLMSyncUserStateError, +}; + +/// A block type used for APIs which asynchronously vend an `RLMSyncUser`. +typedef void(^RLMUserCompletionBlock)(RLMSyncUser * _Nullable, NSError * _Nullable); + +/// A block type used to report the status of a password change operation. +/// If the `NSError` argument is nil, the operation succeeded. +typedef void(^RLMPasswordChangeStatusBlock)(NSError * _Nullable); + +/// A block type used to report the status of a permission apply or revoke operation. +/// If the `NSError` argument is nil, the operation succeeded. +typedef void(^RLMPermissionStatusBlock)(NSError * _Nullable); + +/// A block type used to report the status of a permission offer operation. +typedef void(^RLMPermissionOfferStatusBlock)(NSString * _Nullable, NSError * _Nullable); + +/// A block type used to report the status of a permission offer response operation. +typedef void(^RLMPermissionOfferResponseStatusBlock)(NSURL * _Nullable, NSError * _Nullable); + +/// A block type used to asynchronously report results of a permissions get operation. +/// Exactly one of the two arguments will be populated. +typedef void(^RLMPermissionResultsBlock)(RLMResults * _Nullable, NSError * _Nullable); + +/// A block type used to asynchronously report results of a user info retrieval. +/// Exactly one of the two arguments will be populated. +typedef void(^RLMRetrieveUserBlock)(RLMSyncUserInfo * _Nullable, NSError * _Nullable); + +/// A block type used to report an error related to a specific user. +typedef void(^RLMUserErrorReportingBlock)(RLMSyncUser * _Nonnull, NSError * _Nonnull); + +NS_ASSUME_NONNULL_BEGIN + +/** + A `RLMSyncUser` instance represents a single Realm Object Server user account. + + A user may have one or more credentials associated with it. These credentials + uniquely identify the user to the authentication provider, and are used to sign + into a Realm Object Server user account. + + Note that user objects are only vended out via SDK APIs, and cannot be directly + initialized. User objects can be accessed from any thread. + */ +@interface RLMSyncUser : NSObject + +/** + A dictionary of all valid, logged-in user identities corresponding to their user objects. + */ ++ (NSDictionary *)allUsers NS_REFINED_FOR_SWIFT; + +/** + The logged-in user. `nil` if none exists. + + @warning Throws an exception if more than one logged-in user exists. + */ ++ (nullable RLMSyncUser *)currentUser NS_REFINED_FOR_SWIFT; + +/** + The unique Realm Object Server user ID string identifying this user. + */ +@property (nullable, nonatomic, readonly) NSString *identity; + +/** + The user's refresh token used to access the Realm Object Server. + + This is required to make HTTP requests to Realm Object Server's REST API + for functionality not exposed natively. It should be treated as sensitive data. + */ +@property (nullable, nonatomic, readonly) NSString *refreshToken; + +/** + The URL of the authentication server this user will communicate with. + */ +@property (nullable, nonatomic, readonly) NSURL *authenticationServer; + +/** + Whether the user is a Realm Object Server administrator. Value reflects the + state at the time of the last successful login of this user. + */ +@property (nonatomic, readonly) BOOL isAdmin; + +/** + The current state of the user. + */ +@property (nonatomic, readonly) RLMSyncUserState state; + +#pragma mark - Lifecycle + +/** + Create, log in, and asynchronously return a new user object, specifying a custom + timeout for the network request and a custom queue to run the callback upon. + Credentials identifying the user must be passed in. The user becomes available in + the completion block, at which point it is ready for use. + */ ++ (void)logInWithCredentials:(RLMSyncCredentials *)credentials + authServerURL:(NSURL *)authServerURL + timeout:(NSTimeInterval)timeout + callbackQueue:(dispatch_queue_t)callbackQueue + onCompletion:(RLMUserCompletionBlock)completion NS_REFINED_FOR_SWIFT; + +/** + Create, log in, and asynchronously return a new user object. + + If the login completes successfully, the completion block will invoked with + a `RLMSyncUser` object representing the logged-in user. This object can be + used to open synchronized Realms. If the login fails, the completion block + will be invoked with an error. + + The completion block always runs on the main queue. + + @param credentials A credentials value identifying the user to be logged in. + @param authServerURL The URL of the authentication server (e.g. "http://realm.example.org:9080"). + @param completion A callback block that returns a user object or an error, + indicating the completion of the login operation. + */ ++ (void)logInWithCredentials:(RLMSyncCredentials *)credentials + authServerURL:(NSURL *)authServerURL + onCompletion:(RLMUserCompletionBlock)completion +NS_SWIFT_UNAVAILABLE("Use the full version of this API."); + + +/** + Returns the default configuration for the user. The default configuration + points to the default query-based Realm on the server the user authenticated against. + */ +- (RLMRealmConfiguration *)configuration NS_REFINED_FOR_SWIFT; + +/** + Create a query-based configuration instance for the given url. + + @param url The unresolved absolute URL to the Realm on the Realm Object Server, + e.g. "realm://example.org/~/path/to/realm". "Unresolved" means the + path should contain the wildcard marker `~`, which will automatically + be filled in with the user identity by the Realm Object Server. + @return A default configuration object with the sync configuration set to use the given URL. + */ +- (RLMRealmConfiguration *)configurationWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + Create a configuration instance for the given url. + + @param url The unresolved absolute URL to the Realm on the Realm Object Server, + e.g. "realm://example.org/~/path/to/realm". "Unresolved" means the + path should contain the wildcard marker `~`, which will automatically + be filled in with the user identity by the Realm Object Server. + @param fullSynchronization If YES, all objects in the server Realm are + automatically synchronized, and the query subscription + methods cannot be used. + @return A default configuration object with the sync configuration set to use + the given URL and options. + */ +- (RLMRealmConfiguration *)configurationWithURL:(nullable NSURL *)url + fullSynchronization:(bool)fullSynchronization NS_REFINED_FOR_SWIFT; + +/** + Create a configuration instance for the given url. + + @param url The unresolved absolute URL to the Realm on the Realm Object Server, + e.g. "realm://example.org/~/path/to/realm". "Unresolved" means the + path should contain the wildcard marker `~`, which will automatically + be filled in with the user identity by the Realm Object Server. + @param fullSynchronization If YES, all objects in the server Realm are + automatically synchronized, and the query subscription + methods cannot be used. + @param enableSSLValidation If NO, invalid SSL certificates for the server will + not be rejected. THIS SHOULD NEVER BE USED IN + PRODUCTION AND EXISTS ONLY FOR TESTING PURPOSES. + @param urlPrefix A prefix which is prepending to URLs constructed for + the server. This should normally be `nil`, and customized only + to match corresponding settings on the server. + @return A default configuration object with the sync configuration set to use + the given URL and options. + */ +- (RLMRealmConfiguration *)configurationWithURL:(nullable NSURL *)url + fullSynchronization:(bool)fullSynchronization + enableSSLValidation:(bool)enableSSLValidation + urlPrefix:(nullable NSString *)urlPrefix NS_REFINED_FOR_SWIFT; + +/** + Log a user out, destroying their server state, unregistering them from the SDK, + and removing any synced Realms associated with them from on-disk storage on + next app launch. If the user is already logged out or in an error state, this + method does nothing. + + This method should be called whenever the application is committed to not using + a user again unless they are recreated. + Failing to call this method may result in unused files and metadata needlessly + taking up space. + */ +- (void)logOut; + +/** + An optional error handler which can be set to notify the host application when + the user encounters an error. Errors reported by this error handler are always + `RLMSyncAuthError`s. + + @note Check for `RLMSyncAuthErrorInvalidAccessToken` to see if the user has + been remotely logged out because its refresh token expired, or because the + third party authentication service providing the user's identity has + logged the user out. + + @warning Regardless of whether an error handler is installed, certain user errors + will automatically cause the user to enter the logged out state. + */ +@property (nullable, nonatomic) RLMUserErrorReportingBlock errorHandler NS_REFINED_FOR_SWIFT; + +#pragma mark - Sessions + +/** + Retrieve a valid session object belonging to this user for a given URL, or `nil` + if no such object exists. + */ +- (nullable RLMSyncSession *)sessionForURL:(NSURL *)url; + +/** + Retrieve all the valid sessions belonging to this user. + */ +- (NSArray *)allSessions; + +#pragma mark - Passwords + +/** + Change this user's password asynchronously. + + @warning Changing a user's password using an authentication server that doesn't + use HTTPS is a major security flaw, and should only be done while + testing. + + @param newPassword The user's new password. + @param completion Completion block invoked when login has completed or failed. + The callback will be invoked on a background queue provided + by `NSURLSession`. + */ +- (void)changePassword:(NSString *)newPassword completion:(RLMPasswordChangeStatusBlock)completion; + +/** + Change an arbitrary user's password asynchronously. + + @note The current user must be an admin user for this operation to succeed. + + @warning Changing a user's password using an authentication server that doesn't + use HTTPS is a major security flaw, and should only be done while + testing. + + @param newPassword The user's new password. + @param userID The identity of the user whose password should be changed. + @param completion Completion block invoked when login has completed or failed. + The callback will be invoked on a background queue provided + by `NSURLSession`. + */ +- (void)changePassword:(NSString *)newPassword forUserID:(NSString *)userID completion:(RLMPasswordChangeStatusBlock)completion; + +/** + Ask the server to send a password reset email to the given email address. + + If `email` is an email address which is associated with a user account that was + registered using the "password" authentication service, the server will send an + email to that address with a password reset token. No error is reported if the + email address is invalid or not associated with an account. + + @param serverURL The authentication server URL for the user. + @param email The email address to send the email to. + @param completion A block which will be called when the request completes or + fails. The callback will be invoked on a background queue + provided by `NSURLSession`, and not on the calling queue. + */ ++ (void)requestPasswordResetForAuthServer:(NSURL *)serverURL + userEmail:(NSString *)email + completion:(RLMPasswordChangeStatusBlock)completion; + +/** + Change a user's password using a one-time password reset token. + + By default, the password reset email sent by ROS will link to a web site where + the user can select a new password, and the app will not need to call this + method. If you wish to instead handle this within your native app, you must + change the `baseURL` in the server configuration for `PasswordAuthProvider` to + a scheme registered for your app, extract the token from the URL, and call this + method after prompting the user for a new password. + + @warning Changing a user's password using an authentication server that doesn't + use HTTPS is a major security flaw, and should only be done while + testing. + + @param serverURL The authentication server URL for the user. + @param token The one-time use token from the URL. + @param newPassword The user's new password. + @param completion A block which will be called when the request completes or + fails. The callback will be invoked on a background queue + provided by `NSURLSession`, and not on the calling queue. + */ ++ (void)completePasswordResetForAuthServer:(NSURL *)serverURL + token:(NSString *)token + password:(NSString *)newPassword + completion:(RLMPasswordChangeStatusBlock)completion; + +/** + Ask the server to send a confirmation email to the given email address. + + If `email` is an email address which is associated with a user account that was + registered using the "password" authentication service, the server will send an + email to that address with a confirmation token. No error is reported if the + email address is invalid or not associated with an account. + + @param serverURL The authentication server URL for the user. + @param email The email address to send the email to. + @param completion A block which will be called when the request completes or + fails. The callback will be invoked on a background queue + provided by `NSURLSession`, and not on the calling queue. + */ ++ (void)requestEmailConfirmationForAuthServer:(NSURL *)serverURL + userEmail:(NSString *)email + completion:(RLMPasswordChangeStatusBlock)completion; + +/** + Confirm a user's email using a one-time confirmation token. + + By default, the confirmation email sent by ROS will link to a web site with + a generic "thank you for confirming your email" message, and the app will not + need to call this method. If you wish to instead handle this within your native + app, you must change the `baseURL` in the server configuration for + `PasswordAuthProvider` to a scheme registered for your app, extract the token + from the URL, and call this method. + + @param serverURL The authentication server URL for the user. + @param token The one-time use token from the URL. + @param completion A block which will be called when the request completes or + fails. The callback will be invoked on a background queue + provided by `NSURLSession`, and not on the calling queue. + */ ++ (void)confirmEmailForAuthServer:(NSURL *)serverURL + token:(NSString *)token + completion:(RLMPasswordChangeStatusBlock)completion; + +#pragma mark - Administrator + +/** + Given a Realm Object Server authentication provider and a provider identifier for a user + (for example, a username), look up and return user information for that user. + + @param providerUserIdentity The username or identity of the user as issued by the authentication provider. + In most cases this is different from the Realm Object Server-issued identity. + @param provider The authentication provider that manages the user whose information is desired. + @param completion Completion block invoked when request has completed or failed. + The callback will be invoked on a background queue provided + by `NSURLSession`. + */ +- (void)retrieveInfoForUser:(NSString *)providerUserIdentity + identityProvider:(RLMIdentityProvider)provider + completion:(RLMRetrieveUserBlock)completion; + +#pragma mark - Permissions + +/** + Asynchronously retrieve all permissions associated with the user calling this method. + + The results will be returned through the callback block, or an error if the operation failed. + The callback block will be run on the same thread the method was called on. + + @warning This method must be called from a thread with a currently active run loop. Unless + you have manually configured a run loop on a side thread, this will usually be the + main thread. + */ +- (void)retrievePermissionsWithCallback:(RLMPermissionResultsBlock)callback NS_REFINED_FOR_SWIFT; + +/** + Apply a given permission. + + The operation will take place asynchronously, and the callback will be used to report whether + the permission change succeeded or failed. The user calling this method must have the right + to grant the given permission, or else the operation will fail. + + @see `RLMSyncPermission` + */ +- (void)applyPermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback; + +/** + Revoke a given permission. + + The operation will take place asynchronously, and the callback will be used to report whether + the permission change succeeded or failed. The user calling this method must have the right + to grant the given permission, or else the operation will fail. + + @see `RLMSyncPermission` + */ +- (void)revokePermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback; + +/** + Create a permission offer for a Realm. + + A permission offer is used to grant access to a Realm this user manages to another + user. Creating a permission offer produces a string token which can be passed to the + recepient in any suitable way (for example, via e-mail). + + The operation will take place asynchronously. The token can be accepted by the recepient + using the `-[RLMSyncUser acceptOfferForToken:callback:]` method. + + @param url The URL of the Realm for which the permission offer should pertain. This + may be the URL of any Realm which this user is allowed to manage. If the URL + has a `~` wildcard it will be replaced with this user's user identity. + @param accessLevel What access level to grant to whoever accepts the token. + @param expirationDate Optionally, a date which indicates when the offer expires. If the + recepient attempts to accept the offer after the date it will be rejected. + @param callback A callback indicating whether the operation succeeded or failed. If it + succeeded the token will be passed in as a string. + + @see `acceptOfferForToken:callback:` + */ +- (void)createOfferForRealmAtURL:(NSURL *)url + accessLevel:(RLMSyncAccessLevel)accessLevel + expiration:(nullable NSDate *)expirationDate + callback:(RLMPermissionOfferStatusBlock)callback NS_REFINED_FOR_SWIFT; + +/** + Accept a permission offer. + + Pass in a token representing a permission offer. The operation will take place asynchronously. + If the operation succeeds, the callback will be passed the URL of the Realm for which the + offer applied, so the Realm can be opened. + + The token this method accepts can be created by the offering user through the + `-[RLMSyncUser createOfferForRealmAtURL:accessLevel:expiration:callback:]` method. + + @see `createOfferForRealmAtURL:accessLevel:expiration:callback:` + */ +- (void)acceptOfferForToken:(NSString *)token + callback:(RLMPermissionOfferResponseStatusBlock)callback; + +/// :nodoc: +- (instancetype)init __attribute__((unavailable("RLMSyncUser cannot be created directly"))); +/// :nodoc: ++ (instancetype)new __attribute__((unavailable("RLMSyncUser cannot be created directly"))); + +@end + +#pragma mark - User info classes + +/** + A data object representing a user account associated with a user. + + @see `RLMSyncUserInfo` + */ +@interface RLMSyncUserAccountInfo : NSObject + +/// The authentication provider which manages this user account. +@property (nonatomic, readonly) RLMIdentityProvider provider; + +/// The username or identity of this user account. +@property (nonatomic, readonly) NSString *providerUserIdentity; + +/// :nodoc: +- (instancetype)init __attribute__((unavailable("RLMSyncUserAccountInfo cannot be created directly"))); +/// :nodoc: ++ (instancetype)new __attribute__((unavailable("RLMSyncUserAccountInfo cannot be created directly"))); + +@end + +/** + A data object representing information about a user that was retrieved from a user lookup call. + */ +@interface RLMSyncUserInfo : NSObject + +/** + An array of all the user accounts associated with this user. + */ +@property (nonatomic, readonly) NSArray *accounts; + +/** + The identity issued to this user by the Realm Object Server. + */ +@property (nonatomic, readonly) NSString *identity; + +/** + Metadata about this user stored on the Realm Object Server. + */ +@property (nonatomic, readonly) NSDictionary *metadata; + +/** + Whether the user is flagged on the Realm Object Server as an administrator. + */ +@property (nonatomic, readonly) BOOL isAdmin; + +/// :nodoc: +- (instancetype)init __attribute__((unavailable("RLMSyncUserInfo cannot be created directly"))); +/// :nodoc: ++ (instancetype)new __attribute__((unavailable("RLMSyncUserInfo cannot be created directly"))); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncUser_Private.hpp b/Pods/Realm/include/RLMSyncUser_Private.hpp new file mode 100644 index 0000000000..f49a37e68e --- /dev/null +++ b/Pods/Realm/include/RLMSyncUser_Private.hpp @@ -0,0 +1,75 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncUser.h" + +#import "RLMSyncConfiguration.h" +#import "RLMSyncUtil_Private.h" + +#import "sync/sync_config.hpp" +#import "sync/sync_user.hpp" +#import "sync/impl/sync_metadata.hpp" + +@class RLMSyncConfiguration, RLMSyncSessionRefreshHandle; + +using namespace realm; + +typedef void(^RLMFetchedRealmCompletionBlock)(NSError * _Nullable, RLMRealm * _Nullable, BOOL * _Nonnull); + +NS_ASSUME_NONNULL_BEGIN + +class CocoaSyncUserContext : public SyncUserContext { +public: + void register_refresh_handle(const std::string& path, RLMSyncSessionRefreshHandle *handle); + void unregister_refresh_handle(const std::string& path); + void invalidate_all_handles(); + + RLMUserErrorReportingBlock error_handler() const; + void set_error_handler(RLMUserErrorReportingBlock); + +private: + /** + A map of paths to 'refresh handles'. + + A refresh handle is an object that encapsulates the concept of periodically + refreshing the Realm's access token before it expires. Tokens are indexed by their + paths (e.g. `/~/path/to/realm`). + */ + std::unordered_map m_refresh_handles; + std::mutex m_mutex; + + /** + An optional callback invoked when the authentication server reports the user as + being in an expired state. + */ + RLMUserErrorReportingBlock m_error_handler; + mutable std::mutex m_error_handler_mutex; +}; + +@interface RLMSyncUser () +- (instancetype)initWithSyncUser:(std::shared_ptr)user; +- (NSURL *)defaultRealmURL; +- (std::shared_ptr)_syncUser; ++ (void)_setUpBindingContextFactory; +@end + +using PermissionChangeCallback = std::function; + +PermissionChangeCallback RLMWrapPermissionStatusCallback(RLMPermissionStatusBlock callback); + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncUtil.h b/Pods/Realm/include/RLMSyncUtil.h new file mode 100644 index 0000000000..5867d74a3b --- /dev/null +++ b/Pods/Realm/include/RLMSyncUtil.h @@ -0,0 +1,222 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +/// A token originating from the Realm Object Server. +typedef NSString* RLMServerToken; + +NS_ASSUME_NONNULL_BEGIN + +/// A user info key for use with `RLMSyncErrorClientResetError`. +extern NSString *const kRLMSyncPathOfRealmBackupCopyKey; + +/// A user info key for use with certain error types. +extern NSString *const kRLMSyncErrorActionTokenKey; + +/** + The error domain string for all SDK errors related to errors reported + by the synchronization manager error handler, as well as general sync + errors that don't fall into any of the other categories. + */ +extern NSString *const RLMSyncErrorDomain; + +/** + The error domain string for all SDK errors related to the authentication + endpoint. + */ +extern NSString *const RLMSyncAuthErrorDomain; + +/** + The error domain string for all SDK errors related to the permissions + system and APIs. + */ +extern NSString *const RLMSyncPermissionErrorDomain; + +/** + An error related to a problem that might be reported by the synchronization manager + error handler, or a callback on a sync-related API that performs asynchronous work. + */ +typedef RLM_ERROR_ENUM(NSInteger, RLMSyncError, RLMSyncErrorDomain) { + + /// An error that indicates a problem with the session (a specific Realm opened for sync). + RLMSyncErrorClientSessionError = 4, + + /// An error that indicates a problem with a specific user. + RLMSyncErrorClientUserError = 5, + + /** + An error that indicates an internal, unrecoverable problem + with the underlying synchronization engine. + */ + RLMSyncErrorClientInternalError = 6, + + /** + An error that indicates the Realm needs to be reset. + + A synced Realm may need to be reset because the Realm Object Server encountered an + error and had to be restored from a backup. If the backup copy of the remote Realm + is of an earlier version than the local copy of the Realm, the server will ask the + client to reset the Realm. + + The reset process is as follows: the local copy of the Realm is copied into a recovery + directory for safekeeping, and then deleted from the original location. The next time + the Realm for that URL is opened, the Realm will automatically be re-downloaded from the + Realm Object Server, and can be used as normal. + + Data written to the Realm after the local copy of the Realm diverged from the backup + remote copy will be present in the local recovery copy of the Realm file. The + re-downloaded Realm will initially contain only the data present at the time the Realm + was backed up on the server. + + The client reset process can be initiated in one of two ways. + + The `userInfo` dictionary contains an opaque token object under the key + `kRLMSyncErrorActionTokenKey`. This token can be passed into + `+[RLMSyncSession immediatelyHandleError:]` in order to immediately perform the client + reset process. This should only be done after your app closes and invalidates every + instance of the offending Realm on all threads (note that autorelease pools may make this + difficult to guarantee). + + If `+[RLMSyncSession immediatelyHandleError:]` is not called, the client reset process + will be automatically carried out the next time the app is launched and the + `RLMSyncManager` singleton is accessed. + + The value for the `kRLMSyncPathOfRealmBackupCopyKey` key in the `userInfo` dictionary + describes the path of the recovered copy of the Realm. This copy will not actually be + created until the client reset process is initiated. + + @see `-[NSError rlmSync_errorActionToken]`, `-[NSError rlmSync_clientResetBackedUpRealmPath]` + */ + RLMSyncErrorClientResetError = 7, + + /** + An error that indicates an authentication error occurred. + + The `kRLMSyncUnderlyingErrorKey` key in the user info dictionary will contain the + underlying error, which is guaranteed to be under the `RLMSyncAuthErrorDomain` + error domain. + */ + RLMSyncErrorUnderlyingAuthError = 8, + + /** + An error that indicates the user does not have permission to perform an operation + upon a synced Realm. For example, a user may receive this error if they attempt to + open a Realm they do not have at least read access to, or write to a Realm they only + have read access to. + + This error may also occur if a user incorrectly opens a Realm they have read-only + permissions to without using the `asyncOpen()` APIs. + + A Realm that suffers a permission denied error is, by default, flagged so that its + local copy will be deleted the next time the application starts. + + The `userInfo` dictionary contains an opaque token object under the key + `kRLMSyncErrorActionTokenKey`. This token can be passed into + `+[RLMSyncSession immediatelyHandleError:]` in order to immediately delete the local + copy. This should only be done after your app closes and invalidates every instance + of the offending Realm on all threads (note that autorelease pools may make this + difficult to guarantee). + + @warning It is strongly recommended that, if a Realm has encountered a permission denied + error, its files be deleted before attempting to re-open it. + + @see `-[NSError rlmSync_errorActionToken]` + */ + RLMSyncErrorPermissionDeniedError = 9, +}; + +/// An error which is related to authentication to a Realm Object Server. +typedef RLM_ERROR_ENUM(NSInteger, RLMSyncAuthError, RLMSyncAuthErrorDomain) { + /// An error that indicates that the response received from the authentication server was malformed. + RLMSyncAuthErrorBadResponse = 1, + + /// An error that indicates that the supplied Realm path was invalid, or could not be resolved by the authentication + /// server. + RLMSyncAuthErrorBadRemoteRealmPath = 2, + + /// An error that indicates that the response received from the authentication server was an HTTP error code. The + /// `userInfo` dictionary contains the actual error code value. + RLMSyncAuthErrorHTTPStatusCodeError = 3, + + /// An error that indicates a problem with the session (a specific Realm opened for sync). + RLMSyncAuthErrorClientSessionError = 4, + + /// An error that indicates that the provided credentials are ill-formed. + RLMSyncAuthErrorInvalidParameters = 601, + + /// An error that indicates that no Realm path was included in the URL. + RLMSyncAuthErrorMissingPath = 602, + + /// An error that indicates that the provided credentials are invalid. + RLMSyncAuthErrorInvalidCredential = 611, + + /// An error that indicates that the user with provided credentials does not exist. + RLMSyncAuthErrorUserDoesNotExist = 612, + + /// An error that indicates that the user cannot be registered as it exists already. + RLMSyncAuthErrorUserAlreadyExists = 613, + + /// An error that indicates the path is invalid or the user doesn't have access to that Realm. + RLMSyncAuthErrorAccessDeniedOrInvalidPath = 614, + + /// An error that indicates the refresh token was invalid. + RLMSyncAuthErrorInvalidAccessToken = 615, + + /// An error that indicates the permission offer is expired. + RLMSyncAuthErrorExpiredPermissionOffer = 701, + + /// An error that indicates the permission offer is ambiguous. + RLMSyncAuthErrorAmbiguousPermissionOffer = 702, + + /// An error that indicates the file at the given path can't be shared. + RLMSyncAuthErrorFileCannotBeShared = 703, +}; + +/** + An error related to the permissions subsystem. + */ +typedef RLM_ERROR_ENUM(NSInteger, RLMSyncPermissionError, RLMSyncPermissionErrorDomain) { + /** + An error that indicates a permission change operation failed. The `userInfo` + dictionary contains the underlying error code and a message (if any). + */ + RLMSyncPermissionErrorChangeFailed = 1, + + /** + An error that indicates that attempting to retrieve permissions failed. + */ + RLMSyncPermissionErrorGetFailed = 2, + + /** + An error that indicates that trying to create a permission offer failed. + */ + RLMSyncPermissionErrorOfferFailed = 3, + + /** + An error that indicates that trying to accept a permission offer failed. + */ + RLMSyncPermissionErrorAcceptOfferFailed = 4, + + /** + An error that indicates that an internal error occurred. + */ + RLMSyncPermissionErrorInternal = 5, +}; + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMSyncUtil_Private.h b/Pods/Realm/include/RLMSyncUtil_Private.h new file mode 100644 index 0000000000..d4c044ffd4 --- /dev/null +++ b/Pods/Realm/include/RLMSyncUtil_Private.h @@ -0,0 +1,135 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import +#import +#import + +typedef NS_ENUM(NSUInteger, RLMSyncSystemErrorKind) { + // Specific + RLMSyncSystemErrorKindClientReset, + RLMSyncSystemErrorKindPermissionDenied, + // General + RLMSyncSystemErrorKindClient, + RLMSyncSystemErrorKindConnection, + RLMSyncSystemErrorKindSession, + RLMSyncSystemErrorKindUser, + RLMSyncSystemErrorKindUnknown, +}; + +@class RLMSyncUser; + +typedef void(^RLMSyncCompletionBlock)(NSError * _Nullable, NSDictionary * _Nullable); +typedef void(^RLMSyncBasicErrorReportingBlock)(NSError * _Nullable); + +typedef NSString* RLMServerPath; + +NS_ASSUME_NONNULL_BEGIN + +extern RLMIdentityProvider const RLMIdentityProviderAccessToken; +extern RLMIdentityProvider const RLMIdentityProviderRealm; + +extern NSString *const kRLMSyncAppIDKey; +extern NSString *const kRLMSyncDataKey; +extern NSString *const kRLMSyncErrorJSONKey; +extern NSString *const kRLMSyncErrorStatusCodeKey; +extern NSString *const kRLMSyncIdentityKey; +extern NSString *const kRLMSyncIsAdminKey; +extern NSString *const kRLMSyncNewPasswordKey; +extern NSString *const kRLMSyncPasswordKey; +extern NSString *const kRLMSyncPathKey; +extern NSString *const kRLMSyncTokenKey; +extern NSString *const kRLMSyncProviderKey; +extern NSString *const kRLMSyncProviderIDKey; +extern NSString *const kRLMSyncRegisterKey; +extern NSString *const kRLMSyncUnderlyingErrorKey; +extern NSString *const kRLMSyncUserIDKey; + +FOUNDATION_EXTERN uint8_t RLMGetComputedPermissions(RLMRealm *realm, id _Nullable object); + +#define RLM_SYNC_UNINITIALIZABLE \ +- (instancetype)init __attribute__((unavailable("This type cannot be created directly"))); \ ++ (instancetype)new __attribute__((unavailable("This type cannot be created directly"))); + +NS_ASSUME_NONNULL_END + +/// A macro to parse a string out of a JSON dictionary, or return nil. +#define RLM_SYNC_PARSE_STRING_OR_ABORT(json_macro_val, key_macro_val, prop_macro_val) \ +{ \ +id data = json_macro_val[key_macro_val]; \ +if (![data isKindOfClass:[NSString class]]) { return nil; } \ +self.prop_macro_val = data; \ +} \ + +#define RLM_SYNC_PARSE_OPTIONAL_STRING(json_macro_val, key_macro_val, prop_macro_val) \ +{ \ +id data = json_macro_val[key_macro_val]; \ +if (![data isKindOfClass:[NSString class]]) { data = nil; } \ +self.prop_macro_val = data; \ +} \ + +#define RLM_SYNC_PARSE_OPTIONAL_BOOL(json_macro_val, key_macro_val, prop_macro_val) \ +{ \ +id data = json_macro_val[key_macro_val]; \ +if (![data isKindOfClass:[NSNumber class]]) { data = @NO; } \ +self.prop_macro_val = [data boolValue]; \ +} \ + +/// A macro to parse a double out of a JSON dictionary, or return nil. +#define RLM_SYNC_PARSE_DOUBLE_OR_ABORT(json_macro_val, key_macro_val, prop_macro_val) \ +{ \ +id data = json_macro_val[key_macro_val]; \ +if (![data isKindOfClass:[NSNumber class]]) { return nil; } \ +self.prop_macro_val = [data doubleValue]; \ +} \ + +/// A macro to build a sub-model out of a JSON dictionary, or return nil. +#define RLM_SYNC_PARSE_MODEL_OR_ABORT(json_macro_val, key_macro_val, class_macro_val, prop_macro_val) \ +{ \ +id raw = json_macro_val[key_macro_val]; \ +if (![raw isKindOfClass:[NSDictionary class]]) { return nil; } \ +id model = [[class_macro_val alloc] initWithDictionary:raw]; \ +if (!model) { return nil; } \ +self.prop_macro_val = model; \ +} \ + +/// A macro to build an array of sub-models out of a JSON dictionary, or return nil. +#define RLM_SYNC_PARSE_MODEL_ARRAY_OR_ABORT(json_macro_val, key_macro_val, class_macro_val, prop_macro_val) \ +{ \ +NSArray *jsonArray = json_macro_val[key_macro_val]; \ +if (![jsonArray isKindOfClass:[NSArray class]]) { return nil; } \ +NSMutableArray *buffer = [NSMutableArray array]; \ +for (id value in jsonArray) { \ +id next = nil; \ +if ([value isKindOfClass:[NSDictionary class]]) { next = [[class_macro_val alloc] initWithDictionary:value]; } \ +if (!next) { return nil; } \ +[buffer addObject:next]; \ +} \ +self.prop_macro_val = [buffer copy]; \ +} \ + +#define RLM_SYNC_PARSE_OPTIONAL_MODEL(json_macro_val, key_macro_val, class_macro_val, prop_macro_val) \ +{ \ +id model; \ +id raw = json_macro_val[key_macro_val]; \ +if (![raw isKindOfClass:[NSDictionary class]]) { model = nil; } \ +else { model = [[class_macro_val alloc] initWithDictionary:raw]; } \ +self.prop_macro_val = model; \ +} \ diff --git a/Pods/Realm/include/RLMSyncUtil_Private.hpp b/Pods/Realm/include/RLMSyncUtil_Private.hpp new file mode 100644 index 0000000000..3ea2130c1c --- /dev/null +++ b/Pods/Realm/include/RLMSyncUtil_Private.hpp @@ -0,0 +1,74 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMSyncUtil_Private.h" + +#import "RLMSyncConfiguration_Private.h" +#import "RLMSyncPermission.h" + +#import "sync/sync_manager.hpp" +#import "realm/util/optional.hpp" + +@class RLMSyncErrorResponseModel; +class CocoaSyncUserContext; + +namespace realm { +enum class AccessLevel; +} + +realm::SyncSessionStopPolicy translateStopPolicy(RLMSyncStopPolicy stopPolicy); +RLMSyncStopPolicy translateStopPolicy(realm::SyncSessionStopPolicy stop_policy); + +std::shared_ptr sync_session_for_realm(RLMRealm *realm); + +#pragma mark - Get user context + +CocoaSyncUserContext& context_for(const std::shared_ptr& user); + +#pragma mark - Access level conversion + +realm::AccessLevel accessLevelForObjCAccessLevel(RLMSyncAccessLevel level); +RLMSyncAccessLevel objCAccessLevelForAccessLevel(realm::AccessLevel level); + +#pragma mark - Error conversion + +typedef enum : NSUInteger { + RLMPermissionActionTypeGet, + RLMPermissionActionTypeChange, + RLMPermissionActionTypeOffer, + RLMPermissionActionTypeAcceptOffer, +} RLMPermissionActionType; + +NSError *translateSyncExceptionPtrToError(std::exception_ptr ptr, RLMPermissionActionType type); + +#pragma mark - Error construction + +NSError *make_auth_error_bad_response(NSDictionary *json=nil); +NSError *make_auth_error_http_status(NSInteger status); +NSError *make_auth_error_client_issue(); +NSError *make_auth_error(RLMSyncErrorResponseModel *responseModel); + +NSError *make_permission_error_get(NSString *description, realm::util::Optional code=none); +NSError *make_permission_error_change(NSString *description, realm::util::Optional code=none); +NSError *make_permission_error_offer(NSString *description, realm::util::Optional code=none); +NSError *make_permission_error_accept_offer(NSString *description, realm::util::Optional code=none); + +// Set 'code' to NSNotFound to not actually have an error code. +NSError *make_sync_error(RLMSyncSystemErrorKind kind, NSString *description, NSInteger code, NSDictionary *custom); +NSError *make_sync_error(NSError *wrapped_auth_error); +NSError *make_sync_error(std::error_code, RLMSyncSystemErrorKind kind=RLMSyncSystemErrorKindSession); diff --git a/Pods/Realm/include/RLMThreadSafeReference.h b/Pods/Realm/include/RLMThreadSafeReference.h new file mode 100644 index 0000000000..a935ebe047 --- /dev/null +++ b/Pods/Realm/include/RLMThreadSafeReference.h @@ -0,0 +1,106 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMRealm; + +NS_ASSUME_NONNULL_BEGIN + +/** + Objects of types which conform to `RLMThreadConfined` can be managed by a Realm, which will make + them bound to a thread-specific `RLMRealm` instance. Managed objects must be explicitly exported + and imported to be passed between threads. + + Managed instances of objects conforming to this protocol can be converted to a thread-safe + reference for transport between threads by passing to the + `+[RLMThreadSafeReference referenceWithThreadConfined:]` constructor. + + Note that only types defined by Realm can meaningfully conform to this protocol, and defining new + classes which attempt to conform to it will not make them work with `RLMThreadSafeReference`. + */ +@protocol RLMThreadConfined +// Conformance to the `RLMThreadConfined_Private` protocol will be enforced at runtime. + +/** + The Realm which manages the object, or `nil` if the object is unmanaged. + + Unmanaged objects are not confined to a thread and cannot be passed to methods expecting a + `RLMThreadConfined` object. + */ +@property (nonatomic, readonly, nullable) RLMRealm *realm; + +/// Indicates if the object can no longer be accessed because it is now invalid. +@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; + +@end + +/** + An object intended to be passed between threads containing a thread-safe reference to its + thread-confined object. + + To resolve a thread-safe reference on a target Realm on a different thread, pass to + `-[RLMRealm resolveThreadSafeReference:]`. + + @warning A `RLMThreadSafeReference` object must be resolved at most once. + Failing to resolve a `RLMThreadSafeReference` will result in the source version of the + Realm being pinned until the reference is deallocated. + + @note Prefer short-lived `RLMThreadSafeReference`s as the data for the version of the source Realm + will be retained until all references have been resolved or deallocated. + + @see `RLMThreadConfined` + @see `-[RLMRealm resolveThreadSafeReference:]` + */ +@interface RLMThreadSafeReference<__covariant Confined : id> : NSObject + +/** + Create a thread-safe reference to the thread-confined object. + + @param threadConfined The thread-confined object to create a thread-safe reference to. + + @note You may continue to use and access the thread-confined object after passing it to this + constructor. + */ ++ (instancetype)referenceWithThreadConfined:(Confined)threadConfined; + +/** + Indicates if the reference can no longer be resolved because an attempt to resolve it has already + occurred. References can only be resolved once. + */ +@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; + +#pragma mark - Unavailable Methods + +/** + `-[RLMThreadSafeReference init]` is not available because `RLMThreadSafeReference` cannot be + created directly. `RLMThreadSafeReference` instances must be obtained by calling + `-[RLMRealm resolveThreadSafeReference:]`. + */ +- (instancetype)init __attribute__((unavailable("RLMThreadSafeReference cannot be created directly"))); + +/** + `-[RLMThreadSafeReference new]` is not available because `RLMThreadSafeReference` cannot be + created directly. `RLMThreadSafeReference` instances must be obtained by calling + `-[RLMRealm resolveThreadSafeReference:]`. + */ ++ (instancetype)new __attribute__((unavailable("RLMThreadSafeReference cannot be created directly"))); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMThreadSafeReference_Private.hpp b/Pods/Realm/include/RLMThreadSafeReference_Private.hpp new file mode 100644 index 0000000000..5cf78edd4a --- /dev/null +++ b/Pods/Realm/include/RLMThreadSafeReference_Private.hpp @@ -0,0 +1,44 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import "RLMThreadSafeReference.h" +#import "thread_safe_reference.hpp" + +NS_ASSUME_NONNULL_BEGIN + +@protocol RLMThreadConfined_Private + +// Constructs a new `ThreadSafeReference` +- (std::unique_ptr)makeThreadSafeReference; + +// The extra information needed to construct an instance of this type from the Object Store type +@property (nonatomic, readonly, nullable) id objectiveCMetadata; + +// Constructs an new instance of this type ++ (nullable instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference + metadata:(nullable id)metadata + realm:(RLMRealm *)realm; +@end + +@interface RLMThreadSafeReference () + +- (nullable id)resolveReferenceInRealm:(RLMRealm *)realm; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Realm/include/RLMUpdateChecker.hpp b/Pods/Realm/include/RLMUpdateChecker.hpp new file mode 100644 index 0000000000..7f01ac7351 --- /dev/null +++ b/Pods/Realm/include/RLMUpdateChecker.hpp @@ -0,0 +1,20 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +// Asynchronously check for updates to Realm if running on a simulator +void RLMCheckForUpdates(); diff --git a/Pods/Realm/include/RLMUtil.hpp b/Pods/Realm/include/RLMUtil.hpp new file mode 100644 index 0000000000..f5674692da --- /dev/null +++ b/Pods/Realm/include/RLMUtil.hpp @@ -0,0 +1,177 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import +#import + +#import +#import +#import +#import +#import + +namespace realm { + class Mixed; +} + +@class RLMObjectSchema; +@class RLMProperty; + +namespace realm { + class RealmFileException; +} + +__attribute__((format(NSString, 1, 2))) +NSException *RLMException(NSString *fmt, ...); +NSException *RLMException(std::exception const& exception); + +NSError *RLMMakeError(RLMError code, std::exception const& exception); +NSError *RLMMakeError(RLMError code, const realm::util::File::AccessError&); +NSError *RLMMakeError(RLMError code, const realm::RealmFileException&); +NSError *RLMMakeError(std::system_error const& exception); + +void RLMSetErrorOrThrow(NSError *error, NSError **outError); + +// returns if the object can be inserted as the given type +BOOL RLMIsObjectValidForProperty(id obj, RLMProperty *prop); +// throw an exception if the object is not a valid value for the property +void RLMValidateValueForProperty(id obj, RLMObjectSchema *objectSchema, + RLMProperty *prop, bool validateObjects=false); +BOOL RLMValidateValue(id value, RLMPropertyType type, bool optional, bool array, + NSString *objectClassName); + +void RLMThrowTypeError(id obj, RLMObjectSchema *objectSchema, RLMProperty *prop); + +// gets default values for the given schema (+defaultPropertyValues) +// merges with native property defaults if Swift class +NSDictionary *RLMDefaultValuesForObjectSchema(RLMObjectSchema *objectSchema); + +BOOL RLMIsDebuggerAttached(); +BOOL RLMIsRunningInPlayground(); + +// C version of isKindOfClass +static inline BOOL RLMIsKindOfClass(Class class1, Class class2) { + while (class1) { + if (class1 == class2) return YES; + class1 = class_getSuperclass(class1); + } + return NO; +} + +template +static inline T *RLMDynamicCast(__unsafe_unretained id obj) { + if ([obj isKindOfClass:[T class]]) { + return obj; + } + return nil; +} + +static inline id RLMCoerceToNil(__unsafe_unretained id obj) { + if (static_cast(obj) == NSNull.null) { + return nil; + } + else if (__unsafe_unretained auto optional = RLMDynamicCast(obj)) { + return RLMCoerceToNil(RLMGetOptional(optional)); + } + return obj; +} + +template +static inline T RLMCoerceToNil(__unsafe_unretained T obj) { + return RLMCoerceToNil(static_cast(obj)); +} + +// String conversion utilities +static inline NSString * RLMStringDataToNSString(realm::StringData stringData) { + static_assert(sizeof(NSUInteger) >= sizeof(size_t), + "Need runtime overflow check for size_t to NSUInteger conversion"); + if (stringData.is_null()) { + return nil; + } + else { + return [[NSString alloc] initWithBytes:stringData.data() + length:stringData.size() + encoding:NSUTF8StringEncoding]; + } +} + +static inline realm::StringData RLMStringDataWithNSString(__unsafe_unretained NSString *const string) { + static_assert(sizeof(size_t) >= sizeof(NSUInteger), + "Need runtime overflow check for NSUInteger to size_t conversion"); + return realm::StringData(string.UTF8String, + [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); +} + +// Binary conversion utilities +static inline NSData *RLMBinaryDataToNSData(realm::BinaryData binaryData) { + return binaryData ? [NSData dataWithBytes:binaryData.data() length:binaryData.size()] : nil; +} + +static inline realm::BinaryData RLMBinaryDataForNSData(__unsafe_unretained NSData *const data) { + // this is necessary to ensure that the empty NSData isn't treated by core as the null realm::BinaryData + // because data.bytes == 0 when data.length == 0 + // the casting bit ensures that we create a data with a non-null pointer + auto bytes = static_cast(data.bytes) ?: static_cast((__bridge void *)data); + return realm::BinaryData(bytes, data.length); +} + +// Date conversion utilities +// These use the reference date and shift the seconds rather than just getting +// the time interval since the epoch directly to avoid losing sub-second precision +static inline NSDate *RLMTimestampToNSDate(realm::Timestamp ts) NS_RETURNS_RETAINED { + if (ts.is_null()) + return nil; + auto timeInterval = ts.get_seconds() - NSTimeIntervalSince1970 + ts.get_nanoseconds() / 1'000'000'000.0; + return [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:timeInterval]; +} + +static inline realm::Timestamp RLMTimestampForNSDate(__unsafe_unretained NSDate *const date) { + if (!date) + return {}; + auto timeInterval = date.timeIntervalSinceReferenceDate; + if (isnan(timeInterval)) + return {0, 0}; // Arbitrary choice + + // Clamp dates that we can't represent as a Timestamp to the maximum value + if (timeInterval >= std::numeric_limits::max() - NSTimeIntervalSince1970) + return {std::numeric_limits::max(), 1'000'000'000 - 1}; + if (timeInterval - NSTimeIntervalSince1970 < std::numeric_limits::min()) + return {std::numeric_limits::min(), -1'000'000'000 + 1}; + + auto seconds = static_cast(timeInterval); + auto nanoseconds = static_cast((timeInterval - seconds) * 1'000'000'000.0); + seconds += static_cast(NSTimeIntervalSince1970); + + // Seconds and nanoseconds have to have the same sign + if (nanoseconds < 0 && seconds > 0) { + nanoseconds += 1'000'000'000; + --seconds; + } + return {seconds, nanoseconds}; +} + +static inline NSUInteger RLMConvertNotFound(size_t index) { + return index == realm::not_found ? NSNotFound : index; +} + +id RLMMixedToObjc(realm::Mixed const& value); + +// Given a bundle identifier, return the base directory on the disk within which Realm database and support files should +// be stored. +NSString *RLMDefaultDirectoryForBundleIdentifier(NSString *bundleIdentifier); diff --git a/Pods/Realm/include/Realm.h b/Pods/Realm/include/Realm.h new file mode 100644 index 0000000000..f460336bb2 --- /dev/null +++ b/Pods/Realm/include/Realm.h @@ -0,0 +1,41 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import diff --git a/Pods/Realm/include/binding_callback_thread_observer.hpp b/Pods/Realm/include/binding_callback_thread_observer.hpp new file mode 100644 index 0000000000..e956349b20 --- /dev/null +++ b/Pods/Realm/include/binding_callback_thread_observer.hpp @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_OS_BINDING_CALLBACK_THREAD_OBSERVER_HPP +#define REALM_OS_BINDING_CALLBACK_THREAD_OBSERVER_HPP + +#include + +namespace realm { +// Interface for bindings interested in registering callbacks before/after the ObjectStore thread runs. +// This is for example helpful to attach/detach the pthread to the JavaVM in order to be able to perform JNI calls. +class BindingCallbackThreadObserver { +public: + // This method is called just before the thread is started + virtual void did_create_thread() = 0; + + // This method is called just before the thread is being destroyed + virtual void will_destroy_thread() = 0; + + // This method is called with any exception throws by client.run(). + virtual void handle_error(std::exception const& e) = 0; +}; + +extern BindingCallbackThreadObserver* g_binding_callback_thread_observer; +} + +#endif // REALM_OS_BINDING_CALLBACK_THREAD_OBSERVER_HPP diff --git a/Pods/Realm/include/binding_context.hpp b/Pods/Realm/include/binding_context.hpp new file mode 100644 index 0000000000..8d7532cb6c --- /dev/null +++ b/Pods/Realm/include/binding_context.hpp @@ -0,0 +1,185 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef BINDING_CONTEXT_HPP +#define BINDING_CONTEXT_HPP + +#include "index_set.hpp" + +#include +#include +#include + +namespace realm { +// BindingContext is the extension point for adding binding-specific behavior to +// a SharedRealm. It can be used to store additional data associated with the +// Realm which is needed by the binding, and there are several methods which +// can be overridden to receive notifications of state changes within the Realm. +// +// A simple implementation which lets the user register functions to be +// called on refresh could look like the following: +// +// class BindingContextImplementation : public BindingContext { +// public: +// // A token returned from add_notification that can be used to remove the +// // notification later +// struct token : private std::list>::iterator { +// token(std::list>::iterator it) : std::list>::iterator(it) { } +// friend class DelegateImplementation; +// }; +// +// token add_notification(std::function func) +// { +// m_registered_notifications.push_back(std::move(func)); +// return token(std::prev(m_registered_notifications.end())); +// } +// +// void remove_notification(token entry) +// { +// m_registered_notifications.erase(entry); +// } +// +// // Override the did_change method to call each registered notification +// void did_change(std::vector const&, std::vector const&, bool) override +// { +// // Loop oddly so that unregistering a notification from within the +// // registered function works +// for (auto it = m_registered_notifications.begin(); it != m_registered_notifications.end(); ) { +// (*it++)(); +// } +// } +// +// private: +// std::list> m_registered_notifications; +// }; +class Realm; +class Schema; +class BindingContext { +public: + virtual ~BindingContext() = default; + + std::weak_ptr realm; + + // If the user adds a notification handler to the Realm, will it ever + // actually be called? + virtual bool can_deliver_notifications() const noexcept { return true; } + + // Called when the Realm is about to send notifications about Realm, + // Collection or Object changes. This method will be called even if + // no notification callbacks have been registered. + virtual void will_send_notifications() { } + + // Called when the Realm is done sending all change notifications. This method + // will be called even if no notification callbacks have been registered. + virtual void did_send_notifications() { } + + // Called by the Realm when refresh called or a notification arrives which + // is triggered through write transaction committed by itself or a different + // Realm instance. + virtual void before_notify() { } + + // Called by the Realm when a write transaction is committed to the file by + // a different Realm instance (possibly in a different process) + virtual void changes_available() { } + + struct ObserverState; + + // Override this function if you want to receive detailed information about + // external changes to a specific set of objects. + // This is called before each operation which may advance the read + // transaction to include + // ObserverStates for each row for which detailed change information is + // desired. + virtual std::vector get_observed_rows() { return {}; } + + // Called immediately before the read transaction is advanced if detailed + // change information was requested (by returning a non-empty array from + // get_observed_rows()). + // The observers vector is the vector returned by get_observed_row(), + // updated with change information. The invalidated vector is a list of the + // `info` fields of observed rows which will be deleted. + virtual void will_change(std::vector const& observers, + std::vector const& invalidated); + + // Called immediately after the read transaction version is advanced. Unlike + // will_change(), this is called even if detailed change information was not + // requested or if the Realm is not actually in a read transaction, although + // both vectors will be empty in that case. + virtual void did_change(std::vector const& observers, + std::vector const& invalidated, + bool version_changed=true); + + // Called immediately after the corresponding Realm's schema is changed through + // update_schema()/set_schema_subset() or the schema is changed by another Realm + // instance. The parameter is a schema reference which is the same as the return + // value of Realm::schema(). + virtual void schema_did_change(Schema const&) {} + + // Change information for a single field of a row + struct ColumnInfo { + // The index of this column prior to the changes in the tracked + // transaction, or -1 for newly inserted columns. + size_t initial_column_index = -1; + // What kind of change occurred? + // Always Set or None for everything but LinkList columns. + enum class Kind { + None, // No change + Set, // The value or entries at `indices` were assigned to + Insert, // New values were inserted at each of the indices given + Remove, // Values were removed at each of the indices given + SetAll // The entire LinkList has been replaced with a new set of values + } kind = Kind::None; + // The indices where things happened for Set, Insert and Remove on + // LinkList columns. Not used for other types or for None or SetAll. + IndexSet indices; + }; + + // Information about an observed row in a table + // + // Each object which needs detailed change information should have an + // ObserverState entry in the vector returned from get_observed_rows(), with + // the initial table and row indexes set (and optionally the info field). + // The Realm parses the transaction log, and populates the `changes` vector + // in each ObserverState with information about what changes were made. + struct ObserverState { + // Initial table and row which is observed + // May be updated by row insertions and removals + size_t table_ndx; + size_t row_ndx; + + // Opaque userdata for the delegate's use + void* info; + + // Populated with information about which columns were changed + // May be shorter than the actual number of columns if the later columns + // are not modified + std::vector changes; + + // Simple lexographic ordering + friend bool operator<(ObserverState const& lft, ObserverState const& rgt) + { + return std::tie(lft.table_ndx, lft.row_ndx) < std::tie(rgt.table_ndx, rgt.row_ndx); + } + }; +}; + +inline void BindingContext::will_change(std::vector const&, std::vector const&) { } +inline void BindingContext::did_change(std::vector const&, std::vector const&, bool) { } +} // namespace realm + +#endif /* BINDING_CONTEXT_HPP */ diff --git a/Pods/Realm/include/collection_notifications.hpp b/Pods/Realm/include/collection_notifications.hpp new file mode 100644 index 0000000000..919e8b465a --- /dev/null +++ b/Pods/Realm/include/collection_notifications.hpp @@ -0,0 +1,181 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2016 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_COLLECTION_NOTIFICATIONS_HPP +#define REALM_COLLECTION_NOTIFICATIONS_HPP + +#include "index_set.hpp" +#include "util/atomic_shared_ptr.hpp" + +#include +#include +#include +#include + +namespace realm { +namespace _impl { + class CollectionNotifier; +} + +// A token which keeps an asynchronous query alive +struct NotificationToken { + NotificationToken() = default; + NotificationToken(std::shared_ptr<_impl::CollectionNotifier> notifier, uint64_t token); + ~NotificationToken(); + + NotificationToken(NotificationToken&&); + NotificationToken& operator=(NotificationToken&&); + + NotificationToken(NotificationToken const&) = delete; + NotificationToken& operator=(NotificationToken const&) = delete; + + void suppress_next(); + +private: + util::AtomicSharedPtr<_impl::CollectionNotifier> m_notifier; + uint64_t m_token; +}; + +struct CollectionChangeSet { + struct Move { + size_t from; + size_t to; + + bool operator==(Move m) const noexcept { return from == m.from && to == m.to; } + }; + + // Indices which were removed from the _old_ collection + IndexSet deletions; + + // Indices in the _new_ collection which are new insertions + IndexSet insertions; + + // Indices of objects in the _old_ collection which were modified + IndexSet modifications; + + // Indices in the _new_ collection which were modified. This will always + // have the same number of indices as `modifications` and conceptually + // represents the same entries, just in different versions of the collection. + // It exists for the sake of code which finds it easier to process + // modifications after processing deletions and insertions rather than before. + IndexSet modifications_new; + + // Rows in the collection which moved. + // + // Every `from` index will also be present in `deletions` and every `to` + // index will be present in `insertions`. + // + // This is currently not reliably calculated for all types of collections. A + // reported move will always actually be a move, but there may also be + // unreported moves which show up only as a delete/insert pair. + std::vector moves; + + // Per-column version of `modifications` + std::vector columns; + + bool empty() const noexcept + { + return deletions.empty() && insertions.empty() && modifications.empty() + && modifications_new.empty() && moves.empty(); + } +}; + +// A type-erasing wrapper for the callback for collection notifications. Can be +// constructed with either any callable compatible with the signature +// `void (CollectionChangeSet, std::exception_ptr)`, an object with member +// functions `void before(CollectionChangeSet)`, `void after(CollectionChangeSet)`, +// `void error(std::exception_ptr)`, or a pointer to such an object. If a pointer +// is given, the caller is responsible for ensuring that the pointed-to object +// outlives the collection. +class CollectionChangeCallback { +public: + CollectionChangeCallback(std::nullptr_t={}) { } + + template + CollectionChangeCallback(Callback cb) : m_impl(make_impl(std::move(cb))) { } + template + CollectionChangeCallback& operator=(Callback cb) { m_impl = make_impl(std::move(cb)); return *this; } + + // Explicitly default the copy/move constructors as otherwise they'll use + // the above ones and add an extra layer of wrapping + CollectionChangeCallback(CollectionChangeCallback&&) = default; + CollectionChangeCallback(CollectionChangeCallback const&) = default; + CollectionChangeCallback& operator=(CollectionChangeCallback&&) = default; + CollectionChangeCallback& operator=(CollectionChangeCallback const&) = default; + + void before(CollectionChangeSet const& c) { m_impl->before(c); } + void after(CollectionChangeSet const& c) { m_impl->after(c); } + void error(std::exception_ptr e) { m_impl->error(e); } + + explicit operator bool() const { return !!m_impl; } + +private: + struct Base { + virtual void before(CollectionChangeSet const&)=0; + virtual void after(CollectionChangeSet const&)=0; + virtual void error(std::exception_ptr)=0; + }; + + template()(CollectionChangeSet(), std::exception_ptr()))> + std::shared_ptr make_impl(Callback cb) + { + return std::make_shared>(std::move(cb)); + } + + template().after(CollectionChangeSet())), typename = void> + std::shared_ptr make_impl(Callback cb) + { + return std::make_shared>(std::move(cb)); + } + + template().after(CollectionChangeSet())), typename = void> + std::shared_ptr make_impl(Callback* cb) + { + return std::make_shared>(cb); + } + + template + struct Impl : public Base { + T impl; + Impl(T impl) : impl(std::move(impl)) { } + void before(CollectionChangeSet const&) override { } + void after(CollectionChangeSet const& change) override { impl(change, {}); } + void error(std::exception_ptr error) override { impl({}, error); } + }; + template + struct Impl2 : public Base { + T impl; + Impl2(T impl) : impl(std::move(impl)) { } + void before(CollectionChangeSet const& c) override { impl.before(c); } + void after(CollectionChangeSet const& c) override { impl.after(c); } + void error(std::exception_ptr error) override { impl.error(error); } + }; + template + struct Impl3 : public Base { + T* impl; + Impl3(T* impl) : impl(impl) { } + void before(CollectionChangeSet const& c) override { impl->before(c); } + void after(CollectionChangeSet const& c) override { impl->after(c); } + void error(std::exception_ptr error) override { impl->error(error); } + }; + + std::shared_ptr m_impl; +}; +} // namespace realm + +#endif // REALM_COLLECTION_NOTIFICATIONS_HPP diff --git a/Pods/Realm/include/core/realm.hpp b/Pods/Realm/include/core/realm.hpp new file mode 100644 index 0000000000..7ede53fccd --- /dev/null +++ b/Pods/Realm/include/core/realm.hpp @@ -0,0 +1,30 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_HPP +#define REALM_HPP + +#include +#include +#include +#include +#include +#include +#include + +#endif // REALM_HPP diff --git a/Pods/Realm/include/core/realm/alloc.hpp b/Pods/Realm/include/core/realm/alloc.hpp new file mode 100644 index 0000000000..157d2445b5 --- /dev/null +++ b/Pods/Realm/include/core/realm/alloc.hpp @@ -0,0 +1,387 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ALLOC_HPP +#define REALM_ALLOC_HPP + +#include +#include +#include + +#include +#include +#include + +namespace realm { + +class Allocator; + +class Replication; + +using ref_type = size_t; + +int_fast64_t from_ref(ref_type) noexcept; +ref_type to_ref(int_fast64_t) noexcept; +int64_t to_int64(size_t value) noexcept; + +class MemRef { +public: + MemRef() noexcept; + ~MemRef() noexcept; + + MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept; + MemRef(ref_type ref, Allocator& alloc) noexcept; + + char* get_addr(); + ref_type get_ref(); + void set_ref(ref_type ref); + void set_addr(char* addr); + +private: + char* m_addr; + ref_type m_ref; +#if REALM_ENABLE_MEMDEBUG + // Allocator that created m_ref. Used to verify that the ref is valid whenever you call + // get_ref()/get_addr and that it e.g. has not been free'ed + const Allocator* m_alloc = nullptr; +#endif +}; + + +/// The common interface for Realm allocators. +/// +/// A Realm allocator must associate a 'ref' to each allocated +/// object and be able to efficiently map any 'ref' to the +/// corresponding memory address. The 'ref' is an integer and it must +/// always be divisible by 8. Also, a value of zero is used to +/// indicate a null-reference, and must therefore never be returned by +/// Allocator::alloc(). +/// +/// The purpose of the 'refs' is to decouple the memory reference from +/// the actual address and thereby allowing objects to be relocated in +/// memory without having to modify stored references. +/// +/// \sa SlabAlloc +class Allocator { +public: + /// The specified size must be divisible by 8, and must not be + /// zero. + /// + /// \throw std::bad_alloc If insufficient memory was available. + MemRef alloc(size_t size); + + /// Calls do_realloc(). + /// + /// Note: The underscore has been added because the name `realloc` + /// would conflict with a macro on the Windows platform. + MemRef realloc_(ref_type, const char* addr, size_t old_size, size_t new_size); + + /// Calls do_free(). + /// + /// Note: The underscore has been added because the name `free + /// would conflict with a macro on the Windows platform. + void free_(ref_type, const char* addr) noexcept; + + /// Shorthand for free_(mem.get_ref(), mem.get_addr()). + void free_(MemRef mem) noexcept; + + /// Calls do_translate(). + char* translate(ref_type ref) const noexcept; + + /// Returns true if, and only if the object at the specified 'ref' + /// is in the immutable part of the memory managed by this + /// allocator. The method by which some objects become part of the + /// immuatble part is entirely up to the class that implements + /// this interface. + bool is_read_only(ref_type) const noexcept; + + /// Returns a simple allocator that can be used with free-standing + /// Realm objects (such as a free-standing table). A + /// free-standing object is one that is not part of a Group, and + /// therefore, is not part of an actual database. + static Allocator& get_default() noexcept; + + virtual ~Allocator() noexcept; + + // Disable copying. Copying an allocator can produce double frees. + Allocator(const Allocator&) = delete; + Allocator& operator=(const Allocator&) = delete; + + virtual void verify() const = 0; + +#ifdef REALM_DEBUG + /// Terminate the program precisely when the specified 'ref' is + /// freed (or reallocated). You can use this to detect whether the + /// ref is freed (or reallocated), and even to get a stacktrace at + /// the point where it happens. Call watch(0) to stop watching + /// that ref. + void watch(ref_type ref) + { + m_debug_watch = ref; + } +#endif + + Replication* get_replication() noexcept; + +protected: + size_t m_baseline = 0; // Separation line between immutable and mutable refs. + + Replication* m_replication = nullptr; + + ref_type m_debug_watch = 0; + + /// The specified size must be divisible by 8, and must not be + /// zero. + /// + /// \throw std::bad_alloc If insufficient memory was available. + virtual MemRef do_alloc(const size_t size) = 0; + + /// The specified size must be divisible by 8, and must not be + /// zero. + /// + /// The default version of this function simply allocates a new + /// chunk of memory, copies over the old contents, and then frees + /// the old chunk. + /// + /// \throw std::bad_alloc If insufficient memory was available. + virtual MemRef do_realloc(ref_type, char* addr, size_t old_size, size_t new_size) = 0; + + /// Release the specified chunk of memory. + virtual void do_free(ref_type, char* addr) noexcept = 0; + + /// Map the specified \a ref to the corresponding memory + /// address. Note that if is_read_only(ref) returns true, then the + /// referenced object is to be considered immutable, and it is + /// then entirely the responsibility of the caller that the memory + /// is not modified by way of the returned memory pointer. + virtual char* do_translate(ref_type ref) const noexcept = 0; + + Allocator() noexcept; + + // FIXME: This really doesn't belong in an allocator, but it is the best + // place for now, because every table has a pointer leading here. It would + // be more obvious to place it in Group, but that would add a runtime overhead, + // and access is time critical. + // + // This means that multiple threads that allocate Realm objects through the + // default allocator will share this variable, which is a logical design flaw + // that can make sync_if_needed() re-run queries even though it is not required. + // It must be atomic because it's shared. + std::atomic m_table_versioning_counter; + std::atomic m_latest_observed_counter; + + /// Bump the global version counter. This method should be called when + /// version bumping is initiated. Then following calls to should_propagate_version() + /// can be used to prune the version bumping. + void bump_global_version() noexcept; + + /// Determine if the "local_version" is out of sync, so that it should + /// be updated. In that case: also update it. Called from Table::bump_version + /// to control propagation of version updates on tables within the group. + bool should_propagate_version(uint_fast64_t& local_version) noexcept; + + /// Note the current global version has been observed. + void observe_version() noexcept; + + friend class Table; + friend class Group; +}; + +inline void Allocator::bump_global_version() noexcept +{ + if (m_latest_observed_counter == m_table_versioning_counter) + m_table_versioning_counter += 1; +} + + +inline void Allocator::observe_version() noexcept +{ + if (m_latest_observed_counter != m_table_versioning_counter) + m_latest_observed_counter.store(m_table_versioning_counter, std::memory_order_relaxed); +} + + +inline bool Allocator::should_propagate_version(uint_fast64_t& local_version) noexcept +{ + if (local_version != m_table_versioning_counter) { + local_version = m_table_versioning_counter; + return true; + } + else { + return false; + } +} + + +// Implementation: + +inline int_fast64_t from_ref(ref_type v) noexcept +{ + // Check that v is divisible by 8 (64-bit aligned). + REALM_ASSERT_DEBUG(v % 8 == 0); + + static_assert(std::is_same::value, + "If ref_type changes, from_ref and to_ref should probably be updated"); + + // Make sure that we preserve the bit pattern of the ref_type (without sign extension). + return util::from_twos_compl(uint_fast64_t(v)); +} + +inline ref_type to_ref(int_fast64_t v) noexcept +{ + // Check that v is divisible by 8 (64-bit aligned). + REALM_ASSERT_DEBUG(v % 8 == 0); + + // C++11 standard, paragraph 4.7.2 [conv.integral]: + // If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source + // integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two's + // complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is + // no truncation). - end note ] + static_assert(std::is_unsigned::value, + "If ref_type changes, from_ref and to_ref should probably be updated"); + return ref_type(v); +} + +inline int64_t to_int64(size_t value) noexcept +{ + // FIXME: Enable once we get clang warning flags correct + // REALM_ASSERT_DEBUG(value <= std::numeric_limits::max()); + return static_cast(value); +} + + +inline MemRef::MemRef() noexcept + : m_addr(nullptr) + , m_ref(0) +{ +} + +inline MemRef::~MemRef() noexcept +{ +} + +inline MemRef::MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept + : m_addr(addr) + , m_ref(ref) +{ + static_cast(alloc); +#if REALM_ENABLE_MEMDEBUG + m_alloc = &alloc; +#endif +} + +inline MemRef::MemRef(ref_type ref, Allocator& alloc) noexcept + : m_addr(alloc.translate(ref)) + , m_ref(ref) +{ + static_cast(alloc); +#if REALM_ENABLE_MEMDEBUG + m_alloc = &alloc; +#endif +} + +inline char* MemRef::get_addr() +{ +#if REALM_ENABLE_MEMDEBUG + // Asserts if the ref has been freed + m_alloc->translate(m_ref); +#endif + return m_addr; +} + +inline ref_type MemRef::get_ref() +{ +#if REALM_ENABLE_MEMDEBUG + // Asserts if the ref has been freed + m_alloc->translate(m_ref); +#endif + return m_ref; +} + +inline void MemRef::set_ref(ref_type ref) +{ +#if REALM_ENABLE_MEMDEBUG + // Asserts if the ref has been freed + m_alloc->translate(ref); +#endif + m_ref = ref; +} + +inline void MemRef::set_addr(char* addr) +{ + m_addr = addr; +} + +inline MemRef Allocator::alloc(size_t size) +{ + return do_alloc(size); +} + +inline MemRef Allocator::realloc_(ref_type ref, const char* addr, size_t old_size, size_t new_size) +{ +#ifdef REALM_DEBUG + if (ref == m_debug_watch) + REALM_TERMINATE("Allocator watch: Ref was reallocated"); +#endif + return do_realloc(ref, const_cast(addr), old_size, new_size); +} + +inline void Allocator::free_(ref_type ref, const char* addr) noexcept +{ +#ifdef REALM_DEBUG + if (ref == m_debug_watch) + REALM_TERMINATE("Allocator watch: Ref was freed"); +#endif + return do_free(ref, const_cast(addr)); +} + +inline void Allocator::free_(MemRef mem) noexcept +{ + free_(mem.get_ref(), mem.get_addr()); +} + +inline char* Allocator::translate(ref_type ref) const noexcept +{ + return do_translate(ref); +} + +inline bool Allocator::is_read_only(ref_type ref) const noexcept +{ + REALM_ASSERT_DEBUG(ref != 0); + REALM_ASSERT_DEBUG(m_baseline != 0); // Attached SlabAlloc + return ref < m_baseline; +} + +inline Allocator::Allocator() noexcept +{ + m_table_versioning_counter = 0; + m_latest_observed_counter = 0; +} + +inline Allocator::~Allocator() noexcept +{ +} + +inline Replication* Allocator::get_replication() noexcept +{ + return m_replication; +} + +} // namespace realm + +#endif // REALM_ALLOC_HPP diff --git a/Pods/Realm/include/core/realm/alloc_slab.hpp b/Pods/Realm/include/core/realm/alloc_slab.hpp new file mode 100644 index 0000000000..8024a9b630 --- /dev/null +++ b/Pods/Realm/include/core/realm/alloc_slab.hpp @@ -0,0 +1,694 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ALLOC_SLAB_HPP +#define REALM_ALLOC_SLAB_HPP + +#include // unint8_t etc +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace realm { + +// Pre-declarations +class Group; +class GroupWriter; + + +/// Thrown by Group and SharedGroup constructors if the specified file +/// (or memory buffer) does not appear to contain a valid Realm +/// database. +struct InvalidDatabase; + + +/// The allocator that is used to manage the memory of a Realm +/// group, i.e., a Realm database. +/// +/// Optionally, it can be attached to an pre-existing database (file +/// or memory buffer) which then becomes an immuatble part of the +/// managed memory. +/// +/// To attach a slab allocator to a pre-existing database, call +/// attach_file() or attach_buffer(). To create a new database +/// in-memory, call attach_empty(). +/// +/// For efficiency, this allocator manages its mutable memory as a set +/// of slabs. +class SlabAlloc : public Allocator { +public: + ~SlabAlloc() noexcept override; + SlabAlloc(); + + // Disable copying. Copying an allocator can produce double frees. + SlabAlloc(const SlabAlloc&) = delete; + SlabAlloc& operator=(const SlabAlloc&) = delete; + + /// \struct Config + /// \brief Storage for combining setup flags for initialization to + /// the SlabAlloc. + /// + /// \var Config::is_shared + /// Must be true if, and only if we are called on behalf of SharedGroup. + /// + /// \var Config::read_only + /// Open the file in read-only mode. This implies \a Config::no_create. + /// + /// \var Config::no_create + /// Fail if the file does not already exist. + /// + /// \var Config::skip_validate + /// Skip validation of file header. In a + /// set of overlapping SharedGroups, only the first one (the one + /// that creates/initlializes the coordination file) may validate + /// the header, otherwise it will result in a race condition. + /// + /// \var Config::encryption_key + /// 32-byte key to use to encrypt and decrypt the backing storage, + /// or nullptr to disable encryption. + /// + /// \var Config::session_initiator + /// If set, the caller is the session initiator and + /// guarantees exclusive access to the file. If attaching in + /// read/write mode, the file is modified: files on streaming form + /// is changed to non-streaming form, and if needed the file size + /// is adjusted to match mmap boundaries. + /// Must be set to false if is_shared is false. + /// + /// \var Config::clear_file + /// Always initialize the file as if it was a newly + /// created file and ignore any pre-existing contents. Requires that + /// Config::session_initiator be true as well. + struct Config { + bool is_shared = false; + bool read_only = false; + bool no_create = false; + bool skip_validate = false; + bool session_initiator = false; + bool clear_file = false; + const char* encryption_key = nullptr; + }; + + struct Retry { + }; + + /// \brief Attach this allocator to the specified file. + /// + /// It is an error if this function is called at a time where the specified + /// Realm file (file system inode) is modified asynchronously. + /// + /// In non-shared mode (when this function is called on behalf of a + /// free-standing Group instance), it is the responsibility of the + /// application to ensure that the Realm file is not modified concurrently + /// from any other thread or process. + /// + /// In shared mode (when this function is called on behalf of a SharedGroup + /// instance), the caller (SharedGroup::do_open()) must take steps to ensure + /// cross-process mutual exclusion. + /// + /// Except for \a file_path, the parameters are passed in through a + /// configuration object. + /// + /// \return The `ref` of the root node, or zero if there is none. + /// + /// Please note that attach_file can fail to attach to a file due to a + /// collision with a writer extending the file. This can only happen if the + /// caller is *not* the session initiator. When this happens, attach_file() + /// throws SlabAlloc::Retry, and the caller must retry the call. The caller + /// should check if it has become the session initiator before retrying. + /// This can happen if the conflicting thread (or process) terminates or + /// crashes before the next retry. + /// + /// \throw util::File::AccessError + /// \throw SlabAlloc::Retry + ref_type attach_file(const std::string& file_path, Config& cfg); + + /// Get the attached file. Only valid when called on an allocator with + /// an attached file. + util::File& get_file(); + + /// Attach this allocator to the specified memory buffer. + /// + /// It is an error to call this function on an attached + /// allocator. Doing so will result in undefined behavor. + /// + /// \return The `ref` of the root node, or zero if there is none. + /// + /// \sa own_buffer() + /// + /// \throw InvalidDatabase + ref_type attach_buffer(const char* data, size_t size); + + /// Reads file format from file header. Must be called from within a write + /// transaction. + int get_committed_file_format_version() const noexcept; + + /// Attach this allocator to an empty buffer. + /// + /// It is an error to call this function on an attached + /// allocator. Doing so will result in undefined behavor. + void attach_empty(); + + /// Detach from a previously attached file or buffer. + /// + /// This function does not reset free space tracking. To + /// completely reset the allocator, you must also call + /// reset_free_space_tracking(). + /// + /// This function has no effect if the allocator is already in the + /// detached state (idempotency). + void detach() noexcept; + + class DetachGuard; + + /// If a memory buffer has been attached using attach_buffer(), + /// mark it as owned by this slab allocator. Behaviour is + /// undefined if this function is called on a detached allocator, + /// one that is not attached using attach_buffer(), or one for + /// which this function has already been called during the latest + /// attachment. + void own_buffer() noexcept; + + /// Returns true if, and only if this allocator is currently + /// in the attached state. + bool is_attached() const noexcept; + + /// Returns true if, and only if this allocator is currently in + /// the attached state and attachment was not established using + /// attach_empty(). + bool nonempty_attachment() const noexcept; + + /// Reserve disk space now to avoid allocation errors at a later + /// point in time, and to minimize on-disk fragmentation. In some + /// cases, less fragmentation translates into improved + /// performance. On flash or SSD-drives this is likely a waste. + /// + /// Note: File::prealloc() may misbehave under race conditions (see + /// documentation of File::prealloc()). For that reason, to avoid race + /// conditions, when this allocator is used in a transactional mode, this + /// function may be called only when the caller has exclusive write + /// access. In non-transactional mode it is the responsibility of the user + /// to ensure non-concurrent file mutation. + /// + /// This function will call File::sync(). + /// + /// It is an error to call this function on an allocator that is not + /// attached to a file. Doing so will result in undefined behavior. + void resize_file(size_t new_file_size); + +#ifdef REALM_DEBUG + /// Deprecated method, only called from a unit test + /// + /// WARNING: This method is NOT thread safe on multiple platforms; see + /// File::prealloc(). + /// + /// Reserve disk space now to avoid allocation errors at a later point in + /// time, and to minimize on-disk fragmentation. In some cases, less + /// fragmentation translates into improved performance. On SSD-drives + /// preallocation is likely a waste. + /// + /// When supported by the system, a call to this function will make the + /// database file at least as big as the specified size, and cause space on + /// the target device to be allocated (note that on many systems on-disk + /// allocation is done lazily by default). If the file is already bigger + /// than the specified size, the size will be unchanged, and on-disk + /// allocation will occur only for the initial section that corresponds to + /// the specified size. + /// + /// This function will call File::sync() if it changes the size of the file. + /// + /// It is an error to call this function on an allocator that is not + /// attached to a file. Doing so will result in undefined behavior. + void reserve_disk_space(size_t size_in_bytes); +#endif + + /// Get the size of the attached database file or buffer in number + /// of bytes. This size is not affected by new allocations. After + /// attachment, it can only be modified by a call to update_reader_view(). + /// + /// It is an error to call this function on a detached allocator, + /// or one that was attached using attach_empty(). Doing so will + /// result in undefined behavior. + size_t get_baseline() const noexcept; + + /// Get the total amount of managed memory. This is the baseline plus the + /// sum of the sizes of the allocated slabs. It includes any free space. + /// + /// It is an error to call this function on a detached + /// allocator. Doing so will result in undefined behavior. + size_t get_total_size() const noexcept; + + /// Mark all mutable memory (ref-space outside the attached file) as free + /// space. + void reset_free_space_tracking(); + + /// Update the readers view of the file: + /// + /// Remap the attached file such that a prefix of the specified + /// size becomes available in memory. If sucessfull, + /// get_baseline() will return the specified new file size. + /// + /// It is an error to call this function on a detached allocator, + /// or one that was not attached using attach_file(). Doing so + /// will result in undefined behavior. + /// + /// The file_size argument must be aligned to a *section* boundary: + /// The database file is logically split into sections, each section + /// guaranteed to be mapped as a contiguous address range. The allocation + /// of memory in the file must ensure that no allocation crosses the + /// boundary between two sections. + /// + /// Clears any allocator specicific caching of address translations + /// and force any later address translations to trigger decryption if required. + void update_reader_view(size_t file_size); + + /// Returns true initially, and after a call to reset_free_space_tracking() + /// up until the point of the first call to SlabAlloc::alloc(). Note that a + /// call to SlabAlloc::alloc() corresponds to a mutation event. + bool is_free_space_clean() const noexcept; + + void verify() const override; +#ifdef REALM_DEBUG + void enable_debug(bool enable) + { + m_debug_out = enable; + } + bool is_all_free() const; + void print() const; +#endif + struct MappedFile; + +protected: + MemRef do_alloc(const size_t size) override; + MemRef do_realloc(ref_type, char*, size_t old_size, size_t new_size) override; + // FIXME: It would be very nice if we could detect an invalid free operation in debug mode + void do_free(ref_type, char*) noexcept override; + char* do_translate(ref_type) const noexcept override; + + /// Returns the first section boundary *above* the given position. + size_t get_upper_section_boundary(size_t start_pos) const noexcept; + + /// Returns the first section boundary *at or below* the given position. + size_t get_lower_section_boundary(size_t start_pos) const noexcept; + + /// Returns true if the given position is at a section boundary + bool matches_section_boundary(size_t pos) const noexcept; + + /// Returns the index of the section holding a given address. + /// The section index is determined solely by the minimal section size, + /// and does not necessarily reflect the mapping. A mapping may + /// cover multiple sections - the initial mapping often does. + size_t get_section_index(size_t pos) const noexcept; + + /// Reverse: get the base offset of a section at a given index. Since the + /// computation is very time critical, this method just looks it up in + /// a table. The actual computation and setup of that table is done + /// during initialization with the help of compute_section_base() below. + inline size_t get_section_base(size_t index) const noexcept; + + /// Actually compute the starting offset of a section. Only used to initialize + /// a table of predefined results, which are then used by get_section_base(). + size_t compute_section_base(size_t index) const noexcept; + + /// Find a possible allocation of 'request_size' that will fit into a section + /// which is inside the range from 'start_pos' to 'start_pos'+'free_chunk_size' + /// If found return the position, if not return 0. + size_t find_section_in_range(size_t start_pos, size_t free_chunk_size, size_t request_size) const noexcept; + +private: + void internal_invalidate_cache() noexcept; + enum AttachMode { + attach_None, // Nothing is attached + attach_OwnedBuffer, // We own the buffer (m_data = nullptr for empty buffer) + attach_UsersBuffer, // We do not own the buffer + attach_SharedFile, // On behalf of SharedGroup + attach_UnsharedFile // Not on behalf of SharedGroup + }; + + // A slab is a dynamically allocated contiguous chunk of memory used to + // extend the amount of space available for database node + // storage. Inter-node references are represented as file offsets + // (a.k.a. "refs"), and each slab creates an apparently seamless extension + // of this file offset addressable space. Slabes are stored as rows in the + // Slabs table in order of ascending file offsets. + struct Slab { + ref_type ref_end; + char* addr; + }; + struct Chunk { // describes a freed in-file block + ref_type ref; + size_t size; + }; + + // free blocks that are in the slab area are managed using the following structures: + // - FreeBlock: Placed at the start of any free space. Holds the 'ref' corresponding to + // the start of the space, and prev/next links used to place it in a size-specific + // freelist. + // - BetweenBlocks: Structure sitting between any two free OR allocated spaces. + // describes the size of the space before and after. + // Each slab (area obtained from the underlying system) has a terminating BetweenBlocks + // at the beginning and at the end of the Slab. + struct FreeBlock { + ref_type ref; // ref for this entry. Saves a reverse translate / representing links as refs + FreeBlock* prev; // circular doubly linked list + FreeBlock* next; + void clear_links() { prev = next = nullptr; } + void unlink(); + }; + struct BetweenBlocks { // stores sizes and used/free status of blocks before and after. + int32_t block_before_size; // negated if block is in use, + int32_t block_after_size; // positive if block is free - and zero at end + }; + + using FreeListMap = std::map; // log(N) addressing for larger blocks + FreeListMap m_block_map; + + // abstract notion of a freelist - used to hide whether a freelist + // is residing in the small blocks or the large blocks structures. + struct FreeList { + int size = 0; // size of every element in the list, 0 if not found + FreeListMap::iterator it; + bool found_something() { return size != 0; } + bool found_exact(int sz) { return size == sz; } + }; + + // simple helper functions for accessing/navigating blocks and betweenblocks (TM) + BetweenBlocks* bb_before(FreeBlock* entry) const { + return reinterpret_cast(entry) - 1; + } + BetweenBlocks* bb_after(FreeBlock* entry) const { + auto bb = bb_before(entry); + size_t sz = bb->block_after_size; + char* addr = reinterpret_cast(entry) + sz; + return reinterpret_cast(addr); + } + FreeBlock* block_before(BetweenBlocks* bb) const { + size_t sz = bb->block_before_size; + if (sz <= 0) return nullptr; // only blocks that are not in use + char* addr = reinterpret_cast(bb) - sz; + return reinterpret_cast(addr); + } + FreeBlock* block_after(BetweenBlocks* bb) const { + if (bb->block_after_size <= 0) + return nullptr; + return reinterpret_cast(bb + 1); + } + int size_from_block(FreeBlock* entry) const { + return bb_before(entry)->block_after_size; + } + void mark_allocated(FreeBlock* entry); + // mark the entry freed in bordering BetweenBlocks. Also validate size. + void mark_freed(FreeBlock* entry, int size); + + // hook for the memory verifier in Group. + template + void for_all_free_entries(Func f) const; + + // Main entry points for alloc/free: + FreeBlock* allocate_block(int size); + void free_block(ref_type ref, FreeBlock* addr); + + // Searching/manipulating freelists + FreeList find(int size); + FreeList find_larger(FreeList hint, int size); + FreeBlock* pop_freelist_entry(FreeList list); + void push_freelist_entry(FreeBlock* entry); + void remove_freelist_entry(FreeBlock* element); + void rebuild_freelists_from_slab(); + void clear_freelists(); + + // grow the slab area to accommodate the requested size. + // returns a free block large enough to handle the request. + FreeBlock* grow_slab_for(int request_size); + // create a single free chunk with "BetweenBlocks" at both ends and a + // single free chunk between them. This free chunk will be of size: + // slab_size - 2 * sizeof(BetweenBlocks) + FreeBlock* slab_to_entry(Slab slab, ref_type ref_start); + + // breaking/merging of blocks + FreeBlock* get_prev_block_if_mergeable(FreeBlock* block); + FreeBlock* get_next_block_if_mergeable(FreeBlock* block); + // break 'block' to give it 'new_size'. Return remaining block. + // If the block is too small to split, return nullptr. + FreeBlock* break_block(FreeBlock* block, int new_size); + FreeBlock* merge_blocks(FreeBlock* first, FreeBlock* second); + + // Values of each used bit in m_flags + enum { + flags_SelectBit = 1, + }; + + // 24 bytes + struct Header { + uint64_t m_top_ref[2]; // 2 * 8 bytes + // Info-block 8-bytes + uint8_t m_mnemonic[4]; // "T-DB" + uint8_t m_file_format[2]; // See `library_file_format` + uint8_t m_reserved; + // bit 0 of m_flags is used to select between the two top refs. + uint8_t m_flags; + }; + + // 16 bytes + struct StreamingFooter { + uint64_t m_top_ref; + uint64_t m_magic_cookie; + }; + + static_assert(sizeof(Header) == 24, "Bad header size"); + static_assert(sizeof(StreamingFooter) == 16, "Bad footer size"); + + static const Header empty_file_header; + static void init_streaming_header(Header*, int file_format_version); + + static const uint_fast64_t footer_magic_cookie = 0x3034125237E526C8ULL; + + // The mappings are shared, if they are from a file + std::shared_ptr m_file_mappings; + + // We are caching local copies of all the additional mappings to allow + // for lock-free lookup during ref->address translation (we do not need + // to cache the first mapping, because it is immutable) (well, all the + // mappings are immutable, but the array holding them is not - it may + // have to be relocated) + std::unique_ptr>[]> m_local_mappings; + size_t m_num_local_mappings = 0; + + const char* m_data = nullptr; + size_t m_initial_chunk_size = 0; + size_t m_initial_section_size = 0; + int m_section_shifts = 0; + std::unique_ptr m_section_bases; + size_t m_num_section_bases = 0; + AttachMode m_attach_mode = attach_None; + enum FeeeSpaceState { + free_space_Clean, + free_space_Dirty, + free_space_Invalid, + }; + + /// When set to free_space_Invalid, the free lists are no longer + /// up-to-date. This happens if do_free() or + /// reset_free_space_tracking() fails, presumably due to + /// std::bad_alloc being thrown during updating of the free space + /// list. In this this case, alloc(), realloc_(), and + /// get_free_read_only() must throw. This member is deliberately + /// placed here (after m_attach_mode) in the hope that it leads to + /// less padding between members due to alignment requirements. + FeeeSpaceState m_free_space_state = free_space_Clean; + + typedef std::vector slabs; + typedef std::vector chunks; + slabs m_slabs; + chunks m_free_read_only; + + bool m_debug_out = false; + struct hash_entry { + ref_type ref = 0; + const char* addr = nullptr; + size_t version = 0; + }; + mutable hash_entry cache[256]; + mutable size_t version = 1; + + /// Throws if free-lists are no longer valid. + size_t consolidate_free_read_only(); + /// Throws if free-lists are no longer valid. + const chunks& get_free_read_only() const; + + /// Throws InvalidDatabase if the file is not a Realm file, if the file is + /// corrupted, or if the specified encryption key is incorrect. This + /// function will not detect all forms of corruption, though. + void validate_buffer(const char* data, size_t len, const std::string& path); + void throw_header_exception(std::string msg, const Header& header, const std::string& path); + + static bool is_file_on_streaming_form(const Header& header); + /// Read the top_ref from the given buffer and set m_file_on_streaming_form + /// if the buffer contains a file in streaming form + static ref_type get_top_ref(const char* data, size_t len); + + class ChunkRefEq; + class ChunkRefEndEq; + class SlabRefEndEq; + static bool ref_less_than_slab_ref_end(ref_type, const Slab&) noexcept; + + Replication* get_replication() const noexcept + { + return m_replication; + } + void set_replication(Replication* r) noexcept + { + m_replication = r; + } + + friend class Group; + friend class SharedGroup; + friend class GroupWriter; +}; + +inline void SlabAlloc::internal_invalidate_cache() noexcept +{ + ++version; +} + +class SlabAlloc::DetachGuard { +public: + DetachGuard(SlabAlloc& alloc) noexcept + : m_alloc(&alloc) + { + } + ~DetachGuard() noexcept; + SlabAlloc* release() noexcept; + +private: + SlabAlloc* m_alloc; +}; + + +// Implementation: + +struct InvalidDatabase : util::File::AccessError { + InvalidDatabase(const std::string& msg, const std::string& path) + : util::File::AccessError(msg, path) + { + } +}; + +inline void SlabAlloc::own_buffer() noexcept +{ + REALM_ASSERT_3(m_attach_mode, ==, attach_UsersBuffer); + REALM_ASSERT(m_data); + REALM_ASSERT(m_file_mappings == nullptr); + m_attach_mode = attach_OwnedBuffer; +} + +inline bool SlabAlloc::is_attached() const noexcept +{ + return m_attach_mode != attach_None; +} + +inline bool SlabAlloc::nonempty_attachment() const noexcept +{ + return is_attached() && m_data; +} + +inline size_t SlabAlloc::get_baseline() const noexcept +{ + REALM_ASSERT_DEBUG(is_attached()); + return m_baseline; +} + +inline bool SlabAlloc::is_free_space_clean() const noexcept +{ + return m_free_space_state == free_space_Clean; +} + +inline SlabAlloc::DetachGuard::~DetachGuard() noexcept +{ + if (m_alloc) + m_alloc->detach(); +} + +inline SlabAlloc* SlabAlloc::DetachGuard::release() noexcept +{ + SlabAlloc* alloc = m_alloc; + m_alloc = nullptr; + return alloc; +} + +inline bool SlabAlloc::ref_less_than_slab_ref_end(ref_type ref, const Slab& slab) noexcept +{ + return ref < slab.ref_end; +} + +inline size_t SlabAlloc::get_upper_section_boundary(size_t start_pos) const noexcept +{ + return get_section_base(1 + get_section_index(start_pos)); +} + +inline size_t SlabAlloc::get_lower_section_boundary(size_t start_pos) const noexcept +{ + return get_section_base(get_section_index(start_pos)); +} + +inline bool SlabAlloc::matches_section_boundary(size_t pos) const noexcept +{ + return pos == get_lower_section_boundary(pos); +} + +inline size_t SlabAlloc::get_section_base(size_t index) const noexcept +{ + return m_section_bases[index]; +} + +template +void SlabAlloc::for_all_free_entries(Func f) const +{ + ref_type ref = m_baseline; + for (auto& e : m_slabs) { + BetweenBlocks* bb = reinterpret_cast(e.addr); + REALM_ASSERT(bb->block_before_size == 0); + while (1) { + int size = bb->block_after_size; + f(ref, sizeof(BetweenBlocks)); + ref += sizeof(BetweenBlocks); + if (size == 0) { + break; + } + if (size > 0) { // freeblock. + f(ref, size); + bb = reinterpret_cast(reinterpret_cast(bb) + sizeof(BetweenBlocks) + size); + ref += size; + } + else { + bb = reinterpret_cast(reinterpret_cast(bb) + sizeof(BetweenBlocks) - size); + ref -= size; + } + } + } +} + +} // namespace realm + +#endif // REALM_ALLOC_SLAB_HPP diff --git a/Pods/Realm/include/core/realm/array.hpp b/Pods/Realm/include/core/realm/array.hpp new file mode 100644 index 0000000000..e0c2684c8c --- /dev/null +++ b/Pods/Realm/include/core/realm/array.hpp @@ -0,0 +1,3104 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +/* +Searching: The main finding function is: + template + void find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState *state, Callback callback) const + + cond: One of Equal, NotEqual, Greater, etc. classes + Action: One of act_ReturnFirst, act_FindAll, act_Max, act_CallbackIdx, etc, constants + Callback: Optional function to call for each search result. Will be called if action == act_CallbackIdx + + find() will call find_action_pattern() or find_action() that again calls match() for each search result which + optionally calls callback(): + + find() -> find_action() -------> bool match() -> bool callback() + | ^ + +-> find_action_pattern()----+ + + If callback() returns false, find() will exit, otherwise it will keep searching remaining items in array. +*/ + +#ifndef REALM_ARRAY_HPP +#define REALM_ARRAY_HPP + +#include +#include // size_t +#include +#include +#include +#include + +#include // unint8_t etc + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + MMX: mmintrin.h + SSE: xmmintrin.h + SSE2: emmintrin.h + SSE3: pmmintrin.h + SSSE3: tmmintrin.h + SSE4A: ammintrin.h + SSE4.1: smmintrin.h + SSE4.2: nmmintrin.h +*/ +#ifdef REALM_COMPILER_SSE +#include // SSE2 +#include // SSE42 +#endif + +namespace realm { + +enum Action { + act_ReturnFirst, + act_Sum, + act_Max, + act_Min, + act_Count, + act_FindAll, + act_CallIdx, + act_CallbackIdx, + act_CallbackVal, + act_CallbackNone, + act_CallbackBoth, + act_Average +}; + +template +inline T no0(T v) +{ + return v == 0 ? 1 : v; +} + +/// Special index value. It has various meanings depending on +/// context. It is returned by some search functions to indicate 'not +/// found'. It is similar in function to std::string::npos. +const size_t npos = size_t(-1); + +const size_t max_array_size = 0x00ffffffL; // Maximum number of elements in an array +const size_t max_array_payload_aligned = 0x07ffffc0L; // Maximum number of bytes that the payload of an array can be + +/// Alias for realm::npos. +const size_t not_found = npos; + +// Pre-definitions +class Array; +class StringColumn; +class GroupWriter; +template +class QueryState; +namespace _impl { +class ArrayWriterBase; +} + + +struct MemStats { + size_t allocated = 0; + size_t used = 0; + size_t array_count = 0; +}; + +#ifdef REALM_DEBUG +template +std::basic_ostream& operator<<(std::basic_ostream& out, MemStats stats); +#endif + + +// Stores a value obtained from Array::get(). It is a ref if the least +// significant bit is clear, otherwise it is a tagged integer. A tagged interger +// is obtained from a logical integer value by left shifting by one bit position +// (multiplying by two), and then setting the least significant bit to +// one. Clearly, this means that the maximum value that can be stored as a +// tagged integer is 2**63 - 1. +class RefOrTagged { +public: + bool is_ref() const noexcept; + bool is_tagged() const noexcept; + ref_type get_as_ref() const noexcept; + uint_fast64_t get_as_int() const noexcept; + + static RefOrTagged make_ref(ref_type) noexcept; + static RefOrTagged make_tagged(uint_fast64_t) noexcept; + +private: + int_fast64_t m_value; + RefOrTagged(int_fast64_t) noexcept; + friend class Array; +}; + + +class ArrayParent { +public: + virtual ~ArrayParent() noexcept + { + } + +protected: + virtual void update_child_ref(size_t child_ndx, ref_type new_ref) = 0; + + virtual ref_type get_child_ref(size_t child_ndx) const noexcept = 0; + + // Used only by Array::to_dot(). + virtual std::pair get_to_dot_parent(size_t ndx_in_parent) const = 0; + + friend class Array; +}; + +struct TreeInsertBase { + size_t m_split_offset; + size_t m_split_size; +}; + +/// Provides access to individual array nodes of the database. +/// +/// This class serves purely as an accessor, it assumes no ownership of the +/// referenced memory. +/// +/// An array accessor can be in one of two states: attached or unattached. It is +/// in the attached state if, and only if is_attached() returns true. Most +/// non-static member functions of this class have undefined behaviour if the +/// accessor is in the unattached state. The exceptions are: is_attached(), +/// detach(), create(), init_from_ref(), init_from_mem(), init_from_parent(), +/// has_parent(), get_parent(), set_parent(), get_ndx_in_parent(), +/// set_ndx_in_parent(), adjust_ndx_in_parent(), and get_ref_from_parent(). +/// +/// An array accessor contains information about the parent of the referenced +/// array node. This 'reverse' reference is not explicitely present in the +/// underlying node hierarchy, but it is needed when modifying an array. A +/// modification may lead to relocation of the underlying array node, and the +/// parent must be updated accordingly. Since this applies recursivly all the +/// way to the root node, it is essential that the entire chain of parent +/// accessors is constructed and propperly maintained when a particular array is +/// modified. +/// +/// The parent reference (`pointer to parent`, `index in parent`) is updated +/// independently from the state of attachment to an underlying node. In +/// particular, the parent reference remains valid and is unannfected by changes +/// in attachment. These two aspects of the state of the accessor is updated +/// independently, and it is entirely the responsibility of the caller to update +/// them such that they are consistent with the underlying node hierarchy before +/// calling any method that modifies the underlying array node. +/// +/// FIXME: This class currently has fragments of ownership, in particular the +/// constructors that allocate underlying memory. On the other hand, the +/// destructor never frees the memory. This is a problematic situation, because +/// it so easily becomes an obscure source of leaks. There are three options for +/// a fix of which the third is most attractive but hardest to implement: (1) +/// Remove all traces of ownership semantics, that is, remove the constructors +/// that allocate memory, but keep the trivial copy constructor. For this to +/// work, it is important that the constness of the accessor has nothing to do +/// with the constness of the underlying memory, otherwise constness can be +/// violated simply by copying the accessor. (2) Disallov copying but associate +/// the constness of the accessor with the constness of the underlying +/// memory. (3) Provide full ownership semantics like is done for Table +/// accessors, and provide a proper copy constructor that really produces a copy +/// of the array. For this to work, the class should assume ownership if, and +/// only if there is no parent. A copy produced by a copy constructor will not +/// have a parent. Even if the original was part of a database, the copy will be +/// free-standing, that is, not be part of any database. For intra, or inter +/// database copying, one would have to also specify the target allocator. +class Array : public ArrayParent { +public: + // void state_init(int action, QueryState *state); + // bool match(int action, size_t index, int64_t value, QueryState *state); + + /// Create an array accessor in the unattached state. + explicit Array(Allocator&) noexcept; + + ~Array() noexcept override + { + } + + enum Type { + type_Normal, + + /// This array is the main array of an innner node of a B+-tree as used + /// in table columns. + type_InnerBptreeNode, + + /// This array may contain refs to subarrays. An element whose least + /// significant bit is zero, is a ref pointing to a subarray. An element + /// whose least significant bit is one, is just a value. It is the + /// responsibility of the application to ensure that non-ref values have + /// their least significant bit set. This will generally be done by + /// shifting the desired vlue to the left by one bit position, and then + /// setting the vacated bit to one. + type_HasRefs + }; + + /// Create a new integer array of the specified type and size, and filled + /// with the specified value, and attach this accessor to it. This does not + /// modify the parent reference information of this accessor. + /// + /// Note that the caller assumes ownership of the allocated underlying + /// node. It is not owned by the accessor. + void create(Type, bool context_flag = false, size_t size = 0, int_fast64_t value = 0); + + /// Reinitialize this array accessor to point to the specified new + /// underlying memory. This does not modify the parent reference information + /// of this accessor. + void init_from_ref(ref_type) noexcept; + + /// Same as init_from_ref(ref_type) but avoid the mapping of 'ref' to memory + /// pointer. + void init_from_mem(MemRef) noexcept; + + /// Same as `init_from_ref(get_ref_from_parent())`. + void init_from_parent() noexcept; + + /// Update the parents reference to this child. This requires, of course, + /// that the parent information stored in this child is up to date. If the + /// parent pointer is set to null, this function has no effect. + void update_parent(); + + /// Called in the context of Group::commit() to ensure that attached + /// accessors stay valid across a commit. Please note that this works only + /// for non-transactional commits. Accessors obtained during a transaction + /// are always detached when the transaction ends. + /// + /// Returns true if, and only if the array has changed. If the array has not + /// changed, then its children are guaranteed to also not have changed. + bool update_from_parent(size_t old_baseline) noexcept; + + /// Change the type of an already attached array node. + /// + /// The effect of calling this function on an unattached accessor is + /// undefined. + void set_type(Type); + + /// Construct a complete copy of this array (including its subarrays) using + /// the specified target allocator and return just the reference to the + /// underlying memory. + MemRef clone_deep(Allocator& target_alloc) const; + + /// Construct an empty integer array of the specified type, and return just + /// the reference to the underlying memory. + static MemRef create_empty_array(Type, bool context_flag, Allocator&); + + /// Construct an integer array of the specified type and size, and return + /// just the reference to the underlying memory. All elements will be + /// initialized to the specified value. + static MemRef create_array(Type, bool context_flag, size_t size, int_fast64_t value, Allocator&); + + /// Construct a shallow copy of the specified slice of this array using the + /// specified target allocator. Subarrays will **not** be cloned. See + /// slice_and_clone_children() for an alternative. + MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; + + /// Construct a deep copy of the specified slice of this array using the + /// specified target allocator. Subarrays will be cloned. + MemRef slice_and_clone_children(size_t offset, size_t slice_size, Allocator& target_alloc) const; + + // Parent tracking + bool has_parent() const noexcept; + ArrayParent* get_parent() const noexcept; + + /// Setting a new parent affects ownership of the attached array node, if + /// any. If a non-null parent is specified, and there was no parent + /// originally, then the caller passes ownership to the parent, and vice + /// versa. This assumes, of course, that the change in parentship reflects a + /// corresponding change in the list of children in the affected parents. + void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept; + + size_t get_ndx_in_parent() const noexcept; + void set_ndx_in_parent(size_t) noexcept; + void adjust_ndx_in_parent(int diff) noexcept; + + /// Get the ref of this array as known to the parent. The caller must ensure + /// that the parent information ('pointer to parent' and 'index in parent') + /// is correct before calling this function. + ref_type get_ref_from_parent() const noexcept; + + bool is_attached() const noexcept; + + /// Detach from the underlying array node. This method has no effect if the + /// accessor is currently unattached (idempotency). + void detach() noexcept; + + size_t size() const noexcept; + bool is_empty() const noexcept; + Type get_type() const noexcept; + + + static void add_to_column(IntegerColumn* column, int64_t value); + + void insert(size_t ndx, int_fast64_t value); + void add(int_fast64_t value); + + // Used from ArrayBlob + size_t blob_size() const noexcept; + ref_type blob_replace(size_t begin, size_t end, const char* data, size_t data_size, bool add_zero_term); + + /// This function is guaranteed to not throw if the current width is + /// sufficient for the specified value (e.g. if you have called + /// ensure_minimum_width(value)) and get_alloc().is_read_only(get_ref()) + /// returns false (noexcept:array-set). Note that for a value of zero, the + /// first criterion is trivially satisfied. + void set(size_t ndx, int64_t value); + + void set_as_ref(size_t ndx, ref_type ref); + + template + void set(size_t ndx, int64_t value); + + int64_t get(size_t ndx) const noexcept; + + template + int64_t get(size_t ndx) const noexcept; + + void get_chunk(size_t ndx, int64_t res[8]) const noexcept; + + template + void get_chunk(size_t ndx, int64_t res[8]) const noexcept; + + ref_type get_as_ref(size_t ndx) const noexcept; + + RefOrTagged get_as_ref_or_tagged(size_t ndx) const noexcept; + void set(size_t ndx, RefOrTagged); + void add(RefOrTagged); + void ensure_minimum_width(RefOrTagged); + + int64_t front() const noexcept; + int64_t back() const noexcept; + + /// Remove the element at the specified index, and move elements at higher + /// indexes to the next lower index. + /// + /// This function does **not** destroy removed subarrays. That is, if the + /// erased element is a 'ref' pointing to a subarray, then that subarray + /// will not be destroyed automatically. + /// + /// This function guarantees that no exceptions will be thrown if + /// get_alloc().is_read_only(get_ref()) would return false before the + /// call. This is automatically guaranteed if the array is used in a + /// non-transactional context, or if the array has already been successfully + /// modified within the current write transaction. + void erase(size_t ndx); + + /// Same as erase(size_t), but remove all elements in the specified + /// range. + /// + /// Please note that this function does **not** destroy removed subarrays. + /// + /// This function guarantees that no exceptions will be thrown if + /// get_alloc().is_read_only(get_ref()) would return false before the call. + void erase(size_t begin, size_t end); + + /// Reduce the size of this array to the specified number of elements. It is + /// an error to specify a size that is greater than the current size of this + /// array. The effect of doing so is undefined. This is just a shorthand for + /// calling the ranged erase() function with appropriate arguments. + /// + /// Please note that this function does **not** destroy removed + /// subarrays. See clear_and_destroy_children() for an alternative. + /// + /// This function guarantees that no exceptions will be thrown if + /// get_alloc().is_read_only(get_ref()) would return false before the call. + void truncate(size_t new_size); + + /// Reduce the size of this array to the specified number of elements. It is + /// an error to specify a size that is greater than the current size of this + /// array. The effect of doing so is undefined. Subarrays will be destroyed + /// recursively, as if by a call to `destroy_deep(subarray_ref, alloc)`. + /// + /// This function is guaranteed not to throw if + /// get_alloc().is_read_only(get_ref()) returns false. + void truncate_and_destroy_children(size_t new_size); + + /// Remove every element from this array. This is just a shorthand for + /// calling truncate(0). + /// + /// Please note that this function does **not** destroy removed + /// subarrays. See clear_and_destroy_children() for an alternative. + /// + /// This function guarantees that no exceptions will be thrown if + /// get_alloc().is_read_only(get_ref()) would return false before the call. + void clear(); + + /// Remove every element in this array. Subarrays will be destroyed + /// recursively, as if by a call to `destroy_deep(subarray_ref, + /// alloc)`. This is just a shorthand for calling + /// truncate_and_destroy_children(0). + /// + /// This function guarantees that no exceptions will be thrown if + /// get_alloc().is_read_only(get_ref()) would return false before the call. + void clear_and_destroy_children(); + + /// If neccessary, expand the representation so that it can store the + /// specified value. + void ensure_minimum_width(int_fast64_t value); + + /// This one may change the represenation of the array, so be carefull if + /// you call it after ensure_minimum_width(). + void set_all_to_zero(); + + /// Add \a diff to the element at the specified index. + void adjust(size_t ndx, int_fast64_t diff); + + /// Add \a diff to all the elements in the specified index range. + void adjust(size_t begin, size_t end, int_fast64_t diff); + + /// Add signed \a diff to all elements that are greater than, or equal to \a + /// limit. + void adjust_ge(int_fast64_t limit, int_fast64_t diff); + + //@{ + /// These are similar in spirit to std::move() and std::move_backward from + /// ``. \a dest_begin must not be in the range [`begin`,`end`), and + /// \a dest_end must not be in the range (`begin`,`end`]. + /// + /// These functions are guaranteed to not throw if + /// `get_alloc().is_read_only(get_ref())` returns false. + void move(size_t begin, size_t end, size_t dest_begin); + void move_backward(size_t begin, size_t end, size_t dest_end); + //@} + + /// move_rotate moves one element from \a from to be located at index \a to, + /// shifting all elements inbetween by one. + /// + /// If \a from is larger than \a to, the elements inbetween are shifted down. + /// If \a to is larger than \a from, the elements inbetween are shifted up. + /// + /// This function is guaranteed to not throw if + /// `get_alloc().is_read_only(get_ref())` returns false. + void move_rotate(size_t from, size_t to, size_t num_elems = 1); + + //@{ + /// Find the lower/upper bound of the specified value in a sequence of + /// integers which must already be sorted ascendingly. + /// + /// For an integer value '`v`', lower_bound_int(v) returns the index '`l`' + /// of the first element such that `get(l) ≥ v`, and upper_bound_int(v) + /// returns the index '`u`' of the first element such that `get(u) > + /// v`. In both cases, if no such element is found, the returned value is + /// the number of elements in the array. + /// + /// 3 3 3 4 4 4 5 6 7 9 9 9 + /// ^ ^ ^ ^ ^ + /// | | | | | + /// | | | | -- Lower and upper bound of 15 + /// | | | | + /// | | | -- Lower and upper bound of 8 + /// | | | + /// | | -- Upper bound of 4 + /// | | + /// | -- Lower bound of 4 + /// | + /// -- Lower and upper bound of 1 + /// + /// These functions are similar to std::lower_bound() and + /// std::upper_bound(). + /// + /// We currently use binary search. See for example + /// http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary. + /// + /// FIXME: It may be worth considering if overall efficiency can be improved + /// by doing a linear search for short sequences. + size_t lower_bound_int(int64_t value) const noexcept; + size_t upper_bound_int(int64_t value) const noexcept; + //@} + + /// \brief Search the \c Array for a value greater or equal than \a target, + /// starting the search at the \a start index. If \a indirection is + /// provided, use it as a look-up table to iterate over the \c Array. + /// + /// If \a indirection is not provided, then the \c Array must be sorted in + /// ascending order. If \a indirection is provided, then its values should + /// point to indices in this \c Array in such a way that iteration happens + /// in ascending order. + /// + /// Behaviour is undefined if: + /// - a value in \a indirection is out of bounds for this \c Array; + /// - \a indirection does not contain at least as many elements as this \c + /// Array; + /// - sorting conditions are not respected; + /// - \a start is greater than the number of elements in this \c Array or + /// \a indirection (if provided). + /// + /// \param target the smallest value to search for + /// \param start the offset at which to start searching in the array + /// \param indirection an \c Array containing valid indices of values in + /// this \c Array, sorted in ascending order + /// \return the index of the value if found, or realm::not_found otherwise + size_t find_gte(const int64_t target, size_t start, size_t end = size_t(-1)) const; + + void preset(int64_t min, int64_t max, size_t num_items); + void preset(size_t bitwidth, size_t num_items); + + int64_t sum(size_t start = 0, size_t end = size_t(-1)) const; + size_t count(int64_t value) const noexcept; + + bool maximum(int64_t& result, size_t start = 0, size_t end = size_t(-1), size_t* return_ndx = nullptr) const; + + bool minimum(int64_t& result, size_t start = 0, size_t end = size_t(-1), size_t* return_ndx = nullptr) const; + + /// This information is guaranteed to be cached in the array accessor. + bool is_inner_bptree_node() const noexcept; + + /// Returns true if type is either type_HasRefs or type_InnerColumnNode. + /// + /// This information is guaranteed to be cached in the array accessor. + bool has_refs() const noexcept; + void set_has_refs(bool) noexcept; + + /// This information is guaranteed to be cached in the array accessor. + /// + /// Columns and indexes can use the context bit to differentiate leaf types. + bool get_context_flag() const noexcept; + void set_context_flag(bool) noexcept; + + ref_type get_ref() const noexcept; + MemRef get_mem() const noexcept; + + /// Destroy only the array that this accessor is attached to, not the + /// children of that array. See non-static destroy_deep() for an + /// alternative. If this accessor is already in the detached state, this + /// function has no effect (idempotency). + void destroy() noexcept; + + /// Recursively destroy children (as if calling + /// clear_and_destroy_children()), then put this accessor into the detached + /// state (as if calling detach()), then free the allocated memory. If this + /// accessor is already in the detached state, this function has no effect + /// (idempotency). + void destroy_deep() noexcept; + + /// Shorthand for `destroy(MemRef(ref, alloc), alloc)`. + static void destroy(ref_type ref, Allocator& alloc) noexcept; + + /// Destroy only the specified array node, not its children. See also + /// destroy_deep(MemRef, Allocator&). + static void destroy(MemRef, Allocator&) noexcept; + + /// Shorthand for `destroy_deep(MemRef(ref, alloc), alloc)`. + static void destroy_deep(ref_type ref, Allocator& alloc) noexcept; + + /// Destroy the specified array node and all of its children, recursively. + /// + /// This is done by freeing the specified array node after calling + /// destroy_deep() for every contained 'ref' element. + static void destroy_deep(MemRef, Allocator&) noexcept; + + Allocator& get_alloc() const noexcept + { + return m_alloc; + } + + // Serialization + + /// Returns the ref (position in the target stream) of the written copy of + /// this array, or the ref of the original array if \a only_if_modified is + /// true, and this array is unmodified (Alloc::is_read_only()). + /// + /// The number of bytes that will be written by a non-recursive invocation + /// of this function is exactly the number returned by get_byte_size(). + /// + /// \param out The destination stream (writer). + /// + /// \param deep If true, recursively write out subarrays, but still subject + /// to \a only_if_modified. + /// + /// \param only_if_modified Set to `false` to always write, or to `true` to + /// only write the array if it has been modified. + ref_type write(_impl::ArrayWriterBase& out, bool deep, bool only_if_modified) const; + + /// Same as non-static write() with `deep` set to true. This is for the + /// cases where you do not already have an array accessor available. + static ref_type write(ref_type, Allocator&, _impl::ArrayWriterBase&, bool only_if_modified); + + // Main finding function - used for find_first, find_all, sum, max, min, etc. + bool find(int cond, Action action, int64_t value, size_t start, size_t end, size_t baseindex, + QueryState* state, bool nullable_array = false, bool find_null = false) const; + + // Templated find function to avoid conversion to and from integer represenation of condition + template + bool find(Action action, int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + bool nullable_array = false, bool find_null = false) const + { + if (action == act_ReturnFirst) { + REALM_TEMPEX3(return find, cond, act_ReturnFirst, m_width, + (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) + } + else if (action == act_Sum) { + REALM_TEMPEX3(return find, cond, act_Sum, m_width, + (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) + } + else if (action == act_Min) { + REALM_TEMPEX3(return find, cond, act_Min, m_width, + (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) + } + else if (action == act_Max) { + REALM_TEMPEX3(return find, cond, act_Max, m_width, + (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) + } + else if (action == act_Count) { + REALM_TEMPEX3(return find, cond, act_Count, m_width, + (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) + } + else if (action == act_FindAll) { + REALM_TEMPEX3(return find, cond, act_FindAll, m_width, + (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) + } + else if (action == act_CallbackIdx) { + REALM_TEMPEX3(return find, cond, act_CallbackIdx, m_width, + (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) + } + REALM_ASSERT_DEBUG(false); + return false; + } + + + /* + bool find(int cond, Action action, null, size_t start, size_t end, size_t baseindex, + QueryState* state) const; + */ + + template + bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback, bool nullable_array = false, bool find_null = false) const; + + // This is the one installed into the m_vtable->finder slots. + template + bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state) const; + + template + bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback, bool nullable_array = false, bool find_null = false) const; + + /* + template + bool find(null, size_t start, size_t end, size_t baseindex, + QueryState* state, Callback callback) const; + */ + + // Optimized implementation for release mode + template + bool find_optimized(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback, bool nullable_array = false, bool find_null = false) const; + + // Called for each search result + template + bool find_action(size_t index, util::Optional value, QueryState* state, + Callback callback) const; + + template + bool find_action_pattern(size_t index, uint64_t pattern, QueryState* state, Callback callback) const; + + // Wrappers for backwards compatibility and for simple use without + // setting up state initialization etc + template + size_t find_first(int64_t value, size_t start = 0, size_t end = size_t(-1)) const; + + void find_all(IntegerColumn* result, int64_t value, size_t col_offset = 0, size_t begin = 0, + size_t end = size_t(-1)) const; + + size_t find_first(int64_t value, size_t begin = 0, size_t end = size_t(-1)) const; + + // Non-SSE find for the four functions Equal/NotEqual/Less/Greater + template + bool compare(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const; + + // Non-SSE find for Equal/NotEqual + template + inline bool compare_equality(int64_t value, size_t start, size_t end, size_t baseindex, + QueryState* state, Callback callback) const; + + // Non-SSE find for Less/Greater + template + bool compare_relation(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const; + + template + bool compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const; + + template + bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const; + + template + bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const; + + template + bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const; + +// SSE find for the four functions Equal/NotEqual/Less/Greater +#ifdef REALM_COMPILER_SSE + template + bool find_sse(int64_t value, __m128i* data, size_t items, QueryState* state, size_t baseindex, + Callback callback) const; + + template + REALM_FORCEINLINE bool find_sse_intern(__m128i* action_data, __m128i* data, size_t items, + QueryState* state, size_t baseindex, Callback callback) const; + +#endif + + template + inline bool test_zero(uint64_t value) const; // Tests value for 0-elements + + template + size_t find_zero(uint64_t v) const; // Finds position of 0/non-zero element + + template + uint64_t cascade(uint64_t a) const; // Sets lowermost bits of zero or non-zero elements + + template + int64_t + find_gtlt_magic(int64_t v) const; // Compute magic constant needed for searching for value 'v' using bit hacks + + template + inline int64_t lower_bits() const; // Return chunk with lower bit set in each element + + size_t first_set_bit(unsigned int v) const; + size_t first_set_bit64(int64_t v) const; + + template + int64_t get_universal(const char* const data, const size_t ndx) const; + + // Find value greater/less in 64-bit chunk - only works for positive values + template + bool find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryState* state, size_t baseindex, + Callback callback) const; + + // Find value greater/less in 64-bit chunk - no constraints + template + bool find_gtlt(int64_t v, uint64_t chunk, QueryState* state, size_t baseindex, Callback callback) const; + + ref_type bptree_leaf_insert(size_t ndx, int64_t, TreeInsertBase& state); + + /// Get the specified element without the cost of constructing an + /// array instance. If an array instance is already available, or + /// you need to get multiple values, then this method will be + /// slower. + static int_fast64_t get(const char* header, size_t ndx) noexcept; + + /// Like get(const char*, size_t) but gets two consecutive + /// elements. + static std::pair get_two(const char* header, size_t ndx) noexcept; + + static void get_three(const char* data, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept; + + /// The meaning of 'width' depends on the context in which this + /// array is used. + size_t get_width() const noexcept + { + return m_width; + } + + static char* get_data_from_header(char*) noexcept; + static char* get_header_from_data(char*) noexcept; + static const char* get_data_from_header(const char*) noexcept; + + enum WidthType { + wtype_Bits = 0, + wtype_Multiply = 1, + wtype_Ignore = 2, + }; + + static bool get_is_inner_bptree_node_from_header(const char*) noexcept; + static bool get_hasrefs_from_header(const char*) noexcept; + static bool get_context_flag_from_header(const char*) noexcept; + static WidthType get_wtype_from_header(const char*) noexcept; + static uint_least8_t get_width_from_header(const char*) noexcept; + static size_t get_size_from_header(const char*) noexcept; + + static Type get_type_from_header(const char*) noexcept; + + /// Get the number of bytes currently in use by this array. This + /// includes the array header, but it does not include allocated + /// bytes corresponding to excess capacity. The result is + /// guaranteed to be a multiple of 8 (i.e., 64-bit aligned). + /// + /// This number is exactly the number of bytes that will be + /// written by a non-recursive invocation of write(). + size_t get_byte_size() const noexcept; + + /// Get the maximum number of bytes that can be written by a + /// non-recursive invocation of write() on an array with the + /// specified number of elements, that is, the maximum value that + /// can be returned by get_byte_size(). + static size_t get_max_byte_size(size_t num_elems) noexcept; + + /// FIXME: Belongs in IntegerArray + static size_t calc_aligned_byte_size(size_t size, int width); + + class MemUsageHandler { + public: + virtual void handle(ref_type ref, size_t allocated, size_t used) = 0; + }; + + void report_memory_usage(MemUsageHandler&) const; + + void stats(MemStats& stats_dest) const noexcept; + +#ifdef REALM_DEBUG + void print() const; + void verify() const; + typedef size_t (*LeafVerifier)(MemRef, Allocator&); + void verify_bptree(LeafVerifier) const; + typedef void (*LeafDumper)(MemRef, Allocator&, std::ostream&, int level); + void dump_bptree_structure(std::ostream&, int level, LeafDumper) const; + void to_dot(std::ostream&, StringData title = StringData()) const; + class ToDotHandler { + public: + virtual void to_dot(MemRef leaf_mem, ArrayParent*, size_t ndx_in_parent, std::ostream&) = 0; + ~ToDotHandler() + { + } + }; + void bptree_to_dot(std::ostream&, ToDotHandler&) const; + void to_dot_parent_edge(std::ostream&) const; +#endif + + static const int header_size = 8; // Number of bytes used by header + + // The encryption layer relies on headers always fitting within a single page. + static_assert(header_size == 8, "Header must always fit in entirely on a page"); + + Array& operator=(const Array&) = delete; // not allowed + Array(const Array&) = delete; // not allowed +protected: + typedef bool (*CallbackDummy)(int64_t); + +protected: + // Includes array header. Not necessarily 8-byte aligned. + virtual size_t calc_byte_len(size_t num_items, size_t width) const; + + virtual size_t calc_item_count(size_t bytes, size_t width) const noexcept; + + bool get_is_inner_bptree_node_from_header() const noexcept; + bool get_hasrefs_from_header() const noexcept; + bool get_context_flag_from_header() const noexcept; + WidthType get_wtype_from_header() const noexcept; + uint_least8_t get_width_from_header() const noexcept; + size_t get_size_from_header() const noexcept; + + // Undefined behavior if m_alloc.is_read_only(m_ref) returns true + size_t get_capacity_from_header() const noexcept; + + void set_header_is_inner_bptree_node(bool value) noexcept; + void set_header_hasrefs(bool value) noexcept; + void set_header_context_flag(bool value) noexcept; + void set_header_wtype(WidthType value) noexcept; + void set_header_width(int value) noexcept; + void set_header_size(size_t value) noexcept; + void set_header_capacity(size_t value) noexcept; + + static void set_header_is_inner_bptree_node(bool value, char* header) noexcept; + static void set_header_hasrefs(bool value, char* header) noexcept; + static void set_header_context_flag(bool value, char* header) noexcept; + static void set_header_wtype(WidthType value, char* header) noexcept; + static void set_header_width(int value, char* header) noexcept; + static void set_header_size(size_t value, char* header) noexcept; + static void set_header_capacity(size_t value, char* header) noexcept; + + static void init_header(char* header, bool is_inner_bptree_node, bool has_refs, bool context_flag, + WidthType width_type, int width, size_t size, size_t capacity) noexcept; + + + // This returns the minimum value ("lower bound") of the representable values + // for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64. + template + static int_fast64_t lbound_for_width() noexcept; + + static int_fast64_t lbound_for_width(size_t width) noexcept; + + // This returns the maximum value ("inclusive upper bound") of the representable values + // for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64. + template + static int_fast64_t ubound_for_width() noexcept; + + static int_fast64_t ubound_for_width(size_t width) noexcept; + + template + void set_width() noexcept; + void set_width(size_t) noexcept; + void alloc(size_t init_size, size_t width); + void copy_on_write(); + +private: + void do_copy_on_write(size_t minimum_size = 0); + void do_ensure_minimum_width(int_fast64_t); + + template + int64_t sum(size_t start, size_t end) const; + + template + bool minmax(int64_t& result, size_t start, size_t end, size_t* return_ndx) const; + + template + size_t find_gte(const int64_t target, size_t start, size_t end) const; + + template + size_t adjust_ge(size_t start, size_t end, int_fast64_t limit, int_fast64_t diff); + +protected: + /// The total size in bytes (including the header) of a new empty + /// array. Must be a multiple of 8 (i.e., 64-bit aligned). + static const size_t initial_capacity = 128; + + /// It is an error to specify a non-zero value unless the width + /// type is wtype_Bits. It is also an error to specify a non-zero + /// size if the width type is wtype_Ignore. + static MemRef create(Type, bool context_flag, WidthType, size_t size, int_fast64_t value, Allocator&); + + static MemRef clone(MemRef header, Allocator& alloc, Allocator& target_alloc); + + /// Get the address of the header of this array. + char* get_header() noexcept; + + /// Same as get_byte_size(). + static size_t get_byte_size_from_header(const char*) noexcept; + + // Undefined behavior if array is in immutable memory + static size_t get_capacity_from_header(const char*) noexcept; + + // Overriding method in ArrayParent + void update_child_ref(size_t, ref_type) override; + + // Overriding method in ArrayParent + ref_type get_child_ref(size_t) const noexcept override; + + void destroy_children(size_t offset = 0) noexcept; + + std::pair get_to_dot_parent(size_t ndx_in_parent) const override; + + bool is_read_only() const noexcept; + +protected: + // Getters and Setters for adaptive-packed arrays + typedef int64_t (Array::*Getter)(size_t) const; // Note: getters must not throw + typedef void (Array::*Setter)(size_t, int64_t); + typedef bool (Array::*Finder)(int64_t, size_t, size_t, size_t, QueryState*) const; + typedef void (Array::*ChunkGetter)(size_t, int64_t res[8]) const; // Note: getters must not throw + + struct VTable { + Getter getter; + ChunkGetter chunk_getter; + Setter setter; + Finder finder[cond_VTABLE_FINDER_COUNT]; // one for each active function pointer + }; + template + struct VTableForWidth; + +protected: + /// Takes a 64-bit value and returns the minimum number of bits needed + /// to fit the value. For alignment this is rounded up to nearest + /// log2. Posssible results {0, 1, 2, 4, 8, 16, 32, 64} + static size_t bit_width(int64_t value); + + void report_memory_usage_2(MemUsageHandler&) const; + +private: + Getter m_getter = nullptr; // cached to avoid indirection + const VTable* m_vtable = nullptr; + +public: + // FIXME: Should not be public + char* m_data = nullptr; // Points to first byte after header + +#if REALM_ENABLE_MEMDEBUG + // If m_no_relocation is false, then copy_on_write() will always relocate this array, regardless if it's + // required or not. If it's true, then it will never relocate, which is currently only expeted inside + // GroupWriter::write_group() due to a unique chicken/egg problem (see description there). + bool m_no_relocation = false; +#endif + +protected: + int64_t m_lbound; // min number that can be stored with current m_width + int64_t m_ubound; // max number that can be stored with current m_width + + size_t m_size = 0; // Number of elements currently stored. + size_t m_capacity = 0; // Number of elements that fit inside the allocated memory. + + Allocator& m_alloc; + +private: + size_t m_ref; + ArrayParent* m_parent = nullptr; + size_t m_ndx_in_parent = 0; // Ignored if m_parent is null. + +protected: + uint_least8_t m_width = 0; // Size of an element (meaning depend on type of array). + bool m_is_inner_bptree_node; // This array is an inner node of B+-tree. + bool m_has_refs; // Elements whose first bit is zero are refs to subarrays. + bool m_context_flag; // Meaning depends on context. + +private: + ref_type do_write_shallow(_impl::ArrayWriterBase&) const; + ref_type do_write_deep(_impl::ArrayWriterBase&, bool only_if_modified) const; + static size_t calc_byte_size(WidthType wtype, size_t size, uint_least8_t width) noexcept; + + friend class SlabAlloc; + friend class GroupWriter; + friend class StringColumn; +}; + + +// Implementation: + +class QueryStateBase { + virtual void dyncast() + { + } +}; + +template <> +class QueryState : public QueryStateBase { +public: + int64_t m_state; + size_t m_match_count; + size_t m_limit; + size_t m_minmax_index; // used only for min/max, to save index of current min/max value + + template + bool uses_val() + { + if (action == act_Max || action == act_Min || action == act_Sum) + return true; + else + return false; + } + + void init(Action action, IntegerColumn* akku, size_t limit) + { + m_match_count = 0; + m_limit = limit; + m_minmax_index = not_found; + + if (action == act_Max) + m_state = -0x7fffffffffffffffLL - 1LL; + else if (action == act_Min) + m_state = 0x7fffffffffffffffLL; + else if (action == act_ReturnFirst) + m_state = not_found; + else if (action == act_Sum) + m_state = 0; + else if (action == act_Count) + m_state = 0; + else if (action == act_FindAll) + m_state = reinterpret_cast(akku); + else if (action == act_CallbackIdx) { + } + else { + REALM_ASSERT_DEBUG(false); + } + } + + template + inline bool match(size_t index, uint64_t indexpattern, int64_t value) + { + if (pattern) { + if (action == act_Count) { + // If we are close to 'limit' argument in query, we cannot count-up a complete chunk. Count up single + // elements instead + if (m_match_count + 64 >= m_limit) + return false; + + m_state += fast_popcount64(indexpattern); + m_match_count = size_t(m_state); + return true; + } + // Other aggregates cannot (yet) use bit pattern for anything. Make Array-finder call with pattern = false + // instead + return false; + } + + ++m_match_count; + + if (action == act_Max) { + if (value > m_state) { + m_state = value; + m_minmax_index = index; + } + } + else if (action == act_Min) { + if (value < m_state) { + m_state = value; + m_minmax_index = index; + } + } + else if (action == act_Sum) + m_state += value; + else if (action == act_Count) { + m_state++; + m_match_count = size_t(m_state); + } + else if (action == act_FindAll) { + Array::add_to_column(reinterpret_cast(m_state), index); + } + else if (action == act_ReturnFirst) { + m_state = index; + return false; + } + else { + REALM_ASSERT_DEBUG(false); + } + return (m_limit > m_match_count); + } + + template + inline bool match(size_t index, uint64_t indexpattern, util::Optional value) + { + // FIXME: This is a temporary hack for nullable integers. + if (value) { + return match(index, indexpattern, *value); + } + + // If value is null, the only sensible actions are count, find_all, and return first. + // Max, min, and sum should all have no effect. + if (action == act_Count) { + m_state++; + m_match_count = size_t(m_state); + } + else if (action == act_FindAll) { + Array::add_to_column(reinterpret_cast(m_state), index); + } + else if (action == act_ReturnFirst) { + m_match_count++; + m_state = index; + return false; + } + return m_limit > m_match_count; + } +}; + +// Used only for Basic-types: currently float and double +template +class QueryState : public QueryStateBase { +public: + R m_state; + size_t m_match_count; + size_t m_limit; + size_t m_minmax_index; // used only for min/max, to save index of current min/max value + + template + bool uses_val() + { + return (action == act_Max || action == act_Min || action == act_Sum || action == act_Count); + } + + void init(Action action, Array*, size_t limit) + { + REALM_ASSERT((std::is_same::value || std::is_same::value)); + m_match_count = 0; + m_limit = limit; + m_minmax_index = not_found; + + if (action == act_Max) + m_state = -std::numeric_limits::infinity(); + else if (action == act_Min) + m_state = std::numeric_limits::infinity(); + else if (action == act_Sum) + m_state = 0.0; + else { + REALM_ASSERT_DEBUG(false); + } + } + + template + inline bool match(size_t index, uint64_t /*indexpattern*/, resulttype value) + { + if (pattern) + return false; + + static_assert(action == act_Sum || action == act_Max || action == act_Min || action == act_Count, + "Search action not supported"); + + if (action == act_Count) { + ++m_match_count; + } + else if (!null::is_null_float(value)) { + ++m_match_count; + if (action == act_Max) { + if (value > m_state) { + m_state = value; + m_minmax_index = index; + } + } + else if (action == act_Min) { + if (value < m_state) { + m_state = value; + m_minmax_index = index; + } + } + else if (action == act_Sum) + m_state += value; + else { + REALM_ASSERT_DEBUG(false); + } + } + + return (m_limit > m_match_count); + } +}; + +inline bool RefOrTagged::is_ref() const noexcept +{ + return (m_value & 1) == 0; +} + +inline bool RefOrTagged::is_tagged() const noexcept +{ + return !is_ref(); +} + +inline ref_type RefOrTagged::get_as_ref() const noexcept +{ + // to_ref() is defined in + return to_ref(m_value); +} + +inline uint_fast64_t RefOrTagged::get_as_int() const noexcept +{ + // The bitwise AND is there in case uint_fast64_t is wider than 64 bits. + return (uint_fast64_t(m_value) & 0xFFFFFFFFFFFFFFFFULL) >> 1; +} + +inline RefOrTagged RefOrTagged::make_ref(ref_type ref) noexcept +{ + // from_ref() is defined in + int_fast64_t value = from_ref(ref); + return RefOrTagged(value); +} + +inline RefOrTagged RefOrTagged::make_tagged(uint_fast64_t i) noexcept +{ + REALM_ASSERT(i < (1ULL << 63)); + int_fast64_t value = util::from_twos_compl((i << 1) | 1); + return RefOrTagged(value); +} + +inline RefOrTagged::RefOrTagged(int_fast64_t value) noexcept + : m_value(value) +{ +} + +inline Array::Array(Allocator& allocator) noexcept + : m_alloc(allocator) +{ +} + +inline void Array::create(Type type, bool context_flag, size_t length, int_fast64_t value) +{ + MemRef mem = create_array(type, context_flag, length, value, m_alloc); // Throws + init_from_mem(mem); +} + + +inline void Array::init_from_ref(ref_type ref) noexcept +{ + REALM_ASSERT_DEBUG(ref); + char* header = m_alloc.translate(ref); + init_from_mem(MemRef(header, ref, m_alloc)); +} + + +inline void Array::init_from_parent() noexcept +{ + ref_type ref = get_ref_from_parent(); + init_from_ref(ref); +} + + +inline Array::Type Array::get_type() const noexcept +{ + if (m_is_inner_bptree_node) { + REALM_ASSERT_DEBUG(m_has_refs); + return type_InnerBptreeNode; + } + if (m_has_refs) + return type_HasRefs; + return type_Normal; +} + + +inline void Array::get_chunk(size_t ndx, int64_t res[8]) const noexcept +{ + REALM_ASSERT_DEBUG(ndx < m_size); + (this->*(m_vtable->chunk_getter))(ndx, res); +} + + +inline int64_t Array::get(size_t ndx) const noexcept +{ + REALM_ASSERT_DEBUG(is_attached()); + REALM_ASSERT_DEBUG(ndx < m_size); + return (this->*m_getter)(ndx); + + // Two ideas that are not efficient but may be worth looking into again: + /* + // Assume correct width is found early in REALM_TEMPEX, which is the case for B tree offsets that + // are probably either 2^16 long. Turns out to be 25% faster if found immediately, but 50-300% slower + // if found later + REALM_TEMPEX(return get, (ndx)); + */ + /* + // Slightly slower in both of the if-cases. Also needs an matchcount m_size check too, to avoid + // reading beyond array. + if (m_width >= 8 && m_size > ndx + 7) + return get<64>(ndx >> m_shift) & m_widthmask; + else + return (this->*(m_vtable->getter))(ndx); + */ +} + +inline int64_t Array::front() const noexcept +{ + return get(0); +} + +inline int64_t Array::back() const noexcept +{ + return get(m_size - 1); +} + +inline ref_type Array::get_as_ref(size_t ndx) const noexcept +{ + REALM_ASSERT_DEBUG(is_attached()); + REALM_ASSERT_DEBUG(m_has_refs); + int64_t v = get(ndx); + return to_ref(v); +} + +inline RefOrTagged Array::get_as_ref_or_tagged(size_t ndx) const noexcept +{ + REALM_ASSERT(has_refs()); + return RefOrTagged(get(ndx)); +} + +inline void Array::set(size_t ndx, RefOrTagged ref_or_tagged) +{ + REALM_ASSERT(has_refs()); + set(ndx, ref_or_tagged.m_value); // Throws +} + +inline void Array::add(RefOrTagged ref_or_tagged) +{ + REALM_ASSERT(has_refs()); + add(ref_or_tagged.m_value); // Throws +} + +inline void Array::ensure_minimum_width(RefOrTagged ref_or_tagged) +{ + REALM_ASSERT(has_refs()); + ensure_minimum_width(ref_or_tagged.m_value); // Throws +} + +inline bool Array::is_inner_bptree_node() const noexcept +{ + return m_is_inner_bptree_node; +} + +inline bool Array::has_refs() const noexcept +{ + return m_has_refs; +} + +inline void Array::set_has_refs(bool value) noexcept +{ + if (m_has_refs != value) { + REALM_ASSERT(!is_read_only()); + m_has_refs = value; + set_header_hasrefs(value); + } +} + +inline bool Array::get_context_flag() const noexcept +{ + return m_context_flag; +} + +inline void Array::set_context_flag(bool value) noexcept +{ + if (m_context_flag != value) { + REALM_ASSERT(!is_read_only()); + m_context_flag = value; + set_header_context_flag(value); + } +} + +inline ref_type Array::get_ref() const noexcept +{ + return m_ref; +} + +inline MemRef Array::get_mem() const noexcept +{ + return MemRef(get_header_from_data(m_data), m_ref, m_alloc); +} + +inline void Array::destroy() noexcept +{ + if (!is_attached()) + return; + char* header = get_header_from_data(m_data); + m_alloc.free_(m_ref, header); + m_data = nullptr; +} + +inline void Array::destroy_deep() noexcept +{ + if (!is_attached()) + return; + + if (m_has_refs) + destroy_children(); + + char* header = get_header_from_data(m_data); + m_alloc.free_(m_ref, header); + m_data = nullptr; +} + +inline ref_type Array::write(_impl::ArrayWriterBase& out, bool deep, bool only_if_modified) const +{ + REALM_ASSERT(is_attached()); + + if (only_if_modified && m_alloc.is_read_only(m_ref)) + return m_ref; + + if (!deep || !m_has_refs) + return do_write_shallow(out); // Throws + + return do_write_deep(out, only_if_modified); // Throws +} + +inline ref_type Array::write(ref_type ref, Allocator& alloc, _impl::ArrayWriterBase& out, bool only_if_modified) +{ + if (only_if_modified && alloc.is_read_only(ref)) + return ref; + + Array array(alloc); + array.init_from_ref(ref); + + if (!array.m_has_refs) + return array.do_write_shallow(out); // Throws + + return array.do_write_deep(out, only_if_modified); // Throws +} + +inline void Array::add(int_fast64_t value) +{ + insert(m_size, value); +} + +inline void Array::erase(size_t ndx) +{ + // This can throw, but only if array is currently in read-only + // memory. + move(ndx + 1, size(), ndx); + + // Update size (also in header) + --m_size; + set_header_size(m_size); +} + + +inline void Array::erase(size_t begin, size_t end) +{ + if (begin != end) { + // This can throw, but only if array is currently in read-only memory. + move(end, size(), begin); // Throws + + // Update size (also in header) + m_size -= end - begin; + set_header_size(m_size); + } +} + +inline void Array::clear() +{ + truncate(0); // Throws +} + +inline void Array::clear_and_destroy_children() +{ + truncate_and_destroy_children(0); +} + +inline void Array::destroy(ref_type ref, Allocator& alloc) noexcept +{ + destroy(MemRef(ref, alloc), alloc); +} + +inline void Array::destroy(MemRef mem, Allocator& alloc) noexcept +{ + alloc.free_(mem); +} + +inline void Array::destroy_deep(ref_type ref, Allocator& alloc) noexcept +{ + destroy_deep(MemRef(ref, alloc), alloc); +} + +inline void Array::destroy_deep(MemRef mem, Allocator& alloc) noexcept +{ + if (!get_hasrefs_from_header(mem.get_addr())) { + alloc.free_(mem); + return; + } + Array array(alloc); + array.init_from_mem(mem); + array.destroy_deep(); +} + + +inline void Array::adjust(size_t ndx, int_fast64_t diff) +{ + REALM_ASSERT_3(ndx, <=, m_size); + if (diff != 0) { + // FIXME: Should be optimized + int_fast64_t v = get(ndx); + set(ndx, int64_t(v + diff)); // Throws + } +} + +inline void Array::adjust(size_t begin, size_t end, int_fast64_t diff) +{ + if (diff != 0) { + // FIXME: Should be optimized + for (size_t i = begin; i != end; ++i) + adjust(i, diff); // Throws + } +} + + +//------------------------------------------------- + +inline bool Array::get_is_inner_bptree_node_from_header(const char* header) noexcept +{ + typedef unsigned char uchar; + const uchar* h = reinterpret_cast(header); + return (int(h[4]) & 0x80) != 0; +} +inline bool Array::get_hasrefs_from_header(const char* header) noexcept +{ + typedef unsigned char uchar; + const uchar* h = reinterpret_cast(header); + return (int(h[4]) & 0x40) != 0; +} +inline bool Array::get_context_flag_from_header(const char* header) noexcept +{ + typedef unsigned char uchar; + const uchar* h = reinterpret_cast(header); + return (int(h[4]) & 0x20) != 0; +} +inline Array::WidthType Array::get_wtype_from_header(const char* header) noexcept +{ + typedef unsigned char uchar; + const uchar* h = reinterpret_cast(header); + return WidthType((int(h[4]) & 0x18) >> 3); +} +inline uint_least8_t Array::get_width_from_header(const char* header) noexcept +{ + typedef unsigned char uchar; + const uchar* h = reinterpret_cast(header); + return uint_least8_t((1 << (int(h[4]) & 0x07)) >> 1); +} +inline size_t Array::get_size_from_header(const char* header) noexcept +{ + typedef unsigned char uchar; + const uchar* h = reinterpret_cast(header); + return (size_t(h[5]) << 16) + (size_t(h[6]) << 8) + h[7]; +} +inline size_t Array::get_capacity_from_header(const char* header) noexcept +{ + typedef unsigned char uchar; + const uchar* h = reinterpret_cast(header); + return (size_t(h[0]) << 19) + (size_t(h[1]) << 11) + (h[2] << 3); +} + + +inline char* Array::get_data_from_header(char* header) noexcept +{ + return header + header_size; +} +inline char* Array::get_header_from_data(char* data) noexcept +{ + return data - header_size; +} +inline const char* Array::get_data_from_header(const char* header) noexcept +{ + return get_data_from_header(const_cast(header)); +} + + +inline bool Array::get_is_inner_bptree_node_from_header() const noexcept +{ + return get_is_inner_bptree_node_from_header(get_header_from_data(m_data)); +} +inline bool Array::get_hasrefs_from_header() const noexcept +{ + return get_hasrefs_from_header(get_header_from_data(m_data)); +} +inline bool Array::get_context_flag_from_header() const noexcept +{ + return get_context_flag_from_header(get_header_from_data(m_data)); +} +inline Array::WidthType Array::get_wtype_from_header() const noexcept +{ + return get_wtype_from_header(get_header_from_data(m_data)); +} +inline uint_least8_t Array::get_width_from_header() const noexcept +{ + return get_width_from_header(get_header_from_data(m_data)); +} +inline size_t Array::get_size_from_header() const noexcept +{ + return get_size_from_header(get_header_from_data(m_data)); +} +inline size_t Array::get_capacity_from_header() const noexcept +{ + return get_capacity_from_header(get_header_from_data(m_data)); +} + + +inline void Array::set_header_is_inner_bptree_node(bool value, char* header) noexcept +{ + typedef unsigned char uchar; + uchar* h = reinterpret_cast(header); + h[4] = uchar((int(h[4]) & ~0x80) | int(value) << 7); +} + +inline void Array::set_header_hasrefs(bool value, char* header) noexcept +{ + typedef unsigned char uchar; + uchar* h = reinterpret_cast(header); + h[4] = uchar((int(h[4]) & ~0x40) | int(value) << 6); +} + +inline void Array::set_header_context_flag(bool value, char* header) noexcept +{ + typedef unsigned char uchar; + uchar* h = reinterpret_cast(header); + h[4] = uchar((int(h[4]) & ~0x20) | int(value) << 5); +} + +inline void Array::set_header_wtype(WidthType value, char* header) noexcept +{ + // Indicates how to calculate size in bytes based on width + // 0: bits (width/8) * size + // 1: multiply width * size + // 2: ignore 1 * size + typedef unsigned char uchar; + uchar* h = reinterpret_cast(header); + h[4] = uchar((int(h[4]) & ~0x18) | int(value) << 3); +} + +inline void Array::set_header_width(int value, char* header) noexcept +{ + // Pack width in 3 bits (log2) + int w = 0; + while (value) { + ++w; + value >>= 1; + } + REALM_ASSERT_3(w, <, 8); + + typedef unsigned char uchar; + uchar* h = reinterpret_cast(header); + h[4] = uchar((int(h[4]) & ~0x7) | w); +} + +inline void Array::set_header_size(size_t value, char* header) noexcept +{ + REALM_ASSERT_3(value, <=, max_array_size); + typedef unsigned char uchar; + uchar* h = reinterpret_cast(header); + h[5] = uchar((value >> 16) & 0x000000FF); + h[6] = uchar((value >> 8) & 0x000000FF); + h[7] = uchar(value & 0x000000FF); +} + +// Note: There is a copy of this function is test_alloc.cpp +inline void Array::set_header_capacity(size_t value, char* header) noexcept +{ + REALM_ASSERT_3(value, <=, (0xffffff << 3)); + typedef unsigned char uchar; + uchar* h = reinterpret_cast(header); + h[0] = uchar((value >> 19) & 0x000000FF); + h[1] = uchar((value >> 11) & 0x000000FF); + h[2] = uchar(value >> 3 & 0x000000FF); +} + + +inline void Array::set_header_is_inner_bptree_node(bool value) noexcept +{ + set_header_is_inner_bptree_node(value, get_header_from_data(m_data)); +} +inline void Array::set_header_hasrefs(bool value) noexcept +{ + set_header_hasrefs(value, get_header_from_data(m_data)); +} +inline void Array::set_header_context_flag(bool value) noexcept +{ + set_header_context_flag(value, get_header_from_data(m_data)); +} +inline void Array::set_header_wtype(WidthType value) noexcept +{ + set_header_wtype(value, get_header_from_data(m_data)); +} +inline void Array::set_header_width(int value) noexcept +{ + set_header_width(value, get_header_from_data(m_data)); +} +inline void Array::set_header_size(size_t value) noexcept +{ + set_header_size(value, get_header_from_data(m_data)); +} +inline void Array::set_header_capacity(size_t value) noexcept +{ + set_header_capacity(value, get_header_from_data(m_data)); +} + + +inline Array::Type Array::get_type_from_header(const char* header) noexcept +{ + if (get_is_inner_bptree_node_from_header(header)) + return type_InnerBptreeNode; + if (get_hasrefs_from_header(header)) + return type_HasRefs; + return type_Normal; +} + + +inline char* Array::get_header() noexcept +{ + return get_header_from_data(m_data); +} + +inline size_t Array::calc_byte_size(WidthType wtype, size_t size, uint_least8_t width) noexcept +{ + size_t num_bytes = 0; + switch (wtype) { + case wtype_Bits: { + // Current assumption is that size is at most 2^24 and that width is at most 64. + // In that case the following will never overflow. (Assuming that size_t is at least 32 bits) + REALM_ASSERT_3(size, <, 0x1000000); + size_t num_bits = size * width; + num_bytes = (num_bits + 7) >> 3; + break; + } + case wtype_Multiply: { + num_bytes = size * width; + break; + } + case wtype_Ignore: + num_bytes = size; + break; + } + + // Ensure 8-byte alignment + num_bytes = (num_bytes + 7) & ~size_t(7); + + num_bytes += header_size; + + return num_bytes; +} + +inline size_t Array::get_byte_size() const noexcept +{ + const char* header = get_header_from_data(m_data); + WidthType wtype = get_wtype_from_header(header); + size_t num_bytes = calc_byte_size(wtype, m_size, m_width); + + REALM_ASSERT_7(m_alloc.is_read_only(m_ref), ==, true, ||, num_bytes, <=, get_capacity_from_header(header)); + + return num_bytes; +} + + +inline size_t Array::get_byte_size_from_header(const char* header) noexcept +{ + size_t size = get_size_from_header(header); + uint_least8_t width = get_width_from_header(header); + WidthType wtype = get_wtype_from_header(header); + size_t num_bytes = calc_byte_size(wtype, size, width); + + return num_bytes; +} + + +inline void Array::init_header(char* header, bool is_inner_bptree_node, bool has_refs, bool context_flag, + WidthType width_type, int width, size_t size, size_t capacity) noexcept +{ + // Note: Since the header layout contains unallocated bit and/or + // bytes, it is important that we put the entire header into a + // well defined state initially. + std::fill(header, header + header_size, 0); + set_header_is_inner_bptree_node(is_inner_bptree_node, header); + set_header_hasrefs(has_refs, header); + set_header_context_flag(context_flag, header); + set_header_wtype(width_type, header); + set_header_width(width, header); + set_header_size(size, header); + set_header_capacity(capacity, header); +} + + +//------------------------------------------------- + +inline MemRef Array::clone_deep(Allocator& target_alloc) const +{ + char* header = get_header_from_data(m_data); + return clone(MemRef(header, m_ref, m_alloc), m_alloc, target_alloc); // Throws +} + +inline MemRef Array::create_empty_array(Type type, bool context_flag, Allocator& alloc) +{ + size_t size = 0; + int_fast64_t value = 0; + return create_array(type, context_flag, size, value, alloc); // Throws +} + +inline MemRef Array::create_array(Type type, bool context_flag, size_t size, int_fast64_t value, Allocator& alloc) +{ + return create(type, context_flag, wtype_Bits, size, value, alloc); // Throws +} + +inline bool Array::has_parent() const noexcept +{ + return m_parent != nullptr; +} + +inline ArrayParent* Array::get_parent() const noexcept +{ + return m_parent; +} + +inline void Array::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept +{ + m_parent = parent; + m_ndx_in_parent = ndx_in_parent; +} + +inline size_t Array::get_ndx_in_parent() const noexcept +{ + return m_ndx_in_parent; +} + +inline void Array::set_ndx_in_parent(size_t ndx) noexcept +{ + m_ndx_in_parent = ndx; +} + +inline void Array::adjust_ndx_in_parent(int diff) noexcept +{ + // Note that `diff` is promoted to an unsigned type, and that + // C++03 still guarantees the expected result regardless of the + // sizes of `int` and `decltype(m_ndx_in_parent)`. + m_ndx_in_parent += diff; +} + +inline ref_type Array::get_ref_from_parent() const noexcept +{ + ref_type ref = m_parent->get_child_ref(m_ndx_in_parent); + return ref; +} + +inline bool Array::is_attached() const noexcept +{ + return m_data != nullptr; +} + +inline void Array::detach() noexcept +{ + m_data = nullptr; +} + +inline size_t Array::size() const noexcept +{ + REALM_ASSERT_DEBUG(is_attached()); + return m_size; +} + +inline bool Array::is_empty() const noexcept +{ + return size() == 0; +} + +inline size_t Array::get_max_byte_size(size_t num_elems) noexcept +{ + int max_bytes_per_elem = 8; + return header_size + num_elems * max_bytes_per_elem; +} + +inline void Array::update_parent() +{ + if (m_parent) + m_parent->update_child_ref(m_ndx_in_parent, m_ref); +} + + +inline void Array::update_child_ref(size_t child_ndx, ref_type new_ref) +{ + set(child_ndx, new_ref); +} + +inline ref_type Array::get_child_ref(size_t child_ndx) const noexcept +{ + return get_as_ref(child_ndx); +} + +inline bool Array::is_read_only() const noexcept +{ + REALM_ASSERT_DEBUG(is_attached()); + return m_alloc.is_read_only(m_ref); +} + +inline void Array::copy_on_write() +{ +#if REALM_ENABLE_MEMDEBUG + // We want to relocate this array regardless if there is a need or not, in order to catch use-after-free bugs. + // Only exception is inside GroupWriter::write_group() (see explanation at the definition of the m_no_relocation + // member) + if (!m_no_relocation) { +#else + if (is_read_only()) { +#endif + do_copy_on_write(); + } +} + +inline void Array::ensure_minimum_width(int_fast64_t value) +{ + if (value >= m_lbound && value <= m_ubound) + return; + do_ensure_minimum_width(value); +} + + +//************************************************************************************* +// Finding code * +//************************************************************************************* + +template +int64_t Array::get(size_t ndx) const noexcept +{ + return get_universal(m_data, ndx); +} + +template +int64_t Array::get_universal(const char* data, size_t ndx) const +{ + if (w == 0) { + return 0; + } + else if (w == 1) { + size_t offset = ndx >> 3; + return (data[offset] >> (ndx & 7)) & 0x01; + } + else if (w == 2) { + size_t offset = ndx >> 2; + return (data[offset] >> ((ndx & 3) << 1)) & 0x03; + } + else if (w == 4) { + size_t offset = ndx >> 1; + return (data[offset] >> ((ndx & 1) << 2)) & 0x0F; + } + else if (w == 8) { + return *reinterpret_cast(data + ndx); + } + else if (w == 16) { + size_t offset = ndx * 2; + return *reinterpret_cast(data + offset); + } + else if (w == 32) { + size_t offset = ndx * 4; + return *reinterpret_cast(data + offset); + } + else if (w == 64) { + size_t offset = ndx * 8; + return *reinterpret_cast(data + offset); + } + else { + REALM_ASSERT_DEBUG(false); + return int64_t(-1); + } +} + +/* +find() (calls find_optimized()) will call match() for each search result. + +If pattern == true: + 'indexpattern' contains a 64-bit chunk of elements, each of 'width' bits in size where each element indicates a + match if its lower bit is set, otherwise it indicates a non-match. 'index' tells the database row index of the + first element. You must return true if you chose to 'consume' the chunk or false if not. If not, then Array-finder + will afterwards call match() successive times with pattern == false. + +If pattern == false: + 'index' tells the row index of a single match and 'value' tells its value. Return false to make Array-finder break + its search or return true to let it continue until 'end' or 'limit'. + +Array-finder decides itself if - and when - it wants to pass you an indexpattern. It depends on array bit width, match +frequency, and whether the arithemetic and computations for the given search criteria makes it feasible to construct +such a pattern. +*/ + +// These wrapper functions only exist to enable a possibility to make the compiler see that 'value' and/or 'index' are +// unused, such that caller's computation of these values will not be made. Only works if find_action() and +// find_action_pattern() rewritten as macros. Note: This problem has been fixed in next upcoming array.hpp version +template +bool Array::find_action(size_t index, util::Optional value, QueryState* state, + Callback callback) const +{ + if (action == act_CallbackIdx) + return callback(index); + else + return state->match(index, 0, value); +} +template +bool Array::find_action_pattern(size_t index, uint64_t pattern, QueryState* state, Callback callback) const +{ + static_cast(callback); + if (action == act_CallbackIdx) { + // Possible future optimization: call callback(index) like in above find_action(), in a loop for each bit set + // in 'pattern' + return false; + } + return state->match(index, pattern, 0); +} + + +template +uint64_t Array::cascade(uint64_t a) const +{ + // Takes a chunk of values as argument and sets the least significant bit for each + // element which is zero or non-zero, depending on the template parameter. + // Example for zero=true: + // width == 4 and a = 0x5fd07a107610f610 + // will return: 0x0001000100010001 + + // static values needed for fast population count + const uint64_t m1 = 0x5555555555555555ULL; + + if (width == 1) { + return zero ? ~a : a; + } + else if (width == 2) { + // Masks to avoid spillover between segments in cascades + const uint64_t c1 = ~0ULL / 0x3 * 0x1; + + a |= (a >> 1) & c1; // cascade ones in non-zeroed segments + a &= m1; // isolate single bit in each segment + if (zero) + a ^= m1; // reverse isolated bits if checking for zeroed segments + + return a; + } + else if (width == 4) { + const uint64_t m = ~0ULL / 0xF * 0x1; + + // Masks to avoid spillover between segments in cascades + const uint64_t c1 = ~0ULL / 0xF * 0x7; + const uint64_t c2 = ~0ULL / 0xF * 0x3; + + a |= (a >> 1) & c1; // cascade ones in non-zeroed segments + a |= (a >> 2) & c2; + a &= m; // isolate single bit in each segment + if (zero) + a ^= m; // reverse isolated bits if checking for zeroed segments + + return a; + } + else if (width == 8) { + const uint64_t m = ~0ULL / 0xFF * 0x1; + + // Masks to avoid spillover between segments in cascades + const uint64_t c1 = ~0ULL / 0xFF * 0x7F; + const uint64_t c2 = ~0ULL / 0xFF * 0x3F; + const uint64_t c3 = ~0ULL / 0xFF * 0x0F; + + a |= (a >> 1) & c1; // cascade ones in non-zeroed segments + a |= (a >> 2) & c2; + a |= (a >> 4) & c3; + a &= m; // isolate single bit in each segment + if (zero) + a ^= m; // reverse isolated bits if checking for zeroed segments + + return a; + } + else if (width == 16) { + const uint64_t m = ~0ULL / 0xFFFF * 0x1; + + // Masks to avoid spillover between segments in cascades + const uint64_t c1 = ~0ULL / 0xFFFF * 0x7FFF; + const uint64_t c2 = ~0ULL / 0xFFFF * 0x3FFF; + const uint64_t c3 = ~0ULL / 0xFFFF * 0x0FFF; + const uint64_t c4 = ~0ULL / 0xFFFF * 0x00FF; + + a |= (a >> 1) & c1; // cascade ones in non-zeroed segments + a |= (a >> 2) & c2; + a |= (a >> 4) & c3; + a |= (a >> 8) & c4; + a &= m; // isolate single bit in each segment + if (zero) + a ^= m; // reverse isolated bits if checking for zeroed segments + + return a; + } + + else if (width == 32) { + const uint64_t m = ~0ULL / 0xFFFFFFFF * 0x1; + + // Masks to avoid spillover between segments in cascades + const uint64_t c1 = ~0ULL / 0xFFFFFFFF * 0x7FFFFFFF; + const uint64_t c2 = ~0ULL / 0xFFFFFFFF * 0x3FFFFFFF; + const uint64_t c3 = ~0ULL / 0xFFFFFFFF * 0x0FFFFFFF; + const uint64_t c4 = ~0ULL / 0xFFFFFFFF * 0x00FFFFFF; + const uint64_t c5 = ~0ULL / 0xFFFFFFFF * 0x0000FFFF; + + a |= (a >> 1) & c1; // cascade ones in non-zeroed segments + a |= (a >> 2) & c2; + a |= (a >> 4) & c3; + a |= (a >> 8) & c4; + a |= (a >> 16) & c5; + a &= m; // isolate single bit in each segment + if (zero) + a ^= m; // reverse isolated bits if checking for zeroed segments + + return a; + } + else if (width == 64) { + return (a == 0) == zero; + } + else { + REALM_ASSERT_DEBUG(false); + return uint64_t(-1); + } +} + +// This is the main finding function for Array. Other finding functions are just wrappers around this one. +// Search for 'value' using condition cond (Equal, NotEqual, Less, etc) and call find_action() or +// find_action_pattern() for each match. Break and return if find_action() returns false or 'end' is reached. + +// If nullable_array is set, then find_optimized() will treat the array is being nullable, i.e. it will skip the +// first entry and compare correctly against null, etc. +// +// If find_null is set, it means that we search for a null. In that case, `value` is ignored. If find_null is set, +// then nullable_array must be set too. +template +bool Array::find_optimized(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback, bool nullable_array, bool find_null) const +{ + REALM_ASSERT(!(find_null && !nullable_array)); + REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); + + size_t start2 = start; + cond c; + + if (end == npos) + end = nullable_array ? size() - 1 : size(); + + if (nullable_array) { + // We were called by find() of a nullable array. So skip first entry, take nulls in count, etc, etc. Fixme: + // Huge speed optimizations are possible here! This is a very simple generic method. + for (; start2 < end; start2++) { + int64_t v = get(start2 + 1); + if (c(v, value, v == get(0), find_null)) { + util::Optional v2(v == get(0) ? util::none : util::make_optional(v)); + if (!find_action(start2 + baseindex, v2, state, callback)) + return false; // tell caller to stop aggregating/search + } + } + return true; // tell caller to continue aggregating/search (on next array leafs) + } + + + // Test first few items with no initial time overhead + if (start2 > 0) { + if (m_size > start2 && c(get(start2), value) && start2 < end) { + if (!find_action(start2 + baseindex, get(start2), state, callback)) + return false; + } + + ++start2; + + if (m_size > start2 && c(get(start2), value) && start2 < end) { + if (!find_action(start2 + baseindex, get(start2), state, callback)) + return false; + } + + ++start2; + + if (m_size > start2 && c(get(start2), value) && start2 < end) { + if (!find_action(start2 + baseindex, get(start2), state, callback)) + return false; + } + + ++start2; + + if (m_size > start2 && c(get(start2), value) && start2 < end) { + if (!find_action(start2 + baseindex, get(start2), state, callback)) + return false; + } + + ++start2; + } + + if (!(m_size > start2 && start2 < end)) + return true; + + if (end == size_t(-1)) + end = m_size; + + // Return immediately if no items in array can match (such as if cond == Greater && value == 100 && + // m_ubound == 15) + if (!c.can_match(value, m_lbound, m_ubound)) + return true; + + // optimization if all items are guaranteed to match (such as cond == NotEqual && value == 100 && m_ubound == 15) + if (c.will_match(value, m_lbound, m_ubound)) { + size_t end2; + + if (action == act_CallbackIdx) + end2 = end; + else { + REALM_ASSERT_DEBUG(state->m_match_count < state->m_limit); + size_t process = state->m_limit - state->m_match_count; + end2 = end - start2 > process ? start2 + process : end; + } + if (action == act_Sum || action == act_Max || action == act_Min) { + int64_t res; + size_t res_ndx = 0; + if (action == act_Sum) + res = Array::sum(start2, end2); + if (action == act_Max) + Array::maximum(res, start2, end2, &res_ndx); + if (action == act_Min) + Array::minimum(res, start2, end2, &res_ndx); + + find_action(res_ndx + baseindex, res, state, callback); + // find_action will increment match count by 1, so we need to `-1` from the number of elements that + // we performed the fast Array methods on. + state->m_match_count += end2 - start2 - 1; + } + else if (action == act_Count) { + state->m_state += end2 - start2; + } + else { + for (; start2 < end2; start2++) + if (!find_action(start2 + baseindex, get(start2), state, callback)) + return false; + } + return true; + } + + // finder cannot handle this bitwidth + REALM_ASSERT_3(m_width, !=, 0); + +#if defined(REALM_COMPILER_SSE) + // Only use SSE if payload is at least one SSE chunk (128 bits) in size. Also note taht SSE doesn't support + // Less-than comparison for 64-bit values. + if ((!(std::is_same::value && m_width == 64)) && end - start2 >= sizeof(__m128i) && m_width >= 8 && + (sseavx<42>() || (sseavx<30>() && std::is_same::value && m_width < 64))) { + + // find_sse() must start2 at 16-byte boundary, so search area before that using compare_equality() + __m128i* const a = reinterpret_cast<__m128i*>(round_up(m_data + start2 * bitwidth / 8, sizeof(__m128i))); + __m128i* const b = reinterpret_cast<__m128i*>(round_down(m_data + end * bitwidth / 8, sizeof(__m128i))); + + if (!compare( + value, start2, (reinterpret_cast(a) - m_data) * 8 / no0(bitwidth), baseindex, state, callback)) + return false; + + // Search aligned area with SSE + if (b > a) { + if (sseavx<42>()) { + if (!find_sse( + value, a, b - a, state, + baseindex + ((reinterpret_cast(a) - m_data) * 8 / no0(bitwidth)), callback)) + return false; + } + else if (sseavx<30>()) { + + if (!find_sse( + value, a, b - a, state, + baseindex + ((reinterpret_cast(a) - m_data) * 8 / no0(bitwidth)), callback)) + return false; + } + } + + // Search remainder with compare_equality() + if (!compare( + value, (reinterpret_cast(b) - m_data) * 8 / no0(bitwidth), end, baseindex, state, callback)) + return false; + + return true; + } + else { + return compare(value, start2, end, baseindex, state, callback); + } +#else + return compare(value, start2, end, baseindex, state, callback); +#endif +} + +template +inline int64_t Array::lower_bits() const +{ + if (width == 1) + return 0xFFFFFFFFFFFFFFFFULL; + else if (width == 2) + return 0x5555555555555555ULL; + else if (width == 4) + return 0x1111111111111111ULL; + else if (width == 8) + return 0x0101010101010101ULL; + else if (width == 16) + return 0x0001000100010001ULL; + else if (width == 32) + return 0x0000000100000001ULL; + else if (width == 64) + return 0x0000000000000001ULL; + else { + REALM_ASSERT_DEBUG(false); + return int64_t(-1); + } +} + +// Tests if any chunk in 'value' is 0 +template +inline bool Array::test_zero(uint64_t value) const +{ + uint64_t hasZeroByte; + uint64_t lower = lower_bits(); + uint64_t upper = lower_bits() * 1ULL << (width == 0 ? 0 : (width - 1ULL)); + hasZeroByte = (value - lower) & ~value & upper; + return hasZeroByte != 0; +} + +// Finds first zero (if eq == true) or non-zero (if eq == false) element in v and returns its position. +// IMPORTANT: This function assumes that at least 1 item matches (test this with test_zero() or other means first)! +template +size_t Array::find_zero(uint64_t v) const +{ + size_t start = 0; + uint64_t hasZeroByte; + // Warning free way of computing (1ULL << width) - 1 + uint64_t mask = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); + + if (eq == (((v >> (width * start)) & mask) == 0)) { + return 0; + } + + // Bisection optimization, speeds up small bitwidths with high match frequency. More partions than 2 do NOT pay + // off because the work done by test_zero() is wasted for the cases where the value exists in first half, but + // useful if it exists in last half. Sweet spot turns out to be the widths and partitions below. + if (width <= 8) { + hasZeroByte = test_zero(v | 0xffffffff00000000ULL); + if (eq ? !hasZeroByte : (v & 0x00000000ffffffffULL) == 0) { + // 00?? -> increasing + start += 64 / no0(width) / 2; + if (width <= 4) { + hasZeroByte = test_zero(v | 0xffff000000000000ULL); + if (eq ? !hasZeroByte : (v & 0x0000ffffffffffffULL) == 0) { + // 000? + start += 64 / no0(width) / 4; + } + } + } + else { + if (width <= 4) { + // ??00 + hasZeroByte = test_zero(v | 0xffffffffffff0000ULL); + if (eq ? !hasZeroByte : (v & 0x000000000000ffffULL) == 0) { + // 0?00 + start += 64 / no0(width) / 4; + } + } + } + } + + while (eq == (((v >> (width * start)) & mask) != 0)) { + // You must only call find_zero() if you are sure that at least 1 item matches + REALM_ASSERT_3(start, <=, 8 * sizeof(v)); + start++; + } + + return start; +} + +// Generate a magic constant used for later bithacks +template +int64_t Array::find_gtlt_magic(int64_t v) const +{ + uint64_t mask1 = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - + 1ULL)); // Warning free way of computing (1ULL << width) - 1 + uint64_t mask2 = mask1 >> 1; + uint64_t magic = gt ? (~0ULL / no0(mask1) * (mask2 - v)) : (~0ULL / no0(mask1) * v); + return magic; +} + +template +bool Array::find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryState* state, size_t baseindex, + Callback callback) const +{ + // Tests if a a chunk of values contains values that are greater (if gt == true) or less (if gt == false) than v. + // Fast, but limited to work when all values in the chunk are positive. + + uint64_t mask1 = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - + 1ULL)); // Warning free way of computing (1ULL << width) - 1 + uint64_t mask2 = mask1 >> 1; + uint64_t m = gt ? (((chunk + magic) | chunk) & ~0ULL / no0(mask1) * (mask2 + 1)) + : ((chunk - magic) & ~chunk & ~0ULL / no0(mask1) * (mask2 + 1)); + size_t p = 0; + while (m) { + if (find_action_pattern(baseindex, m >> (no0(width) - 1), state, callback)) + break; // consumed, so do not call find_action() + + size_t t = first_set_bit64(m) / no0(width); + p += t; + if (!find_action(p + baseindex, (chunk >> (p * width)) & mask1, state, callback)) + return false; + + if ((t + 1) * width == 64) + m = 0; + else + m >>= (t + 1) * width; + p++; + } + + return true; +} + +// clang-format off +template +bool Array::find_gtlt(int64_t v, uint64_t chunk, QueryState* state, size_t baseindex, Callback callback) const +{ + // Find items in 'chunk' that are greater (if gt == true) or smaller (if gt == false) than 'v'. Fixme, __forceinline can make it crash in vS2010 - find out why + if (width == 1) { + for (size_t t = 0; t < 64; t++) { + if (gt ? static_cast(chunk & 0x1) > v : static_cast(chunk & 0x1) < v) {if (!find_action( t + baseindex, static_cast(chunk & 0x1), state, callback)) return false;} + chunk >>= 1; + } + } + else if (width == 2) { + // Alot (50% +) faster than loop/compiler-unrolled loop + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 0 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 1 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 2 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 3 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 4 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 5 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 6 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 7 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 8 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 9 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 10 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 11 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 12 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 13 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 14 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 15 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 16 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 17 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 18 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 19 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 20 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 21 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 22 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 23 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 24 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 25 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 26 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 27 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 28 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 29 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 30 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 31 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} + chunk >>= 2; + } + else if (width == 4) { + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 0 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 1 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 2 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 3 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 4 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 5 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 6 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 7 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 8 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 9 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 10 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 11 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 12 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 13 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 14 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 15 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} + chunk >>= 4; + } + else if (width == 8) { + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 0 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 8; + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 1 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 8; + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 2 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 8; + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 3 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 8; + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 4 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 8; + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 5 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 8; + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 6 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 8; + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 7 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 8; + } + else if (width == 16) { + + if (gt ? static_cast(chunk >> 0 * 16) > v : static_cast(chunk >> 0 * 16) < v) {if (!find_action( 0 + baseindex, static_cast(chunk >> 0 * 16), state, callback)) return false;}; + if (gt ? static_cast(chunk >> 1 * 16) > v : static_cast(chunk >> 1 * 16) < v) {if (!find_action( 1 + baseindex, static_cast(chunk >> 1 * 16), state, callback)) return false;}; + if (gt ? static_cast(chunk >> 2 * 16) > v : static_cast(chunk >> 2 * 16) < v) {if (!find_action( 2 + baseindex, static_cast(chunk >> 2 * 16), state, callback)) return false;}; + if (gt ? static_cast(chunk >> 3 * 16) > v : static_cast(chunk >> 3 * 16) < v) {if (!find_action( 3 + baseindex, static_cast(chunk >> 3 * 16), state, callback)) return false;}; + } + else if (width == 32) { + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 0 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 32; + if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 1 + baseindex, static_cast(chunk), state, callback)) return false;} + chunk >>= 32; + } + else if (width == 64) { + if (gt ? static_cast(v) > v : static_cast(v) < v) {if (!find_action( 0 + baseindex, static_cast(v), state, callback)) return false;}; + } + + return true; +} +// clang-format on + +/// Find items in this Array that are equal (eq == true) or different (eq = false) from 'value' +template +inline bool Array::compare_equality(int64_t value, size_t start, size_t end, size_t baseindex, + QueryState* state, Callback callback) const +{ + REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); + + size_t ee = round_up(start, 64 / no0(width)); + ee = ee > end ? end : ee; + for (; start < ee; ++start) + if (eq ? (get(start) == value) : (get(start) != value)) { + if (!find_action(start + baseindex, get(start), state, callback)) + return false; + } + + if (start >= end) + return true; + + if (width != 32 && width != 64) { + const int64_t* p = reinterpret_cast(m_data + (start * width / 8)); + const int64_t* const e = reinterpret_cast(m_data + (end * width / 8)) - 1; + const uint64_t mask = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - + 1ULL)); // Warning free way of computing (1ULL << width) - 1 + const uint64_t valuemask = + ~0ULL / no0(mask) * (value & mask); // the "== ? :" is to avoid division by 0 compiler error + + while (p < e) { + uint64_t chunk = *p; + uint64_t v2 = chunk ^ valuemask; + start = (p - reinterpret_cast(m_data)) * 8 * 8 / no0(width); + size_t a = 0; + + while (eq ? test_zero(v2) : v2) { + + if (find_action_pattern(start + baseindex, cascade(v2), state, callback)) + break; // consumed + + size_t t = find_zero(v2); + a += t; + + if (a >= 64 / no0(width)) + break; + + if (!find_action(a + start + baseindex, get(start + t), state, callback)) + return false; + v2 >>= (t + 1) * width; + a += 1; + } + + ++p; + } + + // Loop ended because we are near end or end of array. No need to optimize search in remainder in this case + // because end of array means that + // lots of search work has taken place prior to ending here. So time spent searching remainder is relatively + // tiny + start = (p - reinterpret_cast(m_data)) * 8 * 8 / no0(width); + } + + while (start < end) { + if (eq ? get(start) == value : get(start) != value) { + if (!find_action(start + baseindex, get(start), state, callback)) + return false; + } + ++start; + } + + return true; +} + +// There exists a couple of find() functions that take more or less template arguments. Always call the one that +// takes as most as possible to get best performance. + +// This is the one installed into the m_vtable->finder slots. +template +bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state) const +{ + return find(value, start, end, baseindex, state, CallbackDummy()); +} + +template +bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback, bool nullable_array, bool find_null) const +{ + REALM_TEMPEX4(return find, cond, action, m_width, Callback, + (value, start, end, baseindex, state, callback, nullable_array, find_null)); +} + +template +bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback, bool nullable_array, bool find_null) const +{ + return find_optimized(value, start, end, baseindex, state, callback, + nullable_array, find_null); +} + +#ifdef REALM_COMPILER_SSE +// 'items' is the number of 16-byte SSE chunks. Returns index of packed element relative to first integer of first +// chunk +template +bool Array::find_sse(int64_t value, __m128i* data, size_t items, QueryState* state, size_t baseindex, + Callback callback) const +{ + __m128i search = {0}; + + if (width == 8) + search = _mm_set1_epi8(static_cast(value)); + else if (width == 16) + search = _mm_set1_epi16(static_cast(value)); + else if (width == 32) + search = _mm_set1_epi32(static_cast(value)); + else if (width == 64) { + if (std::is_same::value) + REALM_ASSERT(false); + else + search = _mm_set_epi64x(value, value); + } + + return find_sse_intern(data, &search, items, state, baseindex, callback); +} + +// Compares packed action_data with packed data (equal, less, etc) and performs aggregate action (max, min, sum, +// find_all, etc) on value inside action_data for first match, if any +template +REALM_FORCEINLINE bool Array::find_sse_intern(__m128i* action_data, __m128i* data, size_t items, + QueryState* state, size_t baseindex, Callback callback) const +{ + size_t i = 0; + __m128i compare_result = {0}; + unsigned int resmask; + + // Search loop. Unrolling it has been tested to NOT increase performance (apparently mem bound) + for (i = 0; i < items; ++i) { + // equal / not-equal + if (std::is_same::value || std::is_same::value) { + if (width == 8) + compare_result = _mm_cmpeq_epi8(action_data[i], *data); + if (width == 16) + compare_result = _mm_cmpeq_epi16(action_data[i], *data); + if (width == 32) + compare_result = _mm_cmpeq_epi32(action_data[i], *data); + if (width == 64) { + compare_result = _mm_cmpeq_epi64(action_data[i], *data); // SSE 4.2 only + } + } + + // greater + else if (std::is_same::value) { + if (width == 8) + compare_result = _mm_cmpgt_epi8(action_data[i], *data); + if (width == 16) + compare_result = _mm_cmpgt_epi16(action_data[i], *data); + if (width == 32) + compare_result = _mm_cmpgt_epi32(action_data[i], *data); + if (width == 64) + compare_result = _mm_cmpgt_epi64(action_data[i], *data); + } + // less + else if (std::is_same::value) { + if (width == 8) + compare_result = _mm_cmplt_epi8(action_data[i], *data); + else if (width == 16) + compare_result = _mm_cmplt_epi16(action_data[i], *data); + else if (width == 32) + compare_result = _mm_cmplt_epi32(action_data[i], *data); + else + REALM_ASSERT(false); + } + + resmask = _mm_movemask_epi8(compare_result); + + if (std::is_same::value) + resmask = ~resmask & 0x0000ffff; + + size_t s = i * sizeof(__m128i) * 8 / no0(width); + + while (resmask != 0) { + + uint64_t upper = lower_bits() << (no0(width / 8) - 1); + uint64_t pattern = + resmask & + upper; // fixme, bits at wrong offsets. Only OK because we only use them in 'count' aggregate + if (find_action_pattern(s + baseindex, pattern, state, callback)) + break; + + size_t idx = first_set_bit(resmask) * 8 / no0(width); + s += idx; + if (!find_action( + s + baseindex, get_universal(reinterpret_cast(action_data), s), state, callback)) + return false; + resmask >>= (idx + 1) * no0(width) / 8; + ++s; + } + } + + return true; +} +#endif // REALM_COMPILER_SSE + +template +bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, + QueryState* state, Callback callback) const +{ + cond c; + REALM_ASSERT_3(start, <=, end); + if (start == end) + return true; + + + int64_t v; + + // We can compare first element without checking for out-of-range + v = get(start); + if (c(v, foreign->get(start))) { + if (!find_action(start + baseindex, v, state, callback)) + return false; + } + + start++; + + if (start + 3 < end) { + v = get(start); + if (c(v, foreign->get(start))) + if (!find_action(start + baseindex, v, state, callback)) + return false; + + v = get(start + 1); + if (c(v, foreign->get(start + 1))) + if (!find_action(start + 1 + baseindex, v, state, callback)) + return false; + + v = get(start + 2); + if (c(v, foreign->get(start + 2))) + if (!find_action(start + 2 + baseindex, v, state, callback)) + return false; + + start += 3; + } + else if (start == end) { + return true; + } + + bool r; + REALM_TEMPEX4(r = compare_leafs, cond, action, m_width, Callback, + (foreign, start, end, baseindex, state, callback)) + return r; +} + + +template +bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, + QueryState* state, Callback callback) const +{ + size_t fw = foreign->m_width; + bool r; + REALM_TEMPEX5(r = compare_leafs_4, cond, action, width, Callback, fw, + (foreign, start, end, baseindex, state, callback)) + return r; +} + + +template +bool Array::compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex, + QueryState* state, Callback callback) const +{ + cond c; + char* foreign_m_data = foreign->m_data; + + if (width == 0 && foreign_width == 0) { + if (c(0, 0)) { + while (start < end) { + if (!find_action(start + baseindex, 0, state, callback)) + return false; + start++; + } + } + else { + return true; + } + } + + +#if defined(REALM_COMPILER_SSE) + if (sseavx<42>() && width == foreign_width && (width == 8 || width == 16 || width == 32)) { + // We can only use SSE if both bitwidths are equal and above 8 bits and all values are signed + while (start < end && (((reinterpret_cast(m_data) & 0xf) * 8 + start * width) % (128) != 0)) { + int64_t v = get_universal(m_data, start); + int64_t fv = get_universal(foreign_m_data, start); + if (c(v, fv)) { + if (!find_action(start + baseindex, v, state, callback)) + return false; + } + start++; + } + if (start == end) + return true; + + + size_t sse_items = (end - start) * width / 128; + size_t sse_end = start + sse_items * 128 / no0(width); + + while (start < sse_end) { + __m128i* a = reinterpret_cast<__m128i*>(m_data + start * width / 8); + __m128i* b = reinterpret_cast<__m128i*>(foreign_m_data + start * width / 8); + + bool continue_search = + find_sse_intern(a, b, 1, state, baseindex + start, callback); + + if (!continue_search) + return false; + + start += 128 / no0(width); + } + } +#endif + + while (start < end) { + int64_t v = get_universal(m_data, start); + int64_t fv = get_universal(foreign_m_data, start); + + if (c(v, fv)) { + if (!find_action(start + baseindex, v, state, callback)) + return false; + } + + start++; + } + + return true; +} + + +template +bool Array::compare(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const +{ + bool ret = false; + + if (std::is_same::value) + ret = compare_equality(value, start, end, baseindex, state, callback); + else if (std::is_same::value) + ret = compare_equality(value, start, end, baseindex, state, callback); + else if (std::is_same::value) + ret = compare_relation(value, start, end, baseindex, state, callback); + else if (std::is_same::value) + ret = compare_relation(value, start, end, baseindex, state, callback); + else + REALM_ASSERT_DEBUG(false); + + return ret; +} + +template +bool Array::compare_relation(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const +{ + REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); + uint64_t mask = (bitwidth == 64 ? ~0ULL : ((1ULL << (bitwidth == 64 ? 0 : bitwidth)) - + 1ULL)); // Warning free way of computing (1ULL << width) - 1 + + size_t ee = round_up(start, 64 / no0(bitwidth)); + ee = ee > end ? end : ee; + for (; start < ee; start++) { + if (gt ? (get(start) > value) : (get(start) < value)) { + if (!find_action(start + baseindex, get(start), state, callback)) + return false; + } + } + + if (start >= end) + return true; // none found, continue (return true) regardless what find_action() would have returned on match + + const int64_t* p = reinterpret_cast(m_data + (start * bitwidth / 8)); + const int64_t* const e = reinterpret_cast(m_data + (end * bitwidth / 8)) - 1; + + // Matches are rare enough to setup fast linear search for remaining items. We use + // bit hacks from http://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord + + if (bitwidth == 1 || bitwidth == 2 || bitwidth == 4 || bitwidth == 8 || bitwidth == 16) { + uint64_t magic = find_gtlt_magic(value); + + // Bit hacks only work if searched item has its most significant bit clear for 'greater than' or + // 'item <= 1 << bitwidth' for 'less than' + if (value != int64_t((magic & mask)) && value >= 0 && bitwidth >= 2 && + value <= static_cast((mask >> 1) - (gt ? 1 : 0))) { + // 15 ms + while (p < e) { + uint64_t upper = lower_bits() << (no0(bitwidth) - 1); + + const int64_t v = *p; + size_t idx; + + // Bit hacks only works if all items in chunk have their most significant bit clear. Test this: + upper = upper & v; + + if (!upper) { + idx = find_gtlt_fast( + v, magic, state, (p - reinterpret_cast(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, + callback); + } + else + idx = find_gtlt( + value, v, state, (p - reinterpret_cast(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, + callback); + + if (!idx) + return false; + ++p; + } + } + else { + // 24 ms + while (p < e) { + int64_t v = *p; + if (!find_gtlt( + value, v, state, (p - reinterpret_cast(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, + callback)) + return false; + ++p; + } + } + start = (p - reinterpret_cast(m_data)) * 8 * 8 / no0(bitwidth); + } + + // matchcount logic in SIMD no longer pays off for 32/64 bit ints because we have just 4/2 elements + + // Test unaligned end and/or values of width > 16 manually + while (start < end) { + if (gt ? get(start) > value : get(start) < value) { + if (!find_action(start + baseindex, get(start), state, callback)) + return false; + } + ++start; + } + return true; +} + +template +size_t Array::find_first(int64_t value, size_t start, size_t end) const +{ + REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); + QueryState state; + state.init(act_ReturnFirst, nullptr, + 1); // todo, would be nice to avoid this in order to speed up find_first loops + Finder finder = m_vtable->finder[cond::condition]; + (this->*finder)(value, start, end, 0, &state); + + return static_cast(state.m_state); +} + +//************************************************************************************* +// Finding code ends * +//************************************************************************************* + + +} // namespace realm + +#endif // REALM_ARRAY_HPP diff --git a/Pods/Realm/include/core/realm/array_basic.hpp b/Pods/Realm/include/core/realm/array_basic.hpp new file mode 100644 index 0000000000..6b9c212f47 --- /dev/null +++ b/Pods/Realm/include/core/realm/array_basic.hpp @@ -0,0 +1,120 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_BASIC_HPP +#define REALM_ARRAY_BASIC_HPP + +#include + +namespace realm { + +/// A BasicArray can currently only be used for simple unstructured +/// types like float, double. +template +class BasicArray : public Array { +public: + explicit BasicArray(Allocator&) noexcept; + ~BasicArray() noexcept override + { + } + + // Disable copying, this is not allowed. + BasicArray& operator=(const BasicArray&) = delete; + BasicArray(const BasicArray&) = delete; + + T get(size_t ndx) const noexcept; + bool is_null(size_t ndx) const noexcept; + void add(T value); + void set(size_t ndx, T value); + void set_null(size_t ndx); + void insert(size_t ndx, T value); + void erase(size_t ndx); + void truncate(size_t size); + void clear(); + + size_t find_first(T value, size_t begin = 0, size_t end = npos) const; + void find_all(IntegerColumn* result, T value, size_t add_offset = 0, size_t begin = 0, size_t end = npos) const; + + size_t count(T value, size_t begin = 0, size_t end = npos) const; + bool maximum(T& result, size_t begin = 0, size_t end = npos) const; + bool minimum(T& result, size_t begin = 0, size_t end = npos) const; + + /// Compare two arrays for equality. + bool compare(const BasicArray&) const; + + /// Get the specified element without the cost of constructing an + /// array instance. If an array instance is already available, or + /// you need to get multiple values, then this method will be + /// slower. + static T get(const char* header, size_t ndx) noexcept; + + ref_type bptree_leaf_insert(size_t ndx, T, TreeInsertBase& state); + + size_t lower_bound(T value) const noexcept; + size_t upper_bound(T value) const noexcept; + + /// Construct a basic array of the specified size and return just + /// the reference to the underlying memory. All elements will be + /// initialized to `T()`. + static MemRef create_array(size_t size, Allocator&); + + static MemRef create_array(Array::Type leaf_type, bool context_flag, size_t size, T value, Allocator&); + + /// Create a new empty array and attach this accessor to it. This + /// does not modify the parent reference information of this + /// accessor. + /// + /// Note that the caller assumes ownership of the allocated + /// underlying node. It is not owned by the accessor. + void create(Array::Type = type_Normal, bool context_flag = false); + + /// Construct a copy of the specified slice of this basic array + /// using the specified target allocator. + MemRef slice(size_t offset, size_t size, Allocator& target_alloc) const; + MemRef slice_and_clone_children(size_t offset, size_t size, Allocator& target_alloc) const; + +#ifdef REALM_DEBUG + void to_dot(std::ostream&, StringData title = StringData()) const; +#endif + +private: + size_t find(T target, size_t begin, size_t end) const; + + size_t calc_byte_len(size_t count, size_t width) const override; + virtual size_t calc_item_count(size_t bytes, size_t width) const noexcept override; + + template + bool minmax(T& result, size_t begin, size_t end) const; + + /// Calculate the total number of bytes needed for a basic array + /// with the specified number of elements. This includes the size + /// of the header. The result will be upwards aligned to the + /// closest 8-byte boundary. + static size_t calc_aligned_byte_size(size_t size); +}; + + +// Class typedefs for BasicArray's: ArrayFloat and ArrayDouble +typedef BasicArray ArrayFloat; +typedef BasicArray ArrayDouble; + +} // namespace realm + +#include + +#endif // REALM_ARRAY_BASIC_HPP diff --git a/Pods/Realm/include/core/realm/array_basic_tpl.hpp b/Pods/Realm/include/core/realm/array_basic_tpl.hpp new file mode 100644 index 0000000000..5ce37fde1f --- /dev/null +++ b/Pods/Realm/include/core/realm/array_basic_tpl.hpp @@ -0,0 +1,467 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_BASIC_TPL_HPP +#define REALM_ARRAY_BASIC_TPL_HPP + +#include +#include +#include +#include + +#include + +namespace realm { + +template +inline BasicArray::BasicArray(Allocator& allocator) noexcept + : Array(allocator) +{ +} + +template +inline MemRef BasicArray::create_array(size_t init_size, Allocator& allocator) +{ + size_t byte_size_0 = calc_aligned_byte_size(init_size); // Throws + // Adding zero to Array::initial_capacity to avoid taking the + // address of that member + size_t byte_size = std::max(byte_size_0, Array::initial_capacity + 0); // Throws + + MemRef mem = allocator.alloc(byte_size); // Throws + + bool is_inner_bptree_node = false; + bool has_refs = false; + bool context_flag = false; + int width = sizeof(T); + init_header(mem.get_addr(), is_inner_bptree_node, has_refs, context_flag, wtype_Multiply, width, init_size, + byte_size); + + return mem; +} + + +template +inline MemRef BasicArray::create_array(Array::Type type, bool context_flag, size_t init_size, T value, + Allocator& allocator) +{ + REALM_ASSERT(type == Array::type_Normal); + REALM_ASSERT(!context_flag); + MemRef mem = create_array(init_size, allocator); + if (init_size) { + // GCC 7.x emits a false-positive strict aliasing warning for this code. Suppress it, since it + // clutters up the build output. See for details. + REALM_DIAG_PUSH(); + REALM_DIAG(ignored "-Wstrict-aliasing"); + + BasicArray tmp(allocator); + tmp.init_from_mem(mem); + T* p = reinterpret_cast(tmp.m_data); + T* end = p + init_size; + while (p < end) { + *p++ = value; + } + + REALM_DIAG_POP(); + } + return mem; +} + + +template +inline void BasicArray::create(Array::Type type, bool context_flag) +{ + REALM_ASSERT(type == Array::type_Normal); + REALM_ASSERT(!context_flag); + size_t length = 0; + MemRef mem = create_array(length, get_alloc()); // Throws + init_from_mem(mem); +} + + +template +MemRef BasicArray::slice(size_t offset, size_t slice_size, Allocator& target_alloc) const +{ + REALM_ASSERT(is_attached()); + + // FIXME: This can be optimized as a single contiguous copy + // operation. + BasicArray array_slice(target_alloc); + _impl::ShallowArrayDestroyGuard dg(&array_slice); + array_slice.create(); // Throws + size_t begin = offset; + size_t end = offset + slice_size; + for (size_t i = begin; i != end; ++i) { + T value = get(i); + array_slice.add(value); // Throws + } + dg.release(); + return array_slice.get_mem(); +} + +template +MemRef BasicArray::slice_and_clone_children(size_t offset, size_t slice_size, Allocator& target_alloc) const +{ + // BasicArray never contains refs, so never has children. + return slice(offset, slice_size, target_alloc); +} + + +template +inline void BasicArray::add(T value) +{ + insert(m_size, value); +} + + +template +inline T BasicArray::get(size_t ndx) const noexcept +{ + return *(reinterpret_cast(m_data) + ndx); +} + + +template +inline bool BasicArray::is_null(size_t ndx) const noexcept +{ + // FIXME: This assumes BasicArray will only ever be instantiated for float-like T. + static_assert(realm::is_any::value, "T can only be float or double"); + auto x = get(ndx); + return null::is_null_float(x); +} + + +template +inline T BasicArray::get(const char* header, size_t ndx) noexcept +{ + const char* data = get_data_from_header(header); + // This casting assumes that T can be aliged on an 8-bype + // boundary (since data is aligned on an 8-byte boundary.) + return *(reinterpret_cast(data) + ndx); +} + + +template +inline void BasicArray::set(size_t ndx, T value) +{ + REALM_ASSERT_3(ndx, <, m_size); + if (get(ndx) == value) + return; + + // Check if we need to copy before modifying + copy_on_write(); // Throws + + // Set the value + T* data = reinterpret_cast(m_data) + ndx; + *data = value; +} + +template +inline void BasicArray::set_null(size_t ndx) +{ + // FIXME: This assumes BasicArray will only ever be instantiated for float-like T. + set(ndx, null::get_null_float()); +} + +template +void BasicArray::insert(size_t ndx, T value) +{ + REALM_ASSERT_3(ndx, <=, m_size); + + // Check if we need to copy before modifying + copy_on_write(); // Throws + + // Make room for the new value + alloc(m_size + 1, m_width); // Throws + + // Move values below insertion + if (ndx != m_size) { + char* src_begin = m_data + ndx * m_width; + char* src_end = m_data + m_size * m_width; + char* dst_end = src_end + m_width; + std::copy_backward(src_begin, src_end, dst_end); + } + + // Set the value + T* data = reinterpret_cast(m_data) + ndx; + *data = value; + + ++m_size; +} + +template +void BasicArray::erase(size_t ndx) +{ + REALM_ASSERT_3(ndx, <, m_size); + + // Check if we need to copy before modifying + copy_on_write(); // Throws + + // move data under deletion up + if (ndx < m_size - 1) { + char* dst_begin = m_data + ndx * m_width; + const char* src_begin = dst_begin + m_width; + const char* src_end = m_data + m_size * m_width; + realm::safe_copy_n(src_begin, src_end - src_begin, dst_begin); + } + + // Update size (also in header) + --m_size; + set_header_size(m_size); +} + +template +void BasicArray::truncate(size_t to_size) +{ + REALM_ASSERT(is_attached()); + REALM_ASSERT_3(to_size, <=, m_size); + + copy_on_write(); // Throws + + // Update size in accessor and in header. This leaves the capacity + // unchanged. + m_size = to_size; + set_header_size(to_size); +} + +template +inline void BasicArray::clear() +{ + truncate(0); // Throws +} + +template +bool BasicArray::compare(const BasicArray& a) const +{ + size_t n = size(); + if (a.size() != n) + return false; + const T* data_1 = reinterpret_cast(m_data); + const T* data_2 = reinterpret_cast(a.m_data); + return realm::safe_equal(data_1, data_1 + n, data_2); +} + + +template +size_t BasicArray::calc_byte_len(size_t for_size, size_t) const +{ + // FIXME: Consider calling `calc_aligned_byte_size(size)` + // instead. Note however, that calc_byte_len() is supposed to return + // the unaligned byte size. It is probably the case that no harm + // is done by returning the aligned version, and most callers of + // calc_byte_len() will actually benefit if calc_byte_len() was + // changed to always return the aligned byte size. + return header_size + for_size * sizeof(T); +} + +template +size_t BasicArray::calc_item_count(size_t bytes, size_t) const noexcept +{ + size_t bytes_without_header = bytes - header_size; + return bytes_without_header / sizeof(T); +} + +template +size_t BasicArray::find(T value, size_t begin, size_t end) const +{ + if (end == npos) + end = m_size; + REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end); + const T* data = reinterpret_cast(m_data); + const T* i = std::find(data + begin, data + end, value); + return i == data + end ? not_found : size_t(i - data); +} + +template +inline size_t BasicArray::find_first(T value, size_t begin, size_t end) const +{ + return this->find(value, begin, end); +} + +template +void BasicArray::find_all(IntegerColumn* result, T value, size_t add_offset, size_t begin, size_t end) const +{ + size_t first = begin - 1; + for (;;) { + first = this->find(value, first + 1, end); + if (first == not_found) + break; + + Array::add_to_column(result, first + add_offset); + } +} + +template +size_t BasicArray::count(T value, size_t begin, size_t end) const +{ + if (end == npos) + end = m_size; + REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end); + const T* data = reinterpret_cast(m_data); + return std::count(data + begin, data + end, value); +} + +#if 0 +// currently unused +template +double BasicArray::sum(size_t begin, size_t end) const +{ + if (end == npos) + end = m_size; + REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end); + const T* data = reinterpret_cast(m_data); + return std::accumulate(data + begin, data + end, double(0)); +} +#endif + +template +template +bool BasicArray::minmax(T& result, size_t begin, size_t end) const +{ + if (end == npos) + end = m_size; + if (m_size == 0) + return false; + REALM_ASSERT(begin < m_size && end <= m_size && begin < end); + + T m = get(begin); + ++begin; + for (; begin < end; ++begin) { + T val = get(begin); + if (find_max ? val > m : val < m) + m = val; + } + result = m; + return true; +} + +template +bool BasicArray::maximum(T& result, size_t begin, size_t end) const +{ + return minmax(result, begin, end); +} + +template +bool BasicArray::minimum(T& result, size_t begin, size_t end) const +{ + return minmax(result, begin, end); +} + + +template +ref_type BasicArray::bptree_leaf_insert(size_t ndx, T value, TreeInsertBase& state) +{ + size_t leaf_size = size(); + REALM_ASSERT_3(leaf_size, <=, REALM_MAX_BPNODE_SIZE); + if (leaf_size < ndx) + ndx = leaf_size; + if (REALM_LIKELY(leaf_size < REALM_MAX_BPNODE_SIZE)) { + insert(ndx, value); + return 0; // Leaf was not split + } + + // Split leaf node + BasicArray new_leaf(get_alloc()); + new_leaf.create(); // Throws + if (ndx == leaf_size) { + new_leaf.add(value); + state.m_split_offset = ndx; + } + else { + // FIXME: Could be optimized by first resizing the target + // array, then copy elements with std::copy(). + for (size_t i = ndx; i != leaf_size; ++i) + new_leaf.add(get(i)); + truncate(ndx); + add(value); + state.m_split_offset = ndx + 1; + } + state.m_split_size = leaf_size + 1; + return new_leaf.get_ref(); +} + +template +inline size_t BasicArray::lower_bound(T value) const noexcept +{ + const T* begin = reinterpret_cast(m_data); + const T* end = begin + size(); + return std::lower_bound(begin, end, value) - begin; +} + +template +inline size_t BasicArray::upper_bound(T value) const noexcept +{ + const T* begin = reinterpret_cast(m_data); + const T* end = begin + size(); + return std::upper_bound(begin, end, value) - begin; +} + +template +inline size_t BasicArray::calc_aligned_byte_size(size_t size) +{ + size_t max = std::numeric_limits::max(); + size_t max_2 = max & ~size_t(7); // Allow for upwards 8-byte alignment + if (size > (max_2 - header_size) / sizeof(T)) + throw util::overflow_error("Byte size overflow"); + size_t byte_size = header_size + size * sizeof(T); + REALM_ASSERT_3(byte_size, >, 0); + size_t aligned_byte_size = ((byte_size - 1) | 7) + 1; // 8-byte alignment + return aligned_byte_size; +} + + +#ifdef REALM_DEBUG + +// LCOV_EXCL_START +template +void BasicArray::to_dot(std::ostream& out, StringData title) const +{ + ref_type ref = get_ref(); + if (title.size() != 0) { + out << "subgraph cluster_" << ref << " {\n"; + out << " label = \"" << title << "\";\n"; + out << " color = white;\n"; + } + + out << "n" << std::hex << ref << std::dec << "[shape=none,label=<"; + out << "
\n"; + + // Header + out << "\n"; + + // Values + size_t n = m_size; + for (size_t i = 0; i != n; ++i) + out << "\n"; + + out << "
"; + out << "0x" << std::hex << ref << std::dec << "
"; + out << "
" << get(i) << "
>];\n"; + + if (title.size() != 0) + out << "}\n"; + + to_dot_parent_edge(out); +} +// LCOV_EXCL_STOP + +#endif // REALM_DEBUG + + +} // namespace realm + +#endif // REALM_ARRAY_BASIC_TPL_HPP diff --git a/Pods/Realm/include/core/realm/array_binary.hpp b/Pods/Realm/include/core/realm/array_binary.hpp new file mode 100644 index 0000000000..347c7be5c5 --- /dev/null +++ b/Pods/Realm/include/core/realm/array_binary.hpp @@ -0,0 +1,259 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_BINARY_HPP +#define REALM_ARRAY_BINARY_HPP + +#include +#include +#include +#include + +namespace realm { + +/* +STORAGE FORMAT +--------------------------------------------------------------------------------------- +ArrayBinary stores binary elements using two ArrayInteger and one ArrayBlob. The ArrayBlob can only store one +single concecutive array of bytes (contrary to its 'Array' name that misleadingly indicates it could store multiple +elements). + +Assume we have the strings "a", "", "abc", null, "ab". Then the three arrays will contain: + +ArrayInteger m_offsets 1, 1, 5, 5, 6 +ArrayBlob m_blob aabcab +ArrayInteger m_nulls 0, 0, 0, 1, 0 // 1 indicates null, 0 indicates non-null + +So for each element the ArrayInteger, the ArrayInteger points into the ArrayBlob at the position of the first +byte of the next element. + +m_nulls is always present (except for old database files; see below), so any ArrayBinary is always nullable! +The nullable property (such as throwing exception upon set(null) on non-nullable column, etc) is handled on +column level only. + +DATABASE FILE VERSION CHANGES +--------------------------------------------------------------------------------------- +Old database files do not have any m_nulls array. To be backwardscompatible, many methods will have tests like +`if(Array::size() == 3)` and have a backwards compatible code paths for these (e.g. avoid writing to m_nulls +in set(), etc). This way no file format upgrade is needed to support nulls for BinaryData. +*/ + +class ArrayBinary : public Array { +public: + explicit ArrayBinary(Allocator&) noexcept; + ~ArrayBinary() noexcept override + { + } + + // Disable copying, this is not allowed. + ArrayBinary& operator=(const ArrayBinary&) = delete; + ArrayBinary(const ArrayBinary&) = delete; + + /// Create a new empty binary array and attach this accessor to + /// it. This does not modify the parent reference information of + /// this accessor. + /// + /// Note that the caller assumes ownership of the allocated + /// underlying node. It is not owned by the accessor. + void create(); + + // Old database files will not have the m_nulls array, so we need code paths for + // backwards compatibility for these cases. + bool legacy_array_type() const noexcept; + + //@{ + /// Overriding functions of Array + void init_from_ref(ref_type) noexcept; + void init_from_mem(MemRef) noexcept; + void init_from_parent() noexcept; + //@} + + bool is_empty() const noexcept; + size_t size() const noexcept; + + BinaryData get(size_t ndx) const noexcept; + size_t read(size_t ndx, size_t pos, char* buffer, size_t max_size) const noexcept; + + void add(BinaryData value, bool add_zero_term = false); + void set(size_t ndx, BinaryData value, bool add_zero_term = false); + void insert(size_t ndx, BinaryData value, bool add_zero_term = false); + void erase(size_t ndx); + void truncate(size_t new_size); + void clear(); + void destroy(); + + /// Get the specified element without the cost of constructing an + /// array instance. If an array instance is already available, or + /// you need to get multiple values, then this method will be + /// slower. + static BinaryData get(const char* header, size_t ndx, Allocator&) noexcept; + + ref_type bptree_leaf_insert(size_t ndx, BinaryData, bool add_zero_term, TreeInsertBase& state); + + static size_t get_size_from_header(const char*, Allocator&) noexcept; + + /// Construct a binary array of the specified size and return just + /// the reference to the underlying memory. All elements will be + /// initialized to the binary value `defaults`, which can be either + /// null or zero-length non-null (value with size > 0 is not allowed as + /// initialization value). + static MemRef create_array(size_t size, Allocator&, BinaryData defaults); + + /// Construct a copy of the specified slice of this binary array + /// using the specified target allocator. + MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; + +#ifdef REALM_DEBUG + void to_dot(std::ostream&, bool is_strings, StringData title = StringData()) const; +#endif + bool update_from_parent(size_t old_baseline) noexcept; + +private: + ArrayInteger m_offsets; + ArrayBlob m_blob; + ArrayInteger m_nulls; +}; + + +// Implementation: + +inline ArrayBinary::ArrayBinary(Allocator& allocator) noexcept + : Array(allocator) + , m_offsets(allocator) + , m_blob(allocator) + , m_nulls(allocator) +{ + m_offsets.set_parent(this, 0); + m_blob.set_parent(this, 1); + m_nulls.set_parent(this, 2); +} + +inline void ArrayBinary::create() +{ + size_t init_size = 0; + BinaryData defaults = BinaryData{}; // This init value is ignored because size = 0 + MemRef mem = create_array(init_size, get_alloc(), defaults); // Throws + init_from_mem(mem); +} + +inline void ArrayBinary::init_from_ref(ref_type ref) noexcept +{ + REALM_ASSERT(ref); + char* header = get_alloc().translate(ref); + init_from_mem(MemRef(header, ref, m_alloc)); +} + +inline void ArrayBinary::init_from_parent() noexcept +{ + ref_type ref = get_ref_from_parent(); + init_from_ref(ref); +} + +inline bool ArrayBinary::is_empty() const noexcept +{ + return m_offsets.is_empty(); +} + +// Old database files will not have the m_nulls array, so we need code paths for +// backwards compatibility for these cases. We can test if m_nulls exists by looking +// at number of references in this ArrayBinary. +inline bool ArrayBinary::legacy_array_type() const noexcept +{ + if (Array::size() == 3) + return false; // New database file + else if (Array::size() == 2) + return true; // Old database file + else + REALM_ASSERT(false); // Should never happen + return false; +} + +inline size_t ArrayBinary::size() const noexcept +{ + return m_offsets.size(); +} + +inline BinaryData ArrayBinary::get(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, m_offsets.size()); + + if (!legacy_array_type() && m_nulls.get(ndx)) { + return BinaryData(); + } + else { + size_t begin = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0; + size_t end = to_size_t(m_offsets.get(ndx)); + + BinaryData bd = BinaryData(m_blob.get(begin), end - begin); + // Old database file (non-nullable column should never return null) + REALM_ASSERT(!bd.is_null()); + return bd; + } +} + +inline void ArrayBinary::truncate(size_t new_size) +{ + REALM_ASSERT_3(new_size, <, m_offsets.size()); + + size_t sz = new_size ? to_size_t(m_offsets.get(new_size - 1)) : 0; + + m_offsets.truncate(new_size); + m_blob.truncate(sz); + if (!legacy_array_type()) + m_nulls.truncate(new_size); +} + +inline void ArrayBinary::clear() +{ + m_blob.clear(); + m_offsets.clear(); + if (!legacy_array_type()) + m_nulls.clear(); +} + +inline void ArrayBinary::destroy() +{ + m_blob.destroy(); + m_offsets.destroy(); + if (!legacy_array_type()) + m_nulls.destroy(); + Array::destroy(); +} + +inline size_t ArrayBinary::get_size_from_header(const char* header, Allocator& alloc) noexcept +{ + ref_type offsets_ref = to_ref(Array::get(header, 0)); + const char* offsets_header = alloc.translate(offsets_ref); + return Array::get_size_from_header(offsets_header); +} + +inline bool ArrayBinary::update_from_parent(size_t old_baseline) noexcept +{ + bool res = Array::update_from_parent(old_baseline); + if (res) { + m_blob.update_from_parent(old_baseline); + m_offsets.update_from_parent(old_baseline); + if (!legacy_array_type()) + m_nulls.update_from_parent(old_baseline); + } + return res; +} + +} // namespace realm + +#endif // REALM_ARRAY_BINARY_HPP diff --git a/Pods/Realm/include/core/realm/array_blob.hpp b/Pods/Realm/include/core/realm/array_blob.hpp new file mode 100644 index 0000000000..556d40a3bb --- /dev/null +++ b/Pods/Realm/include/core/realm/array_blob.hpp @@ -0,0 +1,146 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_BLOB_HPP +#define REALM_ARRAY_BLOB_HPP + +#include + +namespace realm { + + +class ArrayBlob : public Array { +public: + static constexpr size_t max_binary_size = 0xFFFFF8 - Array::header_size; + + explicit ArrayBlob(Allocator&) noexcept; + ~ArrayBlob() noexcept override + { + } + + // Disable copying, this is not allowed. + ArrayBlob& operator=(const ArrayBlob&) = delete; + ArrayBlob(const ArrayBlob&) = delete; + + const char* get(size_t index) const noexcept; + BinaryData get_at(size_t& pos) const noexcept; + bool is_null(size_t index) const noexcept; + ref_type add(const char* data, size_t data_size, bool add_zero_term = false); + void insert(size_t pos, const char* data, size_t data_size, bool add_zero_term = false); + ref_type replace(size_t begin, size_t end, const char* data, size_t data_size, bool add_zero_term = false); + void erase(size_t begin, size_t end); + + /// Get the specified element without the cost of constructing an + /// array instance. If an array instance is already available, or + /// you need to get multiple values, then this method will be + /// slower. + static const char* get(const char* header, size_t index) noexcept; + + /// Create a new empty blob (binary) array and attach this + /// accessor to it. This does not modify the parent reference + /// information of this accessor. + /// + /// Note that the caller assumes ownership of the allocated + /// underlying node. It is not owned by the accessor. + void create(); + + /// Construct a blob of the specified size and return just the + /// reference to the underlying memory. All bytes will be + /// initialized to zero. + static MemRef create_array(size_t init_size, Allocator&); + +#ifdef REALM_DEBUG + void verify() const; + void to_dot(std::ostream&, StringData title = StringData()) const; +#endif + +private: + size_t calc_byte_len(size_t for_size, size_t width) const override; + size_t calc_item_count(size_t bytes, size_t width) const noexcept override; +}; + + +// Implementation: + +// Creates new array (but invalid, call init_from_ref() to init) +inline ArrayBlob::ArrayBlob(Allocator& allocator) noexcept + : Array(allocator) +{ +} + +inline bool ArrayBlob::is_null(size_t index) const noexcept +{ + return (get(index) == nullptr); +} + +inline const char* ArrayBlob::get(size_t index) const noexcept +{ + return m_data + index; +} + +inline ref_type ArrayBlob::add(const char* data, size_t data_size, bool add_zero_term) +{ + return replace(m_size, m_size, data, data_size, add_zero_term); +} + +inline void ArrayBlob::insert(size_t pos, const char* data, size_t data_size, bool add_zero_term) +{ + replace(pos, pos, data, data_size, add_zero_term); +} + +inline void ArrayBlob::erase(size_t begin, size_t end) +{ + const char* data = nullptr; + size_t data_size = 0; + replace(begin, end, data, data_size); +} + +inline const char* ArrayBlob::get(const char* header, size_t pos) noexcept +{ + const char* data = get_data_from_header(header); + return data + pos; +} + +inline void ArrayBlob::create() +{ + size_t init_size = 0; + MemRef mem = create_array(init_size, get_alloc()); // Throws + init_from_mem(mem); +} + +inline MemRef ArrayBlob::create_array(size_t init_size, Allocator& allocator) +{ + bool context_flag = false; + int_fast64_t value = 0; + return Array::create(type_Normal, context_flag, wtype_Ignore, init_size, value, allocator); // Throws +} + +inline size_t ArrayBlob::calc_byte_len(size_t for_size, size_t) const +{ + return header_size + for_size; +} + +inline size_t ArrayBlob::calc_item_count(size_t bytes, size_t) const noexcept +{ + return bytes - header_size; +} + + +} // namespace realm + +#endif // REALM_ARRAY_BLOB_HPP diff --git a/Pods/Realm/include/core/realm/array_blobs_big.hpp b/Pods/Realm/include/core/realm/array_blobs_big.hpp new file mode 100644 index 0000000000..cc793fb5e7 --- /dev/null +++ b/Pods/Realm/include/core/realm/array_blobs_big.hpp @@ -0,0 +1,222 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_BIG_BLOBS_HPP +#define REALM_ARRAY_BIG_BLOBS_HPP + +#include + +namespace realm { + + +class ArrayBigBlobs : public Array { +public: + typedef BinaryData value_type; + + explicit ArrayBigBlobs(Allocator&, bool nullable) noexcept; + + // Disable copying, this is not allowed. + ArrayBigBlobs& operator=(const ArrayBigBlobs&) = delete; + ArrayBigBlobs(const ArrayBigBlobs&) = delete; + + BinaryData get(size_t ndx) const noexcept; + BinaryData get_at(size_t ndx, size_t& pos) const noexcept; + void set(size_t ndx, BinaryData value, bool add_zero_term = false); + void add(BinaryData value, bool add_zero_term = false); + void insert(size_t ndx, BinaryData value, bool add_zero_term = false); + void erase(size_t ndx); + void truncate(size_t new_size); + void clear(); + void destroy(); + + size_t count(BinaryData value, bool is_string = false, size_t begin = 0, size_t end = npos) const noexcept; + size_t find_first(BinaryData value, bool is_string = false, size_t begin = 0, size_t end = npos) const noexcept; + void find_all(IntegerColumn& result, BinaryData value, bool is_string = false, size_t add_offset = 0, + size_t begin = 0, size_t end = npos); + + /// Get the specified element without the cost of constructing an + /// array instance. If an array instance is already available, or + /// you need to get multiple values, then this method will be + /// slower. + static BinaryData get(const char* header, size_t ndx, Allocator&) noexcept; + + ref_type bptree_leaf_insert(size_t ndx, BinaryData, bool add_zero_term, TreeInsertBase& state); + + //@{ + /// Those that return a string, discard the terminating zero from + /// the stored value. Those that accept a string argument, add a + /// terminating zero before storing the value. + StringData get_string(size_t ndx) const noexcept; + void add_string(StringData value); + void set_string(size_t ndx, StringData value); + void insert_string(size_t ndx, StringData value); + static StringData get_string(const char* header, size_t ndx, Allocator&, bool nullable) noexcept; + ref_type bptree_leaf_insert_string(size_t ndx, StringData, TreeInsertBase& state); + //@} + + /// Create a new empty big blobs array and attach this accessor to + /// it. This does not modify the parent reference information of + /// this accessor. + /// + /// Note that the caller assumes ownership of the allocated + /// underlying node. It is not owned by the accessor. + void create(); + + /// Construct a copy of the specified slice of this big blobs + /// array using the specified target allocator. + MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; + +#ifdef REALM_DEBUG + void verify() const; + void to_dot(std::ostream&, bool is_strings, StringData title = StringData()) const; +#endif + +private: + bool m_nullable; +}; + + +// Implementation: + +inline ArrayBigBlobs::ArrayBigBlobs(Allocator& allocator, bool nullable) noexcept + : Array(allocator) + , m_nullable(nullable) +{ +} + +inline BinaryData ArrayBigBlobs::get(size_t ndx) const noexcept +{ + ref_type ref = get_as_ref(ndx); + if (ref == 0) + return {}; // realm::null(); + + const char* blob_header = get_alloc().translate(ref); + if (!get_context_flag_from_header(blob_header)) { + const char* value = ArrayBlob::get(blob_header, 0); + size_t sz = get_size_from_header(blob_header); + return BinaryData(value, sz); + } + return {}; +} + +inline BinaryData ArrayBigBlobs::get(const char* header, size_t ndx, Allocator& alloc) noexcept +{ + ref_type blob_ref = to_ref(Array::get(header, ndx)); + if (blob_ref == 0) + return {}; + + const char* blob_header = alloc.translate(blob_ref); + if (!get_context_flag_from_header(blob_header)) { + const char* blob_data = Array::get_data_from_header(blob_header); + size_t sz = Array::get_size_from_header(blob_header); + return BinaryData(blob_data, sz); + } + return {}; +} + +inline void ArrayBigBlobs::erase(size_t ndx) +{ + ref_type blob_ref = Array::get_as_ref(ndx); + if (blob_ref != 0) { // nothing to destroy if null + Array::destroy_deep(blob_ref, get_alloc()); // Deep + } + Array::erase(ndx); +} + +inline void ArrayBigBlobs::truncate(size_t new_size) +{ + Array::truncate_and_destroy_children(new_size); +} + +inline void ArrayBigBlobs::clear() +{ + Array::clear_and_destroy_children(); +} + +inline void ArrayBigBlobs::destroy() +{ + Array::destroy_deep(); +} + +inline StringData ArrayBigBlobs::get_string(size_t ndx) const noexcept +{ + BinaryData bin = get(ndx); + if (bin.is_null()) + return realm::null(); + else + return StringData(bin.data(), bin.size() - 1); // Do not include terminating zero +} + +inline void ArrayBigBlobs::set_string(size_t ndx, StringData value) +{ + REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); + BinaryData bin(value.data(), value.size()); + bool add_zero_term = true; + set(ndx, bin, add_zero_term); +} + +inline void ArrayBigBlobs::add_string(StringData value) +{ + REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); + BinaryData bin(value.data(), value.size()); + bool add_zero_term = true; + add(bin, add_zero_term); +} + +inline void ArrayBigBlobs::insert_string(size_t ndx, StringData value) +{ + REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); + BinaryData bin(value.data(), value.size()); + bool add_zero_term = true; + insert(ndx, bin, add_zero_term); +} + +inline StringData ArrayBigBlobs::get_string(const char* header, size_t ndx, Allocator& alloc, bool nullable) noexcept +{ + static_cast(nullable); + BinaryData bin = get(header, ndx, alloc); + REALM_ASSERT_DEBUG(!(!nullable && bin.is_null())); + if (bin.is_null()) + return realm::null(); + else + return StringData(bin.data(), bin.size() - 1); // Do not include terminating zero +} + +inline ref_type ArrayBigBlobs::bptree_leaf_insert_string(size_t ndx, StringData value, TreeInsertBase& state) +{ + REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); + BinaryData bin(value.data(), value.size()); + bool add_zero_term = true; + return bptree_leaf_insert(ndx, bin, add_zero_term, state); +} + +inline void ArrayBigBlobs::create() +{ + bool context_flag = true; + Array::create(type_HasRefs, context_flag); // Throws +} + +inline MemRef ArrayBigBlobs::slice(size_t offset, size_t slice_size, Allocator& target_alloc) const +{ + return slice_and_clone_children(offset, slice_size, target_alloc); +} + + +} // namespace realm + +#endif // REALM_ARRAY_BIG_BLOBS_HPP diff --git a/Pods/Realm/include/core/realm/array_direct.hpp b/Pods/Realm/include/core/realm/array_direct.hpp new file mode 100644 index 0000000000..e33739256f --- /dev/null +++ b/Pods/Realm/include/core/realm/array_direct.hpp @@ -0,0 +1,372 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_DIRECT_HPP +#define REALM_ARRAY_DIRECT_HPP + +#include +#include + +using namespace realm::util; + +// clang-format off +/* wid == 16/32 likely when accessing offsets in B tree */ +#define REALM_TEMPEX(fun, wid, arg) \ + if (wid == 16) {fun<16> arg;} \ + else if (wid == 32) {fun<32> arg;} \ + else if (wid == 0) {fun<0> arg;} \ + else if (wid == 1) {fun<1> arg;} \ + else if (wid == 2) {fun<2> arg;} \ + else if (wid == 4) {fun<4> arg;} \ + else if (wid == 8) {fun<8> arg;} \ + else if (wid == 64) {fun<64> arg;} \ + else {REALM_ASSERT_DEBUG(false); fun<0> arg;} + +#define REALM_TEMPEX2(fun, targ, wid, arg) \ + if (wid == 16) {fun arg;} \ + else if (wid == 32) {fun arg;} \ + else if (wid == 0) {fun arg;} \ + else if (wid == 1) {fun arg;} \ + else if (wid == 2) {fun arg;} \ + else if (wid == 4) {fun arg;} \ + else if (wid == 8) {fun arg;} \ + else if (wid == 64) {fun arg;} \ + else {REALM_ASSERT_DEBUG(false); fun arg;} + +#define REALM_TEMPEX3(fun, targ1, targ2, wid, arg) \ + if (wid == 16) {fun arg;} \ + else if (wid == 32) {fun arg;} \ + else if (wid == 0) {fun arg;} \ + else if (wid == 1) {fun arg;} \ + else if (wid == 2) {fun arg;} \ + else if (wid == 4) {fun arg;} \ + else if (wid == 8) {fun arg;} \ + else if (wid == 64) {fun arg;} \ + else {REALM_ASSERT_DEBUG(false); fun arg;} + +#define REALM_TEMPEX4(fun, targ1, targ2, wid, targ3, arg) \ + if (wid == 16) {fun arg;} \ + else if (wid == 32) {fun arg;} \ + else if (wid == 0) {fun arg;} \ + else if (wid == 1) {fun arg;} \ + else if (wid == 2) {fun arg;} \ + else if (wid == 4) {fun arg;} \ + else if (wid == 8) {fun arg;} \ + else if (wid == 64) {fun arg;} \ + else {REALM_ASSERT_DEBUG(false); fun arg;} + +#define REALM_TEMPEX5(fun, targ1, targ2, targ3, targ4, wid, arg) \ + if (wid == 16) {fun arg;} \ + else if (wid == 32) {fun arg;} \ + else if (wid == 0) {fun arg;} \ + else if (wid == 1) {fun arg;} \ + else if (wid == 2) {fun arg;} \ + else if (wid == 4) {fun arg;} \ + else if (wid == 8) {fun arg;} \ + else if (wid == 64) {fun arg;} \ + else {REALM_ASSERT_DEBUG(false); fun arg;} +// clang-format on + +namespace realm { + +// Direct access methods + +template +void set_direct(char* data, size_t ndx, int_fast64_t value) noexcept +{ + if (width == 0) { + REALM_ASSERT_DEBUG(value == 0); + return; + } + else if (width == 1) { + REALM_ASSERT_DEBUG(0 <= value && value <= 0x01); + size_t byte_ndx = ndx / 8; + size_t bit_ndx = ndx % 8; + typedef unsigned char uchar; + uchar* p = reinterpret_cast(data) + byte_ndx; + *p = uchar((*p & ~(0x01 << bit_ndx)) | (int(value) & 0x01) << bit_ndx); + } + else if (width == 2) { + REALM_ASSERT_DEBUG(0 <= value && value <= 0x03); + size_t byte_ndx = ndx / 4; + size_t bit_ndx = ndx % 4 * 2; + typedef unsigned char uchar; + uchar* p = reinterpret_cast(data) + byte_ndx; + *p = uchar((*p & ~(0x03 << bit_ndx)) | (int(value) & 0x03) << bit_ndx); + } + else if (width == 4) { + REALM_ASSERT_DEBUG(0 <= value && value <= 0x0F); + size_t byte_ndx = ndx / 2; + size_t bit_ndx = ndx % 2 * 4; + typedef unsigned char uchar; + uchar* p = reinterpret_cast(data) + byte_ndx; + *p = uchar((*p & ~(0x0F << bit_ndx)) | (int(value) & 0x0F) << bit_ndx); + } + else if (width == 8) { + REALM_ASSERT_DEBUG(std::numeric_limits::min() <= value && + value <= std::numeric_limits::max()); + *(reinterpret_cast(data) + ndx) = int8_t(value); + } + else if (width == 16) { + REALM_ASSERT_DEBUG(std::numeric_limits::min() <= value && + value <= std::numeric_limits::max()); + *(reinterpret_cast(data) + ndx) = int16_t(value); + } + else if (width == 32) { + REALM_ASSERT_DEBUG(std::numeric_limits::min() <= value && + value <= std::numeric_limits::max()); + *(reinterpret_cast(data) + ndx) = int32_t(value); + } + else if (width == 64) { + REALM_ASSERT_DEBUG(std::numeric_limits::min() <= value && + value <= std::numeric_limits::max()); + *(reinterpret_cast(data) + ndx) = int64_t(value); + } + else { + REALM_ASSERT_DEBUG(false); + } +} + +template +void fill_direct(char* data, size_t begin, size_t end, int_fast64_t value) noexcept +{ + for (size_t i = begin; i != end; ++i) + set_direct(data, i, value); +} + +template +int64_t get_direct(const char* data, size_t ndx) noexcept +{ + if (w == 0) { + return 0; + } + if (w == 1) { + size_t offset = ndx >> 3; + return (data[offset] >> (ndx & 7)) & 0x01; + } + if (w == 2) { + size_t offset = ndx >> 2; + return (data[offset] >> ((ndx & 3) << 1)) & 0x03; + } + if (w == 4) { + size_t offset = ndx >> 1; + return (data[offset] >> ((ndx & 1) << 2)) & 0x0F; + } + if (w == 8) { + return *reinterpret_cast(data + ndx); + } + if (w == 16) { + size_t offset = ndx * 2; + return *reinterpret_cast(data + offset); + } + if (w == 32) { + size_t offset = ndx * 4; + return *reinterpret_cast(data + offset); + } + if (w == 64) { + size_t offset = ndx * 8; + return *reinterpret_cast(data + offset); + } + REALM_ASSERT_DEBUG(false); + return int64_t(-1); +} + +inline int64_t get_direct(const char* data, size_t width, size_t ndx) noexcept +{ + REALM_TEMPEX(return get_direct, width, (data, ndx)); +} + + +template +inline std::pair get_two(const char* data, size_t ndx) noexcept +{ + return std::make_pair(to_size_t(get_direct(data, ndx + 0)), to_size_t(get_direct(data, ndx + 1))); +} + +inline std::pair get_two(const char* data, size_t width, size_t ndx) noexcept +{ + REALM_TEMPEX(return get_two, width, (data, ndx)); +} + + +template +inline void get_three(const char* data, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept +{ + v0 = to_ref(get_direct(data, ndx + 0)); + v1 = to_ref(get_direct(data, ndx + 1)); + v2 = to_ref(get_direct(data, ndx + 2)); +} + +inline void get_three(const char* data, size_t width, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept +{ + REALM_TEMPEX(get_three, width, (data, ndx, v0, v1, v2)); +} + + +// Lower/upper bound in sorted sequence +// ------------------------------------ +// +// 3 3 3 4 4 4 5 6 7 9 9 9 +// ^ ^ ^ ^ ^ +// | | | | | +// | | | | -- Lower and upper bound of 15 +// | | | | +// | | | -- Lower and upper bound of 8 +// | | | +// | | -- Upper bound of 4 +// | | +// | -- Lower bound of 4 +// | +// -- Lower and upper bound of 1 +// +// These functions are semantically identical to std::lower_bound() and +// std::upper_bound(). +// +// We currently use binary search. See for example +// http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary. +template +inline size_t lower_bound(const char* data, size_t size, int64_t value) noexcept +{ + // The binary search used here is carefully optimized. Key trick is to use a single + // loop controlling variable (size) instead of high/low pair, and to keep updates + // to size done inside the loop independent of comparisons. Further key to speed + // is to avoid branching inside the loop, using conditional moves instead. This + // provides robust performance for random searches, though predictable searches + // might be slightly faster if we used branches instead. The loop unrolling yields + // a final 5-20% speedup depending on circumstances. + + size_t low = 0; + + while (size >= 8) { + // The following code (at X, Y and Z) is 3 times manually unrolled instances of (A) below. + // These code blocks must be kept in sync. Meassurements indicate 3 times unrolling to give + // the best performance. See (A) for comments on the loop body. + // (X) + size_t half = size / 2; + size_t other_half = size - half; + size_t probe = low + half; + size_t other_low = low + other_half; + int64_t v = get_direct(data, probe); + size = half; + low = (v < value) ? other_low : low; + + // (Y) + half = size / 2; + other_half = size - half; + probe = low + half; + other_low = low + other_half; + v = get_direct(data, probe); + size = half; + low = (v < value) ? other_low : low; + + // (Z) + half = size / 2; + other_half = size - half; + probe = low + half; + other_low = low + other_half; + v = get_direct(data, probe); + size = half; + low = (v < value) ? other_low : low; + } + while (size > 0) { + // (A) + // To understand the idea in this code, please note that + // for performance, computation of size for the next iteration + // MUST be INDEPENDENT of the conditional. This allows the + // processor to unroll the loop as fast as possible, and it + // minimizes the length of dependence chains leading up to branches. + // Making the unfolding of the loop independent of the data being + // searched, also minimizes the delays incurred by branch + // mispredictions, because they can be determined earlier + // and the speculation corrected earlier. + + // Counterintuitive: + // To make size independent of data, we cannot always split the + // range at the theoretical optimal point. When we determine that + // the key is larger than the probe at some index K, and prepare + // to search the upper part of the range, you would normally start + // the search at the next index, K+1, to get the shortest range. + // We can only do this when splitting a range with odd number of entries. + // If there is an even number of entries we search from K instead of K+1. + // This potentially leads to redundant comparisons, but in practice we + // gain more performance by making the changes to size predictable. + + // if size is even, half and other_half are the same. + // if size is odd, half is one less than other_half. + size_t half = size / 2; + size_t other_half = size - half; + size_t probe = low + half; + size_t other_low = low + other_half; + int64_t v = get_direct(data, probe); + size = half; + // for max performance, the line below should compile into a conditional + // move instruction. Not all compilers do this. To maximize chance + // of succes, no computation should be done in the branches of the + // conditional. + low = (v < value) ? other_low : low; + }; + + return low; +} + +// See lower_bound() +template +inline size_t upper_bound(const char* data, size_t size, int64_t value) noexcept +{ + size_t low = 0; + while (size >= 8) { + size_t half = size / 2; + size_t other_half = size - half; + size_t probe = low + half; + size_t other_low = low + other_half; + int64_t v = get_direct(data, probe); + size = half; + low = (value >= v) ? other_low : low; + + half = size / 2; + other_half = size - half; + probe = low + half; + other_low = low + other_half; + v = get_direct(data, probe); + size = half; + low = (value >= v) ? other_low : low; + + half = size / 2; + other_half = size - half; + probe = low + half; + other_low = low + other_half; + v = get_direct(data, probe); + size = half; + low = (value >= v) ? other_low : low; + } + + while (size > 0) { + size_t half = size / 2; + size_t other_half = size - half; + size_t probe = low + half; + size_t other_low = low + other_half; + int64_t v = get_direct(data, probe); + size = half; + low = (value >= v) ? other_low : low; + }; + + return low; +} +} + +#endif /* ARRAY_TPL_HPP_ */ diff --git a/Pods/Realm/include/core/realm/array_integer.hpp b/Pods/Realm/include/core/realm/array_integer.hpp new file mode 100644 index 0000000000..e460c5381d --- /dev/null +++ b/Pods/Realm/include/core/realm/array_integer.hpp @@ -0,0 +1,629 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_INTEGER_HPP +#define REALM_ARRAY_INTEGER_HPP + +#include +#include +#include + +namespace realm { + +class ArrayInteger : public Array { +public: + typedef int64_t value_type; + + explicit ArrayInteger(Allocator&) noexcept; + ~ArrayInteger() noexcept override + { + } + + // Disable copying, this is not allowed. + ArrayInteger& operator=(const ArrayInteger&) = delete; + ArrayInteger(const ArrayInteger&) = delete; + + void create(Type type = type_Normal, bool context_flag = false); + + void add(int64_t value); + void set(size_t ndx, int64_t value); + void set_uint(size_t ndx, uint_fast64_t value) noexcept; + int64_t get(size_t ndx) const noexcept; + uint64_t get_uint(size_t ndx) const noexcept; + static int64_t get(const char* header, size_t ndx) noexcept; + bool compare(const ArrayInteger& a) const noexcept; + + /// Add \a diff to the element at the specified index. + void adjust(size_t ndx, int_fast64_t diff); + + /// Add \a diff to all the elements in the specified index range. + void adjust(size_t begin, size_t end, int_fast64_t diff); + + /// Add signed \a diff to all elements that are greater than, or equal to \a + /// limit. + void adjust_ge(int_fast64_t limit, int_fast64_t diff); + + int64_t operator[](size_t ndx) const noexcept + { + return get(ndx); + } + int64_t front() const noexcept; + int64_t back() const noexcept; + + size_t lower_bound(int64_t value) const noexcept; + size_t upper_bound(int64_t value) const noexcept; + + std::vector to_vector() const; + +private: + template + bool minmax(size_t from, size_t to, uint64_t maxdiff, int64_t* min, int64_t* max) const; +}; + +class ArrayIntNull : public Array { +public: + using value_type = util::Optional; + + explicit ArrayIntNull(Allocator&) noexcept; + ~ArrayIntNull() noexcept override; + + /// Construct an array of the specified type and size, and return just the + /// reference to the underlying memory. All elements will be initialized to + /// the specified value. + static MemRef create_array(Type, bool context_flag, size_t size, value_type value, Allocator&); + void create(Type = type_Normal, bool context_flag = false); + + void init_from_ref(ref_type) noexcept; + void init_from_mem(MemRef) noexcept; + void init_from_parent() noexcept; + + size_t size() const noexcept; + bool is_empty() const noexcept; + + void insert(size_t ndx, value_type value); + void add(value_type value); + void set(size_t ndx, value_type value) noexcept; + value_type get(size_t ndx) const noexcept; + static value_type get(const char* header, size_t ndx) noexcept; + void get_chunk(size_t ndx, value_type res[8]) const noexcept; + void set_null(size_t ndx) noexcept; + bool is_null(size_t ndx) const noexcept; + int64_t null_value() const noexcept; + + value_type operator[](size_t ndx) const noexcept; + value_type front() const noexcept; + value_type back() const noexcept; + void erase(size_t ndx); + void erase(size_t begin, size_t end); + void truncate(size_t size); + void clear(); + void set_all_to_zero(); + + void move(size_t begin, size_t end, size_t dest_begin); + void move_backward(size_t begin, size_t end, size_t dest_end); + + size_t lower_bound(int64_t value) const noexcept; + size_t upper_bound(int64_t value) const noexcept; + + int64_t sum(size_t start = 0, size_t end = npos) const; + size_t count(int64_t value) const noexcept; + bool maximum(int64_t& result, size_t start = 0, size_t end = npos, size_t* return_ndx = nullptr) const; + bool minimum(int64_t& result, size_t start = 0, size_t end = npos, size_t* return_ndx = nullptr) const; + + bool find(int cond, Action action, value_type value, size_t start, size_t end, size_t baseindex, + QueryState* state) const; + + template + bool find(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const; + + // This is the one installed into the m_finder slots. + template + bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state) const; + + template + bool find(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const; + + // Optimized implementation for release mode + template + bool find_optimized(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const; + + // Called for each search result + template + bool find_action(size_t index, value_type value, QueryState* state, Callback callback) const; + + template + bool find_action_pattern(size_t index, uint64_t pattern, QueryState* state, Callback callback) const; + + // Wrappers for backwards compatibility and for simple use without + // setting up state initialization etc + template + size_t find_first(value_type value, size_t start = 0, size_t end = npos) const; + + void find_all(IntegerColumn* result, value_type value, size_t col_offset = 0, size_t begin = 0, + size_t end = npos) const; + + + size_t find_first(value_type value, size_t begin = 0, size_t end = npos) const; + + + // Overwrite Array::bptree_leaf_insert to correctly split nodes. + ref_type bptree_leaf_insert(size_t ndx, value_type value, TreeInsertBase& state); + + MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; + + /// Construct a deep copy of the specified slice of this array using the + /// specified target allocator. Subarrays will be cloned. + MemRef slice_and_clone_children(size_t offset, size_t slice_size, Allocator& target_alloc) const; + +protected: + void avoid_null_collision(int64_t value); + +private: + template + bool minmax_helper(int64_t& result, size_t start = 0, size_t end = npos, size_t* return_ndx = nullptr) const; + + int_fast64_t choose_random_null(int64_t incoming) const; + void replace_nulls_with(int64_t new_null); + bool can_use_as_null(int64_t value) const; +}; + + +// Implementation: + +inline ArrayInteger::ArrayInteger(Allocator& allocator) noexcept + : Array(allocator) +{ + m_is_inner_bptree_node = false; +} + +inline void ArrayInteger::add(int64_t value) +{ + Array::add(value); +} + +inline int64_t ArrayInteger::get(size_t ndx) const noexcept +{ + return Array::get(ndx); +} + +inline int64_t ArrayInteger::get(const char* header, size_t ndx) noexcept +{ + return Array::get(header, ndx); +} + +inline void ArrayInteger::set(size_t ndx, int64_t value) +{ + Array::set(ndx, value); +} + +inline void ArrayInteger::set_uint(size_t ndx, uint_fast64_t value) noexcept +{ + // When a value of a signed type is converted to an unsigned type, the C++ + // standard guarantees that negative values are converted from the native + // representation to 2's complement, but the effect of conversions in the + // opposite direction is left unspecified by the + // standard. `realm::util::from_twos_compl()` is used here to perform the + // correct opposite unsigned-to-signed conversion, which reduces to a no-op + // when 2's complement is the native representation of negative values. + set(ndx, util::from_twos_compl(value)); +} + +inline bool ArrayInteger::compare(const ArrayInteger& a) const noexcept +{ + if (a.size() != size()) + return false; + + for (size_t i = 0; i < size(); ++i) { + if (get(i) != a.get(i)) + return false; + } + + return true; +} + +inline int64_t ArrayInteger::front() const noexcept +{ + return Array::front(); +} + +inline int64_t ArrayInteger::back() const noexcept +{ + return Array::back(); +} + +inline void ArrayInteger::adjust(size_t ndx, int_fast64_t diff) +{ + Array::adjust(ndx, diff); +} + +inline void ArrayInteger::adjust(size_t begin, size_t end, int_fast64_t diff) +{ + Array::adjust(begin, end, diff); +} + +inline void ArrayInteger::adjust_ge(int_fast64_t limit, int_fast64_t diff) +{ + Array::adjust_ge(limit, diff); +} + +inline size_t ArrayInteger::lower_bound(int64_t value) const noexcept +{ + return lower_bound_int(value); +} + +inline size_t ArrayInteger::upper_bound(int64_t value) const noexcept +{ + return upper_bound_int(value); +} + + +inline ArrayIntNull::ArrayIntNull(Allocator& allocator) noexcept + : Array(allocator) +{ +} + +inline ArrayIntNull::~ArrayIntNull() noexcept +{ +} + +inline void ArrayIntNull::create(Type type, bool context_flag) +{ + MemRef r = create_array(type, context_flag, 0, util::none, m_alloc); + init_from_mem(r); +} + + +inline size_t ArrayIntNull::size() const noexcept +{ + return Array::size() - 1; +} + +inline bool ArrayIntNull::is_empty() const noexcept +{ + return size() == 0; +} + +inline void ArrayIntNull::insert(size_t ndx, value_type value) +{ + if (value) { + avoid_null_collision(*value); + Array::insert(ndx + 1, *value); + } + else { + Array::insert(ndx + 1, null_value()); + } +} + +inline void ArrayIntNull::add(value_type value) +{ + if (value) { + avoid_null_collision(*value); + Array::add(*value); + } + else { + Array::add(null_value()); + } +} + +inline void ArrayIntNull::set(size_t ndx, value_type value) noexcept +{ + if (value) { + avoid_null_collision(*value); + Array::set(ndx + 1, *value); + } + else { + Array::set(ndx + 1, null_value()); + } +} + +inline void ArrayIntNull::set_null(size_t ndx) noexcept +{ + Array::set(ndx + 1, null_value()); +} + +inline ArrayIntNull::value_type ArrayIntNull::get(size_t ndx) const noexcept +{ + int64_t value = Array::get(ndx + 1); + if (value == null_value()) { + return util::none; + } + return util::some(value); +} + +inline ArrayIntNull::value_type ArrayIntNull::get(const char* header, size_t ndx) noexcept +{ + int64_t null_value = Array::get(header, 0); + int64_t value = Array::get(header, ndx + 1); + if (value == null_value) { + return util::none; + } + else { + return util::some(value); + } +} + +inline bool ArrayIntNull::is_null(size_t ndx) const noexcept +{ + return !get(ndx); +} + +inline int64_t ArrayIntNull::null_value() const noexcept +{ + return Array::get(0); +} + +inline ArrayIntNull::value_type ArrayIntNull::operator[](size_t ndx) const noexcept +{ + return get(ndx); +} + +inline ArrayIntNull::value_type ArrayIntNull::front() const noexcept +{ + return get(0); +} + +inline ArrayIntNull::value_type ArrayIntNull::back() const noexcept +{ + return Array::back(); +} + +inline void ArrayIntNull::erase(size_t ndx) +{ + Array::erase(ndx + 1); +} + +inline void ArrayIntNull::erase(size_t begin, size_t end) +{ + Array::erase(begin + 1, end + 1); +} + +inline void ArrayIntNull::truncate(size_t to_size) +{ + Array::truncate(to_size + 1); +} + +inline void ArrayIntNull::clear() +{ + truncate(0); +} + +inline void ArrayIntNull::set_all_to_zero() +{ + // FIXME: Array::set_all_to_zero does something else + for (size_t i = 0; i < size(); ++i) { + set(i, 0); + } +} + +inline void ArrayIntNull::move(size_t begin, size_t end, size_t dest_begin) +{ + Array::move(begin + 1, end + 1, dest_begin + 1); +} + +inline void ArrayIntNull::move_backward(size_t begin, size_t end, size_t dest_end) +{ + Array::move_backward(begin + 1, end + 1, dest_end + 1); +} + +inline size_t ArrayIntNull::lower_bound(int64_t value) const noexcept +{ + // FIXME: Consider this behaviour with NULLs. + // Array::lower_bound_int assumes an already sorted array, but + // this array could be sorted with nulls first or last. + return Array::lower_bound_int(value); +} + +inline size_t ArrayIntNull::upper_bound(int64_t value) const noexcept +{ + // FIXME: see lower_bound + return Array::upper_bound_int(value); +} + +inline int64_t ArrayIntNull::sum(size_t start, size_t end) const +{ + // FIXME: Optimize + int64_t sum_of_range = 0; + if (end == npos) + end = size(); + for (size_t i = start; i < end; ++i) { + value_type x = get(i); + if (x) { + sum_of_range += *x; + } + } + return sum_of_range; +} + +inline size_t ArrayIntNull::count(int64_t value) const noexcept +{ + size_t count_of_value = Array::count(value); + if (value == null_value()) { + --count_of_value; + } + return count_of_value; +} + +// FIXME: Optimize +template +inline bool ArrayIntNull::minmax_helper(int64_t& result, size_t start, size_t end, size_t* return_ndx) const +{ + size_t best_index = 1; + + if (end == npos) { + end = m_size; + } + + ++start; + + REALM_ASSERT(start < m_size && end <= m_size && start < end); + + if (m_size == 1) { + // empty array + return false; + } + + if (m_width == 0) { + if (return_ndx) + *return_ndx = best_index - 1; + result = 0; + return true; + } + + int64_t m = Array::get(start); + + const int64_t null_val = null_value(); + for (; start < end; ++start) { + const int64_t v = Array::get(start); + if (find_max ? v > m : v < m) { + if (v == null_val) { + continue; + } + m = v; + best_index = start; + } + } + + result = m; + if (return_ndx) { + *return_ndx = best_index - 1; + } + return true; +} + +inline bool ArrayIntNull::maximum(int64_t& result, size_t start, size_t end, size_t* return_ndx) const +{ + return minmax_helper(result, start, end, return_ndx); +} + +inline bool ArrayIntNull::minimum(int64_t& result, size_t start, size_t end, size_t* return_ndx) const +{ + return minmax_helper(result, start, end, return_ndx); +} + +inline bool ArrayIntNull::find(int cond, Action action, value_type value, size_t start, size_t end, size_t baseindex, + QueryState* state) const +{ + if (value) { + return Array::find(cond, action, *value, start, end, baseindex, state, true /*treat as nullable array*/, + false /*search parameter given in 'value' argument*/); + } + else { + return Array::find(cond, action, 0 /* unused dummy*/, start, end, baseindex, state, + true /*treat as nullable array*/, true /*search for null, ignore value argument*/); + } +} + +template +bool ArrayIntNull::find(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const +{ + if (value) { + return Array::find(*value, start, end, baseindex, state, std::forward(callback), + true /*treat as nullable array*/, + false /*search parameter given in 'value' argument*/); + } + else { + return Array::find(0 /*ignored*/, start, end, baseindex, state, + std::forward(callback), true /*treat as nullable array*/, + true /*search for null, ignore value argument*/); + } +} + + +template +bool ArrayIntNull::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state) const +{ + return Array::find(value, start, end, baseindex, state, true /*treat as nullable array*/, + false /*search parameter given in 'value' argument*/); +} + + +template +bool ArrayIntNull::find(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, + Callback callback) const +{ + if (value) { + return Array::find(*value, start, end, baseindex, state, std::forward(callback), + true /*treat as nullable array*/, + false /*search parameter given in 'value' argument*/); + } + else { + return Array::find(0 /*ignored*/, start, end, baseindex, state, + std::forward(callback), true /*treat as nullable array*/, + true /*search for null, ignore value argument*/); + } +} + + +template +bool ArrayIntNull::find_action(size_t index, value_type value, QueryState* state, Callback callback) const +{ + if (value) { + return Array::find_action(index, *value, state, callback, true /*treat as nullable array*/, + false /*search parameter given in 'value' argument*/); + } + else { + return Array::find_action(index, 0 /* ignored */, state, callback, + true /*treat as nullable array*/, + true /*search for null, ignore value argument*/); + } +} + + +template +bool ArrayIntNull::find_action_pattern(size_t index, uint64_t pattern, QueryState* state, + Callback callback) const +{ + return Array::find_action_pattern(index, pattern, state, callback, + true /*treat as nullable array*/, + false /*search parameter given in 'value' argument*/); +} + + +template +size_t ArrayIntNull::find_first(value_type value, size_t start, size_t end) const +{ + QueryState state; + state.init(act_ReturnFirst, nullptr, 1); + if (value) { + Array::find(*value, start, end, 0, &state, Array::CallbackDummy(), + true /*treat as nullable array*/, + false /*search parameter given in 'value' argument*/); + } + else { + Array::find(0 /*ignored*/, start, end, 0, &state, Array::CallbackDummy(), + true /*treat as nullable array*/, + true /*search for null, ignore value argument*/); + } + + if (state.m_match_count > 0) + return to_size_t(state.m_state); + else + return not_found; +} + +inline size_t ArrayIntNull::find_first(value_type value, size_t begin, size_t end) const +{ + return find_first(value, begin, end); +} +} + +#endif // REALM_ARRAY_INTEGER_HPP diff --git a/Pods/Realm/include/core/realm/array_string.hpp b/Pods/Realm/include/core/realm/array_string.hpp new file mode 100644 index 0000000000..bbf3203606 --- /dev/null +++ b/Pods/Realm/include/core/realm/array_string.hpp @@ -0,0 +1,180 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_STRING_HPP +#define REALM_ARRAY_STRING_HPP + +#include + +namespace realm { + +/* +ArrayString stores strings as a concecutive list of fixed-length blocks of m_width bytes. The +longest string it can store is (m_width - 1) bytes before it needs to expand. + +An example of the format for m_width = 4 is following sequence of bytes, where x is payload: + +xxx0 xx01 x002 0003 0004 (strings "xxx",. "xx", "x", "", realm::null()) + +So each string is 0 terminated, and the last byte in a block tells how many 0s are present, except +for a realm::null() which has the byte set to m_width (4). The byte is used to compute the length of a string +in various functions. + +New: If m_witdh = 0, then all elements are realm::null(). So to add an empty string we must expand m_width +New: StringData is null() if-and-only-if StringData::data() == 0. +*/ + +class ArrayString : public Array { +public: + static const size_t max_width = 64; + + typedef StringData value_type; + // Constructor defaults to non-nullable because we use non-nullable ArrayString so many places internally in core + // (data which isn't user payload) where null isn't needed. + explicit ArrayString(Allocator&, bool nullable = false) noexcept; + ~ArrayString() noexcept override + { + } + + bool is_null(size_t ndx) const; + void set_null(size_t ndx); + StringData get(size_t ndx) const noexcept; + void add(); + void add(StringData value); + void set(size_t ndx, StringData value); + void insert(size_t ndx, StringData value); + void erase(size_t ndx); + + size_t count(StringData value, size_t begin = 0, size_t end = npos) const noexcept; + size_t find_first(StringData value, size_t begin = 0, size_t end = npos) const noexcept; + void find_all(IntegerColumn& result, StringData value, size_t add_offset = 0, size_t begin = 0, + size_t end = npos); + + /// Compare two string arrays for equality. + bool compare_string(const ArrayString&) const noexcept; + + /// Get the specified element without the cost of constructing an + /// array instance. If an array instance is already available, or + /// you need to get multiple values, then this method will be + /// slower. + static StringData get(const char* header, size_t ndx, bool nullable) noexcept; + + ref_type bptree_leaf_insert(size_t ndx, StringData, TreeInsertBase& state); + + /// Construct a string array of the specified size and return just + /// the reference to the underlying memory. All elements will be + /// initialized to the empty string. + static MemRef create_array(size_t size, Allocator&); + + /// Create a new empty string array and attach this accessor to + /// it. This does not modify the parent reference information of + /// this accessor. + /// + /// Note that the caller assumes ownership of the allocated + /// underlying node. It is not owned by the accessor. + void create(); + + /// Construct a copy of the specified slice of this string array + /// using the specified target allocator. + MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; + +#ifdef REALM_DEBUG + void string_stats() const; + void to_dot(std::ostream&, StringData title = StringData()) const; +#endif + +private: + size_t calc_byte_len(size_t num_items, size_t width) const override; + size_t calc_item_count(size_t bytes, size_t width) const noexcept override; + + bool m_nullable; +}; + + +// Implementation: + +// Creates new array (but invalid, call init_from_ref() to init) +inline ArrayString::ArrayString(Allocator& allocator, bool nullable) noexcept + : Array(allocator) + , m_nullable(nullable) +{ +} + +inline void ArrayString::create() +{ + size_t init_size = 0; + MemRef mem = create_array(init_size, get_alloc()); // Throws + init_from_mem(mem); +} + +inline MemRef ArrayString::create_array(size_t init_size, Allocator& allocator) +{ + bool context_flag = false; + int_fast64_t value = 0; + return Array::create(type_Normal, context_flag, wtype_Multiply, init_size, value, allocator); // Throws +} + +inline StringData ArrayString::get(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, m_size); + if (m_width == 0) + return m_nullable ? realm::null() : StringData(""); + + const char* data = m_data + (ndx * m_width); + size_t array_size = (m_width - 1) - data[m_width - 1]; + + if (array_size == static_cast(-1)) + return m_nullable ? realm::null() : StringData(""); + + REALM_ASSERT_EX(data[array_size] == 0, data[array_size], + array_size); // Realm guarantees 0 terminated return strings + return StringData(data, array_size); +} + +inline void ArrayString::add(StringData value) +{ + REALM_ASSERT(!(!m_nullable && value.is_null())); + insert(m_size, value); // Throws +} + +inline void ArrayString::add() +{ + add(m_nullable ? realm::null() : StringData("")); // Throws +} + +inline StringData ArrayString::get(const char* header, size_t ndx, bool nullable) noexcept +{ + REALM_ASSERT(ndx < get_size_from_header(header)); + uint_least8_t width = get_width_from_header(header); + const char* data = get_data_from_header(header) + (ndx * width); + + if (width == 0) + return nullable ? realm::null() : StringData(""); + + size_t size = (width - 1) - data[width - 1]; + + if (size == static_cast(-1)) + return nullable ? realm::null() : StringData(""); + + return StringData(data, size); +} + + +} // namespace realm + +#endif // REALM_ARRAY_STRING_HPP diff --git a/Pods/Realm/include/core/realm/array_string_long.hpp b/Pods/Realm/include/core/realm/array_string_long.hpp new file mode 100644 index 0000000000..8f5878d92e --- /dev/null +++ b/Pods/Realm/include/core/realm/array_string_long.hpp @@ -0,0 +1,228 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_STRING_LONG_HPP +#define REALM_ARRAY_STRING_LONG_HPP + +#include +#include + +namespace realm { + + +class ArrayStringLong : public Array { +public: + typedef StringData value_type; + + explicit ArrayStringLong(Allocator&, bool nullable) noexcept; + ~ArrayStringLong() noexcept override + { + } + + // Disable copying, this is not allowed. + ArrayStringLong& operator=(const ArrayStringLong&) = delete; + ArrayStringLong(const ArrayStringLong&) = delete; + + /// Create a new empty long string array and attach this accessor to + /// it. This does not modify the parent reference information of + /// this accessor. + /// + /// Note that the caller assumes ownership of the allocated + /// underlying node. It is not owned by the accessor. + void create(); + + //@{ + /// Overriding functions of Array + void init_from_ref(ref_type) noexcept; + void init_from_mem(MemRef) noexcept; + void init_from_parent() noexcept; + //@} + + bool is_empty() const noexcept; + size_t size() const noexcept; + + StringData get(size_t ndx) const noexcept; + + + void add(StringData value); + void set(size_t ndx, StringData value); + void insert(size_t ndx, StringData value); + void erase(size_t ndx); + void truncate(size_t size); + void clear(); + void destroy(); + + bool is_null(size_t ndx) const; + void set_null(size_t ndx); + + size_t count(StringData value, size_t begin = 0, size_t end = npos) const noexcept; + size_t find_first(StringData value, size_t begin = 0, size_t end = npos) const noexcept; + void find_all(IntegerColumn& result, StringData value, size_t add_offset = 0, size_t begin = 0, + size_t end = npos) const; + + /// Get the specified element without the cost of constructing an + /// array instance. If an array instance is already available, or + /// you need to get multiple values, then this method will be + /// slower. + static StringData get(const char* header, size_t ndx, Allocator&, bool nullable) noexcept; + + ref_type bptree_leaf_insert(size_t ndx, StringData, TreeInsertBase&); + + static size_t get_size_from_header(const char*, Allocator&) noexcept; + + /// Construct a long string array of the specified size and return + /// just the reference to the underlying memory. All elements will + /// be initialized to zero size blobs. + static MemRef create_array(size_t size, Allocator&, bool nullable); + + /// Construct a copy of the specified slice of this long string + /// array using the specified target allocator. + MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; + +#ifdef REALM_DEBUG + void to_dot(std::ostream&, StringData title = StringData()) const; +#endif + + bool update_from_parent(size_t old_baseline) noexcept; + +private: + ArrayInteger m_offsets; + ArrayBlob m_blob; + Array m_nulls; + bool m_nullable; +}; + + +// Implementation: +inline ArrayStringLong::ArrayStringLong(Allocator& allocator, bool nullable) noexcept + : Array(allocator) + , m_offsets(allocator) + , m_blob(allocator) + , m_nulls(nullable ? allocator : Allocator::get_default()) + , m_nullable(nullable) +{ + m_offsets.set_parent(this, 0); + m_blob.set_parent(this, 1); + if (nullable) + m_nulls.set_parent(this, 2); +} + +inline void ArrayStringLong::create() +{ + size_t init_size = 0; + MemRef mem = create_array(init_size, get_alloc(), m_nullable); // Throws + init_from_mem(mem); +} + +inline void ArrayStringLong::init_from_ref(ref_type ref) noexcept +{ + REALM_ASSERT(ref); + char* header = get_alloc().translate(ref); + init_from_mem(MemRef(header, ref, m_alloc)); + m_nullable = (Array::size() == 3); +} + +inline void ArrayStringLong::init_from_parent() noexcept +{ + ref_type ref = get_ref_from_parent(); + init_from_ref(ref); +} + +inline bool ArrayStringLong::is_empty() const noexcept +{ + return m_offsets.is_empty(); +} + +inline size_t ArrayStringLong::size() const noexcept +{ + return m_offsets.size(); +} + +inline StringData ArrayStringLong::get(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, m_offsets.size()); + + if (m_nullable && m_nulls.get(ndx) == 0) + return realm::null(); + + size_t begin, end; + if (0 < ndx) { + begin = to_size_t(m_offsets.get(ndx - 1)); + end = to_size_t(m_offsets.get(ndx)); + } + else { + begin = 0; + end = to_size_t(m_offsets.get(0)); + } + --end; // Discount the terminating zero + + return StringData(m_blob.get(begin), end - begin); +} + +inline void ArrayStringLong::truncate(size_t new_size) +{ + REALM_ASSERT_3(new_size, <, m_offsets.size()); + + size_t sz = new_size ? to_size_t(m_offsets.get(new_size - 1)) : 0; + + m_offsets.truncate(new_size); + m_blob.truncate(sz); + if (m_nullable) + m_nulls.truncate(new_size); +} + +inline void ArrayStringLong::clear() +{ + m_blob.clear(); + m_offsets.clear(); + if (m_nullable) + m_nulls.clear(); +} + +inline void ArrayStringLong::destroy() +{ + m_blob.destroy(); + m_offsets.destroy(); + if (m_nullable) + m_nulls.destroy(); + Array::destroy(); +} + +inline bool ArrayStringLong::update_from_parent(size_t old_baseline) noexcept +{ + bool res = Array::update_from_parent(old_baseline); + if (res) { + m_blob.update_from_parent(old_baseline); + m_offsets.update_from_parent(old_baseline); + if (m_nullable) + m_nulls.update_from_parent(old_baseline); + } + return res; +} + +inline size_t ArrayStringLong::get_size_from_header(const char* header, Allocator& alloc) noexcept +{ + ref_type offsets_ref = to_ref(Array::get(header, 0)); + const char* offsets_header = alloc.translate(offsets_ref); + return Array::get_size_from_header(offsets_header); +} + + +} // namespace realm + +#endif // REALM_ARRAY_STRING_LONG_HPP diff --git a/Pods/Realm/include/core/realm/binary_data.hpp b/Pods/Realm/include/core/realm/binary_data.hpp new file mode 100644 index 0000000000..a184f0c3b9 --- /dev/null +++ b/Pods/Realm/include/core/realm/binary_data.hpp @@ -0,0 +1,239 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_BINARY_DATA_HPP +#define REALM_BINARY_DATA_HPP + +#include +#include +#include + +#include +#include +#include +#include + +namespace realm { + +/// A reference to a chunk of binary data. +/// +/// This class does not own the referenced memory, nor does it in any other way +/// attempt to manage the lifetime of it. +/// +/// \sa StringData +class BinaryData { +public: + BinaryData() noexcept + : m_data(nullptr) + , m_size(0) + { + } + BinaryData(const char* external_data, size_t data_size) noexcept + : m_data(external_data) + , m_size(data_size) + { + } + template + explicit BinaryData(const char (&external_data)[N]) + : m_data(external_data) + , m_size(N) + { + } + template + explicit BinaryData(const std::basic_string&); + + // BinaryData does not store data, callers must manage their own strings. + template + BinaryData(const std::basic_string&&) = delete; + + template + explicit operator std::basic_string() const; + + char operator[](size_t i) const noexcept + { + return m_data[i]; + } + + const char* data() const noexcept + { + return m_data; + } + size_t size() const noexcept + { + return m_size; + } + + /// Is this a null reference? + /// + /// An instance of BinaryData is a null reference when, and only when the + /// stored size is zero (size()) and the stored pointer is the null pointer + /// (data()). + /// + /// In the case of the empty byte sequence, the stored size is still zero, + /// but the stored pointer is **not** the null pointer. Note that the actual + /// value of the pointer is immaterial in this case (as long as it is not + /// zero), because when the size is zero, it is an error to dereference the + /// pointer. + /// + /// Conversion of a BinaryData object to `bool` yields the logical negation + /// of the result of calling this function. In other words, a BinaryData + /// object is converted to true if it is not the null reference, otherwise + /// it is converted to false. + /// + /// It is important to understand that all of the functions and operators in + /// this class, and most of the functions in the Realm API in general + /// makes no distinction between a null reference and a reference to the + /// empty byte sequence. These functions and operators never look at the + /// stored pointer if the stored size is zero. + bool is_null() const noexcept; + + friend bool operator==(const BinaryData&, const BinaryData&) noexcept; + friend bool operator!=(const BinaryData&, const BinaryData&) noexcept; + + //@{ + /// Trivial bytewise lexicographical comparison. + friend bool operator<(const BinaryData&, const BinaryData&) noexcept; + friend bool operator>(const BinaryData&, const BinaryData&) noexcept; + friend bool operator<=(const BinaryData&, const BinaryData&) noexcept; + friend bool operator>=(const BinaryData&, const BinaryData&) noexcept; + //@} + + bool begins_with(BinaryData) const noexcept; + bool ends_with(BinaryData) const noexcept; + bool contains(BinaryData) const noexcept; + + template + friend std::basic_ostream& operator<<(std::basic_ostream&, const BinaryData&); + + explicit operator bool() const noexcept; + +private: + const char* m_data; + size_t m_size; +}; + +/// A read-only chunk of binary data. +class OwnedBinaryData : public OwnedData { +public: + using OwnedData::OwnedData; + + OwnedBinaryData() = default; + OwnedBinaryData(const BinaryData& binary_data) + : OwnedData(binary_data.data(), binary_data.size()) + { + } + + BinaryData get() const + { + return {data(), size()}; + } +}; + + +// Implementation: + +template +inline BinaryData::BinaryData(const std::basic_string& s) + : m_data(s.data()) + , m_size(s.size()) +{ +} + +template +inline BinaryData::operator std::basic_string() const +{ + return std::basic_string(m_data, m_size); +} + +inline bool BinaryData::is_null() const noexcept +{ + return !m_data; +} + +inline bool operator==(const BinaryData& a, const BinaryData& b) noexcept +{ + return a.m_size == b.m_size && a.is_null() == b.is_null() && safe_equal(a.m_data, a.m_data + a.m_size, b.m_data); +} + +inline bool operator!=(const BinaryData& a, const BinaryData& b) noexcept +{ + return !(a == b); +} + +inline bool operator<(const BinaryData& a, const BinaryData& b) noexcept +{ + if (a.is_null() || b.is_null()) + return !a.is_null() < !b.is_null(); + + return std::lexicographical_compare(a.m_data, a.m_data + a.m_size, b.m_data, b.m_data + b.m_size); +} + +inline bool operator>(const BinaryData& a, const BinaryData& b) noexcept +{ + return b < a; +} + +inline bool operator<=(const BinaryData& a, const BinaryData& b) noexcept +{ + return !(b < a); +} + +inline bool operator>=(const BinaryData& a, const BinaryData& b) noexcept +{ + return !(a < b); +} + +inline bool BinaryData::begins_with(BinaryData d) const noexcept +{ + if (is_null() && !d.is_null()) + return false; + + return d.m_size <= m_size && safe_equal(m_data, m_data + d.m_size, d.m_data); +} + +inline bool BinaryData::ends_with(BinaryData d) const noexcept +{ + if (is_null() && !d.is_null()) + return false; + + return d.m_size <= m_size && safe_equal(m_data + m_size - d.m_size, m_data + m_size, d.m_data); +} + +inline bool BinaryData::contains(BinaryData d) const noexcept +{ + if (is_null() && !d.is_null()) + return false; + + return d.m_size == 0 || std::search(m_data, m_data + m_size, d.m_data, d.m_data + d.m_size) != m_data + m_size; +} + +template +inline std::basic_ostream& operator<<(std::basic_ostream& out, const BinaryData& d) +{ + out << "BinaryData(" << static_cast(d.m_data) << ", " << d.m_size << ")"; + return out; +} + +inline BinaryData::operator bool() const noexcept +{ + return !is_null(); +} + +} // namespace realm + +#endif // REALM_BINARY_DATA_HPP diff --git a/Pods/Realm/include/core/realm/bptree.hpp b/Pods/Realm/include/core/realm/bptree.hpp new file mode 100644 index 0000000000..aae64de829 --- /dev/null +++ b/Pods/Realm/include/core/realm/bptree.hpp @@ -0,0 +1,1271 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_BPTREE_HPP +#define REALM_BPTREE_HPP + +#include // std::unique_ptr +#include +#include +#include +#include +#include + +namespace realm { + +/// Specialize BpTree to implement column types. +template +class BpTree; + +class ArrayInteger; +class ArrayIntNull; + +class BpTreeNode : public Array { +public: + using Array::Array; + /// Get the number of elements in the B+-tree rooted at this array + /// node. The root must not be a leaf. + /// + /// Please avoid using this function (consider it deprecated). It + /// will have to be removed if we choose to get rid of the last + /// element of the main array of an inner B+-tree node that stores + /// the total number of elements in the subtree. The motivation + /// for removing it, is that it will significantly improve the + /// efficiency when inserting after, and erasing the last element. + size_t get_bptree_size() const noexcept; + + /// The root must not be a leaf. + static size_t get_bptree_size_from_header(const char* root_header) noexcept; + + + /// Find the leaf node corresponding to the specified element + /// index index. The specified element index must refer to an + /// element that exists in the tree. This function must be called + /// on an inner B+-tree node, never a leaf. Note that according to + /// invar:bptree-nonempty-inner and invar:bptree-nonempty-leaf, an + /// inner B+-tree node can never be empty. + /// + /// This function is not obliged to instantiate intermediate array + /// accessors. For this reason, this function cannot be used for + /// operations that modify the tree, as that requires an unbroken + /// chain of parent array accessors between the root and the + /// leaf. Thus, despite the fact that the returned MemRef object + /// appears to allow modification of the referenced memory, the + /// caller must handle the memory reference as if it was + /// const-qualified. + /// + /// \return (`leaf_header`, `ndx_in_leaf`) where `leaf_header` + /// points to the the header of the located leaf, and + /// `ndx_in_leaf` is the local index within that leaf + /// corresponding to the specified element index. + std::pair get_bptree_leaf(size_t elem_ndx) const noexcept; + + + class NodeInfo; + class VisitHandler; + + /// Visit leaves of the B+-tree rooted at this inner node, + /// starting with the leaf that contains the element at the + /// specified element index start offset, and ending when the + /// handler returns false. The specified element index offset must + /// refer to an element that exists in the tree. This function + /// must be called on an inner B+-tree node, never a leaf. Note + /// that according to invar:bptree-nonempty-inner and + /// invar:bptree-nonempty-leaf, an inner B+-tree node can never be + /// empty. + /// + /// \param elem_ndx_offset The start position (must be valid). + /// + /// \param elems_in_tree The total number of elements in the tree. + /// + /// \param handler The callback which will get called for each leaf. + /// + /// \return True if, and only if the handler has returned true for + /// all visited leafs. + bool visit_bptree_leaves(size_t elem_ndx_offset, size_t elems_in_tree, VisitHandler& handler); + + + class UpdateHandler; + + /// Call the handler for every leaf. This function must be called + /// on an inner B+-tree node, never a leaf. + void update_bptree_leaves(UpdateHandler&); + + /// Call the handler for the leaf that contains the element at the + /// specified index. This function must be called on an inner + /// B+-tree node, never a leaf. + void update_bptree_elem(size_t elem_ndx, UpdateHandler&); + + + class EraseHandler; + + /// Erase the element at the specified index in the B+-tree with + /// the specified root. When erasing the last element, you must + /// pass npos in place of the index. This function must be called + /// with a root that is an inner B+-tree node, never a leaf. + /// + /// This function is guaranteed to succeed (not throw) if the + /// specified element was inserted during the current transaction, + /// and no other modifying operation has been carried out since + /// then (noexcept:bptree-erase-alt). + /// + /// FIXME: ExceptionSafety: The exception guarantee explained + /// above is not as powerfull as we would like it to be. Here is + /// what we would like: This function is guaranteed to succeed + /// (not throw) if the specified element was inserted during the + /// current transaction (noexcept:bptree-erase). This must be true + /// even if the element is modified after insertion, and/or if + /// other elements are inserted or erased around it. There are two + /// aspects of the current design that stand in the way of this + /// guarantee: (A) The fact that the node accessor, that is cached + /// in the column accessor, has to be reallocated/reinstantiated + /// when the root switches between being a leaf and an inner + /// node. This problem would go away if we always cached the last + /// used leaf accessor in the column accessor instead. (B) The + /// fact that replacing one child ref with another can fail, + /// because it may require reallocation of memory to expand the + /// bit-width. This can be fixed in two ways: Either have the + /// inner B+-tree nodes always have a bit-width of 64, or allow + /// the root node to be discarded and the column ref to be set to + /// zero in Table::m_columns. + static void erase_bptree_elem(BpTreeNode* root, size_t elem_ndx, EraseHandler&); + + template + struct TreeInsert : TreeInsertBase { + typename TreeTraits::value_type m_value; + bool m_nullable; + }; + + /// Same as bptree_insert() but insert after the last element. + template + ref_type bptree_append(TreeInsert& state); + + /// Insert an element into the B+-subtree rooted at this array + /// node. The element is inserted before the specified element + /// index. This function must be called on an inner B+-tree node, + /// never a leaf. If this inner node had to be split, this + /// function returns the `ref` of the new sibling. + template + ref_type bptree_insert(size_t elem_ndx, TreeInsert& state); + +protected: + /// Insert a new child after original. If the parent has to be + /// split, this function returns the `ref` of the new parent node. + ref_type insert_bptree_child(Array& offsets, size_t orig_child_ndx, ref_type new_sibling_ref, + TreeInsertBase& state); + + void ensure_bptree_offsets(Array& offsets); + void create_bptree_offsets(Array& offsets, int_fast64_t first_value); + + bool do_erase_bptree_elem(size_t elem_ndx, EraseHandler&); +}; + +class BpTreeBase { +public: + struct unattached_tag { + }; + + // Disable copying, this is not allowed. + BpTreeBase& operator=(const BpTreeBase&) = delete; + BpTreeBase(const BpTreeBase&) = delete; + + // Accessor concept: + Allocator& get_alloc() const noexcept; + void destroy() noexcept; + void detach(); + bool is_attached() const noexcept; + void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept; + size_t get_ndx_in_parent() const noexcept; + void set_ndx_in_parent(size_t ndx) noexcept; + void update_from_parent(size_t old_baseline) noexcept; + MemRef clone_deep(Allocator& alloc) const; + + // BpTree interface: + const Array& root() const noexcept; + Array& root() noexcept; + bool root_is_leaf() const noexcept; + BpTreeNode& root_as_node(); + const BpTreeNode& root_as_node() const; + void introduce_new_root(ref_type new_sibling_ref, TreeInsertBase& state, bool is_append); + void replace_root(std::unique_ptr leaf); + +protected: + explicit BpTreeBase(std::unique_ptr root); + explicit BpTreeBase(BpTreeBase&&) = default; + BpTreeBase& operator=(BpTreeBase&&) = default; + std::unique_ptr m_root; + + struct SliceHandler { + virtual MemRef slice_leaf(MemRef leaf_mem, size_t offset, size_t size, Allocator& target_alloc) = 0; + ~SliceHandler() noexcept + { + } + }; + static ref_type write_subtree(const BpTreeNode& root, size_t slice_offset, size_t slice_size, size_t table_size, + SliceHandler&, _impl::OutputStream&); + friend class ColumnBase; + friend class ColumnBaseSimple; + +private: + struct WriteSliceHandler; + + // FIXME: Move B+Tree functionality from Array to this class. +}; + + +// Default implementation of BpTree. This should work for all types that have monomorphic +// leaves (i.e. all leaves are of the same type). +template +class BpTree : public BpTreeBase { +public: + using value_type = T; + using LeafType = typename ColumnTypeTraits::leaf_type; + + /// LeafInfo is used by get_leaf() to provide access to a leaf + /// without instantiating unnecessary nodes along the way. + /// Upon return, out_leaf with hold a pointer to the leaf containing + /// the index given to get_leaf(). If the index happens to be + /// in the root node (i.e., the root is a leaf), it will point + /// to the root node. + /// If the index isn't in the root node, fallback will be initialized + /// to represent the leaf holding the node, and out_leaf will be set + /// to point to fallback. + struct LeafInfo { + const LeafType** out_leaf; + LeafType* fallback; + }; + + BpTree(); + explicit BpTree(BpTreeBase::unattached_tag); + explicit BpTree(Allocator& alloc); + REALM_DEPRECATED("Initialize with MemRef instead") + explicit BpTree(std::unique_ptr init_root) + : BpTreeBase(std::move(init_root)) + { + } + explicit BpTree(Allocator& alloc, MemRef mem) + : BpTreeBase(std::unique_ptr(new LeafType(alloc))) + { + init_from_mem(alloc, mem); + } + BpTree(BpTree&&) = default; + BpTree& operator=(BpTree&&) = default; + + // Disable copying, this is not allowed. + BpTree& operator=(const BpTree&) = delete; + BpTree(const BpTree&) = delete; + + void init_from_ref(Allocator& alloc, ref_type ref); + void init_from_mem(Allocator& alloc, MemRef mem); + void init_from_parent(); + + size_t size() const noexcept; + bool is_empty() const noexcept + { + return size() == 0; + } + + T get(size_t ndx) const noexcept; + bool is_null(size_t ndx) const noexcept; + void set(size_t, T value); + void set_null(size_t); + void insert(size_t ndx, T value, size_t num_rows = 1); + void erase(size_t ndx, bool is_last = false); + void move_last_over(size_t ndx, size_t last_row_ndx); + void clear(); + T front() const noexcept; + T back() const noexcept; + + size_t find_first(T value, size_t begin = 0, size_t end = npos) const; + void find_all(IntegerColumn& out_indices, T value, size_t begin = 0, size_t end = npos) const; + + static MemRef create_leaf(Array::Type leaf_type, size_t size, T value, Allocator&); + + /// See LeafInfo for information about what to put in the inout_leaf + /// parameter. + /// + /// This function cannot be used for modifying operations as it + /// does not ensure the presence of an unbroken chain of parent + /// accessors. For this reason, the identified leaf should always + /// be accessed through the returned const-qualified reference, + /// and never directly through the specfied fallback accessor. + void get_leaf(size_t ndx, size_t& out_ndx_in_leaf, LeafInfo& inout_leaf) const noexcept; + + void update_each(BpTreeNode::UpdateHandler&); + void update_elem(size_t, BpTreeNode::UpdateHandler&); + + void adjust(size_t ndx, T diff); + void adjust(T diff); + void adjust_ge(T limit, T diff); + + ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream& out) const; + +#if defined(REALM_DEBUG) + void verify() const; + static size_t verify_leaf(MemRef mem, Allocator& alloc); +#endif + static void leaf_to_dot(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, std::ostream& out, + Allocator& alloc); + +private: + LeafType& root_as_leaf(); + const LeafType& root_as_leaf() const; + + std::unique_ptr create_root_from_ref(Allocator& alloc, ref_type ref); + std::unique_ptr create_root_from_mem(Allocator& alloc, MemRef mem); + + struct EraseHandler; + struct UpdateHandler; + struct SetNullHandler; + struct SliceHandler; + struct AdjustHandler; + struct AdjustGEHandler; + + struct LeafValueInserter; + struct LeafNullInserter; + + template + void bptree_insert(size_t row_ndx, BpTreeNode::TreeInsert& state, size_t num_rows); +}; + + +class BpTreeNode::NodeInfo { +public: + MemRef m_mem; + Array* m_parent; + size_t m_ndx_in_parent; + size_t m_offset, m_size; +}; + +class BpTreeNode::VisitHandler { +public: + virtual bool visit(const NodeInfo& leaf_info) = 0; + virtual ~VisitHandler() noexcept + { + } +}; + + +class BpTreeNode::UpdateHandler { +public: + virtual void update(MemRef, ArrayParent*, size_t leaf_ndx_in_parent, size_t elem_ndx_in_leaf) = 0; + virtual ~UpdateHandler() noexcept + { + } +}; + + +class BpTreeNode::EraseHandler { +public: + /// If the specified leaf has more than one element, this function + /// must erase the specified element from the leaf and return + /// false. Otherwise, when the leaf has a single element, this + /// function must return true without modifying the leaf. If \a + /// elem_ndx_in_leaf is `npos`, it refers to the last element in + /// the leaf. The implementation of this function must be + /// exception safe. This function is guaranteed to be called at + /// most once during each execution of Array::erase_bptree_elem(), + /// and *exactly* once during each *successful* execution of + /// Array::erase_bptree_elem(). + virtual bool erase_leaf_elem(MemRef, ArrayParent*, size_t leaf_ndx_in_parent, size_t elem_ndx_in_leaf) = 0; + + virtual void destroy_leaf(MemRef leaf_mem) noexcept = 0; + + /// Must replace the current root with the specified leaf. The + /// implementation of this function must not destroy the + /// underlying root node, or any of its children, as that will be + /// done by Array::erase_bptree_elem(). The implementation of this + /// function must be exception safe. + virtual void replace_root_by_leaf(MemRef leaf_mem) = 0; + + /// Same as replace_root_by_leaf(), but must replace the root with + /// an empty leaf. Also, if this function is called during an + /// execution of Array::erase_bptree_elem(), it is guaranteed that + /// it will be preceeded by a call to erase_leaf_elem(). + virtual void replace_root_by_empty_leaf() = 0; + + virtual ~EraseHandler() noexcept + { + } +}; + + +/// Implementation: + +inline BpTreeBase::BpTreeBase(std::unique_ptr init_root) + : m_root(std::move(init_root)) +{ +} + +inline Allocator& BpTreeBase::get_alloc() const noexcept +{ + return m_root->get_alloc(); +} + +inline void BpTreeBase::destroy() noexcept +{ + if (m_root) + m_root->destroy_deep(); +} + +inline void BpTreeBase::detach() +{ + m_root->detach(); +} + +inline bool BpTreeBase::is_attached() const noexcept +{ + return m_root->is_attached(); +} + +inline bool BpTreeBase::root_is_leaf() const noexcept +{ + return !m_root->is_inner_bptree_node(); +} + +inline BpTreeNode& BpTreeBase::root_as_node() +{ + REALM_ASSERT_DEBUG(!root_is_leaf()); + REALM_ASSERT_DEBUG(dynamic_cast(m_root.get()) != nullptr); + return static_cast(root()); +} + +inline const BpTreeNode& BpTreeBase::root_as_node() const +{ + Array* arr = m_root.get(); + REALM_ASSERT_DEBUG(!root_is_leaf()); + REALM_ASSERT_DEBUG(dynamic_cast(arr) != nullptr); + return static_cast(*arr); +} + +inline void BpTreeBase::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept +{ + m_root->set_parent(parent, ndx_in_parent); +} + +inline size_t BpTreeBase::get_ndx_in_parent() const noexcept +{ + return m_root->get_ndx_in_parent(); +} + +inline void BpTreeBase::set_ndx_in_parent(size_t ndx) noexcept +{ + m_root->set_ndx_in_parent(ndx); +} + +inline void BpTreeBase::update_from_parent(size_t old_baseline) noexcept +{ + m_root->update_from_parent(old_baseline); +} + +inline MemRef BpTreeBase::clone_deep(Allocator& alloc) const +{ + return m_root->clone_deep(alloc); +} + +inline const Array& BpTreeBase::root() const noexcept +{ + return *m_root; +} + +inline Array& BpTreeBase::root() noexcept +{ + return *m_root; +} + +inline size_t BpTreeNode::get_bptree_size() const noexcept +{ + REALM_ASSERT_DEBUG(is_inner_bptree_node()); + int_fast64_t v = back(); + return size_t(v / 2); // v = 1 + 2*total_elems_in_tree +} + +inline size_t BpTreeNode::get_bptree_size_from_header(const char* root_header) noexcept +{ + REALM_ASSERT_DEBUG(get_is_inner_bptree_node_from_header(root_header)); + size_t root_size = get_size_from_header(root_header); + int_fast64_t v = get(root_header, root_size - 1); + return size_t(v / 2); // v = 1 + 2*total_elems_in_tree +} + +inline void BpTreeNode::ensure_bptree_offsets(Array& offsets) +{ + int_fast64_t first_value = get(0); + if (first_value % 2 == 0) { + offsets.init_from_ref(to_ref(first_value)); + } + else { + create_bptree_offsets(offsets, first_value); // Throws + } + offsets.set_parent(this, 0); +} + + +template +ref_type BpTreeNode::bptree_append(TreeInsert& state) +{ + // FIXME: Consider exception safety. Especially, how can the split + // be carried out in an exception safe manner? + // + // Can split be done as a separate preparation step, such that if + // the actual insert fails, the split will still have occured. + // + // Unfortunately, it requires a rather significant rearrangement + // of the insertion flow. Instead of returning the sibling ref + // from insert functions, the leaf-insert functions must instead + // call the special bptree_insert() function on the parent, which + // will then cascade the split towards the root as required. + // + // At each level where a split is required (starting at the leaf): + // + // 1. Create the new sibling. + // + // 2. Copy relevant entries over such that new sibling is in + // its final state. + // + // 3. Call Array::bptree_insert() on parent with sibling ref. + // + // 4. Rearrange entries in original sibling and truncate as + // required (must not throw). + // + // What about the 'offsets' array? It will always be + // present. Consider this carefully. + + REALM_ASSERT_DEBUG(size() >= 1 + 1 + 1); // At least one child + + ArrayParent& childs_parent = *this; + size_t child_ref_ndx = size() - 2; + ref_type child_ref = get_as_ref(child_ref_ndx), new_sibling_ref; + char* child_header = static_cast(m_alloc.translate(child_ref)); + + bool child_is_leaf = !get_is_inner_bptree_node_from_header(child_header); + if (child_is_leaf) { + size_t elem_ndx_in_child = npos; // Append + new_sibling_ref = TreeTraits::leaf_insert(MemRef(child_header, child_ref, m_alloc), childs_parent, + child_ref_ndx, m_alloc, elem_ndx_in_child, state); // Throws + } + else { + BpTreeNode child(m_alloc); + child.init_from_mem(MemRef(child_header, child_ref, m_alloc)); + child.set_parent(&childs_parent, child_ref_ndx); + new_sibling_ref = child.bptree_append(state); // Throws + } + + if (REALM_LIKELY(!new_sibling_ref)) { + // +2 because stored value is 1 + 2*total_elems_in_subtree + adjust(size() - 1, +2); // Throws + return 0; // Child was not split, so parent was not split either + } + + Array offsets(m_alloc); + int_fast64_t first_value = get(0); + if (first_value % 2 == 0) { + // Offsets array is present (general form) + offsets.init_from_ref(to_ref(first_value)); + offsets.set_parent(this, 0); + } + size_t child_ndx = child_ref_ndx - 1; + return insert_bptree_child(offsets, child_ndx, new_sibling_ref, state); // Throws +} + + +template +ref_type BpTreeNode::bptree_insert(size_t elem_ndx, TreeInsert& state) +{ + REALM_ASSERT_3(size(), >=, 1 + 1 + 1); // At least one child + + // Conversion to general form if in compact form. Since this + // conversion will occur from root to leaf, it will maintain + // invar:bptree-node-form. + Array offsets(m_alloc); + ensure_bptree_offsets(offsets); // Throws + + size_t child_ndx, elem_ndx_in_child; + if (elem_ndx == 0) { + // Optimization for prepend + child_ndx = 0; + elem_ndx_in_child = 0; + } + else { + // There is a choice to be made when the element is to be + // inserted between two subtrees. It can either be appended to + // the first subtree, or it can be prepended to the second + // one. We currently always append to the first subtree. It is + // essentially a matter of using the lower vs. the upper bound + // when searching through the offsets array. + child_ndx = offsets.lower_bound_int(elem_ndx); + REALM_ASSERT_3(child_ndx, <, size() - 2); + size_t elem_ndx_offset = child_ndx == 0 ? 0 : to_size_t(offsets.get(child_ndx - 1)); + elem_ndx_in_child = elem_ndx - elem_ndx_offset; + } + + ArrayParent& childs_parent = *this; + size_t child_ref_ndx = child_ndx + 1; + ref_type child_ref = get_as_ref(child_ref_ndx), new_sibling_ref; + char* child_header = static_cast(m_alloc.translate(child_ref)); + bool child_is_leaf = !get_is_inner_bptree_node_from_header(child_header); + if (child_is_leaf) { + REALM_ASSERT_3(elem_ndx_in_child, <=, REALM_MAX_BPNODE_SIZE); + new_sibling_ref = TreeTraits::leaf_insert(MemRef(child_header, child_ref, m_alloc), childs_parent, + child_ref_ndx, m_alloc, elem_ndx_in_child, state); // Throws + } + else { + BpTreeNode child(m_alloc); + child.init_from_mem(MemRef(child_header, child_ref, m_alloc)); + child.set_parent(&childs_parent, child_ref_ndx); + new_sibling_ref = child.bptree_insert(elem_ndx_in_child, state); // Throws + } + + if (REALM_LIKELY(!new_sibling_ref)) { + // +2 because stored value is 1 + 2*total_elems_in_subtree + adjust(size() - 1, +2); // Throws + offsets.adjust(child_ndx, offsets.size(), +1); + return 0; // Child was not split, so parent was not split either + } + + return insert_bptree_child(offsets, child_ndx, new_sibling_ref, state); // Throws +} + +template +BpTree::BpTree() + : BpTree(Allocator::get_default()) +{ +} + +template +BpTree::BpTree(Allocator& alloc) + : BpTreeBase(std::unique_ptr(new LeafType(alloc))) +{ +} + +template +BpTree::BpTree(BpTreeBase::unattached_tag) + : BpTreeBase(nullptr) +{ +} + +template +std::unique_ptr BpTree::create_root_from_mem(Allocator& alloc, MemRef mem) +{ + const char* header = mem.get_addr(); + std::unique_ptr new_root; + bool is_inner_bptree_node = Array::get_is_inner_bptree_node_from_header(header); + + bool can_reuse_root_accessor = + m_root && &m_root->get_alloc() == &alloc && m_root->is_inner_bptree_node() == is_inner_bptree_node; + if (can_reuse_root_accessor) { + if (is_inner_bptree_node) { + m_root->init_from_mem(mem); + } + else { + static_cast(*m_root).init_from_mem(mem); + } + return std::move(m_root); // Same root will be reinstalled. + } + + // Not reusing root note, allocating a new one. + if (is_inner_bptree_node) { + new_root.reset(new BpTreeNode{alloc}); + new_root->init_from_mem(mem); + } + else { + std::unique_ptr leaf{new LeafType{alloc}}; + leaf->init_from_mem(mem); + new_root = std::move(leaf); + } + return new_root; +} + +template +std::unique_ptr BpTree::create_root_from_ref(Allocator& alloc, ref_type ref) +{ + MemRef mem = MemRef{alloc.translate(ref), ref, alloc}; + return create_root_from_mem(alloc, mem); +} + +template +void BpTree::init_from_ref(Allocator& alloc, ref_type ref) +{ + auto new_root = create_root_from_ref(alloc, ref); + replace_root(std::move(new_root)); +} + +template +void BpTree::init_from_mem(Allocator& alloc, MemRef mem) +{ + auto new_root = create_root_from_mem(alloc, mem); + replace_root(std::move(new_root)); +} + +template +void BpTree::init_from_parent() +{ + ref_type ref = root().get_ref_from_parent(); + if (ref) { + ArrayParent* parent = m_root->get_parent(); + size_t ndx_in_parent = m_root->get_ndx_in_parent(); + auto new_root = create_root_from_ref(get_alloc(), ref); + new_root->set_parent(parent, ndx_in_parent); + m_root = std::move(new_root); + } + else { + m_root->detach(); + } +} + +template +typename BpTree::LeafType& BpTree::root_as_leaf() +{ + REALM_ASSERT_DEBUG(root_is_leaf()); + REALM_ASSERT_DEBUG(dynamic_cast(m_root.get()) != nullptr); + return static_cast(root()); +} + +template +const typename BpTree::LeafType& BpTree::root_as_leaf() const +{ + REALM_ASSERT_DEBUG(root_is_leaf()); + REALM_ASSERT_DEBUG(dynamic_cast(m_root.get()) != nullptr); + return static_cast(root()); +} + +template +size_t BpTree::size() const noexcept +{ + if (root_is_leaf()) { + return root_as_leaf().size(); + } + return root_as_node().get_bptree_size(); +} + +template +T BpTree::back() const noexcept +{ + // FIXME: slow + return get(size() - 1); +} + +namespace _impl { + +// NullableOrNothing encapsulates the behavior of nullable and +// non-nullable leaf types, so that non-nullable leaf types +// don't have to implement is_null/set_null but BpTree can still +// support the interface (and return false / assert when null +// is not supported). +template +struct NullableOrNothing { + static bool is_null(const Leaf& leaf, size_t ndx) + { + return leaf.is_null(ndx); + } + static void set_null(Leaf& leaf, size_t ndx) + { + leaf.set_null(ndx); + } +}; +template <> +struct NullableOrNothing { + static bool is_null(const ArrayInteger&, size_t) + { + return false; + } + static void set_null(ArrayInteger&, size_t) + { + REALM_ASSERT_RELEASE(false); + } +}; +} + +template +bool BpTree::is_null(size_t ndx) const noexcept +{ + if (root_is_leaf()) { + return _impl::NullableOrNothing::is_null(root_as_leaf(), ndx); + } + LeafType fallback(get_alloc()); + const LeafType* leaf; + LeafInfo leaf_info{&leaf, &fallback}; + size_t ndx_in_leaf; + get_leaf(ndx, ndx_in_leaf, leaf_info); + return _impl::NullableOrNothing::is_null(*leaf, ndx_in_leaf); +} + +template +T BpTree::get(size_t ndx) const noexcept +{ + REALM_ASSERT_DEBUG_EX(ndx < size(), ndx, size()); + if (root_is_leaf()) { + return root_as_leaf().get(ndx); + } + + // Use direct getter to avoid initializing leaf array: + std::pair p = root_as_node().get_bptree_leaf(ndx); + const char* leaf_header = p.first.get_addr(); + size_t ndx_in_leaf = p.second; + return LeafType::get(leaf_header, ndx_in_leaf); +} + +template +template +void BpTree::bptree_insert(size_t row_ndx, BpTreeNode::TreeInsert& state, size_t num_rows) +{ + ref_type new_sibling_ref; + for (size_t i = 0; i < num_rows; ++i) { + size_t row_ndx_2 = row_ndx == realm::npos ? realm::npos : row_ndx + i; + if (root_is_leaf()) { + REALM_ASSERT_DEBUG(row_ndx_2 == realm::npos || row_ndx_2 < REALM_MAX_BPNODE_SIZE); + new_sibling_ref = root_as_leaf().bptree_leaf_insert(row_ndx_2, state.m_value, state); + } + else { + if (row_ndx_2 == realm::npos) { + new_sibling_ref = root_as_node().bptree_append(state); // Throws + } + else { + new_sibling_ref = root_as_node().bptree_insert(row_ndx_2, state); // Throws + } + } + + if (REALM_UNLIKELY(new_sibling_ref)) { + bool is_append = row_ndx_2 == realm::npos; + introduce_new_root(new_sibling_ref, state, is_append); + } + } +} + +template +struct BpTree::LeafValueInserter { + using value_type = T; + T m_value; + LeafValueInserter(T value) + : m_value(std::move(value)) + { + } + + // TreeTraits concept: + static ref_type leaf_insert(MemRef leaf_mem, ArrayParent& parent, size_t ndx_in_parent, Allocator& alloc, + size_t ndx_in_leaf, BpTreeNode::TreeInsert& state) + { + LeafType leaf{alloc}; + leaf.init_from_mem(leaf_mem); + leaf.set_parent(&parent, ndx_in_parent); + // Should not move out of m_value, because the same inserter may be used to perform + // multiple insertions (for example, if num_rows > 1). + return leaf.bptree_leaf_insert(ndx_in_leaf, state.m_value, state); + } +}; + +template +struct BpTree::LeafNullInserter { + using value_type = null; + // TreeTraits concept: + static ref_type leaf_insert(MemRef leaf_mem, ArrayParent& parent, size_t ndx_in_parent, Allocator& alloc, + size_t ndx_in_leaf, BpTreeNode::TreeInsert& state) + { + LeafType leaf{alloc}; + leaf.init_from_mem(leaf_mem); + leaf.set_parent(&parent, ndx_in_parent); + return leaf.bptree_leaf_insert(ndx_in_leaf, null{}, state); + } +}; + +template +void BpTree::insert(size_t row_ndx, T value, size_t num_rows) +{ + REALM_ASSERT_DEBUG(row_ndx == npos || row_ndx < size()); + BpTreeNode::TreeInsert inserter; + inserter.m_value = std::move(value); + inserter.m_nullable = std::is_same>::value; // FIXME + bptree_insert(row_ndx, inserter, num_rows); // Throws +} + +template +struct BpTree::UpdateHandler : BpTreeNode::UpdateHandler { + LeafType m_leaf; + const T m_value; + UpdateHandler(BpTreeBase& tree, T value) noexcept + : m_leaf(tree.get_alloc()) + , m_value(std::move(value)) + { + } + void update(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, size_t elem_ndx_in_leaf) override + { + m_leaf.init_from_mem(mem); + m_leaf.set_parent(parent, ndx_in_parent); + m_leaf.set(elem_ndx_in_leaf, m_value); // Throws + } +}; + +template +struct BpTree::SetNullHandler : BpTreeNode::UpdateHandler { + LeafType m_leaf; + SetNullHandler(BpTreeBase& tree) noexcept + : m_leaf(tree.get_alloc()) + { + } + void update(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, size_t elem_ndx_in_leaf) override + { + m_leaf.init_from_mem(mem); + m_leaf.set_parent(parent, ndx_in_parent); + _impl::NullableOrNothing::set_null(m_leaf, elem_ndx_in_leaf); // Throws + } +}; + +template +void BpTree::set(size_t ndx, T value) +{ + if (root_is_leaf()) { + root_as_leaf().set(ndx, std::move(value)); + } + else { + UpdateHandler set_leaf_elem(*this, std::move(value)); + static_cast(m_root.get())->update_bptree_elem(ndx, set_leaf_elem); // Throws + } +} + +template +void BpTree::set_null(size_t ndx) +{ + if (root_is_leaf()) { + _impl::NullableOrNothing::set_null(root_as_leaf(), ndx); + } + else { + SetNullHandler set_leaf_elem(*this); + static_cast(m_root.get())->update_bptree_elem(ndx, set_leaf_elem); // Throws; + } +} + +template +struct BpTree::EraseHandler : BpTreeNode::EraseHandler { + BpTreeBase& m_tree; + LeafType m_leaf; + bool m_leaves_have_refs; // FIXME: Should be able to eliminate this. + EraseHandler(BpTreeBase& tree) noexcept + : m_tree(tree) + , m_leaf(tree.get_alloc()) + , m_leaves_have_refs(false) + { + } + bool erase_leaf_elem(MemRef leaf_mem, ArrayParent* parent, size_t leaf_ndx_in_parent, + size_t elem_ndx_in_leaf) override + { + m_leaf.init_from_mem(leaf_mem); + REALM_ASSERT_3(m_leaf.size(), >=, 1); + size_t last_ndx = m_leaf.size() - 1; + if (last_ndx == 0) { + m_leaves_have_refs = m_leaf.has_refs(); + return true; + } + m_leaf.set_parent(parent, leaf_ndx_in_parent); + size_t ndx = elem_ndx_in_leaf; + if (ndx == npos) + ndx = last_ndx; + m_leaf.erase(ndx); // Throws + return false; + } + void destroy_leaf(MemRef leaf_mem) noexcept override + { + // FIXME: Seems like this would cause file space leaks if + // m_leaves_have_refs is true, but consider carefully how + // m_leaves_have_refs get its value. + m_tree.get_alloc().free_(leaf_mem); + } + void replace_root_by_leaf(MemRef leaf_mem) override + { + std::unique_ptr leaf{new LeafType(m_tree.get_alloc())}; // Throws + leaf->init_from_mem(leaf_mem); + m_tree.replace_root(std::move(leaf)); // Throws + } + void replace_root_by_empty_leaf() override + { + std::unique_ptr leaf{new LeafType(m_tree.get_alloc())}; // Throws + leaf->create(m_leaves_have_refs ? Array::type_HasRefs : Array::type_Normal); // Throws + m_tree.replace_root(std::move(leaf)); // Throws + } +}; + +template +void BpTree::erase(size_t ndx, bool is_last) +{ + REALM_ASSERT_DEBUG_EX(ndx < size(), ndx, size()); + REALM_ASSERT_DEBUG(is_last == (ndx == size() - 1)); + if (root_is_leaf()) { + root_as_leaf().erase(ndx); + } + else { + size_t ndx_2 = is_last ? npos : ndx; + EraseHandler handler(*this); + BpTreeNode::erase_bptree_elem(&root_as_node(), ndx_2, handler); + } +} + +template +void BpTree::move_last_over(size_t row_ndx, size_t last_row_ndx) +{ + // Copy value from last row over + T value = get(last_row_ndx); + set(row_ndx, value); + erase(last_row_ndx, true); +} + +template +void BpTree::clear() +{ + if (root_is_leaf()) { + if (std::is_same::value && root().get_type() == Array::type_HasRefs) { + // FIXME: This is because some column types rely on integer columns + // to contain refs. + root().clear_and_destroy_children(); + } + else { + root_as_leaf().clear(); + } + } + else { + Allocator& alloc = get_alloc(); + root().destroy_deep(); + + std::unique_ptr new_root(new LeafType(alloc)); + new_root->create(); + replace_root(std::move(new_root)); + } +} + + +template +struct BpTree::AdjustHandler : BpTreeNode::UpdateHandler { + LeafType m_leaf; + const T m_diff; + AdjustHandler(BpTreeBase& tree, T diff) + : m_leaf(tree.get_alloc()) + , m_diff(diff) + { + } + + void update(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, size_t) final + { + m_leaf.init_from_mem(mem); + m_leaf.set_parent(parent, ndx_in_parent); + m_leaf.adjust(0, m_leaf.size(), m_diff); + } +}; + +template +void BpTree::adjust(T diff) +{ + if (root_is_leaf()) { + root_as_leaf().adjust(0, m_root->size(), std::move(diff)); // Throws + } + else { + AdjustHandler adjust_leaf_elem(*this, std::move(diff)); + root_as_node().update_bptree_leaves(adjust_leaf_elem); // Throws + } +} + +template +void BpTree::adjust(size_t ndx, T diff) +{ + static_assert(std::is_arithmetic::value, "adjust is undefined for non-arithmetic trees"); + set(ndx, get(ndx) + diff); +} + +template +struct BpTree::AdjustGEHandler : BpTreeNode::UpdateHandler { + LeafType m_leaf; + const T m_limit, m_diff; + + AdjustGEHandler(BpTreeBase& tree, T limit, T diff) + : m_leaf(tree.get_alloc()) + , m_limit(limit) + , m_diff(diff) + { + } + + void update(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, size_t) final + { + m_leaf.init_from_mem(mem); + m_leaf.set_parent(parent, ndx_in_parent); + m_leaf.adjust_ge(m_limit, m_diff); + } +}; + +template +void BpTree::adjust_ge(T limit, T diff) +{ + if (root_is_leaf()) { + root_as_leaf().adjust_ge(std::move(limit), std::move(diff)); // Throws + } + else { + AdjustGEHandler adjust_leaf_elem(*this, std::move(limit), std::move(diff)); + root_as_node().update_bptree_leaves(adjust_leaf_elem); // Throws + } +} + +template +struct BpTree::SliceHandler : public BpTreeBase::SliceHandler { +public: + SliceHandler(Allocator& alloc) + : m_leaf(alloc) + { + } + MemRef slice_leaf(MemRef leaf_mem, size_t offset, size_t size, Allocator& target_alloc) override + { + m_leaf.init_from_mem(leaf_mem); + return m_leaf.slice_and_clone_children(offset, size, target_alloc); // Throws + } + +private: + LeafType m_leaf; +}; + +template +ref_type BpTree::write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream& out) const +{ + ref_type ref; + if (root_is_leaf()) { + Allocator& alloc = Allocator::get_default(); + MemRef mem = root_as_leaf().slice_and_clone_children(slice_offset, slice_size, alloc); // Throws + Array slice(alloc); + _impl::DeepArrayDestroyGuard dg(&slice); + slice.init_from_mem(mem); + bool deep = true; + bool only_when_modified = false; + ref = slice.write(out, deep, only_when_modified); // Throws + } + else { + SliceHandler handler(get_alloc()); + ref = write_subtree(root_as_node(), slice_offset, slice_size, table_size, handler, out); // Throws + } + return ref; +} + +template +MemRef BpTree::create_leaf(Array::Type leaf_type, size_t size, T value, Allocator& alloc) +{ + bool context_flag = false; + MemRef mem = LeafType::create_array(leaf_type, context_flag, size, std::move(value), alloc); + return mem; +} + +template +void BpTree::get_leaf(size_t ndx, size_t& ndx_in_leaf, LeafInfo& inout_leaf_info) const noexcept +{ + if (root_is_leaf()) { + ndx_in_leaf = ndx; + *inout_leaf_info.out_leaf = &root_as_leaf(); + return; + } + std::pair p = root_as_node().get_bptree_leaf(ndx); + inout_leaf_info.fallback->init_from_mem(p.first); + ndx_in_leaf = p.second; + *inout_leaf_info.out_leaf = inout_leaf_info.fallback; +} + +template +size_t BpTree::find_first(T value, size_t begin, size_t end) const +{ + if (root_is_leaf()) { + return root_as_leaf().find_first(value, begin, end); + } + + // FIXME: It would be better to always require that 'end' is + // specified explicitly, since Table has the size readily + // available, and Array::get_bptree_size() is deprecated. + if (end == npos) + end = size(); + + LeafType leaf_cache(get_alloc()); + size_t ndx_in_tree = begin; + while (ndx_in_tree < end) { + const LeafType* leaf; + LeafInfo leaf_info{&leaf, &leaf_cache}; + size_t ndx_in_leaf; + get_leaf(ndx_in_tree, ndx_in_leaf, leaf_info); + size_t leaf_offset = ndx_in_tree - ndx_in_leaf; + size_t end_in_leaf = std::min(leaf->size(), end - leaf_offset); + size_t ndx = leaf->find_first(value, ndx_in_leaf, end_in_leaf); // Throws (maybe) + if (ndx != not_found) + return leaf_offset + ndx; + ndx_in_tree = leaf_offset + end_in_leaf; + } + + return not_found; +} + +template +void BpTree::find_all(IntegerColumn& result, T value, size_t begin, size_t end) const +{ + if (root_is_leaf()) { + root_as_leaf().find_all(&result, value, 0, begin, end); // Throws + return; + } + + // FIXME: It would be better to always require that 'end' is + // specified explicitely, since Table has the size readily + // available, and Array::get_bptree_size() is deprecated. + if (end == npos) + end = size(); + + LeafType leaf_cache(get_alloc()); + size_t ndx_in_tree = begin; + while (ndx_in_tree < end) { + const LeafType* leaf; + LeafInfo leaf_info{&leaf, &leaf_cache}; + size_t ndx_in_leaf; + get_leaf(ndx_in_tree, ndx_in_leaf, leaf_info); + size_t leaf_offset = ndx_in_tree - ndx_in_leaf; + size_t end_in_leaf = std::min(leaf->size(), end - leaf_offset); + leaf->find_all(&result, value, leaf_offset, ndx_in_leaf, end_in_leaf); // Throws + ndx_in_tree = leaf_offset + end_in_leaf; + } +} + +#if defined(REALM_DEBUG) +template +size_t BpTree::verify_leaf(MemRef mem, Allocator& alloc) +{ + LeafType leaf(alloc); + leaf.init_from_mem(mem); + leaf.verify(); + return leaf.size(); +} + +template +void BpTree::verify() const +{ + if (root_is_leaf()) { + root_as_leaf().verify(); + } + else { + root().verify_bptree(&verify_leaf); + } +} +#endif // REALM_DEBUG + +template +void BpTree::leaf_to_dot(MemRef leaf_mem, ArrayParent* parent, size_t ndx_in_parent, std::ostream& out, + Allocator& alloc) +{ + LeafType leaf(alloc); + leaf.init_from_mem(leaf_mem); + leaf.set_parent(parent, ndx_in_parent); + leaf.to_dot(out); +} + +} // namespace realm + +#endif // REALM_BPTREE_HPP diff --git a/Pods/Realm/include/core/realm/chunked_binary.hpp b/Pods/Realm/include/core/realm/chunked_binary.hpp new file mode 100644 index 0000000000..1e76fa85e5 --- /dev/null +++ b/Pods/Realm/include/core/realm/chunked_binary.hpp @@ -0,0 +1,125 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_NOINST_CHUNKED_BINARY_HPP +#define REALM_NOINST_CHUNKED_BINARY_HPP + +#include +#include +#include + +#include +#include + + +namespace realm { + +/// ChunkedBinaryData manages a vector of BinaryData. It is used to facilitate +/// extracting large binaries from binary columns and tables. +class ChunkedBinaryData { +public: + + ChunkedBinaryData(); + ChunkedBinaryData(const BinaryData& bd); + ChunkedBinaryData(const BinaryIterator& bd); + ChunkedBinaryData(const BinaryColumn& col, size_t index); + + /// size() returns the number of bytes in the chunked binary. + /// FIXME: This operation is O(n). + size_t size() const noexcept; + + /// is_null returns true if the chunked binary has zero chunks or if + /// the first chunk points to the nullptr. + bool is_null() const; + + /// FIXME: O(n) + char operator[](size_t index) const; + + std::string hex_dump(const char* separator = " ", int min_digits = -1) const; + + void write_to(util::ResettableExpandableBufferOutputStream& out) const; + + /// copy_to() copies the chunked binary data to \a buffer of size + /// \a buffer_size starting at \a offset in the ChunkedBinary. + /// copy_to() copies until the end of \a buffer or the end of + /// the ChunkedBinary whichever comes first. + /// copy_to() returns the number of copied bytes. + size_t copy_to(char* buffer, size_t buffer_size, size_t offset) const; + + /// copy_to() allocates a buffer of size() in \a dest and + /// copies the chunked binary data to \a dest. + size_t copy_to(std::unique_ptr& dest) const; + + /// get_first_chunk() is used in situations + /// where it is known that there is exactly one + /// chunk. This is the case if the ChunkedBinary + /// has been constructed from BinaryData. + BinaryData get_first_chunk() const; + +private: + BinaryIterator m_begin; + friend class ChunkedBinaryInputStream; +}; + +// FIXME: When ChunkedBinaryData is moved into Core, this should be moved as well. +class ChunkedBinaryInputStream : public _impl::NoCopyInputStream { +public: + explicit ChunkedBinaryInputStream(const ChunkedBinaryData& chunks) + : m_it(chunks.m_begin) + { + } + + bool next_block(const char*& begin, const char*& end) override + { + BinaryData block = m_it.get_next(); + begin = block.data(); + end = begin + block.size(); + return begin != end; + } + +private: + BinaryIterator m_it; +}; + + +/// Implementation: + + +inline ChunkedBinaryData::ChunkedBinaryData() +{ +} + +inline ChunkedBinaryData::ChunkedBinaryData(const BinaryData& bd) : m_begin{bd} +{ +} + +inline ChunkedBinaryData::ChunkedBinaryData(const BinaryIterator& bd) : m_begin{bd} +{ +} + +inline ChunkedBinaryData::ChunkedBinaryData(const BinaryColumn& col, size_t index) + : m_begin{&col, index} +{ +} + + +} // namespace realm + +#endif // REALM_NOINST_CHUNKED_BINARY_HPP diff --git a/Pods/Realm/include/core/realm/column.hpp b/Pods/Realm/include/core/realm/column.hpp new file mode 100644 index 0000000000..928fd93a7c --- /dev/null +++ b/Pods/Realm/include/core/realm/column.hpp @@ -0,0 +1,1854 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_HPP +#define REALM_COLUMN_HPP + +#include // unint8_t etc +#include // size_t +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace realm { + + +// Pre-definitions +struct CascadeState; +class StringIndex; + +template +struct ImplicitNull; + +template +struct ImplicitNull> { + static constexpr bool value = true; +}; + +template <> +struct ImplicitNull { + static constexpr bool value = false; +}; + +template <> +struct ImplicitNull { + static constexpr bool value = true; +}; + +template <> +struct ImplicitNull { + static constexpr bool value = true; +}; + +// FIXME: Add specialization for ImplicitNull for float, double, StringData, BinaryData. + +template +R aggregate(const ColType& column, T target, size_t start, size_t end, size_t limit, size_t* return_ndx); + + +// Iterator with random access for Columns +template +class ColumnRandIterator : public std::iterator { +public: + ColumnRandIterator(const Column* src_col, size_t ndx = 0); + bool operator==(const ColumnRandIterator& rhs) const; + bool operator!=(const ColumnRandIterator& rhs) const; + bool operator<(const ColumnRandIterator& rhs) const; + bool operator>(const ColumnRandIterator& rhs) const; + bool operator<=(const ColumnRandIterator& rhs) const; + bool operator>=(const ColumnRandIterator& rhs) const; + ColumnRandIterator& operator+=(ptrdiff_t movement); + ColumnRandIterator& operator-=(ptrdiff_t movement); + ColumnRandIterator& operator++(); + ColumnRandIterator& operator--(); + ColumnRandIterator operator++(int); + ColumnRandIterator operator--(int); + ColumnRandIterator operator+(ptrdiff_t movement); + ColumnRandIterator operator-(ptrdiff_t movement); + ptrdiff_t operator-(const ColumnRandIterator& right) const; + const ColumnDataType operator*() const; + const ColumnDataType operator->() const; + const ColumnDataType operator[](ptrdiff_t offset) const; + size_t get_col_ndx() const; + +protected: + size_t m_col_ndx; + const Column* m_col; +}; + +/// Base class for all column types. +class ColumnBase { +public: + /// Get the number of entries in this column. This operation is relatively + /// slow. + virtual size_t size() const noexcept = 0; + + /// \throw LogicError Thrown if this column is not string valued. + virtual void set_string(size_t row_ndx, StringData value); + + /// Whether or not this column is nullable. + virtual bool is_nullable() const noexcept; + + /// Whether or not the value at \a row_ndx is NULL. If the column is not + /// nullable, always returns false. + virtual bool is_null(size_t row_ndx) const noexcept; + + /// Sets the value at \a row_ndx to be NULL. + /// \throw LogicError Thrown if this column is not nullable. + virtual void set_null(size_t row_ndx); + + /// Inserts the specified number of elements into this column + /// starting at the specified row index. The new elements will have the + /// default value for the column type. + /// + /// \param row_ndx The row to start insertion at. If the row_ndx is less + /// than prior_num_rows then previous rows from row_ndx onwards will be + /// moved ahead by num_rows_to_insert. + /// + /// \param num_rows_to_insert The number of rows to insert. There is no + /// restriction on this value. + /// + /// \param prior_num_rows The number of elements in this column prior to the + /// modification. + /// + /// \param nullable Specifies whether or not this column is nullable. This + /// function may assert if nullable does not agree with \a is_nullable() + virtual void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) = 0; + + /// Removes the specified number of consecutive elements from + /// this column, starting at the specified row index. + /// + /// \param row_ndx The row to start removal at (inclusive). This must be + /// less than prior_num_rows. + /// + /// \param num_rows_to_erase The number of rows to erase. + /// The row_ndx + num_rows_to_erase must be less than prior_num_rows. + /// + /// \param prior_num_rows The number of elements in this column prior to the + /// modification. + /// + /// \param broken_reciprocal_backlinks If true, link columns must assume + /// that reciprocal backlinks have already been removed. Non-link columns + /// should ignore this argument. + virtual void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, + bool broken_reciprocal_backlinks) = 0; + + /// Removes the element at the specified row index by + /// moving the element at the last row index over it. This reduces the + /// number of elements by one. + /// + /// \param row_ndx The row to erase. Must be less than prior_num_rows. + /// + /// \param prior_num_rows The number of elements in this column prior to the + /// modification. + /// + /// \param broken_reciprocal_backlinks If true, link columns must assume + /// that reciprocal backlinks have already been removed. Non-link columns + /// should ignore this argument. + virtual void move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool broken_reciprocal_backlinks) = 0; + + /// Remove all elements from this column. + /// + /// \param num_rows The total number of rows in this column. + /// + /// \param broken_reciprocal_backlinks If true, link columns must assume + /// that reciprocal backlinks have already been removed. Non-link columns + /// should ignore this argument. + virtual void clear(size_t num_rows, bool broken_reciprocal_backlinks) = 0; + + /// \brief Swap the elements at the specified indices. + /// + /// Behaviour is undefined if: + /// - \a row_ndx_1 or \a row_ndx_2 point to an invalid element (out-of + /// bounds) + /// - \a row_ndx_1 and \a row_ndx_2 point to the same value + virtual void swap_rows(size_t row_ndx_1, size_t row_ndx_2) = 0; + + virtual void destroy() noexcept = 0; + void move_assign(ColumnBase& col) noexcept; + + virtual ~ColumnBase() noexcept + { + } + + // Disable copying, this is not supported. + ColumnBase& operator=(const ColumnBase&) = delete; + ColumnBase(const ColumnBase&) = delete; + + // Getter function for index. For integer index, the caller must supply a + // buffer that we can store the extracted value in (it may be bitpacked, so + // we cannot return a pointer in to the Array as we do with String index). + virtual StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept = 0; + + // Search index + virtual bool supports_search_index() const noexcept; + virtual bool has_search_index() const noexcept; + virtual StringIndex* create_search_index(); + virtual void destroy_search_index() noexcept; + virtual const StringIndex* get_search_index() const noexcept; + virtual StringIndex* get_search_index() noexcept; + virtual void set_search_index_ref(ref_type, ArrayParent*, size_t ndx_in_parent); + + virtual Allocator& get_alloc() const noexcept = 0; + + /// Returns the 'ref' of the root array. + virtual ref_type get_ref() const noexcept = 0; + virtual MemRef get_mem() const noexcept = 0; + + virtual void replace_root_array(std::unique_ptr leaf) = 0; + virtual MemRef clone_deep(Allocator& alloc) const = 0; + virtual void detach(void) = 0; + virtual bool is_attached(void) const noexcept = 0; + + static size_t get_size_from_type_and_ref(ColumnType, ref_type, Allocator&, bool) noexcept; + + // These assume that the right column compile-time type has been + // figured out. + static size_t get_size_from_ref(ref_type root_ref, Allocator&); + static size_t get_size_from_ref(ref_type spec_ref, ref_type columns_ref, Allocator&); + + /// Write a slice of this column to the specified output stream. + virtual ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const = 0; + + /// Get this column's logical index within the containing table, or npos + /// for free-standing or non-top-level columns. + size_t get_column_index() const noexcept + { + return m_column_ndx; + } + + virtual void set_parent(ArrayParent*, size_t ndx_in_parent) noexcept = 0; + virtual size_t get_ndx_in_parent() const noexcept = 0; + virtual void set_ndx_in_parent(size_t ndx_in_parent) noexcept = 0; + + /// Called to update refs and memory pointers of this column accessor and + /// all its nested accessors, but only in cases where the logical contents + /// in strictly unchanged. Group::commit(), and + /// SharedGroup::commit_and_continue_as_read()() are examples of such + /// cases. In both those cases, the purpose is to keep user visible + /// accessors in a valid state across a commit. + virtual void update_from_parent(size_t old_baseline) noexcept = 0; + + //@{ + + /// cascade_break_backlinks_to() is called iteratively for each column by + /// Table::cascade_break_backlinks_to() with the same arguments as are + /// passed to Table::cascade_break_backlinks_to(). Link columns must + /// override it. The same is true for cascade_break_backlinks_to_all_rows(), + /// except that it is called from + /// Table::cascade_break_backlinks_to_all_rows(), and that it expects + /// Table::cascade_break_backlinks_to_all_rows() to pass the number of rows + /// in the table as \a num_rows. + + virtual void cascade_break_backlinks_to(size_t row_ndx, CascadeState&); + virtual void cascade_break_backlinks_to_all_rows(size_t num_rows, CascadeState&); + + //@} + + void discard_child_accessors() noexcept; + + /// For columns that are able to contain subtables, this function returns + /// the pointer to the subtable accessor at the specified row index if it + /// exists, otherwise it returns null. For other column types, this function + /// returns null. + virtual TableRef get_subtable_accessor(size_t row_ndx) const noexcept; + + /// Detach and remove the subtable accessor at the specified row if it + /// exists. For column types that are unable to contain subtable, this + /// function does nothing. + virtual void discard_subtable_accessor(size_t row_ndx) noexcept; + + virtual void adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept; + virtual void adj_acc_erase_row(size_t row_ndx) noexcept; + /// See Table::adj_acc_move_over() + virtual void adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; + virtual void adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; + virtual void adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept; + virtual void adj_acc_merge_rows(size_t old_row_ndx, size_t new_row_ndx) noexcept; + virtual void adj_acc_clear_root_table() noexcept; + + enum { + mark_Recursive = 0x01, + mark_LinkTargets = 0x02, + mark_LinkOrigins = 0x04, + }; + + virtual void mark(int type) noexcept; + + virtual void bump_link_origin_table_version() noexcept; + + virtual int compare_values(size_t row1, size_t row2) const noexcept = 0; + + /// Refresh the dirty part of the accessor subtree rooted at this column + /// accessor. + /// + /// The following conditions are necessary and sufficient for the proper + /// operation of this function: + /// + /// - The parent table accessor (excluding its column accessors) is in a + /// valid state (already refreshed). + /// + /// - Every subtable accessor in the subtree is marked dirty if it needs to + /// be refreshed, or if it has a descendant accessor that needs to be + /// refreshed. + /// + /// - This column accessor, as well as all its descendant accessors, are in + /// structural correspondence with the underlying node hierarchy whose + /// root ref is stored in the parent (`Table::m_columns`) (see + /// AccessorConsistencyLevels). + /// + /// - The 'index in parent' property of the cached root array + /// (`root->m_ndx_in_parent`) is valid. + virtual void refresh_accessor_tree(size_t new_col_ndx, const Spec&); + + virtual void verify() const = 0; + virtual void verify(const Table&, size_t col_ndx) const; + virtual void to_dot(std::ostream&, StringData title = StringData()) const = 0; + virtual void do_dump_node_structure(std::ostream&, int level) const = 0; + +#ifdef REALM_DEBUG + void dump_node_structure() const; // To std::cerr (for GDB) + void bptree_to_dot(const Array* root, std::ostream& out) const; +#endif + +protected: + using SliceHandler = BpTreeBase::SliceHandler; + + ColumnBase(size_t column_ndx = npos) + : m_column_ndx(column_ndx) + { + } + ColumnBase(ColumnBase&&) = default; + + // Must not assume more than minimal consistency (see + // AccessorConsistencyLevels). + virtual void do_discard_child_accessors() noexcept + { + } + + //@{ + /// \tparam L Any type with an appropriate `value_type`, %size(), + /// and %get() members. + template + size_t lower_bound(const L& list, T value) const noexcept; + + template + size_t upper_bound(const L& list, T value) const noexcept; + //@} + + // Node functions + + class CreateHandler { + public: + virtual ref_type create_leaf(size_t size) = 0; + ~CreateHandler() noexcept + { + } + }; + + static ref_type create(Allocator&, size_t size, CreateHandler&); + + class LeafToDot; + virtual void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const = 0; + + template + static int compare_values(const Column* column, size_t row1, size_t row2) noexcept; + +private: + size_t m_column_ndx = npos; + + static ref_type build(size_t* rest_size_ptr, size_t fixed_height, Allocator&, CreateHandler&); +}; + + +// FIXME: Temporary class until all column types have been migrated to use BpTree interface +class ColumnBaseSimple : public ColumnBase { +public: + //@{ + /// Returns the array node at the root of this column, but note + /// that there is no guarantee that this node is an inner B+-tree + /// node or a leaf. This is the case for a MixedColumn in + /// particular. + Array* get_root_array() noexcept + { + return m_array.get(); + } + const Array* get_root_array() const noexcept + { + return m_array.get(); + } + //@} + + Allocator& get_alloc() const noexcept final + { + return m_array->get_alloc(); + } + void destroy() noexcept override + { + if (m_array) + m_array->destroy_deep(); + } + ref_type get_ref() const noexcept final + { + return m_array->get_ref(); + } + MemRef get_mem() const noexcept final + { + return m_array->get_mem(); + } + void detach() noexcept final + { + m_array->detach(); + } + bool is_attached() const noexcept final + { + return m_array->is_attached(); + } + void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept final + { + m_array->set_parent(parent, ndx_in_parent); + } + size_t get_ndx_in_parent() const noexcept final + { + return m_array->get_ndx_in_parent(); + } + void set_ndx_in_parent(size_t ndx_in_parent) noexcept override + { + m_array->set_ndx_in_parent(ndx_in_parent); + } + void update_from_parent(size_t old_baseline) noexcept override + { + m_array->update_from_parent(old_baseline); + } + MemRef clone_deep(Allocator& alloc) const override + { + return m_array->clone_deep(alloc); + } + +protected: + ColumnBaseSimple(size_t column_ndx) + : ColumnBase(column_ndx) + { + } + ColumnBaseSimple(Array* root) + : m_array(root) + { + } + std::unique_ptr m_array; + + void replace_root_array(std::unique_ptr new_root) final; + bool root_is_leaf() const noexcept + { + return !m_array->is_inner_bptree_node(); + } + + /// Introduce a new root node which increments the height of the + /// tree by one. + void introduce_new_root(ref_type new_sibling_ref, TreeInsertBase& state, bool is_append); + + static ref_type write(const Array* root, size_t slice_offset, size_t slice_size, size_t table_size, SliceHandler&, + _impl::OutputStream&); + +#if defined(REALM_DEBUG) + void tree_to_dot(std::ostream&) const; +#endif +}; + +class ColumnBaseWithIndex : public ColumnBase { +public: + ~ColumnBaseWithIndex() noexcept override + { + } + void set_ndx_in_parent(size_t ndx) noexcept override; + void update_from_parent(size_t old_baseline) noexcept override; + void refresh_accessor_tree(size_t, const Spec&) override; + void move_assign(ColumnBaseWithIndex& col) noexcept; + void destroy() noexcept override; + + virtual bool supports_search_index() const noexcept override + { + return true; + } + bool has_search_index() const noexcept final + { + return bool(m_search_index); + } + StringIndex* get_search_index() noexcept final + { + return m_search_index.get(); + } + const StringIndex* get_search_index() const noexcept final + { + return m_search_index.get(); + } + void destroy_search_index() noexcept override; + void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent) final; + StringIndex* create_search_index() override = 0; + +protected: + using ColumnBase::ColumnBase; + ColumnBaseWithIndex(ColumnBaseWithIndex&&) = default; + std::unique_ptr m_search_index; +}; + + +/// A column (Column) is a single B+-tree, and the root of +/// the column is the root of the B+-tree. All leaf nodes are arrays. +template +class Column : public ColumnBaseWithIndex { +public: + using value_type = T; + using LeafInfo = typename BpTree::LeafInfo; + using LeafType = typename BpTree::LeafType; + + static constexpr bool nullable = ImplicitNull::value; + + struct unattached_root_tag { + }; + + explicit Column() noexcept + : ColumnBaseWithIndex(npos) + , m_tree(Allocator::get_default()) + { + } + REALM_DEPRECATED("Initialize with ref instead") explicit Column(std::unique_ptr root) noexcept; + Column(Allocator&, ref_type, size_t column_ndx = npos); + Column(unattached_root_tag, Allocator&); + Column(Column&&) noexcept = default; + ~Column() noexcept override; + + void init_from_parent(); + void init_from_ref(Allocator&, ref_type); + void init_from_mem(Allocator&, MemRef); + // Accessor concept: + void destroy() noexcept override; + Allocator& get_alloc() const noexcept final; + ref_type get_ref() const noexcept final; + MemRef get_mem() const noexcept final; + void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override; + size_t get_ndx_in_parent() const noexcept final; + void set_ndx_in_parent(size_t ndx) noexcept final; + void update_from_parent(size_t old_baseline) noexcept override; + void refresh_accessor_tree(size_t, const Spec&) override; + void detach() noexcept final; + bool is_attached() const noexcept final; + MemRef clone_deep(Allocator&) const override; + + void move_assign(Column&); + + static size_t get_size_from_ref(ref_type root_ref, Allocator& alloc) + { + return ColumnBase::get_size_from_ref(root_ref, alloc); + } + + size_t size() const noexcept override; + bool is_empty() const noexcept + { + return size() == 0; + } + bool is_nullable() const noexcept override; + + /// Provides access to the leaf that contains the element at the + /// specified index. Upon return \a ndx_in_leaf will be set to the + /// corresponding index relative to the beginning of the leaf. + /// + /// LeafInfo is a struct defined by the underlying BpTree + /// data structure, that provides a way for the caller to do + /// leaf caching without instantiating too many objects along + /// the way. + /// + /// This function cannot be used for modifying operations as it + /// does not ensure the presence of an unbroken chain of parent + /// accessors. For this reason, the identified leaf should always + /// be accessed through the returned const-qualified reference, + /// and never directly through the specfied fallback accessor. + void get_leaf(size_t ndx, size_t& ndx_in_leaf, LeafInfo& inout_leaf) const noexcept; + + // Getting and setting values + T get(size_t ndx) const noexcept; + bool is_null(size_t ndx) const noexcept override; + T back() const noexcept; + void set(size_t, T value); + void set_null(size_t) override; + void add(T value = T{}); + void insert(size_t ndx, T value = T{}, size_t num_rows = 1); + void erase(size_t row_ndx); + void erase(size_t row_ndx, bool is_last); + void move_last_over(size_t row_ndx, size_t last_row_ndx); + void clear(); + + // Index support + StringData get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept override; + + // FIXME: Remove these + uint64_t get_uint(size_t ndx) const noexcept; + ref_type get_as_ref(size_t ndx) const noexcept; + void set_uint(size_t ndx, uint64_t value); + void set_as_ref(size_t ndx, ref_type value); + + template + void adjust(size_t ndx, U diff); + + template + void adjust(U diff); + + template + void adjust_ge(T limit, U diff); + + size_t count(T target) const; + + typename ColumnTypeTraits::sum_type sum(size_t start = 0, size_t end = npos, size_t limit = npos, + size_t* return_ndx = nullptr) const; + + typename ColumnTypeTraits::minmax_type maximum(size_t start = 0, size_t end = npos, size_t limit = npos, + size_t* return_ndx = nullptr) const; + + typename ColumnTypeTraits::minmax_type minimum(size_t start = 0, size_t end = npos, size_t limit = npos, + size_t* return_ndx = nullptr) const; + + double average(size_t start = 0, size_t end = npos, size_t limit = npos, size_t* return_ndx = nullptr) const; + + size_t find_first(T value, size_t begin = 0, size_t end = npos) const; + void find_all(Column& out_indices, T value, size_t begin = 0, size_t end = npos) const; + + void populate_search_index(); + StringIndex* create_search_index() override; + inline bool supports_search_index() const noexcept override + { + if (realm::is_any::value) + return false; + else + return true; + } + + + //@{ + /// Find the lower/upper bound for the specified value assuming + /// that the elements are already sorted in ascending order + /// according to ordinary integer comparison. + size_t lower_bound(T value) const noexcept; + size_t upper_bound(T value) const noexcept; + //@} + + using const_iterator = ColumnRandIterator; + + const_iterator cbegin() const + { + return const_iterator(this, 0); // `this` is const in a const method + } + const_iterator cend() const + { + return const_iterator(this, size()); + } + + size_t find_gte(T target, size_t start) const; + + bool compare(const Column&) const noexcept; + int compare_values(size_t row1, size_t row2) const noexcept override; + + static ref_type create(Allocator&, Array::Type leaf_type = Array::type_Normal, size_t size = 0, T value = T{}); + + // Overriding method in ColumnBase + ref_type write(size_t, size_t, size_t, _impl::OutputStream&) const override; + + void insert_rows(size_t, size_t, size_t, bool) override; + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + + /// \brief Swap the elements at the specified indices. + /// + /// If this \c Column has a search index defined, it will be updated to + /// reflect the changes induced by the swap. + /// + /// Behaviour is undefined if: + /// - \a row_ndx_1 or \a row_ndx_2 point to an invalid element (out-of + /// bounds) + /// - \a row_ndx_1 and \a row_ndx_2 point to the same value + void swap_rows(size_t, size_t) override; + void clear(size_t, bool) override; + + /// \param row_ndx Must be `realm::npos` if appending. + /// \param value The value to store at the specified row. + /// \param num_rows The number of rows to insert. + void insert_without_updating_index(size_t row_ndx, T value, size_t num_rows); + + void verify() const override; + void to_dot(std::ostream&, StringData title) const override; + void do_dump_node_structure(std::ostream&, int) const override; +#ifdef REALM_DEBUG + using ColumnBase::verify; + void tree_to_dot(std::ostream&) const; + MemStats stats() const; +#endif + + //@{ + /// Returns the array node at the root of this column, but note + /// that there is no guarantee that this node is an inner B+-tree + /// node or a leaf. This is the case for a MixedColumn in + /// particular. + Array* get_root_array() noexcept + { + return &m_tree.root(); + } + const Array* get_root_array() const noexcept + { + return &m_tree.root(); + } + //@} + +protected: + bool root_is_leaf() const noexcept + { + return m_tree.root_is_leaf(); + } + void replace_root_array(std::unique_ptr leaf) final + { + m_tree.replace_root(std::move(leaf)); + } + + void set_without_updating_index(size_t row_ndx, T value); + void erase_without_updating_index(size_t row_ndx, bool is_last); + void move_last_over_without_updating_index(size_t row_ndx, size_t last_row_ndx); + void swap_rows_without_updating_index(size_t row_ndx_1, size_t row_ndx_2); + + /// If any element points to an array node, this function recursively + /// destroys that array node. Note that the same is **not** true for + /// IntegerColumn::do_erase() and IntegerColumn::do_move_last_over(). + /// + /// FIXME: Be careful, clear_without_updating_index() currently forgets + /// if the leaf type is Array::type_HasRefs. + void clear_without_updating_index(); + + void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override; +#ifdef REALM_DEBUG + static void dump_node_structure(const Array& root, std::ostream&, int level); +#endif + std::pair get_to_dot_parent(size_t ndx_in_parent) const; + +private: + class EraseLeafElem; + class CreateHandler; + class SliceHandler; + + friend class Array; + friend class ColumnBase; + friend class StringIndex; + + BpTree m_tree; + + void do_erase(size_t row_ndx, size_t num_rows_to_erase, bool is_last); +}; + +// Implementation: + + +template <> +inline size_t IntNullColumn::get_size_from_ref(ref_type root_ref, Allocator& alloc) +{ + // FIXME: Speed improvement possible by not creating instance, but tricky! This slow method is OK so far + // because it's only invoked by Table::get_size_from_ref() which is only used for subtables which we + // currently 2016) do not expose publicly. + IntNullColumn inc(alloc, root_ref); + return inc.size(); +} + + +inline bool ColumnBase::supports_search_index() const noexcept +{ + REALM_ASSERT(!has_search_index()); + return false; +} + +inline bool ColumnBase::has_search_index() const noexcept +{ + return get_search_index() != nullptr; +} + +inline StringIndex* ColumnBase::create_search_index() +{ + return nullptr; +} + +inline void ColumnBase::destroy_search_index() noexcept +{ +} + +inline const StringIndex* ColumnBase::get_search_index() const noexcept +{ + return nullptr; +} + +inline StringIndex* ColumnBase::get_search_index() noexcept +{ + return nullptr; +} + +inline void ColumnBase::set_search_index_ref(ref_type, ArrayParent*, size_t) +{ +} + +inline void ColumnBase::discard_child_accessors() noexcept +{ + do_discard_child_accessors(); +} + +inline void ColumnBase::discard_subtable_accessor(size_t) noexcept +{ + // Noop +} + +inline void ColumnBase::adj_acc_insert_rows(size_t, size_t) noexcept +{ + // Noop +} + +inline void ColumnBase::adj_acc_erase_row(size_t) noexcept +{ + // Noop +} + +inline void ColumnBase::adj_acc_move_over(size_t, size_t) noexcept +{ + // Noop +} + +inline void ColumnBase::adj_acc_swap_rows(size_t, size_t) noexcept +{ + // Noop +} + +inline void ColumnBase::adj_acc_move_row(size_t, size_t) noexcept +{ + // Noop +} + +inline void ColumnBase::adj_acc_merge_rows(size_t, size_t) noexcept +{ + // Noop +} + +inline void ColumnBase::adj_acc_clear_root_table() noexcept +{ + // Noop +} + +inline void ColumnBase::mark(int) noexcept +{ + // Noop +} + +inline void ColumnBase::bump_link_origin_table_version() noexcept +{ + // Noop +} + +template +int ColumnBase::compare_values(const Column* column, size_t row1, size_t row2) noexcept +{ + // we negate nullability such that the two ternary statements in this method can look identical to reduce + // risk of bugs + bool v1 = !column->is_null(row1); + bool v2 = !column->is_null(row2); + + if (!v1 || !v2) + return v1 == v2 ? 0 : v1 < v2 ? 1 : -1; + + auto a = column->get(row1); + auto b = column->get(row2); + return a == b ? 0 : a < b ? 1 : -1; +} + +template +void Column::set_without_updating_index(size_t ndx, T value) +{ + m_tree.set(ndx, std::move(value)); +} + +template +void Column::set(size_t ndx, T value) +{ + REALM_ASSERT_DEBUG(ndx < size()); + if (has_search_index()) { + m_search_index->set(ndx, value); + } + set_without_updating_index(ndx, std::move(value)); +} + +template +void Column::set_null(size_t ndx) +{ + REALM_ASSERT_DEBUG(ndx < size()); + if (!is_nullable()) { + throw LogicError{LogicError::column_not_nullable}; + } + if (has_search_index()) { + m_search_index->set(ndx, null{}); + } + m_tree.set_null(ndx); +} + +// When a value of a signed type is converted to an unsigned type, the C++ standard guarantees that negative values +// are converted from the native representation to 2's complement, but the opposite conversion is left as undefined. +// realm::util::from_twos_compl() is used here to perform the correct opposite unsigned-to-signed conversion, +// which reduces to a no-op when 2's complement is the native representation of negative values. +template +void Column::set_uint(size_t ndx, uint64_t value) +{ + set(ndx, util::from_twos_compl(value)); +} + +template +void Column::set_as_ref(size_t ndx, ref_type ref) +{ + set(ndx, from_ref(ref)); +} + +template +template +void Column::adjust(size_t ndx, U diff) +{ + REALM_ASSERT_3(ndx, <, size()); + m_tree.adjust(ndx, diff); +} + +template +template +void Column::adjust(U diff) +{ + m_tree.adjust(diff); +} + +template +template +void Column::adjust_ge(T limit, U diff) +{ + m_tree.adjust_ge(limit, diff); +} + +template +size_t Column::count(T target) const +{ + if (has_search_index()) { + return m_search_index->count(target); + } + return to_size_t(aggregate(*this, target, 0, size(), npos, nullptr)); +} + +template +typename ColumnTypeTraits::sum_type Column::sum(size_t start, size_t end, size_t limit, + size_t* return_ndx) const +{ + using sum_type = typename ColumnTypeTraits::sum_type; + if (nullable) + return aggregate(*this, 0, start, end, limit, return_ndx); + else + return aggregate(*this, 0, start, end, limit, return_ndx); +} + +template +double Column::average(size_t start, size_t end, size_t limit, size_t* return_ndx) const +{ + if (end == size_t(-1)) + end = size(); + + auto s = sum(start, end, limit); + size_t cnt = to_size_t(aggregate(*this, 0, start, end, limit, nullptr)); + if (return_ndx) + *return_ndx = cnt; + double avg = double(s) / (cnt == 0 ? 1 : cnt); + return avg; +} + +template +typename ColumnTypeTraits::minmax_type Column::minimum(size_t start, size_t end, size_t limit, + size_t* return_ndx) const +{ + using R = typename ColumnTypeTraits::minmax_type; + return aggregate(*this, 0, start, end, limit, return_ndx); +} + +template +typename ColumnTypeTraits::minmax_type Column::maximum(size_t start, size_t end, size_t limit, + size_t* return_ndx) const +{ + using R = typename ColumnTypeTraits::minmax_type; + return aggregate(*this, 0, start, end, limit, return_ndx); +} + +template +void Column::get_leaf(size_t ndx, size_t& ndx_in_leaf, LeafInfo& inout_leaf_info) const noexcept +{ + m_tree.get_leaf(ndx, ndx_in_leaf, inout_leaf_info); +} + +template +StringData Column::get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept +{ + T x = get(ndx); + return to_str(x, buffer); +} + +template +void Column::populate_search_index() +{ + REALM_ASSERT(has_search_index()); + // Populate the index + size_t num_rows = size(); + for (size_t row_ndx = 0; row_ndx != num_rows; ++row_ndx) { + bool is_append = true; + if (is_null(row_ndx)) { + m_search_index->insert(row_ndx, null{}, 1, is_append); // Throws + } + else { + T value = get(row_ndx); + m_search_index->insert(row_ndx, value, 1, is_append); // Throws + } + } +} + +template +StringIndex* Column::create_search_index() +{ + if (realm::is_any::value) + return nullptr; + + REALM_ASSERT(!has_search_index()); + REALM_ASSERT(supports_search_index()); + m_search_index.reset(new StringIndex(this, get_alloc())); // Throws + populate_search_index(); + return m_search_index.get(); +} + +template +size_t Column::find_first(T value, size_t begin, size_t end) const +{ + REALM_ASSERT_3(begin, <=, size()); + REALM_ASSERT(end == npos || (begin <= end && end <= size())); + + if (m_search_index && begin == 0 && end == npos) + return m_search_index->find_first(value); + return m_tree.find_first(value, begin, end); +} + +template +void Column::find_all(IntegerColumn& result, T value, size_t begin, size_t end) const +{ + REALM_ASSERT_3(begin, <=, size()); + REALM_ASSERT(end == npos || (begin <= end && end <= size())); + + if (m_search_index && begin == 0 && end == npos) + return m_search_index->find_all(result, value); + return m_tree.find_all(result, value, begin, end); +} + +inline size_t ColumnBase::get_size_from_ref(ref_type root_ref, Allocator& alloc) +{ + const char* root_header = alloc.translate(root_ref); + bool root_is_leaf = !Array::get_is_inner_bptree_node_from_header(root_header); + if (root_is_leaf) + return Array::get_size_from_header(root_header); + return BpTreeNode::get_bptree_size_from_header(root_header); +} + +template +size_t ColumnBase::lower_bound(const L& list, T value) const noexcept +{ + size_t i = 0; + size_t list_size = list.size(); + while (0 < list_size) { + size_t half = list_size / 2; + size_t mid = i + half; + typename L::value_type probe = list.get(mid); + if (probe < value) { + i = mid + 1; + list_size -= half + 1; + } + else { + list_size = half; + } + } + return i; +} + +template +size_t ColumnBase::upper_bound(const L& list, T value) const noexcept +{ + size_t i = 0; + size_t list_size = list.size(); + while (0 < list_size) { + size_t half = list_size / 2; + size_t mid = i + half; + typename L::value_type probe = list.get(mid); + if (!(value < probe)) { + i = mid + 1; + list_size -= half + 1; + } + else { + list_size = half; + } + } + return i; +} + + +inline ref_type ColumnBase::create(Allocator& alloc, size_t column_size, CreateHandler& handler) +{ + size_t rest_size = column_size; + size_t fixed_height = 0; // Not fixed + return build(&rest_size, fixed_height, alloc, handler); +} + +template +Column::Column(Allocator& alloc, ref_type ref, size_t column_ndx) + : ColumnBaseWithIndex(column_ndx) + , m_tree(BpTreeBase::unattached_tag{}) +{ + // fixme, must m_search_index be copied here? + m_tree.init_from_ref(alloc, ref); +} + +template +Column::Column(unattached_root_tag, Allocator& alloc) + : ColumnBaseWithIndex(npos) + , m_tree(alloc) +{ +} + +template +Column::Column(std::unique_ptr root) noexcept + : m_tree(std::move(root)) +{ +} + +template +Column::~Column() noexcept +{ +} + +template +void Column::init_from_parent() +{ + m_tree.init_from_parent(); +} + +template +void Column::init_from_ref(Allocator& alloc, ref_type ref) +{ + m_tree.init_from_ref(alloc, ref); +} + +template +void Column::init_from_mem(Allocator& alloc, MemRef mem) +{ + m_tree.init_from_mem(alloc, mem); +} + +template +void Column::destroy() noexcept +{ + ColumnBaseWithIndex::destroy(); + m_tree.destroy(); +} + +template +void Column::move_assign(Column& col) +{ + ColumnBaseWithIndex::move_assign(col); + m_tree = std::move(col.m_tree); +} + +template +Allocator& Column::get_alloc() const noexcept +{ + return m_tree.get_alloc(); +} + +template +void Column::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept +{ + m_tree.set_parent(parent, ndx_in_parent); +} + +template +size_t Column::get_ndx_in_parent() const noexcept +{ + return m_tree.get_ndx_in_parent(); +} + +template +void Column::set_ndx_in_parent(size_t ndx_in_parent) noexcept +{ + ColumnBaseWithIndex::set_ndx_in_parent(ndx_in_parent); + m_tree.set_ndx_in_parent(ndx_in_parent); +} + +template +void Column::detach() noexcept +{ + m_tree.detach(); +} + +template +bool Column::is_attached() const noexcept +{ + return m_tree.is_attached(); +} + +template +ref_type Column::get_ref() const noexcept +{ + return get_root_array()->get_ref(); +} + +template +MemRef Column::get_mem() const noexcept +{ + return get_root_array()->get_mem(); +} + +template +void Column::update_from_parent(size_t old_baseline) noexcept +{ + ColumnBaseWithIndex::update_from_parent(old_baseline); + m_tree.update_from_parent(old_baseline); +} + +template +MemRef Column::clone_deep(Allocator& alloc) const +{ + return m_tree.clone_deep(alloc); +} + +template +size_t Column::size() const noexcept +{ + return m_tree.size(); +} + +template +bool Column::is_nullable() const noexcept +{ + return nullable; +} + +template +T Column::get(size_t ndx) const noexcept +{ + return m_tree.get(ndx); +} + +template +bool Column::is_null(size_t ndx) const noexcept +{ + return nullable && m_tree.is_null(ndx); +} + +template +T Column::back() const noexcept +{ + return m_tree.back(); +} + +template +ref_type Column::get_as_ref(size_t ndx) const noexcept +{ + return to_ref(get(ndx)); +} + +template +uint64_t Column::get_uint(size_t ndx) const noexcept +{ + static_assert(std::is_convertible::value, "T is not convertible to uint."); + return static_cast(get(ndx)); +} + +template +void Column::add(T value) +{ + insert(npos, std::move(value)); +} + +template +void Column::insert_without_updating_index(size_t row_ndx, T value, size_t num_rows) +{ + size_t column_size = this->size(); // Slow + bool is_append = row_ndx == column_size || row_ndx == npos; + size_t ndx_or_npos_if_append = is_append ? npos : row_ndx; + + m_tree.insert(ndx_or_npos_if_append, std::move(value), num_rows); // Throws +} + +template +void Column::insert(size_t row_ndx, T value, size_t num_rows) +{ + size_t column_size = this->size(); // Slow + bool is_append = row_ndx == column_size || row_ndx == npos; + size_t ndx_or_npos_if_append = is_append ? npos : row_ndx; + + m_tree.insert(ndx_or_npos_if_append, value, num_rows); // Throws + + if (has_search_index()) { + row_ndx = is_append ? column_size : row_ndx; + m_search_index->insert(row_ndx, value, num_rows, is_append); // Throws + } +} + +template +void Column::erase_without_updating_index(size_t row_ndx, bool is_last) +{ + m_tree.erase(row_ndx, is_last); +} + +template +void Column::erase(size_t row_ndx) +{ + REALM_ASSERT(size() >= 1); + size_t last_row_ndx = size() - 1; // Note that size() is slow + bool is_last = (row_ndx == last_row_ndx); + erase(row_ndx, is_last); // Throws +} + +template +void Column::erase(size_t row_ndx, bool is_last) +{ + size_t num_rows_to_erase = 1; + do_erase(row_ndx, num_rows_to_erase, is_last); // Throws +} + +template +void Column::move_last_over_without_updating_index(size_t row_ndx, size_t last_row_ndx) +{ + m_tree.move_last_over(row_ndx, last_row_ndx); +} + +template +void Column::move_last_over(size_t row_ndx, size_t last_row_ndx) +{ + REALM_ASSERT_3(row_ndx, <=, last_row_ndx); + REALM_ASSERT_DEBUG(last_row_ndx + 1 == size()); + + if (has_search_index()) { + // remove the value to be overwritten from index + bool is_last = true; // This tells StringIndex::erase() to not adjust subsequent indexes + m_search_index->erase(row_ndx, is_last); // Throws + + // update index to point to new location + if (row_ndx != last_row_ndx) { + T moved_value = get(last_row_ndx); + m_search_index->update_ref(moved_value, last_row_ndx, row_ndx); // Throws + } + } + + move_last_over_without_updating_index(row_ndx, last_row_ndx); +} + +template +void Column::swap_rows(size_t row_ndx_1, size_t row_ndx_2) +{ + REALM_ASSERT_3(row_ndx_1, <, size()); + REALM_ASSERT_3(row_ndx_2, <, size()); + REALM_ASSERT_DEBUG(row_ndx_1 != row_ndx_2); + + if (has_search_index()) { + T value_1 = get(row_ndx_1); + T value_2 = get(row_ndx_2); + size_t column_size = this->size(); + bool row_ndx_1_is_last = row_ndx_1 == column_size - 1; + bool row_ndx_2_is_last = row_ndx_2 == column_size - 1; + m_search_index->erase(row_ndx_1, row_ndx_1_is_last); + m_search_index->insert(row_ndx_1, value_2, 1, row_ndx_1_is_last); + + m_search_index->erase(row_ndx_2, row_ndx_2_is_last); + m_search_index->insert(row_ndx_2, value_1, 1, row_ndx_2_is_last); + } + + swap_rows_without_updating_index(row_ndx_1, row_ndx_2); +} + +template +void Column::swap_rows_without_updating_index(size_t row_ndx_1, size_t row_ndx_2) +{ + // FIXME: This can be optimized with direct getters and setters. + T value_1 = get(row_ndx_1); + T value_2 = get(row_ndx_2); + m_tree.set(row_ndx_1, value_2); + m_tree.set(row_ndx_2, value_1); +} + +template +void Column::clear_without_updating_index() +{ + m_tree.clear(); // Throws +} + +template +void Column::clear() +{ + if (has_search_index()) { + m_search_index->clear(); + } + clear_without_updating_index(); +} + +template +struct NullOrDefaultValue; +template +struct NullOrDefaultValue::value>::type> { + static T null_or_default_value(bool is_null) + { + if (is_null) { + return null::get_null_float(); + } + else { + return T{}; + } + } +}; +template +struct NullOrDefaultValue, void> { + static util::Optional null_or_default_value(bool is_null) + { + if (is_null) { + return util::none; + } + else { + return util::some(T{}); + } + } +}; +template +struct NullOrDefaultValue::value>::type> { + static T null_or_default_value(bool is_null) + { + REALM_ASSERT(!is_null); + return T{}; + } +}; + +// Implementing pure virtual method of ColumnBase. +template +void Column::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool insert_nulls) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx <= prior_num_rows); + + size_t row_ndx_2 = (row_ndx == prior_num_rows ? realm::npos : row_ndx); + T value = NullOrDefaultValue::null_or_default_value(insert_nulls); + insert(row_ndx_2, value, num_rows_to_insert); // Throws +} + +// Implementing pure virtual method of ColumnBase. +template +void Column::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(num_rows_to_erase <= prior_num_rows); + REALM_ASSERT(row_ndx <= prior_num_rows - num_rows_to_erase); + + bool is_last = (row_ndx + num_rows_to_erase == prior_num_rows); + do_erase(row_ndx, num_rows_to_erase, is_last); // Throws +} + +// Implementing pure virtual method of ColumnBase. +template +void Column::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx < prior_num_rows); + + size_t last_row_ndx = prior_num_rows - 1; + move_last_over(row_ndx, last_row_ndx); // Throws +} + +// Implementing pure virtual method of ColumnBase. +template +void Column::clear(size_t, bool) +{ + clear(); // Throws +} + + +template +size_t Column::lower_bound(T value) const noexcept +{ + if (root_is_leaf()) { + auto root = static_cast(get_root_array()); + return root->lower_bound(value); + } + return ColumnBase::lower_bound(*this, value); +} + +template +size_t Column::upper_bound(T value) const noexcept +{ + if (root_is_leaf()) { + auto root = static_cast(get_root_array()); + return root->upper_bound(value); + } + return ColumnBase::upper_bound(*this, value); +} + +// For a *sorted* Column, return first element E for which E >= target or return -1 if none +template +size_t Column::find_gte(T target, size_t start) const +{ + // fixme: slow reference implementation. See Array::find_gte for faster version + size_t ref = 0; + size_t idx; + for (idx = start; idx < size(); ++idx) { + if (get(idx) >= target) { + ref = idx; + break; + } + } + if (idx == size()) + ref = not_found; + + return ref; +} + + +template +bool Column::compare(const Column& c) const noexcept +{ + size_t n = size(); + if (c.size() != n) + return false; + for (size_t i = 0; i < n; ++i) { + bool left_is_null = is_null(i); + bool right_is_null = c.is_null(i); + if (left_is_null != right_is_null) { + return false; + } + if (!left_is_null) { + if (get(i) != c.get(i)) + return false; + } + } + return true; +} + +template +int Column::compare_values(size_t row1, size_t row2) const noexcept +{ + return ColumnBase::compare_values(this, row1, row2); +} + +template +class Column::CreateHandler : public ColumnBase::CreateHandler { +public: + CreateHandler(Array::Type leaf_type, T value, Allocator& alloc) + : m_value(value) + , m_alloc(alloc) + , m_leaf_type(leaf_type) + { + } + ref_type create_leaf(size_t size) override + { + MemRef mem = BpTree::create_leaf(m_leaf_type, size, m_value, m_alloc); // Throws + return mem.get_ref(); + } + +private: + const T m_value; + Allocator& m_alloc; + Array::Type m_leaf_type; +}; + +template +ref_type Column::create(Allocator& alloc, Array::Type leaf_type, size_t size, T value) +{ + CreateHandler handler(leaf_type, std::move(value), alloc); + return ColumnBase::create(alloc, size, handler); +} + +template +ref_type Column::write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream& out) const +{ + return m_tree.write(slice_offset, slice_size, table_size, out); +} + +template +void Column::refresh_accessor_tree(size_t new_col_ndx, const Spec& spec) +{ + m_tree.init_from_parent(); + ColumnBaseWithIndex::refresh_accessor_tree(new_col_ndx, spec); +} + +template +void Column::do_erase(size_t row_ndx, size_t num_rows_to_erase, bool is_last) +{ + if (has_search_index()) { + for (size_t i = num_rows_to_erase; i > 0; --i) { + size_t row_ndx_2 = row_ndx + i - 1; + m_search_index->erase(row_ndx_2, is_last); // Throws + } + } + for (size_t i = num_rows_to_erase; i > 0; --i) { + size_t row_ndx_2 = row_ndx + i - 1; + erase_without_updating_index(row_ndx_2, is_last); // Throws + } +} + +template +void Column::verify() const +{ +#ifdef REALM_DEBUG + m_tree.verify(); +#endif +} + +// LCOV_EXCL_START + +template +void Column::to_dot(std::ostream& out, StringData title) const +{ +#ifdef REALM_DEBUG + ref_type ref = get_root_array()->get_ref(); + out << "subgraph cluster_integer_column" << ref << " {" << std::endl; + out << " label = \"Integer column"; + if (title.size() != 0) + out << "\\n'" << title << "'"; + out << "\";" << std::endl; + tree_to_dot(out); + out << "}" << std::endl; +#else + static_cast(out); + static_cast(title); +#endif +} + +template +void Column::leaf_to_dot(MemRef leaf_mem, ArrayParent* parent, size_t ndx_in_parent, std::ostream& out) const +{ +#ifdef REALM_DEBUG + BpTree::leaf_to_dot(leaf_mem, parent, ndx_in_parent, out, get_alloc()); +#else + static_cast(leaf_mem); + static_cast(parent); + static_cast(ndx_in_parent); + static_cast(out); +#endif +} + +template +void Column::do_dump_node_structure(std::ostream& out, int level) const +{ +#ifdef REALM_DEBUG + dump_node_structure(*get_root_array(), out, level); +#else + static_cast(out); + static_cast(level); +#endif +} + +#ifdef REALM_DEBUG + +template +void Column::tree_to_dot(std::ostream& out) const +{ + ColumnBase::bptree_to_dot(get_root_array(), out); +} + + +template +MemStats Column::stats() const +{ + MemStats mem_stats; + get_root_array()->stats(mem_stats); + return mem_stats; +} + +namespace _impl { +void leaf_dumper(MemRef mem, Allocator& alloc, std::ostream& out, int level); +} + +template +void Column::dump_node_structure(const Array& root, std::ostream& out, int level) +{ + root.dump_bptree_structure(out, level, &_impl::leaf_dumper); +} + +#endif + +template +std::pair Column::get_to_dot_parent(size_t ndx_in_parent) const +{ + auto root = get_root_array(); + if (root->is_inner_bptree_node()) { + std::pair p = static_cast(root)->get_bptree_leaf(ndx_in_parent); + return std::make_pair(p.first.get_ref(), p.second); + } + else { + return std::make_pair(root->get_ref(), ndx_in_parent); + } +} + +// LCOV_EXCL_STOP ignore debug functions + + +template +ColumnRandIterator::ColumnRandIterator(const Column* src_col, size_t ndx) + : m_col_ndx(ndx) + , m_col(src_col) +{ +} + +template +bool ColumnRandIterator::operator==(const ColumnRandIterator& rhs) const +{ + return (m_col_ndx == rhs.m_col_ndx); +} + +template +bool ColumnRandIterator::operator!=(const ColumnRandIterator& rhs) const +{ + return !(*this == rhs); +} + +template +bool ColumnRandIterator::operator<(const ColumnRandIterator& rhs) const +{ + return m_col_ndx < rhs.m_col_ndx; +} + +template +bool ColumnRandIterator::operator>(const ColumnRandIterator& rhs) const +{ + return rhs < *this; +} + +template +bool ColumnRandIterator::operator<=(const ColumnRandIterator& rhs) const +{ + return !(rhs < *this); +} + +template +bool ColumnRandIterator::operator>=(const ColumnRandIterator& rhs) const +{ + return !(*this < rhs); +} + +template +ColumnRandIterator& ColumnRandIterator::operator+=(ptrdiff_t movement) +{ + m_col_ndx += movement; + return (*this); +} + +template +ColumnRandIterator& ColumnRandIterator::operator-=(ptrdiff_t movement) +{ + m_col_ndx -= movement; + return (*this); +} + +template +ColumnRandIterator& ColumnRandIterator::operator++() +{ + ++m_col_ndx; + return (*this); +} + +template +ColumnRandIterator& ColumnRandIterator::operator--() +{ + --m_col_ndx; + return (*this); +} + +template +ColumnRandIterator ColumnRandIterator::operator++(int) +{ + auto temp(*this); + ++m_col_ndx; + return temp; +} + +template +ColumnRandIterator ColumnRandIterator::operator--(int) +{ + auto temp(*this); + --m_col_ndx; + return temp; +} + +template +ColumnRandIterator ColumnRandIterator::operator+(ptrdiff_t movement) +{ + return ColumnRandIterator(m_col, m_col_ndx + movement); +} + +template +ColumnRandIterator ColumnRandIterator::operator-(ptrdiff_t movement) +{ + return ColumnRandIterator(m_col, m_col_ndx - movement); +} + +template +ptrdiff_t ColumnRandIterator::operator-(const ColumnRandIterator& right) const +{ + return m_col_ndx - right.m_col_ndx; +} + +template +const ColumnDataType ColumnRandIterator::operator*() const +{ + return m_col->get(m_col_ndx); +} + +template +const ColumnDataType ColumnRandIterator::operator->() const +{ + return m_col->get(m_col_ndx); +} + +template +const ColumnDataType ColumnRandIterator::operator[](ptrdiff_t offset) const +{ + return m_col->get(m_col_ndx + offset); +} + +template +size_t ColumnRandIterator::get_col_ndx() const +{ + return m_col_ndx; +} + +template +std::ostream& operator<<(std::ostream& out, const ColumnRandIterator& it) +{ + out << "ColumnRandIterator at index: " << it.get_col_ndx(); + return out; +} + +} // namespace realm + +#endif // REALM_COLUMN_HPP diff --git a/Pods/Realm/include/core/realm/column_backlink.hpp b/Pods/Realm/include/core/realm/column_backlink.hpp new file mode 100644 index 0000000000..cbbe9e6c41 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_backlink.hpp @@ -0,0 +1,246 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_BACKLINK_HPP +#define REALM_COLUMN_BACKLINK_HPP + +#include + +#include +#include +#include + +namespace realm { + +/// A column of backlinks (BacklinkColumn) is a single B+-tree, and the root of +/// the column is the root of the B+-tree. All leaf nodes are single arrays of +/// type Array with the hasRefs bit set. +/// +/// The individual values in the column are either refs to Columns containing +/// the row indexes in the origin table that links to it, or in the case where +/// there is a single link, a tagged ref encoding the origin row position. +class BacklinkColumn : public IntegerColumn, public ArrayParent { +public: + BacklinkColumn(Allocator&, ref_type, size_t col_ndx = npos); + ~BacklinkColumn() noexcept override + { + } + + static ref_type create(Allocator&, size_t size = 0); + + bool has_backlinks(size_t row_ndx) const noexcept; + size_t get_backlink_count(size_t row_ndx) const noexcept; + size_t get_backlink(size_t row_ndx, size_t backlink_ndx) const noexcept; + + void add_backlink(size_t row_ndx, size_t origin_row_ndx); + void remove_one_backlink(size_t row_ndx, size_t origin_row_ndx); + void remove_all_backlinks(size_t num_rows); + void update_backlink(size_t row_ndx, size_t old_origin_row_ndx, size_t new_origin_row_ndx); + void swap_backlinks(size_t row_ndx, size_t origin_row_ndx_1, size_t origin_row_ndx_2); + + void add_row(); + + // Link origination info + Table& get_origin_table() const noexcept; + void set_origin_table(Table&) noexcept; + LinkColumnBase& get_origin_column() const noexcept; + size_t get_origin_column_index() const noexcept; + void set_origin_column(LinkColumnBase& column) noexcept; + + void insert_rows(size_t, size_t, size_t, bool) override; + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + void swap_rows(size_t, size_t) override; + void clear(size_t, bool) override; + void adj_acc_insert_rows(size_t, size_t) noexcept override; + void adj_acc_erase_row(size_t) noexcept override; + void adj_acc_move_over(size_t, size_t) noexcept override; + void adj_acc_swap_rows(size_t, size_t) noexcept override; + void adj_acc_move_row(size_t, size_t) noexcept override; + void adj_acc_merge_rows(size_t, size_t) noexcept override; + void adj_acc_clear_root_table() noexcept override; + void mark(int) noexcept override; + + void bump_link_origin_table_version() noexcept override; + + void cascade_break_backlinks_to(size_t row_ndx, CascadeState& state) override; + void cascade_break_backlinks_to_all_rows(size_t num_rows, CascadeState&) override; + + int compare_values(size_t, size_t) const noexcept override; + + void verify() const override; + void verify(const Table&, size_t) const override; +#ifdef REALM_DEBUG + struct VerifyPair { + size_t origin_row_ndx, target_row_ndx; + bool operator<(const VerifyPair&) const noexcept; + }; + void get_backlinks(std::vector&); // Sorts +#endif + +protected: + // ArrayParent overrides + void update_child_ref(size_t child_ndx, ref_type new_ref) override; + ref_type get_child_ref(size_t child_ndx) const noexcept override; + + std::pair get_to_dot_parent(size_t) const override; + +private: + TableRef m_origin_table; + LinkColumnBase* m_origin_column = nullptr; + + template + size_t for_each_link(size_t row_ndx, bool do_destroy, Func&& f); +}; + + +// Implementation + +inline BacklinkColumn::BacklinkColumn(Allocator& alloc, ref_type ref, size_t col_ndx) + : IntegerColumn(alloc, ref, col_ndx) // Throws +{ +} + +inline ref_type BacklinkColumn::create(Allocator& alloc, size_t size) +{ + return IntegerColumn::create(alloc, Array::type_HasRefs, size); // Throws +} + +inline bool BacklinkColumn::has_backlinks(size_t ndx) const noexcept +{ + return IntegerColumn::get(ndx) != 0; +} + +inline Table& BacklinkColumn::get_origin_table() const noexcept +{ + return *m_origin_table; +} + +inline void BacklinkColumn::set_origin_table(Table& table) noexcept +{ + REALM_ASSERT(!m_origin_table); + m_origin_table = table.get_table_ref(); +} + +inline LinkColumnBase& BacklinkColumn::get_origin_column() const noexcept +{ + return *m_origin_column; +} + +inline size_t BacklinkColumn::get_origin_column_index() const noexcept +{ + return m_origin_column ? m_origin_column->get_column_index() : npos; +} + +inline void BacklinkColumn::set_origin_column(LinkColumnBase& column) noexcept +{ + m_origin_column = &column; +} + +inline void BacklinkColumn::add_row() +{ + IntegerColumn::add(0); +} + +inline void BacklinkColumn::adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept +{ + IntegerColumn::adj_acc_insert_rows(row_ndx, num_rows); + + typedef _impl::TableFriend tf; + tf::mark(*m_origin_table); +} + +inline void BacklinkColumn::adj_acc_erase_row(size_t row_ndx) noexcept +{ + IntegerColumn::adj_acc_erase_row(row_ndx); + + typedef _impl::TableFriend tf; + tf::mark(*m_origin_table); +} + +inline void BacklinkColumn::adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept +{ + IntegerColumn::adj_acc_move_over(from_row_ndx, to_row_ndx); + + typedef _impl::TableFriend tf; + tf::mark(*m_origin_table); +} + +inline void BacklinkColumn::adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept +{ + Column::adj_acc_swap_rows(row_ndx_1, row_ndx_2); + + using tf = _impl::TableFriend; + tf::mark(*m_origin_table); +} + +inline void BacklinkColumn::adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept +{ + Column::adj_acc_move_row(from_ndx, to_ndx); + + using tf = _impl::TableFriend; + tf::mark(*m_origin_table); +} + +inline void BacklinkColumn::adj_acc_merge_rows(size_t old_row_ndx, size_t new_row_ndx) noexcept +{ + Column::adj_acc_merge_rows(old_row_ndx, new_row_ndx); + + using tf = _impl::TableFriend; + tf::mark(*m_origin_table); +} + +inline void BacklinkColumn::adj_acc_clear_root_table() noexcept +{ + IntegerColumn::adj_acc_clear_root_table(); + + typedef _impl::TableFriend tf; + tf::mark(*m_origin_table); +} + +inline void BacklinkColumn::mark(int type) noexcept +{ + if (type & mark_LinkOrigins) { + typedef _impl::TableFriend tf; + tf::mark(*m_origin_table); + } +} + +inline void BacklinkColumn::bump_link_origin_table_version() noexcept +{ + // It is important to mark connected tables as modified. + // Also see LinkColumnBase::bump_link_origin_table_version(). + typedef _impl::TableFriend tf; + if (m_origin_table) { + bool bump_global = false; + tf::bump_version(*m_origin_table, bump_global); + } +} + +#ifdef REALM_DEBUG + +inline bool BacklinkColumn::VerifyPair::operator<(const VerifyPair& p) const noexcept +{ + return origin_row_ndx < p.origin_row_ndx; +} + +#endif // REALM_DEBUG + +} // namespace realm + +#endif // REALM_COLUMN_BACKLINK_HPP diff --git a/Pods/Realm/include/core/realm/column_binary.hpp b/Pods/Realm/include/core/realm/column_binary.hpp new file mode 100644 index 0000000000..7802e03a1c --- /dev/null +++ b/Pods/Realm/include/core/realm/column_binary.hpp @@ -0,0 +1,429 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_BINARY_HPP +#define REALM_COLUMN_BINARY_HPP + +#include +#include +#include + +namespace realm { + + +/// A binary column (BinaryColumn) is a single B+-tree, and the root +/// of the column is the root of the B+-tree. Leaf nodes are either of +/// type ArrayBinary (array of small blobs) or ArrayBigBlobs (array of +/// big blobs). +class BinaryColumn : public ColumnBaseSimple { +public: + typedef BinaryData value_type; + + BinaryColumn(Allocator&, ref_type, bool nullable = false, size_t column_ndx = npos); + + size_t size() const noexcept final; + bool is_empty() const noexcept + { + return size() == 0; + } + bool is_nullable() const noexcept override; + + BinaryData get(size_t ndx) const noexcept; + + /// Return data from position 'pos' and onwards. If the blob is distributed + /// across multiple arrays (if bigger than ~ 16M), you will only get data + /// from one array. 'pos' will be updated to be an index to next available + /// data. It will be 0 if no more data. + BinaryData get_at(size_t ndx, size_t& pos) const noexcept; + + bool is_null(size_t ndx) const noexcept override; + StringData get_index_data(size_t, StringIndex::StringConversionBuffer&) const noexcept final; + + void add(BinaryData value); + void set(size_t ndx, BinaryData value, bool add_zero_term = false); + void set_null(size_t ndx) override; + void insert(size_t ndx, BinaryData value); + void erase(size_t row_ndx); + void erase(size_t row_ndx, bool is_last); + void move_last_over(size_t row_ndx); + void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override; + void clear(); + size_t find_first(BinaryData value) const; + + // Requires that the specified entry was inserted as StringData. + StringData get_string(size_t ndx) const noexcept; + + void add_string(StringData value); + void set_string(size_t ndx, StringData value) override; + void insert_string(size_t ndx, StringData value); + + /// Compare two binary columns for equality. + bool compare_binary(const BinaryColumn&) const; + + int compare_values(size_t row1, size_t row2) const noexcept override; + + static ref_type create(Allocator&, size_t size, bool nullable); + + static size_t get_size_from_ref(ref_type root_ref, Allocator&) noexcept; + + // Overrriding method in ColumnBase + ref_type write(size_t, size_t, size_t, _impl::OutputStream&) const override; + + void insert_rows(size_t, size_t, size_t, bool) override; + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + void clear(size_t, bool) override; + void update_from_parent(size_t) noexcept override; + void refresh_accessor_tree(size_t, const Spec&) override; + + /// In contrast to update_from_parent(), this function is able to handle + /// cases where the accessed payload data has changed. In particular, it + /// handles cases where the B+-tree switches from having one level (root is + /// a leaf node), to having multiple levels (root is an inner node). Note + /// that this is at the expense of loosing the `noexcept` guarantee. + void update_from_ref(ref_type ref); + + void verify() const override; + void to_dot(std::ostream&, StringData title) const override; + void do_dump_node_structure(std::ostream&, int) const override; + +private: + /// \param row_ndx Must be `realm::npos` if appending. + void do_insert(size_t row_ndx, BinaryData value, bool add_zero_term, size_t num_rows); + + // Called by Array::bptree_insert(). + static ref_type leaf_insert(MemRef leaf_mem, ArrayParent&, size_t ndx_in_parent, Allocator&, size_t insert_ndx, + BpTreeNode::TreeInsert& state); + + struct InsertState : BpTreeNode::TreeInsert { + bool m_add_zero_term; + }; + + class EraseLeafElem; + class CreateHandler; + class SliceHandler; + + void do_move_last_over(size_t row_ndx, size_t last_row_ndx); + void do_clear(); + + /// Root must be a leaf. Upgrades the root leaf if + /// necessary. Returns true if, and only if the root is a 'big + /// blobs' leaf upon return. + bool upgrade_root_leaf(size_t value_size); + + bool m_nullable = false; + + void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override; + + friend class BpTreeNode; + friend class ColumnBase; +}; + +class BinaryIterator { +public: + BinaryIterator() + { + } + // TODO: When WriteLogCollector is removed, there is no need for this + BinaryIterator(BinaryData binary) + : m_binary(binary) + { + } + + BinaryIterator(const BinaryColumn* col, size_t ndx) + : m_binary_col(col) + , m_ndx(ndx) + { + } + + BinaryData get_next() noexcept + { + if (!end_of_data) { + if (m_binary_col) { + BinaryData ret = m_binary_col->get_at(m_ndx, m_pos); + end_of_data = (m_pos == 0); + return ret; + } + else if (!m_binary.is_null()) { + end_of_data = true; + return m_binary; + } + } + return {}; + } + +private: + bool end_of_data = false; + const BinaryColumn* m_binary_col = nullptr; + size_t m_ndx = 0; + size_t m_pos = 0; + BinaryData m_binary; +}; + + +// Implementation + +// LCOV_EXCL_START +inline StringData BinaryColumn::get_index_data(size_t, StringIndex::StringConversionBuffer&) const noexcept +{ + REALM_ASSERT(false && "Index not implemented for BinaryColumn."); + REALM_UNREACHABLE(); +} +// LCOV_EXCL_STOP + +inline size_t BinaryColumn::size() const noexcept +{ + if (root_is_leaf()) { + bool is_big = m_array->get_context_flag(); + if (!is_big) { + // Small blobs root leaf + ArrayBinary* leaf = static_cast(m_array.get()); + return leaf->size(); + } + // Big blobs root leaf + ArrayBigBlobs* leaf = static_cast(m_array.get()); + return leaf->size(); + } + // Non-leaf root + return static_cast(m_array.get())->get_bptree_size(); +} + +inline bool BinaryColumn::is_nullable() const noexcept +{ + return m_nullable; +} + +inline void BinaryColumn::update_from_parent(size_t old_baseline) noexcept +{ + if (root_is_leaf()) { + bool is_big = m_array->get_context_flag(); + if (!is_big) { + // Small blobs root leaf + REALM_ASSERT(dynamic_cast(m_array.get())); + ArrayBinary* leaf = static_cast(m_array.get()); + leaf->update_from_parent(old_baseline); + return; + } + // Big blobs root leaf + REALM_ASSERT(dynamic_cast(m_array.get())); + ArrayBigBlobs* leaf = static_cast(m_array.get()); + leaf->update_from_parent(old_baseline); + return; + } + // Non-leaf root + m_array->update_from_parent(old_baseline); +} + +inline BinaryData BinaryColumn::get(size_t ndx) const noexcept +{ + REALM_ASSERT_DEBUG(ndx < size()); + if (root_is_leaf()) { + bool is_big = m_array->get_context_flag(); + BinaryData ret; + if (!is_big) { + // Small blobs root leaf + ArrayBinary* leaf = static_cast(m_array.get()); + ret = leaf->get(ndx); + } + else { + // Big blobs root leaf + ArrayBigBlobs* leaf = static_cast(m_array.get()); + ret = leaf->get(ndx); + } + if (!m_nullable && ret.is_null()) + return BinaryData("", 0); // return empty string (non-null) + return ret; + } + + // Non-leaf root + std::pair p = static_cast(m_array.get())->get_bptree_leaf(ndx); + const char* leaf_header = p.first.get_addr(); + size_t ndx_in_leaf = p.second; + Allocator& alloc = m_array->get_alloc(); + bool is_big = Array::get_context_flag_from_header(leaf_header); + if (!is_big) { + // Small blobs + return ArrayBinary::get(leaf_header, ndx_in_leaf, alloc); + } + // Big blobs + return ArrayBigBlobs::get(leaf_header, ndx_in_leaf, alloc); +} + +inline bool BinaryColumn::is_null(size_t ndx) const noexcept +{ + return m_nullable && get(ndx).is_null(); +} + +inline StringData BinaryColumn::get_string(size_t ndx) const noexcept +{ + BinaryData bin = get(ndx); + REALM_ASSERT_3(0, <, bin.size()); + return StringData(bin.data(), bin.size() - 1); +} + +inline void BinaryColumn::set_string(size_t ndx, StringData value) +{ + if (value.is_null() && !m_nullable) + throw LogicError(LogicError::column_not_nullable); + + BinaryData bin(value.data(), value.size()); + bool add_zero_term = true; + set(ndx, bin, add_zero_term); +} + +inline void BinaryColumn::add(BinaryData value) +{ + if (value.is_null() && !m_nullable) + throw LogicError(LogicError::column_not_nullable); + + size_t row_ndx = realm::npos; + bool add_zero_term = false; + size_t num_rows = 1; + do_insert(row_ndx, value, add_zero_term, num_rows); // Throws +} + +inline void BinaryColumn::insert(size_t row_ndx, BinaryData value) +{ + if (value.is_null() && !m_nullable) + throw LogicError(LogicError::column_not_nullable); + + size_t column_size = this->size(); // Slow + REALM_ASSERT_3(row_ndx, <=, column_size); + size_t row_ndx_2 = row_ndx == column_size ? realm::npos : row_ndx; + bool add_zero_term = false; + size_t num_rows = 1; + do_insert(row_ndx_2, value, add_zero_term, num_rows); // Throws +} + +inline void BinaryColumn::set_null(size_t row_ndx) +{ + set(row_ndx, BinaryData{}); +} + +inline size_t BinaryColumn::find_first(BinaryData value) const +{ + for (size_t t = 0; t < size(); t++) + if (get(t) == value) + return t; + + return not_found; +} + + +inline void BinaryColumn::erase(size_t row_ndx) +{ + size_t last_row_ndx = size() - 1; // Note that size() is slow + bool is_last = row_ndx == last_row_ndx; + erase(row_ndx, is_last); // Throws +} + +inline void BinaryColumn::move_last_over(size_t row_ndx) +{ + size_t last_row_ndx = size() - 1; // Note that size() is slow + do_move_last_over(row_ndx, last_row_ndx); // Throws +} + +inline void BinaryColumn::clear() +{ + do_clear(); // Throws +} + +// Implementing pure virtual method of ColumnBase. +inline void BinaryColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, + bool insert_nulls) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx <= prior_num_rows); + REALM_ASSERT(!insert_nulls || m_nullable); + + size_t row_ndx_2 = (row_ndx == prior_num_rows ? realm::npos : row_ndx); + BinaryData value = m_nullable ? BinaryData() : BinaryData("", 0); + bool add_zero_term = false; + do_insert(row_ndx_2, value, add_zero_term, num_rows_to_insert); // Throws +} + +// Implementing pure virtual method of ColumnBase. +inline void BinaryColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(num_rows_to_erase <= prior_num_rows); + REALM_ASSERT(row_ndx <= prior_num_rows - num_rows_to_erase); + + bool is_last = (row_ndx + num_rows_to_erase == prior_num_rows); + for (size_t i = num_rows_to_erase; i > 0; --i) { + size_t row_ndx_2 = row_ndx + i - 1; + erase(row_ndx_2, is_last); // Throws + } +} + +// Implementing pure virtual method of ColumnBase. +inline void BinaryColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx < prior_num_rows); + + size_t last_row_ndx = prior_num_rows - 1; + do_move_last_over(row_ndx, last_row_ndx); // Throws +} + +// Implementing pure virtual method of ColumnBase. +inline void BinaryColumn::clear(size_t, bool) +{ + do_clear(); // Throws +} + +inline void BinaryColumn::add_string(StringData value) +{ + size_t row_ndx = realm::npos; + BinaryData value_2(value.data(), value.size()); + bool add_zero_term = true; + size_t num_rows = 1; + do_insert(row_ndx, value_2, add_zero_term, num_rows); // Throws +} + +inline void BinaryColumn::insert_string(size_t row_ndx, StringData value) +{ + size_t column_size = this->size(); // Slow + REALM_ASSERT_3(row_ndx, <=, column_size); + size_t row_ndx_2 = row_ndx == column_size ? realm::npos : row_ndx; + BinaryData value_2(value.data(), value.size()); + bool add_zero_term = false; + size_t num_rows = 1; + do_insert(row_ndx_2, value_2, add_zero_term, num_rows); // Throws +} + +inline size_t BinaryColumn::get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept +{ + const char* root_header = alloc.translate(root_ref); + bool root_is_leaf = !Array::get_is_inner_bptree_node_from_header(root_header); + if (root_is_leaf) { + bool is_big = Array::get_context_flag_from_header(root_header); + if (!is_big) { + // Small blobs leaf + return ArrayBinary::get_size_from_header(root_header, alloc); + } + // Big blobs leaf + return ArrayBigBlobs::get_size_from_header(root_header); + } + return BpTreeNode::get_bptree_size_from_header(root_header); +} + + +} // namespace realm + +#endif // REALM_COLUMN_BINARY_HPP diff --git a/Pods/Realm/include/core/realm/column_fwd.hpp b/Pods/Realm/include/core/realm/column_fwd.hpp new file mode 100644 index 0000000000..5b93cdcf47 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_fwd.hpp @@ -0,0 +1,58 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_FWD_HPP +#define REALM_COLUMN_FWD_HPP + +#include + +namespace realm { + +// Regular classes +class ColumnBase; +class StringColumn; +class StringEnumColumn; +class BinaryColumn; +class SubtableColumn; +class MixedColumn; +class LinkColumn; +class LinkListColumn; +class TimestampColumn; + +// Templated classes +template +class Column; +template +class BasicColumn; +template +class ColumnRandIterator; + +namespace util { +template +class Optional; +} + +// Shortcuts, aka typedefs. +using IntegerColumn = Column; +using IntNullColumn = Column>; +using DoubleColumn = Column; +using FloatColumn = Column; +using IntegerColumnIterator = ColumnRandIterator; +} // namespace realm + +#endif // REALM_COLUMN_FWD_HPP diff --git a/Pods/Realm/include/core/realm/column_link.hpp b/Pods/Realm/include/core/realm/column_link.hpp new file mode 100644 index 0000000000..185a6c3ebc --- /dev/null +++ b/Pods/Realm/include/core/realm/column_link.hpp @@ -0,0 +1,181 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_LINK_HPP +#define REALM_COLUMN_LINK_HPP + +#include +#include +#include + +namespace realm { + +/// A link column is an extension of an integer column (Column) and maintains +/// its node structure. +/// +/// The individual values in a link column are indexes of rows in the target +/// table (offset with one to allow zero to indicate null links.) The target +/// table is specified by the table descriptor. +class LinkColumn : public LinkColumnBase { +public: + using LinkColumnBase::LinkColumnBase; + ~LinkColumn() noexcept override; + + static ref_type create(Allocator&, size_t size = 0); + + bool is_nullable() const noexcept override; + + //@{ + + /// is_null_link() is shorthand for `get_link() == realm::npos`, + /// nullify_link() is shorthand foe `set_link(realm::npos)`, and + /// insert_null_link() is shorthand for + /// `insert_link(realm::npos)`. set_link() returns the original link, with + /// `realm::npos` indicating that it was null. + + size_t get_link(size_t row_ndx) const noexcept; + bool is_null(size_t row_ndx) const noexcept override; + bool is_null_link(size_t row_ndx) const noexcept; + size_t set_link(size_t row_ndx, size_t target_row_ndx); + void set_null(size_t row_ndx) override; + void nullify_link(size_t row_ndx); + void insert_link(size_t row_ndx, size_t target_row_ndx); + void insert_null_link(size_t row_ndx); + + //@} + + void insert_rows(size_t, size_t, size_t, bool) override; + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + void swap_rows(size_t, size_t) override; + void clear(size_t, bool) override; + void cascade_break_backlinks_to(size_t, CascadeState&) override; + void cascade_break_backlinks_to_all_rows(size_t, CascadeState&) override; + + void verify(const Table&, size_t) const override; + +protected: + friend class BacklinkColumn; + void do_nullify_link(size_t row_ndx, size_t old_target_row_ndx) override; + void do_update_link(size_t row_ndx, size_t old_target_row_ndx, size_t new_target_row_ndx) override; + void do_swap_link(size_t row_ndx, size_t target_row_ndx_1, size_t target_row_ndx_2) override; + +private: + void remove_backlinks(size_t row_ndx); +}; + + +// Implementation + +inline LinkColumn::~LinkColumn() noexcept +{ +} + +inline bool LinkColumn::is_nullable() const noexcept +{ + return true; +} + +inline ref_type LinkColumn::create(Allocator& alloc, size_t size) +{ + return IntegerColumn::create(alloc, Array::type_Normal, size); // Throws +} + +inline bool LinkColumn::is_null(size_t row_ndx) const noexcept +{ + // Null is represented by zero + return LinkColumnBase::get(row_ndx) == 0; +} + +inline size_t LinkColumn::get_link(size_t row_ndx) const noexcept +{ + // Map zero to realm::npos, and `n+1` to `n`, where `n` is a target row index. + return to_size_t(LinkColumnBase::get(row_ndx)) - size_t(1); +} + +inline bool LinkColumn::is_null_link(size_t row_ndx) const noexcept +{ + return is_null(row_ndx); +} + +inline size_t LinkColumn::set_link(size_t row_ndx, size_t target_row_ndx) +{ + int_fast64_t old_value = LinkColumnBase::get(row_ndx); + size_t old_target_row_ndx = to_size_t(old_value) - size_t(1); + if (old_target_row_ndx == target_row_ndx) + return old_target_row_ndx; // Nothing to do + if (old_value != 0) + m_backlink_column->remove_one_backlink(old_target_row_ndx, row_ndx); // Throws + + int_fast64_t new_value = int_fast64_t(size_t(1) + target_row_ndx); + LinkColumnBase::set(row_ndx, new_value); // Throws + + if (target_row_ndx != realm::npos) + m_backlink_column->add_backlink(target_row_ndx, row_ndx); // Throws + + return old_target_row_ndx; +} + +inline void LinkColumn::set_null(size_t row_ndx) +{ + set_link(row_ndx, realm::npos); // Throws +} + +inline void LinkColumn::nullify_link(size_t row_ndx) +{ + set_null(row_ndx); // Throws +} + +inline void LinkColumn::insert_link(size_t row_ndx, size_t target_row_ndx) +{ + int_fast64_t value = int_fast64_t(size_t(1) + target_row_ndx); + LinkColumnBase::insert(row_ndx, value); // Throws + + if (target_row_ndx != realm::npos) + m_backlink_column->add_backlink(target_row_ndx, row_ndx); // Throws +} + +inline void LinkColumn::insert_null_link(size_t row_ndx) +{ + insert_link(row_ndx, realm::npos); // Throws +} + +inline void LinkColumn::do_update_link(size_t row_ndx, size_t, size_t new_target_row_ndx) +{ + // Row pos is offset by one, to allow null refs + LinkColumnBase::set(row_ndx, new_target_row_ndx + 1); +} + +inline void LinkColumn::do_swap_link(size_t row_ndx, size_t target_row_ndx_1, size_t target_row_ndx_2) +{ + // Row pos is offset by one, to allow null refs + ++target_row_ndx_1; + ++target_row_ndx_2; + + uint64_t value = LinkColumnBase::get_uint(row_ndx); + if (value == target_row_ndx_1) { + LinkColumnBase::set_uint(row_ndx, target_row_ndx_2); + } + else if (value == target_row_ndx_2) { + LinkColumnBase::set_uint(row_ndx, target_row_ndx_1); + } +} + +} // namespace realm + +#endif // REALM_COLUMN_LINK_HPP diff --git a/Pods/Realm/include/core/realm/column_linkbase.hpp b/Pods/Realm/include/core/realm/column_linkbase.hpp new file mode 100644 index 0000000000..fa67fabb2a --- /dev/null +++ b/Pods/Realm/include/core/realm/column_linkbase.hpp @@ -0,0 +1,206 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_LINKBASE_HPP +#define REALM_COLUMN_LINKBASE_HPP + +#include + +namespace realm { + +class BacklinkColumn; +class Table; + +// Abstract base class for columns containing links +class LinkColumnBase : public IntegerColumn { +public: + // Create unattached root array aaccessor. + LinkColumnBase(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); + ~LinkColumnBase() noexcept override; + + bool is_nullable() const noexcept override = 0; + void set_null(size_t) override = 0; + bool is_null(size_t) const noexcept override = 0; + + bool supports_search_index() const noexcept final + { + return false; + } + StringIndex* create_search_index() override; + + bool get_weak_links() const noexcept; + void set_weak_links(bool) noexcept; + + Table& get_target_table() const noexcept; + void set_target_table(Table&) noexcept; + BacklinkColumn& get_backlink_column() const noexcept; + void set_backlink_column(BacklinkColumn&) noexcept; + + void swap_rows(size_t, size_t) override = 0; + + virtual void do_nullify_link(size_t row_ndx, size_t old_target_row_ndx) = 0; + virtual void do_update_link(size_t row_ndx, size_t old_target_row_ndx, size_t new_target_row_ndx) = 0; + virtual void do_swap_link(size_t row_ndx, size_t target_row_ndx_1, size_t target_row_ndx_2) = 0; + + void adj_acc_insert_rows(size_t, size_t) noexcept override; + void adj_acc_erase_row(size_t) noexcept override; + void adj_acc_move_over(size_t, size_t) noexcept override; + void adj_acc_swap_rows(size_t, size_t) noexcept override; + void adj_acc_move_row(size_t, size_t) noexcept override; + void adj_acc_clear_root_table() noexcept override; + void mark(int) noexcept override; + void refresh_accessor_tree(size_t, const Spec&) override; + void bump_link_origin_table_version() noexcept override; + + void verify(const Table&, size_t) const override; + using IntegerColumn::verify; + +protected: + // A pointer to the table that this column is part of. + Table* const m_table; + + TableRef m_target_table; + BacklinkColumn* m_backlink_column = nullptr; + bool m_weak_links = false; // True if these links are weak (not strong) + + /// Call Table::cascade_break_backlinks_to() for the specified target row if + /// it is not already in \a state.rows, and the number of strong links to it + /// has dropped to zero. + void check_cascade_break_backlinks_to(size_t target_table_ndx, size_t target_row_ndx, CascadeState& state); +}; + + +// Implementation + +inline LinkColumnBase::LinkColumnBase(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) + : IntegerColumn(alloc, ref, column_ndx) // Throws + , m_table(table) +{ +} + +inline LinkColumnBase::~LinkColumnBase() noexcept +{ +} + +inline StringIndex* LinkColumnBase::create_search_index() +{ + return nullptr; +} + +inline bool LinkColumnBase::get_weak_links() const noexcept +{ + return m_weak_links; +} + +inline void LinkColumnBase::set_weak_links(bool value) noexcept +{ + m_weak_links = value; +} + +inline Table& LinkColumnBase::get_target_table() const noexcept +{ + return *m_target_table; +} + +inline void LinkColumnBase::set_target_table(Table& table) noexcept +{ + REALM_ASSERT(!m_target_table); + m_target_table = table.get_table_ref(); +} + +inline BacklinkColumn& LinkColumnBase::get_backlink_column() const noexcept +{ + return *m_backlink_column; +} + +inline void LinkColumnBase::set_backlink_column(BacklinkColumn& column) noexcept +{ + m_backlink_column = &column; +} + +inline void LinkColumnBase::adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept +{ + IntegerColumn::adj_acc_insert_rows(row_ndx, num_rows); + + typedef _impl::TableFriend tf; + tf::mark(*m_target_table); +} + +inline void LinkColumnBase::adj_acc_erase_row(size_t row_ndx) noexcept +{ + IntegerColumn::adj_acc_erase_row(row_ndx); + + typedef _impl::TableFriend tf; + tf::mark(*m_target_table); +} + +inline void LinkColumnBase::adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept +{ + IntegerColumn::adj_acc_move_over(from_row_ndx, to_row_ndx); + + typedef _impl::TableFriend tf; + tf::mark(*m_target_table); +} + +inline void LinkColumnBase::adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept +{ + IntegerColumn::adj_acc_swap_rows(row_ndx_1, row_ndx_2); + + typedef _impl::TableFriend tf; + tf::mark(*m_target_table); +} + +inline void LinkColumnBase::adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept +{ + IntegerColumn::adj_acc_move_row(from_ndx, to_ndx); + + using tf = _impl::TableFriend; + tf::mark(*m_target_table); +} + +inline void LinkColumnBase::adj_acc_clear_root_table() noexcept +{ + IntegerColumn::adj_acc_clear_root_table(); + + typedef _impl::TableFriend tf; + tf::mark(*m_target_table); +} + +inline void LinkColumnBase::mark(int type) noexcept +{ + if (type & mark_LinkTargets) { + typedef _impl::TableFriend tf; + tf::mark(*m_target_table); + } +} + +inline void LinkColumnBase::bump_link_origin_table_version() noexcept +{ + // It is important to mark connected tables as modified. + // Also see BacklinkColumn::bump_link_origin_table_version(). + typedef _impl::TableFriend tf; + if (m_target_table) { + bool bump_global = false; + tf::bump_version(*m_target_table, bump_global); + } +} + + +} // namespace realm + +#endif // REALM_COLUMN_LINKBASE_HPP diff --git a/Pods/Realm/include/core/realm/column_linklist.hpp b/Pods/Realm/include/core/realm/column_linklist.hpp new file mode 100644 index 0000000000..3dab1b3c43 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_linklist.hpp @@ -0,0 +1,248 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_LINKLIST_HPP +#define REALM_COLUMN_LINKLIST_HPP + +#include +#include + +#include +#include +#include +#include +#include + +namespace realm { + +namespace _impl { +class TransactLogConvenientEncoder; +} + + +/// A column of link lists (LinkListColumn) is a single B+-tree, and the root of +/// the column is the root of the B+-tree. All leaf nodes are single arrays of +/// type Array with the hasRefs bit set. +/// +/// The individual values in the column are either refs to Columns containing the +/// row positions in the target table, or in the case where they are empty, a zero +/// ref. +class LinkListColumn : public LinkColumnBase, public ArrayParent { +public: + using LinkColumnBase::LinkColumnBase; + using value_type = ConstLinkViewRef; + LinkListColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); + ~LinkListColumn() noexcept override; + + static ref_type create(Allocator&, size_t size = 0); + + bool is_nullable() const noexcept final; + + bool has_links(size_t row_ndx) const noexcept; + size_t get_link_count(size_t row_ndx) const noexcept; + + ConstLinkViewRef get(size_t row_ndx) const; + LinkViewRef get(size_t row_ndx); + + bool is_null(size_t row_ndx) const noexcept final; + void set_null(size_t row_ndx) final; + + /// Compare two columns for equality. + bool compare_link_list(const LinkListColumn&) const; + + void to_json_row(size_t row_ndx, std::ostream& out) const; + + void insert_rows(size_t, size_t, size_t, bool) override; + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + void swap_rows(size_t, size_t) override; + void clear(size_t, bool) override; + void cascade_break_backlinks_to(size_t, CascadeState&) override; + void cascade_break_backlinks_to_all_rows(size_t, CascadeState&) override; + void update_from_parent(size_t) noexcept override; + void adj_acc_clear_root_table() noexcept override; + void adj_acc_insert_rows(size_t, size_t) noexcept override; + void adj_acc_erase_row(size_t) noexcept override; + void adj_acc_move_over(size_t, size_t) noexcept override; + void adj_acc_swap_rows(size_t, size_t) noexcept override; + void adj_acc_move_row(size_t, size_t) noexcept override; + void adj_acc_merge_rows(size_t, size_t) noexcept override; + void refresh_accessor_tree(size_t, const Spec&) override; + + void verify() const override; + void verify(const Table&, size_t) const override; + +protected: + void do_discard_child_accessors() noexcept override; + +private: + struct list_entry { + size_t m_row_ndx; + std::weak_ptr m_list; + bool operator<(const list_entry& other) const + { + return m_row_ndx < other.m_row_ndx; + } + }; + + // The accessors stored in `m_list_accessors` are sorted by their row index. + // When a LinkList accessor is destroyed because the last shared_ptr pointing + // to it dies, its entry is implicitly replaced by a tombstone (an entry with + // an empty `m_list`). These tombstones are pruned at a later time by + // `prune_list_accessor_tombstones`. This is done to amortize the O(n) cost + // of `std::vector::erase` that would otherwise be incurred each time an + // accessor is removed. + mutable std::vector m_list_accessors; + mutable std::atomic m_list_accessors_contains_tombstones; + + std::shared_ptr get_ptr(size_t row_ndx) const; + + void do_nullify_link(size_t row_ndx, size_t old_target_row_ndx) override; + void do_update_link(size_t row_ndx, size_t old_target_row_ndx, size_t new_target_row_ndx) override; + void do_swap_link(size_t row_ndx, size_t target_row_ndx_1, size_t target_row_ndx_2) override; + + void unregister_linkview(); + ref_type get_row_ref(size_t row_ndx) const noexcept; + void set_row_ref(size_t row_ndx, ref_type new_ref); + void add_backlink(size_t target_row, size_t source_row); + void remove_backlink(size_t target_row, size_t source_row); + + // ArrayParent overrides + void update_child_ref(size_t child_ndx, ref_type new_ref) override; + ref_type get_child_ref(size_t child_ndx) const noexcept override; + + // These helpers are needed because of the way the B+-tree of links is + // traversed in cascade_break_backlinks_to() and + // cascade_break_backlinks_to_all_rows(). + void cascade_break_backlinks_to__leaf(size_t row_ndx, const Array& link_list_leaf, CascadeState&); + void cascade_break_backlinks_to_all_rows__leaf(const Array& link_list_leaf, CascadeState&); + + void discard_child_accessors() noexcept; + + template + void adj_insert_rows(size_t row_ndx, size_t num_rows_inserted) noexcept; + + template + void adj_erase_rows(size_t row_ndx, size_t num_rows_erased) noexcept; + + template + void adj_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; + + template + void adj_move(size_t from_ndx, size_t to_ndx) noexcept; + + template + void adj_swap(size_t row_ndx_1, size_t row_ndx_2) noexcept; + + void prune_list_accessor_tombstones() noexcept; + void validate_list_accessors() const noexcept; + + std::pair get_to_dot_parent(size_t) const override; + + friend class BacklinkColumn; + friend class LinkView; + friend class _impl::TransactLogConvenientEncoder; +}; + + +// Implementation + +inline LinkListColumn::LinkListColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) + : LinkColumnBase(alloc, ref, table, column_ndx) +{ + m_list_accessors_contains_tombstones.store(false); +} + +inline LinkListColumn::~LinkListColumn() noexcept +{ + discard_child_accessors(); +} + +inline ref_type LinkListColumn::create(Allocator& alloc, size_t size) +{ + return IntegerColumn::create(alloc, Array::type_HasRefs, size); // Throws +} + +inline bool LinkListColumn::is_nullable() const noexcept +{ + return false; +} + +inline bool LinkListColumn::has_links(size_t row_ndx) const noexcept +{ + ref_type ref = LinkColumnBase::get_as_ref(row_ndx); + return (ref != 0); +} + +inline size_t LinkListColumn::get_link_count(size_t row_ndx) const noexcept +{ + ref_type ref = LinkColumnBase::get_as_ref(row_ndx); + if (ref == 0) + return 0; + return ColumnBase::get_size_from_ref(ref, get_alloc()); +} + +inline ConstLinkViewRef LinkListColumn::get(size_t row_ndx) const +{ + return get_ptr(row_ndx); +} + +inline LinkViewRef LinkListColumn::get(size_t row_ndx) +{ + return get_ptr(row_ndx); +} + +inline bool LinkListColumn::is_null(size_t) const noexcept +{ + return false; +} + +inline void LinkListColumn::set_null(size_t) +{ + throw LogicError{LogicError::column_not_nullable}; +} + +inline void LinkListColumn::do_discard_child_accessors() noexcept +{ + discard_child_accessors(); +} + +inline ref_type LinkListColumn::get_row_ref(size_t row_ndx) const noexcept +{ + return LinkColumnBase::get_as_ref(row_ndx); +} + +inline void LinkListColumn::set_row_ref(size_t row_ndx, ref_type new_ref) +{ + LinkColumnBase::set(row_ndx, new_ref); // Throws +} + +inline void LinkListColumn::add_backlink(size_t target_row, size_t source_row) +{ + m_backlink_column->add_backlink(target_row, source_row); // Throws +} + +inline void LinkListColumn::remove_backlink(size_t target_row, size_t source_row) +{ + m_backlink_column->remove_one_backlink(target_row, source_row); // Throws +} + + +} // namespace realm + +#endif // REALM_COLUMN_LINKLIST_HPP diff --git a/Pods/Realm/include/core/realm/column_mixed.hpp b/Pods/Realm/include/core/realm/column_mixed.hpp new file mode 100644 index 0000000000..5f74c41540 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_mixed.hpp @@ -0,0 +1,265 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_MIXED_HPP +#define REALM_COLUMN_MIXED_HPP + +#include + +#include +#include +#include +#include +#include + + +namespace realm { + + +// Pre-declarations +class BinaryColumn; + + +/// A mixed column (MixedColumn) is composed of three subcolumns. The first +/// subcolumn is an integer column (Column) and stores value types. The second +/// one stores values and is a subtable parent column (SubtableColumnBase), +/// which is a subclass of an integer column (Column). The last one is a binary +/// column (BinaryColumn) and stores additional data for values of type string +/// or binary data. The last subcolumn is optional. The root of a mixed column +/// is an array node of type Array that stores the root refs of the subcolumns. +class MixedColumn : public ColumnBaseSimple { +public: + /// Create a mixed column wrapper and attach it to a preexisting + /// underlying structure of arrays. + /// + /// \param alloc The memory allocator to change the underlying + /// structure in memory. + /// + /// \param ref The memory reference of the MixedColumn for which + /// this accessor should be creator for. + /// + /// \param table If this column is used as part of a table you + /// must pass a pointer to that table. Otherwise you must pass + /// null + /// + /// \param column_ndx If this column is used as part of a table + /// you must pass the logical index of the column within that + /// table. Otherwise you should pass zero. + MixedColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); + + ~MixedColumn() noexcept override; + + DataType get_type(size_t ndx) const noexcept; + size_t size() const noexcept final + { + return m_types->size(); + } + bool is_empty() const noexcept + { + return size() == 0; + } + + int64_t get_int(size_t ndx) const noexcept; + bool get_bool(size_t ndx) const noexcept; + OldDateTime get_olddatetime(size_t ndx) const noexcept; + Timestamp get_timestamp(size_t ndx) const noexcept; + float get_float(size_t ndx) const noexcept; + double get_double(size_t ndx) const noexcept; + StringData get_string(size_t ndx) const noexcept; + BinaryData get_binary(size_t ndx) const noexcept; + StringData get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept override; + + /// The returned array ref is zero if the specified row does not + /// contain a subtable. + ref_type get_subtable_ref(size_t row_ndx) const noexcept; + + /// The returned size is zero if the specified row does not + /// contain a subtable. + size_t get_subtable_size(size_t row_ndx) const noexcept; + + TableRef get_subtable_accessor(size_t row_ndx) const noexcept override; + + void discard_subtable_accessor(size_t row_ndx) noexcept override; + + /// If the value at the specified index is a subtable, return a + /// TableRef to that accessor for that subtable. Otherwise return + /// null. The accessor will be created if it does not already + /// exist. + TableRef get_subtable_tableref(size_t row_ndx); + + ConstTableRef get_subtable_tableref(size_t subtable_ndx) const; + + void set_int(size_t ndx, int64_t value); + void set_bool(size_t ndx, bool value); + void set_olddatetime(size_t ndx, OldDateTime value); + void set_timestamp(size_t ndx, Timestamp value); + void set_float(size_t ndx, float value); + void set_double(size_t ndx, double value); + void set_string(size_t ndx, StringData value) override; + void set_binary(size_t ndx, BinaryData value); + void set_subtable(size_t ndx, const Table* value); + + void insert_int(size_t ndx, int_fast64_t value); + void insert_bool(size_t ndx, bool value); + void insert_olddatetime(size_t ndx, OldDateTime value); + void insert_timestamp(size_t ndx, Timestamp value); + void insert_float(size_t ndx, float value); + void insert_double(size_t ndx, double value); + void insert_string(size_t ndx, StringData value); + void insert_binary(size_t ndx, BinaryData value); + void insert_subtable(size_t ndx, const Table* value); + + void erase(size_t row_ndx); + void move_last_over(size_t row_ndx); + void clear(); + + /// Compare two mixed columns for equality. + bool compare_mixed(const MixedColumn&) const; + + int compare_values(size_t row1, size_t row2) const noexcept override; + + void discard_child_accessors() noexcept; + + static ref_type create(Allocator&, size_t size = 0); + + static size_t get_size_from_ref(ref_type root_ref, Allocator&) noexcept; + + // Overriding method in ColumnBase + ref_type write(size_t, size_t, size_t, _impl::OutputStream&) const override; + + void insert_rows(size_t, size_t, size_t, bool) override; + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + void swap_rows(size_t, size_t) override; + void clear(size_t, bool) override; + void update_from_parent(size_t) noexcept override; + void adj_acc_insert_rows(size_t, size_t) noexcept override; + void adj_acc_erase_row(size_t) noexcept override; + void adj_acc_move_over(size_t, size_t) noexcept override; + void adj_acc_swap_rows(size_t, size_t) noexcept override; + void adj_acc_move_row(size_t, size_t) noexcept override; + void adj_acc_clear_root_table() noexcept override; + void mark(int) noexcept override; + void refresh_accessor_tree(size_t, const Spec&) override; + + void verify() const override; + void verify(const Table&, size_t) const override; + void to_dot(std::ostream&, StringData title) const override; + void do_dump_node_structure(std::ostream&, int) const override; + +private: + enum MixedColType { + // NOTE: below numbers must be kept in sync with ColumnType + // Column types used in Mixed + mixcol_Int = 0, + mixcol_Bool = 1, + mixcol_String = 2, + // 3, used for STRING_ENUM in ColumnType + mixcol_Binary = 4, + mixcol_Table = 5, + mixcol_Mixed = 6, + mixcol_OldDateTime = 7, + mixcol_Timestamp = 8, + mixcol_Float = 9, + mixcol_Double = 10, // Positive Double + mixcol_DoubleNeg = 11, // Negative Double + mixcol_IntNeg = 12 // Negative Integers + }; + + class RefsColumn; + + /// Stores the MixedColType of each value at the given index. For + /// values that uses all 64 bits, the type also encodes the sign + /// bit by having distinct types for positive negative values. + std::unique_ptr m_types; + + /// Stores the data for each entry. For a subtable, the stored + /// value is the ref of the subtable. For string, binary data, + /// the stored value is an index within `m_binary_data`. Likewise, + /// for timestamp, an index into `m_timestamp` is stored. For other + /// types the stored value is itself. Since we only have 63 bits + /// available for a non-ref value, the sign of numeric values is + /// encoded as part of the type in `m_types`. + std::unique_ptr m_data; + + /// For string and binary data types, the bytes are stored here. + std::unique_ptr m_binary_data; + + /// Timestamps are stored here. + std::unique_ptr m_timestamp_data; + + void do_erase(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows); + void do_move_last_over(size_t row_ndx, size_t prior_num_rows); + void do_swap_rows(size_t, size_t); + void do_clear(size_t num_rows); + + void create(Allocator&, ref_type, Table*, size_t column_ndx); + void ensure_binary_data_column(); + void ensure_timestamp_column(); + + MixedColType clear_value(size_t ndx, MixedColType new_type); // Returns old type + void clear_value_and_discard_subtab_acc(size_t ndx, MixedColType new_type); + + // Get/set/insert 64-bit values in m_data/m_types + int64_t get_value(size_t ndx) const noexcept; + void set_value(size_t ndx, int64_t value, MixedColType); + void set_int64(size_t ndx, int64_t value, MixedColType pos_type, MixedColType neg_type); + + void insert_value(size_t row_ndx, int_fast64_t types_value, int_fast64_t data_value); + void insert_int(size_t ndx, int_fast64_t value, MixedColType type); + void insert_pos_neg(size_t ndx, int_fast64_t value, MixedColType pos_type, MixedColType neg_type); + + void do_discard_child_accessors() noexcept override; + +#ifdef REALM_DEBUG + void do_verify(const Table*, size_t col_ndx) const; +#endif + void leaf_to_dot(MemRef, ArrayParent*, size_t, std::ostream&) const override; +}; + +// LCOV_EXCL_START +inline StringData MixedColumn::get_index_data(size_t, StringIndex::StringConversionBuffer&) const noexcept +{ + REALM_ASSERT(false && "Index not supported for MixedColumn yet."); + REALM_UNREACHABLE(); + return {}; +} +// LCOV_EXCL_STOP + + +class MixedColumn::RefsColumn : public SubtableColumnBase { +public: + RefsColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); + ~RefsColumn() noexcept override; + + using SubtableColumnBase::get_subtable_tableref; + + void refresh_accessor_tree(size_t, const Spec&) override; + + friend class MixedColumn; +}; + + +} // namespace realm + + +// Implementation +#include + + +#endif // REALM_COLUMN_MIXED_HPP diff --git a/Pods/Realm/include/core/realm/column_mixed_tpl.hpp b/Pods/Realm/include/core/realm/column_mixed_tpl.hpp new file mode 100644 index 0000000000..5afdddcc04 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_mixed_tpl.hpp @@ -0,0 +1,514 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#include +#include + +namespace realm { + +inline MixedColumn::MixedColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) + : ColumnBaseSimple(column_ndx) +{ + create(alloc, ref, table, column_ndx); +} + +inline void MixedColumn::adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept +{ + m_data->adj_acc_insert_rows(row_ndx, num_rows); +} + +inline void MixedColumn::adj_acc_erase_row(size_t row_ndx) noexcept +{ + m_data->adj_acc_erase_row(row_ndx); +} + +inline void MixedColumn::adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept +{ + m_data->adj_acc_swap_rows(row_ndx_1, row_ndx_2); +} + +inline void MixedColumn::adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept +{ + m_data->adj_acc_move_row(from_ndx, to_ndx); +} + +inline void MixedColumn::adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept +{ + m_data->adj_acc_move_over(from_row_ndx, to_row_ndx); +} + +inline void MixedColumn::adj_acc_clear_root_table() noexcept +{ + m_data->adj_acc_clear_root_table(); +} + +inline ref_type MixedColumn::get_subtable_ref(size_t row_ndx) const noexcept +{ + REALM_ASSERT_3(row_ndx, <, m_types->size()); + if (m_types->get(row_ndx) != type_Table) + return 0; + return m_data->get_as_ref(row_ndx); +} + +inline size_t MixedColumn::get_subtable_size(size_t row_ndx) const noexcept +{ + ref_type top_ref = get_subtable_ref(row_ndx); + if (top_ref == 0) + return 0; + return _impl::TableFriend::get_size_from_ref(top_ref, m_data->get_alloc()); +} + +inline TableRef MixedColumn::get_subtable_accessor(size_t row_ndx) const noexcept +{ + return m_data->get_subtable_accessor(row_ndx); +} + +inline void MixedColumn::discard_subtable_accessor(size_t row_ndx) noexcept +{ + m_data->discard_subtable_accessor(row_ndx); +} + +inline TableRef MixedColumn::get_subtable_tableref(size_t row_ndx) +{ + REALM_ASSERT_3(row_ndx, <, m_types->size()); + if (m_types->get(row_ndx) != type_Table) + return {}; + return m_data->get_subtable_tableref(row_ndx); // Throws +} + +inline ConstTableRef MixedColumn::get_subtable_tableref(size_t subtable_ndx) const +{ + return const_cast(this)->get_subtable_tableref(subtable_ndx); +} + +inline void MixedColumn::discard_child_accessors() noexcept +{ + m_data->discard_child_accessors(); +} + + +// +// Getters +// + +#define REALM_BIT63 0x8000000000000000ULL + +inline int64_t MixedColumn::get_value(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, m_types->size()); + + // Shift the unsigned value right - ensuring 0 gets in from left. + // Shifting signed integers right doesn't ensure 0's. + uint64_t value = uint64_t(m_data->get(ndx)) >> 1; + return int64_t(value); +} + +inline int64_t MixedColumn::get_int(size_t ndx) const noexcept +{ + // Get first 63 bits of the integer value + int64_t value = get_value(ndx); + + // restore 'sign'-bit from the column-type + MixedColType col_type = MixedColType(m_types->get(ndx)); + if (col_type == mixcol_IntNeg) { + // FIXME: Bad cast of result of '|' from unsigned to signed + value |= REALM_BIT63; // set sign bit (63) + } + else { + REALM_ASSERT_3(col_type, ==, mixcol_Int); + } + return value; +} + +inline bool MixedColumn::get_bool(size_t ndx) const noexcept +{ + REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_Bool); + + return (get_value(ndx) != 0); +} + +inline OldDateTime MixedColumn::get_olddatetime(size_t ndx) const noexcept +{ + REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_OldDateTime); + + return OldDateTime(get_value(ndx)); +} + +inline float MixedColumn::get_float(size_t ndx) const noexcept +{ + static_assert(std::numeric_limits::is_iec559, "'float' is not IEEE"); + static_assert((sizeof(float) * CHAR_BIT == 32), "Assume 32 bit float."); + REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_Float); + + return type_punning(get_value(ndx)); +} + +inline double MixedColumn::get_double(size_t ndx) const noexcept +{ + static_assert(std::numeric_limits::is_iec559, "'double' is not IEEE"); + static_assert((sizeof(double) * CHAR_BIT == 64), "Assume 64 bit double."); + + int64_t int_val = get_value(ndx); + + // restore 'sign'-bit from the column-type + MixedColType col_type = MixedColType(m_types->get(ndx)); + if (col_type == mixcol_DoubleNeg) + int_val |= REALM_BIT63; // set sign bit (63) + else { + REALM_ASSERT_3(col_type, ==, mixcol_Double); + } + return type_punning(int_val); +} + +inline StringData MixedColumn::get_string(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, m_types->size()); + REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_String); + REALM_ASSERT(m_binary_data); + + size_t data_ndx = size_t(int64_t(m_data->get(ndx)) >> 1); + return m_binary_data->get_string(data_ndx); +} + +inline BinaryData MixedColumn::get_binary(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, m_types->size()); + REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_Binary); + REALM_ASSERT(m_binary_data); + + size_t data_ndx = size_t(uint64_t(m_data->get(ndx)) >> 1); + return m_binary_data->get(data_ndx); +} + +inline Timestamp MixedColumn::get_timestamp(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, m_types->size()); + REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_Timestamp); + REALM_ASSERT(m_timestamp_data); + size_t data_ndx = size_t(uint64_t(m_data->get(ndx)) >> 1); + return m_timestamp_data->get(data_ndx); +} + +// +// Setters +// + +// Set a int64 value. +// Store 63 bit of the value in m_data. Store sign bit in m_types. + +inline void MixedColumn::set_int64(size_t ndx, int64_t value, MixedColType pos_type, MixedColType neg_type) +{ + REALM_ASSERT_3(ndx, <, m_types->size()); + + // If sign-bit is set in value, 'store' it in the column-type + MixedColType coltype = ((value & REALM_BIT63) == 0) ? pos_type : neg_type; + + // Remove refs or binary data (sets type to double) + clear_value_and_discard_subtab_acc(ndx, coltype); // Throws + + // Shift value one bit and set lowest bit to indicate that this is not a ref + value = (value << 1) + 1; + m_data->set(ndx, value); +} + +inline void MixedColumn::set_int(size_t ndx, int64_t value) +{ + set_int64(ndx, value, mixcol_Int, mixcol_IntNeg); // Throws +} + +inline void MixedColumn::set_double(size_t ndx, double value) +{ + int64_t val64 = type_punning(value); + set_int64(ndx, val64, mixcol_Double, mixcol_DoubleNeg); // Throws +} + +inline void MixedColumn::set_value(size_t ndx, int64_t value, MixedColType coltype) +{ + REALM_ASSERT_3(ndx, <, m_types->size()); + + // Remove refs or binary data (sets type to float) + clear_value_and_discard_subtab_acc(ndx, coltype); // Throws + + // Shift value one bit and set lowest bit to indicate that this is not a ref + int64_t v = (value << 1) + 1; + m_data->set(ndx, v); // Throws +} + +inline void MixedColumn::set_float(size_t ndx, float value) +{ + int64_t val64 = type_punning(value); + set_value(ndx, val64, mixcol_Float); // Throws +} + +inline void MixedColumn::set_bool(size_t ndx, bool value) +{ + set_value(ndx, (value ? 1 : 0), mixcol_Bool); // Throws +} + +inline void MixedColumn::set_olddatetime(size_t ndx, OldDateTime value) +{ + set_value(ndx, int64_t(value.get_olddatetime()), mixcol_OldDateTime); // Throws +} + +inline void MixedColumn::set_subtable(size_t ndx, const Table* t) +{ + REALM_ASSERT_3(ndx, <, m_types->size()); + typedef _impl::TableFriend tf; + ref_type ref; + if (t) { + ref = tf::clone(*t, get_alloc()); // Throws + } + else { + ref = tf::create_empty_table(get_alloc()); // Throws + } + // Remove any previous refs or binary data + clear_value_and_discard_subtab_acc(ndx, mixcol_Table); // Throws + m_data->set(ndx, ref); // Throws +} + +// +// Inserts +// + +inline void MixedColumn::insert_value(size_t row_ndx, int_fast64_t types_value, int_fast64_t data_value) +{ + size_t types_size = m_types->size(); // Slow + bool is_append = row_ndx == types_size; + size_t row_ndx_2 = is_append ? realm::npos : row_ndx; + size_t num_rows = 1; + m_types->insert_without_updating_index(row_ndx_2, types_value, num_rows); // Throws + m_data->do_insert(row_ndx_2, data_value, num_rows); // Throws +} + +// Insert a int64 value. +// Store 63 bit of the value in m_data. Store sign bit in m_types. + +inline void MixedColumn::insert_int(size_t ndx, int_fast64_t value, MixedColType type) +{ + int_fast64_t types_value = type; + // Shift value one bit and set lowest bit to indicate that this is not a ref + int_fast64_t data_value = 1 + (value << 1); + insert_value(ndx, types_value, data_value); // Throws +} + +inline void MixedColumn::insert_pos_neg(size_t ndx, int_fast64_t value, MixedColType pos_type, MixedColType neg_type) +{ + // 'store' the sign-bit in the integer-type + MixedColType type = (value & REALM_BIT63) == 0 ? pos_type : neg_type; + int_fast64_t types_value = type; + // Shift value one bit and set lowest bit to indicate that this is not a ref + int_fast64_t data_value = 1 + (value << 1); + insert_value(ndx, types_value, data_value); // Throws +} + +inline void MixedColumn::insert_int(size_t ndx, int_fast64_t value) +{ + insert_pos_neg(ndx, value, mixcol_Int, mixcol_IntNeg); // Throws +} + +inline void MixedColumn::insert_double(size_t ndx, double value) +{ + int_fast64_t value_2 = type_punning(value); + insert_pos_neg(ndx, value_2, mixcol_Double, mixcol_DoubleNeg); // Throws +} + +inline void MixedColumn::insert_float(size_t ndx, float value) +{ + int_fast64_t value_2 = type_punning(value); + insert_int(ndx, value_2, mixcol_Float); // Throws +} + +inline void MixedColumn::insert_bool(size_t ndx, bool value) +{ + int_fast64_t value_2 = int_fast64_t(value); + insert_int(ndx, value_2, mixcol_Bool); // Throws +} + +inline void MixedColumn::insert_olddatetime(size_t ndx, OldDateTime value) +{ + int_fast64_t value_2 = int_fast64_t(value.get_olddatetime()); + insert_int(ndx, value_2, mixcol_OldDateTime); // Throws +} + +inline void MixedColumn::insert_timestamp(size_t ndx, Timestamp value) +{ + ensure_timestamp_column(); + size_t data_ndx = m_timestamp_data->size(); + m_timestamp_data->add(value); // Throws + insert_int(ndx, int_fast64_t(data_ndx), mixcol_Timestamp); +} + +inline void MixedColumn::insert_string(size_t ndx, StringData value) +{ + ensure_binary_data_column(); + size_t blob_ndx = m_binary_data->size(); + m_binary_data->add_string(value); // Throws + + int_fast64_t value_2 = int_fast64_t(blob_ndx); + insert_int(ndx, value_2, mixcol_String); // Throws +} + +inline void MixedColumn::insert_binary(size_t ndx, BinaryData value) +{ + ensure_binary_data_column(); + size_t blob_ndx = m_binary_data->size(); + m_binary_data->add(value); // Throws + + int_fast64_t value_2 = int_fast64_t(blob_ndx); + insert_int(ndx, value_2, mixcol_Binary); // Throws +} + +inline void MixedColumn::insert_subtable(size_t ndx, const Table* t) +{ + typedef _impl::TableFriend tf; + ref_type ref; + if (t) { + ref = tf::clone(*t, get_alloc()); // Throws + } + else { + ref = tf::create_empty_table(get_alloc()); // Throws + } + int_fast64_t types_value = mixcol_Table; + int_fast64_t data_value = int_fast64_t(ref); + insert_value(ndx, types_value, data_value); // Throws +} + +inline void MixedColumn::erase(size_t row_ndx) +{ + size_t num_rows_to_erase = 1; + size_t prior_num_rows = size(); // Note that size() is slow + do_erase(row_ndx, num_rows_to_erase, prior_num_rows); // Throws +} + +inline void MixedColumn::move_last_over(size_t row_ndx) +{ + size_t prior_num_rows = size(); // Note that size() is slow + do_move_last_over(row_ndx, prior_num_rows); // Throws +} + +inline void MixedColumn::swap_rows(size_t row_ndx_1, size_t row_ndx_2) +{ + do_swap_rows(row_ndx_1, row_ndx_2); +} + +inline void MixedColumn::clear() +{ + size_t num_rows = size(); // Note that size() is slow + do_clear(num_rows); // Throws +} + +inline size_t MixedColumn::get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept +{ + const char* root_header = alloc.translate(root_ref); + ref_type types_ref = to_ref(Array::get(root_header, 0)); + return IntegerColumn::get_size_from_ref(types_ref, alloc); +} + +inline void MixedColumn::clear_value_and_discard_subtab_acc(size_t row_ndx, MixedColType new_type) +{ + MixedColType old_type = clear_value(row_ndx, new_type); + if (old_type == mixcol_Table) + m_data->discard_subtable_accessor(row_ndx); +} + +// Implementing pure virtual method of ColumnBase. +inline void MixedColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, + bool insert_nulls) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx <= prior_num_rows); + REALM_ASSERT(!insert_nulls); + + size_t row_ndx_2 = (row_ndx == prior_num_rows ? realm::npos : row_ndx); + + int_fast64_t type_value = mixcol_Int; + m_types->insert_without_updating_index(row_ndx_2, type_value, num_rows_to_insert); // Throws + + // The least significant bit indicates that the rest of the bits form an + // integer value, so 1 is actually zero. + int_fast64_t data_value = 1; + m_data->do_insert(row_ndx_2, data_value, num_rows_to_insert); // Throws +} + +// Implementing pure virtual method of ColumnBase. +inline void MixedColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) +{ + do_erase(row_ndx, num_rows_to_erase, prior_num_rows); // Throws +} + +// Implementing pure virtual method of ColumnBase. +inline void MixedColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) +{ + do_move_last_over(row_ndx, prior_num_rows); // Throws +} + +// Implementing pure virtual method of ColumnBase. +inline void MixedColumn::clear(size_t num_rows, bool) +{ + do_clear(num_rows); // Throws +} + +inline void MixedColumn::mark(int type) noexcept +{ + m_data->mark(type); +} + +inline void MixedColumn::refresh_accessor_tree(size_t col_ndx, const Spec& spec) +{ + ColumnBaseSimple::refresh_accessor_tree(col_ndx, spec); + + get_root_array()->init_from_parent(); + m_types->refresh_accessor_tree(col_ndx, spec); // Throws + m_data->refresh_accessor_tree(col_ndx, spec); // Throws + + m_binary_data.reset(); + // See if m_binary_data needs to be created. + if (get_root_array()->size() >= 3) { + ref_type ref = get_root_array()->get_as_ref(2); + m_binary_data.reset(new BinaryColumn(get_alloc(), ref)); // Throws + m_binary_data->set_parent(get_root_array(), 2); + } + + m_timestamp_data.reset(); + // See if m_timestamp_data needs to be created. + if (get_root_array()->size() >= 4) { + ref_type ref = get_root_array()->get_as_ref(3); + // When adding/creating a Mixed column the user cannot specify nullability, so the "true" below + // makes it implicitly nullable, which may not be wanted. But it's OK since Mixed columns are not + // publicly supported + m_timestamp_data.reset(new TimestampColumn(true /*fixme*/, get_alloc(), ref)); // Throws + m_timestamp_data->set_parent(get_root_array(), 3); + } + + if (m_binary_data) { + REALM_ASSERT_3(get_root_array()->size(), >=, 3); + m_binary_data->refresh_accessor_tree(col_ndx, spec); // Throws + } + if (m_timestamp_data) { + REALM_ASSERT_3(get_root_array()->size(), >=, 4); + m_timestamp_data->refresh_accessor_tree(col_ndx, spec); // Throws + } +} + +inline void MixedColumn::RefsColumn::refresh_accessor_tree(size_t col_ndx, const Spec& spec) +{ + SubtableColumnBase::refresh_accessor_tree(col_ndx, spec); // Throws + m_subtable_map.refresh_accessor_tree(); // Throws +} + +} // namespace realm diff --git a/Pods/Realm/include/core/realm/column_string.hpp b/Pods/Realm/include/core/realm/column_string.hpp new file mode 100644 index 0000000000..e7693eeb23 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_string.hpp @@ -0,0 +1,377 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_STRING_HPP +#define REALM_COLUMN_STRING_HPP + +#include +#include +#include +#include +#include +#include + +namespace realm { + +// Pre-declarations +class StringIndex; + + +/// A string column (StringColumn) is a single B+-tree, and +/// the root of the column is the root of the B+-tree. Leaf nodes are +/// either of type ArrayString (array of small strings), +/// ArrayStringLong (array of medium strings), or ArrayBigBlobs (array +/// of big strings). +/// +/// A string column can optionally be equipped with a search index. If +/// it is, then the root ref of the index is stored in +/// Table::m_columns immediately after the root ref of the string +/// column. +class StringColumn : public ColumnBaseSimple { +public: + typedef StringData value_type; + + StringColumn(Allocator&, ref_type, bool nullable = false, size_t column_ndx = npos); + ~StringColumn() noexcept override; + + void destroy() noexcept override; + + size_t size() const noexcept final; + bool is_empty() const noexcept + { + return size() == 0; + } + + bool is_null(size_t ndx) const noexcept final; + void set_null(size_t ndx) final; + StringData get(size_t ndx) const noexcept; + void set(size_t ndx, StringData); + void add(); + void add(StringData value); + void insert(size_t ndx); + void insert(size_t ndx, StringData value); + void erase(size_t row_ndx); + void move_last_over(size_t row_ndx); + void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override; + void clear(); + + size_t count(StringData value) const; + size_t find_first(StringData value, size_t begin = 0, size_t end = npos) const; + void find_all(IntegerColumn& result, StringData value, size_t begin = 0, size_t end = npos) const; + FindRes find_all_no_copy(StringData value, InternalFindResult& result) const; + + int compare_values(size_t, size_t) const noexcept override; + + //@{ + /// Find the lower/upper bound for the specified value assuming + /// that the elements are already sorted in ascending order + /// according to StringData::operator<(). + size_t lower_bound_string(StringData value) const noexcept; + size_t upper_bound_string(StringData value) const noexcept; + //@} + + void set_string(size_t, StringData) override; + + bool is_nullable() const noexcept final; + + // Search index + StringData get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept final; + bool has_search_index() const noexcept override; + void set_search_index_ref(ref_type, ArrayParent*, size_t) override; + StringIndex* get_search_index() noexcept override; + const StringIndex* get_search_index() const noexcept override; + std::unique_ptr release_search_index() noexcept; + bool supports_search_index() const noexcept final + { + return true; + } + StringIndex* create_search_index() override; + + // Simply inserts all column values in the index in a loop + void populate_search_index(); + void destroy_search_index() noexcept override; + + // Optimizing data layout. enforce == true will enforce enumeration; + // enforce == false will auto-evaluate if it should be enumerated or not + bool auto_enumerate(ref_type& keys, ref_type& values, bool enforce = false) const; + + /// Compare two string columns for equality. + bool compare_string(const StringColumn&) const; + + enum LeafType { + leaf_type_Small, ///< ArrayString + leaf_type_Medium, ///< ArrayStringLong + leaf_type_Big ///< ArrayBigBlobs + }; + + std::unique_ptr get_leaf(size_t ndx, size_t& out_ndx_in_parent, LeafType& out_leaf_type) const; + + static ref_type create(Allocator&, size_t size = 0); + + static size_t get_size_from_ref(ref_type root_ref, Allocator&) noexcept; + + // Overrriding method in ColumnBase + ref_type write(size_t, size_t, size_t, _impl::OutputStream&) const override; + + void insert_rows(size_t, size_t, size_t, bool) override; + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + void clear(size_t, bool) override; + void set_ndx_in_parent(size_t ndx_in_parent) noexcept override; + void update_from_parent(size_t old_baseline) noexcept override; + void refresh_accessor_tree(size_t, const Spec&) override; + + void verify() const override; + void verify(const Table&, size_t) const override; + void to_dot(std::ostream&, StringData title) const override; + void do_dump_node_structure(std::ostream&, int) const override; + +private: + std::unique_ptr m_search_index; + bool m_nullable; + + LeafType get_block(size_t ndx, ArrayParent**, size_t& off, bool use_retval = false) const; + + /// If you are appending and have the size of the column readily available, + /// call the 4 argument version instead. If you are not appending, either + /// one is fine. + /// + /// \param row_ndx Must be `realm::npos` if appending. + void do_insert(size_t row_ndx, StringData value, size_t num_rows); + + /// If you are appending and you do not have the size of the column readily + /// available, call the 3 argument version instead. If you are not + /// appending, either one is fine. + /// + /// \param is_append Must be true if, and only if `row_ndx` is equal to the + /// size of the column (before insertion). + void do_insert(size_t row_ndx, StringData value, size_t num_rows, bool is_append); + + /// \param row_ndx Must be `realm::npos` if appending. + void bptree_insert(size_t row_ndx, StringData value, size_t num_rows); + + // Called by Array::bptree_insert(). + static ref_type leaf_insert(MemRef leaf_mem, ArrayParent&, size_t ndx_in_parent, Allocator&, size_t insert_ndx, + BpTreeNode::TreeInsert& state); + + class EraseLeafElem; + class CreateHandler; + class SliceHandler; + + void do_erase(size_t row_ndx, bool is_last); + void do_move_last_over(size_t row_ndx, size_t last_row_ndx); + void do_swap_rows(size_t row_ndx_1, size_t row_ndx_2); + void do_clear(); + + /// Root must be a leaf. Upgrades the root leaf as + /// necessary. Returns the type of the root leaf as it is upon + /// return. + LeafType upgrade_root_leaf(size_t value_size); + + void refresh_root_accessor(); + + void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override; + + friend class BpTreeNode; + friend class ColumnBase; +}; + + +// Implementation: + +inline size_t StringColumn::size() const noexcept +{ + if (root_is_leaf()) { + bool long_strings = m_array->has_refs(); + if (!long_strings) { + // Small strings root leaf + ArrayString* leaf = static_cast(m_array.get()); + return leaf->size(); + } + bool is_big = m_array->get_context_flag(); + if (!is_big) { + // Medium strings root leaf + ArrayStringLong* leaf = static_cast(m_array.get()); + return leaf->size(); + } + // Big strings root leaf + ArrayBigBlobs* leaf = static_cast(m_array.get()); + return leaf->size(); + } + // Non-leaf root + BpTreeNode* node = static_cast(m_array.get()); + return node->get_bptree_size(); +} + +inline void StringColumn::add(StringData value) +{ + REALM_ASSERT(!(value.is_null() && !m_nullable)); + size_t row_ndx = realm::npos; + size_t num_rows = 1; + do_insert(row_ndx, value, num_rows); // Throws +} + +inline void StringColumn::add() +{ + add(m_nullable ? realm::null() : StringData("")); +} + +inline void StringColumn::insert(size_t row_ndx, StringData value) +{ + REALM_ASSERT(!(value.is_null() && !m_nullable)); + size_t column_size = this->size(); + REALM_ASSERT_3(row_ndx, <=, column_size); + size_t num_rows = 1; + bool is_append = row_ndx == column_size; + do_insert(row_ndx, value, num_rows, is_append); // Throws +} + +inline void StringColumn::insert(size_t row_ndx) +{ + insert(row_ndx, m_nullable ? realm::null() : StringData("")); +} + +inline void StringColumn::erase(size_t row_ndx) +{ + size_t last_row_ndx = size() - 1; // Note that size() is slow + bool is_last = row_ndx == last_row_ndx; + do_erase(row_ndx, is_last); // Throws +} + +inline void StringColumn::move_last_over(size_t row_ndx) +{ + size_t last_row_ndx = size() - 1; // Note that size() is slow + do_move_last_over(row_ndx, last_row_ndx); // Throws +} + +inline void StringColumn::swap_rows(size_t row_ndx_1, size_t row_ndx_2) +{ + do_swap_rows(row_ndx_1, row_ndx_2); // Throws +} + +inline void StringColumn::clear() +{ + do_clear(); // Throws +} + +inline int StringColumn::compare_values(size_t row1, size_t row2) const noexcept +{ + StringData a = get(row1); + StringData b = get(row2); + + if (a.is_null() && !b.is_null()) + return 1; + else if (b.is_null() && !a.is_null()) + return -1; + else if (a.is_null() && b.is_null()) + return 0; + + if (a == b) + return 0; + return utf8_compare(a, b) ? 1 : -1; +} + +inline void StringColumn::set_string(size_t row_ndx, StringData value) +{ + REALM_ASSERT(!(value.is_null() && !m_nullable)); + set(row_ndx, value); // Throws +} + +inline bool StringColumn::has_search_index() const noexcept +{ + return m_search_index != 0; +} + +inline StringIndex* StringColumn::get_search_index() noexcept +{ + return m_search_index.get(); +} + +inline const StringIndex* StringColumn::get_search_index() const noexcept +{ + return m_search_index.get(); +} + +inline size_t StringColumn::get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept +{ + const char* root_header = alloc.translate(root_ref); + bool root_is_leaf = !Array::get_is_inner_bptree_node_from_header(root_header); + if (root_is_leaf) { + bool long_strings = Array::get_hasrefs_from_header(root_header); + if (!long_strings) { + // Small strings leaf + return ArrayString::get_size_from_header(root_header); + } + bool is_big = Array::get_context_flag_from_header(root_header); + if (!is_big) { + // Medium strings leaf + return ArrayStringLong::get_size_from_header(root_header, alloc); + } + // Big strings leaf + return ArrayBigBlobs::get_size_from_header(root_header); + } + + return BpTreeNode::get_bptree_size_from_header(root_header); +} + +// Implementing pure virtual method of ColumnBase. +inline void StringColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, + bool insert_nulls) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx <= prior_num_rows); + REALM_ASSERT(!insert_nulls || m_nullable); + + StringData value = m_nullable ? realm::null() : StringData(""); + bool is_append = (row_ndx == prior_num_rows); + do_insert(row_ndx, value, num_rows_to_insert, is_append); // Throws +} + +// Implementing pure virtual method of ColumnBase. +inline void StringColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(num_rows_to_erase <= prior_num_rows); + REALM_ASSERT(row_ndx <= prior_num_rows - num_rows_to_erase); + + bool is_last = (row_ndx + num_rows_to_erase == prior_num_rows); + for (size_t i = num_rows_to_erase; i > 0; --i) { + size_t row_ndx_2 = row_ndx + i - 1; + do_erase(row_ndx_2, is_last); // Throws + } +} + +// Implementing pure virtual method of ColumnBase. +inline void StringColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx < prior_num_rows); + + size_t last_row_ndx = prior_num_rows - 1; + do_move_last_over(row_ndx, last_row_ndx); // Throws +} + +// Implementing pure virtual method of ColumnBase. +inline void StringColumn::clear(size_t, bool) +{ + do_clear(); // Throws +} + +} // namespace realm + +#endif // REALM_COLUMN_STRING_HPP diff --git a/Pods/Realm/include/core/realm/column_string_enum.hpp b/Pods/Realm/include/core/realm/column_string_enum.hpp new file mode 100644 index 0000000000..a73fe0c227 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_string_enum.hpp @@ -0,0 +1,311 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_STRING_ENUM_HPP +#define REALM_COLUMN_STRING_ENUM_HPP + +#include + +namespace realm { + +// Pre-declarations +class StringIndex; + + +/// From the point of view of the application, an enumerated strings column +/// (StringEnumColumn) is like a string column (StringColumn), yet it manages +/// its strings in such a way that each unique string is stored only once. In +/// fact, an enumerated strings column is a combination of two subcolumns; a +/// regular string column (StringColumn) that stores the unique strings, and an +/// integer column that stores one unique string index for each entry in the +/// enumerated strings column. +/// +/// In terms of the underlying node structure, the subcolumn containing the +/// unique strings is not a true part of the enumerated strings column. Instead +/// it is a part of the spec structure that describes the table of which the +/// enumerated strings column is a part. This way, the unique strings can be +/// shared across enumerated strings columns of multiple subtables. This also +/// means that the root of an enumerated strings column coincides with the root +/// of the integer subcolumn, and in some sense, an enumerated strings column is +/// just the integer subcolumn. +/// +/// An enumerated strings column can optionally be equipped with a +/// search index. If it is, then the root ref of the index is stored +/// in Table::m_columns immediately after the root ref of the +/// enumerated strings column. +class StringEnumColumn : public IntegerColumn { +public: + typedef StringData value_type; + + StringEnumColumn(Allocator&, ref_type ref, ref_type keys_ref, bool nullable, size_t column_ndx = npos); + ~StringEnumColumn() noexcept override; + void destroy() noexcept override; + MemRef clone_deep(Allocator& alloc) const override; + + int compare_values(size_t row1, size_t row2) const noexcept override + { + StringData a = get(row1); + StringData b = get(row2); + + if (a.is_null() && !b.is_null()) + return 1; + else if (b.is_null() && !a.is_null()) + return -1; + else if (a.is_null() && b.is_null()) + return 0; + + if (a == b) + return 0; + + return utf8_compare(a, b) ? 1 : -1; + } + + StringData get(size_t ndx) const noexcept; + bool is_null(size_t ndx) const noexcept final; + void set(size_t ndx, StringData value); + void set_null(size_t ndx) override; + void add(); + void add(StringData value); + void insert(size_t ndx); + void insert(size_t ndx, StringData value); + void erase(size_t row_ndx); + void move_last_over(size_t row_ndx); + void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override; + void clear(); + bool is_nullable() const noexcept final; + + size_t count(StringData value) const; + size_t find_first(StringData value, size_t begin = 0, size_t end = npos) const; + void find_all(IntegerColumn& res, StringData value, size_t begin = 0, size_t end = npos) const; + FindRes find_all_no_copy(StringData value, InternalFindResult& result) const; + + size_t count(size_t key_index) const; + size_t find_first(size_t key_index, size_t begin = 0, size_t end = -1) const; + void find_all(IntegerColumn& res, size_t key_index, size_t begin = 0, size_t end = -1) const; + + //@{ + /// Find the lower/upper bound for the specified value assuming + /// that the elements are already sorted in ascending order + /// according to StringData::operator<(). + size_t lower_bound_string(StringData value) const noexcept; + size_t upper_bound_string(StringData value) const noexcept; + //@} + + void set_string(size_t, StringData) override; + + void adjust_keys_ndx_in_parent(int diff) noexcept; + + // Search index + StringData get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept final; + bool supports_search_index() const noexcept final + { + return true; + } + StringIndex* create_search_index() override; + void install_search_index(std::unique_ptr) noexcept; + void destroy_search_index() noexcept override; + + // Compare two string columns for equality + bool compare_string(const StringColumn&) const; + bool compare_string(const StringEnumColumn&) const; + + void insert_rows(size_t, size_t, size_t, bool) override; + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + void clear(size_t, bool) override; + void update_from_parent(size_t) noexcept override; + void refresh_accessor_tree(size_t, const Spec&) override; + + size_t get_key_ndx(StringData value) const; + size_t get_key_ndx_or_add(StringData value); + + StringColumn& get_keys(); + const StringColumn& get_keys() const; + +#ifdef REALM_DEBUG + void verify() const override; + void verify(const Table&, size_t) const override; + void do_dump_node_structure(std::ostream&, int) const override; + void to_dot(std::ostream&, StringData title) const override; +#endif + +private: + // Member variables + StringColumn m_keys; + bool m_nullable; + + /// If you are appending and have the size of the column readily available, + /// call the 4 argument version instead. If you are not appending, either + /// one is fine. + /// + /// \param row_ndx Must be `realm::npos` if appending. + void do_insert(size_t row_ndx, StringData value, size_t num_rows); + + /// If you are appending and you do not have the size of the column readily + /// available, call the 3 argument version instead. If you are not + /// appending, either one is fine. + /// + /// \param is_append Must be true if, and only if `row_ndx` is equal to the + /// size of the column (before insertion). + void do_insert(size_t row_ndx, StringData value, size_t num_rows, bool is_append); + + void do_erase(size_t row_ndx, bool is_last); + void do_move_last_over(size_t row_ndx, size_t last_row_ndx); + void do_clear(); +}; + + +// Implementation: + +inline StringData StringEnumColumn::get(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, IntegerColumn::size()); + size_t key_ndx = to_size_t(IntegerColumn::get(ndx)); + StringData sd = m_keys.get(key_ndx); + REALM_ASSERT_DEBUG(!(!m_nullable && sd.is_null())); + return sd; +} + +inline bool StringEnumColumn::is_null(size_t ndx) const noexcept +{ + return is_nullable() && get(ndx).is_null(); +} + +inline void StringEnumColumn::add() +{ + add(m_nullable ? realm::null() : StringData("")); +} + +inline void StringEnumColumn::add(StringData value) +{ + REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); + size_t row_ndx = realm::npos; + size_t num_rows = 1; + do_insert(row_ndx, value, num_rows); // Throws +} + +inline void StringEnumColumn::insert(size_t row_ndx) +{ + insert(row_ndx, m_nullable ? realm::null() : StringData("")); +} + +inline void StringEnumColumn::insert(size_t row_ndx, StringData value) +{ + REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); + size_t column_size = this->size(); + REALM_ASSERT_3(row_ndx, <=, column_size); + size_t num_rows = 1; + bool is_append = row_ndx == column_size; + do_insert(row_ndx, value, num_rows, is_append); // Throws +} + +inline void StringEnumColumn::erase(size_t row_ndx) +{ + size_t last_row_ndx = size() - 1; // Note that size() is slow + bool is_last = row_ndx == last_row_ndx; + do_erase(row_ndx, is_last); // Throws +} + +inline void StringEnumColumn::move_last_over(size_t row_ndx) +{ + size_t last_row_ndx = size() - 1; // Note that size() is slow + do_move_last_over(row_ndx, last_row_ndx); // Throws +} + +inline void StringEnumColumn::clear() +{ + do_clear(); // Throws +} + +// Overriding virtual method of Column. +inline void StringEnumColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, + bool insert_nulls) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx <= prior_num_rows); + REALM_ASSERT(!insert_nulls || m_nullable); + + StringData value = m_nullable ? realm::null() : StringData(""); + bool is_append = (row_ndx == prior_num_rows); + do_insert(row_ndx, value, num_rows_to_insert, is_append); // Throws +} + +// Overriding virtual method of Column. +inline void StringEnumColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(num_rows_to_erase <= prior_num_rows); + REALM_ASSERT(row_ndx <= prior_num_rows - num_rows_to_erase); + + bool is_last = (row_ndx + num_rows_to_erase == prior_num_rows); + for (size_t i = num_rows_to_erase; i > 0; --i) { + size_t row_ndx_2 = row_ndx + i - 1; + do_erase(row_ndx_2, is_last); // Throws + } +} + +// Overriding virtual method of Column. +inline void StringEnumColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx < prior_num_rows); + + size_t last_row_ndx = prior_num_rows - 1; + do_move_last_over(row_ndx, last_row_ndx); // Throws +} + +// Overriding virtual method of Column. +inline void StringEnumColumn::clear(size_t, bool) +{ + do_clear(); // Throws +} + +inline size_t StringEnumColumn::lower_bound_string(StringData value) const noexcept +{ + return ColumnBase::lower_bound(*this, value); +} + +inline size_t StringEnumColumn::upper_bound_string(StringData value) const noexcept +{ + return ColumnBase::upper_bound(*this, value); +} + +inline void StringEnumColumn::set_string(size_t row_ndx, StringData value) +{ + set(row_ndx, value); // Throws +} + +inline void StringEnumColumn::set_null(size_t row_ndx) +{ + set(row_ndx, realm::null{}); +} + +inline StringColumn& StringEnumColumn::get_keys() +{ + return m_keys; +} + +inline const StringColumn& StringEnumColumn::get_keys() const +{ + return m_keys; +} + + +} // namespace realm + +#endif // REALM_COLUMN_STRING_ENUM_HPP diff --git a/Pods/Realm/include/core/realm/column_table.hpp b/Pods/Realm/include/core/realm/column_table.hpp new file mode 100644 index 0000000000..0d424c2713 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_table.hpp @@ -0,0 +1,693 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_TABLE_HPP +#define REALM_COLUMN_TABLE_HPP + +#include +#include + +#include +#include +#include +#include + +namespace realm { + + +/// Base class for any type of column that can contain subtables. +// FIXME: Don't derive from IntegerColumn, but define a BpTree specialization. +class SubtableColumnBase : public IntegerColumn, public Table::Parent { +public: + void discard_child_accessors() noexcept; + + ~SubtableColumnBase() noexcept override; + + static ref_type create(Allocator&, size_t size = 0); + + TableRef get_subtable_accessor(size_t) const noexcept override; + + void insert_rows(size_t, size_t, size_t, bool) override; + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + void clear(size_t, bool) override; + void swap_rows(size_t, size_t) override; + void discard_subtable_accessor(size_t) noexcept override; + void update_from_parent(size_t) noexcept override; + void adj_acc_insert_rows(size_t, size_t) noexcept override; + void adj_acc_erase_row(size_t) noexcept override; + void adj_acc_move_over(size_t, size_t) noexcept override; + void adj_acc_clear_root_table() noexcept override; + void adj_acc_swap_rows(size_t, size_t) noexcept override; + void adj_acc_move_row(size_t, size_t) noexcept override; + void mark(int) noexcept override; + bool supports_search_index() const noexcept override + { + return false; + } + StringIndex* create_search_index() override + { + return nullptr; + } + bool is_null(size_t ndx) const noexcept override + { + return get_as_ref(ndx) == 0; + } + + void verify() const override; + void verify(const Table&, size_t) const override; + +protected: + /// A pointer to the table that this column is part of. For a free-standing + /// column, this pointer is null. + Table* const m_table; + + struct SubtableMap { + bool empty() const noexcept + { + return m_entries.empty(); + } + Table* find(size_t subtable_ndx) const noexcept; + void add(size_t subtable_ndx, Table*); + // Returns true if, and only if at least one entry was detached and + // removed from the map. + bool detach_and_remove_all() noexcept; + // Returns true if, and only if the entry was found and removed, and it + // was the last entry in the map. + bool detach_and_remove(size_t subtable_ndx) noexcept; + // Returns true if, and only if the entry was found and removed, and it + // was the last entry in the map. + bool remove(Table*) noexcept; + void update_from_parent(size_t old_baseline) const noexcept; + template + void adj_insert_rows(size_t row_ndx, size_t num_rows_inserted) noexcept; + // Returns true if, and only if an entry was found and removed, and it + // was the last entry in the map. + template + bool adj_erase_rows(size_t row_ndx, size_t num_rows_erased) noexcept; + // Returns true if, and only if an entry was found and removed, and it + // was the last entry in the map. + template + bool adj_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; + template + void adj_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; + template + void adj_move_row(size_t from_ndx, size_t to_ndx) noexcept; + void adj_set_null(size_t row_ndx) noexcept; + + void update_accessors(const size_t* col_path_begin, const size_t* col_path_end, + _impl::TableFriend::AccessorUpdater&); + void recursive_mark() noexcept; + void refresh_accessor_tree(); + void verify(const SubtableColumn& parent); + + private: + struct SubtableEntry { + size_t m_subtable_ndx; + Table* m_table; + }; + typedef std::vector entries; + entries m_entries; + }; + + /// Contains all existing accessors that are attached to a subtable in this + /// column. It can map a row index into a pointer to the corresponding + /// accessor when it exists. + /// + /// There is an invariant in force: Either `m_table` is null, or there is an + /// additional referece count on `*m_table` when, and only when the map is + /// non-empty. + mutable SubtableMap m_subtable_map; + mutable std::recursive_mutex m_subtable_map_lock; + + SubtableColumnBase(Allocator&, ref_type, Table*, size_t column_ndx); + + /// Get a TableRef to the accessor of the specified subtable. The + /// accessor will be created if it does not already exist. + /// + /// NOTE: This method must be used only for subtables with + /// independent specs, i.e. for elements of a MixedColumn. + TableRef get_subtable_tableref(size_t subtable_ndx); + + // Overriding method in ArrayParent + void update_child_ref(size_t, ref_type) override; + + // Overriding method in ArrayParent + ref_type get_child_ref(size_t) const noexcept override; + + // Overriding method in Table::Parent + Table* get_parent_table(size_t*) noexcept override; + + // Overriding method in Table::Parent + void child_accessor_destroyed(Table*) noexcept override; + + // Overriding method in Table::Parent + std::recursive_mutex* get_accessor_management_lock() noexcept override + { return &m_subtable_map_lock; } + + /// Assumes that the two tables have the same spec. + static bool compare_subtable_rows(const Table&, const Table&); + + /// Construct a copy of the columns array of the specified table + /// and return just the ref to that array. + /// + /// In the clone, no string column will be of the enumeration + /// type. + ref_type clone_table_columns(const Table*); + + size_t* record_subtable_path(size_t* begin, size_t* end) noexcept override; + + void update_table_accessors(const size_t* col_path_begin, const size_t* col_path_end, + _impl::TableFriend::AccessorUpdater&); + + /// \param row_ndx Must be `realm::npos` if appending. + /// \param value The value to place in any newly created rows. + /// \param num_rows The number of rows to insert. + void do_insert(size_t row_ndx, int_fast64_t value, size_t num_rows); + + std::pair get_to_dot_parent(size_t ndx_in_parent) const override; + + friend class Table; +}; + + +class SubtableColumn : public SubtableColumnBase { +public: + using value_type = ConstTableRef; + /// Create a subtable column accessor and attach it to a + /// preexisting underlying structure of arrays. + /// + /// \param alloc The allocator to provide new memory. + /// + /// \param ref The memory reference of the underlying subtable that + /// we are creating an accessor for. + /// + /// \param table If this column is used as part of a table you must + /// pass a pointer to that table. Otherwise you must pass null. + /// + /// \param column_ndx If this column is used as part of a table + /// you must pass the logical index of the column within that + /// table. Otherwise you should pass zero. + SubtableColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); + + ~SubtableColumn() noexcept override + { + } + + // Overriding method in Table::Parent + Spec* get_subtable_spec() noexcept override; + + size_t get_subtable_size(size_t ndx) const noexcept; + + /// Get a TableRef to the accessor of the specified subtable. The + /// accessor will be created if it does not already exist. + TableRef get_subtable_tableref(size_t subtable_ndx); + + ConstTableRef get_subtable_tableref(size_t subtable_ndx) const; + + /// This is to be used by the query system that does not need to + /// modify the subtable. Will return a ref object containing a + /// nullptr if there is no table object yet. + ConstTableRef get(size_t subtable_ndx) const + { + int64_t ref = IntegerColumn::get(subtable_ndx); + if (ref) + return get_subtable_tableref(subtable_ndx); + else + return {}; + } + + // When passing a table to add() or insert() it is assumed that + // the table spec is compatible with this column. The number of + // columns must be the same, and the corresponding columns must + // have the same data type (as returned by + // Table::get_column_type()). + + void add(const Table* value = nullptr); + void insert(size_t ndx, const Table* value = nullptr); + void set(size_t ndx, const Table*); + void clear_table(size_t ndx); + void set_null(size_t ndx) override; + + using SubtableColumnBase::insert; + + void erase_rows(size_t, size_t, size_t, bool) override; + void move_last_row_over(size_t, size_t, bool) override; + + /// Compare two subtable columns for equality. + bool compare_table(const SubtableColumn&) const; + + void refresh_accessor_tree(size_t, const Spec&) override; + void refresh_subtable_map(); + +#ifdef REALM_DEBUG + void verify(const Table&, size_t) const override; + void do_dump_node_structure(std::ostream&, int) const override; + void to_dot(std::ostream&, StringData title) const override; +#endif + +private: + mutable size_t m_subspec_ndx; // Unknown if equal to `npos` + + size_t get_subspec_ndx() const noexcept; + + void destroy_subtable(size_t ndx) noexcept; + + void do_discard_child_accessors() noexcept override; +}; + + +// Implementation + +// Overriding virtual method of Column. +inline void SubtableColumnBase::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool) +{ + REALM_ASSERT_DEBUG(prior_num_rows == size()); + REALM_ASSERT(row_ndx <= prior_num_rows); + + size_t row_ndx_2 = (row_ndx == prior_num_rows ? realm::npos : row_ndx); + int_fast64_t value = 0; + do_insert(row_ndx_2, value, num_rows_to_insert); // Throws +} + +// Overriding virtual method of Column. +inline void SubtableColumnBase::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, + bool broken_reciprocal_backlinks) +{ + IntegerColumn::erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks); // Throws + + std::lock_guard lg(m_subtable_map_lock); + const bool fix_ndx_in_parent = true; + bool last_entry_removed = m_subtable_map.adj_erase_rows(row_ndx, num_rows_to_erase); + typedef _impl::TableFriend tf; + if (last_entry_removed) + tf::unbind_ptr(*m_table); +} + +// Overriding virtual method of Column. +inline void SubtableColumnBase::move_last_row_over(size_t row_ndx, size_t prior_num_rows, + bool broken_reciprocal_backlinks) +{ + IntegerColumn::move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks); // Throws + + std::lock_guard lg(m_subtable_map_lock); + const bool fix_ndx_in_parent = true; + size_t last_row_ndx = prior_num_rows - 1; + bool last_entry_removed = m_subtable_map.adj_move_over(last_row_ndx, row_ndx); + typedef _impl::TableFriend tf; + if (last_entry_removed) + tf::unbind_ptr(*m_table); +} + +inline void SubtableColumnBase::clear(size_t, bool) +{ + discard_child_accessors(); + clear_without_updating_index(); // Throws + // FIXME: This one is needed because + // IntegerColumn::clear_without_updating_index() forgets about the + // leaf type. A better solution should probably be sought after. + get_root_array()->set_type(Array::type_HasRefs); +} + +inline void SubtableColumnBase::swap_rows(size_t row_ndx_1, size_t row_ndx_2) +{ + IntegerColumn::swap_rows(row_ndx_1, row_ndx_2); // Throws + + std::lock_guard lg(m_subtable_map_lock); + const bool fix_ndx_in_parent = true; + m_subtable_map.adj_swap_rows(row_ndx_1, row_ndx_2); +} + +inline void SubtableColumnBase::mark(int type) noexcept +{ + if (type & mark_Recursive) { + std::lock_guard lg(m_subtable_map_lock); + m_subtable_map.recursive_mark(); + } +} + +inline void SubtableColumnBase::adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept +{ + // This function must assume no more than minimal consistency of the + // accessor hierarchy. This means in particular that it cannot access the + // underlying node structure. See AccessorConsistencyLevels. + + std::lock_guard lg(m_subtable_map_lock); + const bool fix_ndx_in_parent = false; + m_subtable_map.adj_insert_rows(row_ndx, num_rows); +} + +inline void SubtableColumnBase::adj_acc_erase_row(size_t row_ndx) noexcept +{ + // This function must assume no more than minimal consistency of the + // accessor hierarchy. This means in particular that it cannot access the + // underlying node structure. See AccessorConsistencyLevels. + + std::lock_guard lg(m_subtable_map_lock); + const bool fix_ndx_in_parent = false; + size_t num_rows_erased = 1; + bool last_entry_removed = m_subtable_map.adj_erase_rows(row_ndx, num_rows_erased); + typedef _impl::TableFriend tf; + if (last_entry_removed) + tf::unbind_ptr(*m_table); +} + +inline void SubtableColumnBase::adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept +{ + // This function must assume no more than minimal consistency of the + // accessor hierarchy. This means in particular that it cannot access the + // underlying node structure. See AccessorConsistencyLevels. + + std::lock_guard lg(m_subtable_map_lock); + const bool fix_ndx_in_parent = false; + bool last_entry_removed = m_subtable_map.adj_move_over(from_row_ndx, to_row_ndx); + typedef _impl::TableFriend tf; + if (last_entry_removed) + tf::unbind_ptr(*m_table); +} + +inline void SubtableColumnBase::adj_acc_clear_root_table() noexcept +{ + // This function must assume no more than minimal consistency of the + // accessor hierarchy. This means in particular that it cannot access the + // underlying node structure. See AccessorConsistencyLevels. + + IntegerColumn::adj_acc_clear_root_table(); + discard_child_accessors(); +} + +inline void SubtableColumnBase::adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept +{ + std::lock_guard lg(m_subtable_map_lock); + const bool fix_ndx_in_parent = false; + m_subtable_map.adj_swap_rows(row_ndx_1, row_ndx_2); +} + +inline void SubtableColumnBase::adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept +{ + std::lock_guard lg(m_subtable_map_lock); + const bool fix_ndx_in_parent = false; + m_subtable_map.adj_move_row(from_ndx, to_ndx); +} + +inline TableRef SubtableColumnBase::get_subtable_accessor(size_t row_ndx) const noexcept +{ + // This function must assume no more than minimal consistency of the + // accessor hierarchy. This means in particular that it cannot access the + // underlying node structure. See AccessorConsistencyLevels. + std::lock_guard lg(m_subtable_map_lock); + TableRef subtable(m_subtable_map.find(row_ndx)); + return subtable; +} + +inline void SubtableColumnBase::discard_subtable_accessor(size_t row_ndx) noexcept +{ + // This function must assume no more than minimal consistency of the + // accessor hierarchy. This means in particular that it cannot access the + // underlying node structure. See AccessorConsistencyLevels. + + std::lock_guard lg(m_subtable_map_lock); + bool last_entry_removed = m_subtable_map.detach_and_remove(row_ndx); + typedef _impl::TableFriend tf; + if (last_entry_removed) + tf::unbind_ptr(*m_table); +} + +inline void SubtableColumnBase::SubtableMap::add(size_t subtable_ndx, Table* table) +{ + SubtableEntry e; + e.m_subtable_ndx = subtable_ndx; + e.m_table = table; + m_entries.push_back(e); +} + +template +void SubtableColumnBase::SubtableMap::adj_insert_rows(size_t row_ndx, size_t num_rows_inserted) noexcept +{ + for (auto& entry : m_entries) { + if (entry.m_subtable_ndx >= row_ndx) { + entry.m_subtable_ndx += num_rows_inserted; + typedef _impl::TableFriend tf; + if (fix_ndx_in_parent) + tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); + } + } +} + +template +bool SubtableColumnBase::SubtableMap::adj_erase_rows(size_t row_ndx, size_t num_rows_erased) noexcept +{ + if (m_entries.empty()) + return false; + typedef _impl::TableFriend tf; + auto end = m_entries.end(); + auto i = m_entries.begin(); + do { + if (i->m_subtable_ndx >= row_ndx + num_rows_erased) { + i->m_subtable_ndx -= num_rows_erased; + if (fix_ndx_in_parent) + tf::set_ndx_in_parent(*(i->m_table), i->m_subtable_ndx); + } + else if (i->m_subtable_ndx >= row_ndx) { + // Must hold a counted reference while detaching + TableRef table(i->m_table); + tf::detach(*table); + // Move last over + *i = *--end; + continue; + } + ++i; + } while (i != end); + m_entries.erase(end, m_entries.end()); + return m_entries.empty(); +} + + +template +bool SubtableColumnBase::SubtableMap::adj_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept +{ + typedef _impl::TableFriend tf; + + size_t i = 0, n = m_entries.size(); + // We return true if, and only if we remove the last entry in the map. We + // need special handling for the case, where the set of entries are already + // empty, otherwise the final return statement would return true in this + // case, even though we didn't actually remove an entry. + if (n == 0) + return false; + + while (i < n) { + SubtableEntry& e = m_entries[i]; + if (REALM_UNLIKELY(e.m_subtable_ndx == to_row_ndx)) { + // Must hold a counted reference while detaching + TableRef table(e.m_table); + tf::detach(*table); + // Delete entry by moving last over (faster and avoids invalidating + // iterators) + e = m_entries[--n]; + m_entries.pop_back(); + } + else { + if (REALM_UNLIKELY(e.m_subtable_ndx == from_row_ndx)) { + e.m_subtable_ndx = to_row_ndx; + if (fix_ndx_in_parent) + tf::set_ndx_in_parent(*(e.m_table), e.m_subtable_ndx); + } + ++i; + } + } + return m_entries.empty(); +} + +template +void SubtableColumnBase::SubtableMap::adj_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept +{ + using tf = _impl::TableFriend; + for (auto& entry : m_entries) { + if (REALM_UNLIKELY(entry.m_subtable_ndx == row_ndx_1)) { + entry.m_subtable_ndx = row_ndx_2; + if (fix_ndx_in_parent) + tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); + } + else if (REALM_UNLIKELY(entry.m_subtable_ndx == row_ndx_2)) { + entry.m_subtable_ndx = row_ndx_1; + if (fix_ndx_in_parent) + tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); + } + } +} + + +template +void SubtableColumnBase::SubtableMap::adj_move_row(size_t from_ndx, size_t to_ndx) noexcept +{ + using tf = _impl::TableFriend; + for (auto& entry : m_entries) { + if (entry.m_subtable_ndx == from_ndx) { + entry.m_subtable_ndx = to_ndx; + if (fix_ndx_in_parent) + tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); + } + else { + if (from_ndx < to_ndx) { + // shift the range (from, to] down one + if (entry.m_subtable_ndx <= to_ndx && entry.m_subtable_ndx > from_ndx) { + entry.m_subtable_ndx--; + if (fix_ndx_in_parent) { + tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); + } + } + } else if (from_ndx > to_ndx) { + // shift the range (from, to] up one + if (entry.m_subtable_ndx >= to_ndx && entry.m_subtable_ndx < from_ndx) { + entry.m_subtable_ndx++; + if (fix_ndx_in_parent) { + tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); + } + } + } + } + } +} + +inline void SubtableColumnBase::SubtableMap::adj_set_null(size_t row_ndx) noexcept +{ + Table* table = find(row_ndx); + if (table) + _impl::TableFriend::refresh_accessor_tree(*table); +} + +inline SubtableColumnBase::SubtableColumnBase(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) + : IntegerColumn(alloc, ref, column_ndx) // Throws + , m_table(table) +{ +} + +inline void SubtableColumnBase::update_child_ref(size_t child_ndx, ref_type new_ref) +{ + set_as_ref(child_ndx, new_ref); +} + +inline ref_type SubtableColumnBase::get_child_ref(size_t child_ndx) const noexcept +{ + return get_as_ref(child_ndx); +} + +inline void SubtableColumnBase::discard_child_accessors() noexcept +{ + std::lock_guard lg(m_subtable_map_lock); + bool last_entry_removed = m_subtable_map.detach_and_remove_all(); + if (last_entry_removed && m_table) + _impl::TableFriend::unbind_ptr(*m_table); +} + +inline SubtableColumnBase::~SubtableColumnBase() noexcept +{ + discard_child_accessors(); +} + +inline bool SubtableColumnBase::compare_subtable_rows(const Table& a, const Table& b) +{ + return _impl::TableFriend::compare_rows(a, b); +} + +inline ref_type SubtableColumnBase::clone_table_columns(const Table* t) +{ + return _impl::TableFriend::clone_columns(*t, get_root_array()->get_alloc()); +} + +inline ref_type SubtableColumnBase::create(Allocator& alloc, size_t size) +{ + return IntegerColumn::create(alloc, Array::type_HasRefs, size); // Throws +} + +inline size_t* SubtableColumnBase::record_subtable_path(size_t* begin, size_t* end) noexcept +{ + if (end == begin) + return 0; // Error, not enough space in buffer + *begin++ = get_column_index(); + if (end == begin) + return 0; // Error, not enough space in buffer + return _impl::TableFriend::record_subtable_path(*m_table, begin, end); +} + +inline void SubtableColumnBase::update_table_accessors(const size_t* col_path_begin, const size_t* col_path_end, + _impl::TableFriend::AccessorUpdater& updater) +{ + // This function must assume no more than minimal consistency of the + // accessor hierarchy. This means in particular that it cannot access the + // underlying node structure. See AccessorConsistencyLevels. + + m_subtable_map.update_accessors(col_path_begin, col_path_end, updater); // Throws +} + +inline void SubtableColumnBase::do_insert(size_t row_ndx, int_fast64_t value, size_t num_rows) +{ + IntegerColumn::insert_without_updating_index(row_ndx, value, num_rows); // Throws + bool is_append = row_ndx == realm::npos; + if (!is_append) { + const bool fix_ndx_in_parent = true; + m_subtable_map.adj_insert_rows(row_ndx, num_rows); + } +} + + +inline SubtableColumn::SubtableColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) + : SubtableColumnBase(alloc, ref, table, column_ndx) + , m_subspec_ndx(realm::npos) +{ +} + +inline ConstTableRef SubtableColumn::get_subtable_tableref(size_t subtable_ndx) const +{ + return const_cast(this)->get_subtable_tableref(subtable_ndx); +} + +inline void SubtableColumn::refresh_accessor_tree(size_t col_ndx, const Spec& spec) +{ + SubtableColumnBase::refresh_accessor_tree(col_ndx, spec); // Throws + m_subspec_ndx = spec.get_subspec_ndx(col_ndx); + std::lock_guard lg(m_subtable_map_lock); + m_subtable_map.refresh_accessor_tree(); // Throws +} + +inline void SubtableColumn::refresh_subtable_map() +{ + std::lock_guard lg(m_subtable_map_lock); + m_subtable_map.refresh_accessor_tree(); // Throws +} + +inline size_t SubtableColumn::get_subspec_ndx() const noexcept +{ + if (REALM_UNLIKELY(m_subspec_ndx == realm::npos)) { + typedef _impl::TableFriend tf; + m_subspec_ndx = tf::get_spec(*m_table).get_subspec_ndx(get_column_index()); + } + return m_subspec_ndx; +} + +inline Spec* SubtableColumn::get_subtable_spec() noexcept +{ + typedef _impl::TableFriend tf; + return tf::get_spec(*m_table).get_subtable_spec(get_column_index()); +} + + +} // namespace realm + +#endif // REALM_COLUMN_TABLE_HPP diff --git a/Pods/Realm/include/core/realm/column_timestamp.hpp b/Pods/Realm/include/core/realm/column_timestamp.hpp new file mode 100644 index 0000000000..d5c4859d76 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_timestamp.hpp @@ -0,0 +1,155 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_TIMESTAMP_HPP +#define REALM_COLUMN_TIMESTAMP_HPP + +#include +#include + +namespace realm { + +// Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the +// column type +class TimestampColumn : public ColumnBaseSimple { +public: + TimestampColumn(bool nullable, Allocator& alloc, ref_type ref, size_t col_ndx = npos); + + static ref_type create(Allocator& alloc, size_t size, bool nullable); + static size_t get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept; + + /// Get the number of entries in this column. This operation is relatively + /// slow. + size_t size() const noexcept override; + /// Whether or not this column is nullable. + bool is_nullable() const noexcept override; + /// Whether or not the value at \a row_ndx is NULL. If the column is not + /// nullable, always returns false. + bool is_null(size_t row_ndx) const noexcept override; + /// Sets the value at \a row_ndx to be NULL. + /// \throw LogicError Thrown if this column is not nullable. + void set_null(size_t row_ndx) override; + void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override; + void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, + bool broken_reciprocal_backlinks) override; + void move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool broken_reciprocal_backlinks) override; + void clear(size_t num_rows, bool broken_reciprocal_backlinks) override; + void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override; + void destroy() noexcept override; + + bool has_search_index() const noexcept final + { + return bool(m_search_index); + } + StringIndex* get_search_index() noexcept final + { + return m_search_index.get(); + } + StringIndex* get_search_index() const noexcept final + { + return m_search_index.get(); + } + void destroy_search_index() noexcept override; + void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent) final; + void populate_search_index(); + StringIndex* create_search_index() override; + bool supports_search_index() const noexcept final + { + return true; + } + + StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override; + ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override; + void update_from_parent(size_t old_baseline) noexcept override; + void set_ndx_in_parent(size_t ndx) noexcept override; + void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override; + + void verify() const override; + void to_dot(std::ostream&, StringData title = StringData()) const override; + void do_dump_node_structure(std::ostream&, int level) const override; + void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override; + + void add(const Timestamp& ts = Timestamp{}); + Timestamp get(size_t row_ndx) const noexcept; + void set(size_t row_ndx, const Timestamp& ts); + bool compare(const TimestampColumn& c) const noexcept; + int compare_values(size_t row1, size_t row2) const noexcept override; + + Timestamp maximum(size_t* result_index) const; + Timestamp minimum(size_t* result_index) const; + size_t count(Timestamp) const; + void erase(size_t row_ndx, bool is_last); + + template + size_t find(Timestamp value, size_t begin, size_t end) const noexcept + { + // FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match + // check nanoseconds, etc. Lots of possibilities. Below code is naive and slow but works. + + Condition cond; + for (size_t t = begin; t < end; t++) { + Timestamp ts = get(t); + if (cond(ts, value, ts.is_null(), value.is_null())) + return t; + } + return npos; + } + + typedef Timestamp value_type; + +private: + std::unique_ptr>> m_seconds; + std::unique_ptr> m_nanoseconds; + + std::unique_ptr m_search_index; + bool m_nullable; + + template + class CreateHandler; + + template + Timestamp minmax(size_t* result_index) const noexcept + { + // Condition is realm::Greater for maximum and realm::Less for minimum. Any non-null value is both larger + // and smaller than a null value. + if (size() == 0) { + if (result_index) + *result_index = npos; + return Timestamp{}; + } + + Timestamp best = get(0); + size_t best_index = best.is_null() ? npos : 0; + + for (size_t i = 1; i < size(); ++i) { + Timestamp candidate = get(i); + // Condition() will return false if any of the two values are null. + if ((best.is_null() && !candidate.is_null()) || Condition()(candidate, best, candidate.is_null(), best.is_null())) { + best = candidate; + best_index = i; + } + } + if (result_index) + *result_index = best_index; + return best; + } +}; + +} // namespace realm + +#endif // REALM_COLUMN_TIMESTAMP_HPP diff --git a/Pods/Realm/include/core/realm/column_tpl.hpp b/Pods/Realm/include/core/realm/column_tpl.hpp new file mode 100644 index 0000000000..2411007d73 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_tpl.hpp @@ -0,0 +1,143 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_TPL_HPP +#define REALM_COLUMN_TPL_HPP + +#include + +#include +#include +#include + +namespace realm { + +template +class FloatDoubleNode; +template +class IntegerNode; +template +class SequentialGetter; + +template +struct ColumnTypeTraits2; + +template +struct ColumnTypeTraits2 { + typedef IntegerColumn column_type; + typedef ArrayInteger array_type; +}; +template +struct ColumnTypeTraits2 { + typedef IntegerColumn column_type; + typedef ArrayInteger array_type; +}; +template +struct ColumnTypeTraits2 { + typedef FloatColumn column_type; + typedef ArrayFloat array_type; +}; +template +struct ColumnTypeTraits2 { + typedef DoubleColumn column_type; + typedef ArrayDouble array_type; +}; + + +namespace _impl { + +template +struct FindInLeaf { + using LeafType = typename ColType::LeafType; + + template + static bool find(const LeafType& leaf, T target, size_t local_start, size_t local_end, size_t leaf_start, + QueryState& state) + { + Condition cond; + bool cont = true; + // todo, make an additional loop with hard coded `false` instead of is_null(v) for non-nullable columns + bool null_target = null::is_null_float(target); + for (size_t local_index = local_start; cont && local_index < local_end; local_index++) { + auto v = leaf.get(local_index); + if (cond(v, target, null::is_null_float(v), null_target)) { + cont = state.template match(leaf_start + local_index, 0, static_cast(v)); + } + } + return cont; + } +}; + +template <> +struct FindInLeaf { + using LeafType = IntegerColumn::LeafType; + + template + static bool find(const LeafType& leaf, T target, size_t local_start, size_t local_end, size_t leaf_start, + QueryState& state) + { + const int c = Condition::condition; + return leaf.find(c, action, target, local_start, local_end, leaf_start, &state); + } +}; + +template <> +struct FindInLeaf { + using LeafType = IntNullColumn::LeafType; + + template + static bool find(const LeafType& leaf, T target, size_t local_start, size_t local_end, size_t leaf_start, + QueryState& state) + { + constexpr int cond = Condition::condition; + return leaf.find(cond, action, target, local_start, local_end, leaf_start, &state); + } +}; + +} // namespace _impl + +template +R aggregate(const ColType& column, T target, size_t start, size_t end, size_t limit, size_t* return_ndx) +{ + if (end == npos) + end = column.size(); + + QueryState state; + state.init(action, nullptr, limit); + SequentialGetter sg{&column}; + + bool cont = true; + for (size_t s = start; cont && s < end;) { + sg.cache_next(s); + size_t start2 = s - sg.m_leaf_start; + size_t end2 = sg.local_end(end); + cont = _impl::FindInLeaf::template find(*sg.m_leaf_ptr, target, start2, end2, + sg.m_leaf_start, state); + s = sg.m_leaf_start + end2; + } + + if (return_ndx) + *return_ndx = action == act_Sum ? state.m_match_count : state.m_minmax_index; + + return state.m_state; +} + + +} // namespace realm + +#endif // REALM_COLUMN_TPL_HPP diff --git a/Pods/Realm/include/core/realm/column_type.hpp b/Pods/Realm/include/core/realm/column_type.hpp new file mode 100644 index 0000000000..5a6e21cb2d --- /dev/null +++ b/Pods/Realm/include/core/realm/column_type.hpp @@ -0,0 +1,70 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_TYPE_HPP +#define REALM_COLUMN_TYPE_HPP + +namespace realm { + + +// Note: Enumeration value assignments must be kept in sync with +// . +enum ColumnType { + // Column types + col_type_Int = 0, + col_type_Bool = 1, + col_type_String = 2, + col_type_StringEnum = 3, // double refs + col_type_Binary = 4, + col_type_Table = 5, + col_type_Mixed = 6, + col_type_OldDateTime = 7, + col_type_Timestamp = 8, + col_type_Float = 9, + col_type_Double = 10, + col_type_Reserved4 = 11, // Decimal + col_type_Link = 12, + col_type_LinkList = 13, + col_type_BackLink = 14 +}; + + +// Column attributes can be combined using bitwise or. +enum ColumnAttr { + col_attr_None = 0, + col_attr_Indexed = 1, + + /// Specifies that this column forms a unique constraint. It requires + /// `col_attr_Indexed`. + col_attr_Unique = 2, + + /// Reserved for future use. + col_attr_Reserved = 4, + + /// Specifies that the links of this column are strong, not weak. Applies + /// only to link columns (`type_Link` and `type_LinkList`). + col_attr_StrongLinks = 8, + + /// Specifies that elements in the column can be null. + col_attr_Nullable = 16 +}; + + +} // namespace realm + +#endif // REALM_COLUMN_TYPE_HPP diff --git a/Pods/Realm/include/core/realm/column_type_traits.hpp b/Pods/Realm/include/core/realm/column_type_traits.hpp new file mode 100644 index 0000000000..39a32086f7 --- /dev/null +++ b/Pods/Realm/include/core/realm/column_type_traits.hpp @@ -0,0 +1,160 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_COLUMN_TYPE_TRAITS_HPP +#define REALM_COLUMN_TYPE_TRAITS_HPP + +#include +#include +#include +#include + +namespace realm { + +class OldDateTime; +class ArrayBinary; +class ArrayInteger; +class ArrayIntNull; +template +class BasicArray; + +template +struct ColumnTypeTraits; + +template <> +struct ColumnTypeTraits { + using column_type = Column; + using leaf_type = ArrayInteger; + using sum_type = int64_t; + using minmax_type = int64_t; + static const DataType id = type_Int; + static const ColumnType column_id = col_type_Int; + static const ColumnType real_column_type = col_type_Int; +}; + +template <> +struct ColumnTypeTraits> { + using column_type = Column>; + using leaf_type = ArrayIntNull; + using sum_type = int64_t; + using minmax_type = int64_t; + static const DataType id = type_Int; + static const ColumnType column_id = col_type_Int; + static const ColumnType real_column_type = col_type_Int; +}; + +template <> +struct ColumnTypeTraits : ColumnTypeTraits { + static const DataType id = type_Bool; + static const ColumnType column_id = col_type_Bool; +}; + +template <> +struct ColumnTypeTraits> : ColumnTypeTraits> { + static const DataType id = type_Bool; + static const ColumnType column_id = col_type_Bool; +}; + +template <> +struct ColumnTypeTraits { + using column_type = FloatColumn; + using leaf_type = BasicArray; + using sum_type = double; + using minmax_type = float; + static const DataType id = type_Float; + static const ColumnType column_id = col_type_Float; + static const ColumnType real_column_type = col_type_Float; +}; + +template <> +struct ColumnTypeTraits { + using column_type = DoubleColumn; + using leaf_type = BasicArray; + using sum_type = double; + using minmax_type = double; + static const DataType id = type_Double; + static const ColumnType column_id = col_type_Double; + static const ColumnType real_column_type = col_type_Double; +}; + +template <> +struct ColumnTypeTraits : ColumnTypeTraits { + static const DataType id = type_OldDateTime; + static const ColumnType column_id = col_type_OldDateTime; +}; + +template <> +struct ColumnTypeTraits> : ColumnTypeTraits> { + static const DataType id = type_OldDateTime; + static const ColumnType column_id = col_type_OldDateTime; +}; + +template <> +struct ColumnTypeTraits { + static const DataType id = type_String; + static const ColumnType column_id = col_type_String; +}; + +template <> +struct ColumnTypeTraits { + using column_type = BinaryColumn; + using leaf_type = ArrayBinary; + static const DataType id = type_Binary; + static const ColumnType column_id = col_type_Binary; + static const ColumnType real_column_type = col_type_Binary; +}; + +template +struct GetColumnType; +template <> +struct GetColumnType { + using type = IntegerColumn; +}; +template <> +struct GetColumnType { + using type = IntNullColumn; +}; +template +struct GetColumnType { + // FIXME: Null definition + using type = FloatColumn; +}; +template +struct GetColumnType { + // FIXME: Null definition + using type = DoubleColumn; +}; + +// Only purpose is to return 'double' if and only if source column (T) is float and you're doing a sum (A) +template +struct ColumnTypeTraitsSum { + typedef T sum_type; +}; + +template <> +struct ColumnTypeTraitsSum { + typedef double sum_type; +}; + +template +struct ColumnTypeTraitsSum, A> { + using sum_type = int64_t; +}; +} + +#endif // REALM_COLUMN_TYPE_TRAITS_HPP diff --git a/Pods/Realm/include/core/realm/data_type.hpp b/Pods/Realm/include/core/realm/data_type.hpp new file mode 100644 index 0000000000..859d1cf9c8 --- /dev/null +++ b/Pods/Realm/include/core/realm/data_type.hpp @@ -0,0 +1,65 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_DATA_TYPE_HPP +#define REALM_DATA_TYPE_HPP + +#include + +namespace realm { + +class StringData; +class BinaryData; + +typedef int64_t Int; +typedef bool Bool; +typedef float Float; +typedef double Double; +typedef realm::StringData String; +typedef realm::BinaryData Binary; + + +// Note: Value assignments must be kept in sync with +// Note: Value assignments must be kept in sync with +// Note: Value assignments must be kept in sync with +// Note: Value assignments must be kept in sync with "com/realm/ColumnType.java" +// Note: Any change to this enum is a file-format breaking change. +enum DataType { + type_Int = 0, + type_Bool = 1, + type_Float = 9, + type_Double = 10, + type_String = 2, + type_Binary = 4, + type_OldDateTime = 7, + type_Timestamp = 8, + type_Table = 5, + type_Mixed = 6, + type_Link = 12, + type_LinkList = 13 +}; + +/// See Descriptor::set_link_type(). +enum LinkType { + link_Strong, + link_Weak, +}; + +} // namespace realm + +#endif // REALM_DATA_TYPE_HPP diff --git a/Pods/Realm/include/core/realm/descriptor.hpp b/Pods/Realm/include/core/realm/descriptor.hpp new file mode 100644 index 0000000000..9d37de556d --- /dev/null +++ b/Pods/Realm/include/core/realm/descriptor.hpp @@ -0,0 +1,812 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_DESCRIPTOR_HPP +#define REALM_DESCRIPTOR_HPP + +#include + +#include +#include +#include + + +namespace realm { + +namespace _impl { +class DescriptorFriend; +} + + +/// Accessor for table type descriptors. +/// +/// A table type descriptor is an entity that specifies the dynamic +/// type of a Realm table. Objects of this class are accessors +/// through which the descriptor can be inspected and +/// changed. Accessors can become detached, see is_attached() for more +/// on this. The descriptor itself is stored inside the database file, +/// or elsewhere in case of a free-standing table or a table in a +/// free-standing group. +/// +/// The dynamic type consists first, and foremost of an ordered list +/// of column descriptors. Each column descriptor specifies the name +/// and type of the column. +/// +/// When a table has a subtable column, every cell in than column +/// contains a subtable. All those subtables have the same dynamic +/// type, and therefore have a shared descriptor. See is_root() for +/// more on this. +/// +/// The Table class contains convenience methods, such as +/// Table::get_column_count() and Table::add_column(), that allow you +/// to inspect and change the dynamic type of simple tables without +/// resorting to use of descriptors. For example, the following two +/// statements have the same effect: +/// +/// table->add_column(type, name); +/// table->get_descriptor()->add_column(type, name); +/// +/// Note, however, that this equivalence holds only as long as no +/// shared subtable descriptors are involved. +/// +/// \sa Table::get_descriptor() +class Descriptor : public std::enable_shared_from_this { +public: + /// Get the number of columns in the associated tables. + size_t get_column_count() const noexcept; + + /// Get the type of the column at the specified index. + /// + /// The consequences of specifying a column index that is out of + /// range, are undefined. + DataType get_column_type(size_t column_ndx) const noexcept; + + /// Get the name of the column at the specified index. + /// + /// The consequences of specifying a column index that is out of + /// range, are undefined. + StringData get_column_name(size_t column_ndx) const noexcept; + + /// Search for a column with the specified name. + /// + /// This function finds the first column with the specified name, + /// and returns its index. If there are no such columns, it + /// returns `not_found`. + size_t get_column_index(StringData name) const noexcept; + + /// Get the index of the table to which links in the column at the specified + /// index refer. + /// + /// The consequences of specifying a column index that is out of + /// range, are undefined. + /// + /// The consequences of specifying a column index that does not refer + /// to a link column, are undefined. + size_t get_column_link_target(size_t column_ndx) const noexcept; + + /// Get whether or not the specified column is nullable. + /// + /// The consequences of specifying a column index that is out of + /// range, are undefined. + bool is_nullable(size_t column_ndx) const noexcept; + + /// \defgroup descriptor_column_accessors Accessing Columns Via A Descriptor + /// + /// add_column() and add_column_link() are a shorthands for calling + /// insert_column() and insert_column_link(), respectively, with a column + /// index equal to the original number of columns. The returned value is + /// that column index. + /// + /// insert_column() inserts a new column into all the tables associated with + /// this descriptor. If any of the tables are not empty, the new column will + /// be filled with the default value associated with the specified data + /// type. This function cannot be used to insert link-type columns. For + /// that, you have to use insert_column_link() instead. + /// + /// This function modifies the dynamic type of all the tables that + /// share this descriptor. It does this by inserting a new column + /// with the specified name and type into the descriptor at the + /// specified index, and into each of the tables that share this + /// descriptor. + /// + /// insert_column_link() is like insert_column(), but inserts a link-type + /// column to a group-level table. It is not possible to add link-type + /// columns to tables that are not group-level tables. This functions must + /// be used in place of insert_column() when the column type is `type_Link` + /// or `type_LinkList`. A link-type column is associated with a particular + /// target table. All links in a link-type column refer to rows in the + /// target table of that column. The target table must also be a group-level + /// table, and it must belong to the same group as the origin table. + /// + /// \param name Name of new column. All strings are valid column names as + /// long as they are valid UTF-8 encodings and the number of bytes does not + /// exceed `max_column_name_length`. An attempt to add a column with a name + /// that is longer than `max_column_name_length` will cause an exception to + /// be thrown. + /// + /// \param subdesc If a non-null pointer is passed, and the + /// specified type is `type_Table`, then this function + /// automatically retrieves the descriptor associated with the new + /// subtable column, and stores a reference to its accessor in + /// `*subdesc`. + /// + /// \param col_ndx Insert the new column at this index. Preexisting columns + /// at indexes equal to, or greater than `col_ndx` will be shifted to the + /// next higher index. It is an error to specify an index that is greater + /// than the number of columns prior to the insertion. + /// + /// \param link_type See set_link_type(). + /// + /// \sa Table::add_column() + /// \sa Table::insert_column() + /// \sa Table::add_column_link() + /// \sa Table::insert_column_link() + /// \sa is_root() + //@{ + + static const size_t max_column_name_length = 63; + + size_t add_column(DataType type, StringData name, DescriptorRef* subdesc = nullptr, bool nullable = false); + + void insert_column(size_t col_ndx, DataType type, StringData name, DescriptorRef* subdesc = nullptr, + bool nullable = false); + + size_t add_column_link(DataType type, StringData name, Table& target, LinkType = link_Weak); + void insert_column_link(size_t col_ndx, DataType type, StringData name, Table& target, LinkType = link_Weak); + //@} + + /// Remove the specified column from each of the associated + /// tables. If the removed column is the only column in the + /// descriptor, then the table size will drop to zero for all + /// tables that were not already empty. + /// + /// This function modifies the dynamic type of all the tables that + /// share this descriptor. It does this by removing the column at + /// the specified index from the descriptor, and from each of the + /// tables that share this descriptor. The consequences of + /// specifying a column index that is out of range, are undefined. + /// + /// If the removed column was a subtable column, then the + /// associated descriptor accessor will be detached, if it + /// exists. This function will also detach all accessors of + /// subtables of the root table. Only the accessor of the root + /// table will remain attached. The root table is the table + /// associated with the root descriptor. + /// + /// \param col_ndx The index of the column to be removed. It is an error to + /// specify an index that is greater than, or equal to the number of + /// columns. + /// + /// \sa is_root() + /// \sa Table::remove_column() + void remove_column(size_t col_ndx); + + /// Rename the specified column. + /// + /// This function modifies the dynamic type of all the tables that + /// share this descriptor. The consequences of specifying a column + /// index that is out of range, are undefined. + /// + /// This function will detach all accessors of subtables of the + /// root table. Only the accessor of the root table will remain + /// attached. The root table is the table associated with the root + /// descriptor. + /// + /// \param col_ndx The index of the column to be renamed. It is an error to + /// specify an index that is greater than, or equal to the number of + /// columns. + /// + /// \param new_name The new name of the column. + /// + /// \sa is_root() + /// \sa Table::rename_column() + void rename_column(size_t col_ndx, StringData new_name); + + /// If the descriptor is describing a subtable column, the add_search_index() + /// and remove_search_index() will add or remove search indexes of *all* + /// subtables of the subtable column. This may take a while if there are many + /// subtables with many rows each. + bool has_search_index(size_t column_ndx) const noexcept; + void add_search_index(size_t column_ndx); + void remove_search_index(size_t column_ndx); + + /// There are two kinds of links, 'weak' and 'strong'. A strong link is one + /// that implies ownership, i.e., that the origin row (parent) owns the + /// target row (child). Simply stated, this means that when the origin row + /// (parent) is removed, so is the target row (child). If there are multiple + /// strong links to a target row, the origin rows share ownership, and the + /// target row is removed when the last owner disappears. Weak links do not + /// imply ownership, and will be nullified or removed when the target row + /// disappears. + /// + /// To put this in precise terms; when a strong link is broken, and the + /// target row has no other strong links to it, the target row is removed. A + /// row that is implicitly removed in this way, is said to be + /// *cascade-removed*. When a weak link is broken, nothing is + /// cascade-removed. + /// + /// A link is considered broken if + /// + /// - the link is nullified, removed, or replaced by a different link + /// (Row::nullify_link(), Row::set_link(), LinkView::remove_link(), + /// LinkView::set_link(), LinkView::clear()), or if + /// + /// - the origin row is explicitly removed (Row::move_last_over(), + /// Table::clear()), or if + /// + /// - the origin row is cascade-removed, or if + /// + /// - the origin column is removed from the table (Table::remove_column()), + /// or if + /// + /// - the origin table is removed from the group. + /// + /// Note that a link is *not* considered broken when it is replaced by a + /// link to the same target row. I.e., no no rows will be cascade-removed + /// due to such an operation. + /// + /// When a row is explicitly removed (such as by Table::move_last_over()), + /// all links to it are automatically removed or nullified. For single link + /// columns (type_Link), links to the removed row are nullified. For link + /// list columns (type_LinkList), links to the removed row are removed from + /// the list. + /// + /// When a row is cascade-removed there can no longer be any strong links to + /// it, but if there are any weak links, they will be removed or nullified. + /// + /// It is important to understand that this cascade-removal scheme is too + /// simplistic to enable detection and removal of orphaned link-cycles. In + /// this respect, it suffers from the same limitations as a reference + /// counting scheme generally does. + /// + /// It is also important to understand, that the possible presence of a link + /// cycle can cause a row to be cascade-removed as a consequence of being + /// modified. This happens, for example, if two rows, A and B, have strong + /// links to each other, and there are no other strong links to either of + /// them. In this case, if A->B is changed to A->C, then both A and B will + /// be cascade-removed. This can lead to obscure bugs in some applications, + /// such as in the following case: + /// + /// table.set_link(col_ndx_1, row_ndx, ...); + /// table.set_int(col_ndx_2, row_ndx, ...); // Oops, `row_ndx` may no longer refer to the same row + /// + /// To be safe, applications, that may encounter cycles, are advised to + /// adopt the following pattern: + /// + /// Row row = table[row_ndx]; + /// row.set_link(col_ndx_1, ...); + /// if (row) + /// row.set_int(col_ndx_2, ...); // Ok, because we check whether the row has disappeared + /// + /// \param col_ndx The index of the link column (`type_Link` or + /// `type_LinkList`) to be modified. It is an error to specify an index that + /// is greater than, or equal to the number of columns, or to specify the + /// index of a non-link column. + /// + /// \param link_type The type of links the column should store. + void set_link_type(size_t col_ndx, LinkType link_type); + + //@{ + /// Get the descriptor for the specified subtable column. + /// + /// This function provides access to the shared subtable + /// descriptor for the subtables in the specified column. The + /// specified column must be a column whose type is 'table'. The + /// consequences of specifying a column of a different type, or + /// specifying an index that is out of range, are undefined. + /// + /// Note that this function cannot be used with 'mixed' columns, + /// since subtables of that kind have independent dynamic types, + /// and therefore, have independent descriptors. You can only get + /// access to the descriptor of a subtable in a mixed column by + /// first getting access to the subtable itself. + /// + /// \sa is_root() + DescriptorRef get_subdescriptor(size_t column_ndx); + ConstDescriptorRef get_subdescriptor(size_t column_ndx) const; + //@} + + //@{ + /// Returns the parent table descriptor, if any. + /// + /// If this descriptor is the *root descriptor*, then this + /// function returns null. Otherwise it returns the accessor of + /// the parent descriptor. + /// + /// \sa is_root() + DescriptorRef get_parent() noexcept; + ConstDescriptorRef get_parent() const noexcept; + //@} + + //@{ + /// Get the table associated with the root descriptor. + /// + /// \sa get_parent() + /// \sa is_root() + TableRef get_root_table() noexcept; + ConstTableRef get_root_table() const noexcept; + //@} + + //@{ + /// Get the target table associated with the specified link column. This + /// descriptor must be a root descriptor (is_root()), and the specified + /// column must be a link column (`type_Link` or `type_LinkList`). + TableRef get_link_target(size_t col_ndx) noexcept; + ConstTableRef get_link_target(size_t col_ndx) const noexcept; + //@} + + /// Is this a root descriptor? + /// + /// Descriptors of tables with independent dynamic type are root + /// descriptors. Root descriptors are never shared. Tables that + /// are direct members of groups have independent dynamic + /// types. The same is true for free-standing tables and subtables + /// in columns of type 'mixed'. + /// + /// When a table has a column of type 'table', the cells in that + /// column contain subtables. All those subtables have the same + /// dynamic type, and they share a single dynamic type + /// descriptor. Such shared descriptors are never root + /// descriptors. + /// + /// A type descriptor can even be shared by subtables with + /// different parent tables, but only if the parent tables + /// themselves have a shared type descriptor. For example, if a + /// table has a column `foo` of type 'table', and each of the + /// subtables in `foo` has a column `bar` of type 'table', then + /// all the subtables in all the `bar` columns share the same + /// dynamic type descriptor. + /// + /// \sa Table::has_shared_type() + bool is_root() const noexcept; + + /// Determine whether this accessor is still attached. + /// + /// A table descriptor accessor may get detached from the + /// underlying descriptor for various reasons (see below). When it + /// does, it no longer refers to that descriptor, and can no + /// longer be used, except for calling is_attached(). The + /// consequences of calling other methods on a detached accessor + /// are undefined. Descriptor accessors obtained by calling + /// functions in the Realm API are always in the 'attached' + /// state immediately upon return from those functions. + /// + /// A descriptor accessor that is obtained directly from a table + /// becomes detached if the table becomes detached. A shared + /// subtable descriptor accessor that is obtained by a call to + /// get_subdescriptor() becomes detached if the parent descriptor + /// accessor becomes detached, or if the corresponding subtable + /// column is removed. A descriptor accessor does not get detached + /// under any other circumstances. + bool is_attached() const noexcept; + + //@{ + /// \brief Compare two table descriptors. + /// + /// Two table descriptors are equal if they have the same number of columns, + /// and for each column index, the two columns have the same name, data + /// type, and set of attributes. + /// + /// For link columns (`type_Link` and `type_LinkList`), the target table + /// (get_link_target()) of the two columns must be the same. + /// + /// For subtable columns (`type_Table`), the two corresponding + /// subdescriptors must themselves be equal, as if by a recursive call to + /// operator==(). + /// + /// The consequences of comparing a detached descriptor are + /// undefined. + bool operator==(const Descriptor&) const noexcept; + bool operator!=(const Descriptor&) const noexcept; + //@} + + /// If the specified column is optimized to store only unique values, then + /// this function returns the number of unique values currently + /// stored. Otherwise it returns zero. This function is mainly intended for + /// debugging purposes. + size_t get_num_unique_values(size_t column_ndx) const; + + ~Descriptor() noexcept; + +private: + // for initialization through make_shared + struct PrivateTag { + }; + +public: + Descriptor(const PrivateTag&) + : Descriptor() + { + } + +private: + // Table associated with root descriptor. Detached iff null. + TableRef m_root_table; + DescriptorRef m_parent; // Null iff detached or root descriptor. + Spec* m_spec; // Valid if attached. Owned iff valid and `m_parent`. + + // Whenever a subtable descriptor accessor is created, it is + // stored in this map. This ensures that when get_subdescriptor() + // is called to created multiple DescriptorRef objects that + // overlap in time, then they will all refer to the same + // descriptor object. + // + // It also enables the necessary recursive detaching of descriptor + // objects. + struct subdesc_entry { + size_t m_column_ndx; + std::weak_ptr m_subdesc; + subdesc_entry(size_t column_ndx, DescriptorRef); + }; + typedef std::vector subdesc_map; + mutable subdesc_map m_subdesc_map; + + Descriptor() noexcept; + + // Called by the root table if this becomes the root + // descriptor. Otherwise it is called by the descriptor that + // becomes its parent. + // + // Puts this descriptor accessor into the attached state. This + // attaches it to the underlying structure of array nodes. It does + // not establish the parents reference to this descriptor, that is + // the job of the parent. When this function returns, + // is_attached() will return true. + // + // Not idempotent. + // + // The specified table is not allowed to be a subtable with a + // shareable spec. That is, Table::has_shared_spec() must return + // false. + // + // The specified spec must be the spec of the specified table or + // of one of its direct or indirect subtable columns. + // + // When the specified spec is the spec of the root table, the + // parent must be specified as null. When the specified spec is + // not the root spec, a proper parent must be specified. + void attach(Table*, DescriptorRef parent, Spec*) noexcept; + + // Detach accessor from underlying descriptor. Caller must ensure + // that a reference count exists upon return, for example by + // obtaining an extra reference count before the call. + // + // This function is called either by the root table if this is the + // root descriptor, or by the parent descriptor, if it is not. + // + // Puts this descriptor accessor into the detached state. This + // detaches it from the underlying structure of array nodes. It + // also calls detach_subdesc_accessors(). When this function + // returns, is_attached() will return false. + // + // Not idempotent. + void detach() noexcept; + + // Recursively detach all subtable descriptor accessors that + // exist, that is, all subtable descriptor accessors that have + // this descriptor as ancestor. + void detach_subdesc_accessors() noexcept; + + // Record the path in terms of subtable column indexes from the + // root descriptor to this descriptor. If this descriptor is a + // root descriptor, the path is empty. Returns zero if the path is + // too long to fit in the specified buffer. Otherwise the path + // indexes will be stored between `begin_2`and `end`, where + // `begin_2` is the returned pointer. + size_t* record_subdesc_path(size_t* begin, size_t* end) const noexcept; + + // Returns a pointer to the accessor of the specified + // subdescriptor if that accessor exists, otherwise this function + // return null. + DescriptorRef get_subdesc_accessor(size_t column_ndx) noexcept; + + void adj_insert_column(size_t col_ndx) noexcept; + void adj_erase_column(size_t col_ndx) noexcept; + + friend class util::bind_ptr; + friend class util::bind_ptr; + friend class _impl::DescriptorFriend; +}; + + +// Implementation: + +inline size_t Descriptor::get_column_count() const noexcept +{ + REALM_ASSERT(is_attached()); + return m_spec->get_public_column_count(); +} + +inline StringData Descriptor::get_column_name(size_t ndx) const noexcept +{ + REALM_ASSERT(is_attached()); + return m_spec->get_column_name(ndx); +} + +inline DataType Descriptor::get_column_type(size_t ndx) const noexcept +{ + REALM_ASSERT(is_attached()); + return m_spec->get_public_column_type(ndx); +} + +inline bool Descriptor::is_nullable(size_t ndx) const noexcept +{ + REALM_ASSERT(is_attached()); + return m_spec->get_column_attr(ndx) & col_attr_Nullable; +} + +inline size_t Descriptor::get_column_index(StringData name) const noexcept +{ + REALM_ASSERT(is_attached()); + return m_spec->get_column_index(name); +} + +inline size_t Descriptor::get_column_link_target(size_t column_ndx) const noexcept +{ + REALM_ASSERT(is_attached()); + return m_spec->get_opposite_link_table_ndx(column_ndx); +} + +inline size_t Descriptor::add_column(DataType type, StringData name, DescriptorRef* subdesc, bool nullable) +{ + size_t col_ndx = m_spec->get_public_column_count(); + insert_column(col_ndx, type, name, subdesc, nullable); // Throws + return col_ndx; +} + +inline void Descriptor::insert_column(size_t col_ndx, DataType type, StringData name, DescriptorRef* subdesc, + bool nullable) +{ + typedef _impl::TableFriend tf; + + if (REALM_UNLIKELY(!is_attached())) + throw LogicError(LogicError::detached_accessor); + if (REALM_UNLIKELY(col_ndx > get_column_count())) + throw LogicError(LogicError::column_index_out_of_range); + if (REALM_UNLIKELY(tf::is_link_type(ColumnType(type)))) + throw LogicError(LogicError::illegal_type); + + LinkTargetInfo invalid_link; + tf::insert_column(*this, col_ndx, type, name, invalid_link, nullable); // Throws + adj_insert_column(col_ndx); + if (subdesc && type == type_Table) + *subdesc = get_subdescriptor(col_ndx); +} + +inline size_t Descriptor::add_column_link(DataType type, StringData name, Table& target, LinkType link_type) +{ + size_t col_ndx = m_spec->get_public_column_count(); + insert_column_link(col_ndx, type, name, target, link_type); // Throws + return col_ndx; +} + +inline void Descriptor::insert_column_link(size_t col_ndx, DataType type, StringData name, Table& target, + LinkType link_type) +{ + typedef _impl::TableFriend tf; + + if (REALM_UNLIKELY(!is_attached() || !target.is_attached())) + throw LogicError(LogicError::detached_accessor); + if (REALM_UNLIKELY(col_ndx > get_column_count())) + throw LogicError(LogicError::column_index_out_of_range); + if (REALM_UNLIKELY(!tf::is_link_type(ColumnType(type)))) + throw LogicError(LogicError::illegal_type); + if (REALM_UNLIKELY(!is_root())) + throw LogicError(LogicError::wrong_kind_of_descriptor); + // Both origin and target must be group-level tables, and in the same group. + Group* origin_group = tf::get_parent_group(*get_root_table()); + Group* target_group = tf::get_parent_group(target); + if (!origin_group || !target_group) + throw LogicError(LogicError::wrong_kind_of_table); + if (origin_group != target_group) + throw LogicError(LogicError::group_mismatch); + + LinkTargetInfo link(&target); + tf::insert_column(*this, col_ndx, type, name, link); // Throws + adj_insert_column(col_ndx); + + tf::set_link_type(*get_root_table(), col_ndx, link_type); // Throws +} + +inline void Descriptor::remove_column(size_t col_ndx) +{ + typedef _impl::TableFriend tf; + + if (REALM_UNLIKELY(!is_attached())) + throw LogicError(LogicError::detached_accessor); + if (REALM_UNLIKELY(col_ndx >= get_column_count())) + throw LogicError(LogicError::column_index_out_of_range); + + tf::erase_column(*this, col_ndx); // Throws + adj_erase_column(col_ndx); +} + +inline void Descriptor::rename_column(size_t col_ndx, StringData name) +{ + typedef _impl::TableFriend tf; + + if (REALM_UNLIKELY(!is_attached())) + throw LogicError(LogicError::detached_accessor); + if (REALM_UNLIKELY(col_ndx >= get_column_count())) + throw LogicError(LogicError::column_index_out_of_range); + + tf::rename_column(*this, col_ndx, name); // Throws +} + +inline void Descriptor::set_link_type(size_t col_ndx, LinkType link_type) +{ + typedef _impl::TableFriend tf; + + if (REALM_UNLIKELY(!is_attached())) + throw LogicError(LogicError::detached_accessor); + if (REALM_UNLIKELY(col_ndx >= get_column_count())) + throw LogicError(LogicError::column_index_out_of_range); + if (REALM_UNLIKELY(!tf::is_link_type(ColumnType(get_column_type(col_ndx))))) + throw LogicError(LogicError::illegal_type); + + tf::set_link_type(*get_root_table(), col_ndx, link_type); // Throws +} + +inline ConstDescriptorRef Descriptor::get_subdescriptor(size_t column_ndx) const +{ + return const_cast(this)->get_subdescriptor(column_ndx); +} + +inline DescriptorRef Descriptor::get_parent() noexcept +{ + return m_parent; +} + +inline ConstDescriptorRef Descriptor::get_parent() const noexcept +{ + return const_cast(this)->get_parent(); +} + +inline TableRef Descriptor::get_root_table() noexcept +{ + return m_root_table; +} + +inline ConstTableRef Descriptor::get_root_table() const noexcept +{ + return const_cast(this)->get_root_table(); +} + +inline TableRef Descriptor::get_link_target(size_t col_ndx) noexcept +{ + REALM_ASSERT(is_attached()); + REALM_ASSERT(is_root()); + return get_root_table()->get_link_target(col_ndx); +} + +inline ConstTableRef Descriptor::get_link_target(size_t col_ndx) const noexcept +{ + REALM_ASSERT(is_attached()); + REALM_ASSERT(is_root()); + return get_root_table()->get_link_target(col_ndx); +} + +inline bool Descriptor::is_root() const noexcept +{ + return !m_parent; +} + +inline Descriptor::Descriptor() noexcept +{ +} + +inline void Descriptor::attach(Table* table, DescriptorRef parent, Spec* spec) noexcept +{ + REALM_ASSERT(!is_attached()); + REALM_ASSERT(!table->has_shared_type()); + m_root_table.reset(table); + m_parent = parent; + m_spec = spec; +} + +inline bool Descriptor::is_attached() const noexcept +{ + return bool(m_root_table); +} + +inline Descriptor::subdesc_entry::subdesc_entry(size_t n, DescriptorRef d) + : m_column_ndx(n) + , m_subdesc(d) +{ +} + +inline bool Descriptor::operator==(const Descriptor& d) const noexcept +{ + REALM_ASSERT(is_attached()); + REALM_ASSERT(d.is_attached()); + return *m_spec == *d.m_spec; +} + +inline bool Descriptor::operator!=(const Descriptor& d) const noexcept +{ + return !(*this == d); +} + +// The purpose of this class is to give internal access to some, but +// not all of the non-public parts of the Descriptor class. +class _impl::DescriptorFriend { +public: + static DescriptorRef create() + { + return std::make_shared(Descriptor::PrivateTag()); // Throws + } + + static void attach(Descriptor& desc, Table* table, DescriptorRef parent, Spec* spec) noexcept + { + desc.attach(table, parent, spec); + } + + static void detach(Descriptor& desc) noexcept + { + desc.detach(); + } + + static void detach_subdesc_accessors(Descriptor& desc) noexcept + { + desc.detach_subdesc_accessors(); + } + + static Table& get_root_table(Descriptor& desc) noexcept + { + return *desc.m_root_table; + } + + static const Table& get_root_table(const Descriptor& desc) noexcept + { + return *desc.m_root_table; + } + + static Spec& get_spec(Descriptor& desc) noexcept + { + return *desc.m_spec; + } + + static const Spec& get_spec(const Descriptor& desc) noexcept + { + return *desc.m_spec; + } + + static size_t* record_subdesc_path(const Descriptor& desc, size_t* begin, size_t* end) noexcept + { + return desc.record_subdesc_path(begin, end); + } + + static DescriptorRef get_subdesc_accessor(Descriptor& desc, size_t column_ndx) noexcept + { + return desc.get_subdesc_accessor(column_ndx); + } + + static void adj_insert_column(Descriptor& desc, size_t col_ndx) noexcept + { + desc.adj_insert_column(col_ndx); + } + + static void adj_erase_column(Descriptor& desc, size_t col_ndx) noexcept + { + desc.adj_erase_column(col_ndx); + } +}; + +} // namespace realm + +#endif // REALM_DESCRIPTOR_HPP diff --git a/Pods/Realm/include/core/realm/descriptor_fwd.hpp b/Pods/Realm/include/core/realm/descriptor_fwd.hpp new file mode 100644 index 0000000000..2937724835 --- /dev/null +++ b/Pods/Realm/include/core/realm/descriptor_fwd.hpp @@ -0,0 +1,33 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_DESCRIPTOR_FWD_HPP +#define REALM_DESCRIPTOR_FWD_HPP + +#include + + +namespace realm { + +class Descriptor; +typedef std::shared_ptr DescriptorRef; +typedef std::shared_ptr ConstDescriptorRef; + +} // namespace realm + +#endif // REALM_DESCRIPTOR_FWD_HPP diff --git a/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp b/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp new file mode 100644 index 0000000000..f642d6f171 --- /dev/null +++ b/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp @@ -0,0 +1,37 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_DISABLE_SYNC_TO_DISK_HPP +#define REALM_DISABLE_SYNC_TO_DISK_HPP + +#include + +namespace realm { + +/// Completely disable synchronization with storage device to speed up unit +/// testing. This is an unsafe mode of operation, and should never be used in +/// production. This function is thread safe. +void disable_sync_to_disk(); + +/// Returns true after disable_sync_to_disk() has been called. This function is +/// thread safe. +bool get_disable_sync_to_disk() noexcept; + +} // namespace realm + +#endif // REALM_DISABLE_SYNC_TO_DISK_HPP diff --git a/Pods/Realm/include/core/realm/exceptions.hpp b/Pods/Realm/include/core/realm/exceptions.hpp new file mode 100644 index 0000000000..3ddf607515 --- /dev/null +++ b/Pods/Realm/include/core/realm/exceptions.hpp @@ -0,0 +1,320 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_EXCEPTIONS_HPP +#define REALM_EXCEPTIONS_HPP + +#include + +#include +#include + +namespace realm { + +using util::ExceptionWithBacktrace; + +/// Thrown by various functions to indicate that a specified table does not +/// exist. +class NoSuchTable : public ExceptionWithBacktrace { +public: + const char* message() const noexcept override; +}; + + +/// Thrown by various functions to indicate that a specified table name is +/// already in use. +class TableNameInUse : public ExceptionWithBacktrace { +public: + const char* message() const noexcept override; +}; + + +// Thrown by functions that require a table to **not** be the target of link +// columns, unless those link columns are part of the table itself. +class CrossTableLinkTarget : public ExceptionWithBacktrace { +public: + const char* message() const noexcept override; +}; + + +/// Thrown by various functions to indicate that the dynamic type of a table +/// does not match a particular other table type (dynamic or static). +class DescriptorMismatch : public ExceptionWithBacktrace { +public: + const char* message() const noexcept override; +}; + + +/// The FileFormatUpgradeRequired exception can be thrown by the SharedGroup +/// constructor when opening a database that uses a deprecated file format +/// and/or a deprecated history schema, and the user has indicated he does not +/// want automatic upgrades to be performed. This exception indicates that until +/// an upgrade of the file format is performed, the database will be unavailable +/// for read or write operations. +class FileFormatUpgradeRequired : public ExceptionWithBacktrace { +public: + const char* message() const noexcept override; +}; + + +/// Thrown when a sync agent attempts to join a session in which there is +/// already a sync agent. A session may only contain one sync agent at any given +/// time. +class MultipleSyncAgents : public ExceptionWithBacktrace { +public: + const char* message() const noexcept override; +}; + + +/// Thrown when memory can no longer be mapped to. When mmap/remap fails. +class AddressSpaceExhausted : public std::runtime_error { +public: + AddressSpaceExhausted(const std::string& msg); + /// runtime_error::what() returns the msg provided in the constructor. +}; + +/// Thrown when creating references that are too large to be contained in our ref_type (size_t) +class MaximumFileSizeExceeded : public std::runtime_error { +public: + MaximumFileSizeExceeded(const std::string& msg); + /// runtime_error::what() returns the msg provided in the constructor. +}; + +/// Thrown when writing fails because the disk is full. +class OutOfDiskSpace : public std::runtime_error { +public: + OutOfDiskSpace(const std::string& msg); + /// runtime_error::what() returns the msg provided in the constructor. +}; + + +class SerialisationError : public ExceptionWithBacktrace { +public: + SerialisationError(const std::string& msg); + /// runtime_error::what() returns the msg provided in the constructor. +}; + +/// The \c LogicError exception class is intended to be thrown only when +/// applications (or bindings) violate rules that are stated (or ought to have +/// been stated) in the documentation of the public API, and only in cases +/// where the violation could have been easily and efficiently predicted by the +/// application. In other words, this exception class is for the cases where +/// the error is due to incorrect use of the public API. +/// +/// This class is not supposed to be caught by applications. It is not even +/// supposed to be considered part of the public API, and therefore the +/// documentation of the public API should **not** mention the \c LogicError +/// exception class by name. Note how this contrasts with other exception +/// classes, such as \c NoSuchTable, which are part of the public API, and are +/// supposed to be mentioned in the documentation by name. The \c LogicError +/// exception is part of Realm's private API. +/// +/// In other words, the \c LogicError class should exclusively be used in +/// replacement (or in addition to) asserts (debug or not) in order to +/// guarantee program interruption, while still allowing for complete +/// test-cases to be written and run. +/// +/// To this effect, the special `CHECK_LOGIC_ERROR()` macro is provided as a +/// test framework plugin to allow unit tests to check that the functions in +/// the public API do throw \c LogicError when rules are violated. +/// +/// The reason behind hiding this class from the public API is to prevent users +/// from getting used to the idea that "Undefined Behaviour" equates a specific +/// exception being thrown. The whole point of properly documenting "Undefined +/// Behaviour" cases is to help the user know what the limits are, without +/// constraining the database to handle every and any use-case thrown at it. +/// +/// FIXME: This exception class should probably be moved to the `_impl` +/// namespace, in order to avoid some confusion. +class LogicError : public ExceptionWithBacktrace { +public: + enum ErrorKind { + string_too_big, + binary_too_big, + table_name_too_long, + column_name_too_long, + table_index_out_of_range, + row_index_out_of_range, + column_index_out_of_range, + string_position_out_of_range, + link_index_out_of_range, + bad_version, + illegal_type, + + /// Indicates that an argument has a value that is illegal in combination + /// with another argument, or with the state of an involved object. + illegal_combination, + + /// Indicates a data type mismatch, such as when `Table::find_pkey_int()` is + /// called and the type of the primary key is not `type_Int`. + type_mismatch, + + /// Indicates that two involved tables are not in the same group. + group_mismatch, + + /// Indicates that an involved descriptor is of the wrong kind, i.e., if + /// it is a subtable descriptor, and the function requires a root table + /// descriptor. + wrong_kind_of_descriptor, + + /// Indicates that an involved table is of the wrong kind, i.e., if it + /// is a subtable, and the function requires a root table, or if it is a + /// free-standing table, and the function requires a group-level table. + wrong_kind_of_table, + + /// Indicates that an involved accessor is was detached, i.e., was not + /// attached to an underlying object. + detached_accessor, + + /// Indicates that a specified row index of a target table (a link) is + /// out of range. This is used for disambiguation in cases such as + /// Table::set_link() where one specifies both a row index of the origin + /// table, and a row index of the target table. + target_row_index_out_of_range, + + // Indicates that an involved column lacks a search index. + no_search_index, + + /// Indicates that a modification was attempted that would have produced a + /// duplicate primary value. + unique_constraint_violation, + + /// User attempted to insert null in non-nullable column + column_not_nullable, + + /// Group::open() is called on a group accessor that is already in the + /// attached state. Or Group::open() or Group::commit() is called on a + /// group accessor that is managed by a SharedGroup object. + wrong_group_state, + + /// No active transaction on a particular SharedGroup object (e.g., + /// SharedGroup::commit()), or the active transaction on the SharedGroup + /// object is of the wrong type (read/write), or an attampt was made to + /// initiate a new transaction while one is already in progress on the + /// same SharedGroup object. + wrong_transact_state, + + /// Attempted use of a continuous transaction through a SharedGroup + /// object with no history. See Replication::get_history(). + no_history, + + /// Durability setting (as passed to the SharedGroup constructor) was + /// not consistent across the session. + mixed_durability, + + /// History type (as specified by the Replication implementation passed + /// to the SharedGroup constructor) was not consistent across the + /// session. + mixed_history_type, + + /// History schema version (as specified by the Replication + /// implementation passed to the SharedGroup constructor) was not + /// consistent across the session. + mixed_history_schema_version, + + /// Adding rows to a table with no columns is not supported. + table_has_no_columns, + + /// Referring to a column that has been deleted. + column_does_not_exist, + + /// You can not add index on a subtable of a subtable + subtable_of_subtable_index + }; + + LogicError(ErrorKind message); + + const char* message() const noexcept override; + ErrorKind kind() const noexcept; + +private: + ErrorKind m_kind; +}; + + +// Implementation: + +// LCOV_EXCL_START (Wording of what() strings are not to be tested) + +inline const char* NoSuchTable::message() const noexcept +{ + return "No such table exists"; +} + +inline const char* TableNameInUse::message() const noexcept +{ + return "The specified table name is already in use"; +} + +inline const char* CrossTableLinkTarget::message() const noexcept +{ + return "Table is target of cross-table link columns"; +} + +inline const char* DescriptorMismatch::message() const noexcept +{ + return "Table descriptor mismatch"; +} + +inline const char* FileFormatUpgradeRequired::message() const noexcept +{ + return "Database upgrade required but prohibited"; +} + +inline const char* MultipleSyncAgents::message() const noexcept +{ + return "Multiple sync agents attempted to join the same session"; +} + +// LCOV_EXCL_STOP + +inline AddressSpaceExhausted::AddressSpaceExhausted(const std::string& msg) + : std::runtime_error(msg) +{ +} + +inline MaximumFileSizeExceeded::MaximumFileSizeExceeded(const std::string& msg) + : std::runtime_error(msg) +{ +} + +inline OutOfDiskSpace::OutOfDiskSpace(const std::string& msg) +: std::runtime_error(msg) +{ +} + +inline SerialisationError::SerialisationError(const std::string& msg) + : ExceptionWithBacktrace(msg) +{ +} + +inline LogicError::LogicError(LogicError::ErrorKind k) + : m_kind(k) +{ +} + +inline LogicError::ErrorKind LogicError::kind() const noexcept +{ + return m_kind; +} + + +} // namespace realm + + +#endif // REALM_EXCEPTIONS_HPP diff --git a/Pods/Realm/include/core/realm/group.hpp b/Pods/Realm/include/core/realm/group.hpp new file mode 100644 index 0000000000..8c6388efa8 --- /dev/null +++ b/Pods/Realm/include/core/realm/group.hpp @@ -0,0 +1,1432 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_GROUP_HPP +#define REALM_GROUP_HPP + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace realm { + +class SharedGroup; +namespace _impl { +class GroupFriend; +class TransactLogConvenientEncoder; +class TransactLogParser; +} + + +/// A group is a collection of named tables. +/// +/// Tables occur in the group in an unspecified order, but an order that +/// generally remains fixed. The order is guaranteed to remain fixed between two +/// points in time if no tables are added to, or removed from the group during +/// that time. When tables are added to, or removed from the group, the order +/// may change arbitrarily. +/// +/// If `table` is a table accessor attached to a group-level table, and `group` +/// is a group accessor attached to the group, then the following is guaranteed, +/// even after a change in the table order: +/// +/// \code{.cpp} +/// +/// table == group.get_table(table.get_index_in_group()) +/// +/// \endcode +/// +class Group : private Table::Parent { +public: + /// Construct a free-standing group. This group instance will be + /// in the attached state, but neither associated with a file, nor + /// with an external memory buffer. + Group(); + + enum OpenMode { + /// Open in read-only mode. Fail if the file does not already exist. + mode_ReadOnly, + /// Open in read/write mode. Create the file if it doesn't exist. + mode_ReadWrite, + /// Open in read/write mode. Fail if the file does not already exist. + mode_ReadWriteNoCreate + }; + + /// Equivalent to calling open(const std::string&, const char*, OpenMode) + /// on an unattached group accessor. + explicit Group(const std::string& file, const char* encryption_key = nullptr, OpenMode = mode_ReadOnly); + + /// Equivalent to calling open(BinaryData, bool) on an unattached + /// group accessor. Note that if this constructor throws, the + /// ownership of the memory buffer will remain with the caller, + /// regardless of whether \a take_ownership is set to `true` or + /// `false`. + explicit Group(BinaryData, bool take_ownership = true); + + struct unattached_tag { + }; + + /// Create a Group instance in its unattached state. It may then + /// be attached to a database file later by calling one of the + /// open() methods. You may test whether this instance is + /// currently in its attached state by calling + /// is_attached(). Calling any other method (except the + /// destructor) while in the unattached state has undefined + /// behavior. + Group(unattached_tag) noexcept; + + // FIXME: Implement a proper copy constructor (fairly trivial). + Group(const Group&) = delete; + Group& operator=(const Group&) = delete; + + ~Group() noexcept override; + + /// Attach this Group instance to the specified database file. + /// + /// By default, the specified file is opened in read-only mode + /// (mode_ReadOnly). This allows opening a file even when the + /// caller lacks permission to write to that file. The opened + /// group may still be modified freely, but the changes cannot be + /// written back to the same file using the commit() function. An + /// attempt to do that, will cause an exception to be thrown. When + /// opening in read-only mode, it is an error if the specified + /// file does not already exist in the file system. + /// + /// Alternatively, the file can be opened in read/write mode + /// (mode_ReadWrite). This allows use of the commit() function, + /// but, of course, it also requires that the caller has + /// permission to write to the specified file. When opening in + /// read-write mode, an attempt to create the specified file will + /// be made, if it does not already exist in the file system. + /// + /// In any case, if the file already exists, it must contain a + /// valid Realm database. In many cases invalidity will be + /// detected and cause the InvalidDatabase exception to be thrown, + /// but you should not rely on it. + /// + /// Note that changes made to the database via a Group instance + /// are not automatically committed to the specified file. You + /// may, however, at any time, explicitly commit your changes by + /// calling the commit() method, provided that the specified + /// open-mode is not mode_ReadOnly. Alternatively, you may call + /// write() to write the entire database to a new file. Writing + /// the database to a new file does not end, or in any other way + /// change the association between the Group instance and the file + /// that was specified in the call to open(). + /// + /// A Realm file that contains a history (see Replication::HistoryType) may + /// be opened via Group::open(), as long as the application can ensure that + /// there is no concurrent access to the file (see below for more on + /// concurrency), but if the file is modified via Group::commit() the + /// history will be discarded. To retain the history, the application must + /// instead access the file in shared mode, i.e., via SharedGroup, and + /// supply the right kind of replication plugin (see + /// Replication::get_history_type()). + /// + /// A file that is passed to Group::open(), may not be modified by + /// a third party until after the Group object is + /// destroyed. Behavior is undefined if a file is modified by a + /// third party while any Group object is associated with it. + /// + /// Calling open() on a Group instance that is already in the + /// attached state has undefined behavior. + /// + /// Accessing a Realm database file through manual construction + /// of a Group object does not offer any level of thread safety or + /// transaction safety. When any of those kinds of safety are a + /// concern, consider using a SharedGroup instead. When accessing + /// a database file in read/write mode through a manually + /// constructed Group object, it is entirely the responsibility of + /// the application that the file is not accessed in any way by a + /// third party during the life-time of that group object. It is, + /// on the other hand, safe to concurrently access a database file + /// by multiple manually created Group objects, as long as all of + /// them are opened in read-only mode, and there is no other party + /// that modifies the file concurrently. + /// + /// Do not call this function on a group instance that is managed + /// by a shared group. Doing so will result in undefined behavior. + /// + /// Even if this function throws, it may have the side-effect of + /// creating the specified file, and the file may get left behind + /// in an invalid state. Of course, this can only happen if + /// read/write mode (mode_ReadWrite) was requested, and the file + /// did not already exist. + /// + /// \param file File system path to a Realm database file. + /// + /// \param encryption_key 32-byte key used to encrypt and decrypt + /// the database file, or nullptr to disable encryption. + /// + /// \param mode Specifying a mode that is not mode_ReadOnly + /// requires that the specified file can be opened in read/write + /// mode. In general there is no reason to open a group in + /// read/write mode unless you want to be able to call + /// Group::commit(). + /// + /// \throw util::File::AccessError If the file could not be + /// opened. If the reason corresponds to one of the exception + /// types that are derived from util::File::AccessError, the + /// derived exception type is thrown. Note that InvalidDatabase is + /// among these derived exception types. + void open(const std::string& file, const char* encryption_key = nullptr, OpenMode mode = mode_ReadOnly); + + /// Attach this Group instance to the specified memory buffer. + /// + /// This is similar to constructing a group from a file except + /// that in this case the database is assumed to be stored in the + /// specified memory buffer. + /// + /// If \a take_ownership is `true`, you pass the ownership of the + /// specified buffer to the group. In this case the buffer will + /// eventually be freed using std::free(), so the buffer you pass, + /// must have been allocated using std::malloc(). + /// + /// On the other hand, if \a take_ownership is set to `false`, it + /// is your responsibility to keep the memory buffer alive during + /// the lifetime of the group, and in case the buffer needs to be + /// deallocated afterwards, that is your responsibility too. + /// + /// If this function throws, the ownership of the memory buffer + /// will remain with the caller, regardless of whether \a + /// take_ownership is set to `true` or `false`. + /// + /// Calling open() on a Group instance that is already in the + /// attached state has undefined behavior. + /// + /// Do not call this function on a group instance that is managed + /// by a shared group. Doing so will result in undefined behavior. + /// + /// \throw InvalidDatabase If the specified buffer does not appear + /// to contain a valid database. + void open(BinaryData, bool take_ownership = true); + + /// A group may be created in the unattached state, and then later + /// attached to a file with a call to open(). Calling any method + /// other than open(), and is_attached() on an unattached instance + /// results in undefined behavior. + bool is_attached() const noexcept; + + /// Returns true if, and only if the number of tables in this + /// group is zero. + bool is_empty() const noexcept; + + /// Returns the number of tables in this group. + size_t size() const noexcept; + + /// \defgroup group_table_access Table Accessors + /// + /// has_table() returns true if, and only if this group contains a table + /// with the specified name. + /// + /// find_table() returns the index of the first table in this group with the + /// specified name, or `realm::not_found` if this group does not contain a + /// table with the specified name. + /// + /// get_table_name() returns the name of table at the specified index. + /// + /// The versions of get_table(), that accepts a \a name argument, return the + /// first table with the specified name, or null if no such table exists. + /// + /// add_table() adds a table with the specified name to this group. It + /// throws TableNameInUse if \a require_unique_name is true and \a name + /// clashes with the name of an existing table. If \a require_unique_name is + /// false, it is possible to add more than one table with the same + /// name. Whenever a table is added, the order of the preexisting tables may + /// change arbitrarily, and the new table may not end up as the last one + /// either. But know that you can always call Table::get_index_in_group() on + /// the returned table accessor to find out at which index it ends up. + /// + /// get_or_add_table() checks if a table exists in this group with the specified + /// name. If it doesn't exist, a table is created. + /// + /// get_or_insert_table() works slightly differently from get_or_add_table(), + /// in that it considers the position of the requested table as part of that + /// table's identifying "key", in addition to the name. + /// + /// remove_table() removes the specified table from this group. A table can + /// be removed only when it is not the target of a link column of a + /// different table. Whenever a table is removed, the order of the remaining + /// tables may change arbitrarily. + /// + /// rename_table() changes the name of a preexisting table. If \a + /// require_unique_name is false, it becomes possible to have more than one + /// table with a given name in a single group. + /// + /// The template functions work exactly like their non-template namesakes + /// except as follows: The template versions of get_table() and + /// get_or_add_table() throw DescriptorMismatch if the dynamic type of the + /// specified table does not match the statically specified custom table + /// type. The template versions of add_table() and get_or_add_table() set + /// the dynamic type (descriptor) to match the statically specified custom + /// table type. + /// + /// \param index Index of table in this group. + /// + /// \param name Name of table. All strings are valid table names as long as + /// they are valid UTF-8 encodings and the number of bytes does not exceed + /// `max_table_name_length`. A call to add_table() or get_or_add_table() + /// with a name that is longer than `max_table_name_length` will cause an + /// exception to be thrown. + /// + /// \param new_name New name for preexisting table. + /// + /// \param require_unique_name When set to true (the default), it becomes + /// impossible to add a table with a name that is already in use, or to + /// rename a table to a name that is already in use. + /// + /// \param was_added When specified, the boolean variable is set to true if + /// the table was added, and to false otherwise. If the function throws, the + /// boolean variable retains its original value. + /// + /// \return get_table(), add_table(), and get_or_add_table() return a table + /// accessor attached to the requested (or added) table. get_table() may + /// return null. + /// + /// \throw DescriptorMismatch Thrown by get_table() and get_or_add_table() + /// tf the dynamic table type does not match the statically specified custom + /// table type (\a T). + /// + /// \throw NoSuchTable Thrown by remove_table() and rename_table() if there + /// is no table with the specified \a name. + /// + /// \throw TableNameInUse Thrown by add_table() if \a require_unique_name is + /// true and \a name clashes with the name of a preexisting table. Thrown by + /// rename_table() if \a require_unique_name is true and \a new_name clashes + /// with the name of a preexisting table. + /// + /// \throw CrossTableLinkTarget Thrown by remove_table() if the specified + /// table is the target of a link column of a different table. + /// + //@{ + + static const size_t max_table_name_length = 63; + + bool has_table(StringData name) const noexcept; + size_t find_table(StringData name) const noexcept; + StringData get_table_name(size_t table_ndx) const; + + TableRef get_table(size_t index); + ConstTableRef get_table(size_t index) const; + + TableRef get_table(StringData name); + ConstTableRef get_table(StringData name) const; + + TableRef add_table(StringData name, bool require_unique_name = true); + TableRef insert_table(size_t index, StringData name, bool require_unique_name = true); + TableRef get_or_add_table(StringData name, bool* was_added = nullptr); + TableRef get_or_insert_table(size_t index, StringData name, bool* was_added = nullptr); + + void remove_table(size_t index); + void remove_table(StringData name); + + void rename_table(size_t index, StringData new_name, bool require_unique_name = true); + void rename_table(StringData name, StringData new_name, bool require_unique_name = true); + + //@} + + // Serialization + + /// Write this database to the specified output stream. + /// + /// \param out The destination output stream to write to. + /// + /// \param pad If true, the file is padded to ensure the footer is aligned + /// to the end of a page + void write(std::ostream& out, bool pad = false) const; + + /// Write this database to a new file. It is an error to specify a + /// file that already exists. This is to protect against + /// overwriting a database file that is currently open, which + /// would cause undefined behaviour. + /// + /// \param file A filesystem path. + /// + /// \param encryption_key 32-byte key used to encrypt the database file, + /// or nullptr to disable encryption. + /// + /// \param version If different from 0, the new file will be a full fledged + /// realm file with free list and history info. The version of the commit + /// will be set to the value given here. + /// + /// \throw util::File::AccessError If the file could not be + /// opened. If the reason corresponds to one of the exception + /// types that are derived from util::File::AccessError, the + /// derived exception type is thrown. In particular, + /// util::File::Exists will be thrown if the file exists already. + void write(const std::string& file, const char* encryption_key = nullptr, uint64_t version = 0) const; + + /// Write this database to a memory buffer. + /// + /// Ownership of the returned buffer is transferred to the + /// caller. The memory will have been allocated using + /// std::malloc(). + BinaryData write_to_mem() const; + + /// Commit changes to the attached file. This requires that the + /// attached file is opened in read/write mode. + /// + /// Calling this function on an unattached group, a free-standing + /// group, a group whose attached file is opened in read-only + /// mode, a group that is attached to a memory buffer, or a group + /// that is managed by a shared group, is an error and will result + /// in undefined behavior. + /// + /// Table accesors will remain valid across the commit. Note that + /// this is not the case when working with proper transactions. + void commit(); + + //@{ + /// Some operations on Tables in a Group can cause indirect changes to other + /// fields, including in other Tables in the same Group. Specifically, + /// removing a row will set any links to that row to null, and if it had the + /// last strong links to other rows, will remove those rows. When this + /// happens, The cascade notification handler will be called with a + /// CascadeNotification containing information about what indirect changes + /// will occur, before any changes are made. + /// + /// has_cascade_notification_handler() returns true if and only if there is + /// currently a non-null notification handler registered. + /// + /// set_cascade_notification_handler() replaces the current handler (if any) + /// with the passed in handler. Pass in nullptr to remove the current handler + /// without registering a new one. + /// + /// CascadeNotification contains a vector of rows which will be removed and + /// a vector of links which will be set to null (or removed, for entries in + /// LinkLists). + struct CascadeNotification { + struct row { + /// Non-zero iff the removal of this row is ordered + /// (Table::remove()), as opposed to ordered + /// (Table::move_last_over()). Implicit removals are always + /// unordered. + /// + /// This flag does not take part in comparisons (operator==() and + /// operator<()). + size_t is_ordered_removal : 1; + + /// Index within group of a group-level table. + size_t table_ndx : std::numeric_limits::digits - 1; + + /// Row index which will be removed. + size_t row_ndx; + + row() + : is_ordered_removal(0) + { + } + + bool operator==(const row&) const noexcept; + bool operator!=(const row&) const noexcept; + + /// Trivial lexicographic order + bool operator<(const row&) const noexcept; + }; + + struct link { + const Table* origin_table; ///< A group-level table. + size_t origin_col_ndx; ///< Link column being nullified. + size_t origin_row_ndx; ///< Row in column being nullified. + /// The target row index which is being removed. Mostly relevant for + /// LinkList (to know which entries are being removed), but also + /// valid for Link. + size_t old_target_row_ndx; + }; + + /// A sorted list of rows which will be removed by the current operation. + std::vector rows; + + /// An unordered list of links which will be nullified by the current + /// operation. + std::vector links; + }; + + bool has_cascade_notification_handler() const noexcept; + void set_cascade_notification_handler(std::function new_handler) noexcept; + + //@} + + //@{ + /// During sync operation, schema changes may happen at runtime as connected + /// clients update their schema as part of an app update. Since this is a + /// relatively rare event, no attempt is made at limiting the amount of work + /// the handler is required to do to update its information about table and + /// column indices (i.e., all table and column indices must be recalculated). + /// + /// At the time of writing, only additive schema changes may occur in that + /// scenario. + /// + /// has_schema_change_notification_handler() returns true iff there is currently + /// a non-null notification handler registered. + /// + /// set_schema_change_notification_handler() replaces the current handler (if any) + /// with the passed in handler. Pass in nullptr to remove the current handler + /// without registering a new one. + + bool has_schema_change_notification_handler() const noexcept; + void set_schema_change_notification_handler(std::function new_handler) noexcept; + + //@} + + // Conversion + template + void to_json(S& out, size_t link_depth = 0, std::map* renames = nullptr) const; + void to_string(std::ostream& out) const; + + /// Compare two groups for equality. Two groups are equal if, and + /// only if, they contain the same tables in the same order, that + /// is, for each table T at index I in one of the groups, there is + /// a table at index I in the other group that is equal to T. + /// Tables are equal if they have the same content and the same table name. + bool operator==(const Group&) const; + + /// Compare two groups for inequality. See operator==(). + bool operator!=(const Group& g) const + { + return !(*this == g); + } + + /// Control of what to include when computing memory usage + enum SizeAggregateControl { + size_of_state = 1, ///< size of tables, indexes, toplevel array + size_of_history = 2, ///< size of the in-file history compartment + size_of_freelists = 4, ///< size of the freelists + size_of_all = 7 + }; + /// Compute the sum of the sizes in number of bytes of all the array nodes + /// that currently make up this group. When this group represents a snapshot + /// in a Realm file (such as during a read transaction via a SharedGroup + /// instance), this function computes the footprint of that snapshot within + /// the Realm file. + /// + /// If this group accessor is the detached state, this function returns + /// zero. + size_t compute_aggregated_byte_size(SizeAggregateControl ctrl = SizeAggregateControl::size_of_all) const noexcept; + + void verify() const; +#ifdef REALM_DEBUG + void print() const; + void print_free() const; + MemStats stats(); + void enable_mem_diagnostics(bool enable = true) + { + m_alloc.enable_debug(enable); + } + void to_dot(std::ostream&) const; + void to_dot() const; // To std::cerr (for GDB) + void to_dot(const char* file_path) const; +#endif + +private: + SlabAlloc m_alloc; + + int m_file_format_version; + /// `m_top` is the root node (or top array) of the Realm, and has the + /// following layout: + /// + ///
+    ///
+    ///                                                     Introduced in file
+    ///   Slot  Value                                       format version
+    ///   ---------------------------------------------------------------------
+    ///    1st   m_table_names
+    ///    2nd   m_tables
+    ///    3rd   Logical file size
+    ///    4th   GroupWriter::m_free_positions (optional)
+    ///    5th   GroupWriter::m_free_lengths   (optional)
+    ///    6th   GroupWriter::m_free_versions  (optional)
+    ///    7th   Transaction number / version  (optional)
+    ///    8th   History type         (optional)             4
+    ///    9th   History ref          (optional)             4
+    ///   10th   History version      (optional)             7
+    ///
+    /// 
+ /// + /// The 'History type' slot stores a value of type + /// Replication::HistoryType. The 'History version' slot stores a history + /// schema version as returned by Replication::get_history_schema_version(). + /// + /// The first three entries are mandatory. In files created by + /// Group::write(), none of the optional entries are present and the size of + /// `m_top` is 3. In files updated by Group::commit(), the 4th and 5th entry + /// are present, and the size of `m_top` is 5. In files updated by way of a + /// transaction (SharedGroup::commit()), the 4th, 5th, 6th, and 7th entry + /// are present, and the size of `m_top` is 7. In files that contain a + /// changeset history, the 8th, 9th, and 10th entry are present, except that + /// if the file was opened in nonshared mode (via Group::open()), and the + /// file format remains at 6 (not previously upgraded to 7 or later), then + /// the 10th entry will be absent. + /// + /// When a group accessor is attached to a newly created file or an empty + /// memory buffer where there is no top array yet, `m_top`, `m_tables`, and + /// `m_table_names` will be left in the detached state until the initiation + /// of the first write transaction. In particular, they will remain in the + /// detached state during read transactions that precede the first write + /// transaction. + Array m_top; + ArrayInteger m_tables; + ArrayString m_table_names; + + typedef std::vector table_accessors; + mutable table_accessors m_table_accessors; + + bool m_attached = false; + const bool m_is_shared; + + std::function m_notify_handler; + std::function m_schema_change_handler; + std::shared_ptr m_metrics; + size_t m_total_rows; + + struct shared_tag { + }; + Group(shared_tag) noexcept; + + void init_array_parents() noexcept; + + void open(ref_type top_ref, const std::string& file_path); + + /// If `top_ref` is not zero, attach this group accessor to the specified + /// underlying node structure. If `top_ref` is zero and \a + /// create_group_when_missing is true, create a new node structure that + /// represents an empty group, and attach this group accessor to it. It is + /// an error to call this function on an already attached group accessor. + void attach(ref_type top_ref, bool create_group_when_missing); + + /// Detach this group accessor from the underlying node structure. If this + /// group accessors is already in the detached state, this function does + /// nothing (idempotency). + void detach() noexcept; + + /// \param writable Must be set to true when, and only when attaching for a + /// write transaction. + void attach_shared(ref_type new_top_ref, size_t new_file_size, bool writable); + + void create_empty_group(); + + void reset_free_space_tracking(); + + void remap(size_t new_file_size); + void remap_and_update_refs(ref_type new_top_ref, size_t new_file_size); + + /// Recursively update refs stored in all cached array + /// accessors. This includes cached array accessors in any + /// currently attached table accessors. This ensures that the + /// group instance itself, as well as any attached table accessor + /// that exists across Group::commit() will remain valid. This + /// function is not appropriate for use in conjunction with + /// commits via shared group. + void update_refs(ref_type top_ref, size_t old_baseline) noexcept; + + // Overriding method in ArrayParent + void update_child_ref(size_t, ref_type) override; + + // Overriding method in ArrayParent + ref_type get_child_ref(size_t) const noexcept override; + + // Overriding method in Table::Parent + StringData get_child_name(size_t) const noexcept override; + + // Overriding method in Table::Parent + void child_accessor_destroyed(Table*) noexcept override; + + // Overriding method in Table::Parent + std::recursive_mutex* get_accessor_management_lock() noexcept override + { return nullptr; } // we don't need locking for group! + + // Overriding method in Table::Parent + Group* get_parent_group() noexcept override; + + class TableWriter; + class DefaultTableWriter; + + static void write(std::ostream&, int file_format_version, TableWriter&, bool no_top_array, + bool pad_for_encryption, uint_fast64_t version_number); + + typedef void (*DescSetter)(Table&); + typedef bool (*DescMatcher)(const Spec&); + + Table* do_get_table(size_t table_ndx, DescMatcher desc_matcher); + const Table* do_get_table(size_t table_ndx, DescMatcher desc_matcher) const; + Table* do_get_table(StringData name, DescMatcher desc_matcher); + const Table* do_get_table(StringData name, DescMatcher desc_matcher) const; + Table* do_insert_table(size_t, StringData name, DescSetter desc_setter, bool require_unique_name); + Table* do_insert_table(size_t, StringData name, DescSetter desc_setter); + Table* do_get_or_add_table(StringData name, DescMatcher desc_matcher, DescSetter setter, bool* was_added); + Table* do_get_or_insert_table(size_t, StringData name, DescMatcher desc_matcher, DescSetter desc_setter, + bool* was_added); + + void create_and_insert_table(size_t new_table_ndx, StringData name); + Table* create_table_accessor(size_t table_ndx); + + void detach_table_accessors() noexcept; // Idempotent + + void mark_all_table_accessors() noexcept; + + void write(util::File& file, const char* encryption_key, uint_fast64_t version_number) const; + void write(std::ostream&, bool pad, uint_fast64_t version_numer) const; + + Replication* get_replication() const noexcept; + void set_replication(Replication*) noexcept; + std::shared_ptr get_metrics() const noexcept; + void set_metrics(std::shared_ptr other) noexcept; + void update_num_objects(); + class TransactAdvancer; + void advance_transact(ref_type new_top_ref, size_t new_file_size, _impl::NoCopyInputStream&); + void refresh_dirty_accessors(); + template + void update_table_indices(F&& map_function); + + /// \brief The version of the format of the node structure (in file or in + /// memory) in use by Realm objects associated with this group. + /// + /// Every group contains a file format version field, which is returned + /// by this function. The file format version field is set to the file format + /// version specified by the attached file (or attached memory buffer) at the + /// time of attachment and the value is used to determine if a file format + /// upgrade is required. + /// + /// A value of zero means that the file format is not yet decided. This is + /// only possible for empty Realms where top-ref is zero. (When group is created + /// with the unattached_tag). The version number will then be determined in the + /// subsequent call to Group::open. + /// + /// In shared mode (when a Realm file is opened via a SharedGroup instance) + /// it can happen that the file format is upgraded asyncronously (via + /// another SharedGroup instance), and in that case the file format version + /// field can get out of date, but only for a short while. It is always + /// guaranteed to be, and remain up to date after the opening process completes + /// (when SharedGroup::do_open() returns). + /// + /// An empty Realm file (one whose top-ref is zero) may specify a file + /// format version of zero to indicate that the format is not yet + /// decided. In that case the file format version must be changed to a proper + /// before the opening process completes (Group::open() or SharedGroup::open()). + /// + /// File format versions: + /// + /// 1 Initial file format version + /// + /// 2 Various changes. + /// + /// 3 Supporting null on string columns broke the file format in following + /// way: Index appends an 'X' character to all strings except the null + /// string, to be able to distinguish between null and empty + /// string. Bumped to 3 because of null support of String columns and + /// because of new format of index. + /// + /// 4 Introduction of optional in-Realm history of changes (additional + /// entries in Group::m_top). Since this change is not forward + /// compatible, the file format version had to be bumped. This change is + /// implemented in a way that achieves backwards compatibility with + /// version 3 (and in turn with version 2). + /// + /// 5 Introduced the new Timestamp column type that replaces DateTime. + /// When opening an older database file, all DateTime columns will be + /// automatically upgraded Timestamp columns. + /// + /// 6 Introduced a new structure for the StringIndex. Moved the commit + /// logs into the Realm file. Changes to the transaction log format + /// including reshuffling instructions. This is the format used in + /// milestone 2.0.0. + /// + /// 7 Introduced "history schema version" as 10th entry in top array. + /// + /// 8 Subtables can now have search index. + /// + /// 9 Replication instruction values shuffled, instr_MoveRow added. + /// + /// IMPORTANT: When introducing a new file format version, be sure to review + /// the file validity checks in Group::open() and SharedGroup::do_open, the file + /// format selection logic in + /// Group::get_target_file_format_version_for_session(), and the file format + /// upgrade logic in Group::upgrade_file_format(). + + int get_file_format_version() const noexcept; + void set_file_format_version(int) noexcept; + int get_committed_file_format_version() const noexcept; + + /// The specified history type must be a value of Replication::HistoryType. + static int get_target_file_format_version_for_session(int current_file_format_version, int history_type) noexcept; + + /// Must be called from within a write transaction + void upgrade_file_format(int target_file_format_version); + + std::pair get_to_dot_parent(size_t ndx_in_parent) const override; + + void send_cascade_notification(const CascadeNotification& notification) const; + void send_schema_change_notification() const; + + static void get_version_and_history_info(const Array& top, _impl::History::version_type& version, + int& history_type, int& history_schema_version) noexcept; + static ref_type get_history_ref(const Array& top) noexcept; + static int get_history_schema_version(const Array& top) noexcept; + void set_history_schema_version(int version); + void set_history_parent(Array& history_root) noexcept; + void prepare_history_parent(Array& history_root, int history_type, int history_schema_version); + + friend class Table; + friend class GroupWriter; + friend class SharedGroup; + friend class _impl::GroupFriend; + friend class _impl::TransactLogConvenientEncoder; + friend class _impl::TransactLogParser; + friend class Replication; + friend class TrivialReplication; + friend class metrics::QueryInfo; + friend class metrics::Metrics; +}; + + +// Implementation + +inline Group::Group(const std::string& file, const char* key, OpenMode mode) + : m_alloc() // Throws + , m_top(m_alloc) + , m_tables(m_alloc) + , m_table_names(m_alloc) + , m_is_shared(false) + , m_total_rows(0) +{ + init_array_parents(); + + open(file, key, mode); // Throws +} + +inline Group::Group(BinaryData buffer, bool take_ownership) + : m_alloc() // Throws + , m_top(m_alloc) + , m_tables(m_alloc) + , m_table_names(m_alloc) + , m_is_shared(false) + , m_total_rows(0) +{ + init_array_parents(); + open(buffer, take_ownership); // Throws +} + +inline Group::Group(unattached_tag) noexcept + : m_alloc() + , // Throws + m_top(m_alloc) + , m_tables(m_alloc) + , m_table_names(m_alloc) + , m_is_shared(false) + , m_total_rows(0) +{ + init_array_parents(); +} + +inline Group* Group::get_parent_group() noexcept +{ + return this; +} + +inline Group::Group(shared_tag) noexcept + : m_alloc() + , // Throws + m_top(m_alloc) + , m_tables(m_alloc) + , m_table_names(m_alloc) + , m_is_shared(true) + , m_total_rows(0) +{ + init_array_parents(); +} + +inline bool Group::is_attached() const noexcept +{ + return m_attached; +} + +inline bool Group::is_empty() const noexcept +{ + if (!is_attached()) + return false; + if (m_table_names.is_attached()) + return m_table_names.is_empty(); + return true; +} + +inline size_t Group::size() const noexcept +{ + if (!is_attached()) + return 0; + if (m_table_names.is_attached()) + return m_table_names.size(); + return 0; +} + +inline StringData Group::get_table_name(size_t table_ndx) const +{ + if (table_ndx >= size()) + throw LogicError(LogicError::table_index_out_of_range); + return m_table_names.get(table_ndx); +} + +inline bool Group::has_table(StringData name) const noexcept +{ + size_t ndx = find_table(name); + return ndx != not_found; +} + +inline size_t Group::find_table(StringData name) const noexcept +{ + if (!is_attached()) + return 0; + if (m_table_names.is_attached()) + return m_table_names.find_first(name); + return not_found; +} + +inline TableRef Group::get_table(size_t table_ndx) +{ + if (!is_attached()) + throw LogicError(LogicError::detached_accessor); + DescMatcher desc_matcher = nullptr; // Do not check descriptor + Table* table = do_get_table(table_ndx, desc_matcher); // Throws + return TableRef(table); +} + +inline ConstTableRef Group::get_table(size_t table_ndx) const +{ + if (!is_attached()) + throw LogicError(LogicError::detached_accessor); + DescMatcher desc_matcher = nullptr; // Do not check descriptor + const Table* table = do_get_table(table_ndx, desc_matcher); // Throws + return ConstTableRef(table); +} + +inline TableRef Group::get_table(StringData name) +{ + if (!is_attached()) + throw LogicError(LogicError::detached_accessor); + DescMatcher desc_matcher = nullptr; // Do not check descriptor + Table* table = do_get_table(name, desc_matcher); // Throws + return TableRef(table); +} + +inline ConstTableRef Group::get_table(StringData name) const +{ + if (!is_attached()) + throw LogicError(LogicError::detached_accessor); + DescMatcher desc_matcher = nullptr; // Do not check descriptor + const Table* table = do_get_table(name, desc_matcher); // Throws + return ConstTableRef(table); +} + +inline TableRef Group::insert_table(size_t table_ndx, StringData name, bool require_unique_name) +{ + if (!is_attached()) + throw LogicError(LogicError::detached_accessor); + DescSetter desc_setter = nullptr; // Do not add any columns + Table* table = do_insert_table(table_ndx, name, desc_setter, require_unique_name); // Throws + return TableRef(table); +} + +inline TableRef Group::add_table(StringData name, bool require_unique_name) +{ + return insert_table(size(), name, require_unique_name); +} + +inline TableRef Group::get_or_insert_table(size_t table_ndx, StringData name, bool* was_added) +{ + if (!is_attached()) + throw LogicError(LogicError::detached_accessor); + DescMatcher desc_matcher = nullptr; // Do not check descriptor + DescSetter desc_setter = nullptr; // Do not add any columns + Table* table = do_get_or_insert_table(table_ndx, name, desc_matcher, desc_setter, was_added); // Throws + return TableRef(table); +} + +inline TableRef Group::get_or_add_table(StringData name, bool* was_added) +{ + if (!is_attached()) + throw LogicError(LogicError::detached_accessor); + DescMatcher desc_matcher = nullptr; // Do not check descriptor + DescSetter desc_setter = nullptr; // Do not add any columns + Table* table = do_get_or_add_table(name, desc_matcher, desc_setter, was_added); // Throws + return TableRef(table); +} + +template +void Group::to_json(S& out, size_t link_depth, std::map* renames) const +{ + if (!is_attached()) + throw LogicError(LogicError::detached_accessor); + + std::map renames2; + renames = renames ? renames : &renames2; + + out << "{"; + + for (size_t i = 0; i < m_tables.size(); ++i) { + StringData name = m_table_names.get(i); + std::map& m = *renames; + if (m[name] != "") + name = m[name]; + + ConstTableRef table = get_table(i); + + if (i) + out << ","; + out << "\"" << name << "\""; + out << ":"; + table->to_json(out, link_depth, renames); + } + + out << "}"; +} + +inline void Group::init_array_parents() noexcept +{ + m_table_names.set_parent(&m_top, 0); + m_tables.set_parent(&m_top, 1); +} + +inline void Group::update_child_ref(size_t child_ndx, ref_type new_ref) +{ + m_tables.set(child_ndx, new_ref); +} + +inline ref_type Group::get_child_ref(size_t child_ndx) const noexcept +{ + return m_tables.get_as_ref(child_ndx); +} + +inline StringData Group::get_child_name(size_t child_ndx) const noexcept +{ + return m_table_names.get(child_ndx); +} + +inline void Group::child_accessor_destroyed(Table*) noexcept +{ + // Ignore +} + +inline bool Group::has_cascade_notification_handler() const noexcept +{ + return !!m_notify_handler; +} + +inline void +Group::set_cascade_notification_handler(std::function new_handler) noexcept +{ + m_notify_handler = std::move(new_handler); +} + +inline void Group::send_cascade_notification(const CascadeNotification& notification) const +{ + if (m_notify_handler) + m_notify_handler(notification); +} + +inline bool Group::has_schema_change_notification_handler() const noexcept +{ + return !!m_schema_change_handler; +} + +inline void Group::set_schema_change_notification_handler(std::function new_handler) noexcept +{ + m_schema_change_handler = std::move(new_handler); +} + +inline void Group::send_schema_change_notification() const +{ + if (m_schema_change_handler) + m_schema_change_handler(); +} + +inline void Group::get_version_and_history_info(const Array& top, _impl::History::version_type& version, + int& history_type, int& history_schema_version) noexcept +{ + using version_type = _impl::History::version_type; + version_type version_2 = 0; + int history_type_2 = 0; + int history_schema_version_2 = 0; + if (top.is_attached()) { + if (top.size() >= 6) { + REALM_ASSERT(top.size() >= 7); + version_2 = version_type(top.get_as_ref_or_tagged(6).get_as_int()); + } + if (top.size() >= 8) { + REALM_ASSERT(top.size() >= 9); + history_type_2 = int(top.get_as_ref_or_tagged(7).get_as_int()); + } + if (top.size() >= 10) { + history_schema_version_2 = int(top.get_as_ref_or_tagged(9).get_as_int()); + } + } + // Version 0 is not a legal initial version, so it has to be set to 1 + // instead. + if (version_2 == 0) + version_2 = 1; + version = version_2; + history_type = history_type_2; + history_schema_version = history_schema_version_2; +} + +inline ref_type Group::get_history_ref(const Array& top) noexcept +{ + bool has_history = (top.is_attached() && top.size() >= 8); + if (has_history) { + // This function is only used is shared mode (from SharedGroup) + REALM_ASSERT(top.size() >= 10); + return top.get_as_ref(8); + } + return 0; +} + +inline int Group::get_history_schema_version(const Array& top) noexcept +{ + bool has_history = (top.is_attached() && top.size() >= 8); + if (has_history) { + // This function is only used is shared mode (from SharedGroup) + REALM_ASSERT(top.size() >= 10); + return int(top.get_as_ref_or_tagged(9).get_as_int()); + } + return 0; +} + +inline void Group::set_history_schema_version(int version) +{ + // This function is only used is shared mode (from SharedGroup) + REALM_ASSERT(m_top.size() >= 10); + m_top.set(9, RefOrTagged::make_tagged(unsigned(version))); // Throws +} + +inline void Group::set_history_parent(Array& history_root) noexcept +{ + history_root.set_parent(&m_top, 8); +} + +class Group::TableWriter { +public: + struct HistoryInfo { + ref_type ref = 0; + int type = 0; + int version = 0; + }; + + virtual ref_type write_names(_impl::OutputStream&) = 0; + virtual ref_type write_tables(_impl::OutputStream&) = 0; + virtual HistoryInfo write_history(_impl::OutputStream&) = 0; + virtual ~TableWriter() noexcept + { + } +}; + +inline const Table* Group::do_get_table(size_t table_ndx, DescMatcher desc_matcher) const +{ + return const_cast(this)->do_get_table(table_ndx, desc_matcher); // Throws +} + +inline const Table* Group::do_get_table(StringData name, DescMatcher desc_matcher) const +{ + return const_cast(this)->do_get_table(name, desc_matcher); // Throws +} + +inline void Group::reset_free_space_tracking() +{ + m_alloc.reset_free_space_tracking(); // Throws +} + +inline Replication* Group::get_replication() const noexcept +{ + return m_alloc.get_replication(); +} + +inline void Group::set_replication(Replication* repl) noexcept +{ + m_alloc.set_replication(repl); +} + +inline std::shared_ptr Group::get_metrics() const noexcept +{ + return m_metrics; +} + +inline void Group::set_metrics(std::shared_ptr shared) noexcept +{ + m_metrics = shared; +} + +// The purpose of this class is to give internal access to some, but +// not all of the non-public parts of the Group class. +class _impl::GroupFriend { +public: + static Allocator& get_alloc(Group& group) noexcept + { + return group.m_alloc; + } + + static const Allocator& get_alloc(const Group& group) noexcept + { + return group.m_alloc; + } + + static ref_type get_top_ref(const Group& group) noexcept + { + return group.m_top.get_ref(); + } + + static Table& get_table(Group& group, size_t ndx_in_group) + { + Group::DescMatcher desc_matcher = 0; // Do not check descriptor + Table* table = group.do_get_table(ndx_in_group, desc_matcher); // Throws + return *table; + } + + static const Table& get_table(const Group& group, size_t ndx_in_group) + { + Group::DescMatcher desc_matcher = 0; // Do not check descriptor + const Table* table = group.do_get_table(ndx_in_group, desc_matcher); // Throws + return *table; + } + + static Table* get_table(Group& group, StringData name) + { + Group::DescMatcher desc_matcher = 0; // Do not check descriptor + Table* table = group.do_get_table(name, desc_matcher); // Throws + return table; + } + + static const Table* get_table(const Group& group, StringData name) + { + Group::DescMatcher desc_matcher = 0; // Do not check descriptor + const Table* table = group.do_get_table(name, desc_matcher); // Throws + return table; + } + + static Table& insert_table(Group& group, size_t table_ndx, StringData name, bool require_unique_name) + { + Group::DescSetter desc_setter = nullptr; // Do not add any columns + return *group.do_insert_table(table_ndx, name, desc_setter, require_unique_name); + } + + static Table& add_table(Group& group, StringData name, bool require_unique_name) + { + return insert_table(group, group.size(), name, require_unique_name); + } + + static Table& get_or_insert_table(Group& group, size_t table_ndx, StringData name, bool* was_inserted) + { + Group::DescMatcher desc_matcher = nullptr; // Do not check descriptor + Group::DescSetter desc_setter = nullptr; // Do not add any columns + return *group.do_get_or_insert_table(table_ndx, name, desc_matcher, desc_setter, was_inserted); + } + + static Table& get_or_add_table(Group& group, StringData name, bool* was_inserted) + { + Group::DescMatcher desc_matcher = nullptr; // Do not check descriptor + Group::DescSetter desc_setter = nullptr; // Do not add any columns + return *group.do_get_or_add_table(name, desc_matcher, desc_setter, was_inserted); + } + + static void send_cascade_notification(const Group& group, const Group::CascadeNotification& notification) + { + group.send_cascade_notification(notification); + } + + static Replication* get_replication(const Group& group) noexcept + { + return group.get_replication(); + } + + static void set_replication(Group& group, Replication* repl) noexcept + { + group.set_replication(repl); + } + + static void detach(Group& group) noexcept + { + group.detach(); + } + + static void attach_shared(Group& group, ref_type new_top_ref, size_t new_file_size, bool writable) + { + group.attach_shared(new_top_ref, new_file_size, writable); // Throws + } + + static void reset_free_space_tracking(Group& group) + { + group.reset_free_space_tracking(); // Throws + } + + static void remap(Group& group, size_t new_file_size) + { + group.remap(new_file_size); // Throws + } + + static void remap_and_update_refs(Group& group, ref_type new_top_ref, size_t new_file_size) + { + group.remap_and_update_refs(new_top_ref, new_file_size); // Throws + } + + static void advance_transact(Group& group, ref_type new_top_ref, size_t new_file_size, + _impl::NoCopyInputStream& in) + { + group.advance_transact(new_top_ref, new_file_size, in); // Throws + } + + static void create_empty_group_when_missing(Group& group) + { + if (!group.m_top.is_attached()) + group.create_empty_group(); // Throws + } + + static void get_version_and_history_info(const Allocator& alloc, ref_type top_ref, + _impl::History::version_type& version, + int& history_type, + int& history_schema_version) noexcept + { + Array top{const_cast(alloc)}; + if (top_ref != 0) + top.init_from_ref(top_ref); + Group::get_version_and_history_info(top, version, history_type, history_schema_version); + } + + static ref_type get_history_ref(const Group& group) noexcept + { + return Group::get_history_ref(group.m_top); + } + + static ref_type get_history_ref(Allocator& alloc, ref_type top_ref) noexcept + { + Array top(alloc); + if (top_ref != 0) + top.init_from_ref(top_ref); + return Group::get_history_ref(top); + } + + static int get_history_schema_version(const Group& group) noexcept + { + return Group::get_history_schema_version(group.m_top); + } + + static int get_history_schema_version(Allocator& alloc, ref_type top_ref) noexcept + { + Array top{alloc}; + if (top_ref != 0) + top.init_from_ref(top_ref); + return Group::get_history_schema_version(top); + } + + static void set_history_schema_version(Group& group, int version) + { + group.set_history_schema_version(version); // Throws + } + + static void set_history_parent(Group& group, Array& history_root) noexcept + { + group.set_history_parent(history_root); + } + + static void prepare_history_parent(Group& group, Array& history_root, int history_type, + int history_schema_version) + { + group.prepare_history_parent(history_root, history_type, history_schema_version); // Throws + } + + static int get_file_format_version(const Group& group) noexcept + { + return group.get_file_format_version(); + } + + static void set_file_format_version(Group& group, int file_format_version) noexcept + { + group.set_file_format_version(file_format_version); + } + + static int get_committed_file_format_version(const Group& group) noexcept + { + return group.get_committed_file_format_version(); + } + + static int get_target_file_format_version_for_session(int current_file_format_version, int history_type) noexcept + { + return Group::get_target_file_format_version_for_session(current_file_format_version, history_type); + } + + static void upgrade_file_format(Group& group, int target_file_format_version) + { + group.upgrade_file_format(target_file_format_version); // Throws + } +}; + + +struct CascadeState : Group::CascadeNotification { + /// If non-null, then no recursion will be performed for rows of that + /// table. The effect is then exactly as if all the rows of that table were + /// added to \a state.rows initially, and then removed again after the + /// explicit invocations of Table::cascade_break_backlinks_to() (one for + /// each initiating row). This is used by Table::clear() to avoid + /// reentrance. + /// + /// Must never be set concurrently with stop_on_link_list_column. + Table* stop_on_table = nullptr; + + /// If non-null, then Table::cascade_break_backlinks_to() will skip the + /// removal of reciprocal backlinks for the link list at + /// stop_on_link_list_row_ndx in this column, and no recursion will happen + /// on its behalf. This is used by LinkView::clear() to avoid reentrance. + /// + /// Must never be set concurrently with stop_on_table. + LinkListColumn* stop_on_link_list_column = nullptr; + + /// Is ignored if stop_on_link_list_column is null. + size_t stop_on_link_list_row_ndx = 0; + + /// If false, the links field is not needed, so any work done just for that + /// can be skipped. + bool track_link_nullifications = false; + + /// If false, weak links are followed too + bool only_strong_links = true; +}; + +inline bool Group::CascadeNotification::row::operator==(const row& r) const noexcept +{ + return table_ndx == r.table_ndx && row_ndx == r.row_ndx; +} + +inline bool Group::CascadeNotification::row::operator!=(const row& r) const noexcept +{ + return !(*this == r); +} + +inline bool Group::CascadeNotification::row::operator<(const row& r) const noexcept +{ + return table_ndx < r.table_ndx || (table_ndx == r.table_ndx && row_ndx < r.row_ndx); +} + +} // namespace realm + +#endif // REALM_GROUP_HPP diff --git a/Pods/Realm/include/core/realm/group_shared.hpp b/Pods/Realm/include/core/realm/group_shared.hpp new file mode 100644 index 0000000000..f1674403a4 --- /dev/null +++ b/Pods/Realm/include/core/realm/group_shared.hpp @@ -0,0 +1,1214 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_GROUP_SHARED_HPP +#define REALM_GROUP_SHARED_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace realm { + +namespace _impl { +class SharedGroupFriend; +class WriteLogCollector; +} + +/// Thrown by SharedGroup::open() if the lock file is already open in another +/// process which can't share mutexes with this process +struct IncompatibleLockFile : std::runtime_error { + IncompatibleLockFile(const std::string& msg) + : std::runtime_error("Incompatible lock file. " + msg) + { + } +}; + +/// Thrown by SharedGroup::open() if the type of history +/// (Replication::HistoryType) in the opened Realm file is incompatible with the +/// mode in which the Realm file is opened. For example, if there is a mismatch +/// between the history type in the file, and the history type associated with +/// the replication plugin passed to SharedGroup::open(). +/// +/// This exception will also be thrown if the history schema version is lower +/// than required, and no migration is possible +/// (Replication::is_upgradable_history_schema()). +struct IncompatibleHistories : util::File::AccessError { + IncompatibleHistories(const std::string& msg, const std::string& path) + : util::File::AccessError("Incompatible histories. " + msg, path) + { + } +}; + +/// A SharedGroup facilitates transactions. +/// +/// When multiple threads or processes need to access a database +/// concurrently, they must do so using transactions. By design, +/// Realm does not allow for multiple threads (or processes) to +/// share a single instance of SharedGroup. Instead, each concurrently +/// executing thread or process must use a separate instance of +/// SharedGroup. +/// +/// Each instance of SharedGroup manages a single transaction at a +/// time. That transaction can be either a read transaction, or a +/// write transaction. +/// +/// Utility classes ReadTransaction and WriteTransaction are provided +/// to make it safe and easy to work with transactions in a scoped +/// manner (by means of the RAII idiom). However, transactions can +/// also be explicitly started (begin_read(), begin_write()) and +/// stopped (end_read(), commit(), rollback()). +/// +/// If a transaction is active when the SharedGroup is destroyed, that +/// transaction is implicitly terminated, either by a call to +/// end_read() or rollback(). +/// +/// Two processes that want to share a database file must reside on +/// the same host. +/// +/// +/// Desired exception behavior (not yet fully implemented) +/// ------------------------------------------------------ +/// +/// - If any data access API function throws an unexpected exception during a +/// read transaction, the shared group accessor is left in state "error +/// during read". +/// +/// - If any data access API function throws an unexpected exception during a +/// write transaction, the shared group accessor is left in state "error +/// during write". +/// +/// - If SharedGroup::begin_write() or SharedGroup::begin_read() throws an +/// unexpected exception, the shared group accessor is left in state "no +/// transaction in progress". +/// +/// - SharedGroup::end_read() and SharedGroup::rollback() do not throw. +/// +/// - If SharedGroup::commit() throws an unexpected exception, the shared group +/// accessor is left in state "error during write" and the transaction was +/// not committed. +/// +/// - If SharedGroup::advance_read() or SharedGroup::promote_to_write() throws +/// an unexpected exception, the shared group accessor is left in state +/// "error during read". +/// +/// - If SharedGroup::commit_and_continue_as_read() or +/// SharedGroup::rollback_and_continue_as_read() throws an unexpected +/// exception, the shared group accessor is left in state "error during +/// write". +/// +/// It has not yet been decided exactly what an "unexpected exception" is, but +/// `std::bad_alloc` is surely one example. On the other hand, an expected +/// exception is one that is mentioned in the function specific documentation, +/// and is used to abort an operation due to a special, but expected condition. +/// +/// States +/// ------ +/// +/// - A newly created shared group accessor is in state "no transaction in +/// progress". +/// +/// - In state "error during read", almost all Realm API functions are +/// illegal on the connected group of accessors. The only valid operations +/// are destruction of the shared group, and SharedGroup::end_read(). If +/// SharedGroup::end_read() is called, the new state becomes "no transaction +/// in progress". +/// +/// - In state "error during write", almost all Realm API functions are +/// illegal on the connected group of accessors. The only valid operations +/// are destruction of the shared group, and SharedGroup::rollback(). If +/// SharedGroup::end_write() is called, the new state becomes "no transaction +/// in progress" +class SharedGroup { +public: + /// \brief Same as calling the corresponding version of open() on a instance + /// constructed in the unattached state. Exception safety note: if the + /// `upgrade_callback` throws, then the file will be closed properly and the + /// upgrade will be aborted. + explicit SharedGroup(const std::string& file, bool no_create = false, + const SharedGroupOptions options = SharedGroupOptions()); + + /// \brief Same as calling the corresponding version of open() on a instance + /// constructed in the unattached state. Exception safety note: if the + /// `upgrade_callback` throws, then the file will be closed properly and + /// the upgrade will be aborted. + explicit SharedGroup(Replication& repl, const SharedGroupOptions options = SharedGroupOptions()); + + struct unattached_tag { + }; + + /// Create a SharedGroup instance in its unattached state. It may + /// then be attached to a database file later by calling + /// open(). You may test whether this instance is currently in its + /// attached state by calling is_attached(). Calling any other + /// function (except the destructor) while in the unattached state + /// has undefined behavior. + SharedGroup(unattached_tag) noexcept; + + ~SharedGroup() noexcept; + + // Disable copying to prevent accessor errors. If you really want another + // instance, open another SharedGroup object on the same file. + SharedGroup(const SharedGroup&) = delete; + SharedGroup& operator=(const SharedGroup&) = delete; + + /// Attach this SharedGroup instance to the specified database file. + /// + /// While at least one instance of SharedGroup exists for a specific + /// database file, a "lock" file will be present too. The lock file will be + /// placed in the same directory as the database file, and its name will be + /// derived by appending ".lock" to the name of the database file. + /// + /// When multiple SharedGroup instances refer to the same file, they must + /// specify the same durability level, otherwise an exception will be + /// thrown. + /// + /// \param file Filesystem path to a Realm database file. + /// + /// \param no_create If the database file does not already exist, it will be + /// created (unless this is set to true.) When multiple threads are involved, + /// it is safe to let the first thread, that gets to it, create the file. + /// + /// \param options See SharedGroupOptions for details of each option. + /// Sensible defaults are provided if this parameter is left out. + /// + /// Calling open() on a SharedGroup instance that is already in the attached + /// state has undefined behavior. + /// + /// \throw util::File::AccessError If the file could not be opened. If the + /// reason corresponds to one of the exception types that are derived from + /// util::File::AccessError, the derived exception type is thrown. Note that + /// InvalidDatabase is among these derived exception types. + /// + /// \throw FileFormatUpgradeRequired only if \a SharedGroupOptions::allow_upgrade + /// is `false` and an upgrade is required. + void open(const std::string& file, bool no_create = false, + const SharedGroupOptions options = SharedGroupOptions()); + + /// Open this group in replication mode. The specified Replication instance + /// must remain in existence for as long as the SharedGroup. + void open(Replication&, const SharedGroupOptions options = SharedGroupOptions()); + + /// Close any open database, returning to the unattached state. + void close() noexcept; + + /// A SharedGroup may be created in the unattached state, and then + /// later attached to a file with a call to open(). Calling any + /// function other than open(), is_attached(), and ~SharedGroup() + /// on an unattached instance results in undefined behavior. + bool is_attached() const noexcept; + +#ifdef REALM_DEBUG + /// Deprecated method, only called from a unit test + /// + /// Reserve disk space now to avoid allocation errors at a later + /// point in time, and to minimize on-disk fragmentation. In some + /// cases, less fragmentation translates into improved + /// performance. + /// + /// When supported by the system, a call to this function will + /// make the database file at least as big as the specified size, + /// and cause space on the target device to be allocated (note + /// that on many systems on-disk allocation is done lazily by + /// default). If the file is already bigger than the specified + /// size, the size will be unchanged, and on-disk allocation will + /// occur only for the initial section that corresponds to the + /// specified size. + /// + /// It is an error to call this function on an unattached shared + /// group. Doing so will result in undefined behavior. + void reserve(size_t size_in_bytes); +#endif + + /// Querying for changes: + /// + /// NOTE: + /// "changed" means that one or more commits has been made to the database + /// since the SharedGroup (on which wait_for_change() is called) last + /// started, committed, promoted or advanced a transaction. If the + /// SharedGroup has not yet begun a transaction, "changed" is undefined. + /// + /// No distinction is made between changes done by another process + /// and changes done by another thread in the same process as the caller. + /// + /// Has db been changed ? + bool has_changed(); + + /// The calling thread goes to sleep until the database is changed, or + /// until wait_for_change_release() is called. After a call to + /// wait_for_change_release() further calls to wait_for_change() will return + /// immediately. To restore the ability to wait for a change, a call to + /// enable_wait_for_change() is required. Return true if the database has + /// changed, false if it might have. + bool wait_for_change(); + + /// release any thread waiting in wait_for_change() on *this* SharedGroup. + void wait_for_change_release(); + + /// re-enable waiting for change + void enable_wait_for_change(); + // Transactions: + + using version_type = _impl::History::version_type; + using VersionID = realm::VersionID; + + /// Thrown by begin_read() if the specified version does not correspond to a + /// bound (or tethered) snapshot. + struct BadVersion; + + /// \defgroup group_shared_transactions + //@{ + + /// begin_read() initiates a new read transaction. A read transaction is + /// bound to, and provides access to a particular snapshot of the underlying + /// Realm (in general the latest snapshot, but see \a version). It cannot be + /// used to modify the Realm, and in that sense, a read transaction is not a + /// real transaction. + /// + /// begin_write() initiates a new write transaction. A write transaction + /// allows the application to both read and modify the underlying Realm + /// file. At most one write transaction can be in progress at any given time + /// for a particular underlying Realm file. If another write transaction is + /// already in progress, begin_write() will block the caller until the other + /// write transaction terminates. No guarantees are made about the order in + /// which multiple concurrent requests will be served. + /// + /// It is an error to call begin_read() or begin_write() on a SharedGroup + /// object with an active read or write transaction. + /// + /// If begin_read() or begin_write() throws, no transaction is initiated, + /// and the application may try to initiate a new read or write transaction + /// later. + /// + /// end_read() terminates the active read transaction. If no read + /// transaction is active, end_read() does nothing. It is an error to call + /// this function on a SharedGroup object with an active write + /// transaction. end_read() does not throw. + /// + /// commit() commits all changes performed in the context of the active + /// write transaction, and thereby terminates that transaction. This + /// produces a new snapshot in the underlying Realm. commit() returns the + /// version associated with the new snapshot. It is an error to call + /// commit() when there is no active write transaction. If commit() throws, + /// no changes will have been committed, and the transaction will still be + /// active, but in a bad state. In that case, the application must either + /// call rollback() to terminate the bad transaction (in which case a new + /// transaction can be initiated), call close() which also terminates the + /// bad transaction, or destroy the SharedGroup object entirely. When the + /// transaction is in a bad state, the application is not allowed to call + /// any method on the Group accessor or on any of its subordinate accessors + /// (Table, Row, Descriptor). Note that the transaction is also left in a + /// bad state when a modifying operation on any subordinate accessor throws. + /// + /// rollback() terminates the active write transaction and discards any + /// changes performed in the context of it. If no write transaction is + /// active, rollback() does nothing. It is an error to call this function in + /// a SharedGroup object with an active read transaction. rollback() does + /// not throw. + /// + /// the Group accessor and all subordinate accessors (Table, Row, + /// Descriptor) that are obtained in the context of a particular read or + /// write transaction will become detached upon termination of that + /// transaction, which means that they can no longer be used to access the + /// underlying objects. + /// + /// Subordinate accessors that were detached at the end of the previous + /// read or write transaction will not be automatically reattached when a + /// new transaction is initiated. The application must reobtain new + /// accessors during a new transaction to regain access to the underlying + /// objects. + /// + /// \param version If specified, this must be the version associated with a + /// *bound* snapshot. A snapshot is said to be bound (or tethered) if there + /// is at least one active read or write transaction bound to it. A read + /// transaction is bound to the snapshot that it provides access to. A write + /// transaction is bound to the latest snapshot available at the time of + /// initiation of the write transaction. If the specified version is not + /// associated with a bound snapshot, this function throws BadVersion. + /// + /// \throw BadVersion Thrown by begin_read() if the specified version does + /// not correspond to a bound (or tethered) snapshot. + + const Group& begin_read(VersionID version = VersionID()); + void end_read() noexcept; + Group& begin_write(); + // Return true (and take the write lock) if there is no other write + // in progress. In case of contention return false immediately. + // If the write lock is obtained, also provide the Group associated + // with the SharedGroup for further operations. + bool try_begin_write(Group*& group); + version_type commit(); + void rollback() noexcept; + // report statistics of last commit done on THIS shared group. + // The free space reported is what can be expected to be freed + // by compact(). This may not correspond to the space which is free + // at the point where get_stats() is called, since that will include + // memory required to hold older versions of data, which still + // needs to be available. + void get_stats(size_t& free_space, size_t& used_space); + //@} + + enum TransactStage { + transact_Ready, + transact_Reading, + transact_Writing, + }; + + /// Get the current transaction type + TransactStage get_transact_stage() const noexcept; + + /// Get a version id which may be used to request a different SharedGroup + /// to start transaction at a specific version. + VersionID get_version_of_current_transaction(); + + /// Report the number of distinct versions currently stored in the database. + /// Note: the database only cleans up versions as part of commit, so ending + /// a read transaction will not immediately release any versions. + uint_fast64_t get_number_of_versions(); + + /// Compact the database file. + /// - The method will throw if called inside a transaction. + /// - The method will throw if called in unattached state. + /// - The method will return false if other SharedGroups are accessing the + /// database in which case compaction is not done. This is not + /// necessarily an error. + /// It will return true following successful compaction. + /// While compaction is in progress, attempts by other + /// threads or processes to open the database will wait. + /// Be warned that resource requirements for compaction is proportional to + /// the amount of live data in the database. + /// Compaction works by writing the database contents to a temporary + /// database file and then replacing the database with the temporary one. + /// The name of the temporary file is formed by appending + /// ".tmp_compaction_space" to the name of the database + /// + /// If the output_encryption_key is `none` then the file's existing key will + /// be used (if any). If the output_encryption_key is nullptr, the resulting + /// file will be unencrypted. Any other value will change the encryption of + /// the file to the new 64 byte key. + /// + /// FIXME: This function is not yet implemented in an exception-safe manner, + /// therefore, if it throws, the application should not attempt to + /// continue. If may not even be safe to destroy the SharedGroup object. + /// + /// WARNING / FIXME: compact() should NOT be exposed publicly on Windows + /// because it's not crash safe! It may corrupt your database if something fails + bool compact(bool bump_version_number = false, util::Optional output_encryption_key = util::none); + +#ifdef REALM_DEBUG + void test_ringbuf(); +#endif + + /// To handover a table view, query, linkview or row accessor of type T, you + /// must wrap it into a Handover for the transfer. Wrapping and + /// unwrapping of a handover object is done by the methods + /// 'export_for_handover()' and 'import_from_handover()' declared below. + /// 'export_for_handover()' returns a Handover object, and + /// 'import_for_handover()' consumes that object, producing a new accessor + /// which is ready for use in the context of the importing SharedGroup. + /// + /// The Handover always creates a new accessor object at the importing side. + /// For TableViews, there are 3 forms of handover. + /// + /// - with payload move: the payload is handed over and ends up as a payload + /// held by the accessor at the importing side. The accessor on the + /// exporting side will rerun its query and generate a new payload, if + /// TableView::sync_if_needed() is called. If the original payload was in + /// sync at the exporting side, it will also be in sync at the importing + /// side. This is indicated to handover_export() by the argument + /// MutableSourcePayload::Move + /// + /// - with payload copy: a copy of the payload is handed over, so both the + /// accessors on the exporting side *and* the accessors created at the + /// importing side has their own payload. This is indicated to + /// handover_export() by the argument ConstSourcePayload::Copy + /// + /// - without payload: the payload stays with the accessor on the exporting + /// side. On the importing side, the new accessor is created without + /// payload. A call to TableView::sync_if_needed() will trigger generation + /// of a new payload. This form of handover is indicated to + /// handover_export() by the argument ConstSourcePayload::Stay. + /// + /// For all other (non-TableView) accessors, handover is done with payload + /// copy, since the payload is trivial. + /// + /// Handover *without* payload is useful when you want to ship a tableview + /// with its query for execution in a background thread. Handover with + /// *payload move* is useful when you want to transfer the result back. + /// + /// Handover *without* payload or with payload copy is guaranteed *not* to + /// change the accessors on the exporting side. + /// + /// Handover is *not* thread safe and should be carried out + /// by the thread that "owns" the involved accessors. + /// + /// Handover is transitive: + /// If the object being handed over depends on other views + /// (table- or link- ), those objects will be handed over as well. The mode + /// of handover (payload copy, payload move, without payload) is applied + /// recursively. Note: If you are handing over a tableview dependent upon + /// another tableview and using MutableSourcePayload::Move, + /// you are on thin ice! + /// + /// On the importing side, the top-level accessor being created during + /// import takes ownership of all other accessors (if any) being created as + /// part of the import. + + /// Type used to support handover of accessors between shared groups. + template + struct Handover; + + /// thread-safe/const export (mode is Stay or Copy) + /// during export, the following operations on the shared group is locked: + /// - advance_read(), promote_to_write(), commit_and_continue_as_read(), + /// rollback_and_continue_as_read(), close() + template + std::unique_ptr> export_for_handover(const T& accessor, ConstSourcePayload mode); + + // specialization for handover of Rows + template + std::unique_ptr>> export_for_handover(const BasicRow& accessor); + + // destructive export (mode is Move) + template + std::unique_ptr> export_for_handover(T& accessor, MutableSourcePayload mode); + + /// Import an accessor wrapped in a handover object. The import will fail + /// if the importing SharedGroup is viewing a version of the database that + /// is different from the exporting SharedGroup. The call to + /// import_from_handover is not thread-safe. + template + std::unique_ptr import_from_handover(std::unique_ptr> handover); + + // We need two cases for handling of LinkViews, because they are ref counted. + std::unique_ptr> export_linkview_for_handover(const LinkViewRef& accessor); + LinkViewRef import_linkview_from_handover(std::unique_ptr> handover); + + // likewise for Tables. + std::unique_ptr> export_table_for_handover(const TableRef& accessor); + TableRef import_table_from_handover(std::unique_ptr> handover); + + /// When doing handover to background tasks that may be run later, we + /// may want to momentarily pin the current version until the other thread + /// has retrieved it. + /// + /// Pinning can be done in both read- and write-transactions, but with different + /// semantics. When pinning during a read-transaction, the version pinned is the + /// one accessible during the read-transaction. When pinning during a write-transaction, + /// the version pinned will be the last version that was succesfully committed to the + /// realm file at the point in time, when the write-transaction was started. + /// + /// The release is not thread-safe, so it has to be done on the SharedGroup + /// associated with the thread calling unpin_version(), and the SharedGroup + /// must be attached to the realm file at the point of unpinning. + + // Pin version for handover (not thread safe) + VersionID pin_version(); + + // Release pinned version (not thread safe) + void unpin_version(VersionID version); + +#if REALM_METRICS + std::shared_ptr get_metrics(); +#endif // REALM_METRICS + + // Try to grab a exclusive lock of the given realm path's lock file. If the lock + // can be acquired, the callback will be executed with the lock and then return true. + // Otherwise false will be returned directly. + // The lock taken precludes races with other threads or processes accessing the + // files through a SharedGroup. + // It is safe to delete/replace realm files inside the callback. + // WARNING: It is not safe to delete the lock file in the callback. + using CallbackWithLock = std::function; + static bool call_with_lock(const std::string& realm_path, CallbackWithLock callback); + + // Return a list of files/directories core may use of the given realm file path. + // The first element of the pair in the returned list is the path string, the + // second one is to indicate the path is a directory or not. + // The temporary files are not returned by this function. + // It is safe to delete those returned files/directories in the call_with_lock's callback. + static std::vector> get_core_files(const std::string& realm_path); + +private: + struct SharedInfo; + struct ReadCount; + struct ReadLockInfo { + uint_fast64_t m_version = std::numeric_limits::max(); + uint_fast32_t m_reader_idx = 0; + ref_type m_top_ref = 0; + size_t m_file_size = 0; + }; + class ReadLockUnlockGuard; + + // Member variables + size_t m_free_space = 0; + size_t m_used_space = 0; + Group m_group; + ReadLockInfo m_read_lock; + uint_fast32_t m_local_max_entry; + util::File m_file; + util::File::Map m_file_map; // Never remapped + util::File::Map m_reader_map; + bool m_wait_for_change_enabled; + std::string m_lockfile_path; + std::string m_lockfile_prefix; + std::string m_db_path; + std::string m_coordination_dir; + const char* m_key; + TransactStage m_transact_stage; + util::InterprocessMutex m_writemutex; +#ifdef REALM_ASYNC_DAEMON + util::InterprocessMutex m_balancemutex; +#endif + util::InterprocessMutex m_controlmutex; +#ifdef REALM_ASYNC_DAEMON + util::InterprocessCondVar m_room_to_write; + util::InterprocessCondVar m_work_to_do; + util::InterprocessCondVar m_daemon_becomes_ready; +#endif + util::InterprocessCondVar m_new_commit_available; + util::InterprocessCondVar m_pick_next_writer; + std::function m_upgrade_callback; + +#if REALM_METRICS + std::shared_ptr m_metrics; +#endif // REALM_METRICS + + void do_open(const std::string& file, bool no_create, bool is_backend, const SharedGroupOptions options); + + // Ring buffer management + bool ringbuf_is_empty() const noexcept; + size_t ringbuf_size() const noexcept; + size_t ringbuf_capacity() const noexcept; + bool ringbuf_is_first(size_t ndx) const noexcept; + void ringbuf_remove_first() noexcept; + size_t ringbuf_find(uint64_t version) const noexcept; + ReadCount& ringbuf_get(size_t ndx) noexcept; + ReadCount& ringbuf_get_first() noexcept; + ReadCount& ringbuf_get_last() noexcept; + void ringbuf_put(const ReadCount& v); + void ringbuf_expand(); + + /// Grab a read lock on the snapshot associated with the specified + /// version. If `version_id == VersionID()`, a read lock will be grabbed on + /// the latest available snapshot. Fails if the snapshot is no longer + /// available. + /// + /// As a side effect update memory mapping to ensure that the ringbuffer + /// entries referenced in the readlock info is accessible. + /// + /// FIXME: It needs to be made more clear exactly under which conditions + /// this function fails. Also, why is it useful to promise anything about + /// detection of bad versions? Can we really promise enough to make such a + /// promise useful to the caller? + void grab_read_lock(ReadLockInfo&, VersionID); + + // Release a specific read lock. The read lock MUST have been obtained by a + // call to grab_read_lock(). + void release_read_lock(ReadLockInfo&) noexcept; + + void do_begin_read(VersionID, bool writable); + void do_end_read() noexcept; + /// return true if write transaction can commence, false otherwise. + bool do_try_begin_write(); + void do_begin_write(); + version_type do_commit(); + void do_end_write() noexcept; + void set_transact_stage(TransactStage stage) noexcept; + + /// Returns the version of the latest snapshot. + version_type get_version_of_latest_snapshot(); + + /// Returns the version of the snapshot bound in the current read or write + /// transaction. It is an error to call this function when no transaction is + /// in progress. + version_type get_version_of_bound_snapshot() const noexcept; + + // make sure the given index is within the currently mapped area. + // if not, expand the mapped area. Returns true if the area is expanded. + bool grow_reader_mapping(uint_fast32_t index); + + // Must be called only by someone that has a lock on the write + // mutex. + void low_level_commit(uint_fast64_t new_version); + + void do_async_commits(); + + /// Upgrade file format and/or history schema + void upgrade_file_format(bool allow_file_format_upgrade, int target_file_format_version, + int current_hist_schema_version, int target_hist_schema_version); + + //@{ + /// See LangBindHelper. + template + void advance_read(O* observer, VersionID); + template + void promote_to_write(O* observer); + version_type commit_and_continue_as_read(); + template + void rollback_and_continue_as_read(O* observer); + //@} + + /// Returns true if, and only if _impl::History::update_early_from_top_ref() + /// was called during the execution of this function. + template + bool do_advance_read(O* observer, VersionID, _impl::History&); + + /// If there is an associated \ref Replication object, then this function + /// returns `repl->get_history()` where `repl` is that Replication object, + /// otherwise this function returns null. + _impl::History* get_history(); + + int get_file_format_version() const noexcept; + + /// finish up the process of starting a write transaction. Internal use only. + void finish_begin_write(); + + void close_internal(std::unique_lock) noexcept; + friend class _impl::SharedGroupFriend; +}; + + +inline void SharedGroup::get_stats(size_t& free_space, size_t& used_space) { + free_space = m_free_space; + used_space = m_used_space; +} + + +class ReadTransaction { +public: + ReadTransaction(SharedGroup& sg) + : m_shared_group(sg) + { + m_shared_group.begin_read(); // Throws + } + + ~ReadTransaction() noexcept + { + m_shared_group.end_read(); + } + + bool has_table(StringData name) const noexcept + { + return get_group().has_table(name); + } + + ConstTableRef get_table(size_t table_ndx) const + { + return get_group().get_table(table_ndx); // Throws + } + + ConstTableRef get_table(StringData name) const + { + return get_group().get_table(name); // Throws + } + + const Group& get_group() const noexcept; + + /// Get the version of the snapshot to which this read transaction is bound. + SharedGroup::version_type get_version() const noexcept; + +private: + SharedGroup& m_shared_group; +}; + + +class WriteTransaction { +public: + WriteTransaction(SharedGroup& sg) + : m_shared_group(&sg) + { + m_shared_group->begin_write(); // Throws + } + + ~WriteTransaction() noexcept + { + if (m_shared_group) + m_shared_group->rollback(); + } + + bool has_table(StringData name) const noexcept + { + return get_group().has_table(name); + } + + TableRef get_table(size_t table_ndx) const + { + return get_group().get_table(table_ndx); // Throws + } + + TableRef get_table(StringData name) const + { + return get_group().get_table(name); // Throws + } + + TableRef add_table(StringData name, bool require_unique_name = true) const + { + return get_group().add_table(name, require_unique_name); // Throws + } + + TableRef get_or_add_table(StringData name, bool* was_added = nullptr) const + { + return get_group().get_or_add_table(name, was_added); // Throws + } + + Group& get_group() const noexcept; + + /// Get the version of the snapshot on which this write transaction is + /// based. + SharedGroup::version_type get_version() const noexcept; + + SharedGroup::version_type commit() + { + REALM_ASSERT(m_shared_group); + SharedGroup::version_type new_version = m_shared_group->commit(); + m_shared_group = nullptr; + return new_version; + } + + void rollback() noexcept + { + REALM_ASSERT(m_shared_group); + m_shared_group->rollback(); + m_shared_group = nullptr; + } + +private: + SharedGroup* m_shared_group; +}; + + +// Implementation: + +struct SharedGroup::BadVersion : std::exception { +}; + +inline SharedGroup::SharedGroup(const std::string& file, bool no_create, const SharedGroupOptions options) + : m_group(Group::shared_tag()) + , m_upgrade_callback(std::move(options.upgrade_callback)) +{ + open(file, no_create, options); // Throws +} + +inline SharedGroup::SharedGroup(unattached_tag) noexcept + : m_group(Group::shared_tag()) +{ +} + +inline SharedGroup::SharedGroup(Replication& repl, const SharedGroupOptions options) + : m_group(Group::shared_tag()) + , m_upgrade_callback(std::move(options.upgrade_callback)) +{ + open(repl, options); // Throws +} + +inline void SharedGroup::open(const std::string& path, bool no_create_file, const SharedGroupOptions options) +{ + // Exception safety: Since open() is called from constructors, if it throws, + // it must leave the file closed. + + bool is_backend = false; + do_open(path, no_create_file, is_backend, options); // Throws +} + +inline void SharedGroup::open(Replication& repl, const SharedGroupOptions options) +{ + // Exception safety: Since open() is called from constructors, if it throws, + // it must leave the file closed. + + REALM_ASSERT(!is_attached()); + + repl.initialize(*this); // Throws + + typedef _impl::GroupFriend gf; + gf::set_replication(m_group, &repl); + + std::string file = repl.get_database_path(); + bool no_create = false; + bool is_backend = false; + do_open(file, no_create, is_backend, options); // Throws +} + +inline bool SharedGroup::is_attached() const noexcept +{ + return m_file_map.is_attached(); +} + +inline SharedGroup::TransactStage SharedGroup::get_transact_stage() const noexcept +{ + return m_transact_stage; +} + +inline SharedGroup::version_type SharedGroup::get_version_of_bound_snapshot() const noexcept +{ + return m_read_lock.m_version; +} + +class SharedGroup::ReadLockUnlockGuard { +public: + ReadLockUnlockGuard(SharedGroup& shared_group, ReadLockInfo& read_lock) noexcept + : m_shared_group(shared_group) + , m_read_lock(&read_lock) + { + } + ~ReadLockUnlockGuard() noexcept + { + if (m_read_lock) + m_shared_group.release_read_lock(*m_read_lock); + } + void release() noexcept + { + m_read_lock = 0; + } + +private: + SharedGroup& m_shared_group; + ReadLockInfo* m_read_lock; +}; + + +template +struct SharedGroup::Handover { + std::unique_ptr patch; + std::unique_ptr clone; + VersionID version; +}; + +template +std::unique_ptr> SharedGroup::export_for_handover(const T& accessor, ConstSourcePayload mode) +{ + if (m_transact_stage != transact_Reading) + throw LogicError(LogicError::wrong_transact_state); + std::unique_ptr> result(new Handover()); + // Implementation note: + // often, the return value from clone will be T*, BUT it may be ptr to some + // base of T instead, so we must cast it to T*. This is always safe, because + // no matter the type, clone() will clone the actual accessor instance, and + // hence return an instance of the same type. + result->clone.reset(dynamic_cast(accessor.clone_for_handover(result->patch, mode).release())); + result->version = get_version_of_current_transaction(); + return move(result); +} + + +template +std::unique_ptr>> SharedGroup::export_for_handover(const BasicRow& accessor) +{ + if (m_transact_stage != transact_Reading) + throw LogicError(LogicError::wrong_transact_state); + std::unique_ptr>> result(new Handover>()); + // See implementation note above. + result->clone.reset(dynamic_cast*>(accessor.clone_for_handover(result->patch).release())); + result->version = get_version_of_current_transaction(); + return move(result); +} + + +template +std::unique_ptr> SharedGroup::export_for_handover(T& accessor, MutableSourcePayload mode) +{ + if (m_transact_stage != transact_Reading) + throw LogicError(LogicError::wrong_transact_state); + std::unique_ptr> result(new Handover()); + // see implementation note above. + result->clone.reset(dynamic_cast(accessor.clone_for_handover(result->patch, mode).release())); + result->version = get_version_of_current_transaction(); + return move(result); +} + + +template +std::unique_ptr SharedGroup::import_from_handover(std::unique_ptr> handover) +{ + if (handover->version != get_version_of_current_transaction()) { + throw BadVersion(); + } + std::unique_ptr result = move(handover->clone); + result->apply_and_consume_patch(handover->patch, m_group); + return result; +} + +template +inline void SharedGroup::advance_read(O* observer, VersionID version_id) +{ + if (m_transact_stage != transact_Reading) + throw LogicError(LogicError::wrong_transact_state); + + // It is an error if the new version precedes the currently bound one. + if (version_id.version < m_read_lock.m_version) + throw LogicError(LogicError::bad_version); + + _impl::History* hist = get_history(); // Throws + if (!hist) + throw LogicError(LogicError::no_history); + + do_advance_read(observer, version_id, *hist); // Throws +} + +template +inline void SharedGroup::promote_to_write(O* observer) +{ + if (m_transact_stage != transact_Reading) + throw LogicError(LogicError::wrong_transact_state); + + _impl::History* hist = get_history(); // Throws + if (!hist) + throw LogicError(LogicError::no_history); + + do_begin_write(); // Throws + try { + VersionID version = VersionID(); // Latest + bool history_updated = do_advance_read(observer, version, *hist); // Throws + + Replication* repl = m_group.get_replication(); + REALM_ASSERT(repl); // Presence of `repl` follows from the presence of `hist` + version_type current_version = m_read_lock.m_version; + repl->initiate_transact(current_version, history_updated); // Throws + + // If the group has no top array (top_ref == 0), create a new node + // structure for an empty group now, to be ready for modifications. See + // also Group::attach_shared(). + using gf = _impl::GroupFriend; + gf::create_empty_group_when_missing(m_group); // Throws + } + catch (...) { + do_end_write(); + throw; + } + + set_transact_stage(transact_Writing); +} + +template +inline void SharedGroup::rollback_and_continue_as_read(O* observer) +{ + if (m_transact_stage != transact_Writing) + throw LogicError(LogicError::wrong_transact_state); + + _impl::History* hist = get_history(); // Throws + if (!hist) + throw LogicError(LogicError::no_history); + + BinaryData uncommitted_changes = hist->get_uncommitted_changes(); + + // FIXME: We are currently creating two transaction log parsers, one here, + // and one in advance_transact(). That is wasteful as the parser creation is + // expensive. + _impl::SimpleInputStream in(uncommitted_changes.data(), uncommitted_changes.size()); + _impl::TransactLogParser parser; // Throws + _impl::TransactReverser reverser; + parser.parse(in, reverser); // Throws + + if (observer && uncommitted_changes.size()) { + _impl::ReversedNoCopyInputStream reversed_in(reverser); + parser.parse(reversed_in, *observer); // Throws + observer->parse_complete(); // Throws + } + + // Mark all managed space (beyond the attached file) as free. + using gf = _impl::GroupFriend; + gf::reset_free_space_tracking(m_group); // Throws + + ref_type top_ref = m_read_lock.m_top_ref; + size_t file_size = m_read_lock.m_file_size; + _impl::ReversedNoCopyInputStream reversed_in(reverser); + gf::advance_transact(m_group, top_ref, file_size, reversed_in); // Throws + + do_end_write(); + + Replication* repl = gf::get_replication(m_group); + REALM_ASSERT(repl); // Presence of `repl` follows from the presence of `hist` + repl->abort_transact(); + + set_transact_stage(transact_Reading); +} + +template +inline bool SharedGroup::do_advance_read(O* observer, VersionID version_id, _impl::History& hist) +{ + ReadLockInfo new_read_lock; + grab_read_lock(new_read_lock, version_id); // Throws + REALM_ASSERT(new_read_lock.m_version >= m_read_lock.m_version); + if (new_read_lock.m_version == m_read_lock.m_version) { + release_read_lock(new_read_lock); + // _impl::History::update_early_from_top_ref() was not called + return false; + } + + ReadLockUnlockGuard g(*this, new_read_lock); + { + version_type new_version = new_read_lock.m_version; + size_t new_file_size = new_read_lock.m_file_size; + ref_type new_top_ref = new_read_lock.m_top_ref; + + // Synchronize readers view of the file + SlabAlloc& alloc = m_group.m_alloc; + alloc.update_reader_view(new_file_size); + + hist.update_early_from_top_ref(new_version, new_file_size, new_top_ref); // Throws + } + + if (observer) { + // This has to happen in the context of the originally bound snapshot + // and while the read transaction is still in a fully functional state. + _impl::TransactLogParser parser; + version_type old_version = m_read_lock.m_version; + version_type new_version = new_read_lock.m_version; + _impl::ChangesetInputStream in(hist, old_version, new_version); + parser.parse(in, *observer); // Throws + observer->parse_complete(); // Throws + } + + // The old read lock must be retained for as long as the change history is + // accessed (until Group::advance_transact() returns). This ensures that the + // oldest needed changeset remains in the history, even when the history is + // implemented as a separate unversioned entity outside the Realm (i.e., the + // old implementation and ShortCircuitHistory in + // test_lang_Bind_helper.cpp). On the other hand, if it had been the case, + // that the history was always implemented as a versioned entity, that was + // part of the Realm state, then it would not have been necessary to retain + // the old read lock beyond this point. + + { + version_type old_version = m_read_lock.m_version; + version_type new_version = new_read_lock.m_version; + ref_type new_top_ref = new_read_lock.m_top_ref; + size_t new_file_size = new_read_lock.m_file_size; + _impl::ChangesetInputStream in(hist, old_version, new_version); + m_group.advance_transact(new_top_ref, new_file_size, in); // Throws + } + + g.release(); + release_read_lock(m_read_lock); + m_read_lock = new_read_lock; + + return true; // _impl::History::update_early_from_top_ref() was called +} + +inline _impl::History* SharedGroup::get_history() +{ + using gf = _impl::GroupFriend; + if (Replication* repl = gf::get_replication(m_group)) + return repl->get_history(); + return 0; +} + +inline int SharedGroup::get_file_format_version() const noexcept +{ + using gf = _impl::GroupFriend; + return gf::get_file_format_version(m_group); +} + + +// The purpose of this class is to give internal access to some, but +// not all of the non-public parts of the SharedGroup class. +class _impl::SharedGroupFriend { +public: + static Group& get_group(SharedGroup& sg) noexcept + { + return sg.m_group; + } + + template + static void advance_read(SharedGroup& sg, O* obs, SharedGroup::VersionID ver) + { + sg.advance_read(obs, ver); // Throws + } + + template + static void promote_to_write(SharedGroup& sg, O* obs) + { + sg.promote_to_write(obs); // Throws + } + + static SharedGroup::version_type commit_and_continue_as_read(SharedGroup& sg) + { + return sg.commit_and_continue_as_read(); // Throws + } + + template + static void rollback_and_continue_as_read(SharedGroup& sg, O* obs) + { + sg.rollback_and_continue_as_read(obs); // Throws + } + + static void async_daemon_open(SharedGroup& sg, const std::string& file) + { + bool no_create = true; + bool is_backend = true; + SharedGroupOptions options; + options.durability = SharedGroupOptions::Durability::Async; + options.encryption_key = nullptr; + options.allow_file_format_upgrade = false; + sg.do_open(file, no_create, is_backend, options); // Throws + } + + static int get_file_format_version(const SharedGroup& sg) noexcept + { + return sg.get_file_format_version(); + } + + static SharedGroup::version_type get_version_of_latest_snapshot(SharedGroup& sg) + { + return sg.get_version_of_latest_snapshot(); + } + + static SharedGroup::version_type get_version_of_bound_snapshot(const SharedGroup& sg) noexcept + { + return sg.get_version_of_bound_snapshot(); + } +}; + +inline const Group& ReadTransaction::get_group() const noexcept +{ + using sgf = _impl::SharedGroupFriend; + return sgf::get_group(m_shared_group); +} + +inline SharedGroup::version_type ReadTransaction::get_version() const noexcept +{ + using sgf = _impl::SharedGroupFriend; + return sgf::get_version_of_bound_snapshot(m_shared_group); +} + +inline Group& WriteTransaction::get_group() const noexcept +{ + REALM_ASSERT(m_shared_group); + using sgf = _impl::SharedGroupFriend; + return sgf::get_group(*m_shared_group); +} + +inline SharedGroup::version_type WriteTransaction::get_version() const noexcept +{ + using sgf = _impl::SharedGroupFriend; + return sgf::get_version_of_bound_snapshot(*m_shared_group); +} + +} // namespace realm + +#endif // REALM_GROUP_SHARED_HPP diff --git a/Pods/Realm/include/core/realm/group_shared_options.hpp b/Pods/Realm/include/core/realm/group_shared_options.hpp new file mode 100644 index 0000000000..75d5bdadb8 --- /dev/null +++ b/Pods/Realm/include/core/realm/group_shared_options.hpp @@ -0,0 +1,111 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_GROUP_SHARED_OPTIONS_HPP +#define REALM_GROUP_SHARED_OPTIONS_HPP + +#include +#include + +namespace realm { + +struct SharedGroupOptions { + + /// The persistence level of the SharedGroup. + /// uint16_t is the type of SharedGroup::SharedInfo::durability + enum class Durability : uint16_t { + Full, + MemOnly, + Async ///< Not yet supported on windows. + }; + + explicit SharedGroupOptions(Durability level = Durability::Full, const char* key = nullptr, + bool allow_upgrade = true, + std::function file_upgrade_callback = std::function(), + std::string temp_directory = sys_tmp_dir, + bool track_metrics = false) + : durability(level) + , encryption_key(key) + , allow_file_format_upgrade(allow_upgrade) + , upgrade_callback(file_upgrade_callback) + , temp_dir(temp_directory) + , enable_metrics(track_metrics) + + { + } + + explicit SharedGroupOptions(const char* key) + : durability(Durability::Full) + , encryption_key(key) + , allow_file_format_upgrade(true) + , upgrade_callback(std::function()) + , temp_dir(sys_tmp_dir) + , enable_metrics(false) + { + } + + /// The persistence level of the Realm file. See Durability. + Durability durability; + + /// The key to encrypt and decrypt the Realm file with, or nullptr to + /// indicate that encryption should not be used. + const char* encryption_key; + + /// If \a allow_file_format_upgrade is set to `true`, this function will + /// automatically upgrade the file format used in the specified Realm file + /// if necessary (and if it is possible). In order to prevent this, set \a + /// allow_upgrade to `false`. + /// + /// If \a allow_upgrade is set to `false`, only two outcomes are possible: + /// + /// - the specified Realm file is already using the latest file format, and + /// can be used, or + /// + /// - the specified Realm file uses a deprecated file format, resulting a + /// the throwing of FileFormatUpgradeRequired. + bool allow_file_format_upgrade; + + /// Optionally allows a custom function to be called immediately after the + /// Realm file is upgraded. The two parameters in the function are the + /// previous version and the version just upgraded to, respectively. + /// If the callback function throws, the Realm file will safely abort the + /// upgrade (rollback the transaction) but the SharedGroup will not be opened. + std::function upgrade_callback; + + /// A path to a directory where Realm can write temporary files or pipes to. + /// This string should include a trailing slash '/'. + std::string temp_dir; + + /// Controls the feature of collecting various metrics to the SharedGroup. + /// A prerequisite is compiling with REALM_METRICS=ON. + bool enable_metrics; + + /// sys_tmp_dir will be used if the temp_dir is empty when creating SharedGroupOptions. + /// It must be writable and allowed to create pipe/fifo file on it. + /// set_sys_tmp_dir is not a thread-safe call and it is only supposed to be called once + // when process starts. + static void set_sys_tmp_dir(const std::string& dir) noexcept { sys_tmp_dir = dir; } + static std::string get_sys_tmp_dir() noexcept { return sys_tmp_dir; } + +private: + static std::string sys_tmp_dir; +}; + +} // end namespace realm + +#endif // REALM_GROUP_SHARED_OPTIONS_HPP diff --git a/Pods/Realm/include/core/realm/group_writer.hpp b/Pods/Realm/include/core/realm/group_writer.hpp new file mode 100644 index 0000000000..61601053a2 --- /dev/null +++ b/Pods/Realm/include/core/realm/group_writer.hpp @@ -0,0 +1,189 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_GROUP_WRITER_HPP +#define REALM_GROUP_WRITER_HPP + +#include // unint8_t etc +#include +#include + +#include +#include +#include +#include + + +namespace realm { + +// Pre-declarations +class Group; +class SlabAlloc; + + +/// This class is not supposed to be reused for multiple write sessions. In +/// particular, do not reuse it in case any of the functions throw. +/// +/// FIXME: Move this class to namespace realm::_impl and to subdir src/realm/impl. +class GroupWriter : public _impl::ArrayWriterBase { +public: + // For groups in transactional mode (Group::m_is_shared), this constructor + // must be called while a write transaction is in progress. + // + // The constructor adds free-space tracking information to the specified + // group, if it is not already present (4th and 5th entry in + // Group::m_top). If the specified group is in transactional mode + // (Group::m_is_shared), the constructor also adds version tracking + // information to the group, if it is not already present (6th and 7th entry + // in Group::m_top). + GroupWriter(Group&); + ~GroupWriter(); + + void set_versions(uint64_t current, uint64_t read_lock) noexcept; + + /// Write all changed array nodes into free space. + /// + /// Returns the new top ref. When in full durability mode, call + /// commit() with the returned top ref. + ref_type write_group(); + + /// Flush changes to physical medium, then write the new top ref + /// to the file header, then flush again. Pass the top ref + /// returned by write_group(). + void commit(ref_type new_top_ref); + + size_t get_file_size() const noexcept; + + /// Write the specified chunk into free space. + void write(const char* data, size_t size); + + ref_type write_array(const char*, size_t, uint32_t) override; + +#ifdef REALM_DEBUG + void dump(); +#endif + + size_t get_free_space(); +private: + class MapWindow; + Group& m_group; + SlabAlloc& m_alloc; + ArrayInteger m_free_positions; // 4th slot in Group::m_top + ArrayInteger m_free_lengths; // 5th slot in Group::m_top + ArrayInteger m_free_versions; // 6th slot in Group::m_top + uint64_t m_current_version; + uint64_t m_readlock_version; + size_t m_window_alignment; + + struct FreeSpaceEntry { + FreeSpaceEntry(size_t r, size_t s, uint64_t v) + : ref(r) + , size(s) + , released_at_version(v) + { + } + size_t ref; + size_t size; + uint64_t released_at_version; + }; + std::vector m_free_in_file; + std::vector m_not_free_in_file; + std::multimap m_size_map; + using FreeListElement = std::multimap::iterator; + + void sort_freelist(); + // Merge adjacent chunks + void merge_adjacent_entries_in_freelist(); + void read_in_freelist(); + size_t recreate_freelist(size_t reserve_pos); + // Currently cached memory mappings. We keep as many as 16 1MB windows + // open for writing. The allocator will favor sequential allocation + // from a modest number of windows, depending upon fragmentation, so + // 16 windows should be more than enough. If more than 16 windows are + // needed, the least recently used is sync'ed and closed to make room + // for a new one. The windows are kept in MRU (most recently used) order. + const static int num_map_windows = 16; + std::vector> m_map_windows; + + // Get a suitable memory mapping for later access: + // potentially adding it to the cache, potentially closing + // the least recently used and sync'ing it to disk + MapWindow* get_window(ref_type start_ref, size_t size); + + // Sync all cached memory mappings + void sync_all_mappings(); + + // Copy free space entries to structure where entries are sorted by size + void move_free_in_file_to_size_map(); + + /// Allocate a chunk of free space of the specified size. The + /// specified size must be 8-byte aligned. Extend the file if + /// required. The returned chunk is removed from the amount of + /// remaing free space. The returned chunk is guaranteed to be + /// within a single contiguous memory mapping. + /// + /// \return The position within the database file of the allocated + /// chunk. + size_t get_free_space(size_t size); + + /// Find a block of free space that is at least as big as the + /// specified size and which will allow an allocation that is mapped + /// inside a contiguous address range. The specified size does not + /// need to be 8-byte aligned. Extend the file if required. + /// The returned chunk is not removed from the amount of remaing + /// free space. + /// + /// \return A pair (`chunk_ndx`, `chunk_size`) where `chunk_ndx` + /// is the index of a chunk whose size is at least the requestd + /// size, and `chunk_size` is the size of that chunk. + FreeListElement reserve_free_space(size_t size); + + FreeListElement search_free_space_in_free_list_element(FreeListElement element, size_t size); + + /// Search only a range of the free list for a block as big as the + /// specified size. Return a pair with index and size of the found chunk. + /// \param found indicates whether a suitable block was found. + FreeListElement search_free_space_in_part_of_freelist(size_t size); + + /// Extend the file to ensure that a chunk of free space of the + /// specified size is available. The specified size does not need + /// to be 8-byte aligned. This function guarantees that it will + /// add at most one entry to the free-lists. + /// + /// \return A pair (`chunk_ndx`, `chunk_size`) where `chunk_ndx` + /// is the index of a chunk whose size is at least the requestd + /// size, and `chunk_size` is the size of that chunk. + FreeListElement extend_free_space(size_t requested_size); + + void write_array_at(MapWindow* window, ref_type, const char* data, size_t size); + FreeListElement split_freelist_chunk(FreeListElement, size_t alloc_pos); +}; + + +// Implementation: + +inline void GroupWriter::set_versions(uint64_t current, uint64_t read_lock) noexcept +{ + REALM_ASSERT(read_lock <= current); + m_current_version = current; + m_readlock_version = read_lock; +} + +} // namespace realm + +#endif // REALM_GROUP_WRITER_HPP diff --git a/Pods/Realm/include/core/realm/handover_defs.hpp b/Pods/Realm/include/core/realm/handover_defs.hpp new file mode 100644 index 0000000000..ad57b5cd2d --- /dev/null +++ b/Pods/Realm/include/core/realm/handover_defs.hpp @@ -0,0 +1,96 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_HANDOVER_DEFS +#define REALM_HANDOVER_DEFS + +#include +#include + +namespace realm { + +enum class ConstSourcePayload { Copy, Stay }; +enum class MutableSourcePayload { Move }; + +struct RowBaseHandoverPatch; +struct TableViewHandoverPatch; + +struct TableHandoverPatch { + bool m_is_sub_table; + size_t m_table_num; + size_t m_col_ndx; + size_t m_row_ndx; +}; + +struct LinkViewHandoverPatch { + std::unique_ptr m_table; + size_t m_col_num; + size_t m_row_ndx; +}; + +// Base class for handover patches for query nodes. Subclasses are declared in query_engine.hpp. +struct QueryNodeHandoverPatch { + virtual ~QueryNodeHandoverPatch() = default; +}; + +using QueryNodeHandoverPatches = std::vector>; + +struct QueryHandoverPatch { + std::unique_ptr m_table; + std::unique_ptr table_view_data; + std::unique_ptr link_view_data; + QueryNodeHandoverPatches m_node_data; +}; + +enum class DescriptorType { + Sort, + Distinct, + Limit +}; + +struct DescriptorExport { + DescriptorType type; + std::vector> columns; + std::vector ordering; + size_t limit; +}; + +struct DescriptorOrderingHandoverPatch { + std::vector descriptors; +}; + +struct TableViewHandoverPatch { + std::unique_ptr m_table; + std::unique_ptr linked_row; + size_t linked_col; + bool was_in_sync; + QueryHandoverPatch query_patch; + std::unique_ptr linkview_patch; + std::unique_ptr descriptors_patch; +}; + + +struct RowBaseHandoverPatch { + std::unique_ptr m_table; + size_t row_ndx; +}; + + +} // end namespace Realm + +#endif diff --git a/Pods/Realm/include/core/realm/history.hpp b/Pods/Realm/include/core/realm/history.hpp new file mode 100644 index 0000000000..9710d0b8df --- /dev/null +++ b/Pods/Realm/include/core/realm/history.hpp @@ -0,0 +1,35 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_HISTORY_HPP +#define REALM_HISTORY_HPP + +#include +#include + +#include + + +namespace realm { + +std::unique_ptr make_in_realm_history(const std::string& realm_path); + +} // namespace realm + + +#endif // REALM_HISTORY_HPP diff --git a/Pods/Realm/include/core/realm/impl/array_writer.hpp b/Pods/Realm/include/core/realm/impl/array_writer.hpp new file mode 100644 index 0000000000..f039ad505f --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/array_writer.hpp @@ -0,0 +1,44 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ARRAY_WRITER_HPP +#define REALM_ARRAY_WRITER_HPP + +#include + +namespace realm { +namespace _impl { + +class ArrayWriterBase { +public: + virtual ~ArrayWriterBase() + { + } + + /// Write the specified array data and its checksum into free + /// space. + /// + /// Returns the ref (position in the target stream) of the written copy of + /// the specified array data. + virtual ref_type write_array(const char* data, size_t size, uint32_t checksum) = 0; +}; + +} // namespace impl_ +} // namespace realm + +#endif // REALM_ARRAY_WRITER_HPP diff --git a/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp b/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp new file mode 100644 index 0000000000..353e54662d --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp @@ -0,0 +1,49 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_IMPL_CLAMPED_HEX_DUMP_HPP +#define REALM_IMPL_CLAMPED_HEX_DUMP_HPP + +#include +#include + +namespace realm { +namespace _impl { + +/// Limit the amount of dumped data to 1024 bytes. For use in connection with +/// logging. +inline std::string clamped_hex_dump(BinaryData blob, std::size_t max_size = 1024) +{ + bool was_clipped = false; + std::size_t size_2 = blob.size(); + if (size_2 > max_size) { + size_2 = max_size; + was_clipped = true; + } + std::string str = util::hex_dump(blob.data(), size_2); // Throws + if (was_clipped) + str += "..."; // Throws + return str; +} + +} // namespace _impl +} // namespace realm + +#endif // REALM_IMPL_CLAMPED_HEX_DUMP_HPP diff --git a/Pods/Realm/include/core/realm/impl/clock.hpp b/Pods/Realm/include/core/realm/impl/clock.hpp new file mode 100644 index 0000000000..fdf8aa3b65 --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/clock.hpp @@ -0,0 +1,54 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_IMPL_CLOCK_HPP +#define REALM_IMPL_CLOCK_HPP + +#include +#include + +#include + +namespace realm { +namespace _impl { + +inline sync::milliseconds_type realtime_clock_now() noexcept +{ + using clock = std::chrono::system_clock; + auto time_since_epoch = clock::now().time_since_epoch(); + auto millis_since_epoch = + std::chrono::duration_cast(time_since_epoch).count(); + return sync::milliseconds_type(millis_since_epoch); +} + + +inline sync::milliseconds_type monotonic_clock_now() noexcept +{ + using clock = std::chrono::steady_clock; + auto time_since_epoch = clock::now().time_since_epoch(); + auto millis_since_epoch = + std::chrono::duration_cast(time_since_epoch).count(); + return sync::milliseconds_type(millis_since_epoch); +} + +} // namespace _impl +} // namespace realm + +#endif // REALM_IMPL_CLOCK_HPP diff --git a/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp b/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp new file mode 100644 index 0000000000..54e0c84c49 --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp @@ -0,0 +1,153 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_IMPL_CONT_TRANSACT_HIST_HPP +#define REALM_IMPL_CONT_TRANSACT_HIST_HPP + +#include +#include + +#include +#include + +namespace realm { + +class Group; + +namespace _impl { + +/// Read-only access to history of changesets as needed to enable continuous +/// transactions. +class History { +public: + using version_type = VersionID::version_type; + + /// May be called during a read transaction to gain early access to the + /// history as it appears in a new snapshot that succeeds the one bound in + /// the current read transaction. + /// + /// May also be called at other times as long as the caller owns a read lock + /// (SharedGroup::grab_read_lock()) on the Realm for the specified file size + /// and top ref, and the allocator is in a 'free space clean' state + /// (SlabAlloc::is_free_space_clean()). + /// + /// This function may cause a remapping of the Realm file + /// (SlabAlloc::remap()) if it needs to make the new snapshot fully visible + /// in memory. + /// + /// Note that this method of gaining early access to the history in a new + /// snaphot only gives read access. It does not allow for modifications of + /// the history or any other part of the new snapshot. For modifications to + /// be allowed, `Group::m_top` (the parent of the history) would first have + /// to be updated to reflect the new snapshot, but at that time we are no + /// longer in an 'early access' situation. + /// + /// This is not a problem from the point of view of this history interface, + /// as it only contains methods for reading from the history, but some + /// implementations will want to also provide for ways to modify the + /// history, but in those cases, modifications must occur only after the + /// Group accessor has been fully updated to reflect the new snapshot. + virtual void update_early_from_top_ref(version_type new_version, size_t new_file_size, ref_type new_top_ref) = 0; + + virtual void update_from_parent(version_type current_version) = 0; + + /// Get all changesets between the specified versions. References to those + /// changesets will be made availble in successive entries of `buffer`. The + /// number of retreived changesets is exactly `end_version - + /// begin_version`. If this number is greater than zero, the changeset made + /// avaialable in `buffer[0]` is the one that brought the database from + /// `begin_version` to `begin_version + 1`. + /// + /// It is an error to specify a version (for \a begin_version or \a + /// end_version) that is outside the range [V,W] where V is the version that + /// immediately precedes the first changeset available in the history as the + /// history appears in the **latest** available snapshot, and W is the + /// versionm that immediately succeeds the last changeset available in the + /// history as the history appears in the snapshot bound to the **current** + /// transaction. This restriction is necessary to allow for different kinds + /// of implementations of the history (separate standalone history or + /// history as part of versioned Realm state). + /// + /// The calee retains ownership of the memory referenced by those entries, + /// i.e., the memory referenced by `buffer[i].changeset` is **not** handed + /// over to the caller. + /// + /// This function may be called only during a transaction (prior to + /// initiation of commit operation), and only after a successfull invocation + /// of update_early_from_top_ref(). In that case, the caller may assume that + /// the memory references stay valid for the remainder of the transaction + /// (up until initiation of the commit operation). + virtual void get_changesets(version_type begin_version, version_type end_version, BinaryIterator* buffer) const + noexcept = 0; + + /// \brief Specify the version of the oldest bound snapshot. + /// + /// This function must be called by the associated SharedGroup object during + /// each successfully committed write transaction. It must be called before + /// the transaction is finalized (Replication::finalize_commit()) or aborted + /// (Replication::abort_transact()), but after the initiation of the commit + /// operation (Replication::prepare_commit()). This allows history + /// implementations to add new history entries before triming off old ones, + /// and this, in turn, guarantees that the history never becomes empty, + /// except in the initial empty Realm state. + /// + /// The caller must pass the version (\a version) of the oldest snapshot + /// that is currently (or was recently) bound via a transaction of the + /// current session. This gives the history implementation an opportunity to + /// trim off leading (early) history entries. + /// + /// Since this function must be called during a write transaction, there + /// will always be at least one snapshot that is currently bound via a + /// transaction. + /// + /// The caller must guarantee that the passed version (\a version) is less + /// than or equal to `begin_version` in all future invocations of + /// get_changesets(). + /// + /// The caller is allowed to pass a version that is less than the version + /// passed in a preceeding invocation. + /// + /// This function should be called as late as possible, to maximize the + /// trimming opportunity, but at a time where the write transaction is still + /// open for additional modifications. This is necessary because some types + /// of histories are stored inside the Realm file. + virtual void set_oldest_bound_version(version_type version) = 0; + + /// Get the list of uncommited changes accumulated so far in the current + /// write transaction. + /// + /// The callee retains ownership of the referenced memory. The ownership is + /// not handed over the the caller. + /// + /// This function may be called only during a write transaction (prior to + /// initiation of commit operation). In that case, the caller may assume that the + /// returned memory reference stays valid for the remainder of the transaction (up + /// until initiation of the commit operation). + virtual BinaryData get_uncommitted_changes() noexcept = 0; + + virtual void verify() const = 0; + + virtual ~History() noexcept + { + } +}; + +} // namespace _impl +} // namespace realm + +#endif // REALM_IMPL_CONTINUOUS_TRANSACTIONS_HISTORY_HPP diff --git a/Pods/Realm/include/core/realm/impl/destroy_guard.hpp b/Pods/Realm/include/core/realm/impl/destroy_guard.hpp new file mode 100644 index 0000000000..f5b5e37f55 --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/destroy_guard.hpp @@ -0,0 +1,237 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_IMPL_DESTROY_GUARD_HPP +#define REALM_IMPL_DESTROY_GUARD_HPP + +#include +#include + +namespace realm { +namespace _impl { + + +/// Calls `ptr->destroy()` if the guarded pointer (`ptr`) is not null +/// when the guard is destroyed. For arrays (`T` = `Array`) this means +/// that the array is destroyed in a shallow fashion. See +/// `DeepArrayDestroyGuard` for an alternative. +template +class DestroyGuard { +public: + DestroyGuard() noexcept; + + DestroyGuard(T*) noexcept; + + ~DestroyGuard() noexcept; + + // Default implementations of copy/assign can trigger multiple destructions + DestroyGuard(const DestroyGuard&) = delete; + DestroyGuard& operator=(const DestroyGuard&) = delete; + + void reset(T*) noexcept; + + T* get() const noexcept; + + T* release() noexcept; + +private: + T* m_ptr; +}; + +using ShallowArrayDestroyGuard = DestroyGuard; + + +/// Calls `ptr->destroy_deep()` if the guarded Array pointer (`ptr`) +/// is not null when the guard is destroyed. +class DeepArrayDestroyGuard { +public: + DeepArrayDestroyGuard() noexcept; + + DeepArrayDestroyGuard(Array*) noexcept; + + ~DeepArrayDestroyGuard() noexcept; + + // Default implementations of copy/assign can trigger multiple destructions + DeepArrayDestroyGuard(const DeepArrayDestroyGuard&) = delete; + DeepArrayDestroyGuard& operator=(const DeepArrayDestroyGuard&) = delete; + + void reset(Array*) noexcept; + + Array* get() const noexcept; + + Array* release() noexcept; + +private: + Array* m_ptr; +}; + + +/// Calls `Array::destroy_deep(ref, alloc)` if the guarded 'ref' +/// (`ref`) is not zero when the guard is destroyed. +class DeepArrayRefDestroyGuard { +public: + DeepArrayRefDestroyGuard(Allocator&) noexcept; + + DeepArrayRefDestroyGuard(ref_type, Allocator&) noexcept; + + ~DeepArrayRefDestroyGuard() noexcept; + + // Default implementations of copy/assign can trigger multiple destructions + DeepArrayRefDestroyGuard(const DeepArrayRefDestroyGuard&) = delete; + DeepArrayRefDestroyGuard& operator=(const DeepArrayRefDestroyGuard&) = delete; + + void reset(ref_type) noexcept; + + ref_type get() const noexcept; + + ref_type release() noexcept; + +private: + ref_type m_ref; + Allocator& m_alloc; +}; + + +// Implementation: + +// DestroyGuard + +template +inline DestroyGuard::DestroyGuard() noexcept + : m_ptr(nullptr) +{ +} + +template +inline DestroyGuard::DestroyGuard(T* ptr) noexcept + : m_ptr(ptr) +{ +} + +template +inline DestroyGuard::~DestroyGuard() noexcept +{ + if (m_ptr) + m_ptr->destroy(); +} + +template +inline void DestroyGuard::reset(T* ptr) noexcept +{ + if (m_ptr) + m_ptr->destroy(); + m_ptr = ptr; +} + +template +inline T* DestroyGuard::get() const noexcept +{ + return m_ptr; +} + +template +inline T* DestroyGuard::release() noexcept +{ + T* ptr = m_ptr; + m_ptr = nullptr; + return ptr; +} + + +// DeepArrayDestroyGuard + +inline DeepArrayDestroyGuard::DeepArrayDestroyGuard() noexcept + : m_ptr(nullptr) +{ +} + +inline DeepArrayDestroyGuard::DeepArrayDestroyGuard(Array* ptr) noexcept + : m_ptr(ptr) +{ +} + +inline DeepArrayDestroyGuard::~DeepArrayDestroyGuard() noexcept +{ + if (m_ptr) + m_ptr->destroy_deep(); +} + +inline void DeepArrayDestroyGuard::reset(Array* ptr) noexcept +{ + if (m_ptr) + m_ptr->destroy_deep(); + m_ptr = ptr; +} + +inline Array* DeepArrayDestroyGuard::get() const noexcept +{ + return m_ptr; +} + +inline Array* DeepArrayDestroyGuard::release() noexcept +{ + Array* ptr = m_ptr; + m_ptr = nullptr; + return ptr; +} + + +// DeepArrayRefDestroyGuard + +inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(Allocator& alloc) noexcept + : m_ref(0) + , m_alloc(alloc) +{ +} + +inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(ref_type ref, Allocator& alloc) noexcept + : m_ref(ref) + , m_alloc(alloc) +{ +} + +inline DeepArrayRefDestroyGuard::~DeepArrayRefDestroyGuard() noexcept +{ + if (m_ref) + Array::destroy_deep(m_ref, m_alloc); +} + +inline void DeepArrayRefDestroyGuard::reset(ref_type ref) noexcept +{ + if (m_ref) + Array::destroy_deep(m_ref, m_alloc); + m_ref = ref; +} + +inline ref_type DeepArrayRefDestroyGuard::get() const noexcept +{ + return m_ref; +} + +inline ref_type DeepArrayRefDestroyGuard::release() noexcept +{ + ref_type ref = m_ref; + m_ref = 0; + return ref; +} + + +} // namespace _impl +} // namespace realm + +#endif // REALM_IMPL_DESTROY_GUARD_HPP diff --git a/Pods/Realm/include/core/realm/impl/input_stream.hpp b/Pods/Realm/include/core/realm/impl/input_stream.hpp new file mode 100644 index 0000000000..80db30a840 --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/input_stream.hpp @@ -0,0 +1,255 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_IMPL_INPUT_STREAM_HPP +#define REALM_IMPL_INPUT_STREAM_HPP + +#include + +#include +#include +#include + + +namespace realm { +namespace _impl { + + +class InputStream { +public: + /// Read bytes from this input stream and place them in the specified + /// buffer. The returned value is the actual number of bytes that were read, + /// and this is some number `n` such that `n <= min(size, m)` where `m` is + /// the number of bytes that could have been read from this stream before + /// reaching its end. Also, `n` cannot be zero unless `m` or `size` is + /// zero. The intention is that `size` should be non-zero, a the return + /// value used as the end-of-input indicator. + /// + /// Implementations are only allowed to block (put the calling thread to + /// sleep) up until the point in time where the first byte can be made + /// availble. + virtual size_t read(char* buffer, size_t size) = 0; + + virtual ~InputStream() noexcept + { + } +}; + + +class SimpleInputStream : public InputStream { +public: + SimpleInputStream(const char* data, size_t size) noexcept + : m_ptr(data) + , m_end(data + size) + { + } + size_t read(char* buffer, size_t size) override + { + size_t n = std::min(size, size_t(m_end - m_ptr)); + const char* begin = m_ptr; + m_ptr += n; + realm::safe_copy_n(begin, n, buffer); + return n; + } + +private: + const char* m_ptr; + const char* const m_end; +}; + + +class NoCopyInputStream { +public: + /// \return if any bytes was read. + /// A value of false indicates end-of-input. + /// If return value is true, \a begin and \a end are + /// updated to reflect the start and limit of a + /// contiguous memory chunk. + virtual bool next_block(const char*& begin, const char*& end) = 0; + + virtual ~NoCopyInputStream() noexcept + { + } +}; + + +class NoCopyInputStreamAdaptor : public NoCopyInputStream { +public: + NoCopyInputStreamAdaptor(InputStream& in, char* buffer, size_t buffer_size) noexcept + : m_in(in) + , m_buffer(buffer) + , m_buffer_size(buffer_size) + { + } + bool next_block(const char*& begin, const char*& end) override + { + size_t n = m_in.read(m_buffer, m_buffer_size); + begin = m_buffer; + end = m_buffer + n; + return n; + } + +private: + InputStream& m_in; + char* m_buffer; + size_t m_buffer_size; +}; + + +class SimpleNoCopyInputStream : public NoCopyInputStream { +public: + SimpleNoCopyInputStream(const char* data, size_t size) + : m_data(data) + , m_size(size) + { + } + + bool next_block(const char*& begin, const char*& end) override + { + if (m_size == 0) + return 0; + size_t size = m_size; + begin = m_data; + end = m_data + size; + m_size = 0; + return size; + } + +private: + const char* m_data; + size_t m_size; +}; + +class MultiLogNoCopyInputStream : public NoCopyInputStream { +public: + MultiLogNoCopyInputStream(const BinaryData* logs_begin, const BinaryData* logs_end) + : m_logs_begin(logs_begin) + , m_logs_end(logs_end) + { + if (m_logs_begin != m_logs_end) + m_curr_buf_remaining_size = m_logs_begin->size(); + } + + size_t read(char* buffer, size_t size) + { + if (m_logs_begin == m_logs_end) + return 0; + for (;;) { + if (m_curr_buf_remaining_size > 0) { + size_t offset = m_logs_begin->size() - m_curr_buf_remaining_size; + const char* data = m_logs_begin->data() + offset; + size_t size_2 = std::min(m_curr_buf_remaining_size, size); + m_curr_buf_remaining_size -= size_2; + // FIXME: Eliminate the need for copying by changing the API of + // Replication::InputStream such that blocks can be handed over + // without copying. This is a straight forward change, but the + // result is going to be more complicated and less conventional. + realm::safe_copy_n(data, size_2, buffer); + return size_2; + } + + ++m_logs_begin; + if (m_logs_begin == m_logs_end) + return 0; + m_curr_buf_remaining_size = m_logs_begin->size(); + } + } + + bool next_block(const char*& begin, const char*& end) override + { + while (m_logs_begin < m_logs_end) { + size_t result = m_logs_begin->size(); + const char* data = m_logs_begin->data(); + m_logs_begin++; + if (result == 0) + continue; // skip empty blocks + begin = data; + end = data + result; + return result; + } + return 0; + } + +private: + const BinaryData* m_logs_begin; + const BinaryData* m_logs_end; + size_t m_curr_buf_remaining_size; +}; + + +class ChangesetInputStream : public NoCopyInputStream { +public: + using version_type = History::version_type; + static constexpr unsigned NB_BUFFERS = 8; + + ChangesetInputStream(History& hist, version_type begin_version, version_type end_version) + : m_history(hist) + , m_begin_version(begin_version) + , m_end_version(end_version) + { + get_changeset(); + } + + bool next_block(const char*& begin, const char*& end) override + { + while (m_valid) { + BinaryData actual = m_changesets_begin->get_next(); + + if (actual.size() > 0) { + begin = actual.data(); + end = actual.data() + actual.size(); + return true; + } + + m_changesets_begin++; + + if (REALM_UNLIKELY(m_changesets_begin == m_changesets_end)) { + get_changeset(); + } + } + return false; // End of input + } + +private: + History& m_history; + version_type m_begin_version, m_end_version; + BinaryIterator m_changesets[NB_BUFFERS]; // Buffer + BinaryIterator* m_changesets_begin = nullptr; + BinaryIterator* m_changesets_end = nullptr; + bool m_valid; + + void get_changeset() + { + auto versions_to_get = m_end_version - m_begin_version; + m_valid = versions_to_get > 0; + if (m_valid) { + if (versions_to_get > NB_BUFFERS) + versions_to_get = NB_BUFFERS; + version_type end_version = m_begin_version + versions_to_get; + m_history.get_changesets(m_begin_version, end_version, m_changesets); + m_begin_version = end_version; + m_changesets_begin = m_changesets; + m_changesets_end = m_changesets_begin + versions_to_get; + } + } +}; + +} // namespace _impl +} // namespace realm + +#endif // REALM_IMPL_INPUT_STREAM_HPP diff --git a/Pods/Realm/include/core/realm/impl/output_stream.hpp b/Pods/Realm/include/core/realm/impl/output_stream.hpp new file mode 100644 index 0000000000..1d022cd531 --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/output_stream.hpp @@ -0,0 +1,75 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_IMPL_OUTPUT_STREAM_HPP +#define REALM_IMPL_OUTPUT_STREAM_HPP + +#include +#include + +#include + +#include + +#include + +namespace realm { +namespace _impl { + + +class OutputStream : public ArrayWriterBase { +public: + OutputStream(std::ostream&); + ~OutputStream() noexcept; + + ref_type get_ref_of_next_array() const noexcept; + + void write(const char* data, size_t size); + + ref_type write_array(const char* data, size_t size, uint32_t checksum) override; + +private: + ref_type m_next_ref; + std::ostream& m_out; + + void do_write(const char* data, size_t size); +}; + + +// Implementation: + +inline OutputStream::OutputStream(std::ostream& out) + : m_next_ref(0) + , m_out(out) +{ +} + +inline OutputStream::~OutputStream() noexcept +{ +} + +inline size_t OutputStream::get_ref_of_next_array() const noexcept +{ + return m_next_ref; +} + + +} // namespace _impl +} // namespace realm + +#endif // REALM_IMPL_OUTPUT_STREAM_HPP diff --git a/Pods/Realm/include/core/realm/impl/sequential_getter.hpp b/Pods/Realm/include/core/realm/impl/sequential_getter.hpp new file mode 100644 index 0000000000..c7dd8668fa --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/sequential_getter.hpp @@ -0,0 +1,130 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_IMPL_SEQUENTIAL_GETTER_HPP +#define REALM_IMPL_SEQUENTIAL_GETTER_HPP + +namespace realm { + +class SequentialGetterBase { +public: + virtual ~SequentialGetterBase() noexcept + { + } +}; + +template +class SequentialGetter : public SequentialGetterBase { +public: + using T = typename ColType::value_type; + using ArrayType = typename ColType::LeafType; + + SequentialGetter() + { + } + + SequentialGetter(const Table& table, size_t column_ndx) + { + init(static_cast(&table.get_column_base(column_ndx))); + } + + SequentialGetter(const ColType* column) + { + init(column); + } + + ~SequentialGetter() noexcept override + { + } + + void init(const ColType* column) + { + REALM_ASSERT(column != nullptr); + m_array_ptr.reset(); // Explicitly destroy the old one first, because we're reusing the memory. + m_array_ptr.reset(new (&m_leaf_accessor_storage) ArrayType(column->get_alloc())); + m_column = column; + m_leaf_end = 0; + } + + REALM_FORCEINLINE bool cache_next(size_t index) + { + // Set m_leaf_ptr to point at the leaf that contains the value at column row `index`. Return whether or not + // the leaf has changed (could be useful to know for caller). + + // FIXME: Below line has been commented away because array leafs might relocate during the lifetime of the + // object that owns this SequentialGetter. Enable again when we have proper support for that. + // if (index >= m_leaf_end || index < m_leaf_start) + { + typename ColType::LeafInfo leaf{&m_leaf_ptr, m_array_ptr.get()}; + size_t ndx_in_leaf; + m_column->get_leaf(index, ndx_in_leaf, leaf); + m_leaf_start = index - ndx_in_leaf; + const size_t leaf_size = m_leaf_ptr->size(); + m_leaf_end = m_leaf_start + leaf_size; + return true; + } + return false; + } + + + REALM_FORCEINLINE T get_next(size_t index) + { +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4800) // Disable the Microsoft warning about bool performance issue. +#endif + return m_column->get(index); + + // FIXME: Below optimization is skipped because array leafs might relocate during the lifetime of the + // object that owns this SequentialGetter. Enable again when we have proper support for that. +// +// cache_next(index); +// T av = m_leaf_ptr->get(index - m_leaf_start); +// return av; + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + } + + size_t local_end(size_t global_end) + { + if (global_end > m_leaf_end) + return m_leaf_end - m_leaf_start; + else + return global_end - m_leaf_start; + } + + size_t m_leaf_start = 0; + size_t m_leaf_end = 0; + const ColType* m_column = nullptr; + + const ArrayType* m_leaf_ptr = nullptr; + +private: + // Leaf cache for when the root of the column is not a leaf. + // This dog and pony show is because Array has a reference to Allocator internally, + // but we need to be able to transfer queries between contexts, so init() reinitializes + // the leaf cache in the context of the current column. + typename std::aligned_storage::type m_leaf_accessor_storage; + std::unique_ptr m_array_ptr; +}; + +} // namespace realm + +#endif // REALM_IMPL_SEQUENTIAL_GETTER_HPP diff --git a/Pods/Realm/include/core/realm/impl/simulated_failure.hpp b/Pods/Realm/include/core/realm/impl/simulated_failure.hpp new file mode 100644 index 0000000000..4958151f61 --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/simulated_failure.hpp @@ -0,0 +1,228 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_IMPL_SIMULATED_FAILURE_HPP +#define REALM_IMPL_SIMULATED_FAILURE_HPP + +#include +#include + +#include + +#ifdef REALM_DEBUG +#define REALM_ENABLE_SIMULATED_FAILURE +#endif + +namespace realm { +namespace _impl { + +class SimulatedFailure : public std::system_error { +public: + enum FailureType { + generic, + slab_alloc__reset_free_space_tracking, + slab_alloc__remap, + shared_group__grow_reader_mapping, + sync_client__read_head, + sync_server__read_head, + _num_failure_types + }; + + class OneShotPrimeGuard; + class RandomPrimeGuard; + + /// Prime the specified failure type on the calling thread for triggering + /// once. + static void prime_one_shot(FailureType); + + /// Prime the specified failure type on the calling thread for triggering + /// randomly \a n out of \a m times. + static void prime_random(FailureType, int n, int m, uint_fast64_t seed = 0); + + /// Unprime the specified failure type on the calling thread. + static void unprime(FailureType) noexcept; + + /// Returns true according to the mode of priming of the specified failure + /// type on the calling thread, but only if REALM_ENABLE_SIMULATED_FAILURE + /// was defined during compilation. If REALM_ENABLE_SIMULATED_FAILURE was + /// not defined, this function always return false. + static bool check_trigger(FailureType) noexcept; + + /// The specified error code is set to `make_error_code(failure_type)` if + /// check_trigger() returns true. Otherwise it is set to + /// `std::error_code()`. Returns a copy of the updated error code. + static std::error_code trigger(FailureType failure_type, std::error_code&) noexcept; + + /// Throws SimulatedFailure if check_trigger() returns true. The exception + /// will be constructed with an error code equal to + /// `make_error_code(failure_type)`. + static void trigger(FailureType failure_type); + + /// Returns true when, and only when REALM_ENABLE_SIMULATED_FAILURE was + /// defined during compilation. + static constexpr bool is_enabled(); + + SimulatedFailure(std::error_code); + +private: +#ifdef REALM_ENABLE_SIMULATED_FAILURE + static void do_prime_one_shot(FailureType); + static void do_prime_random(FailureType, int n, int m, uint_fast64_t seed); + static void do_unprime(FailureType) noexcept; + static bool do_check_trigger(FailureType) noexcept; +#endif +}; + +std::error_code make_error_code(SimulatedFailure::FailureType) noexcept; + +class SimulatedFailure::OneShotPrimeGuard { +public: + OneShotPrimeGuard(FailureType); + ~OneShotPrimeGuard() noexcept; + +private: + const FailureType m_type; +}; + + +class SimulatedFailure::RandomPrimeGuard { +public: + RandomPrimeGuard(FailureType, int n, int m, uint_fast64_t seed = 0); + ~RandomPrimeGuard() noexcept; + +private: + const FailureType m_type; +}; + +std::error_code make_error_code(SimulatedFailure::FailureType) noexcept; + +} // namespace _impl +} // namespace realm + +namespace std { + +template<> struct is_error_code_enum { + static const bool value = true; +}; + +} // namespace std + +namespace realm { +namespace _impl { + + +// Implementation + +inline void SimulatedFailure::prime_one_shot(FailureType failure_type) +{ +#ifdef REALM_ENABLE_SIMULATED_FAILURE + do_prime_one_shot(failure_type); +#else + static_cast(failure_type); +#endif +} + +inline void SimulatedFailure::prime_random(FailureType failure_type, int n, int m, uint_fast64_t seed) +{ +#ifdef REALM_ENABLE_SIMULATED_FAILURE + do_prime_random(failure_type, n, m, seed); +#else + static_cast(failure_type); + static_cast(n); + static_cast(m); + static_cast(seed); +#endif +} + +inline void SimulatedFailure::unprime(FailureType failure_type) noexcept +{ +#ifdef REALM_ENABLE_SIMULATED_FAILURE + do_unprime(failure_type); +#else + static_cast(failure_type); +#endif +} + +inline bool SimulatedFailure::check_trigger(FailureType failure_type) noexcept +{ +#ifdef REALM_ENABLE_SIMULATED_FAILURE + return do_check_trigger(failure_type); +#else + static_cast(failure_type); + return false; +#endif +} + +inline std::error_code SimulatedFailure::trigger(FailureType failure_type, std::error_code& ec) noexcept +{ + if (check_trigger(failure_type)) { + ec = make_error_code(failure_type); + } + else { + ec = std::error_code(); + } + return ec; +} + +inline void SimulatedFailure::trigger(FailureType failure_type) +{ + if (check_trigger(failure_type)) + throw SimulatedFailure(make_error_code(failure_type)); +} + +inline constexpr bool SimulatedFailure::is_enabled() +{ +#ifdef REALM_ENABLE_SIMULATED_FAILURE + return true; +#else + return false; +#endif +} + +inline SimulatedFailure::SimulatedFailure(std::error_code ec) + : std::system_error(ec) +{ +} + +inline SimulatedFailure::OneShotPrimeGuard::OneShotPrimeGuard(FailureType failure_type) + : m_type(failure_type) +{ + prime_one_shot(m_type); +} + +inline SimulatedFailure::OneShotPrimeGuard::~OneShotPrimeGuard() noexcept +{ + unprime(m_type); +} + +inline SimulatedFailure::RandomPrimeGuard::RandomPrimeGuard(FailureType failure_type, int n, int m, + uint_fast64_t seed) + : m_type(failure_type) +{ + prime_random(m_type, n, m, seed); +} + +inline SimulatedFailure::RandomPrimeGuard::~RandomPrimeGuard() noexcept +{ + unprime(m_type); +} + +} // namespace _impl +} // namespace realm + +#endif // REALM_IMPL_SIMULATED_FAILURE_HPP diff --git a/Pods/Realm/include/core/realm/impl/transact_log.hpp b/Pods/Realm/include/core/realm/impl/transact_log.hpp new file mode 100644 index 0000000000..ee3c710bc2 --- /dev/null +++ b/Pods/Realm/include/core/realm/impl/transact_log.hpp @@ -0,0 +1,2808 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_IMPL_TRANSACT_LOG_HPP +#define REALM_IMPL_TRANSACT_LOG_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace realm { +namespace _impl { + +/// Transaction log instruction encoding +/// NOTE: Any change to this enum is a file-format breaking change. +enum Instruction { + instr_InsertGroupLevelTable = 1, + instr_EraseGroupLevelTable = 2, // Remove columnless table from group + instr_RenameGroupLevelTable = 3, + instr_MoveGroupLevelTable = 4, // UNSUPPORTED/UNUSED. FIXME: remove in next breaking change + instr_SelectTable = 5, + instr_Set = 6, + instr_SetUnique = 7, + instr_SetDefault = 8, + instr_AddInteger = 9, // Add value to integer field + instr_NullifyLink = 10, // Set link to null due to target being erased + instr_InsertSubstring = 11, + instr_EraseFromString = 12, + instr_InsertEmptyRows = 13, + instr_EraseRows = 14, // Remove (multiple) rows + instr_SwapRows = 15, + instr_MoveRow = 16, + instr_MergeRows = 17, // Replace links pointing to row A with links to row B + instr_ClearTable = 18, // Remove all rows in selected table + instr_OptimizeTable = 19, + instr_SelectDescriptor = 20, // Select descriptor from currently selected root table + instr_InsertColumn = + 21, // Insert new non-nullable column into to selected descriptor (nullable is instr_InsertNullableColumn) + instr_InsertLinkColumn = 22, // do, but for a link-type column + instr_InsertNullableColumn = 23, // Insert nullable column + instr_EraseColumn = 24, // Remove column from selected descriptor + instr_EraseLinkColumn = 25, // Remove link-type column from selected descriptor + instr_RenameColumn = 26, // Rename column in selected descriptor + instr_MoveColumn = 27, // Move column in selected descriptor (UNSUPPORTED/UNUSED) FIXME: remove + instr_AddSearchIndex = 28, // Add a search index to a column + instr_RemoveSearchIndex = 29, // Remove a search index from a column + instr_SetLinkType = 30, // Strong/weak + instr_SelectLinkList = 31, + instr_LinkListSet = 32, // Assign to link list entry + instr_LinkListInsert = 33, // Insert entry into link list + instr_LinkListMove = 34, // Move an entry within a link list + instr_LinkListSwap = 35, // Swap two entries within a link list + instr_LinkListErase = 36, // Remove an entry from a link list + instr_LinkListNullify = 37, // Remove an entry from a link list due to linked row being erased + instr_LinkListClear = 38, // Ramove all entries from a link list + instr_LinkListSetAll = 39, // Assign to link list entry + instr_AddRowWithKey = 40, // Insert a row with a given key +}; + +class TransactLogStream { +public: + /// Ensure contiguous free space in the transaction log + /// buffer. This method must update `out_free_begin` + /// and `out_free_end` such that they refer to a chunk + /// of free space whose size is at least \a n. + /// + /// \param n The required amount of contiguous free space. Must be + /// small (probably not greater than 1024) + /// \param n Must be small (probably not greater than 1024) + virtual void transact_log_reserve(size_t size, char** out_free_begin, char** out_free_end) = 0; + + /// Copy the specified data into the transaction log buffer. This + /// function should be called only when the specified data does + /// not fit inside the chunk of free space currently referred to + /// by `out_free_begin` and `out_free_end`. + /// + /// This method must update `out_begin` and + /// `out_end` such that, upon return, they still + /// refer to a (possibly empty) chunk of free space. + virtual void transact_log_append(const char* data, size_t size, char** out_free_begin, char** out_free_end) = 0; +}; + +class TransactLogBufferStream : public TransactLogStream { +public: + void transact_log_reserve(size_t size, char** out_free_begin, char** out_free_end) override; + void transact_log_append(const char* data, size_t size, char** out_free_begin, char** out_free_end) override; + + const char* transact_log_data() const; + + util::Buffer m_buffer; +}; + + +// LCOV_EXCL_START (because the NullInstructionObserver is trivial) +class NullInstructionObserver { +public: + /// The following methods are also those that TransactLogParser expects + /// to find on the `InstructionHandler`. + + // No selection needed: + bool select_table(size_t, size_t, const size_t*) + { + return true; + } + bool select_descriptor(size_t, const size_t*) + { + return true; + } + bool select_link_list(size_t, size_t, size_t) + { + return true; + } + bool insert_group_level_table(size_t, size_t, StringData) + { + return true; + } + bool erase_group_level_table(size_t, size_t) + { + return true; + } + bool rename_group_level_table(size_t, StringData) + { + return true; + } + + // Must have table selected: + bool insert_empty_rows(size_t, size_t, size_t, bool) + { + return true; + } + bool add_row_with_key(size_t, size_t, size_t, int64_t) + { + return true; + } + bool erase_rows(size_t, size_t, size_t, bool) + { + return true; + } + bool swap_rows(size_t, size_t) + { + return true; + } + bool move_row(size_t, size_t) + { + return true; + } + bool merge_rows(size_t, size_t) + { + return true; + } + bool clear_table(size_t) + { + return true; + } + bool set_int(size_t, size_t, int_fast64_t, Instruction, size_t) + { + return true; + } + bool add_int(size_t, size_t, int_fast64_t) + { + return true; + } + bool set_bool(size_t, size_t, bool, Instruction) + { + return true; + } + bool set_float(size_t, size_t, float, Instruction) + { + return true; + } + bool set_double(size_t, size_t, double, Instruction) + { + return true; + } + bool set_string(size_t, size_t, StringData, Instruction, size_t) + { + return true; + } + bool set_binary(size_t, size_t, BinaryData, Instruction) + { + return true; + } + bool set_olddatetime(size_t, size_t, OldDateTime, Instruction) + { + return true; + } + bool set_timestamp(size_t, size_t, Timestamp, Instruction) + { + return true; + } + bool set_table(size_t, size_t, Instruction) + { + return true; + } + bool set_mixed(size_t, size_t, const Mixed&, Instruction) + { + return true; + } + bool set_link(size_t, size_t, size_t, size_t, Instruction) + { + return true; + } + bool set_null(size_t, size_t, Instruction, size_t) + { + return true; + } + bool nullify_link(size_t, size_t, size_t) + { + return true; + } + bool insert_substring(size_t, size_t, size_t, StringData) + { + return true; + } + bool erase_substring(size_t, size_t, size_t, size_t) + { + return true; + } + bool optimize_table() + { + return true; + } + + // Must have descriptor selected: + bool insert_link_column(size_t, DataType, StringData, size_t, size_t) + { + return true; + } + bool insert_column(size_t, DataType, StringData, bool) + { + return true; + } + bool erase_link_column(size_t, size_t, size_t) + { + return true; + } + bool erase_column(size_t) + { + return true; + } + bool rename_column(size_t, StringData) + { + return true; + } + bool add_search_index(size_t) + { + return true; + } + bool remove_search_index(size_t) + { + return true; + } + bool set_link_type(size_t, LinkType) + { + return true; + } + + // Must have linklist selected: + bool link_list_set(size_t, size_t, size_t) + { + return true; + } + bool link_list_insert(size_t, size_t, size_t) + { + return true; + } + bool link_list_move(size_t, size_t) + { + return true; + } + bool link_list_swap(size_t, size_t) + { + return true; + } + bool link_list_erase(size_t, size_t) + { + return true; + } + bool link_list_nullify(size_t, size_t) + { + return true; + } + bool link_list_clear(size_t) + { + return true; + } + + void parse_complete() + { + } +}; +// LCOV_EXCL_STOP (NullInstructionObserver) + + +/// See TransactLogConvenientEncoder for information about the meaning of the +/// arguments of each of the functions in this class. +class TransactLogEncoder { +public: + /// The following methods are also those that TransactLogParser expects + /// to find on the `InstructionHandler`. + + // No selection needed: + bool select_table(size_t group_level_ndx, size_t levels, const size_t* path); + bool select_descriptor(size_t levels, const size_t* path); + bool select_link_list(size_t col_ndx, size_t row_ndx, size_t link_target_group_level_ndx); + bool insert_group_level_table(size_t table_ndx, size_t num_tables, StringData name); + bool erase_group_level_table(size_t table_ndx, size_t num_tables); + bool rename_group_level_table(size_t table_ndx, StringData new_name); + + /// Must have table selected. + bool insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool unordered); + bool add_row_with_key(size_t row_ndx, size_t prior_num_rows, size_t key_col_ndx, int64_t key); + bool erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool unordered); + bool swap_rows(size_t row_ndx_1, size_t row_ndx_2); + bool move_row(size_t from_ndx, size_t to_ndx); + bool merge_rows(size_t row_ndx, size_t new_row_ndx); + bool clear_table(size_t old_table_size); + + bool set_int(size_t col_ndx, size_t row_ndx, int_fast64_t, Instruction = instr_Set, size_t = 0); + bool add_int(size_t col_ndx, size_t row_ndx, int_fast64_t); + bool set_bool(size_t col_ndx, size_t row_ndx, bool, Instruction = instr_Set); + bool set_float(size_t col_ndx, size_t row_ndx, float, Instruction = instr_Set); + bool set_double(size_t col_ndx, size_t row_ndx, double, Instruction = instr_Set); + bool set_string(size_t col_ndx, size_t row_ndx, StringData, Instruction = instr_Set, size_t = 0); + bool set_binary(size_t col_ndx, size_t row_ndx, BinaryData, Instruction = instr_Set); + bool set_olddatetime(size_t col_ndx, size_t row_ndx, OldDateTime, Instruction = instr_Set); + bool set_timestamp(size_t col_ndx, size_t row_ndx, Timestamp, Instruction = instr_Set); + bool set_table(size_t col_ndx, size_t row_ndx, Instruction = instr_Set); + bool set_mixed(size_t col_ndx, size_t row_ndx, const Mixed&, Instruction = instr_Set); + bool set_link(size_t col_ndx, size_t row_ndx, size_t, size_t target_group_level_ndx, Instruction = instr_Set); + bool set_null(size_t col_ndx, size_t row_ndx, Instruction = instr_Set, size_t = 0); + bool nullify_link(size_t col_ndx, size_t row_ndx, size_t target_group_level_ndx); + bool insert_substring(size_t col_ndx, size_t row_ndx, size_t pos, StringData); + bool erase_substring(size_t col_ndx, size_t row_ndx, size_t pos, size_t size); + bool optimize_table(); + + // Must have descriptor selected: + bool insert_link_column(size_t col_ndx, DataType, StringData name, size_t link_target_table_ndx, + size_t backlink_col_ndx); + bool insert_column(size_t col_ndx, DataType, StringData name, bool nullable = false); + bool erase_link_column(size_t col_ndx, size_t link_target_table_ndx, size_t backlink_col_ndx); + bool erase_column(size_t col_ndx); + bool rename_column(size_t col_ndx, StringData new_name); + bool add_search_index(size_t col_ndx); + bool remove_search_index(size_t col_ndx); + bool set_link_type(size_t col_ndx, LinkType); + + // Must have linklist selected: + bool link_list_set(size_t link_ndx, size_t value, size_t prior_size); + bool link_list_set_all(const IntegerColumn& values); + bool link_list_insert(size_t link_ndx, size_t value, size_t prior_size); + bool link_list_move(size_t from_link_ndx, size_t to_link_ndx); + bool link_list_swap(size_t link1_ndx, size_t link2_ndx); + bool link_list_erase(size_t link_ndx, size_t prior_size); + bool link_list_nullify(size_t link_ndx, size_t prior_size); + bool link_list_clear(size_t old_list_size); + + /// End of methods expected by parser. + + + TransactLogEncoder(TransactLogStream& out_stream); + void set_buffer(char* new_free_begin, char* new_free_end); + char* write_position() const + { + return m_transact_log_free_begin; + } + +private: + using IntegerList = std::tuple; + using UnsignedList = std::tuple; + + // Make sure this is in agreement with the actual integer encoding + // scheme (see encode_int()). + static constexpr int max_enc_bytes_per_int = 10; + static constexpr int max_enc_bytes_per_double = sizeof(double); + static constexpr int max_enc_bytes_per_num = + max_enc_bytes_per_int < max_enc_bytes_per_double ? max_enc_bytes_per_double : max_enc_bytes_per_int; +// Space is reserved in chunks to avoid excessive over allocation. +#ifdef REALM_DEBUG + static constexpr int max_numbers_per_chunk = 2; // Increase the chance of chunking in debug mode +#else + static constexpr int max_numbers_per_chunk = 8; +#endif + + // This value is used in Set* instructions in place of the 'type' field in + // the stream to indicate that the value of the Set* instruction is NULL, + // which doesn't have a type. + static constexpr int set_null_sentinel() + { + return -1; + } + + TransactLogStream& m_stream; + + // These two delimit a contiguous region of free space in a + // transaction log buffer following the last written data. It may + // be empty. + char* m_transact_log_free_begin = nullptr; + char* m_transact_log_free_end = nullptr; + + char* reserve(size_t size); + /// \param ptr Must be in the range [m_transact_log_free_begin, m_transact_log_free_end] + void advance(char* ptr) noexcept; + + template + size_t max_size(T); + + size_t max_size_list() + { + return 0; + } + + template + size_t max_size_list(T val, Args... args) + { + return max_size(val) + max_size_list(args...); + } + + template + char* encode(char* ptr, T value); + + char* encode_list(char* ptr) + { + advance(ptr); + return ptr; + } + + template + char* encode_list(char* ptr, T value, Args... args) + { + return encode_list(encode(ptr, value), args...); + } + + template + void append_simple_instr(L... numbers); + + template + void append_mixed_instr(Instruction instr, const Mixed& value, L... numbers); + + template + static char* encode_int(char*, T value); + friend class TransactLogParser; +}; + +class TransactLogConvenientEncoder { +public: + virtual void insert_group_level_table(size_t table_ndx, size_t num_tables, StringData name); + virtual void erase_group_level_table(size_t table_ndx, size_t num_tables); + virtual void rename_group_level_table(size_t table_ndx, StringData new_name); + virtual void insert_column(const Descriptor&, size_t col_ndx, DataType type, StringData name, LinkTargetInfo& link, + bool nullable = false); + virtual void erase_column(const Descriptor&, size_t col_ndx); + virtual void rename_column(const Descriptor&, size_t col_ndx, StringData name); + + virtual void set_int(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value, Instruction variant = instr_Set); + virtual void add_int(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value); + virtual void set_bool(const Table*, size_t col_ndx, size_t ndx, bool value, Instruction variant = instr_Set); + virtual void set_float(const Table*, size_t col_ndx, size_t ndx, float value, Instruction variant = instr_Set); + virtual void set_double(const Table*, size_t col_ndx, size_t ndx, double value, Instruction variant = instr_Set); + virtual void set_string(const Table*, size_t col_ndx, size_t ndx, StringData value, Instruction variant = instr_Set); + virtual void set_binary(const Table*, size_t col_ndx, size_t ndx, BinaryData value, Instruction variant = instr_Set); + virtual void set_olddatetime(const Table*, size_t col_ndx, size_t ndx, OldDateTime value, + Instruction variant = instr_Set); + virtual void set_timestamp(const Table*, size_t col_ndx, size_t ndx, Timestamp value, Instruction variant = instr_Set); + virtual void set_table(const Table*, size_t col_ndx, size_t ndx, Instruction variant = instr_Set); + virtual void set_mixed(const Table*, size_t col_ndx, size_t ndx, const Mixed& value, Instruction variant = instr_Set); + virtual void set_link(const Table*, size_t col_ndx, size_t ndx, size_t value, Instruction variant = instr_Set); + virtual void set_null(const Table*, size_t col_ndx, size_t ndx, Instruction variant = instr_Set); + virtual void set_link_list(const LinkView&, const IntegerColumn& values); + virtual void insert_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, StringData); + virtual void erase_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, size_t size); + + /// \param prior_num_rows The number of rows in the table prior to the + /// modification. + virtual void insert_empty_rows(const Table*, size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows); + virtual void add_row_with_key(const Table* t, size_t row_ndx, size_t prior_num_rows, size_t key_col_ndx, + int64_t key); + + /// \param prior_num_rows The number of rows in the table prior to the + /// modification. + virtual void erase_rows(const Table*, size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, + bool is_move_last_over); + + virtual void swap_rows(const Table*, size_t row_ndx_1, size_t row_ndx_2); + virtual void move_row(const Table*, size_t from_ndx, size_t to_ndx); + virtual void merge_rows(const Table*, size_t row_ndx, size_t new_row_ndx); + virtual void add_search_index(const Descriptor&, size_t col_ndx); + virtual void remove_search_index(const Descriptor&, size_t col_ndx); + virtual void set_link_type(const Table*, size_t col_ndx, LinkType); + virtual void clear_table(const Table*, size_t prior_num_rows); + virtual void optimize_table(const Table*); + + virtual void link_list_set(const LinkView&, size_t link_ndx, size_t value); + virtual void link_list_insert(const LinkView&, size_t link_ndx, size_t value); + virtual void link_list_move(const LinkView&, size_t from_link_ndx, size_t to_link_ndx); + virtual void link_list_swap(const LinkView&, size_t link_ndx_1, size_t link_ndx_2); + virtual void link_list_erase(const LinkView&, size_t link_ndx); + virtual void link_list_clear(const LinkView&); + + //@{ + + /// Implicit nullifications due to removal of target row. This is redundant + /// information from the point of view of replication, as the removal of the + /// target row will reproduce the implicit nullifications in the target + /// Realm anyway. The purpose of this instruction is to allow observers + /// (reactor pattern) to be explicitly notified about the implicit + /// nullifications. + + virtual void nullify_link(const Table*, size_t col_ndx, size_t ndx); + virtual void link_list_nullify(const LinkView&, size_t link_ndx); + + //@} + + void on_table_destroyed(const Table*) noexcept; + void on_spec_destroyed(const Spec*) noexcept; + void on_link_list_destroyed(const LinkView&) noexcept; + +protected: + TransactLogConvenientEncoder(TransactLogStream& encoder); + + void reset_selection_caches() noexcept; + void set_buffer(char* new_free_begin, char* new_free_end) + { + m_encoder.set_buffer(new_free_begin, new_free_end); + } + char* write_position() const + { + return m_encoder.write_position(); + } + +private: + TransactLogEncoder m_encoder; + // These are mutable because they are caches. + mutable util::Buffer m_subtab_path_buf; + mutable const Table* m_selected_table; + mutable const Spec* m_selected_spec; + // Has to be atomic to support concurrent reset when a linklist + // is unselected. This can happen on a different thread. In case + // of races, setting of a new value must win. + mutable std::atomic m_selected_link_list; + + void unselect_all() noexcept; + void select_table(const Table*); // unselects descriptor and link list + void select_desc(const Descriptor&); // unselects link list + void select_link_list(const LinkView&); // unselects descriptor + + void record_subtable_path(const Table&, size_t*& out_begin, size_t*& out_end); + void do_select_table(const Table*); + void do_select_desc(const Descriptor&); + void do_select_link_list(const LinkView&); + + friend class TransactReverser; +}; + + +class TransactLogParser { +public: + class BadTransactLog; // Exception + + TransactLogParser(); + ~TransactLogParser() noexcept; + + /// See `TransactLogEncoder` for a list of methods that the `InstructionHandler` must define. + /// parse() promises that the path passed by reference to + /// InstructionHandler::select_descriptor() will remain valid + /// during subsequent calls to all descriptor modifying functions. + template + void parse(InputStream&, InstructionHandler&); + + template + void parse(NoCopyInputStream&, InstructionHandler&); + +private: + util::Buffer m_input_buffer; + + // The input stream is assumed to consist of chunks of memory organised such that + // every instruction resides in a single chunk only. + NoCopyInputStream* m_input; + // pointer into transaction log, each instruction is parsed from m_input_begin and onwards. + // Each instruction are assumed to be contiguous in memory. + const char* m_input_begin; + // pointer to one past current instruction log chunk. If m_input_begin reaches m_input_end, + // a call to next_input_buffer will move m_input_begin and m_input_end to a new chunk of + // memory. Setting m_input_end to 0 disables this check, and is used if it is already known + // that all of the instructions are in memory. + const char* m_input_end; + util::StringBuffer m_string_buffer; + static const int m_max_levels = 1024; + util::Buffer m_path; + + REALM_NORETURN void parser_error() const; + + template + void parse_one(InstructionHandler&); + bool has_next() noexcept; + + template + T read_int(); + + void read_bytes(char* data, size_t size); + BinaryData read_buffer(util::StringBuffer&, size_t size); + + bool read_bool(); + float read_float(); + double read_double(); + + StringData read_string(util::StringBuffer&); + BinaryData read_binary(util::StringBuffer&); + Timestamp read_timestamp(); + void read_mixed(Mixed*); + + // Advance m_input_begin and m_input_end to reflect the next block of instructions + // Returns false if no more input was available + bool next_input_buffer(); + + // return true if input was available + bool read_char(char&); // throws + + bool is_valid_data_type(int type); + bool is_valid_link_type(int type); +}; + + +class TransactLogParser::BadTransactLog : public std::exception { +public: + const char* what() const noexcept override + { + return "Bad transaction log"; + } +}; + + +/// Implementation: + +inline void TransactLogBufferStream::transact_log_reserve(size_t n, char** inout_new_begin, char** out_new_end) +{ + char* data = m_buffer.data(); + REALM_ASSERT(*inout_new_begin >= data); + REALM_ASSERT(*inout_new_begin <= (data + m_buffer.size())); + size_t size = *inout_new_begin - data; + m_buffer.reserve_extra(size, n); + data = m_buffer.data(); // May have changed + *inout_new_begin = data + size; + *out_new_end = data + m_buffer.size(); +} + +inline void TransactLogBufferStream::transact_log_append(const char* data, size_t size, char** out_new_begin, + char** out_new_end) +{ + transact_log_reserve(size, out_new_begin, out_new_end); + *out_new_begin = realm::safe_copy_n(data, size, *out_new_begin); +} + +inline const char* TransactLogBufferStream::transact_log_data() const +{ + return m_buffer.data(); +} + +inline TransactLogEncoder::TransactLogEncoder(TransactLogStream& stream) + : m_stream(stream) +{ +} + +inline void TransactLogEncoder::set_buffer(char* free_begin, char* free_end) +{ + REALM_ASSERT(free_begin <= free_end); + m_transact_log_free_begin = free_begin; + m_transact_log_free_end = free_end; +} + +inline void TransactLogConvenientEncoder::reset_selection_caches() noexcept +{ + unselect_all(); +} + +inline char* TransactLogEncoder::reserve(size_t n) +{ + if (size_t(m_transact_log_free_end - m_transact_log_free_begin) < n) { + m_stream.transact_log_reserve(n, &m_transact_log_free_begin, &m_transact_log_free_end); + } + return m_transact_log_free_begin; +} + +inline void TransactLogEncoder::advance(char* ptr) noexcept +{ + REALM_ASSERT_DEBUG(m_transact_log_free_begin <= ptr); + REALM_ASSERT_DEBUG(ptr <= m_transact_log_free_end); + m_transact_log_free_begin = ptr; +} + + +// The integer encoding is platform independent. Also, it does not +// depend on the type of the specified integer. Integers of any type +// can be encoded as long as the specified buffer is large enough (see +// below). The decoding does not have to use the same type. Decoding +// will fail if, and only if the encoded value falls outside the range +// of the requested destination type. +// +// The encoding uses one or more bytes. It never uses more than 8 bits +// per byte. The last byte in the sequence is the first one that has +// its 8th bit set to zero. +// +// Consider a particular non-negative value V. Let W be the number of +// bits needed to encode V using the trivial binary encoding of +// integers. The total number of bytes produced is then +// ceil((W+1)/7). The first byte holds the 7 least significant bits of +// V. The last byte holds at most 6 bits of V including the most +// significant one. The value of the first bit of the last byte is +// always 2**((N-1)*7) where N is the total number of bytes. +// +// A negative value W is encoded by setting the sign bit to one and +// then encoding the positive result of -(W+1) as described above. The +// advantage of this representation is that it converts small negative +// values to small positive values which require a small number of +// bytes. This would not have been true for 2's complements +// representation, for example. The sign bit is always stored as the +// 7th bit of the last byte. +// +// value bits value + sign max bytes +// -------------------------------------------------- +// int8_t 7 8 2 +// uint8_t 8 9 2 +// int16_t 15 16 3 +// uint16_t 16 17 3 +// int32_t 31 32 5 +// uint32_t 32 33 5 +// int64_t 63 64 10 +// uint64_t 64 65 10 +// +template +char* TransactLogEncoder::encode_int(char* ptr, T value) +{ + static_assert(std::numeric_limits::is_integer, "Integer required"); + bool negative = util::is_negative(value); + if (negative) { + // The following conversion is guaranteed by C++11 to never + // overflow (contrast this with "-value" which indeed could + // overflow). See C99+TC3 section 6.2.6.2 paragraph 2. + REALM_DIAG_PUSH(); + REALM_DIAG_IGNORE_UNSIGNED_MINUS(); + value = -(value + 1); + REALM_DIAG_POP(); + } + // At this point 'value' is always a positive number. Also, small + // negative numbers have been converted to small positive numbers. + REALM_ASSERT(!util::is_negative(value)); + // One sign bit plus number of value bits + const int num_bits = 1 + std::numeric_limits::digits; + // Only the first 7 bits are available per byte. Had it not been + // for the fact that maximum guaranteed bit width of a char is 8, + // this value could have been increased to 15 (one less than the + // number of value bits in 'unsigned'). + const int bits_per_byte = 7; + const int max_bytes = (num_bits + (bits_per_byte - 1)) / bits_per_byte; + static_assert(max_bytes <= max_enc_bytes_per_int, "Bad max_enc_bytes_per_int"); + // An explicit constant maximum number of iterations is specified + // in the hope that it will help the optimizer (to do loop + // unrolling, for example). + typedef unsigned char uchar; + for (int i = 0; i < max_bytes; ++i) { + if (value >> (bits_per_byte - 1) == 0) + break; + *reinterpret_cast(ptr) = uchar((1U << bits_per_byte) | unsigned(value & ((1U << bits_per_byte) - 1))); + ++ptr; + value >>= bits_per_byte; + } + *reinterpret_cast(ptr) = uchar(negative ? (1U << (bits_per_byte - 1)) | unsigned(value) : value); + return ++ptr; +} + +template +char* TransactLogEncoder::encode(char* ptr, T value) +{ + auto value_2 = value + 0; // Perform integral promotion + return encode_int(ptr, value_2); +} + +template <> +inline char* TransactLogEncoder::encode(char* ptr, char value) +{ + // Write the char as-is without encoding. + *ptr++ = value; + return ptr; +} + +template <> +inline char* TransactLogEncoder::encode(char* ptr, Instruction inst) +{ + return encode(ptr, inst); +} + +template <> +inline char* TransactLogEncoder::encode(char* ptr, bool value) +{ + return encode(ptr, value); +} + +template <> +inline char* TransactLogEncoder::encode(char* ptr, float value) +{ + static_assert(std::numeric_limits::is_iec559 && + sizeof(float) * std::numeric_limits::digits == 32, + "Unsupported 'float' representation"); + const char* val_ptr = reinterpret_cast(&value); + return realm::safe_copy_n(val_ptr, sizeof value, ptr); +} + +template <> +inline char* TransactLogEncoder::encode(char* ptr, double value) +{ + static_assert(std::numeric_limits::is_iec559 && + sizeof(double) * std::numeric_limits::digits == 64, + "Unsupported 'double' representation"); + const char* val_ptr = reinterpret_cast(&value); + return realm::safe_copy_n(val_ptr, sizeof value, ptr); +} + +template <> +inline char* TransactLogEncoder::encode(char* ptr, DataType type) +{ + return encode(ptr, type); +} + +template <> +inline char* TransactLogEncoder::encode(char* ptr, StringData s) +{ + ptr = encode_int(ptr, s.size()); + return std::copy_n(s.data(), s.size(), ptr); +} + +template <> +inline char* TransactLogEncoder::encode(char* ptr, + TransactLogEncoder::IntegerList list) +{ + IntegerColumnIterator i = std::get<0>(list); + IntegerColumnIterator end = std::get<1>(list); + + while (end - i > max_numbers_per_chunk) { + for (int j = 0; j < max_numbers_per_chunk; ++j) + ptr = encode_int(ptr, *i++); + advance(ptr); + size_t max_required_bytes_2 = max_enc_bytes_per_num * max_numbers_per_chunk; + ptr = reserve(max_required_bytes_2); // Throws + } + + while (i != end) + ptr = encode_int(ptr, *i++); + + return ptr; +} + +template <> +inline char* TransactLogEncoder::encode(char* ptr, + TransactLogEncoder::UnsignedList list) +{ + const size_t* i = std::get<0>(list); + const size_t* end = std::get<1>(list); + + while (i != end) + ptr = encode_int(ptr, *i++); + + return ptr; +} + +template +size_t TransactLogEncoder::max_size(T) +{ + return max_enc_bytes_per_num; +} + +template <> +inline size_t TransactLogEncoder::max_size(char) +{ + return 1; +} + +template <> +inline size_t TransactLogEncoder::max_size(bool) +{ + return 1; +} + +template <> +inline size_t TransactLogEncoder::max_size(Instruction) +{ + return 1; +} + +template <> +inline size_t TransactLogEncoder::max_size(DataType) +{ + return 1; +} + +template <> +inline size_t TransactLogEncoder::max_size(StringData s) +{ + return max_enc_bytes_per_num + s.size(); +} + +template <> +inline size_t TransactLogEncoder::max_size(IntegerList) +{ + // We only allocate space for 'max_numbers_per_chunk' at a time + return max_enc_bytes_per_num * max_numbers_per_chunk; +} + +template <> +inline size_t TransactLogEncoder::max_size(UnsignedList list) +{ + const size_t* begin = std::get<0>(list); + const size_t* end = std::get<1>(list); + // list contains (end - begin) elements + return max_enc_bytes_per_num * (end - begin); +} + +template +void TransactLogEncoder::append_simple_instr(L... numbers) +{ + size_t max_required_bytes = max_size_list(numbers...); + char* ptr = reserve(max_required_bytes); // Throws + encode_list(ptr, numbers...); +} + +template +void TransactLogEncoder::append_mixed_instr(Instruction instr, const Mixed& value, L... numbers) +{ + DataType type = value.get_type(); + switch (type) { + case type_Int: + append_simple_instr(instr, numbers..., type, value.get_int()); // Throws + return; + case type_Bool: + append_simple_instr(instr, numbers..., type, value.get_bool()); // Throws + return; + case type_Float: + append_simple_instr(instr, numbers..., type, value.get_float()); // Throws + return; + case type_Double: + append_simple_instr(instr, numbers..., type, value.get_double()); // Throws + return; + case type_OldDateTime: { + auto value_2 = value.get_olddatetime().get_olddatetime(); + append_simple_instr(instr, numbers..., type, value_2); // Throws + return; + } + case type_String: { + append_simple_instr(instr, numbers..., type, value.get_string()); // Throws + return; + } + case type_Binary: { + BinaryData value_2 = value.get_binary(); + StringData value_3(value_2.data(), value_2.size()); + append_simple_instr(instr, numbers..., type, value_3); // Throws + return; + } + case type_Timestamp: { + Timestamp ts = value.get_timestamp(); + int64_t seconds = ts.get_seconds(); + int32_t nano_seconds = ts.get_nanoseconds(); + append_simple_instr(instr, numbers..., type, seconds, nano_seconds); // Throws + return; + } + case type_Table: + append_simple_instr(instr, numbers..., type); // Throws + return; + case type_Mixed: + // Mixed in mixed is not possible + REALM_TERMINATE("Mixed in Mixed not possible"); + case type_Link: + case type_LinkList: + // FIXME: Need to handle new link types here. + REALM_TERMINATE("Link types in Mixed not supported."); + } + REALM_TERMINATE("Invalid Mixed."); +} + +inline void TransactLogConvenientEncoder::unselect_all() noexcept +{ + m_selected_table = nullptr; + m_selected_spec = nullptr; + // no race with on_link_list_destroyed since both are setting to nullptr + m_selected_link_list = nullptr; +} + +inline void TransactLogConvenientEncoder::select_table(const Table* table) +{ + if (table != m_selected_table) + do_select_table(table); // Throws + m_selected_spec = nullptr; + // no race with on_link_list_destroyed since both are setting to nullptr + m_selected_link_list = nullptr; +} + +inline void TransactLogConvenientEncoder::select_desc(const Descriptor& desc) +{ + typedef _impl::DescriptorFriend df; + if (&df::get_spec(desc) != m_selected_spec) + do_select_desc(desc); // Throws + // no race with on_link_list_destroyed since both are setting to nullptr + m_selected_link_list = nullptr; +} + +inline void TransactLogConvenientEncoder::select_link_list(const LinkView& list) +{ + // A race between this and a call to on_link_list_destroyed() must + // end up with m_selected_link_list pointing to the list argument given + // here. We assume that the list given to on_link_list_destroyed() can + // *never* be the same as the list argument given here. We resolve the + // race by a) always updating m_selected_link_list in do_select_link_list() + // and b) only atomically and conditionally updating it in + // on_link_list_destroyed(). + if (&list != m_selected_link_list) { + do_select_link_list(list); // Throws + } + m_selected_spec = nullptr; +} + + +inline bool TransactLogEncoder::insert_group_level_table(size_t table_ndx, size_t prior_num_tables, StringData name) +{ + append_simple_instr(instr_InsertGroupLevelTable, table_ndx, prior_num_tables, name); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::insert_group_level_table(size_t table_ndx, size_t prior_num_tables, + StringData name) +{ + unselect_all(); + m_encoder.insert_group_level_table(table_ndx, prior_num_tables, name); // Throws +} + +inline bool TransactLogEncoder::erase_group_level_table(size_t table_ndx, size_t prior_num_tables) +{ + append_simple_instr(instr_EraseGroupLevelTable, table_ndx, prior_num_tables); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::erase_group_level_table(size_t table_ndx, size_t prior_num_tables) +{ + unselect_all(); + m_encoder.erase_group_level_table(table_ndx, prior_num_tables); // Throws +} + +inline bool TransactLogEncoder::rename_group_level_table(size_t table_ndx, StringData new_name) +{ + append_simple_instr(instr_RenameGroupLevelTable, table_ndx, new_name); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::rename_group_level_table(size_t table_ndx, StringData new_name) +{ + unselect_all(); + m_encoder.rename_group_level_table(table_ndx, new_name); // Throws +} + +inline bool TransactLogEncoder::insert_column(size_t col_ndx, DataType type, StringData name, bool nullable) +{ + Instruction instr = (nullable ? instr_InsertNullableColumn : instr_InsertColumn); + append_simple_instr(instr, col_ndx, type, name); // Throws + return true; +} + +inline bool TransactLogEncoder::insert_link_column(size_t col_ndx, DataType type, StringData name, + size_t link_target_table_ndx, size_t backlink_col_ndx) +{ + REALM_ASSERT(_impl::TableFriend::is_link_type(ColumnType(type))); + append_simple_instr(instr_InsertLinkColumn, col_ndx, type, link_target_table_ndx, backlink_col_ndx, + name); // Throws + return true; +} + + +inline void TransactLogConvenientEncoder::insert_column(const Descriptor& desc, size_t col_ndx, DataType type, + StringData name, LinkTargetInfo& link, bool nullable) +{ + select_desc(desc); // Throws + if (link.is_valid()) { + typedef _impl::TableFriend tf; + typedef _impl::DescriptorFriend df; + size_t target_table_ndx = link.m_target_table->get_index_in_group(); + const Table& origin_table = df::get_root_table(desc); + REALM_ASSERT(origin_table.is_group_level()); + const Spec& target_spec = tf::get_spec(*(link.m_target_table)); + size_t origin_table_ndx = origin_table.get_index_in_group(); + size_t backlink_col_ndx = target_spec.find_backlink_column(origin_table_ndx, col_ndx); + REALM_ASSERT_3(backlink_col_ndx, ==, link.m_backlink_col_ndx); + m_encoder.insert_link_column(col_ndx, type, name, target_table_ndx, backlink_col_ndx); // Throws + } + else { + m_encoder.insert_column(col_ndx, type, name, nullable); // Throws + } +} + +inline bool TransactLogEncoder::erase_column(size_t col_ndx) +{ + append_simple_instr(instr_EraseColumn, col_ndx); // Throws + return true; +} + +inline bool TransactLogEncoder::erase_link_column(size_t col_ndx, size_t link_target_table_ndx, + size_t backlink_col_ndx) +{ + append_simple_instr(instr_EraseLinkColumn, col_ndx, link_target_table_ndx, backlink_col_ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::erase_column(const Descriptor& desc, size_t col_ndx) +{ + select_desc(desc); // Throws + + DataType type = desc.get_column_type(col_ndx); + typedef _impl::TableFriend tf; + if (!tf::is_link_type(ColumnType(type))) { + m_encoder.erase_column(col_ndx); // Throws + } + else { // it's a link column: + REALM_ASSERT(desc.is_root()); + typedef _impl::DescriptorFriend df; + const Table& origin_table = df::get_root_table(desc); + REALM_ASSERT(origin_table.is_group_level()); + const Table& target_table = *tf::get_link_target_table_accessor(origin_table, col_ndx); + size_t target_table_ndx = target_table.get_index_in_group(); + const Spec& target_spec = tf::get_spec(target_table); + size_t origin_table_ndx = origin_table.get_index_in_group(); + size_t backlink_col_ndx = target_spec.find_backlink_column(origin_table_ndx, col_ndx); + m_encoder.erase_link_column(col_ndx, target_table_ndx, backlink_col_ndx); // Throws + } +} + +inline bool TransactLogEncoder::rename_column(size_t col_ndx, StringData new_name) +{ + append_simple_instr(instr_RenameColumn, col_ndx, new_name); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::rename_column(const Descriptor& desc, size_t col_ndx, StringData name) +{ + select_desc(desc); // Throws + m_encoder.rename_column(col_ndx, name); // Throws +} + + +inline bool TransactLogEncoder::set_int(size_t col_ndx, size_t ndx, int_fast64_t value, Instruction variant, + size_t prior_num_rows) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault || variant == instr_SetUnique, variant); + if (REALM_UNLIKELY(variant == instr_SetUnique)) + append_simple_instr(variant, type_Int, col_ndx, ndx, prior_num_rows, value); // Throws + else + append_simple_instr(variant, type_Int, col_ndx, ndx, value); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_int(const Table* t, size_t col_ndx, size_t ndx, int_fast64_t value, + Instruction variant) +{ + select_table(t); // Throws + size_t prior_num_rows = (variant == instr_SetUnique ? t->size() : 0); + m_encoder.set_int(col_ndx, ndx, value, variant, prior_num_rows); // Throws +} + + +inline bool TransactLogEncoder::add_int(size_t col_ndx, size_t ndx, int_fast64_t value) +{ + append_simple_instr(instr_AddInteger, col_ndx, ndx, value); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::add_int(const Table* t, size_t col_ndx, size_t ndx, int_fast64_t value) +{ + select_table(t); // Throws + m_encoder.add_int(col_ndx, ndx, value); +} + +inline bool TransactLogEncoder::set_bool(size_t col_ndx, size_t ndx, bool value, Instruction variant) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); + append_simple_instr(variant, type_Bool, col_ndx, ndx, value); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_bool(const Table* t, size_t col_ndx, size_t ndx, bool value, + Instruction variant) +{ + select_table(t); // Throws + m_encoder.set_bool(col_ndx, ndx, value, variant); // Throws +} + +inline bool TransactLogEncoder::set_float(size_t col_ndx, size_t ndx, float value, Instruction variant) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); + append_simple_instr(variant, type_Float, col_ndx, ndx, value); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_float(const Table* t, size_t col_ndx, size_t ndx, float value, + Instruction variant) +{ + select_table(t); // Throws + m_encoder.set_float(col_ndx, ndx, value, variant); // Throws +} + +inline bool TransactLogEncoder::set_double(size_t col_ndx, size_t ndx, double value, Instruction variant) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); + append_simple_instr(instr_Set, type_Double, col_ndx, ndx, value); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_double(const Table* t, size_t col_ndx, size_t ndx, double value, + Instruction variant) +{ + select_table(t); // Throws + m_encoder.set_double(col_ndx, ndx, value, variant); // Throws +} + +inline bool TransactLogEncoder::set_string(size_t col_ndx, size_t ndx, StringData value, Instruction variant, + size_t prior_num_rows) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault || variant == instr_SetUnique, variant); + if (value.is_null()) { + set_null(col_ndx, ndx, variant, prior_num_rows); // Throws + } + else { + if (REALM_UNLIKELY(variant == instr_SetUnique)) + append_simple_instr(variant, type_String, col_ndx, ndx, prior_num_rows, value); // Throws + else + append_simple_instr(variant, type_String, col_ndx, ndx, value); // Throws + } + return true; +} + +inline void TransactLogConvenientEncoder::set_string(const Table* t, size_t col_ndx, size_t ndx, StringData value, + Instruction variant) +{ + select_table(t); // Throws + size_t prior_num_rows = (variant == instr_SetUnique ? t->size() : 0); + m_encoder.set_string(col_ndx, ndx, value, variant, prior_num_rows); // Throws +} + +inline bool TransactLogEncoder::set_binary(size_t col_ndx, size_t row_ndx, BinaryData value, Instruction variant) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); + if (value.is_null()) { + set_null(col_ndx, row_ndx, variant); // Throws + } + else { + StringData value_2(value.data(), value.size()); + append_simple_instr(variant, type_Binary, col_ndx, row_ndx, value_2); // Throws + } + return true; +} + +inline void TransactLogConvenientEncoder::set_binary(const Table* t, size_t col_ndx, size_t ndx, BinaryData value, + Instruction variant) +{ + select_table(t); // Throws + m_encoder.set_binary(col_ndx, ndx, value, variant); // Throws +} + +inline bool TransactLogEncoder::set_olddatetime(size_t col_ndx, size_t ndx, OldDateTime value, Instruction variant) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); + append_simple_instr(variant, type_OldDateTime, col_ndx, ndx, value.get_olddatetime()); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_olddatetime(const Table* t, size_t col_ndx, size_t ndx, + OldDateTime value, Instruction variant) +{ + select_table(t); // Throws + m_encoder.set_olddatetime(col_ndx, ndx, value, variant); // Throws +} + +inline bool TransactLogEncoder::set_timestamp(size_t col_ndx, size_t ndx, Timestamp value, Instruction variant) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); + append_simple_instr(variant, type_Timestamp, col_ndx, ndx, value.get_seconds(), + value.get_nanoseconds()); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_timestamp(const Table* t, size_t col_ndx, size_t ndx, Timestamp value, + Instruction variant) +{ + select_table(t); // Throws + m_encoder.set_timestamp(col_ndx, ndx, value, variant); // Throws +} + +inline bool TransactLogEncoder::set_table(size_t col_ndx, size_t ndx, Instruction variant) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); + append_simple_instr(variant, type_Table, col_ndx, ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_table(const Table* t, size_t col_ndx, size_t ndx, Instruction variant) +{ + select_table(t); // Throws + m_encoder.set_table(col_ndx, ndx, variant); // Throws +} + +inline bool TransactLogEncoder::set_mixed(size_t col_ndx, size_t ndx, const Mixed& value, Instruction variant) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); + append_mixed_instr(variant, value, type_Mixed, col_ndx, ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_mixed(const Table* t, size_t col_ndx, size_t ndx, const Mixed& value, + Instruction variant) +{ + select_table(t); // Throws + m_encoder.set_mixed(col_ndx, ndx, value, variant); // Throws +} + +inline bool TransactLogEncoder::set_link(size_t col_ndx, size_t ndx, size_t value, size_t target_group_level_ndx, + Instruction variant) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); + // Map `realm::npos` to zero, and `n` to `n+1`, where `n` is a target row + // index. + size_t value_2 = size_t(1) + value; + append_simple_instr(variant, type_Link, col_ndx, ndx, value_2, target_group_level_ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_link(const Table* t, size_t col_ndx, size_t ndx, size_t value, + Instruction variant) +{ + select_table(t); // Throws + size_t target_group_level_ndx = t->get_descriptor()->get_column_link_target(col_ndx); + m_encoder.set_link(col_ndx, ndx, value, target_group_level_ndx, variant); // Throws +} + +inline bool TransactLogEncoder::set_null(size_t col_ndx, size_t ndx, Instruction variant, size_t prior_num_rows) +{ + REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault || variant == instr_SetUnique, variant); + if (REALM_UNLIKELY(variant == instr_SetUnique)) { + append_simple_instr(variant, set_null_sentinel(), col_ndx, ndx, prior_num_rows); // Throws + } + else { + append_simple_instr(variant, set_null_sentinel(), col_ndx, ndx); // Throws + } + return true; +} + +inline void TransactLogConvenientEncoder::set_null(const Table* t, size_t col_ndx, size_t row_ndx, + Instruction variant) +{ + select_table(t); // Throws + size_t prior_num_rows = (variant == instr_SetUnique ? t->size() : 0); + m_encoder.set_null(col_ndx, row_ndx, variant, prior_num_rows); // Throws +} + +inline bool TransactLogEncoder::nullify_link(size_t col_ndx, size_t ndx, size_t target_group_level_ndx) +{ + append_simple_instr(instr_NullifyLink, col_ndx, ndx, target_group_level_ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::nullify_link(const Table* t, size_t col_ndx, size_t ndx) +{ + select_table(t); // Throws + size_t target_group_level_ndx = t->get_descriptor()->get_column_link_target(col_ndx); + m_encoder.nullify_link(col_ndx, ndx, target_group_level_ndx); // Throws +} + +inline bool TransactLogEncoder::insert_substring(size_t col_ndx, size_t row_ndx, size_t pos, StringData value) +{ + append_simple_instr(instr_InsertSubstring, col_ndx, row_ndx, pos, value); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::insert_substring(const Table* t, size_t col_ndx, size_t row_ndx, size_t pos, + StringData value) +{ + if (value.size() > 0) { + select_table(t); // Throws + m_encoder.insert_substring(col_ndx, row_ndx, pos, value); // Throws + } +} + +inline bool TransactLogEncoder::erase_substring(size_t col_ndx, size_t row_ndx, size_t pos, size_t size) +{ + append_simple_instr(instr_EraseFromString, col_ndx, row_ndx, pos, size); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::erase_substring(const Table* t, size_t col_ndx, size_t row_ndx, size_t pos, + size_t size) +{ + if (size > 0) { + select_table(t); // Throws + m_encoder.erase_substring(col_ndx, row_ndx, pos, size); // Throws + } +} + +inline bool TransactLogEncoder::insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, + bool unordered) +{ + append_simple_instr(instr_InsertEmptyRows, row_ndx, num_rows_to_insert, prior_num_rows, unordered); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::insert_empty_rows(const Table* t, size_t row_ndx, size_t num_rows_to_insert, + size_t prior_num_rows) +{ + select_table(t); // Throws + bool unordered = false; + m_encoder.insert_empty_rows(row_ndx, num_rows_to_insert, prior_num_rows, unordered); // Throws +} + +inline bool TransactLogEncoder::add_row_with_key(size_t row_ndx, size_t prior_num_rows, size_t key_col_ndx, + int64_t key) +{ + append_simple_instr(instr_AddRowWithKey, row_ndx, prior_num_rows, key_col_ndx, key); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::add_row_with_key(const Table* t, size_t row_ndx, size_t prior_num_rows, + size_t key_col_ndx, int64_t key) +{ + select_table(t); // Throws + m_encoder.add_row_with_key(row_ndx, prior_num_rows, key_col_ndx, key); // Throws +} + +inline bool TransactLogEncoder::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, + bool unordered) +{ + append_simple_instr(instr_EraseRows, row_ndx, num_rows_to_erase, prior_num_rows, unordered); // Throws + return true; +} + + +inline void TransactLogConvenientEncoder::erase_rows(const Table* t, size_t row_ndx, size_t num_rows_to_erase, + size_t prior_num_rows, bool is_move_last_over) +{ + select_table(t); // Throws + bool unordered = is_move_last_over; + m_encoder.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, unordered); // Throws +} + +inline bool TransactLogEncoder::swap_rows(size_t row_ndx_1, size_t row_ndx_2) +{ + append_simple_instr(instr_SwapRows, row_ndx_1, row_ndx_2); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::swap_rows(const Table* t, size_t row_ndx_1, size_t row_ndx_2) +{ + REALM_ASSERT(row_ndx_1 < row_ndx_2); + select_table(t); // Throws + m_encoder.swap_rows(row_ndx_1, row_ndx_2); +} + +inline bool TransactLogEncoder::move_row(size_t from_ndx, size_t to_ndx) +{ + append_simple_instr(instr_MoveRow, from_ndx, to_ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::move_row(const Table* t, size_t from_ndx, size_t to_ndx) +{ + REALM_ASSERT(from_ndx != to_ndx); + select_table(t); // Throws + m_encoder.move_row(from_ndx, to_ndx); +} + +inline bool TransactLogEncoder::merge_rows(size_t row_ndx, size_t new_row_ndx) +{ + append_simple_instr(instr_MergeRows, row_ndx, new_row_ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::merge_rows(const Table* t, size_t row_ndx, size_t new_row_ndx) +{ + select_table(t); // Throws + m_encoder.merge_rows(row_ndx, new_row_ndx); +} + +inline bool TransactLogEncoder::add_search_index(size_t col_ndx) +{ + append_simple_instr(instr_AddSearchIndex, col_ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::add_search_index(const Descriptor& desc, size_t col_ndx) +{ + select_desc(desc); // Throws + m_encoder.add_search_index(col_ndx); // Throws +} + + +inline bool TransactLogEncoder::remove_search_index(size_t col_ndx) +{ + append_simple_instr(instr_RemoveSearchIndex, col_ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::remove_search_index(const Descriptor& desc, size_t col_ndx) +{ + select_desc(desc); // Throws + m_encoder.remove_search_index(col_ndx); // Throws +} + +inline bool TransactLogEncoder::set_link_type(size_t col_ndx, LinkType link_type) +{ + append_simple_instr(instr_SetLinkType, col_ndx, int(link_type)); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_link_type(const Table* t, size_t col_ndx, LinkType link_type) +{ + select_table(t); // Throws + m_encoder.set_link_type(col_ndx, link_type); // Throws +} + + +inline bool TransactLogEncoder::clear_table(size_t old_size) +{ + append_simple_instr(instr_ClearTable, old_size); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::clear_table(const Table* t, size_t prior_num_rows) +{ + select_table(t); // Throws + m_encoder.clear_table(prior_num_rows); // Throws +} + +inline bool TransactLogEncoder::optimize_table() +{ + append_simple_instr(instr_OptimizeTable); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::optimize_table(const Table* t) +{ + select_table(t); // Throws + m_encoder.optimize_table(); // Throws +} + +inline bool TransactLogEncoder::link_list_set(size_t link_ndx, size_t value, size_t prior_size) +{ + append_simple_instr(instr_LinkListSet, link_ndx, value, prior_size); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::link_list_set(const LinkView& list, size_t link_ndx, size_t value) +{ + select_link_list(list); // Throws + m_encoder.link_list_set(link_ndx, value, list.size()); // Throws +} + +inline bool TransactLogEncoder::link_list_nullify(size_t link_ndx, size_t prior_size) +{ + append_simple_instr(instr_LinkListNullify, link_ndx, prior_size); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::link_list_nullify(const LinkView& list, size_t link_ndx) +{ + select_link_list(list); // Throws + size_t prior_size = list.size(); // Instruction is emitted before the fact. + m_encoder.link_list_nullify(link_ndx, prior_size); // Throws +} + +inline bool TransactLogEncoder::link_list_set_all(const IntegerColumn& values) +{ + size_t num_values = values.size(); + append_simple_instr( + instr_LinkListSetAll, num_values, + std::make_tuple(IntegerColumnIterator(&values, 0), IntegerColumnIterator(&values, num_values))); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::set_link_list(const LinkView& list, const IntegerColumn& values) +{ + select_link_list(list); // Throws + m_encoder.link_list_set_all(values); // Throws +} + +inline bool TransactLogEncoder::link_list_insert(size_t link_ndx, size_t value, size_t prior_size) +{ + append_simple_instr(instr_LinkListInsert, link_ndx, value, prior_size); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::link_list_insert(const LinkView& list, size_t link_ndx, size_t value) +{ + select_link_list(list); // Throws + size_t prior_size = list.size() - 1; // The instruction is emitted after the fact. + m_encoder.link_list_insert(link_ndx, value, prior_size); // Throws +} + +inline bool TransactLogEncoder::link_list_move(size_t from_link_ndx, size_t to_link_ndx) +{ + REALM_ASSERT(from_link_ndx != to_link_ndx); + append_simple_instr(instr_LinkListMove, from_link_ndx, to_link_ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::link_list_move(const LinkView& list, size_t from_link_ndx, + size_t to_link_ndx) +{ + select_link_list(list); // Throws + m_encoder.link_list_move(from_link_ndx, to_link_ndx); // Throws +} + +inline bool TransactLogEncoder::link_list_swap(size_t link1_ndx, size_t link2_ndx) +{ + append_simple_instr(instr_LinkListSwap, link1_ndx, link2_ndx); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::link_list_swap(const LinkView& list, size_t link1_ndx, size_t link2_ndx) +{ + select_link_list(list); // Throws + m_encoder.link_list_swap(link1_ndx, link2_ndx); // Throws +} + +inline bool TransactLogEncoder::link_list_erase(size_t link_ndx, size_t prior_size) +{ + append_simple_instr(instr_LinkListErase, link_ndx, prior_size); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::link_list_erase(const LinkView& list, size_t link_ndx) +{ + select_link_list(list); // Throws + size_t prior_size = list.size(); // The instruction is emitted before the fact. + m_encoder.link_list_erase(link_ndx, prior_size); // Throws +} + +inline bool TransactLogEncoder::link_list_clear(size_t old_list_size) +{ + append_simple_instr(instr_LinkListClear, old_list_size); // Throws + return true; +} + +inline void TransactLogConvenientEncoder::on_table_destroyed(const Table* t) noexcept +{ + if (m_selected_table == t) + m_selected_table = nullptr; +} + +inline void TransactLogConvenientEncoder::on_spec_destroyed(const Spec* s) noexcept +{ + if (m_selected_spec == s) + m_selected_spec = nullptr; +} + + +inline void TransactLogConvenientEncoder::on_link_list_destroyed(const LinkView& list) noexcept +{ + const LinkView* lw_ptr = &list; + // atomically clear m_selected_link_list iff it already points to 'list': + // (lw_ptr will be modified if the swap fails, but we ignore that) + m_selected_link_list.compare_exchange_strong(lw_ptr, nullptr, std::memory_order_relaxed, + std::memory_order_relaxed); +} + + +inline TransactLogParser::TransactLogParser() + : m_input_buffer(1024) // Throws +{ +} + + +inline TransactLogParser::~TransactLogParser() noexcept +{ +} + + +template +void TransactLogParser::parse(NoCopyInputStream& in, InstructionHandler& handler) +{ + m_input = ∈ + m_input_begin = m_input_end = nullptr; + + while (has_next()) + parse_one(handler); // Throws +} + +template +void TransactLogParser::parse(InputStream& in, InstructionHandler& handler) +{ + NoCopyInputStreamAdaptor in_2(in, m_input_buffer.data(), m_input_buffer.size()); + parse(in_2, handler); // Throws +} + +inline bool TransactLogParser::has_next() noexcept +{ + return m_input_begin != m_input_end || next_input_buffer(); +} + +template +void TransactLogParser::parse_one(InstructionHandler& handler) +{ + char instr_ch; + if (!read_char(instr_ch)) + parser_error(); // Throws + // std::cerr << "parsing " << util::promote(instr) << " @ " << std::hex << long(m_input_begin) << std::dec << + // "\n"; + Instruction instr = Instruction(instr_ch); + switch (instr) { + case instr_SetDefault: + case instr_SetUnique: + case instr_Set: { + int type = read_int(); // Throws + size_t col_ndx = read_int(); // Throws + size_t row_ndx = read_int(); // Throws + size_t prior_num_rows = 0; + if (REALM_UNLIKELY(instr == instr_SetUnique)) + prior_num_rows = read_int(); // Throws + + if (type == TransactLogEncoder::set_null_sentinel()) { + // Special case for set_null + if (!handler.set_null(col_ndx, row_ndx, instr, prior_num_rows)) // Throws + parser_error(); + return; + } + + switch (DataType(type)) { + case type_Int: { + int_fast64_t value = read_int(); // Throws + if (!handler.set_int(col_ndx, row_ndx, value, instr, prior_num_rows)) // Throws + parser_error(); + return; + } + case type_Bool: { + bool value = read_bool(); // Throws + if (!handler.set_bool(col_ndx, row_ndx, value, instr)) // Throws + parser_error(); + return; + } + case type_Float: { + float value = read_float(); // Throws + if (!handler.set_float(col_ndx, row_ndx, value, instr)) // Throws + parser_error(); + return; + } + case type_Double: { + double value = read_double(); // Throws + if (!handler.set_double(col_ndx, row_ndx, value, instr)) // Throws + parser_error(); + return; + } + case type_String: { + StringData value = read_string(m_string_buffer); // Throws + if (!handler.set_string(col_ndx, row_ndx, value, instr, prior_num_rows)) // Throws + parser_error(); + return; + } + case type_Binary: { + BinaryData value = read_binary(m_string_buffer); // Throws + if (!handler.set_binary(col_ndx, row_ndx, value, instr)) // Throws + parser_error(); + return; + } + case type_OldDateTime: { + int_fast64_t value = read_int(); // Throws + if (!handler.set_olddatetime(col_ndx, row_ndx, value, instr)) // Throws + parser_error(); + return; + } + case type_Timestamp: { + int64_t seconds = read_int(); // Throws + int32_t nanoseconds = read_int(); // Throws + Timestamp value = Timestamp(seconds, nanoseconds); + if (!handler.set_timestamp(col_ndx, row_ndx, value, instr)) // Throws + parser_error(); + return; + } + case type_Table: { + if (!handler.set_table(col_ndx, row_ndx, instr)) // Throws + parser_error(); + return; + } + case type_Mixed: { + Mixed value; + read_mixed(&value); // Throws + if (!handler.set_mixed(col_ndx, row_ndx, value, instr)) // Throws + parser_error(); + return; + } + case type_Link: { + size_t value = read_int(); // Throws + // Map zero to realm::npos, and `n+1` to `n`, where `n` is a target row index. + size_t target_row_ndx = size_t(value - 1); + size_t target_group_level_ndx = read_int(); // Throws + if (!handler.set_link(col_ndx, row_ndx, target_row_ndx, target_group_level_ndx, instr)) // Throws + parser_error(); + return; + } + case type_LinkList: { + // Unsupported column type for Set. + parser_error(); + return; + } + } + parser_error(); + return; + } + case instr_AddInteger: { + size_t col_ndx = read_int(); // Throws + size_t row_ndx = read_int(); // Throws + int_fast64_t value = read_int(); // Throws + if (!handler.add_int(col_ndx, row_ndx, value)) // Throws + parser_error(); + return; + } + case instr_NullifyLink: { + size_t col_ndx = read_int(); // Throws + size_t row_ndx = read_int(); // Throws + size_t target_group_level_ndx = read_int(); // Throws + if (!handler.nullify_link(col_ndx, row_ndx, target_group_level_ndx)) // Throws + parser_error(); + return; + } + case instr_InsertSubstring: { + size_t col_ndx = read_int(); // Throws + size_t row_ndx = read_int(); // Throws + size_t pos = read_int(); // Throws + StringData value = read_string(m_string_buffer); // Throws + if (!handler.insert_substring(col_ndx, row_ndx, pos, value)) // Throws + parser_error(); + return; + } + case instr_EraseFromString: { + size_t col_ndx = read_int(); // Throws + size_t row_ndx = read_int(); // Throws + size_t pos = read_int(); // Throws + size_t size = read_int(); // Throws + if (!handler.erase_substring(col_ndx, row_ndx, pos, size)) // Throws + parser_error(); + return; + } + case instr_InsertEmptyRows: { + size_t row_ndx = read_int(); // Throws + size_t num_rows_to_insert = read_int(); // Throws + size_t prior_num_rows = read_int(); // Throws + bool unordered = read_bool(); // Throws + if (!handler.insert_empty_rows(row_ndx, num_rows_to_insert, prior_num_rows, unordered)) // Throws + parser_error(); + return; + } + case instr_AddRowWithKey: { + size_t row_ndx = read_int(); // Throws + size_t prior_num_rows = read_int(); // Throws + size_t key_col_ndx = read_int(); // Throws + int64_t key = read_int(); // Throws + if (!handler.add_row_with_key(row_ndx, prior_num_rows, key_col_ndx, key)) // Throws + parser_error(); + return; + } + case instr_EraseRows: { + size_t row_ndx = read_int(); // Throws + size_t num_rows_to_erase = read_int(); // Throws + size_t prior_num_rows = read_int(); // Throws + bool unordered = read_bool(); // Throws + if (!handler.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, unordered)) // Throws + parser_error(); + return; + } + case instr_SwapRows: { + size_t row_ndx_1 = read_int(); // Throws + size_t row_ndx_2 = read_int(); // Throws + if (!handler.swap_rows(row_ndx_1, row_ndx_2)) // Throws + parser_error(); + return; + } + case instr_MoveRow: { + size_t from_ndx = read_int(); // Throws + size_t to_ndx = read_int(); // Throws + if (!handler.move_row(from_ndx, to_ndx)) // Throws + parser_error(); + return; + } + case instr_MergeRows: { + size_t row_ndx = read_int(); // Throws + size_t new_row_ndx = read_int(); // Throws + if (!handler.merge_rows(row_ndx, new_row_ndx)) // Throws + parser_error(); + return; + } + case instr_SelectTable: { + int levels = read_int(); // Throws + if (levels < 0 || levels > m_max_levels) + parser_error(); + m_path.reserve(0, 2 * levels); // Throws + size_t* path = m_path.data(); + size_t group_level_ndx = read_int(); // Throws + for (int i = 0; i != levels; ++i) { + size_t col_ndx = read_int(); // Throws + size_t row_ndx = read_int(); // Throws + path[2 * i + 0] = col_ndx; + path[2 * i + 1] = row_ndx; + } + if (!handler.select_table(group_level_ndx, levels, path)) // Throws + parser_error(); + return; + } + case instr_ClearTable: { + size_t old_size = read_int(); // Throws + if (!handler.clear_table(old_size)) // Throws + parser_error(); + return; + } + case instr_LinkListSet: { + size_t link_ndx = read_int(); // Throws + size_t value = read_int(); // Throws + size_t prior_size = read_int(); // Throws + if (!handler.link_list_set(link_ndx, value, prior_size)) // Throws + parser_error(); + return; + } + case instr_LinkListSetAll: { + // todo, log that it's a SetAll we're doing + size_t size = read_int(); // Throws + for (size_t i = 0; i < size; i++) { + size_t link = read_int(); // Throws + if (!handler.link_list_set(i, link, size)) // Throws + parser_error(); + } + return; + } + case instr_LinkListInsert: { + size_t link_ndx = read_int(); // Throws + size_t value = read_int(); // Throws + size_t prior_size = read_int(); // Throws + if (!handler.link_list_insert(link_ndx, value, prior_size)) // Throws + parser_error(); + return; + } + case instr_LinkListMove: { + size_t from_link_ndx = read_int(); // Throws + size_t to_link_ndx = read_int(); // Throws + if (!handler.link_list_move(from_link_ndx, to_link_ndx)) // Throws + parser_error(); + return; + } + case instr_LinkListSwap: { + size_t link1_ndx = read_int(); // Throws + size_t link2_ndx = read_int(); // Throws + if (!handler.link_list_swap(link1_ndx, link2_ndx)) // Throws + parser_error(); + return; + } + case instr_LinkListErase: { + size_t link_ndx = read_int(); // Throws + size_t prior_size = read_int(); // Throws + if (!handler.link_list_erase(link_ndx, prior_size)) // Throws + parser_error(); + return; + } + case instr_LinkListNullify: { + size_t link_ndx = read_int(); // Throws + size_t prior_size = read_int(); // Throws + if (!handler.link_list_nullify(link_ndx, prior_size)) // Throws + parser_error(); + return; + } + case instr_LinkListClear: { + size_t old_list_size = read_int(); // Throws + if (!handler.link_list_clear(old_list_size)) // Throws + parser_error(); + return; + } + case instr_SelectLinkList: { + size_t col_ndx = read_int(); // Throws + size_t row_ndx = read_int(); // Throws + size_t target_group_level_ndx = read_int(); // Throws + if (!handler.select_link_list(col_ndx, row_ndx, target_group_level_ndx)) // Throws + parser_error(); + return; + } + case instr_MoveColumn: { + // FIXME: remove this in the next breaking change. + // This instruction is no longer supported and not used by either + // bindings or sync, so if we see it here, there was a problem parsing. + parser_error(); + return; + } + case instr_AddSearchIndex: { + size_t col_ndx = read_int(); // Throws + if (!handler.add_search_index(col_ndx)) // Throws + parser_error(); + return; + } + case instr_RemoveSearchIndex: { + size_t col_ndx = read_int(); // Throws + if (!handler.remove_search_index(col_ndx)) // Throws + parser_error(); + return; + } + case instr_SetLinkType: { + size_t col_ndx = read_int(); // Throws + int link_type = read_int(); // Throws + if (!is_valid_link_type(link_type)) + parser_error(); + if (!handler.set_link_type(col_ndx, LinkType(link_type))) // Throws + parser_error(); + return; + } + case instr_InsertColumn: + case instr_InsertNullableColumn: { + size_t col_ndx = read_int(); // Throws + int type = read_int(); // Throws + if (!is_valid_data_type(type)) + parser_error(); + if (REALM_UNLIKELY(type == type_Link || type == type_LinkList)) + parser_error(); + StringData name = read_string(m_string_buffer); // Throws + bool nullable = (Instruction(instr) == instr_InsertNullableColumn); + if (REALM_UNLIKELY(nullable && (type == type_Mixed))) { + // Nullability not supported for Mixed columns. + parser_error(); + } + if (!handler.insert_column(col_ndx, DataType(type), name, nullable)) // Throws + parser_error(); + return; + } + case instr_InsertLinkColumn: { + size_t col_ndx = read_int(); // Throws + int type = read_int(); // Throws + if (!is_valid_data_type(type)) + parser_error(); + if (REALM_UNLIKELY(type != type_Link && type != type_LinkList)) + parser_error(); + size_t link_target_table_ndx = read_int(); // Throws + size_t backlink_col_ndx = read_int(); // Throws + StringData name = read_string(m_string_buffer); // Throws + if (!handler.insert_link_column(col_ndx, DataType(type), name, link_target_table_ndx, + backlink_col_ndx)) // Throws + parser_error(); + return; + } + case instr_EraseColumn: { + size_t col_ndx = read_int(); // Throws + if (!handler.erase_column(col_ndx)) // Throws + parser_error(); + return; + } + case instr_EraseLinkColumn: { + size_t col_ndx = read_int(); // Throws + size_t link_target_table_ndx = read_int(); // Throws + size_t backlink_col_ndx = read_int(); // Throws + if (!handler.erase_link_column(col_ndx, link_target_table_ndx, backlink_col_ndx)) // Throws + parser_error(); + return; + } + case instr_RenameColumn: { + size_t col_ndx = read_int(); // Throws + StringData name = read_string(m_string_buffer); // Throws + if (!handler.rename_column(col_ndx, name)) // Throws + parser_error(); + return; + } + case instr_SelectDescriptor: { + int levels = read_int(); // Throws + if (levels < 0 || levels > m_max_levels) + parser_error(); + m_path.reserve(0, levels); // Throws + size_t* path = m_path.data(); + for (int i = 0; i != levels; ++i) { + size_t col_ndx = read_int(); // Throws + path[i] = col_ndx; + } + if (!handler.select_descriptor(levels, path)) // Throws + parser_error(); + return; + } + case instr_InsertGroupLevelTable: { + size_t table_ndx = read_int(); // Throws + size_t num_tables = read_int(); // Throws + StringData name = read_string(m_string_buffer); // Throws + if (!handler.insert_group_level_table(table_ndx, num_tables, name)) // Throws + parser_error(); + return; + } + case instr_EraseGroupLevelTable: { + size_t table_ndx = read_int(); // Throws + size_t prior_num_tables = read_int(); // Throws + if (!handler.erase_group_level_table(table_ndx, prior_num_tables)) // Throws + parser_error(); + return; + } + case instr_RenameGroupLevelTable: { + size_t table_ndx = read_int(); // Throws + StringData new_name = read_string(m_string_buffer); // Throws + if (!handler.rename_group_level_table(table_ndx, new_name)) // Throws + parser_error(); + return; + } + case instr_MoveGroupLevelTable: { + // This instruction is no longer supported and not used by either + // bindings or sync, so if we see it here, there was a problem parsing. + // FIXME: remove this in the next breaking change. + parser_error(); + return; + } + case instr_OptimizeTable: { + if (!handler.optimize_table()) // Throws + parser_error(); + return; + } + } + + throw BadTransactLog(); +} + + +template +T TransactLogParser::read_int() +{ + T value = 0; + int part = 0; + const int max_bytes = (std::numeric_limits::digits + 1 + 6) / 7; + for (int i = 0; i != max_bytes; ++i) { + char c; + if (!read_char(c)) + goto bad_transact_log; + part = static_cast(c); + if (0xFF < part) + goto bad_transact_log; // Only the first 8 bits may be used in each byte + if ((part & 0x80) == 0) { + T p = part & 0x3F; + if (util::int_shift_left_with_overflow_detect(p, i * 7)) + goto bad_transact_log; + value |= p; + break; + } + if (i == max_bytes - 1) + goto bad_transact_log; // Too many bytes + value |= T(part & 0x7F) << (i * 7); + } + if (part & 0x40) { + // The real value is negative. Because 'value' is positive at + // this point, the following negation is guaranteed by C++11 + // to never overflow. See C99+TC3 section 6.2.6.2 paragraph 2. + REALM_DIAG_PUSH(); + REALM_DIAG_IGNORE_UNSIGNED_MINUS(); + value = -value; + REALM_DIAG_POP(); + if (util::int_subtract_with_overflow_detect(value, 1)) + goto bad_transact_log; + } + return value; + +bad_transact_log: + throw BadTransactLog(); +} + + +inline void TransactLogParser::read_bytes(char* data, size_t size) +{ + for (;;) { + const size_t avail = m_input_end - m_input_begin; + if (size <= avail) + break; + realm::safe_copy_n(m_input_begin, avail, data); + if (!next_input_buffer()) + throw BadTransactLog(); + data += avail; + size -= avail; + } + const char* to = m_input_begin + size; + realm::safe_copy_n(m_input_begin, size, data); + m_input_begin = to; +} + + +inline BinaryData TransactLogParser::read_buffer(util::StringBuffer& buf, size_t size) +{ + const size_t avail = m_input_end - m_input_begin; + if (avail >= size) { + m_input_begin += size; + return BinaryData(m_input_begin - size, size); + } + + buf.clear(); + buf.resize(size); // Throws + read_bytes(buf.data(), size); + return BinaryData(buf.data(), size); +} + + +inline bool TransactLogParser::read_bool() +{ + return read_int(); +} + + +inline float TransactLogParser::read_float() +{ + static_assert(std::numeric_limits::is_iec559 && + sizeof(float) * std::numeric_limits::digits == 32, + "Unsupported 'float' representation"); + float value; + read_bytes(reinterpret_cast(&value), sizeof value); // Throws + return value; +} + + +inline double TransactLogParser::read_double() +{ + static_assert(std::numeric_limits::is_iec559 && + sizeof(double) * std::numeric_limits::digits == 64, + "Unsupported 'double' representation"); + double value; + read_bytes(reinterpret_cast(&value), sizeof value); // Throws + return value; +} + + +inline StringData TransactLogParser::read_string(util::StringBuffer& buf) +{ + size_t size = read_int(); // Throws + + if (size > Table::max_string_size) + parser_error(); + + BinaryData buffer = read_buffer(buf, size); + return StringData{buffer.data(), size}; +} + +inline Timestamp TransactLogParser::read_timestamp() +{ + int64_t seconds = read_int(); // Throws + int32_t nanoseconds = read_int(); // Throws + return Timestamp(seconds, nanoseconds); +} + + +inline BinaryData TransactLogParser::read_binary(util::StringBuffer& buf) +{ + size_t size = read_int(); // Throws + + return read_buffer(buf, size); +} + + +inline void TransactLogParser::read_mixed(Mixed* mixed) +{ + DataType type = DataType(read_int()); // Throws + switch (type) { + case type_Int: { + int_fast64_t value = read_int(); // Throws + mixed->set_int(value); + return; + } + case type_Bool: { + bool value = read_bool(); // Throws + mixed->set_bool(value); + return; + } + case type_Float: { + float value = read_float(); // Throws + mixed->set_float(value); + return; + } + case type_Double: { + double value = read_double(); // Throws + mixed->set_double(value); + return; + } + case type_OldDateTime: { + int_fast64_t value = read_int(); // Throws + mixed->set_olddatetime(value); + return; + } + case type_Timestamp: { + Timestamp value = read_timestamp(); // Throws + mixed->set_timestamp(value); + return; + } + case type_String: { + StringData value = read_string(m_string_buffer); // Throws + mixed->set_string(value); + return; + } + case type_Binary: { + BinaryData value = read_binary(m_string_buffer); // Throws + mixed->set_binary(value); + return; + } + case type_Table: { + *mixed = Mixed::subtable_tag(); + return; + } + case type_Mixed: + break; + case type_Link: + case type_LinkList: + // FIXME: Need to handle new link types here + break; + } + throw BadTransactLog(); +} + + +inline bool TransactLogParser::next_input_buffer() +{ + return m_input->next_block(m_input_begin, m_input_end); +} + + +inline bool TransactLogParser::read_char(char& c) +{ + if (m_input_begin == m_input_end && !next_input_buffer()) + return false; + c = *m_input_begin++; + return true; +} + + +inline bool TransactLogParser::is_valid_data_type(int type) +{ + switch (DataType(type)) { + case type_Int: + case type_Bool: + case type_Float: + case type_Double: + case type_String: + case type_Binary: + case type_OldDateTime: + case type_Timestamp: + case type_Table: + case type_Mixed: + case type_Link: + case type_LinkList: + return true; + } + return false; +} + + +inline bool TransactLogParser::is_valid_link_type(int type) +{ + switch (LinkType(type)) { + case link_Strong: + case link_Weak: + return true; + } + return false; +} + + +class TransactReverser { +public: + bool select_table(size_t group_level_ndx, size_t levels, const size_t* path) + { + sync_table(); + m_encoder.select_table(group_level_ndx, levels, path); + m_pending_ts_instr = get_inst(); + return true; + } + + bool select_descriptor(size_t levels, const size_t* path) + { + sync_descriptor(); + m_encoder.select_descriptor(levels, path); + m_pending_ds_instr = get_inst(); + return true; + } + + bool insert_group_level_table(size_t table_ndx, size_t num_tables, StringData) + { + sync_table(); + m_encoder.erase_group_level_table(table_ndx, num_tables + 1); + append_instruction(); + return true; + } + + bool erase_group_level_table(size_t table_ndx, size_t num_tables) + { + sync_table(); + m_encoder.insert_group_level_table(table_ndx, num_tables - 1, ""); + append_instruction(); + return true; + } + + bool rename_group_level_table(size_t, StringData) + { + sync_table(); + return true; + } + + bool optimize_table() + { + return true; // No-op + } + + bool insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool unordered) + { + size_t num_rows_to_erase = num_rows_to_insert; + size_t prior_num_rows_2 = prior_num_rows + num_rows_to_insert; + m_encoder.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows_2, unordered); // Throws + append_instruction(); + return true; + } + + bool add_row_with_key(size_t row_ndx, size_t prior_num_rows, size_t, int64_t) + { + bool unordered = true; + m_encoder.erase_rows(row_ndx, 1, prior_num_rows + 1, unordered); // Throws + append_instruction(); + return true; + } + + bool erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool unordered) + { + size_t num_rows_to_insert = num_rows_to_erase; + // Number of rows in table after removal, but before inverse insertion + size_t prior_num_rows_2 = prior_num_rows - num_rows_to_erase; + m_encoder.insert_empty_rows(row_ndx, num_rows_to_insert, prior_num_rows_2, unordered); // Throws + append_instruction(); + return true; + } + + bool swap_rows(size_t row_ndx_1, size_t row_ndx_2) + { + m_encoder.swap_rows(row_ndx_1, row_ndx_2); + append_instruction(); + return true; + } + + bool move_row(size_t from_ndx, size_t to_ndx) + { + m_encoder.move_row(to_ndx, from_ndx); + append_instruction(); + return true; + } + + bool merge_rows(size_t row_ndx, size_t new_row_ndx) + { + // There is no instruction we can generate here to change back. + // However, we do need to refresh accessors for any tables + // connected through backlinks, so we generate updates on each + // affected row by merging to itself. + m_encoder.merge_rows(row_ndx, row_ndx); + append_instruction(); + m_encoder.merge_rows(new_row_ndx, new_row_ndx); + append_instruction(); + return true; + } + + bool set_int(size_t col_ndx, size_t row_ndx, int_fast64_t value, Instruction variant, size_t prior_num_rows) + { + m_encoder.set_int(col_ndx, row_ndx, value, variant, prior_num_rows); + append_instruction(); + return true; + } + + bool add_int(size_t col_ndx, size_t row_ndx, int_fast64_t value) + { + m_encoder.add_int(col_ndx, row_ndx, -value); + append_instruction(); + return true; + } + + bool set_bool(size_t col_ndx, size_t row_ndx, bool value, Instruction variant) + { + m_encoder.set_bool(col_ndx, row_ndx, value, variant); + append_instruction(); + return true; + } + + bool set_float(size_t col_ndx, size_t row_ndx, float value, Instruction variant) + { + m_encoder.set_float(col_ndx, row_ndx, value, variant); + append_instruction(); + return true; + } + + bool set_double(size_t col_ndx, size_t row_ndx, double value, Instruction variant) + { + m_encoder.set_double(col_ndx, row_ndx, value, variant); + append_instruction(); + return true; + } + + bool set_string(size_t col_ndx, size_t row_ndx, StringData value, Instruction variant, size_t prior_num_rows) + { + m_encoder.set_string(col_ndx, row_ndx, value, variant, prior_num_rows); + append_instruction(); + return true; + } + + bool set_binary(size_t col_ndx, size_t row_ndx, BinaryData value, Instruction variant) + { + m_encoder.set_binary(col_ndx, row_ndx, value, variant); + append_instruction(); + return true; + } + + bool set_olddatetime(size_t col_ndx, size_t row_ndx, OldDateTime value, Instruction variant) + { + m_encoder.set_olddatetime(col_ndx, row_ndx, value, variant); + append_instruction(); + return true; + } + + bool set_timestamp(size_t col_ndx, size_t row_ndx, Timestamp value, Instruction variant) + { + m_encoder.set_timestamp(col_ndx, row_ndx, value, variant); + append_instruction(); + return true; + } + + bool set_table(size_t col_ndx, size_t row_ndx, Instruction variant) + { + m_encoder.set_table(col_ndx, row_ndx, variant); + append_instruction(); + return true; + } + + bool set_mixed(size_t col_ndx, size_t row_ndx, const Mixed& value, Instruction variant) + { + m_encoder.set_mixed(col_ndx, row_ndx, value, variant); + append_instruction(); + return true; + } + + bool set_null(size_t col_ndx, size_t row_ndx, Instruction variant, size_t prior_num_rows) + { + m_encoder.set_null(col_ndx, row_ndx, variant, prior_num_rows); + append_instruction(); + return true; + } + + bool set_link(size_t col_ndx, size_t row_ndx, size_t value, size_t target_group_level_ndx, Instruction variant) + { + m_encoder.set_link(col_ndx, row_ndx, value, target_group_level_ndx, variant); + append_instruction(); + return true; + } + + bool insert_substring(size_t, size_t, size_t, StringData) + { + return true; // No-op + } + + bool erase_substring(size_t, size_t, size_t, size_t) + { + return true; // No-op + } + + bool clear_table(size_t old_size) + { + bool unordered = false; + m_encoder.insert_empty_rows(0, old_size, 0, unordered); + append_instruction(); + return true; + } + + bool add_search_index(size_t) + { + return true; // No-op + } + + bool remove_search_index(size_t) + { + return true; // No-op + } + + bool set_link_type(size_t, LinkType) + { + return true; // No-op + } + + bool insert_link_column(size_t col_idx, DataType, StringData, size_t target_table_idx, size_t backlink_col_ndx) + { + m_encoder.erase_link_column(col_idx, target_table_idx, backlink_col_ndx); + append_instruction(); + return true; + } + + bool erase_link_column(size_t col_idx, size_t target_table_idx, size_t backlink_col_idx) + { + DataType type = type_Link; // The real type of the column doesn't matter here, + // but the encoder asserts that it's actually a link type. + m_encoder.insert_link_column(col_idx, type, "", target_table_idx, backlink_col_idx); + append_instruction(); + return true; + } + + bool insert_column(size_t col_idx, DataType, StringData, bool) + { + m_encoder.erase_column(col_idx); + append_instruction(); + return true; + } + + bool erase_column(size_t col_idx) + { + m_encoder.insert_column(col_idx, DataType(), ""); + append_instruction(); + return true; + } + + bool rename_column(size_t, StringData) + { + return true; // No-op + } + + bool select_link_list(size_t col_ndx, size_t row_ndx, size_t link_target_group_level_ndx) + { + sync_linkview(); + m_encoder.select_link_list(col_ndx, row_ndx, link_target_group_level_ndx); + m_pending_lv_instr = get_inst(); + return true; + } + + bool link_list_set(size_t row, size_t value, size_t prior_size) + { + m_encoder.link_list_set(row, value, prior_size); + append_instruction(); + return true; + } + + bool link_list_insert(size_t link_ndx, size_t, size_t prior_size) + { + m_encoder.link_list_erase(link_ndx, prior_size + 1); + append_instruction(); + return true; + } + + bool link_list_move(size_t from_link_ndx, size_t to_link_ndx) + { + m_encoder.link_list_move(from_link_ndx, to_link_ndx); + append_instruction(); + return true; + } + + bool link_list_swap(size_t link1_ndx, size_t link2_ndx) + { + m_encoder.link_list_swap(link1_ndx, link2_ndx); + append_instruction(); + return true; + } + + bool link_list_erase(size_t link_ndx, size_t prior_size) + { + m_encoder.link_list_insert(link_ndx, 0, prior_size - 1); + append_instruction(); + return true; + } + + bool link_list_clear(size_t old_list_size) + { + // Append in reverse order because the reversed log is itself applied + // in reverse, and this way it generates all back-insertions rather than + // all front-insertions + for (size_t i = old_list_size; i > 0; --i) { + m_encoder.link_list_insert(i - 1, 0, old_list_size - i); + append_instruction(); + } + return true; + } + + bool nullify_link(size_t col_ndx, size_t row_ndx, size_t target_group_level_ndx) + { + size_t value = 0; + // FIXME: Is zero this right value to pass here, or should + // TransactReverser::nullify_link() also have taken a + // `target_group_level_ndx` argument. + m_encoder.set_link(col_ndx, row_ndx, value, target_group_level_ndx); + append_instruction(); + return true; + } + + bool link_list_nullify(size_t link_ndx, size_t prior_size) + { + m_encoder.link_list_insert(link_ndx, 0, prior_size - 1); + append_instruction(); + return true; + } + +private: + _impl::TransactLogBufferStream m_buffer; + _impl::TransactLogEncoder m_encoder{m_buffer}; + struct Instr { + size_t begin; + size_t end; + }; + std::vector m_instructions; + size_t current_instr_start = 0; + Instr m_pending_ts_instr{0, 0}; + Instr m_pending_ds_instr{0, 0}; + Instr m_pending_lv_instr{0, 0}; + + Instr get_inst() + { + Instr instr; + instr.begin = current_instr_start; + current_instr_start = transact_log_size(); + instr.end = current_instr_start; + return instr; + } + + size_t transact_log_size() const + { + REALM_ASSERT_3(m_encoder.write_position(), >=, m_buffer.transact_log_data()); + return m_encoder.write_position() - m_buffer.transact_log_data(); + } + + void append_instruction() + { + m_instructions.push_back(get_inst()); + } + + void append_instruction(Instr instr) + { + m_instructions.push_back(instr); + } + + void sync_select(Instr& pending_instr) + { + if (pending_instr.begin != pending_instr.end) { + append_instruction(pending_instr); + pending_instr = {0, 0}; + } + } + + void sync_linkview() + { + sync_select(m_pending_lv_instr); + } + + void sync_descriptor() + { + sync_linkview(); + sync_select(m_pending_ds_instr); + } + + void sync_table() + { + sync_descriptor(); + sync_select(m_pending_ts_instr); + } + + friend class ReversedNoCopyInputStream; +}; + + +class ReversedNoCopyInputStream : public NoCopyInputStream { +public: + ReversedNoCopyInputStream(TransactReverser& reverser) + : m_instr_order(reverser.m_instructions) + { + // push any pending select_table or select_descriptor into the buffer + reverser.sync_table(); + + m_buffer = reverser.m_buffer.transact_log_data(); + m_current = m_instr_order.size(); + } + + bool next_block(const char*& begin, const char*& end) override + { + if (m_current != 0) { + m_current--; + begin = m_buffer + m_instr_order[m_current].begin; + end = m_buffer + m_instr_order[m_current].end; + return (end > begin); + } + return false; + } + +private: + const char* m_buffer; + std::vector& m_instr_order; + size_t m_current; +}; + +} // namespace _impl +} // namespace realm + +#endif // REALM_IMPL_TRANSACT_LOG_HPP diff --git a/Pods/Realm/include/core/realm/index_string.hpp b/Pods/Realm/include/core/realm/index_string.hpp new file mode 100644 index 0000000000..b357c19f9f --- /dev/null +++ b/Pods/Realm/include/core/realm/index_string.hpp @@ -0,0 +1,606 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_INDEX_STRING_HPP +#define REALM_INDEX_STRING_HPP + +#include +#include +#include + +#include +#include + +/* +The StringIndex class is used for both type_String and all integral types, such as type_Bool, type_OldDateTime and +type_Int. When used for integral types, the 64-bit integer is simply casted to a string of 8 bytes through a +pretty simple "wrapper layer" in all public methods. + +The StringIndex data structure is like an "inversed" B+ tree where the leafs contain row indexes and the non-leafs +contain 4-byte chunks of payload. Imagine a table with following strings: + + hello, kitty, kitten, foobar, kitty, foobar + +The topmost level of the index tree contains prefixes of the payload strings of length <= 4. The next level contains +prefixes of the remaining parts of the strings. Unnecessary levels of the tree are optimized away; the prefix "foob" +is shared only by rows that are identical ("foobar"), so "ar" is not needed to be stored in the tree. + + hell kitt foob + | /\ | + 0 en y {3, 5} + | \ + {1, 4} 2 + +Each non-leafs consists of two integer arrays of the same length, one containing payload and the other containing +references to the sublevel nodes. + +The leafs can be either a single value or a Column. If the reference in its parent node has its least significant +bit set, then the remaining upper bits specify the row index at which the string is stored. If the bit is clear, +it must be interpreted as a reference to a Column that stores the row indexes at which the string is stored. + +If a Column is used, then all row indexes are guaranteed to be sorted increasingly, which means you an search in it +using our binary search functions such as upper_bound() and lower_bound(). Each duplicate value will be stored in +the same Column, but Columns may contain more than just duplicates if the depth of the tree exceeds the value +`s_max_offset` This is to avoid stack overflow problems with many of our recursive functions if we have two very +long strings that have a long common prefix but differ in the last couple bytes. If a Column stores more than just +duplicates, then the list is kept sorted in ascending order by string value and within the groups of common +strings, the rows are sorted in ascending order. +*/ + +namespace realm { + +class Spec; +class Timestamp; + +class IndexArray : public Array { +public: + IndexArray(Allocator& allocator) + : Array(allocator) + { + } + + size_t index_string_find_first(StringData value, ColumnBase* column) const; + void index_string_find_all(IntegerColumn& result, StringData value, ColumnBase* column, bool case_insensitive = false) const; + FindRes index_string_find_all_no_copy(StringData value, ColumnBase* column, InternalFindResult& result) const; + size_t index_string_count(StringData value, ColumnBase* column) const; + +private: + template + size_t from_list(StringData value, InternalFindResult& result_ref, const IntegerColumn& rows, + ColumnBase* column) const; + + void from_list_all(StringData value, IntegerColumn& result, const IntegerColumn& rows, ColumnBase* column) const; + + void from_list_all_ins(StringData value, std::vector& result, const IntegerColumn& rows, + ColumnBase* column) const; + + template + size_t index_string(StringData value, InternalFindResult& result_ref, ColumnBase* column) const; + + void index_string_all(StringData value, IntegerColumn& result, ColumnBase* column) const; + + void index_string_all_ins(StringData value, IntegerColumn& result, ColumnBase* column) const; +}; + + +class StringIndex { +public: + StringIndex(ColumnBase* target_column, Allocator&); + StringIndex(ref_type, ArrayParent*, size_t ndx_in_parent, ColumnBase* target_column, Allocator&); + ~StringIndex() noexcept + { + } + + static ref_type create_empty(Allocator& alloc); + + void set_target(ColumnBase* target_column) noexcept; + + // Accessor concept: + Allocator& get_alloc() const noexcept; + void destroy() noexcept; + void detach(); + bool is_attached() const noexcept; + void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept; + size_t get_ndx_in_parent() const noexcept; + void set_ndx_in_parent(size_t ndx_in_parent) noexcept; + void update_from_parent(size_t old_baseline) noexcept; + void refresh_accessor_tree(size_t, const Spec&); + ref_type get_ref() const noexcept; + + // StringIndex interface: + + // 12 is the biggest element size of any non-string/binary Realm type + static const size_t string_conversion_buffer_size = 12; + using StringConversionBuffer = std::array; + + bool is_empty() const; + + template + void insert(size_t row_ndx, T value, size_t num_rows, bool is_append); + template + void insert(size_t row_ndx, util::Optional value, size_t num_rows, bool is_append); + + template + void set(size_t row_ndx, T new_value); + template + void set(size_t row_ndx, util::Optional new_value); + + template + void erase(size_t row_ndx, bool is_last); + + template + size_t find_first(T value) const; + template + void find_all(IntegerColumn& result, T value, bool case_insensitive = false) const; + template + FindRes find_all_no_copy(T value, InternalFindResult& result) const; + template + size_t count(T value) const; + template + void update_ref(T value, size_t old_row_ndx, size_t new_row_ndx); + + void clear(); + + void distinct(IntegerColumn& result) const; + bool has_duplicate_values() const noexcept; + + void verify() const; +#ifdef REALM_DEBUG + template + void verify_entries(const T& column) const; + void do_dump_node_structure(std::ostream&, int) const; + void to_dot() const; + void to_dot(std::ostream&, StringData title = StringData()) const; + void to_dot_2(std::ostream&, StringData title = StringData()) const; +#endif + + typedef int32_t key_type; + + // s_max_offset specifies the number of levels of recursive string indexes + // allowed before storing everything in lists. This is to avoid nesting + // to too deep of a level. Since every SubStringIndex stores 4 bytes, this + // means that a StringIndex is helpful for strings of a common prefix up to + // 4 times this limit (200 bytes shared). Lists are stored in sorted order, + // so strings sharing a common prefix of more than this limit will use a + // binary search of approximate complexity log2(n) from `std::lower_bound`. + static const size_t s_max_offset = 200; // max depth * s_index_key_length + static const size_t s_index_key_length = 4; + static key_type create_key(StringData) noexcept; + static key_type create_key(StringData, size_t) noexcept; + +private: + // m_array is a compact representation for storing the children of this StringIndex. + // Children can be: + // 1) a row number + // 2) a reference to a list which stores row numbers (for duplicate strings). + // 3) a reference to a sub-index + // m_array[0] is always a reference to a values array which stores the 4 byte chunk + // of payload data for quick string chunk comparisons. The array stored + // at m_array[0] lines up with the indices of values in m_array[1] so for example + // starting with an empty StringIndex: + // StringColumn::insert(target_row_ndx=42, value="test_string") would result with + // get_array_from_ref(m_array[0])[0] == create_key("test") and + // m_array[1] == 42 + // In this way, m_array which stores one child has a size of two. + // Children are type 1 (row number) if the LSB of the value is set. + // To get the actual row value, shift value down by one. + // If the LSB of the value is 0 then the value is a reference and can be either + // type 2, or type 3 (no shifting in either case). + // References point to a list if the context header flag is NOT set. + // If the header flag is set, references point to a sub-StringIndex (nesting). + std::unique_ptr m_array; + ColumnBase* m_target_column; + + struct inner_node_tag { + }; + StringIndex(inner_node_tag, Allocator&); + + static IndexArray* create_node(Allocator&, bool is_leaf); + + void insert_with_offset(size_t row_ndx, StringData value, size_t offset); + void insert_row_list(size_t ref, size_t offset, StringData value); + void insert_to_existing_list(size_t row, StringData value, IntegerColumn& list); + void insert_to_existing_list_at_lower(size_t row, StringData value, IntegerColumn& list, + const IntegerColumnIterator& lower); + key_type get_last_key() const; + + /// Add small signed \a diff to all elements that are greater than, or equal + /// to \a min_row_ndx. + void adjust_row_indexes(size_t min_row_ndx, int diff); + + struct NodeChange { + size_t ref1; + size_t ref2; + enum ChangeType { none, insert_before, insert_after, split } type; + NodeChange(ChangeType t, size_t r1 = 0, size_t r2 = 0) + : ref1(r1) + , ref2(r2) + , type(t) + { + } + NodeChange() + : ref1(0) + , ref2(0) + , type(none) + { + } + }; + + // B-Tree functions + void TreeInsert(size_t row_ndx, key_type, size_t offset, StringData value); + NodeChange do_insert(size_t ndx, key_type, size_t offset, StringData value); + /// Returns true if there is room or it can join existing entries + bool leaf_insert(size_t row_ndx, key_type, size_t offset, StringData value, bool noextend = false); + void node_insert_split(size_t ndx, size_t new_ref); + void node_insert(size_t ndx, size_t ref); + void do_delete(size_t ndx, StringData, size_t offset); + void do_update_ref(StringData value, size_t row_ndx, size_t new_row_ndx, size_t offset); + + StringData get(size_t ndx, StringConversionBuffer& buffer) const; + + void node_add_key(ref_type ref); + +#ifdef REALM_DEBUG + static void dump_node_structure(const Array& node, std::ostream&, int level); + static void array_to_dot(std::ostream&, const Array&); + static void keys_to_dot(std::ostream&, const Array&, StringData title = StringData()); +#endif +}; + + +class SortedListComparator { +public: + SortedListComparator(ColumnBase& column_values); + bool operator()(int64_t ndx, StringData needle); + bool operator()(StringData needle, int64_t ndx); + +private: + ColumnBase& values; +}; + + +// Implementation: + +template +struct GetIndexData; + +template <> +struct GetIndexData { + static StringData get_index_data(const int64_t& value, StringIndex::StringConversionBuffer& buffer) + { + const char* c = reinterpret_cast(&value); + realm::safe_copy_n(c, sizeof(int64_t), buffer.data()); + return StringData{buffer.data(), sizeof(int64_t)}; + } +}; + +template <> +struct GetIndexData { + static StringData get_index_data(StringData data, StringIndex::StringConversionBuffer&) + { + return data; + } +}; + +template <> +struct GetIndexData { + static StringData get_index_data(null, StringIndex::StringConversionBuffer&) + { + return null{}; + } +}; + +template <> +struct GetIndexData { + static StringData get_index_data(const Timestamp&, StringIndex::StringConversionBuffer&); +}; + +template +struct GetIndexData> { + static StringData get_index_data(const util::Optional& value, StringIndex::StringConversionBuffer& buffer) + { + if (value) + return GetIndexData::get_index_data(*value, buffer); + return null{}; + } +}; + +template <> +struct GetIndexData { + static StringData get_index_data(float, StringIndex::StringConversionBuffer&) + { + REALM_ASSERT_RELEASE(false); // LCOV_EXCL_LINE; Index on float not supported + } +}; + +template <> +struct GetIndexData { + static StringData get_index_data(double, StringIndex::StringConversionBuffer&) + { + REALM_ASSERT_RELEASE(false); // LCOV_EXCL_LINE; Index on float not supported + } +}; + +template <> +struct GetIndexData : GetIndexData { +}; + +// to_str() is used by the integer index. The existing StringIndex is re-used for this +// by making IntegerColumn convert its integers to strings by calling to_str(). + +template +inline StringData to_str(T&& value, StringIndex::StringConversionBuffer& buffer) +{ + return GetIndexData::type>::get_index_data(value, buffer); +} + + +inline StringIndex::StringIndex(ColumnBase* target_column, Allocator& alloc) + : m_array(create_node(alloc, true)) // Throws + , m_target_column(target_column) +{ +} + +inline StringIndex::StringIndex(ref_type ref, ArrayParent* parent, size_t ndx_in_parent, ColumnBase* target_column, + Allocator& alloc) + : m_array(new IndexArray(alloc)) + , m_target_column(target_column) +{ + REALM_ASSERT_EX(Array::get_context_flag_from_header(alloc.translate(ref)), ref, size_t(alloc.translate(ref))); + m_array->init_from_ref(ref); + set_parent(parent, ndx_in_parent); +} + +inline StringIndex::StringIndex(inner_node_tag, Allocator& alloc) + : m_array(create_node(alloc, false)) // Throws + , m_target_column(nullptr) +{ +} + +// Byte order of the key is *reversed*, so that for the integer index, the least significant +// byte comes first, so that it fits little-endian machines. That way we can perform fast +// range-lookups and iterate in order, etc, as future features. This, however, makes the same +// features slower for string indexes. Todo, we should reverse the order conditionally, depending +// on the column type. +inline StringIndex::key_type StringIndex::create_key(StringData str) noexcept +{ + key_type key = 0; + + if (str.size() >= 4) + goto four; + if (str.size() < 2) { + if (str.size() == 0) + goto none; + goto one; + } + if (str.size() == 2) + goto two; + goto three; + +// Create 4 byte index key +// (encoded like this to allow literal comparisons +// independently of endianness) +four: + key |= (key_type(static_cast(str[3])) << 0); +three: + key |= (key_type(static_cast(str[2])) << 8); +two: + key |= (key_type(static_cast(str[1])) << 16); +one: + key |= (key_type(static_cast(str[0])) << 24); +none: + return key; +} + +// Index works as follows: All non-NULL values are stored as if they had appended an 'X' character at the end. So +// "foo" is stored as if it was "fooX", and "" (empty string) is stored as "X". And NULLs are stored as empty strings. +inline StringIndex::key_type StringIndex::create_key(StringData str, size_t offset) noexcept +{ + if (str.is_null()) + return 0; + + if (offset > str.size()) + return 0; + + // for very short strings + size_t tail = str.size() - offset; + if (tail <= sizeof(key_type) - 1) { + char buf[sizeof(key_type)]; + memset(buf, 0, sizeof(key_type)); + buf[tail] = 'X'; + memcpy(buf, str.data() + offset, tail); + return create_key(StringData(buf, tail + 1)); + } + // else fallback + return create_key(str.substr(offset)); +} + +template +void StringIndex::insert(size_t row_ndx, T value, size_t num_rows, bool is_append) +{ + REALM_ASSERT_3(row_ndx, !=, npos); + + // If the new row is inserted after the last row in the table, we don't need + // to adjust any row indexes. + if (!is_append) { + for (size_t i = 0; i < num_rows; ++i) { + size_t row_ndx_2 = row_ndx + i; + adjust_row_indexes(row_ndx_2, 1); // Throws + } + } + + StringConversionBuffer buffer; + + for (size_t i = 0; i < num_rows; ++i) { + size_t row_ndx_2 = row_ndx + i; + size_t offset = 0; // First key from beginning of string + insert_with_offset(row_ndx_2, to_str(value, buffer), offset); // Throws + } +} + +template +void StringIndex::insert(size_t row_ndx, util::Optional value, size_t num_rows, bool is_append) +{ + if (value) { + insert(row_ndx, *value, num_rows, is_append); + } + else { + insert(row_ndx, null{}, num_rows, is_append); + } +} + +template +void StringIndex::set(size_t row_ndx, T new_value) +{ + StringConversionBuffer buffer; + StringConversionBuffer buffer2; + StringData old_value = get(row_ndx, buffer); + StringData new_value2 = to_str(new_value, buffer2); + + // Note that insert_with_offset() throws UniqueConstraintViolation. + + if (REALM_LIKELY(new_value2 != old_value)) { + // We must erase this row first because erase uses find_first which + // might find the duplicate if we insert before erasing. + bool is_last = true; // To avoid updating refs + erase(row_ndx, is_last); // Throws + + size_t offset = 0; // First key from beginning of string + insert_with_offset(row_ndx, new_value2, offset); // Throws + } +} + +template +void StringIndex::set(size_t row_ndx, util::Optional new_value) +{ + if (new_value) { + set(row_ndx, *new_value); + } + else { + set(row_ndx, null{}); + } +} + +template +void StringIndex::erase(size_t row_ndx, bool is_last) +{ + StringConversionBuffer buffer; + StringData value = get(row_ndx, buffer); + + do_delete(row_ndx, value, 0); + + // Collapse top nodes with single item + while (m_array->is_inner_bptree_node()) { + REALM_ASSERT(m_array->size() > 1); // node cannot be empty + if (m_array->size() > 2) + break; + + ref_type ref = m_array->get_as_ref(1); + m_array->set(1, 1); // avoid destruction of the extracted ref + m_array->destroy_deep(); + m_array->init_from_ref(ref); + m_array->update_parent(); + } + + // If it is last item in column, we don't have to update refs + if (!is_last) + adjust_row_indexes(row_ndx, -1); +} + +template +size_t StringIndex::find_first(T value) const +{ + // Use direct access method + StringConversionBuffer buffer; + return m_array->index_string_find_first(to_str(value, buffer), m_target_column); +} + +template +void StringIndex::find_all(IntegerColumn& result, T value, bool case_insensitive) const +{ + // Use direct access method + StringConversionBuffer buffer; + return m_array->index_string_find_all(result, to_str(value, buffer), m_target_column, case_insensitive); +} + +template +FindRes StringIndex::find_all_no_copy(T value, InternalFindResult& result) const +{ + // Use direct access method + StringConversionBuffer buffer; + return m_array->index_string_find_all_no_copy(to_str(value, buffer), m_target_column, result); +} + +template +size_t StringIndex::count(T value) const +{ + // Use direct access method + StringConversionBuffer buffer; + return m_array->index_string_count(to_str(value, buffer), m_target_column); +} + +template +void StringIndex::update_ref(T value, size_t old_row_ndx, size_t new_row_ndx) +{ + StringConversionBuffer buffer; + do_update_ref(to_str(value, buffer), old_row_ndx, new_row_ndx, 0); +} + +inline void StringIndex::destroy() noexcept +{ + return m_array->destroy_deep(); +} + +inline bool StringIndex::is_attached() const noexcept +{ + return m_array->is_attached(); +} + +inline void StringIndex::refresh_accessor_tree(size_t, const Spec&) +{ + m_array->init_from_parent(); +} + +inline ref_type StringIndex::get_ref() const noexcept +{ + return m_array->get_ref(); +} + +inline void StringIndex::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept +{ + m_array->set_parent(parent, ndx_in_parent); +} + +inline size_t StringIndex::get_ndx_in_parent() const noexcept +{ + return m_array->get_ndx_in_parent(); +} + +inline void StringIndex::set_ndx_in_parent(size_t ndx_in_parent) noexcept +{ + m_array->set_ndx_in_parent(ndx_in_parent); +} + +inline void StringIndex::update_from_parent(size_t old_baseline) noexcept +{ + m_array->update_from_parent(old_baseline); +} + +} // namespace realm + +#endif // REALM_INDEX_STRING_HPP diff --git a/Pods/Realm/include/core/realm/lang_bind_helper.hpp b/Pods/Realm/include/core/realm/lang_bind_helper.hpp new file mode 100644 index 0000000000..de287bf7bb --- /dev/null +++ b/Pods/Realm/include/core/realm/lang_bind_helper.hpp @@ -0,0 +1,378 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_LANG_BIND_HELPER_HPP +#define REALM_LANG_BIND_HELPER_HPP + +#include + +#include +#include +#include +#include +#include + +#include + +namespace realm { + + +/// These functions are only to be used by language bindings to gain +/// access to certain memebers that are othewise private. +/// +/// \note Applications are not supposed to call any of these functions +/// directly. +/// +/// All of the get_subtable_ptr() functions bind the table accessor pointer +/// before it is returned (bind_table_ptr()). The caller is then responsible for +/// making the corresponding call to unbind_table_ptr(). +class LangBindHelper { +public: + /// Increment the reference counter of the specified table accessor. This is + /// done automatically by all of the functions in this class that return + /// table accessor pointers, but if the binding/application makes a copy of + /// such a pointer, and the copy needs to have an "independent life", then + /// the binding/application must bind that copy using this function. + static void bind_table_ptr(const Table*) noexcept; + + /// Decrement the reference counter of the specified table accessor. The + /// binding/application must call this function for every bound table + /// accessor pointer object, when that pointer object ends its life. + static void unbind_table_ptr(const Table*) noexcept; + + /// Construct a new freestanding table. The table accessor pointer is bound + /// by the callee before it is returned (bind_table_ptr()). + static Table* new_table(); + + /// Construct a new freestanding table as a copy of the specified one. The + /// table accessor pointer is bound by the callee before it is returned + /// (bind_table_ptr()). + static Table* copy_table(const Table&); + + //@{ + + /// These functions are like their namesakes in Group, but these bypass the + /// construction of a smart-pointer object (TableRef). The table accessor + /// pointer is bound by the callee before it is returned (bind_table_ptr()). + + static Table* get_table(Group&, size_t index_in_group); + static const Table* get_table(const Group&, size_t index_in_group); + + static Table* get_table(Group&, StringData name); + static const Table* get_table(const Group&, StringData name); + + static Table* add_table(Group&, StringData name, bool require_unique_name = true); + static Table* get_or_add_table(Group&, StringData name, bool* was_added = nullptr); + + //@} + + static Table* get_subtable_ptr(Table*, size_t column_ndx, size_t row_ndx); + static const Table* get_subtable_ptr(const Table*, size_t column_ndx, size_t row_ndx); + + // FIXME: This is an 'oddball', do we really need it? If we do, + // please provide a comment that explains why it is needed! + static Table* get_subtable_ptr_during_insert(Table*, size_t col_ndx, size_t row_ndx); + + static Table* get_subtable_ptr(TableView*, size_t column_ndx, size_t row_ndx); + static const Table* get_subtable_ptr(const TableView*, size_t column_ndx, size_t row_ndx); + static const Table* get_subtable_ptr(const ConstTableView*, size_t column_ndx, size_t row_ndx); + + /// Calls parent.set_mixed_subtable(col_ndx, row_ndx, &source). Note + /// that the source table must have a descriptor that is + /// compatible with the target subtable column. + static void set_mixed_subtable(Table& parent, size_t col_ndx, size_t row_ndx, const Table& source); + + static const LinkViewRef& get_linklist_ptr(Row&, size_t col_ndx); + static void unbind_linklist_ptr(const LinkViewRef&); + + using VersionID = SharedGroup::VersionID; + + /// \defgroup lang_bind_helper_transactions Continuous Transactions + /// + /// advance_read() is equivalent to terminating the current read transaction + /// (SharedGroup::end_read()), and initiating a new one + /// (SharedGroup::begin_read()), except that all subordinate accessors + /// (Table, Row, Descriptor) will remain attached to the underlying objects, + /// unless those objects were removed in the target snapshot. By default, + /// the read transaction is advanced to the latest available snapshot, but + /// see SharedGroup::begin_read() for information about \a version. + /// + /// promote_to_write() is equivalent to terminating the current read + /// transaction (SharedGroup::end_read()), and initiating a new write + /// transaction (SharedGroup::begin_write()), except that all subordinate + /// accessors (Table, Row, Descriptor) will remain attached to the + /// underlying objects, unless those objects were removed in the target + /// snapshot. + /// + /// commit_and_continue_as_read() is equivalent to committing the current + /// write transaction (SharedGroup::commit()) and initiating a new read + /// transaction, which is bound to the snapshot produced by the write + /// transaction (SharedGroup::begin_read()), except that all subordinate + /// accessors (Table, Row, Descriptor) will remain attached to the + /// underlying objects. commit_and_continue_as_read() returns the version + /// produced by the committed transaction. + /// + /// rollback_and_continue_as_read() is equivalent to rolling back the + /// current write transaction (SharedGroup::rollback()) and initiating a new + /// read transaction, which is bound to the snapshot, that the write + /// transaction was based on (SharedGroup::begin_read()), except that all + /// subordinate accessors (Table, Row, Descriptor) will remain attached to + /// the underlying objects, unless they were attached to object that were + /// added during the rolled back transaction. + /// + /// If advance_read(), promote_to_write(), commit_and_continue_as_read(), or + /// rollback_and_continue_as_read() throws, the associated group accessor + /// and all of its subordinate accessors are left in a state that may not be + /// fully consistent. Only minimal consistency is guaranteed (see + /// AccessorConsistencyLevels). In this case, the application is required to + /// either destroy the SharedGroup object, forcing all associated accessors + /// to become detached, or take some other equivalent action that involves a + /// complete accessor detachment, such as terminating the transaction in + /// progress. Until then it is an error, and unsafe if the application + /// attempts to access any of those accessors. + /// + /// The application must use SharedGroup::end_read() if it wants to + /// terminate the transaction after advance_read() or promote_to_write() has + /// thrown an exception. Likewise, it must use SharedGroup::rollback() if it + /// wants to terminate the transaction after commit_and_continue_as_read() + /// or rollback_and_continue_as_read() has thrown an exception. + /// + /// \param observer An optional custom replication instruction handler. The + /// application may pass such a handler to observe the sequence of + /// modifications that advances (or rolls back) the state of the Realm. + /// + /// \throw SharedGroup::BadVersion Thrown by advance_read() if the specified + /// version does not correspond to a bound (or tethered) snapshot. + /// + //@{ + + static void advance_read(SharedGroup&, VersionID = VersionID()); + template + static void advance_read(SharedGroup&, O&& observer, VersionID = VersionID()); + static void promote_to_write(SharedGroup&); + template + static void promote_to_write(SharedGroup&, O&& observer); + static SharedGroup::version_type commit_and_continue_as_read(SharedGroup&); + static void rollback_and_continue_as_read(SharedGroup&); + template + static void rollback_and_continue_as_read(SharedGroup&, O&& observer); + + //@} + + /// Returns the name of the specified data type. Examples: + /// + ///
+    ///
+    ///   type_Int          ->  "int"
+    ///   type_Bool         ->  "bool"
+    ///   type_Float        ->  "float"
+    ///   ...
+    ///
+    /// 
+ static const char* get_data_type_name(DataType) noexcept; + + static SharedGroup::version_type get_version_of_latest_snapshot(SharedGroup&); +}; + + +// Implementation: + +inline Table* LangBindHelper::new_table() +{ + typedef _impl::TableFriend tf; + Allocator& alloc = Allocator::get_default(); + size_t ref = tf::create_empty_table(alloc); // Throws + Table::Parent* parent = nullptr; + size_t ndx_in_parent = 0; + Table* table = tf::create_accessor(alloc, ref, parent, ndx_in_parent); // Throws + bind_table_ptr(table); + return table; +} + +inline Table* LangBindHelper::copy_table(const Table& table) +{ + typedef _impl::TableFriend tf; + Allocator& alloc = Allocator::get_default(); + size_t ref = tf::clone(table, alloc); // Throws + Table::Parent* parent = nullptr; + size_t ndx_in_parent = 0; + Table* copy_of_table = tf::create_accessor(alloc, ref, parent, ndx_in_parent); // Throws + bind_table_ptr(copy_of_table); + return copy_of_table; +} + +inline Table* LangBindHelper::get_subtable_ptr(Table* t, size_t column_ndx, size_t row_ndx) +{ + TableRef subtab = t->get_subtable_tableref(column_ndx, row_ndx); // Throws + return subtab.release(); +} + +inline const Table* LangBindHelper::get_subtable_ptr(const Table* t, size_t column_ndx, size_t row_ndx) +{ + ConstTableRef subtab = t->get_subtable_tableref(column_ndx, row_ndx); // Throws + return subtab.release(); +} + +inline Table* LangBindHelper::get_subtable_ptr(TableView* tv, size_t column_ndx, size_t row_ndx) +{ + return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); +} + +inline const Table* LangBindHelper::get_subtable_ptr(const TableView* tv, size_t column_ndx, size_t row_ndx) +{ + return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); +} + +inline const Table* LangBindHelper::get_subtable_ptr(const ConstTableView* tv, size_t column_ndx, size_t row_ndx) +{ + return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); +} + +inline Table* LangBindHelper::get_table(Group& group, size_t index_in_group) +{ + typedef _impl::GroupFriend gf; + Table* table = &gf::get_table(group, index_in_group); // Throws + table->bind_ptr(); + return table; +} + +inline const Table* LangBindHelper::get_table(const Group& group, size_t index_in_group) +{ + typedef _impl::GroupFriend gf; + const Table* table = &gf::get_table(group, index_in_group); // Throws + table->bind_ptr(); + return table; +} + +inline Table* LangBindHelper::get_table(Group& group, StringData name) +{ + typedef _impl::GroupFriend gf; + Table* table = gf::get_table(group, name); // Throws + if (table) + table->bind_ptr(); + return table; +} + +inline const Table* LangBindHelper::get_table(const Group& group, StringData name) +{ + typedef _impl::GroupFriend gf; + const Table* table = gf::get_table(group, name); // Throws + if (table) + table->bind_ptr(); + return table; +} + +inline Table* LangBindHelper::add_table(Group& group, StringData name, bool require_unique_name) +{ + typedef _impl::GroupFriend gf; + Table* table = &gf::add_table(group, name, require_unique_name); // Throws + table->bind_ptr(); + return table; +} + +inline Table* LangBindHelper::get_or_add_table(Group& group, StringData name, bool* was_added) +{ + typedef _impl::GroupFriend gf; + Table* table = &gf::get_or_add_table(group, name, was_added); // Throws + table->bind_ptr(); + return table; +} + +inline void LangBindHelper::unbind_table_ptr(const Table* t) noexcept +{ + t->unbind_ptr(); +} + +inline void LangBindHelper::bind_table_ptr(const Table* t) noexcept +{ + t->bind_ptr(); +} + +inline void LangBindHelper::set_mixed_subtable(Table& parent, size_t col_ndx, size_t row_ndx, const Table& source) +{ + parent.set_mixed_subtable(col_ndx, row_ndx, &source); +} + +inline const LinkViewRef& LangBindHelper::get_linklist_ptr(Row& row, size_t col_ndx) +{ + LinkViewRef* link_view = new LinkViewRef(row.get_linklist(col_ndx)); + return *link_view; +} + +inline void LangBindHelper::unbind_linklist_ptr(const LinkViewRef& link_view) +{ + delete (&link_view); +} + +inline void LangBindHelper::advance_read(SharedGroup& sg, VersionID version) +{ + using sgf = _impl::SharedGroupFriend; + _impl::NullInstructionObserver* observer = nullptr; + sgf::advance_read(sg, observer, version); // Throws +} + +template +inline void LangBindHelper::advance_read(SharedGroup& sg, O&& observer, VersionID version) +{ + using sgf = _impl::SharedGroupFriend; + sgf::advance_read(sg, &observer, version); // Throws +} + +inline void LangBindHelper::promote_to_write(SharedGroup& sg) +{ + using sgf = _impl::SharedGroupFriend; + _impl::NullInstructionObserver* observer = nullptr; + sgf::promote_to_write(sg, observer); // Throws +} + +template +inline void LangBindHelper::promote_to_write(SharedGroup& sg, O&& observer) +{ + using sgf = _impl::SharedGroupFriend; + sgf::promote_to_write(sg, &observer); // Throws +} + +inline SharedGroup::version_type LangBindHelper::commit_and_continue_as_read(SharedGroup& sg) +{ + using sgf = _impl::SharedGroupFriend; + return sgf::commit_and_continue_as_read(sg); // Throws +} + +inline void LangBindHelper::rollback_and_continue_as_read(SharedGroup& sg) +{ + using sgf = _impl::SharedGroupFriend; + _impl::NullInstructionObserver* observer = nullptr; + sgf::rollback_and_continue_as_read(sg, observer); // Throws +} + +template +inline void LangBindHelper::rollback_and_continue_as_read(SharedGroup& sg, O&& observer) +{ + using sgf = _impl::SharedGroupFriend; + sgf::rollback_and_continue_as_read(sg, &observer); // Throws +} + +inline SharedGroup::version_type LangBindHelper::get_version_of_latest_snapshot(SharedGroup& sg) +{ + using sgf = _impl::SharedGroupFriend; + return sgf::get_version_of_latest_snapshot(sg); // Throws +} + +} // namespace realm + +#endif // REALM_LANG_BIND_HELPER_HPP diff --git a/Pods/Realm/include/core/realm/link_view.hpp b/Pods/Realm/include/core/realm/link_view.hpp new file mode 100644 index 0000000000..14be525b92 --- /dev/null +++ b/Pods/Realm/include/core/realm/link_view.hpp @@ -0,0 +1,397 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_LINK_VIEW_HPP +#define REALM_LINK_VIEW_HPP + +#include +#include +#include +#include + +namespace realm { + +class LinkListColumn; + +namespace _impl { +class LinkListFriend; +class TransactLogConvenientEncoder; +} + + +/// The effect of calling most of the link list functions on a detached accessor +/// is unspecified and may lead to general corruption, or even a crash. The +/// exceptions are is_attached() and the destructor. +/// +/// FIXME: Rename this class to `LinkList`. +class LinkView : public RowIndexes, public std::enable_shared_from_this { +public: + ~LinkView() noexcept; + bool is_attached() const noexcept; + + /// This method will return true if the LinkView is detached (no assert). + bool is_empty() const noexcept; + + /// This method will return 0 if the LinkView is detached (no assert). + size_t size() const noexcept override; + + bool operator==(const LinkView&) const noexcept; + bool operator!=(const LinkView&) const noexcept; + + // Getting links + Table::ConstRowExpr operator[](size_t link_ndx) const noexcept; + Table::RowExpr operator[](size_t link_ndx) noexcept; + Table::ConstRowExpr get(size_t link_ndx) const noexcept; + Table::RowExpr get(size_t link_ndx) noexcept; + + // Modifiers + void add(size_t target_row_ndx); + void insert(size_t link_ndx, size_t target_row_ndx); + void set(size_t link_ndx, size_t target_row_ndx); + /// Move the link at \a from_ndx such that it ends up at \a to_ndx. Other + /// links are shifted as necessary in such a way that their order is + /// preserved. + /// + /// Note that \a to_ndx is the desired final index of the moved link, + /// therefore, `move(1,1)` is a no-op, while `move(1,2)` moves the link at + /// index 1 by one position, such that it ends up at index 2. A side-effect + /// of that, is that the link, that was originally at index 2, is moved to + /// index 1. + void move(size_t from_ndx, size_t to_ndx); + void swap(size_t link1_ndx, size_t link2_ndx); + void remove(size_t link_ndx); + void clear(); + + void sort(size_t column, bool ascending = true); + void sort(SortDescriptor&& order); + + TableView get_sorted_view(size_t column_index, bool ascending = true) const; + TableView get_sorted_view(SortDescriptor order) const; + + /// Remove the target row of the specified link from the target table. This + /// also removes the specified link from this link list, and any other link + /// pointing to that row. This is merely a shorthand for + /// `get_target_table.move_last_over(get(link_ndx))`. + void remove_target_row(size_t link_ndx); + + /// Remove all target rows pointed to by links in this link list, and clear + /// this link list. + void remove_all_target_rows(); + + /// Search this list for a link to the specified target table row (specified + /// by its index in the target table). If found, the index of the link to + /// that row within this list is returned, otherwise `realm::not_found` is + /// returned. + size_t find(size_t target_row_ndx, size_t start = 0) const noexcept; + + const ColumnBase& get_column_base(size_t index) + const override; // FIXME: `ColumnBase` is not part of the public API, so this function must be made private. + const Table& get_origin_table() const noexcept; + Table& get_origin_table() noexcept; + + size_t get_origin_row_index() const noexcept; + + const Table& get_target_table() const noexcept; + Table& get_target_table() noexcept; + + // No-op because LinkViews are always kept in sync. + uint_fast64_t sync_if_needed() const override; + bool is_in_sync() const override + { + return true; + } + +private: + struct ctor_cookie { + }; + + TableRef m_origin_table; + LinkListColumn* m_origin_column; + + using HandoverPatch = LinkViewHandoverPatch; + static void generate_patch(const ConstLinkViewRef& ref, std::unique_ptr& patch); + static LinkViewRef create_from_and_consume_patch(std::unique_ptr& patch, Group& group); + + void detach(); + void set_origin_row_index(size_t row_ndx) noexcept; + + void do_insert(size_t link_ndx, size_t target_row_ndx); + size_t do_set(size_t link_ndx, size_t target_row_ndx); + size_t do_remove(size_t link_ndx); + void do_clear(bool broken_reciprocal_backlinks); + + void do_nullify_link(size_t old_target_row_ndx); + void do_update_link(size_t old_target_row_ndx, size_t new_target_row_ndx); + void do_swap_link(size_t target_row_ndx_1, size_t target_row_ndx_2); + + void refresh_accessor_tree(size_t new_row_ndx) noexcept; + + void update_from_parent(size_t old_baseline) noexcept; + + Replication* get_repl() noexcept; + void repl_unselect() noexcept; + friend class _impl::TransactLogConvenientEncoder; + +#ifdef REALM_DEBUG + void verify(size_t row_ndx) const; +#endif + // allocate using make_shared: + static std::shared_ptr create(Table* origin_table, LinkListColumn&, size_t row_ndx); + static std::shared_ptr create_detached(); + + friend class _impl::LinkListFriend; + friend class LinkListColumn; + friend class LangBindHelper; + friend class SharedGroup; + friend class Query; + friend class TableViewBase; + + // must be public for use by make_shared, but cannot be called from outside, + // because ctor_cookie is private +public: + LinkView(const ctor_cookie&, Table* origin_table, LinkListColumn&, size_t row_ndx); + LinkView(const ctor_cookie&); +}; + + +// Implementation + +inline LinkView::LinkView(const ctor_cookie&, Table* origin_table, LinkListColumn& column, size_t row_ndx) + : RowIndexes(IntegerColumn::unattached_root_tag(), column.get_alloc()) // Throws + , m_origin_table(origin_table->get_table_ref()) + , m_origin_column(&column) +{ + m_row_indexes.set_parent(m_origin_column, row_ndx); + m_row_indexes.init_from_parent(); +} + +// create a detached LinkView. Only partially initialized, as it will never be used for +// anything, but indicating that it is detached. +inline LinkView::LinkView(const ctor_cookie&) + : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) // Throws + , m_origin_table(TableRef()) + , m_origin_column(nullptr) +{ +} + +inline std::shared_ptr LinkView::create(Table* origin_table, LinkListColumn& column, size_t row_ndx) +{ + return std::make_shared(ctor_cookie(), origin_table, column, row_ndx); +} + +inline std::shared_ptr LinkView::create_detached() +{ + return std::make_shared(ctor_cookie()); +} + +inline LinkView::~LinkView() noexcept +{ + if (is_attached()) { + repl_unselect(); + m_origin_column->unregister_linkview(); + } +} + +inline void LinkView::detach() +{ + REALM_ASSERT(is_attached()); + repl_unselect(); + m_origin_table.reset(); + m_row_indexes.detach(); +} + +inline bool LinkView::is_attached() const noexcept +{ + return static_cast(m_origin_table); +} + +inline bool LinkView::is_empty() const noexcept +{ + if (!is_attached()) + return true; + + if (!m_row_indexes.is_attached()) + return true; + + return m_row_indexes.is_empty(); +} + +inline size_t LinkView::size() const noexcept +{ + if (!is_attached()) + return 0; + + if (!m_row_indexes.is_attached()) + return 0; + + return m_row_indexes.size(); +} + +inline bool LinkView::operator==(const LinkView& link_list) const noexcept +{ + Table& target_table_1 = m_origin_column->get_target_table(); + Table& target_table_2 = link_list.m_origin_column->get_target_table(); + if (target_table_1.get_index_in_group() != target_table_2.get_index_in_group()) + return false; + if (!m_row_indexes.is_attached() || m_row_indexes.is_empty()) { + return !link_list.m_row_indexes.is_attached() || link_list.m_row_indexes.is_empty(); + } + return link_list.m_row_indexes.is_attached() && m_row_indexes.compare(link_list.m_row_indexes); +} + +inline bool LinkView::operator!=(const LinkView& link_list) const noexcept +{ + return !(*this == link_list); +} + +inline Table::ConstRowExpr LinkView::get(size_t link_ndx) const noexcept +{ + return const_cast(this)->get(link_ndx); +} + +inline Table::RowExpr LinkView::get(size_t link_ndx) noexcept +{ + REALM_ASSERT(is_attached()); + REALM_ASSERT(m_row_indexes.is_attached()); + REALM_ASSERT_3(link_ndx, <, m_row_indexes.size()); + + Table& target_table = m_origin_column->get_target_table(); + size_t target_row_ndx = to_size_t(m_row_indexes.get(link_ndx)); + return target_table[target_row_ndx]; +} + +inline Table::ConstRowExpr LinkView::operator[](size_t link_ndx) const noexcept +{ + return get(link_ndx); +} + +inline Table::RowExpr LinkView::operator[](size_t link_ndx) noexcept +{ + return get(link_ndx); +} + +inline void LinkView::add(size_t target_row_ndx) +{ + REALM_ASSERT(is_attached()); + size_t ins_pos = (m_row_indexes.is_attached()) ? m_row_indexes.size() : 0; + insert(ins_pos, target_row_ndx); +} + +inline size_t LinkView::find(size_t target_row_ndx, size_t start) const noexcept +{ + REALM_ASSERT(is_attached()); + REALM_ASSERT_3(target_row_ndx, <, m_origin_column->get_target_table().size()); + REALM_ASSERT_3(start, <=, size()); + + if (!m_row_indexes.is_attached()) + return not_found; + + return m_row_indexes.find_first(target_row_ndx, start); +} + +inline const ColumnBase& LinkView::get_column_base(size_t index) const +{ + return get_target_table().get_column_base(index); +} + +inline const Table& LinkView::get_origin_table() const noexcept +{ + return *m_origin_table; +} + +inline Table& LinkView::get_origin_table() noexcept +{ + return *m_origin_table; +} + +inline size_t LinkView::get_origin_row_index() const noexcept +{ + REALM_ASSERT(is_attached()); + return m_row_indexes.get_root_array()->get_ndx_in_parent(); +} + +inline void LinkView::set_origin_row_index(size_t row_ndx) noexcept +{ + REALM_ASSERT(is_attached()); + m_row_indexes.get_root_array()->set_ndx_in_parent(row_ndx); +} + +inline const Table& LinkView::get_target_table() const noexcept +{ + return m_origin_column->get_target_table(); +} + +inline Table& LinkView::get_target_table() noexcept +{ + return m_origin_column->get_target_table(); +} + +inline void LinkView::refresh_accessor_tree(size_t new_row_ndx) noexcept +{ + set_origin_row_index(new_row_ndx); + m_row_indexes.init_from_parent(); +} + +inline void LinkView::update_from_parent(size_t old_baseline) noexcept +{ + if (m_row_indexes.is_attached()) + m_row_indexes.update_from_parent(old_baseline); +} + +inline Replication* LinkView::get_repl() noexcept +{ + typedef _impl::TableFriend tf; + return tf::get_repl(*m_origin_table); +} + + +// The purpose of this class is to give internal access to some, but not all of +// the non-public parts of LinkView. +class _impl::LinkListFriend { +public: + static void do_set(LinkView& list, size_t link_ndx, size_t target_row_ndx) + { + list.do_set(link_ndx, target_row_ndx); + } + + static void do_remove(LinkView& list, size_t link_ndx) + { + list.do_remove(link_ndx); + } + + static void do_clear(LinkView& list) + { + bool broken_reciprocal_backlinks = false; + list.do_clear(broken_reciprocal_backlinks); + } + + static void do_insert(LinkView& list, size_t link_ndx, size_t target_row_ndx) + { + list.do_insert(link_ndx, target_row_ndx); + } + + static const LinkListColumn& get_origin_column(const LinkView& list) + { + REALM_ASSERT(list.is_attached()); + return *list.m_origin_column; + } +}; + +} // namespace realm + +#endif // REALM_LINK_VIEW_HPP diff --git a/Pods/Realm/include/core/realm/link_view_fwd.hpp b/Pods/Realm/include/core/realm/link_view_fwd.hpp new file mode 100644 index 0000000000..cba8801e6c --- /dev/null +++ b/Pods/Realm/include/core/realm/link_view_fwd.hpp @@ -0,0 +1,32 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_LINK_VIEW_FWD_HPP +#define REALM_LINK_VIEW_FWD_HPP + +#include + +namespace realm { + +class LinkView; +using LinkViewRef = std::shared_ptr; +using ConstLinkViewRef = std::shared_ptr; + +} // namespace realm + +#endif // REALM_LINK_VIEW_FWD_HPP diff --git a/Pods/Realm/include/core/realm/metrics/metric_timer.hpp b/Pods/Realm/include/core/realm/metrics/metric_timer.hpp new file mode 100644 index 0000000000..505a23c1b3 --- /dev/null +++ b/Pods/Realm/include/core/realm/metrics/metric_timer.hpp @@ -0,0 +1,103 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_METRIC_TIMER_HPP +#define REALM_METRIC_TIMER_HPP + +#include + +#include +#include +#include + +#if REALM_METRICS + +namespace realm { +namespace metrics { + + +class MetricTimerResult +{ +public: + MetricTimerResult(); + ~MetricTimerResult(); + double get_elapsed_seconds() const; + void report_seconds(double time); +protected: + double m_elapsed_seconds; +}; + + +class MetricTimer { +public: + MetricTimer(std::shared_ptr destination = nullptr); + ~MetricTimer(); + + void reset(); + + /// Returns elapsed time in seconds since last call to reset(). + double get_elapsed_time() const; + /// Same as get_elapsed_time(). + operator double() const; + + /// Format the elapsed time on the form 0h00m, 00m00s, 00.00s, or + /// 000.0ms depending on magnitude. + static void format(double seconds, std::ostream&); + + static std::string format(double seconds); + +private: + using clock_type = std::chrono::high_resolution_clock; + using time_point = std::chrono::time_point; + time_point m_start; + time_point m_paused_at; + std::shared_ptr m_dest; + + time_point get_timer_ticks() const; + double calc_elapsed_seconds(time_point begin, time_point end) const; +}; + + +inline void MetricTimer::reset() +{ + m_start = get_timer_ticks(); +} + +inline double MetricTimer::get_elapsed_time() const +{ + return calc_elapsed_seconds(m_start, get_timer_ticks()); +} + +inline MetricTimer::operator double() const +{ + return get_elapsed_time(); +} + +inline std::ostream& operator<<(std::ostream& out, const MetricTimer& timer) +{ + MetricTimer::format(timer, out); + return out; +} + + +} // namespace metrics +} // namespace realm + +#endif // REALM_METRICS + +#endif // REALM_METRIC_TIMER_HPP diff --git a/Pods/Realm/include/core/realm/metrics/metrics.hpp b/Pods/Realm/include/core/realm/metrics/metrics.hpp new file mode 100644 index 0000000000..73e8d59630 --- /dev/null +++ b/Pods/Realm/include/core/realm/metrics/metrics.hpp @@ -0,0 +1,82 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_METRICS_HPP +#define REALM_METRICS_HPP + +#include +#include + +#include +#include +#include + +namespace realm { + +class Group; + +namespace metrics { + +#if REALM_METRICS + +class Metrics { +public: + Metrics(); + ~Metrics() noexcept; + size_t num_query_metrics() const; + size_t num_transaction_metrics() const; + + void add_query(QueryInfo info); + void add_transaction(TransactionInfo info); + + void start_read_transaction(); + void start_write_transaction(); + void end_read_transaction(size_t total_size, size_t free_space, size_t num_objects, size_t num_versions); + void end_write_transaction(size_t total_size, size_t free_space, size_t num_objects, size_t num_versions); + static std::unique_ptr report_fsync_time(const Group& g); + static std::unique_ptr report_write_time(const Group& g); + + using QueryInfoList = std::vector; + using TransactionInfoList = std::vector; + + // Get the list of metric objects tracked since the last take + std::unique_ptr take_queries(); + std::unique_ptr take_transactions(); +private: + std::unique_ptr m_query_info; + std::unique_ptr m_transaction_info; + + std::unique_ptr m_pending_read; + std::unique_ptr m_pending_write; +}; + + +#else + +class Metrics +{ +}; + +#endif // REALM_METRICS + +} // namespace metrics +} // namespace realm + + + +#endif // REALM_METRICS_HPP diff --git a/Pods/Realm/include/core/realm/metrics/query_info.hpp b/Pods/Realm/include/core/realm/metrics/query_info.hpp new file mode 100644 index 0000000000..020eaa5e6b --- /dev/null +++ b/Pods/Realm/include/core/realm/metrics/query_info.hpp @@ -0,0 +1,72 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_QUERY_INFO_HPP +#define REALM_QUERY_INFO_HPP + +#include +#include +#include + +#include +#include +#include + +#if REALM_METRICS + +namespace realm { + +class Query; // forward declare in namespace realm + +namespace metrics { + +class QueryInfo { +public: + + enum QueryType { + type_Find, + type_FindAll, + type_Count, + type_Sum, + type_Average, + type_Maximum, + type_Minimum, + type_Invalid + }; + + QueryInfo(const Query* query, QueryType type); + ~QueryInfo() noexcept; + + std::string get_description() const; + QueryType get_type() const; + double get_query_time() const; + + static std::unique_ptr track(const Query* query, QueryType type); + static QueryType type_from_action(Action action); + +private: + std::string m_description; + QueryType m_type; + std::shared_ptr m_query_time; +}; + +} // namespace metrics +} // namespace realm + +#endif // REALM_METRICS +#endif // REALM_QUERY_INFO_HPP diff --git a/Pods/Realm/include/core/realm/metrics/transaction_info.hpp b/Pods/Realm/include/core/realm/metrics/transaction_info.hpp new file mode 100644 index 0000000000..c647e34827 --- /dev/null +++ b/Pods/Realm/include/core/realm/metrics/transaction_info.hpp @@ -0,0 +1,77 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_TRANSACTION_INFO_HPP +#define REALM_TRANSACTION_INFO_HPP + +#include +#include + +#include +#include + +#if REALM_METRICS + +namespace realm { +namespace metrics { + +class Metrics; + +class TransactionInfo { +public: + enum TransactionType { + read_transaction, + write_transaction + }; + TransactionInfo(TransactionType type); + TransactionInfo(const TransactionInfo&) = default; + ~TransactionInfo() noexcept; + + TransactionType get_transaction_type() const; + // the transaction time is a total amount which includes fsync_time + write_time + user_time + double get_transaction_time() const; + double get_fsync_time() const; + double get_write_time() const; + size_t get_disk_size() const; + size_t get_free_space() const; + size_t get_total_objects() const; + size_t get_num_available_versions() const; + +private: + MetricTimerResult m_transaction_time; + std::shared_ptr m_fsync_time; + std::shared_ptr m_write_time; + MetricTimer m_transact_timer; + + size_t m_realm_disk_size; + size_t m_realm_free_space; + size_t m_total_objects; + TransactionType m_type; + size_t m_num_versions; + + friend class Metrics; + void update_stats(size_t disk_size, size_t free_space, size_t total_objects, size_t available_versions); + void finish_timer(); +}; + +} // namespace metrics +} // namespace realm + +#endif // REALM_METRICS + +#endif // REALM_TRANSACTION_INFO_HPP diff --git a/Pods/Realm/include/core/realm/mixed.hpp b/Pods/Realm/include/core/realm/mixed.hpp new file mode 100644 index 0000000000..f50f4a0d16 --- /dev/null +++ b/Pods/Realm/include/core/realm/mixed.hpp @@ -0,0 +1,680 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_MIXED_HPP +#define REALM_MIXED_HPP + +#include // int64_t - not part of C++03, not even required by C++11 (see C++11 section 18.4.1) + +#include // size_t +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace realm { + + +/// This class represents a polymorphic Realm value. +/// +/// At any particular moment an instance of this class stores a +/// definite value of a definite type. If, for instance, that is an +/// integer value, you may call get_int() to extract that value. You +/// may call get_type() to discover what type of value is currently +/// stored. Calling get_int() on an instance that does not store an +/// integer, has undefined behavior, and likewise for all the other +/// types that can be stored. +/// +/// It is crucial to understand that the act of extracting a value of +/// a particular type requires definite knowledge about the stored +/// type. Calling a getter method for any particular type, that is not +/// the same type as the stored value, has undefined behavior. +/// +/// While values of numeric types are contained directly in a Mixed +/// instance, character and binary data are merely referenced. A Mixed +/// instance never owns the referenced data, nor does it in any other +/// way attempt to manage its lifetime. +/// +/// For compatibility with C style strings, when a string (character +/// data) is stored in a Realm database, it is always followed by a +/// terminating null character. This is also true when strings are +/// stored in a mixed type column. This means that in the following +/// code, if the 'mixed' value of the 8th row stores a string, then \c +/// c_str will always point to a null-terminated string: +/// +/// \code{.cpp} +/// +/// const char* c_str = my_table[7].mixed.data(); // Always null-terminated +/// +/// \endcode +/// +/// Note that this assumption does not hold in general for strings in +/// instances of Mixed. Indeed there is nothing stopping you from +/// constructing a new Mixed instance that refers to a string without +/// a terminating null character. +/// +/// At the present time no soultion has been found that would allow +/// for a Mixed instance to directly store a reference to a table. The +/// problem is roughly as follows: From most points of view, the +/// desirable thing to do, would be to store the table reference in a +/// Mixed instance as a plain pointer without any ownership +/// semantics. This would have no negative impact on the performance +/// of copying and destroying Mixed instances, and it would serve just +/// fine for passing a table as argument when setting the value of an +/// entry in a mixed column. In that case a copy of the referenced +/// table would be inserted into the mixed column. +/// +/// On the other hand, when retrieving a table reference from a mixed +/// column, storing it as a plain pointer in a Mixed instance is no +/// longer an acceptable option. The complex rules for managing the +/// lifetime of a Table instance, that represents a subtable, +/// necessitates the use of a "smart pointer" such as +/// TableRef. Enhancing the Mixed class to be able to act as a +/// TableRef would be possible, but would also lead to several new +/// problems. One problem is the risk of a Mixed instance outliving a +/// stack allocated Table instance that it references. This would be a +/// fatal error. Another problem is the impact that the nontrivial +/// table reference has on the performance of copying and destroying +/// Mixed instances. +/// +/// \sa StringData +class Mixed { +public: + Mixed() noexcept; + + Mixed(bool) noexcept; + Mixed(int64_t) noexcept; + Mixed(float) noexcept; + Mixed(double) noexcept; + Mixed(StringData) noexcept; + Mixed(BinaryData) noexcept; + Mixed(OldDateTime) noexcept; + Mixed(Timestamp) noexcept; + + // These are shortcuts for Mixed(StringData(c_str)), and are + // needed to avoid unwanted implicit conversion of char* to bool. + Mixed(char* c_str) noexcept + { + set_string(c_str); + } + Mixed(const char* c_str) noexcept + { + set_string(c_str); + } + + struct subtable_tag { + }; + Mixed(subtable_tag) noexcept + : m_type(type_Table) + { + } + + ~Mixed() noexcept + { + } + + DataType get_type() const noexcept + { + return m_type; + } + + int64_t get_int() const noexcept; + bool get_bool() const noexcept; + float get_float() const noexcept; + double get_double() const noexcept; + StringData get_string() const noexcept; + BinaryData get_binary() const noexcept; + OldDateTime get_olddatetime() const noexcept; + Timestamp get_timestamp() const noexcept; + + void set_int(int64_t) noexcept; + void set_bool(bool) noexcept; + void set_float(float) noexcept; + void set_double(double) noexcept; + void set_string(StringData) noexcept; + void set_binary(BinaryData) noexcept; + void set_binary(const char* data, size_t size) noexcept; + void set_olddatetime(OldDateTime) noexcept; + void set_timestamp(Timestamp) noexcept; + + template + friend std::basic_ostream& operator<<(std::basic_ostream&, const Mixed&); + +private: + DataType m_type; + union { + int64_t m_int; + bool m_bool; + float m_float; + double m_double; + const char* m_data; + int_fast64_t m_date; + Timestamp m_timestamp; + }; + size_t m_size = 0; +}; + +// Note: We cannot compare two mixed values, since when the type of +// both is type_Table, we would have to compare the two tables, but +// the mixed values do not provide access to those tables. + +// Note: The mixed values are specified as Wrap. If they were +// not, these operators would apply to simple comparisons, such as int +// vs int64_t, and cause ambiguity. This is because the constructors +// of Mixed are not explicit. + +// Compare mixed with integer +template +bool operator==(Wrap, const T&) noexcept; +template +bool operator!=(Wrap, const T&) noexcept; +template +bool operator==(const T&, Wrap) noexcept; +template +bool operator!=(const T&, Wrap) noexcept; + +// Compare mixed with boolean +bool operator==(Wrap, bool) noexcept; +bool operator!=(Wrap, bool) noexcept; +bool operator==(bool, Wrap) noexcept; +bool operator!=(bool, Wrap) noexcept; + +// Compare mixed with float +bool operator==(Wrap, float); +bool operator!=(Wrap, float); +bool operator==(float, Wrap); +bool operator!=(float, Wrap); + +// Compare mixed with double +bool operator==(Wrap, double); +bool operator!=(Wrap, double); +bool operator==(double, Wrap); +bool operator!=(double, Wrap); + +// Compare mixed with string +bool operator==(Wrap, StringData) noexcept; +bool operator!=(Wrap, StringData) noexcept; +bool operator==(StringData, Wrap) noexcept; +bool operator!=(StringData, Wrap) noexcept; +bool operator==(Wrap, const char* c_str) noexcept; +bool operator!=(Wrap, const char* c_str) noexcept; +bool operator==(const char* c_str, Wrap) noexcept; +bool operator!=(const char* c_str, Wrap) noexcept; +bool operator==(Wrap, char* c_str) noexcept; +bool operator!=(Wrap, char* c_str) noexcept; +bool operator==(char* c_str, Wrap) noexcept; +bool operator!=(char* c_str, Wrap) noexcept; + +// Compare mixed with binary data +bool operator==(Wrap, BinaryData) noexcept; +bool operator!=(Wrap, BinaryData) noexcept; +bool operator==(BinaryData, Wrap) noexcept; +bool operator!=(BinaryData, Wrap) noexcept; + +// Compare mixed with date +bool operator==(Wrap, OldDateTime) noexcept; +bool operator!=(Wrap, OldDateTime) noexcept; +bool operator==(OldDateTime, Wrap) noexcept; +bool operator!=(OldDateTime, Wrap) noexcept; + +// Compare mixed with Timestamp +bool operator==(Wrap, Timestamp) noexcept; +bool operator!=(Wrap, Timestamp) noexcept; +bool operator==(Timestamp, Wrap) noexcept; +bool operator!=(Timestamp, Wrap) noexcept; + +// Implementation: + +inline Mixed::Mixed() noexcept +{ + m_type = type_Int; + m_int = 0; +} + +inline Mixed::Mixed(int64_t v) noexcept +{ + m_type = type_Int; + m_int = v; +} + +inline Mixed::Mixed(bool v) noexcept +{ + m_type = type_Bool; + m_bool = v; +} + +inline Mixed::Mixed(float v) noexcept +{ + m_type = type_Float; + m_float = v; +} + +inline Mixed::Mixed(double v) noexcept +{ + m_type = type_Double; + m_double = v; +} + +inline Mixed::Mixed(StringData v) noexcept +{ + m_type = type_String; + m_data = v.data(); + m_size = v.size(); +} + +inline Mixed::Mixed(BinaryData v) noexcept +{ + m_type = type_Binary; + m_data = v.data(); + m_size = v.size(); +} + +inline Mixed::Mixed(OldDateTime v) noexcept +{ + m_type = type_OldDateTime; + m_date = v.get_olddatetime(); +} + +inline Mixed::Mixed(Timestamp v) noexcept +{ + m_type = type_Timestamp; + m_timestamp = v; +} + +inline int64_t Mixed::get_int() const noexcept +{ + REALM_ASSERT(m_type == type_Int); + return m_int; +} + +inline bool Mixed::get_bool() const noexcept +{ + REALM_ASSERT(m_type == type_Bool); + return m_bool; +} + +inline float Mixed::get_float() const noexcept +{ + REALM_ASSERT(m_type == type_Float); + return m_float; +} + +inline double Mixed::get_double() const noexcept +{ + REALM_ASSERT(m_type == type_Double); + return m_double; +} + +inline StringData Mixed::get_string() const noexcept +{ + REALM_ASSERT(m_type == type_String); + return StringData(m_data, m_size); +} + +inline BinaryData Mixed::get_binary() const noexcept +{ + REALM_ASSERT(m_type == type_Binary); + return BinaryData(m_data, m_size); +} + +inline OldDateTime Mixed::get_olddatetime() const noexcept +{ + REALM_ASSERT(m_type == type_OldDateTime); + return m_date; +} + +inline Timestamp Mixed::get_timestamp() const noexcept +{ + REALM_ASSERT(m_type == type_Timestamp); + return m_timestamp; +} + +inline void Mixed::set_int(int64_t v) noexcept +{ + m_type = type_Int; + m_int = v; +} + +inline void Mixed::set_bool(bool v) noexcept +{ + m_type = type_Bool; + m_bool = v; +} + +inline void Mixed::set_float(float v) noexcept +{ + m_type = type_Float; + m_float = v; +} + +inline void Mixed::set_double(double v) noexcept +{ + m_type = type_Double; + m_double = v; +} + +inline void Mixed::set_string(StringData v) noexcept +{ + m_type = type_String; + m_data = v.data(); + m_size = v.size(); +} + +inline void Mixed::set_binary(BinaryData v) noexcept +{ + set_binary(v.data(), v.size()); +} + +inline void Mixed::set_binary(const char* data, size_t size) noexcept +{ + m_type = type_Binary; + m_data = data; + m_size = size; +} + +inline void Mixed::set_olddatetime(OldDateTime v) noexcept +{ + m_type = type_OldDateTime; + m_date = v.get_olddatetime(); +} + +inline void Mixed::set_timestamp(Timestamp v) noexcept +{ + m_type = type_Timestamp; + m_timestamp = v; +} + +// LCOV_EXCL_START +template +inline std::basic_ostream& operator<<(std::basic_ostream& out, const Mixed& m) +{ + out << "Mixed("; + switch (m.m_type) { + case type_Int: + out << m.m_int; + break; + case type_Bool: + out << m.m_bool; + break; + case type_Float: + out << m.m_float; + break; + case type_Double: + out << m.m_double; + break; + case type_String: + out << StringData(m.m_data, m.m_size); + break; + case type_Binary: + out << BinaryData(m.m_data, m.m_size); + break; + case type_OldDateTime: + out << OldDateTime(m.m_date); + break; + case type_Timestamp: + out << Timestamp(m.m_timestamp); + break; + case type_Table: + out << "subtable"; + break; + case type_Mixed: + case type_Link: + case type_LinkList: + REALM_ASSERT(false); + } + out << ")"; + return out; +} +// LCOV_EXCL_STOP + + +// Compare mixed with integer + +template +inline bool operator==(Wrap a, const T& b) noexcept +{ + return Mixed(a).get_type() == type_Int && Mixed(a).get_int() == b; +} + +template +inline bool operator!=(Wrap a, const T& b) noexcept +{ + return Mixed(a).get_type() != type_Int || Mixed(a).get_int() != b; +} + +template +inline bool operator==(const T& a, Wrap b) noexcept +{ + return type_Int == Mixed(b).get_type() && a == Mixed(b).get_int(); +} + +template +inline bool operator!=(const T& a, Wrap b) noexcept +{ + return type_Int != Mixed(b).get_type() || a != Mixed(b).get_int(); +} + + +// Compare mixed with boolean + +inline bool operator==(Wrap a, bool b) noexcept +{ + return Mixed(a).get_type() == type_Bool && Mixed(a).get_bool() == b; +} + +inline bool operator!=(Wrap a, bool b) noexcept +{ + return Mixed(a).get_type() != type_Bool || Mixed(a).get_bool() != b; +} + +inline bool operator==(bool a, Wrap b) noexcept +{ + return type_Bool == Mixed(b).get_type() && a == Mixed(b).get_bool(); +} + +inline bool operator!=(bool a, Wrap b) noexcept +{ + return type_Bool != Mixed(b).get_type() || a != Mixed(b).get_bool(); +} + + +// Compare mixed with float + +inline bool operator==(Wrap a, float b) +{ + return Mixed(a).get_type() == type_Float && Mixed(a).get_float() == b; +} + +inline bool operator!=(Wrap a, float b) +{ + return Mixed(a).get_type() != type_Float || Mixed(a).get_float() != b; +} + +inline bool operator==(float a, Wrap b) +{ + return type_Float == Mixed(b).get_type() && a == Mixed(b).get_float(); +} + +inline bool operator!=(float a, Wrap b) +{ + return type_Float != Mixed(b).get_type() || a != Mixed(b).get_float(); +} + + +// Compare mixed with double + +inline bool operator==(Wrap a, double b) +{ + return Mixed(a).get_type() == type_Double && Mixed(a).get_double() == b; +} + +inline bool operator!=(Wrap a, double b) +{ + return Mixed(a).get_type() != type_Double || Mixed(a).get_double() != b; +} + +inline bool operator==(double a, Wrap b) +{ + return type_Double == Mixed(b).get_type() && a == Mixed(b).get_double(); +} + +inline bool operator!=(double a, Wrap b) +{ + return type_Double != Mixed(b).get_type() || a != Mixed(b).get_double(); +} + + +// Compare mixed with string + +inline bool operator==(Wrap a, StringData b) noexcept +{ + return Mixed(a).get_type() == type_String && Mixed(a).get_string() == b; +} + +inline bool operator!=(Wrap a, StringData b) noexcept +{ + return Mixed(a).get_type() != type_String || Mixed(a).get_string() != b; +} + +inline bool operator==(StringData a, Wrap b) noexcept +{ + return type_String == Mixed(b).get_type() && a == Mixed(b).get_string(); +} + +inline bool operator!=(StringData a, Wrap b) noexcept +{ + return type_String != Mixed(b).get_type() || a != Mixed(b).get_string(); +} + +inline bool operator==(Wrap a, const char* b) noexcept +{ + return a == StringData(b); +} + +inline bool operator!=(Wrap a, const char* b) noexcept +{ + return a != StringData(b); +} + +inline bool operator==(const char* a, Wrap b) noexcept +{ + return StringData(a) == b; +} + +inline bool operator!=(const char* a, Wrap b) noexcept +{ + return StringData(a) != b; +} + +inline bool operator==(Wrap a, char* b) noexcept +{ + return a == StringData(b); +} + +inline bool operator!=(Wrap a, char* b) noexcept +{ + return a != StringData(b); +} + +inline bool operator==(char* a, Wrap b) noexcept +{ + return StringData(a) == b; +} + +inline bool operator!=(char* a, Wrap b) noexcept +{ + return StringData(a) != b; +} + + +// Compare mixed with binary data + +inline bool operator==(Wrap a, BinaryData b) noexcept +{ + return Mixed(a).get_type() == type_Binary && Mixed(a).get_binary() == b; +} + +inline bool operator!=(Wrap a, BinaryData b) noexcept +{ + return Mixed(a).get_type() != type_Binary || Mixed(a).get_binary() != b; +} + +inline bool operator==(BinaryData a, Wrap b) noexcept +{ + return type_Binary == Mixed(b).get_type() && a == Mixed(b).get_binary(); +} + +inline bool operator!=(BinaryData a, Wrap b) noexcept +{ + return type_Binary != Mixed(b).get_type() || a != Mixed(b).get_binary(); +} + + +// Compare mixed with date + +inline bool operator==(Wrap a, OldDateTime b) noexcept +{ + return Mixed(a).get_type() == type_OldDateTime && OldDateTime(Mixed(a).get_olddatetime()) == b; +} + +inline bool operator!=(Wrap a, OldDateTime b) noexcept +{ + return Mixed(a).get_type() != type_OldDateTime || OldDateTime(Mixed(a).get_olddatetime()) != b; +} + +inline bool operator==(OldDateTime a, Wrap b) noexcept +{ + return type_OldDateTime == Mixed(b).get_type() && a == OldDateTime(Mixed(b).get_olddatetime()); +} + +inline bool operator!=(OldDateTime a, Wrap b) noexcept +{ + return type_OldDateTime != Mixed(b).get_type() || a != OldDateTime(Mixed(b).get_olddatetime()); +} + +// Compare mixed with Timestamp + +inline bool operator==(Wrap a, Timestamp b) noexcept +{ + return Mixed(a).get_type() == type_Timestamp && Timestamp(Mixed(a).get_timestamp()) == b; +} + +inline bool operator!=(Wrap a, Timestamp b) noexcept +{ + return Mixed(a).get_type() != type_Timestamp || Timestamp(Mixed(a).get_timestamp()) != b; +} + +inline bool operator==(Timestamp a, Wrap b) noexcept +{ + return type_Timestamp == Mixed(b).get_type() && a == Timestamp(Mixed(b).get_timestamp()); +} + +inline bool operator!=(Timestamp a, Wrap b) noexcept +{ + return type_Timestamp != Mixed(b).get_type() || a != Timestamp(Mixed(b).get_timestamp()); +} + + +} // namespace realm + +#endif // REALM_MIXED_HPP diff --git a/Pods/Realm/include/core/realm/null.hpp b/Pods/Realm/include/core/realm/null.hpp new file mode 100644 index 0000000000..733e79800f --- /dev/null +++ b/Pods/Realm/include/core/realm/null.hpp @@ -0,0 +1,172 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_NULL_HPP +#define REALM_NULL_HPP + +#include +#include + +#include +#include +#include +#include + +namespace realm { + +/* +Represents null in Query, find(), get(), set(), etc. + +Float/Double: Realm can both store user-given NaNs and null. Any user-given signaling NaN is converted to +0x7fa00000 (if float) or 0x7ff4000000000000 (if double). Any user-given quiet NaN is converted to +0x7fc00000 (if float) or 0x7ff8000000000000 (if double). So Realm does not preserve the optional bits in +user-given NaNs. + +However, since both clang and gcc on x64 and ARM, and also Java on x64, return these bit patterns when +requesting NaNs, these will actually seem to roundtrip bit-exact for the end-user in most cases. + +If set_null() is called, a null is stored in form of the bit pattern 0xffffffff (if float) or +0xffffffffffffffff (if double). These are quiet NaNs. + +Executing a query that involves a float/double column that contains NaNs gives an undefined result. If +it contains signaling NaNs, it may throw an exception. + +Notes on IEEE: + +A NaN float is any bit pattern `s 11111111 S xxxxxxxxxxxxxxxxxxxxxx` where `s` and `x` are arbitrary, but at +least 1 `x` must be 1. If `S` is 1, it's a quiet NaN, else it's a signaling NaN. + +A NaN doubule is the same as above, but for `s eeeeeeeeeee S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` + +The `S` bit is at position 22 (float) or 51 (double). +*/ + +struct null { + null() + { + } + operator int64_t() + { + throw(LogicError::type_mismatch); + } + template + operator util::Optional() + { + return util::none; + } + + template + bool operator==(const T&) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator!=(const T&) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator>(const T&) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator>=(const T&) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator<=(const T&) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator<(const T&) const + { + REALM_ASSERT(false); + return false; + } + + /// Returns whether `v` bitwise equals the null bit-pattern + template + static bool is_null_float(T v) + { + T i = null::get_null_float(); + return std::memcmp(&i, &v, sizeof(T)) == 0; + } + + /// Returns the quiet NaNs that represent null for floats/doubles in Realm in stored payload. + template + static T get_null_float() + { + typename std::conditional::value, uint32_t, uint64_t>::type i; + int64_t double_nan = 0x7ff80000000000aa; + i = std::is_same::value ? 0x7fc000aa : static_cast(double_nan); + T d = type_punning(i); + REALM_ASSERT_DEBUG(std::isnan(d)); + REALM_ASSERT_DEBUG(!is_signaling(d)); + return d; + } + + /// Takes a NaN as argument and returns whether or not it's signaling + template + static bool is_signaling(T v) + { + REALM_ASSERT(std::isnan(static_cast(v))); + typename std::conditional::value, uint32_t, uint64_t>::type i; + size_t signal_bit = std::is_same::value ? 22 : 51; // If this bit is set, it's quiet + i = type_punning(v); + return !(i & (1ull << signal_bit)); + } + + /// Converts any signaling or quiet NaN to their their respective bit patterns that are used on x64 gcc+clang, + /// ARM clang and x64 Java. + template + static T to_realm(T v) + { + if (std::isnan(static_cast(v))) { + typename std::conditional::value, uint32_t, uint64_t>::type i; + if (std::is_same::value) { + i = is_signaling(v) ? 0x7fa00000 : 0x7fc00000; + } + else { + i = static_cast(is_signaling(v) ? 0x7ff4000000000000 : 0x7ff8000000000000); + } + return type_punning(i); + } + else { + return v; + } + } +}; + +template +OS& operator<<(OS& os, const null&) +{ + os << "(null)"; + return os; +} + +} // namespace realm + +#endif // REALM_NULL_HPP diff --git a/Pods/Realm/include/core/realm/olddatetime.hpp b/Pods/Realm/include/core/realm/olddatetime.hpp new file mode 100644 index 0000000000..b662899e3c --- /dev/null +++ b/Pods/Realm/include/core/realm/olddatetime.hpp @@ -0,0 +1,157 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_DATETIME_HPP +#define REALM_DATETIME_HPP + +#include +#include + +namespace realm { + + +class OldDateTime { +public: + OldDateTime() noexcept + : m_time(0) + { + } + + /// Construct from the number of seconds since Jan 1 00:00:00 UTC + /// 1970. + /// FIXME: See if we can make this private again. Required by query_expression.hpp + OldDateTime(int_fast64_t d) noexcept + : m_time(d) + { + } + + /// Return the time as seconds since Jan 1 00:00:00 UTC 1970. + int_fast64_t get_olddatetime() const noexcept + { + return m_time; + } + + friend bool operator==(const OldDateTime&, const OldDateTime&) noexcept; + friend bool operator!=(const OldDateTime&, const OldDateTime&) noexcept; + friend bool operator<(const OldDateTime&, const OldDateTime&) noexcept; + friend bool operator<=(const OldDateTime&, const OldDateTime&) noexcept; + friend bool operator>(const OldDateTime&, const OldDateTime&) noexcept; + friend bool operator>=(const OldDateTime&, const OldDateTime&) noexcept; + + /// Construct from broken down local time. + /// + /// \note This constructor uses std::mktime() to convert the + /// specified local time to seconds since the Epoch, that is, the + /// result depends on the current globally specified time zone + /// setting. + /// + /// \param year The year (the minimum valid value is 1970). + /// + /// \param month The month in the range [1, 12]. + /// + /// \param day The day of the month in the range [1, 31]. + /// + /// \param hours Hours since midnight in the range [0, 23]. + /// + /// \param minutes Minutes after the hour in the range [0, 59]. + /// + /// \param seconds Seconds after the minute in the range [0, + /// 60]. Note that the range allows for leap seconds. + OldDateTime(int year, int month, int day, int hours = 0, int minutes = 0, int seconds = 0); + + template + friend std::basic_ostream& operator<<(std::basic_ostream& out, const OldDateTime&); + + // This is used by query_expression.hpp to generalize its templates and simplify the code *alot*; it is needed + // because OldDateTime is internally stored in an int64_t column. + operator int_fast64_t() noexcept; + +private: + int_fast64_t m_time; // Seconds since Jan 1 00:00:00 UTC 1970. + static std::time_t assemble(int year, int month, int day, int hours, int minutes, int seconds); + template + friend class Value; +}; + + +// Implementation: + +inline bool operator==(const OldDateTime& a, const OldDateTime& b) noexcept +{ + return a.m_time == b.m_time; +} + +inline bool operator!=(const OldDateTime& a, const OldDateTime& b) noexcept +{ + return a.m_time != b.m_time; +} + +inline bool operator<(const OldDateTime& a, const OldDateTime& b) noexcept +{ + return a.m_time < b.m_time; +} + +inline bool operator<=(const OldDateTime& a, const OldDateTime& b) noexcept +{ + return a.m_time <= b.m_time; +} + +inline bool operator>(const OldDateTime& a, const OldDateTime& b) noexcept +{ + return a.m_time > b.m_time; +} + +inline bool operator>=(const OldDateTime& a, const OldDateTime& b) noexcept +{ + return a.m_time >= b.m_time; +} + +inline OldDateTime::operator int_fast64_t() noexcept +{ + return m_time; +} + +inline OldDateTime::OldDateTime(int year, int month, int day, int hours, int minutes, int seconds) + : m_time(assemble(year, month, day, hours, minutes, seconds)) +{ +} + +template +inline std::basic_ostream& operator<<(std::basic_ostream& out, const OldDateTime& d) +{ + out << "OldDateTime(" << d.m_time << ")"; + return out; +} + +inline std::time_t OldDateTime::assemble(int year, int month, int day, int hours, int minutes, int seconds) +{ + std::tm local_time; + local_time.tm_year = year - 1900; + local_time.tm_mon = month - 1; + local_time.tm_mday = day; + local_time.tm_hour = hours; + local_time.tm_min = minutes; + local_time.tm_sec = seconds; + local_time.tm_isdst = -1; + return std::mktime(&local_time); +} + + +} // namespace realm + +#endif // REALM_DATETIME_HPP diff --git a/Pods/Realm/include/core/realm/owned_data.hpp b/Pods/Realm/include/core/realm/owned_data.hpp new file mode 100644 index 0000000000..c707f9da4c --- /dev/null +++ b/Pods/Realm/include/core/realm/owned_data.hpp @@ -0,0 +1,96 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_OWNED_DATA_HPP +#define REALM_OWNED_DATA_HPP + +#include + +#include +#include + +namespace realm { + +/// A chunk of owned data. +class OwnedData { +public: + /// Construct a null reference. + OwnedData() noexcept + { + } + + /// If \a data_to_copy is 'null', \a data_size must be zero. + OwnedData(const char* data_to_copy, size_t data_size) + : m_size(data_size) + { + REALM_ASSERT_DEBUG(data_to_copy || data_size == 0); + if (data_to_copy) { + m_data = std::unique_ptr(new char[data_size]); + memcpy(m_data.get(), data_to_copy, data_size); + } + } + + /// If \a unique_data is 'null', \a data_size must be zero. + OwnedData(std::unique_ptr unique_data, size_t data_size) noexcept + : m_data(std::move(unique_data)) + , m_size(data_size) + { + REALM_ASSERT_DEBUG(m_data || m_size == 0); + } + + OwnedData(const OwnedData& other) + : OwnedData(other.m_data.get(), other.m_size) + { + } + OwnedData& operator=(const OwnedData& other); + + OwnedData(OwnedData&&) = default; + OwnedData& operator=(OwnedData&&) = default; + + const char* data() const + { + return m_data.get(); + } + size_t size() const + { + return m_size; + } + +private: + std::unique_ptr m_data; + size_t m_size = 0; +}; + +inline OwnedData& OwnedData::operator=(const OwnedData& other) +{ + if (this != &other) { + if (other.m_data) { + m_data = std::unique_ptr(new char[other.m_size]); + memcpy(m_data.get(), other.m_data.get(), other.m_size); + } + else { + m_data = nullptr; + } + m_size = other.m_size; + } + return *this; +} + +} // namespace realm + +#endif // REALM_OWNED_DATA_HPP diff --git a/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp b/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp new file mode 100644 index 0000000000..4edd5c29b5 --- /dev/null +++ b/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp @@ -0,0 +1,226 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_COLLECTION_OPERATOR_EXPRESSION_HPP +#define REALM_COLLECTION_OPERATOR_EXPRESSION_HPP + +#include "property_expression.hpp" +#include "parser.hpp" +#include "parser_utils.hpp" + +#include + +namespace realm { +namespace parser { + +template +struct CollectionOperatorGetter; + +template +struct CollectionOperatorExpression +{ + static constexpr parser::Expression::KeyPathOp operation_type = OpType; + std::function table_getter; + PropertyExpression pe; + size_t post_link_col_ndx; + DataType post_link_col_type; + + CollectionOperatorExpression(PropertyExpression&& exp, std::string suffix_path, parser::KeyPathMapping& mapping) + : pe(std::move(exp)) + , post_link_col_ndx(realm::not_found) + { + table_getter = std::bind(&PropertyExpression::table_getter, pe); + + const bool requires_suffix_path = !(OpType == parser::Expression::KeyPathOp::SizeString + || OpType == parser::Expression::KeyPathOp::SizeBinary + || OpType == parser::Expression::KeyPathOp::Count + || OpType == parser::Expression::KeyPathOp::BacklinkCount); + + if (requires_suffix_path) { + Table* pre_link_table = pe.table_getter(); + REALM_ASSERT(pre_link_table); + StringData list_property_name; + if (pe.dest_type_is_backlink()) { + list_property_name = "linking object"; + } else { + list_property_name = pre_link_table->get_column_name(pe.get_dest_ndx()); + } + realm_precondition(pe.get_dest_type() == type_LinkList || pe.dest_type_is_backlink(), + util::format("The '%1' operation must be used on a list property, but '%2' is not a list", + util::collection_operator_to_str(OpType), list_property_name)); + + ConstTableRef post_link_table; + if (pe.dest_type_is_backlink()) { + post_link_table = pe.get_dest_table(); + } else { + post_link_table = pe.get_dest_table()->get_link_target(pe.get_dest_ndx()); + } + REALM_ASSERT(post_link_table); + StringData printable_post_link_table_name = get_printable_table_name(*post_link_table); + + KeyPath suffix_key_path = key_path_from_string(suffix_path); + + realm_precondition(suffix_path.size() > 0 && suffix_key_path.size() > 0, + util::format("A property from object '%1' must be provided to perform operation '%2'", + printable_post_link_table_name, util::collection_operator_to_str(OpType))); + size_t index = 0; + KeyPathElement element = mapping.process_next_path(post_link_table, suffix_key_path, index); + + realm_precondition(suffix_key_path.size() == 1, + util::format("Unable to use '%1' because collection aggreate operations are only supported " + "for direct properties at this time", suffix_path)); + + post_link_col_ndx = element.col_ndx; + post_link_col_type = element.col_type; + } + else { // !requires_suffix_path + if (!pe.link_chain.empty()) { + post_link_col_type = pe.get_dest_type(); + } + + realm_precondition(suffix_path.empty(), + util::format("An extraneous property '%1' was found for operation '%2'", + suffix_path, util::collection_operator_to_str(OpType))); + } + } + template + auto value_of_type_for_query() const + { + return CollectionOperatorGetter::convert(*this); + } +}; + + +// Certain operations are disabled for some types (eg. a sum of timestamps is invalid). +// The operations that are supported have a specialisation with std::enable_if for that type below +// any type/operation combination that is not specialised will get the runtime error from the following +// default implementation. The return type is just a dummy to make things compile. +template +struct CollectionOperatorGetter { + static Columns convert(const CollectionOperatorExpression& op) { + throw std::runtime_error(util::format("Predicate error: comparison of type '%1' with result of '%2' is not supported.", + type_to_str(), + collection_operator_to_str(op.operation_type))); + } +}; + +template +struct CollectionOperatorGetter::value> >{ + static SubColumnAggregate > convert(const CollectionOperatorExpression& expr) + { + if (expr.pe.dest_type_is_backlink()) { + return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).min(); + } else { + return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).min(); + } + } +}; + +template +struct CollectionOperatorGetter::value> >{ + static SubColumnAggregate > convert(const CollectionOperatorExpression& expr) + { + if (expr.pe.dest_type_is_backlink()) { + return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).max(); + } else { + return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).max(); + } + } +}; + +template +struct CollectionOperatorGetter::value> >{ + static SubColumnAggregate > convert(const CollectionOperatorExpression& expr) + { + if (expr.pe.dest_type_is_backlink()) { + return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).sum(); + } else { + return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).sum(); + } + } +}; + +template +struct CollectionOperatorGetter::value> >{ + static SubColumnAggregate > convert(const CollectionOperatorExpression& expr) + { + if (expr.pe.dest_type_is_backlink()) { + return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).average(); + } else { + return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).average(); + } + } +}; + +template +struct CollectionOperatorGetter::value> >{ + static LinkCount convert(const CollectionOperatorExpression& expr) + { + if (expr.pe.dest_type_is_backlink()) { + return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).count(); + } else { + return expr.table_getter()->template column(expr.pe.get_dest_ndx()).count(); + } + } +}; + + +template +struct CollectionOperatorGetter::value> >{ + static BacklinkCount convert(const CollectionOperatorExpression& expr) + { + if (expr.pe.link_chain.empty() || expr.pe.get_dest_ndx() == realm::npos) { + // here we are operating on the current table from a "@links.@count" query with no link keypath prefix + return expr.table_getter()->template get_backlink_count(); + } else { + if (expr.pe.dest_type_is_backlink()) { + return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template backlink_count(); + } else { + return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template backlink_count(); + } + } + } +}; + + +template <> +struct CollectionOperatorGetter{ + static SizeOperator > convert(const CollectionOperatorExpression& expr) + { + return expr.table_getter()->template column(expr.pe.get_dest_ndx()).size(); + } +}; + +template <> +struct CollectionOperatorGetter{ + static SizeOperator > convert(const CollectionOperatorExpression& expr) + { + return expr.table_getter()->template column(expr.pe.get_dest_ndx()).size(); + } +}; + +} // namespace parser +} // namespace realm + +#endif // REALM_COLLECTION_OPERATOR_EXPRESSION_HPP diff --git a/Pods/Realm/include/core/realm/parser/expression_container.hpp b/Pods/Realm/include/core/realm/parser/expression_container.hpp new file mode 100644 index 0000000000..7e596b9416 --- /dev/null +++ b/Pods/Realm/include/core/realm/parser/expression_container.hpp @@ -0,0 +1,79 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_EXPRESSION_CONTAINER_HPP +#define REALM_EXPRESSION_CONTAINER_HPP + +#include + +#include "collection_operator_expression.hpp" +#include "parser.hpp" +#include "property_expression.hpp" +#include "query_builder.hpp" +#include "subquery_expression.hpp" +#include "value_expression.hpp" + +namespace realm { +namespace parser { + +class ExpressionContainer +{ +public: + ExpressionContainer(Query& query, const parser::Expression& e, query_builder::Arguments& args, parser::KeyPathMapping& mapping); + + bool is_null(); + + PropertyExpression& get_property(); + ValueExpression& get_value(); + CollectionOperatorExpression& get_min(); + CollectionOperatorExpression& get_max(); + CollectionOperatorExpression& get_sum(); + CollectionOperatorExpression& get_avg(); + CollectionOperatorExpression& get_count(); + CollectionOperatorExpression& get_backlink_count(); + CollectionOperatorExpression& get_size_string(); + CollectionOperatorExpression& get_size_binary(); + SubqueryExpression& get_subexpression(); + + DataType check_type_compatibility(DataType type); + DataType get_comparison_type(ExpressionContainer& rhs); + + enum class ExpressionInternal + { + exp_Value, + exp_Property, + exp_OpMin, + exp_OpMax, + exp_OpSum, + exp_OpAvg, + exp_OpCount, + exp_OpSizeString, + exp_OpSizeBinary, + exp_OpBacklinkCount, + exp_SubQuery + }; + + ExpressionInternal type; +private: + util::Any storage; +}; + +} // namespace parser +} // namespace realm + +#endif // REALM_EXPRESSION_CONTAINER_HPP diff --git a/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp b/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp new file mode 100644 index 0000000000..ef71d8d69f --- /dev/null +++ b/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp @@ -0,0 +1,75 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_KEYPATH_MAPPING_HPP +#define REALM_KEYPATH_MAPPING_HPP + +#include + +#include "parser_utils.hpp" + +#include +#include + +namespace realm { +namespace parser { + +struct KeyPathElement +{ + ConstTableRef table; + size_t col_ndx; + DataType col_type; + bool is_backlink; +}; + +class BacklinksRestrictedError : public std::runtime_error { +public: + BacklinksRestrictedError(const std::string& msg) : std::runtime_error(msg) {} + /// runtime_error::what() returns the msg provided in the constructor. +}; + +struct TableAndColHash { + std::size_t operator () (const std::pair &p) const; +}; + + +// This class holds state which allows aliasing variable names in key paths used in queries. +// It is used to allow variable naming in subqueries such as 'SUBQUERY(list, $obj, $obj.intCol = 5).@count' +// It can also be used to allow querying named backlinks if bindings provide the mappings themselves. +class KeyPathMapping +{ +public: + KeyPathMapping(); + // returns true if added, false if duplicate key already exists + bool add_mapping(ConstTableRef table, std::string name, std::string alias); + void remove_mapping(ConstTableRef table, std::string name); + bool has_mapping(ConstTableRef table, std::string name); + KeyPathElement process_next_path(ConstTableRef table, KeyPath& path, size_t& index); + void set_allow_backlinks(bool allow); + void set_backlink_class_prefix(std::string prefix); + static Table* table_getter(TableRef table, const std::vector& links); +protected: + bool m_allow_backlinks; + std::string m_backlink_class_prefix; + std::unordered_map, std::string, TableAndColHash> m_mapping; +}; + +} // namespace parser +} // namespace realm + +#endif // REALM_KEYPATH_MAPPING_HPP diff --git a/Pods/Realm/include/core/realm/parser/parser.hpp b/Pods/Realm/include/core/realm/parser/parser.hpp new file mode 100644 index 0000000000..7ce72e4c3c --- /dev/null +++ b/Pods/Realm/include/core/realm/parser/parser.hpp @@ -0,0 +1,141 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_PARSER_HPP +#define REALM_PARSER_HPP + +#include +#include +#include + +namespace realm { + +namespace parser { + +struct Predicate; + +struct Expression +{ + enum class Type { None, Number, String, KeyPath, Argument, True, False, Null, Timestamp, Base64, SubQuery } type; + enum class KeyPathOp { None, Min, Max, Avg, Sum, Count, SizeString, SizeBinary, BacklinkCount } collection_op; + std::string s; + std::vector time_inputs; + std::string op_suffix; + std::string subquery_path, subquery_var; + std::shared_ptr subquery; + Expression(Type t = Type::None, std::string input = "") : type(t), collection_op(KeyPathOp::None), s(input) {} + Expression(std::vector&& timestamp) : type(Type::Timestamp), collection_op(KeyPathOp::None), time_inputs(timestamp) {} + Expression(std::string prefix, KeyPathOp op, std::string suffix) : type(Type::KeyPath), collection_op(op), s(prefix), op_suffix(suffix) {} +}; + +struct Predicate +{ + enum class Type + { + Comparison, + Or, + And, + True, + False + } type = Type::And; + + enum class Operator + { + None, + Equal, + NotEqual, + LessThan, + LessThanOrEqual, + GreaterThan, + GreaterThanOrEqual, + BeginsWith, + EndsWith, + Contains, + Like, + In + }; + + enum class OperatorOption + { + None, + CaseInsensitive, + }; + + enum class ComparisonType + { + Unspecified, + Any, + All, + None, + }; + + struct Comparison + { + Operator op = Operator::None; + OperatorOption option = OperatorOption::None; + Expression expr[2] = {{Expression::Type::None, ""}, {Expression::Type::None, ""}}; + ComparisonType compare_type = ComparisonType::Unspecified; + }; + + struct Compound + { + std::vector sub_predicates; + }; + + Comparison cmpr; + Compound cpnd; + + bool negate = false; + + Predicate(Type t, bool n = false) : type(t), negate(n) {} +}; + +struct DescriptorOrderingState +{ + struct PropertyState + { + std::string key_path; + bool ascending; + }; + struct SingleOrderingState + { + std::vector properties; + size_t limit; + enum class DescriptorType { Sort, Distinct, Limit } type; + }; + std::vector orderings; +}; + +struct ParserResult +{ + ParserResult(Predicate p, DescriptorOrderingState o) + : predicate(p) + , ordering(o) {} + Predicate predicate; + DescriptorOrderingState ordering; +}; + +ParserResult parse(const std::string &query); + +// run the analysis tool to check for cycles in the grammar +// returns the number of problems found and prints some info to std::cout +size_t analyze_grammar(); +} +} + +#endif // REALM_PARSER_HPP diff --git a/Pods/Realm/include/core/realm/parser/parser_utils.hpp b/Pods/Realm/include/core/realm/parser/parser_utils.hpp new file mode 100644 index 0000000000..12b79c9915 --- /dev/null +++ b/Pods/Realm/include/core/realm/parser/parser_utils.hpp @@ -0,0 +1,87 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_PARSER_UTILS_HPP +#define REALM_PARSER_UTILS_HPP + +#include +#include +#include "parser.hpp" + +#include +#include + +namespace realm { + +class Table; +class Timestamp; +struct Link; + +namespace util { + +// check a precondition and throw an exception if it is not met +// this should be used iff the condition being false indicates a bug in the caller +// of the function checking its preconditions +#define realm_precondition(condition, message) if (!REALM_LIKELY(condition)) { throw std::logic_error(message); } + + +template +const char* type_to_str(); + +template <> +const char* type_to_str(); +template <> +const char* type_to_str(); +template <> +const char* type_to_str(); +template <> +const char* type_to_str(); +template <> +const char* type_to_str(); +template <> +const char* type_to_str(); +template <> +const char* type_to_str(); +template <> +const char* type_to_str(); + +const char* data_type_to_str(DataType type); +const char* collection_operator_to_str(parser::Expression::KeyPathOp op); +const char* comparison_type_to_str(parser::Predicate::ComparisonType type); + +using KeyPath = std::vector; +KeyPath key_path_from_string(const std::string &s); +std::string key_path_to_string(const KeyPath& keypath); +StringData get_printable_table_name(StringData name); +StringData get_printable_table_name(const Table& table); + +template +T stot(std::string const& s) { + std::istringstream iss(s); + T value; + iss >> value; + if (iss.fail()) { + throw std::invalid_argument(util::format("Cannot convert string '%1'", s)); + } + return value; +} + +} // namespace utils +} // namespace realm + +#endif // REALM_PARSER_UTILS_HPP diff --git a/Pods/Realm/include/core/realm/parser/property_expression.hpp b/Pods/Realm/include/core/realm/parser/property_expression.hpp new file mode 100644 index 0000000000..8f4a7ec062 --- /dev/null +++ b/Pods/Realm/include/core/realm/parser/property_expression.hpp @@ -0,0 +1,78 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_PROPERTY_EXPRESSION_HPP +#define REALM_PROPERTY_EXPRESSION_HPP + +#include +#include +#include + +namespace realm { +namespace parser { + +struct PropertyExpression +{ + Query &query; + std::vector link_chain; + DataType get_dest_type() const; + size_t get_dest_ndx() const; + ConstTableRef get_dest_table() const; + bool dest_type_is_backlink() const; + + PropertyExpression(Query &q, const std::string &key_path_string, parser::KeyPathMapping& mapping); + + Table* table_getter() const; + + template + auto value_of_type_for_query() const + { + return this->table_getter()->template column(get_dest_ndx()); + } +}; + +inline DataType PropertyExpression::get_dest_type() const +{ + REALM_ASSERT_DEBUG(link_chain.size() > 0); + return link_chain.back().col_type; +} + +inline bool PropertyExpression::dest_type_is_backlink() const +{ + REALM_ASSERT_DEBUG(link_chain.size() > 0); + return link_chain.back().is_backlink; +} + +inline size_t PropertyExpression::get_dest_ndx() const +{ + REALM_ASSERT_DEBUG(link_chain.size() > 0); + return link_chain.back().col_ndx; +} + +inline ConstTableRef PropertyExpression::get_dest_table() const +{ + REALM_ASSERT_DEBUG(link_chain.size() > 0); + return link_chain.back().table; +} + + +} // namespace parser +} // namespace realm + +#endif // REALM_PROPERTY_EXPRESSION_HPP + diff --git a/Pods/Realm/include/core/realm/parser/query_builder.hpp b/Pods/Realm/include/core/realm/parser/query_builder.hpp new file mode 100644 index 0000000000..ef91bb118d --- /dev/null +++ b/Pods/Realm/include/core/realm/parser/query_builder.hpp @@ -0,0 +1,155 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_QUERY_BUILDER_HPP +#define REALM_QUERY_BUILDER_HPP + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace realm { +class Query; +class Realm; +class Table; +template class BasicRowExpr; +using RowExpr = BasicRowExpr
; + +namespace parser { + struct Predicate; + struct DescriptorOrderingState; +} + +namespace query_builder { +class Arguments; + +void apply_predicate(Query& query, const parser::Predicate& predicate, Arguments& arguments, parser::KeyPathMapping = parser::KeyPathMapping()); + +void apply_ordering(DescriptorOrdering& ordering, ConstTableRef target, const parser::DescriptorOrderingState& state, Arguments& arguments); +void apply_ordering(DescriptorOrdering& ordering, ConstTableRef target, const parser::DescriptorOrderingState& state); + + +struct AnyContext +{ + template + T unbox(const util::Any& wrapper) { + return util::any_cast(wrapper); + } + bool is_null(const util::Any& wrapper) { + if (!wrapper.has_value()) { + return true; + } + if (wrapper.type() == typeid(realm::null)) { + return true; + } + return false; + } +}; + +class Arguments { +public: + virtual bool bool_for_argument(size_t argument_index) = 0; + virtual long long long_for_argument(size_t argument_index) = 0; + virtual float float_for_argument(size_t argument_index) = 0; + virtual double double_for_argument(size_t argument_index) = 0; + virtual StringData string_for_argument(size_t argument_index) = 0; + virtual BinaryData binary_for_argument(size_t argument_index) = 0; + virtual Timestamp timestamp_for_argument(size_t argument_index) = 0; + virtual size_t object_index_for_argument(size_t argument_index) = 0; + virtual bool is_argument_null(size_t argument_index) = 0; + // dynamic conversion space with lifetime tied to this + // it is used for storing literal binary/string data + std::vector buffer_space; +}; + +template +class ArgumentConverter : public Arguments { +public: + ArgumentConverter(ContextType& context, const ValueType* arguments, size_t count) + : m_ctx(context) + , m_arguments(arguments) + , m_count(count) + {} + + bool bool_for_argument(size_t i) override { return get(i); } + long long long_for_argument(size_t i) override { return get(i); } + float float_for_argument(size_t i) override { return get(i); } + double double_for_argument(size_t i) override { return get(i); } + StringData string_for_argument(size_t i) override { return get(i); } + BinaryData binary_for_argument(size_t i) override { return get(i); } + Timestamp timestamp_for_argument(size_t i) override { return get(i); } + size_t object_index_for_argument(size_t i) override { return get(i).get_index(); } + bool is_argument_null(size_t i) override { return m_ctx.is_null(at(i)); } + +private: + ContextType& m_ctx; + const ValueType* m_arguments; + size_t m_count; + + const ValueType& at(size_t index) const + { + if (index >= m_count) { + std::string error_message; + if (m_count) { + error_message = util::format("Request for argument at index %1 but only %2 argument%3 provided", index, m_count, m_count == 1 ? " is" : "s are"); + } else { + error_message = util::format("Request for argument at index %1 but no arguments are provided", index); + } + throw std::out_of_range(error_message); + } + return m_arguments[index]; + } + + template + T get(size_t index) const + { + return m_ctx.template unbox(at(index)); + } +}; + +class NoArgsError : public std::runtime_error { +public: + NoArgsError() : std::runtime_error("Attempt to retreive an argument when no arguments were given") {} +}; + +class NoArguments : public Arguments { +public: + bool bool_for_argument(size_t) { throw NoArgsError(); } + long long long_for_argument(size_t) { throw NoArgsError(); } + float float_for_argument(size_t) { throw NoArgsError(); } + double double_for_argument(size_t) { throw NoArgsError(); } + StringData string_for_argument(size_t) { throw NoArgsError(); } + BinaryData binary_for_argument(size_t) { throw NoArgsError(); } + Timestamp timestamp_for_argument(size_t) { throw NoArgsError(); } + size_t object_index_for_argument(size_t) { throw NoArgsError(); } + bool is_argument_null(size_t) { throw NoArgsError(); } +}; + +} // namespace query_builder +} // namespace realm + +#endif // REALM_QUERY_BUILDER_HPP diff --git a/Pods/Realm/include/core/realm/parser/subquery_expression.hpp b/Pods/Realm/include/core/realm/parser/subquery_expression.hpp new file mode 100644 index 0000000000..20c04d161d --- /dev/null +++ b/Pods/Realm/include/core/realm/parser/subquery_expression.hpp @@ -0,0 +1,112 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_SUBQUERY_EXPRESSION_HPP +#define REALM_SUBQUERY_EXPRESSION_HPP + +#include +#include +#include +#include + +#include "parser_utils.hpp" + +namespace realm { +namespace parser { + +template +struct SubqueryGetter; + +struct SubqueryExpression +{ + std::string var_name; + Query &query; + Query subquery; + std::vector link_chain; + DataType get_dest_type() const; + size_t get_dest_ndx() const; + ConstTableRef get_dest_table() const; + bool dest_type_is_backlink() const; + + + SubqueryExpression(Query &q, const std::string &key_path_string, const std::string &variable_name, parser::KeyPathMapping &mapping); + Query& get_subquery(); + + Table* table_getter() const; + + template + auto value_of_type_for_query() const + { + return SubqueryGetter::convert(*this); + } +}; + +inline DataType SubqueryExpression::get_dest_type() const +{ + REALM_ASSERT_DEBUG(link_chain.size() > 0); + return link_chain.back().col_type; +} + +inline bool SubqueryExpression::dest_type_is_backlink() const +{ + REALM_ASSERT_DEBUG(link_chain.size() > 0); + return link_chain.back().is_backlink; +} + +inline size_t SubqueryExpression::get_dest_ndx() const +{ + REALM_ASSERT_DEBUG(link_chain.size() > 0); + return link_chain.back().col_ndx; +} + +inline ConstTableRef SubqueryExpression::get_dest_table() const +{ + REALM_ASSERT_DEBUG(link_chain.size() > 0); + return link_chain.back().table; +} + +// Certain operations are disabled for some types (eg. a sum of timestamps is invalid). +// The operations that are supported have a specialisation with std::enable_if for that type below +// any type/operation combination that is not specialised will get the runtime error from the following +// default implementation. The return type is just a dummy to make things compile. +template +struct SubqueryGetter { + static Columns convert(const SubqueryExpression&) { + throw std::runtime_error(util::format("Predicate error: comparison of type '%1' with result of a subquery count is not supported.", + type_to_str())); + } +}; + +template +struct SubqueryGetter::value> >{ + static SubQueryCount convert(const SubqueryExpression& expr) + { + if (expr.dest_type_is_backlink()) { + return expr.table_getter()->template column(*expr.get_dest_table(), expr.get_dest_ndx(), expr.subquery).count(); + } else { + return expr.table_getter()->template column(expr.get_dest_ndx(), expr.subquery).count(); + } + } +}; + +} // namespace parser +} // namespace realm + +#endif // REALM_SUBQUERY_EXPRESSION_HPP + diff --git a/Pods/Realm/include/core/realm/parser/value_expression.hpp b/Pods/Realm/include/core/realm/parser/value_expression.hpp new file mode 100644 index 0000000000..09ac257564 --- /dev/null +++ b/Pods/Realm/include/core/realm/parser/value_expression.hpp @@ -0,0 +1,43 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_VALUE_EXPRESSION_HPP +#define REALM_VALUE_EXPRESSION_HPP + +#include "parser.hpp" +#include "query_builder.hpp" + +namespace realm { +namespace parser { + +struct ValueExpression +{ + const parser::Expression* value; + query_builder::Arguments* arguments; + std::function
table_getter; + + ValueExpression(Query& query, query_builder::Arguments* args, const parser::Expression* v); + bool is_null(); + template + RetType value_of_type_for_query(); +}; + +} // namespace parser +} // namespace realm + +#endif // REALM_VALUE_EXPRESSION_HPP diff --git a/Pods/Realm/include/core/realm/query.hpp b/Pods/Realm/include/core/realm/query.hpp new file mode 100644 index 0000000000..59a764f98c --- /dev/null +++ b/Pods/Realm/include/core/realm/query.hpp @@ -0,0 +1,481 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_QUERY_HPP +#define REALM_QUERY_HPP + +#include +#include +#include +#include +#include +#include + +#define REALM_MULTITHREAD_QUERY 0 + +#if REALM_MULTITHREAD_QUERY +// FIXME: Use our C++ thread abstraction API since it provides a much +// higher level of encapsulation and safety. +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace realm { + + +// Pre-declarations +class ParentNode; +class Table; +class TableView; +class TableViewBase; +class ConstTableView; +class Array; +class Expression; +class SequentialGetterBase; +class Group; + +namespace metrics { +class QueryInfo; +} + +struct QueryGroup { + enum class State { + Default, + OrCondition, + OrConditionChildren, + }; + + QueryGroup() = default; + + QueryGroup(const QueryGroup&); + QueryGroup& operator=(const QueryGroup&); + + QueryGroup(QueryGroup&&) = default; + QueryGroup& operator=(QueryGroup&&) = default; + + QueryGroup(const QueryGroup&, QueryNodeHandoverPatches&); + + std::unique_ptr m_root_node; + + bool m_pending_not = false; + size_t m_subtable_column = not_found; + State m_state = State::Default; +}; + +class Query final { +public: + Query(const Table& table, TableViewBase* tv = nullptr); + Query(const Table& table, std::unique_ptr); + Query(const Table& table, const LinkViewRef& lv); + Query(); + Query(std::unique_ptr); + ~Query() noexcept; + + Query(const Query& copy); + Query& operator=(const Query& source); + + Query(Query&&); + Query& operator=(Query&&); + + // Find links that point to a specific target row + Query& links_to(size_t column_ndx, const ConstRow& target_row); + + // Conditions: null + Query& equal(size_t column_ndx, null); + Query& not_equal(size_t column_ndx, null); + + // Conditions: int64_t + Query& equal(size_t column_ndx, int64_t value); + Query& not_equal(size_t column_ndx, int64_t value); + Query& greater(size_t column_ndx, int64_t value); + Query& greater_equal(size_t column_ndx, int64_t value); + Query& less(size_t column_ndx, int64_t value); + Query& less_equal(size_t column_ndx, int64_t value); + Query& between(size_t column_ndx, int64_t from, int64_t to); + + // Conditions: int (we need those because conversion from '1234' is ambiguous with float/double) + Query& equal(size_t column_ndx, int value); + Query& not_equal(size_t column_ndx, int value); + Query& greater(size_t column_ndx, int value); + Query& greater_equal(size_t column_ndx, int value); + Query& less(size_t column_ndx, int value); + Query& less_equal(size_t column_ndx, int value); + Query& between(size_t column_ndx, int from, int to); + + // Conditions: 2 int columns + Query& equal_int(size_t column_ndx1, size_t column_ndx2); + Query& not_equal_int(size_t column_ndx1, size_t column_ndx2); + Query& greater_int(size_t column_ndx1, size_t column_ndx2); + Query& less_int(size_t column_ndx1, size_t column_ndx2); + Query& greater_equal_int(size_t column_ndx1, size_t column_ndx2); + Query& less_equal_int(size_t column_ndx1, size_t column_ndx2); + + // Conditions: float + Query& equal(size_t column_ndx, float value); + Query& not_equal(size_t column_ndx, float value); + Query& greater(size_t column_ndx, float value); + Query& greater_equal(size_t column_ndx, float value); + Query& less(size_t column_ndx, float value); + Query& less_equal(size_t column_ndx, float value); + Query& between(size_t column_ndx, float from, float to); + + // Conditions: 2 float columns + Query& equal_float(size_t column_ndx1, size_t column_ndx2); + Query& not_equal_float(size_t column_ndx1, size_t column_ndx2); + Query& greater_float(size_t column_ndx1, size_t column_ndx2); + Query& greater_equal_float(size_t column_ndx1, size_t column_ndx2); + Query& less_float(size_t column_ndx1, size_t column_ndx2); + Query& less_equal_float(size_t column_ndx1, size_t column_ndx2); + + // Conditions: double + Query& equal(size_t column_ndx, double value); + Query& not_equal(size_t column_ndx, double value); + Query& greater(size_t column_ndx, double value); + Query& greater_equal(size_t column_ndx, double value); + Query& less(size_t column_ndx, double value); + Query& less_equal(size_t column_ndx, double value); + Query& between(size_t column_ndx, double from, double to); + + // Conditions: 2 double columns + Query& equal_double(size_t column_ndx1, size_t column_ndx2); + Query& not_equal_double(size_t column_ndx1, size_t column_ndx2); + Query& greater_double(size_t column_ndx1, size_t column_ndx2); + Query& greater_equal_double(size_t column_ndx1, size_t column_ndx2); + Query& less_double(size_t column_ndx1, size_t column_ndx2); + Query& less_equal_double(size_t column_ndx1, size_t column_ndx2); + + // Conditions: timestamp + Query& equal(size_t column_ndx, Timestamp value); + Query& not_equal(size_t column_ndx, Timestamp value); + Query& greater(size_t column_ndx, Timestamp value); + Query& greater_equal(size_t column_ndx, Timestamp value); + Query& less_equal(size_t column_ndx, Timestamp value); + Query& less(size_t column_ndx, Timestamp value); + + // Conditions: size + Query& size_equal(size_t column_ndx, int64_t value); + Query& size_not_equal(size_t column_ndx, int64_t value); + Query& size_greater(size_t column_ndx, int64_t value); + Query& size_greater_equal(size_t column_ndx, int64_t value); + Query& size_less_equal(size_t column_ndx, int64_t value); + Query& size_less(size_t column_ndx, int64_t value); + Query& size_between(size_t column_ndx, int64_t from, int64_t to); + + // Conditions: bool + Query& equal(size_t column_ndx, bool value); + + // Conditions: date + Query& equal_olddatetime(size_t column_ndx, OldDateTime value) + { + return equal(column_ndx, int64_t(value.get_olddatetime())); + } + Query& not_equal_olddatetime(size_t column_ndx, OldDateTime value) + { + return not_equal(column_ndx, int64_t(value.get_olddatetime())); + } + Query& greater_olddatetime(size_t column_ndx, OldDateTime value) + { + return greater(column_ndx, int64_t(value.get_olddatetime())); + } + Query& greater_equal_olddatetime(size_t column_ndx, OldDateTime value) + { + return greater_equal(column_ndx, int64_t(value.get_olddatetime())); + } + Query& less_olddatetime(size_t column_ndx, OldDateTime value) + { + return less(column_ndx, int64_t(value.get_olddatetime())); + } + Query& less_equal_olddatetime(size_t column_ndx, OldDateTime value) + { + return less_equal(column_ndx, int64_t(value.get_olddatetime())); + } + Query& between_olddatetime(size_t column_ndx, OldDateTime from, OldDateTime to) + { + return between(column_ndx, int64_t(from.get_olddatetime()), int64_t(to.get_olddatetime())); + } + + // Conditions: strings + Query& equal(size_t column_ndx, StringData value, bool case_sensitive = true); + Query& not_equal(size_t column_ndx, StringData value, bool case_sensitive = true); + Query& begins_with(size_t column_ndx, StringData value, bool case_sensitive = true); + Query& ends_with(size_t column_ndx, StringData value, bool case_sensitive = true); + Query& contains(size_t column_ndx, StringData value, bool case_sensitive = true); + Query& like(size_t column_ndx, StringData value, bool case_sensitive = true); + + // These are shortcuts for equal(StringData(c_str)) and + // not_equal(StringData(c_str)), and are needed to avoid unwanted + // implicit conversion of char* to bool. + Query& equal(size_t column_ndx, const char* c_str, bool case_sensitive = true); + Query& not_equal(size_t column_ndx, const char* c_str, bool case_sensitive = true); + + // Conditions: binary data + Query& equal(size_t column_ndx, BinaryData value, bool case_sensitive = true); + Query& not_equal(size_t column_ndx, BinaryData value, bool case_sensitive = true); + Query& begins_with(size_t column_ndx, BinaryData value, bool case_sensitive = true); + Query& ends_with(size_t column_ndx, BinaryData value, bool case_sensitive = true); + Query& contains(size_t column_ndx, BinaryData value, bool case_sensitive = true); + Query& like(size_t column_ndx, BinaryData b, bool case_sensitive = true); + + // Negation + Query& Not(); + + // Grouping + Query& group(); + Query& end_group(); + Query& subtable(size_t column); + Query& end_subtable(); + Query& Or(); + + Query& and_query(const Query& q); + Query& and_query(Query&& q); + Query operator||(const Query& q); + Query operator&&(const Query& q); + Query operator!(); + + + // Searching + size_t find(size_t begin_at_table_row = size_t(0)); + TableView find_all(size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)); + + // Aggregates + size_t count(size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; + + TableView find_all(const DescriptorOrdering& descriptor); + size_t count(const DescriptorOrdering& descriptor); + + int64_t sum_int(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1)) const; + + double average_int(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1)) const; + + int64_t maximum_int(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; + + int64_t minimum_int(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; + + double sum_float(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1)) const; + + double average_float(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1)) const; + + float maximum_float(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; + + float minimum_float(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; + + double sum_double(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1)) const; + + double average_double(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1)) const; + + double maximum_double(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; + + double minimum_double(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; + + OldDateTime maximum_olddatetime(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, + size_t end = size_t(-1), size_t limit = size_t(-1), + size_t* return_ndx = nullptr) const; + + OldDateTime minimum_olddatetime(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, + size_t end = size_t(-1), size_t limit = size_t(-1), + size_t* return_ndx = nullptr) const; + + Timestamp maximum_timestamp(size_t column_ndx, size_t* return_ndx, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1)); + + Timestamp minimum_timestamp(size_t column_ndx, size_t* return_ndx, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1)); + + // Deletion + size_t remove(); + +#if REALM_MULTITHREAD_QUERY + // Multi-threading + TableView find_all_multi(size_t start = 0, size_t end = size_t(-1)); + ConstTableView find_all_multi(size_t start = 0, size_t end = size_t(-1)) const; + int set_threads(unsigned int threadcount); +#endif + + const TableRef& get_table() + { + return m_table; + } + + // True if matching rows are guaranteed to be returned in table order. + bool produces_results_in_table_order() const + { + return !m_view; + } + + // Calls sync_if_needed on the restricting view, if present. + // Returns the current version of the table(s) this query depends on, + // or util::none if the query is not associated with a table. + util::Optional sync_view_if_needed() const; + + std::string validate(); + + std::string get_description() const; + std::string get_description(util::serializer::SerialisationState& state) const; + +private: + Query(Table& table, TableViewBase* tv = nullptr); + void create(); + + void init() const; + size_t find_internal(size_t start = 0, size_t end = size_t(-1)) const; + size_t peek_tablerow(size_t row) const; + void handle_pending_not(); + void set_table(TableRef tr); + +public: + using HandoverPatch = QueryHandoverPatch; + + std::unique_ptr clone_for_handover(std::unique_ptr& patch, ConstSourcePayload mode) const + { + patch.reset(new HandoverPatch); + return std::make_unique(*this, *patch, mode); + } + + std::unique_ptr clone_for_handover(std::unique_ptr& patch, MutableSourcePayload mode) + { + patch.reset(new HandoverPatch); + return std::make_unique(*this, *patch, mode); + } + + void apply_and_consume_patch(std::unique_ptr& patch, Group& dest_group) + { + apply_patch(*patch, dest_group); + patch.reset(); + } + + void apply_patch(HandoverPatch& patch, Group& dest_group); + Query(const Query& source, HandoverPatch& patch, ConstSourcePayload mode); + Query(Query& source, HandoverPatch& patch, MutableSourcePayload mode); + +private: + void fetch_descriptor(); + + void add_expression_node(std::unique_ptr); + + template + Query& equal(size_t column_ndx1, size_t column_ndx2); + + template + Query& less(size_t column_ndx1, size_t column_ndx2); + + template + Query& less_equal(size_t column_ndx1, size_t column_ndx2); + + template + Query& greater(size_t column_ndx1, size_t column_ndx2); + + template + Query& greater_equal(size_t column_ndx1, size_t column_ndx2); + + template + Query& not_equal(size_t column_ndx1, size_t column_ndx2); + + template + Query& add_condition(size_t column_ndx, T value); + + template + Query& add_size_condition(size_t column_ndx, int64_t value); + + template + double average(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), + size_t limit = size_t(-1)) const; + + template + R aggregate(R (ColClass::*method)(size_t, size_t, size_t, size_t*) const, size_t column_ndx, size_t* resultcount, + size_t start, size_t end, size_t limit, size_t* return_ndx = nullptr) const; + + void aggregate_internal(Action TAction, DataType TSourceColumn, bool nullable, ParentNode* pn, QueryStateBase* st, + size_t start, size_t end, SequentialGetterBase* source_column) const; + + void find_all(TableViewBase& tv, size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; + size_t do_count(size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; + void delete_nodes() noexcept; + + bool has_conditions() const + { + return m_groups.size() > 0 && m_groups[0].m_root_node; + } + ParentNode* root_node() const + { + REALM_ASSERT(m_groups.size()); + return m_groups[0].m_root_node.get(); + } + + void add_node(std::unique_ptr); + + friend class Table; + friend class TableViewBase; + friend class metrics::QueryInfo; + + std::string error_code; + + std::vector m_groups; + + // Used to access schema while building query: + std::vector m_subtable_path; + + ConstDescriptorRef m_current_descriptor; + TableRef m_table; + + // points to the base class of the restricting view. If the restricting + // view is a link view, m_source_link_view is non-zero. If it is a table view, + // m_source_table_view is non-zero. + RowIndexes* m_view = nullptr; + + // At most one of these can be non-zero, and if so the non-zero one indicates the restricting view. + LinkViewRef m_source_link_view; // link views are refcounted and shared. + TableViewBase* m_source_table_view = nullptr; // table views are not refcounted, and not owned by the query. + std::unique_ptr m_owned_source_table_view; // <--- except when indicated here +}; + +// Implementation: + +inline Query& Query::equal(size_t column_ndx, const char* c_str, bool case_sensitive) +{ + return equal(column_ndx, StringData(c_str), case_sensitive); +} + +inline Query& Query::not_equal(size_t column_ndx, const char* c_str, bool case_sensitive) +{ + return not_equal(column_ndx, StringData(c_str), case_sensitive); +} + +} // namespace realm + +#endif // REALM_QUERY_HPP diff --git a/Pods/Realm/include/core/realm/query_conditions.hpp b/Pods/Realm/include/core/realm/query_conditions.hpp new file mode 100644 index 0000000000..f9d66fb531 --- /dev/null +++ b/Pods/Realm/include/core/realm/query_conditions.hpp @@ -0,0 +1,860 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_QUERY_CONDITIONS_HPP +#define REALM_QUERY_CONDITIONS_HPP + +#include +#include + +#include +#include +#include + +namespace realm { + +// Array::VTable only uses the first 4 conditions (enums) in an array of function pointers +enum { cond_Equal, cond_NotEqual, cond_Greater, cond_Less, cond_VTABLE_FINDER_COUNT, cond_None, cond_LeftNotNull }; + +// Quick hack to make "Queries with Integer null columns" able to compile in Visual Studio 2015 which doesn't full +// support sfinae +// (real cause hasn't been investigated yet, cannot exclude that we don't obey c++11 standard) +struct HackClass { + template + bool can_match(A, B, C) + { + REALM_ASSERT(false); + return false; + } + template + bool will_match(A, B, C) + { + REALM_ASSERT(false); + return false; + } +}; + +// Does v2 contain v1? +struct Contains : public HackClass { + bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const + { + return v2.contains(v1); + } + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + return v2.contains(v1); + } + bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const + { + return v2.contains(v1); + } + bool operator()(StringData v1, const std::array &charmap, StringData v2) const + { + return v2.contains(v1, charmap); + } + + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + bool operator()(int64_t, int64_t, bool, bool) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "CONTAINS"; + } + + static const int condition = -1; +}; + +// Does v2 contain something like v1 (wildcard matching)? +struct Like : public HackClass { + bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const + { + return v2.like(v1); + } + bool operator()(BinaryData b1, const char*, const char*, BinaryData b2, bool = false, bool = false) const + { + StringData s1(b1.data(), b1.size()); + StringData s2(b2.data(), b2.size()); + return s2.like(s1); + } + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + return v2.like(v1); + } + bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const + { + StringData s1(b1.data(), b1.size()); + StringData s2(b2.data(), b2.size()); + return s2.like(s1); + } + + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + + bool operator()(int64_t, int64_t, bool, bool) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "LIKE"; + } + + static const int condition = -1; +}; + +// Does v2 begin with v1? +struct BeginsWith : public HackClass { + bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const + { + return v2.begins_with(v1); + } + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + return v2.begins_with(v1); + } + bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const + { + return v2.begins_with(v1); + } + + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "BEGINSWITH"; + } + + static const int condition = -1; +}; + +// Does v2 end with v1? +struct EndsWith : public HackClass { + bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const + { + return v2.ends_with(v1); + } + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + return v2.ends_with(v1); + } + bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const + { + return v2.ends_with(v1); + } + + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "ENDSWITH"; + } + + static const int condition = -1; +}; + +struct Equal { + static const int avx = 0x00; // _CMP_EQ_OQ + // bool operator()(const bool v1, const bool v2, bool v1null = false, bool v2null = false) const { return v1 == + // v2; } + bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const + { + return v1 == v2; + } + bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const + { + return v1 == v2; + } + + template + bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const + { + return (v1null && v2null) || (!v1null && !v2null && v1 == v2); + } + static const int condition = cond_Equal; + bool can_match(int64_t v, int64_t lbound, int64_t ubound) + { + return (v >= lbound && v <= ubound); + } + bool will_match(int64_t v, int64_t lbound, int64_t ubound) + { + return (v == 0 && ubound == 0 && lbound == 0); + } + + static std::string description() + { + return "=="; + } +}; + +struct NotEqual { + static const int avx = 0x0B; // _CMP_FALSE_OQ + bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const + { + return v1 != v2; + } + // bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const { return v1 != v2; } + + template + bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const + { + if (!v1null && !v2null) + return v1 != v2; + + if (v1null && v2null) + return false; + + return true; + } + + static const int condition = cond_NotEqual; + bool can_match(int64_t v, int64_t lbound, int64_t ubound) + { + return !(v == 0 && ubound == 0 && lbound == 0); + } + bool will_match(int64_t v, int64_t lbound, int64_t ubound) + { + return (v > ubound || v < lbound); + } + + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "!="; + } +}; + +// Does v2 contain v1? +struct ContainsIns : public HackClass { + bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, + bool = false) const + { + if (v2.is_null() && !v1.is_null()) + return false; + + if (v1.size() == 0 && !v2.is_null()) + return true; + + return search_case_fold(v2, v1_upper, v1_lower, v1.size()) != v2.size(); + } + + // Slow version, used if caller hasn't stored an upper and lower case version + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + if (v2.is_null() && !v1.is_null()) + return false; + + if (v1.size() == 0 && !v2.is_null()) + return true; + + std::string v1_upper = case_map(v1, true, IgnoreErrors); + std::string v1_lower = case_map(v1, false, IgnoreErrors); + return search_case_fold(v2, v1_upper.c_str(), v1_lower.c_str(), v1.size()) != v2.size(); + } + bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const + { + StringData s1(b1.data(), b1.size()); + StringData s2(b2.data(), b2.size()); + return this->operator()(s1, s2, false, false); + } + + // Case insensitive Boyer-Moore version + bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, const std::array &charmap, StringData v2) const + { + if (v2.is_null() && !v1.is_null()) + return false; + + if (v1.size() == 0 && !v2.is_null()) + return true; + + return contains_ins(v2, v1_upper, v1_lower, v1.size(), charmap); + } + + + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + bool operator()(int64_t, int64_t, bool, bool) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "CONTAINS[c]"; + } + + static const int condition = -1; +}; + +// Does v2 contain something like v1 (wildcard matching)? +struct LikeIns : public HackClass { + bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, + bool = false) const + { + if (v2.is_null() || v1.is_null()) { + return (v2.is_null() && v1.is_null()); + } + + return string_like_ins(v2, v1_lower, v1_upper); + } + bool operator()(BinaryData b1, const char* b1_upper, const char* b1_lower, BinaryData b2, bool = false, + bool = false) const + { + if (b2.is_null() || b1.is_null()) { + return (b2.is_null() && b1.is_null()); + } + StringData s2(b2.data(), b2.size()); + + return string_like_ins(s2, b1_lower, b1_upper); + } + + // Slow version, used if caller hasn't stored an upper and lower case version + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + if (v2.is_null() || v1.is_null()) { + return (v2.is_null() && v1.is_null()); + } + + std::string v1_upper = case_map(v1, true, IgnoreErrors); + std::string v1_lower = case_map(v1, false, IgnoreErrors); + return string_like_ins(v2, v1_lower, v1_upper); + } + bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const + { + if (b2.is_null() || b1.is_null()) { + return (b2.is_null() && b1.is_null()); + } + StringData s1(b1.data(), b1.size()); + StringData s2(b2.data(), b2.size()); + + std::string s1_upper = case_map(s1, true, IgnoreErrors); + std::string s1_lower = case_map(s1, false, IgnoreErrors); + return string_like_ins(s2, s1_lower, s1_upper); + } + + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + bool operator()(int64_t, int64_t, bool, bool) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "LIKE[c]"; + } + + static const int condition = -1; +}; + +// Does v2 begin with v1? +struct BeginsWithIns : public HackClass { + bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, + bool = false) const + { + if (v2.is_null() && !v1.is_null()) + return false; + return v1.size() <= v2.size() && equal_case_fold(v2.prefix(v1.size()), v1_upper, v1_lower); + } + + // Slow version, used if caller hasn't stored an upper and lower case version + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + if (v2.is_null() && !v1.is_null()) + return false; + + if (v1.size() > v2.size()) + return false; + std::string v1_upper = case_map(v1, true, IgnoreErrors); + std::string v1_lower = case_map(v1, false, IgnoreErrors); + return equal_case_fold(v2.prefix(v1.size()), v1_upper.c_str(), v1_lower.c_str()); + } + bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const + { + StringData s1(b1.data(), b1.size()); + StringData s2(b2.data(), b2.size()); + return this->operator()(s1, s2, false, false); + } + + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + bool operator()(int64_t, int64_t, bool, bool) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "BEGINSWITH[c]"; + } + + static const int condition = -1; +}; + +// Does v2 end with v1? +struct EndsWithIns : public HackClass { + bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, + bool = false) const + { + if (v2.is_null() && !v1.is_null()) + return false; + + return v1.size() <= v2.size() && equal_case_fold(v2.suffix(v1.size()), v1_upper, v1_lower); + } + + // Slow version, used if caller hasn't stored an upper and lower case version + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + if (v2.is_null() && !v1.is_null()) + return false; + + if (v1.size() > v2.size()) + return false; + std::string v1_upper = case_map(v1, true, IgnoreErrors); + std::string v1_lower = case_map(v1, false, IgnoreErrors); + return equal_case_fold(v2.suffix(v1.size()), v1_upper.c_str(), v1_lower.c_str()); + } + bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const + { + StringData s1(b1.data(), b1.size()); + StringData s2(b2.data(), b2.size()); + return this->operator()(s1, s2, false, false); + } + + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + bool operator()(int64_t, int64_t, bool, bool) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "ENDSWITH[c]"; + } + + static const int condition = -1; +}; + +struct EqualIns : public HackClass { + bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, + bool = false) const + { + if (v1.is_null() != v2.is_null()) + return false; + + return v1.size() == v2.size() && equal_case_fold(v2, v1_upper, v1_lower); + } + + // Slow version, used if caller hasn't stored an upper and lower case version + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + if (v1.is_null() != v2.is_null()) + return false; + + if (v1.size() != v2.size()) + return false; + std::string v1_upper = case_map(v1, true, IgnoreErrors); + std::string v1_lower = case_map(v1, false, IgnoreErrors); + return equal_case_fold(v2, v1_upper.c_str(), v1_lower.c_str()); + } + bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const + { + StringData s1(b1.data(), b1.size()); + StringData s2(b2.data(), b2.size()); + return this->operator()(s1, s2, false, false); + } + + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + bool operator()(int64_t, int64_t, bool, bool) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "==[c]"; + } + + static const int condition = -1; +}; + +struct NotEqualIns : public HackClass { + bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, + bool = false) const + { + if (v1.is_null() != v2.is_null()) + return true; + return v1.size() != v2.size() || !equal_case_fold(v2, v1_upper, v1_lower); + } + + // Slow version, used if caller hasn't stored an upper and lower case version + bool operator()(StringData v1, StringData v2, bool = false, bool = false) const + { + if (v1.is_null() != v2.is_null()) + return true; + + if (v1.size() != v2.size()) + return true; + std::string v1_upper = case_map(v1, true, IgnoreErrors); + std::string v1_lower = case_map(v1, false, IgnoreErrors); + return !equal_case_fold(v2, v1_upper.c_str(), v1_lower.c_str()); + } + bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const + { + StringData s1(b1.data(), b1.size()); + StringData s2(b2.data(), b2.size()); + return this->operator()(s1, s2, false, false); + } + + template + bool operator()(A, B) const + { + REALM_ASSERT(false); + return false; + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + + static std::string description() + { + return "!=[c]"; + } + + static const int condition = -1; +}; + +struct Greater { + static const int avx = 0x1E; // _CMP_GT_OQ + template + bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const + { + if (v1null || v2null) + return false; + + return v1 > v2; + } + static const int condition = cond_Greater; + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + + bool can_match(int64_t v, int64_t lbound, int64_t ubound) + { + static_cast(lbound); + return ubound > v; + } + bool will_match(int64_t v, int64_t lbound, int64_t ubound) + { + static_cast(ubound); + return lbound > v; + } + + static std::string description() + { + return ">"; + } +}; + +struct None { + template + bool operator()(const T&, const T&, bool = false, bool = false) const + { + return true; + } + static const int condition = cond_None; + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + bool can_match(int64_t v, int64_t lbound, int64_t ubound) + { + static_cast(lbound); + static_cast(ubound); + static_cast(v); + return true; + } + bool will_match(int64_t v, int64_t lbound, int64_t ubound) + { + static_cast(lbound); + static_cast(ubound); + static_cast(v); + return true; + } + + static std::string description() + { + return "none"; + } +}; + +struct NotNull { + template + bool operator()(const T&, const T&, bool v = false, bool = false) const + { + return !v; + } + static const int condition = cond_LeftNotNull; + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + bool can_match(int64_t v, int64_t lbound, int64_t ubound) + { + static_cast(lbound); + static_cast(ubound); + static_cast(v); + return true; + } + bool will_match(int64_t v, int64_t lbound, int64_t ubound) + { + static_cast(lbound); + static_cast(ubound); + static_cast(v); + return true; + } + static std::string description() + { + return "!= NULL"; + } +}; + + +struct Less { + static const int avx = 0x11; // _CMP_LT_OQ + template + bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const + { + if (v1null || v2null) + return false; + + return v1 < v2; + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + static const int condition = cond_Less; + bool can_match(int64_t v, int64_t lbound, int64_t ubound) + { + static_cast(ubound); + return lbound < v; + } + bool will_match(int64_t v, int64_t lbound, int64_t ubound) + { + static_cast(lbound); + return ubound < v; + } + static std::string description() + { + return "<"; + } +}; + +struct LessEqual : public HackClass { + static const int avx = 0x12; // _CMP_LE_OQ + template + bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const + { + if (v1null && v2null) + return true; + + return (!v1null && !v2null && v1 <= v2); + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + static std::string description() + { + return "<="; + } + static const int condition = -1; +}; + +struct GreaterEqual : public HackClass { + static const int avx = 0x1D; // _CMP_GE_OQ + template + bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const + { + if (v1null && v2null) + return true; + + return (!v1null && !v2null && v1 >= v2); + } + template + bool operator()(A, B, C, D) const + { + REALM_ASSERT(false); + return false; + } + static std::string description() + { + return ">="; + } + static const int condition = -1; +}; + + +// CompareLess is a temporary hack to have a generalized way to compare any realm types. Todo, enable correct < +// operator of StringData (currently gives circular header dependency with utf8.hpp) +template +struct CompareLess { + static bool compare(T v1, T v2, bool = false, bool = false) + { + return v1 < v2; + } +}; +template <> +struct CompareLess { + static bool compare(StringData v1, StringData v2, bool = false, bool = false) + { + bool ret = utf8_compare(v1.data(), v2.data()); + return ret; + } +}; + +} // namespace realm + +#endif // REALM_QUERY_CONDITIONS_HPP diff --git a/Pods/Realm/include/core/realm/query_engine.hpp b/Pods/Realm/include/core/realm/query_engine.hpp new file mode 100644 index 0000000000..3bf2949f52 --- /dev/null +++ b/Pods/Realm/include/core/realm/query_engine.hpp @@ -0,0 +1,2125 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +/* +A query consists of node objects, one for each query condition. Each node contains pointers to all other nodes: + +node1 node2 node3 +------ ----- ----- +node2* node1* node1* +node3* node3* node2* + +The construction of all this takes part in query.cpp. Each node has two important functions: + + aggregate(start, end) + aggregate_local(start, end) + +The aggregate() function executes the aggregate of a query. You can call the method on any of the nodes +(except children nodes of OrNode and SubtableNode) - it has the same behaviour. The function contains +scheduling that calls aggregate_local(start, end) on different nodes with different start/end ranges, +depending on what it finds is most optimal. + +The aggregate_local() function contains a tight loop that tests the condition of its own node, and upon match +it tests all other conditions at that index to report a full match or not. It will remain in the tight loop +after a full match. + +So a call stack with 2 and 9 being local matches of a node could look like this: + +aggregate(0, 10) + node1->aggregate_local(0, 3) + node2->find_first_local(2, 3) + node3->find_first_local(2, 3) + node3->aggregate_local(3, 10) + node1->find_first_local(4, 5) + node2->find_first_local(4, 5) + node1->find_first_local(7, 8) + node2->find_first_local(7, 8) + +find_first_local(n, n + 1) is a function that can be used to test a single row of another condition. Note that +this is very simplified. There are other statistical arguments to the methods, and also, find_first_local() can be +called from a callback function called by an integer Array. + + +Template arguments in methods: +---------------------------------------------------------------------------------------------------- + +TConditionFunction: Each node has a condition from query_conditions.c such as Equal, GreaterEqual, etc + +TConditionValue: Type of values in condition column. That is, int64_t, float, int, bool, etc + +TAction: What to do with each search result, from the enums act_ReturnFirst, act_Count, act_Sum, etc + +TResult: Type of result of actions - float, double, int64_t, etc. Special notes: For act_Count it's + int64_t, for RLM_FIND_ALL it's int64_t which points at destination array. + +TSourceColumn: Type of source column used in actions, or *ignored* if no source column is used (like for + act_Count, act_ReturnFirst) + + +There are two important classes used in queries: +---------------------------------------------------------------------------------------------------- +SequentialGetter Column iterator used to get successive values with leaf caching. Used both for condition columns + and aggregate source column + +AggregateState State of the aggregate - contains a state variable that stores intermediate sum, max, min, + etc, etc. + +*/ + +#ifndef REALM_QUERY_ENGINE_HPP +#define REALM_QUERY_ENGINE_HPP + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#if REALM_X86_OR_X64_TRUE && defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 160040219 +#include +#endif + +namespace realm { + +// Number of matches to find in best condition loop before breaking out to probe other conditions. Too low value gives +// too many constant time overheads everywhere in the query engine. Too high value makes it adapt less rapidly to +// changes in match frequencies. +const size_t findlocals = 64; + +// Average match distance in linear searches where further increase in distance no longer increases query speed +// (because time spent on handling each match becomes insignificant compared to time spent on the search). +const size_t bestdist = 512; + +// Minimum number of matches required in a certain condition before it can be used to compute statistics. Too high +// value can spent too much time in a bad node (with high match frequency). Too low value gives inaccurate statistics. +const size_t probe_matches = 4; + +const size_t bitwidth_time_unit = 64; + +typedef bool (*CallbackDummy)(int64_t); + +class ParentNode { + typedef ParentNode ThisType; + +public: + ParentNode() = default; + virtual ~ParentNode() = default; + + void gather_children(std::vector& v) + { + m_children.clear(); + size_t i = v.size(); + v.push_back(this); + + if (m_child) + m_child->gather_children(v); + + m_children = v; + m_children.erase(m_children.begin() + i); + m_children.insert(m_children.begin(), this); + } + + double cost() const + { + return 8 * bitwidth_time_unit / m_dD + + m_dT; // dt = 1/64 to 1. Match dist is 8 times more important than bitwidth + } + + size_t find_first(size_t start, size_t end); + + virtual void init() + { + // Verify that the cached column accessor is still valid + verify_column(); // throws + + if (m_child) + m_child->init(); + + m_column_action_specializer = nullptr; + } + + void set_table(const Table& table) + { + if (&table == m_table) + return; + + m_table.reset(&table); + if (m_child) + m_child->set_table(table); + table_changed(); + } + + virtual size_t find_first_local(size_t start, size_t end) = 0; + + virtual void aggregate_local_prepare(Action TAction, DataType col_id, bool nullable); + + template + bool column_action_specialization(QueryStateBase* st, SequentialGetterBase* source_column, size_t r) + { + // TResult: type of query result + // TSourceValue: type of aggregate source + using TSourceValue = typename TSourceColumn::value_type; + using TResult = typename ColumnTypeTraitsSum::sum_type; + + // Sum of float column must accumulate in double + static_assert(!(TAction == act_Sum && + (std::is_same::value && !std::is_same::value)), + ""); + + TSourceValue av{}; + // uses_val test because compiler cannot see that IntegerColumn::get has no side effect and result is + // discarded + if (static_cast*>(st)->template uses_val() && source_column != nullptr) { + REALM_ASSERT_DEBUG(dynamic_cast*>(source_column) != nullptr); + av = static_cast*>(source_column)->get_next(r); + } + REALM_ASSERT_DEBUG(dynamic_cast*>(st) != nullptr); + bool cont = static_cast*>(st)->template match(r, 0, av); + return cont; + } + + virtual size_t aggregate_local(QueryStateBase* st, size_t start, size_t end, size_t local_limit, + SequentialGetterBase* source_column); + + + virtual std::string validate() + { + if (error_code != "") + return error_code; + if (m_child == nullptr) + return ""; + else + return m_child->validate(); + } + + ParentNode(const ParentNode& from) + : ParentNode(from, nullptr) + { + } + + ParentNode(const ParentNode& from, QueryNodeHandoverPatches* patches) + : m_child(from.m_child ? from.m_child->clone(patches) : nullptr) + , m_condition_column_idx(from.m_condition_column_idx) + , m_dD(from.m_dD) + , m_dT(from.m_dT) + , m_probes(from.m_probes) + , m_matches(from.m_matches) + , m_table(patches ? ConstTableRef{} : from.m_table) + { + } + + void add_child(std::unique_ptr child) + { + if (m_child) + m_child->add_child(std::move(child)); + else + m_child = std::move(child); + } + + virtual std::unique_ptr clone(QueryNodeHandoverPatches* = nullptr) const = 0; + + virtual void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) + { + if (m_child) + m_child->apply_handover_patch(patches, group); + } + + virtual void verify_column() const = 0; + + virtual std::string describe(util::serializer::SerialisationState&) const + { + return ""; + } + + virtual std::string describe_condition() const + { + return "matches"; + } + + virtual std::string describe_expression(util::serializer::SerialisationState& state) const + { + std::string s; + s = describe(state); + if (m_child) { + s = s + " and " + m_child->describe_expression(state); + } + return s; + } + + std::unique_ptr m_child; + std::vector m_children; + size_t m_condition_column_idx = npos; // Column of search criteria + + double m_dD; // Average row distance between each local match at current position + double m_dT = 0.0; // Time overhead of testing index i + 1 if we have just tested index i. > 1 for linear scans, 0 + // for index/tableview + + size_t m_probes = 0; + size_t m_matches = 0; + +protected: + typedef bool (ParentNode::*Column_action_specialized)(QueryStateBase*, SequentialGetterBase*, size_t); + Column_action_specialized m_column_action_specializer; + ConstTableRef m_table; + std::string error_code; + + const ColumnBase& get_column_base(size_t ndx) + { + return m_table->get_column_base(ndx); + } + + template + const ColType& get_column(size_t ndx) + { + auto& col = m_table->get_column_base(ndx); + REALM_ASSERT_DEBUG(dynamic_cast(&col)); + return static_cast(col); + } + + ColumnType get_real_column_type(size_t ndx) + { + return m_table->get_real_column_type(ndx); + } + + template + void copy_getter(SequentialGetter& dst, size_t& dst_idx, const SequentialGetter& src, + const QueryNodeHandoverPatches* patches) + { + if (src.m_column) { + if (patches) + dst_idx = src.m_column->get_column_index(); + else + dst.init(src.m_column); + } + } + + void do_verify_column(const ColumnBase* col, size_t col_ndx = npos) const + { + if (col_ndx == npos) + col_ndx = m_condition_column_idx; + if (m_table && col_ndx != npos) { + m_table->verify_column(col_ndx, col); + } + } + +private: + virtual void table_changed() = 0; +}; + +// For conditions on a subtable (encapsulated in subtable()...end_subtable()). These return the parent row as match if +// and only if one or more subtable rows match the condition. +class SubtableNode : public ParentNode { +public: + SubtableNode(size_t column, std::unique_ptr condition) + : m_condition(std::move(condition)) + { + m_dT = 100.0; + m_condition_column_idx = column; + } + + void init() override + { + ParentNode::init(); + + m_dD = 10.0; + + // m_condition is first node in condition of subtable query. + if (m_condition) { + // Can't call init() here as usual since the subtable can be degenerate + // m_condition->init(table); + std::vector v; + m_condition->gather_children(v); + } + } + + void table_changed() override + { + m_col_type = m_table->get_real_column_type(m_condition_column_idx); + REALM_ASSERT(m_col_type == col_type_Table || m_col_type == col_type_Mixed); + if (m_col_type == col_type_Table) + m_column = &m_table->get_column_table(m_condition_column_idx); + else // Mixed + m_column = &m_table->get_column_mixed(m_condition_column_idx); + } + + void verify_column() const override + { + if (m_table) + m_table->verify_column(m_condition_column_idx, m_column); + } + + std::string validate() override + { + if (error_code != "") + return error_code; + if (m_condition == nullptr) + return "Unbalanced subtable/end_subtable block"; + else + return m_condition->validate(); + } + + std::string describe(util::serializer::SerialisationState&) const override + { + throw SerialisationError("Serialising a query which contains a subtable expression is currently unsupported."); + } + + + size_t find_first_local(size_t start, size_t end) override + { + REALM_ASSERT(m_table); + REALM_ASSERT(m_condition); + + for (size_t s = start; s < end; ++s) { + ConstTableRef subtable; // TBD: optimize this back to Table* + if (m_col_type == col_type_Table) + subtable = static_cast(m_column)->get_subtable_tableref(s); + else { + subtable = static_cast(m_column)->get_subtable_tableref(s); + if (!subtable) + continue; + } + + if (subtable->is_degenerate()) + return not_found; + + m_condition->set_table(*subtable); + m_condition->init(); + const size_t subsize = subtable->size(); + const size_t sub = m_condition->find_first(0, subsize); + + if (sub != not_found) + return s; + } + return not_found; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new SubtableNode(*this, patches)); + } + + SubtableNode(const SubtableNode& from, QueryNodeHandoverPatches* patches) + : ParentNode(from, patches) + , m_condition(from.m_condition ? from.m_condition->clone(patches) : nullptr) + , m_column(from.m_column) + , m_col_type(from.m_col_type) + { + if (m_column && patches) + m_condition_column_idx = m_column->get_column_index(); + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + m_condition->apply_handover_patch(patches, group); + ParentNode::apply_handover_patch(patches, group); + } + + std::unique_ptr m_condition; + const ColumnBase* m_column = nullptr; + ColumnType m_col_type; +}; + +namespace _impl { + +template +struct CostHeuristic; + +template <> +struct CostHeuristic { + static constexpr double dD() + { + return 100.0; + } + static constexpr double dT() + { + return 1.0 / 4.0; + } +}; + +template <> +struct CostHeuristic { + static constexpr double dD() + { + return 100.0; + } + static constexpr double dT() + { + return 1.0 / 4.0; + } +}; + +// FIXME: Add AdaptiveStringColumn, BasicColumn, etc. +} + +class ColumnNodeBase : public ParentNode { +protected: + ColumnNodeBase(size_t column_idx) + { + m_condition_column_idx = column_idx; + } + + ColumnNodeBase(const ColumnNodeBase& from, QueryNodeHandoverPatches* patches) + : ParentNode(from, patches) + , m_last_local_match(from.m_last_local_match) + , m_local_matches(from.m_local_matches) + , m_local_limit(from.m_local_limit) + , m_fastmode_disabled(from.m_fastmode_disabled) + , m_action(from.m_action) + , m_state(from.m_state) + , m_source_column(from.m_source_column) + { + } + + template + bool match_callback(int64_t v) + { + using TSourceValue = typename ColType::value_type; + using QueryStateType = typename ColumnTypeTraitsSum::sum_type; + + size_t i = to_size_t(v); + m_last_local_match = i; + m_local_matches++; + + auto state = static_cast*>(m_state); + auto source_column = static_cast*>(m_source_column); + + // Test remaining sub conditions of this node. m_children[0] is the node that called match_callback(), so skip + // it + for (size_t c = 1; c < m_children.size(); c++) { + m_children[c]->m_probes++; + size_t m = m_children[c]->find_first_local(i, i + 1); + if (m != i) + return true; + } + + bool b; + if (state->template uses_val()) { // Compiler cannot see that IntegerColumn::Get has no side effect + // and result is discarded + TSourceValue av = source_column->get_next(i); + b = state->template match(i, 0, av); + } + else { + b = state->template match(i, 0, TSourceValue{}); + } + + return b; + } + + // Aggregate bookkeeping + size_t m_last_local_match = npos; + size_t m_local_matches = 0; + size_t m_local_limit = 0; + bool m_fastmode_disabled = false; + Action m_action; + QueryStateBase* m_state = nullptr; + SequentialGetterBase* m_source_column = + nullptr; // Column of values used in aggregate (act_FindAll, actReturnFirst, act_Sum, etc) +}; + +template +class IntegerNodeBase : public ColumnNodeBase { + using ThisType = IntegerNodeBase; + +public: + using TConditionValue = typename ColType::value_type; + static const bool nullable = ColType::nullable; + + template + bool find_callback_specialization(size_t s, size_t end_in_leaf) + { + using AggregateColumnType = typename GetColumnType::type; + bool cont; + size_t start_in_leaf = s - this->m_leaf_start; + cont = this->m_leaf_ptr->template find( + m_value, start_in_leaf, end_in_leaf, this->m_leaf_start, nullptr, + std::bind(std::mem_fn(&ThisType::template match_callback), this, + std::placeholders::_1)); + return cont; + } + +protected: + using LeafType = typename ColType::LeafType; + using LeafInfo = typename ColType::LeafInfo; + + size_t aggregate_local_impl(QueryStateBase* st, size_t start, size_t end, size_t local_limit, + SequentialGetterBase* source_column, int c) + { + REALM_ASSERT(m_children.size() > 0); + m_local_matches = 0; + m_local_limit = local_limit; + m_last_local_match = start - 1; + m_state = st; + + // If there are no other nodes than us (m_children.size() == 1) AND the column used for our condition is + // the same as the column used for the aggregate action, then the entire query can run within scope of that + // column only, with no references to other columns: + bool fastmode = should_run_in_fastmode(source_column); + for (size_t s = start; s < end;) { + cache_leaf(s); + + size_t end_in_leaf; + if (end > m_leaf_end) + end_in_leaf = m_leaf_end - m_leaf_start; + else + end_in_leaf = end - m_leaf_start; + + if (fastmode) { + bool cont; + size_t start_in_leaf = s - m_leaf_start; + cont = m_leaf_ptr->find(c, m_action, m_value, start_in_leaf, end_in_leaf, m_leaf_start, + static_cast*>(st)); + if (!cont) + return not_found; + } + // Else, for each match in this node, call our IntegerNodeBase::match_callback to test remaining nodes + // and/or extract + // aggregate payload from aggregate column: + else { + m_source_column = source_column; + bool cont = (this->*m_find_callback_specialized)(s, end_in_leaf); + if (!cont) + return not_found; + } + + if (m_local_matches == m_local_limit) + break; + + s = end_in_leaf + m_leaf_start; + } + + if (m_local_matches == m_local_limit) { + m_dD = (m_last_local_match + 1 - start) / (m_local_matches + 1.0); + return m_last_local_match + 1; + } + else { + m_dD = (end - start) / (m_local_matches + 1.0); + return end; + } + } + + IntegerNodeBase(TConditionValue value, size_t column_idx) + : ColumnNodeBase(column_idx) + , m_value(std::move(value)) + { + } + + IntegerNodeBase(const ThisType& from, QueryNodeHandoverPatches* patches) + : ColumnNodeBase(from, patches) + , m_value(from.m_value) + , m_condition_column(from.m_condition_column) + , m_find_callback_specialized(from.m_find_callback_specialized) + { + if (m_condition_column && patches) + m_condition_column_idx = m_condition_column->get_column_index(); + } + + void table_changed() override + { + m_condition_column = &get_column(m_condition_column_idx); + } + + void verify_column() const override + { + do_verify_column(m_condition_column); + } + + void init() override + { + ColumnNodeBase::init(); + + m_dT = _impl::CostHeuristic::dT(); + m_dD = _impl::CostHeuristic::dD(); + + // Clear leaf cache + m_leaf_end = 0; + m_array_ptr.reset(); // Explicitly destroy the old one first, because we're reusing the memory. + m_array_ptr.reset(new (&m_leaf_cache_storage) LeafType(m_table->get_alloc())); + } + + void get_leaf(const ColType& col, size_t ndx) + { + size_t ndx_in_leaf; + LeafInfo leaf_info{&m_leaf_ptr, m_array_ptr.get()}; + col.get_leaf(ndx, ndx_in_leaf, leaf_info); + m_leaf_start = ndx - ndx_in_leaf; + m_leaf_end = m_leaf_start + m_leaf_ptr->size(); + } + + void cache_leaf(size_t s) + { + if (s >= m_leaf_end || s < m_leaf_start) { + get_leaf(*m_condition_column, s); + size_t w = m_leaf_ptr->get_width(); + m_dT = (w == 0 ? 1.0 / REALM_MAX_BPNODE_SIZE : w / float(bitwidth_time_unit)); + } + } + + bool should_run_in_fastmode(SequentialGetterBase* source_column) const + { + return (m_children.size() == 1 && + (source_column == nullptr || + (!m_fastmode_disabled && + static_cast*>(source_column)->m_column == m_condition_column))); + } + + // Search value: + TConditionValue m_value; + + // Column on which search criteria are applied + const ColType* m_condition_column = nullptr; + + // Leaf cache + using LeafCacheStorage = typename std::aligned_storage::type; + LeafCacheStorage m_leaf_cache_storage; + std::unique_ptr m_array_ptr; + const LeafType* m_leaf_ptr = nullptr; + size_t m_leaf_start = npos; + size_t m_leaf_end = 0; + size_t m_local_end; + + // Aggregate optimization + using TFind_callback_specialized = bool (ThisType::*)(size_t, size_t); + TFind_callback_specialized m_find_callback_specialized = nullptr; +}; + + +// FIXME: Add specialization that uses index for TConditionFunction = Equal +template +class IntegerNode : public IntegerNodeBase { + using BaseType = IntegerNodeBase; + using ThisType = IntegerNode; + +public: + static const bool special_null_node = false; + using TConditionValue = typename BaseType::TConditionValue; + + IntegerNode(TConditionValue value, size_t column_ndx) + : BaseType(value, column_ndx) + { + } + IntegerNode(const IntegerNode& from, QueryNodeHandoverPatches* patches) + : BaseType(from, patches) + { + } + + void aggregate_local_prepare(Action action, DataType col_id, bool nullable) override + { + this->m_fastmode_disabled = (col_id == type_Float || col_id == type_Double); + this->m_action = action; + this->m_find_callback_specialized = get_specialized_callback(action, col_id, nullable); + } + + size_t aggregate_local(QueryStateBase* st, size_t start, size_t end, size_t local_limit, + SequentialGetterBase* source_column) override + { + constexpr int cond = TConditionFunction::condition; + return this->aggregate_local_impl(st, start, end, local_limit, source_column, cond); + } + + size_t find_first_local(size_t start, size_t end) override + { + REALM_ASSERT(this->m_table); + + while (start < end) { + + // Cache internal leaves + if (start >= this->m_leaf_end || start < this->m_leaf_start) { + this->get_leaf(*this->m_condition_column, start); + } + + // FIXME: Create a fast bypass when you just need to check 1 row, which is used alot from within core. + // It should just call array::get and save the initial overhead of find_first() which has become quite + // big. Do this when we have cleaned up core a bit more. + + size_t end2; + if (end > this->m_leaf_end) + end2 = this->m_leaf_end - this->m_leaf_start; + else + end2 = end - this->m_leaf_start; + + size_t s; + s = this->m_leaf_ptr->template find_first(this->m_value, start - this->m_leaf_start, + end2); + + if (s == not_found) { + start = this->m_leaf_end; + continue; + } + else + return s + this->m_leaf_start; + } + + return not_found; + } + + virtual std::string describe(util::serializer::SerialisationState& state) const override + { + return state.describe_column(ParentNode::m_table, IntegerNodeBase::m_condition_column->get_column_index()) + + " " + describe_condition() + " " + util::serializer::print_value(IntegerNodeBase::m_value); + } + + virtual std::string describe_condition() const override + { + return TConditionFunction::description(); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new IntegerNode(*this, patches)); + } + +protected: + using TFind_callback_specialized = typename BaseType::TFind_callback_specialized; + + static TFind_callback_specialized get_specialized_callback(Action action, DataType col_id, bool nullable) + { + switch (action) { + case act_Count: + return get_specialized_callback_2_int(col_id, nullable); + case act_Sum: + return get_specialized_callback_2(col_id, nullable); + case act_Max: + return get_specialized_callback_2(col_id, nullable); + case act_Min: + return get_specialized_callback_2(col_id, nullable); + case act_FindAll: + return get_specialized_callback_2_int(col_id, nullable); + case act_CallbackIdx: + return get_specialized_callback_2_int(col_id, nullable); + default: + break; + } + REALM_ASSERT(false); // Invalid aggregate function + return nullptr; + } + + template + static TFind_callback_specialized get_specialized_callback_2(DataType col_id, bool nullable) + { + switch (col_id) { + case type_Int: + return get_specialized_callback_3(nullable); + case type_Float: + return get_specialized_callback_3(nullable); + case type_Double: + return get_specialized_callback_3(nullable); + default: + break; + } + REALM_ASSERT(false); // Invalid aggregate source column + return nullptr; + } + + template + static TFind_callback_specialized get_specialized_callback_2_int(DataType col_id, bool nullable) + { + if (col_id == type_Int) { + return get_specialized_callback_3(nullable); + } + REALM_ASSERT(false); // Invalid aggregate source column + return nullptr; + } + + template + static TFind_callback_specialized get_specialized_callback_3(bool nullable) + { + if (nullable) { + return &BaseType::template find_callback_specialization; + } + else { + return &BaseType::template find_callback_specialization; + } + } +}; + + +// This node is currently used for floats and doubles only +template +class FloatDoubleNode : public ParentNode { +public: + using TConditionValue = typename ColType::value_type; + static const bool special_null_node = false; + + FloatDoubleNode(TConditionValue v, size_t column_ndx) + : m_value(v) + { + m_condition_column_idx = column_ndx; + m_dT = 1.0; + } + FloatDoubleNode(null, size_t column_ndx) + : m_value(null::get_null_float()) + { + m_condition_column_idx = column_ndx; + m_dT = 1.0; + } + + void table_changed() override + { + m_condition_column.init(&get_column(m_condition_column_idx)); + } + + void verify_column() const override + { + do_verify_column(m_condition_column.m_column); + } + + void init() override + { + ParentNode::init(); + m_dD = 100.0; + } + + size_t find_first_local(size_t start, size_t end) override + { + TConditionFunction cond; + + auto find = [&](bool nullability) { + bool m_value_nan = nullability ? null::is_null_float(m_value) : false; + for (size_t s = start; s < end; ++s) { + TConditionValue v = m_condition_column.get_next(s); + REALM_ASSERT(!(null::is_null_float(v) && !nullability)); + if (cond(v, m_value, nullability ? null::is_null_float(v) : false, m_value_nan)) + return s; + } + return not_found; + }; + + // This will inline the second case but no the first. Todo, use templated lambda when switching to c++14 + if (m_table->is_nullable(m_condition_column_idx)) + return find(true); + else + return find(false); + } + + virtual std::string describe(util::serializer::SerialisationState& state) const override + { + REALM_ASSERT(m_condition_column.m_column != nullptr); + return state.describe_column(ParentNode::m_table, m_condition_column.m_column->get_column_index()) + + " " + describe_condition() + " " + util::serializer::print_value(FloatDoubleNode::m_value); + } + virtual std::string describe_condition() const override + { + return TConditionFunction::description(); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new FloatDoubleNode(*this, patches)); + } + + FloatDoubleNode(const FloatDoubleNode& from, QueryNodeHandoverPatches* patches) + : ParentNode(from, patches) + , m_value(from.m_value) + { + copy_getter(m_condition_column, m_condition_column_idx, from.m_condition_column, patches); + } + +protected: + TConditionValue m_value; + SequentialGetter m_condition_column; +}; + +template +class SizeNode : public ParentNode { +public: + SizeNode(int64_t v, size_t column) + : m_value(v) + { + m_condition_column_idx = column; + } + + void table_changed() override + { + m_condition_column = &get_column(m_condition_column_idx); + } + + void verify_column() const override + { + do_verify_column(m_condition_column); + } + + void init() override + { + ParentNode::init(); + m_dD = 10.0; + } + + size_t find_first_local(size_t start, size_t end) override + { + for (size_t s = start; s < end; ++s) { + TConditionValue v = m_condition_column->get(s); + if (v) { + int64_t sz = m_size_operator(v); + if (TConditionFunction()(sz, m_value)) + return s; + } + } + return not_found; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new SizeNode(*this, patches)); + } + + SizeNode(const SizeNode& from, QueryNodeHandoverPatches* patches) + : ParentNode(from, patches) + , m_value(from.m_value) + , m_condition_column(from.m_condition_column) + { + if (m_condition_column && patches) + m_condition_column_idx = m_condition_column->get_column_index(); + } + +private: + using TConditionValue = typename ColType::value_type; + + int64_t m_value; + const ColType* m_condition_column = nullptr; + Size m_size_operator; +}; + + +template +class BinaryNode : public ParentNode { +public: + using TConditionValue = BinaryData; + static const bool special_null_node = false; + + BinaryNode(BinaryData v, size_t column) + : m_value(v) + { + m_dT = 100.0; + m_condition_column_idx = column; + } + + BinaryNode(null, size_t column) + : BinaryNode(BinaryData{}, column) + { + } + + void table_changed() override + { + m_condition_column = &get_column(m_condition_column_idx); + } + + void verify_column() const override + { + do_verify_column(m_condition_column); + } + + void init() override + { + ParentNode::init(); + + m_dD = 100.0; + } + + size_t find_first_local(size_t start, size_t end) override + { + TConditionFunction condition; + for (size_t s = start; s < end; ++s) { + BinaryData value = m_condition_column->get(s); + if (condition(m_value.get(), value)) + return s; + } + return not_found; + } + + virtual std::string describe(util::serializer::SerialisationState& state) const override + { + REALM_ASSERT(m_condition_column != nullptr); + return state.describe_column(ParentNode::m_table, m_condition_column->get_column_index()) + + " " + TConditionFunction::description() + " " + + util::serializer::print_value(BinaryNode::m_value.get()); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new BinaryNode(*this, patches)); + } + + BinaryNode(const BinaryNode& from, QueryNodeHandoverPatches* patches) + : ParentNode(from, patches) + , m_value(from.m_value) + , m_condition_column(from.m_condition_column) + { + if (m_condition_column && patches) + m_condition_column_idx = m_condition_column->get_column_index(); + } + +private: + OwnedBinaryData m_value; + const BinaryColumn* m_condition_column; +}; + + +template +class TimestampNode : public ParentNode { +public: + using TConditionValue = Timestamp; + static const bool special_null_node = false; + + TimestampNode(Timestamp v, size_t column) + : m_value(v) + { + m_condition_column_idx = column; + } + + TimestampNode(null, size_t column) + : TimestampNode(Timestamp{}, column) + { + } + + void table_changed() override + { + m_condition_column = &get_column(m_condition_column_idx); + } + + void verify_column() const override + { + do_verify_column(m_condition_column); + } + + void init() override + { + ParentNode::init(); + + m_dD = 100.0; + } + + size_t find_first_local(size_t start, size_t end) override + { + size_t ret = m_condition_column->find(m_value, start, end); + return ret; + } + + virtual std::string describe(util::serializer::SerialisationState& state) const override + { + REALM_ASSERT(m_condition_column != nullptr); + return state.describe_column(ParentNode::m_table, m_condition_column->get_column_index()) + + " " + TConditionFunction::description() + " " + util::serializer::print_value(TimestampNode::m_value); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new TimestampNode(*this, patches)); + } + + TimestampNode(const TimestampNode& from, QueryNodeHandoverPatches* patches) + : ParentNode(from, patches) + , m_value(from.m_value) + , m_condition_column(from.m_condition_column) + { + if (m_condition_column && patches) + m_condition_column_idx = m_condition_column->get_column_index(); + } + +private: + Timestamp m_value; + const TimestampColumn* m_condition_column; +}; + +class StringNodeBase : public ParentNode { +public: + using TConditionValue = StringData; + static const bool special_null_node = true; + + StringNodeBase(StringData v, size_t column) + : m_value(v.is_null() ? util::none : util::make_optional(std::string(v))) + { + m_condition_column_idx = column; + } + + void table_changed() override + { + m_condition_column = &get_column_base(m_condition_column_idx); + m_column_type = get_real_column_type(m_condition_column_idx); + } + + void verify_column() const override + { + do_verify_column(m_condition_column); + } + + void init() override + { + ParentNode::init(); + + m_dT = 10.0; + m_probes = 0; + m_matches = 0; + m_end_s = 0; + m_leaf_start = 0; + m_leaf_end = 0; + } + + void clear_leaf_state() + { + m_leaf.reset(nullptr); + } + + StringNodeBase(const StringNodeBase& from, QueryNodeHandoverPatches* patches) + : ParentNode(from, patches) + , m_value(from.m_value) + , m_condition_column(from.m_condition_column) + , m_column_type(from.m_column_type) + , m_leaf_type(from.m_leaf_type) + { + if (m_condition_column && patches) + m_condition_column_idx = m_condition_column->get_column_index(); + } + + virtual std::string describe(util::serializer::SerialisationState& state) const override + { + REALM_ASSERT(m_condition_column != nullptr); + StringData sd; + if (bool(StringNodeBase::m_value)) { + sd = StringData(StringNodeBase::m_value.value()); + } + return state.describe_column(ParentNode::m_table, m_condition_column->get_column_index()) + + " " + describe_condition() + " " + util::serializer::print_value(sd); + } + +protected: + util::Optional m_value; + + const ColumnBase* m_condition_column = nullptr; + ColumnType m_column_type; + + // Used for linear scan through short/long-string + std::unique_ptr m_leaf; + StringColumn::LeafType m_leaf_type; + size_t m_end_s = 0; + size_t m_leaf_start = 0; + size_t m_leaf_end = 0; + + inline StringData get_string(size_t s) + { + StringData t; + + if (m_column_type == col_type_StringEnum) { + // enum + t = static_cast(m_condition_column)->get(s); + } + else { + // short or long + const StringColumn* asc = static_cast(m_condition_column); + REALM_ASSERT_3(s, <, asc->size()); + if (s >= m_end_s || s < m_leaf_start) { + // we exceeded current leaf's range + clear_leaf_state(); + size_t ndx_in_leaf; + m_leaf = asc->get_leaf(s, ndx_in_leaf, m_leaf_type); + m_leaf_start = s - ndx_in_leaf; + + if (m_leaf_type == StringColumn::leaf_type_Small) + m_end_s = m_leaf_start + static_cast(*m_leaf).size(); + else if (m_leaf_type == StringColumn::leaf_type_Medium) + m_end_s = m_leaf_start + static_cast(*m_leaf).size(); + else + m_end_s = m_leaf_start + static_cast(*m_leaf).size(); + } + + if (m_leaf_type == StringColumn::leaf_type_Small) + t = static_cast(*m_leaf).get(s - m_leaf_start); + else if (m_leaf_type == StringColumn::leaf_type_Medium) + t = static_cast(*m_leaf).get(s - m_leaf_start); + else + t = static_cast(*m_leaf).get_string(s - m_leaf_start); + } + return t; + } +}; + +// Conditions for strings. Note that Equal is specialized later in this file! +template +class StringNode : public StringNodeBase { +public: + StringNode(StringData v, size_t column) + : StringNodeBase(v, column) + { + auto upper = case_map(v, true); + auto lower = case_map(v, false); + if (!upper || !lower) { + error_code = "Malformed UTF-8: " + std::string(v); + } + else { + m_ucase = std::move(*upper); + m_lcase = std::move(*lower); + } + } + + void init() override + { + clear_leaf_state(); + + m_dD = 100.0; + + StringNodeBase::init(); + } + + + size_t find_first_local(size_t start, size_t end) override + { + TConditionFunction cond; + + for (size_t s = start; s < end; ++s) { + StringData t = get_string(s); + + if (cond(StringData(m_value), m_ucase.data(), m_lcase.data(), t)) + return s; + } + return not_found; + } + + virtual std::string describe_condition() const override + { + return TConditionFunction::description(); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new StringNode(*this, patches)); + } + + StringNode(const StringNode& from, QueryNodeHandoverPatches* patches) + : StringNodeBase(from, patches) + , m_ucase(from.m_ucase) + , m_lcase(from.m_lcase) + { + } + +protected: + std::string m_ucase; + std::string m_lcase; +}; + +// Specialization for Contains condition on Strings - we specialize because we can utilize Boyer-Moore +template <> +class StringNode : public StringNodeBase { +public: + StringNode(StringData v, size_t column) + : StringNodeBase(v, column), m_charmap() + { + if (v.size() == 0) + return; + + // Build a dictionary of char-to-last distances in the search string + // (zero indicates that the char is not in needle) + size_t last_char_pos = v.size()-1; + for (size_t i = 0; i < last_char_pos; ++i) { + // we never jump longer increments than 255 chars, even if needle is longer (to fit in one byte) + uint8_t jump = last_char_pos-i < 255 ? static_cast(last_char_pos-i) : 255; + + unsigned char c = v[i]; + m_charmap[c] = jump; + } + } + + void init() override + { + clear_leaf_state(); + + m_dD = 100.0; + + StringNodeBase::init(); + } + + + size_t find_first_local(size_t start, size_t end) override + { + Contains cond; + + for (size_t s = start; s < end; ++s) { + StringData t = get_string(s); + + if (cond(StringData(m_value), m_charmap, t)) + return s; + } + return not_found; + } + + virtual std::string describe_condition() const override + { + return Contains::description(); + } + + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new StringNode(*this, patches)); + } + + StringNode(const StringNode& from, QueryNodeHandoverPatches* patches) + : StringNodeBase(from, patches) + , m_charmap(from.m_charmap) + { + } + +protected: + std::array m_charmap; +}; + +// Specialization for ContainsIns condition on Strings - we specialize because we can utilize Boyer-Moore +template <> +class StringNode : public StringNodeBase { +public: + StringNode(StringData v, size_t column) + : StringNodeBase(v, column), m_charmap() + { + auto upper = case_map(v, true); + auto lower = case_map(v, false); + if (!upper || !lower) { + error_code = "Malformed UTF-8: " + std::string(v); + } + else { + m_ucase = std::move(*upper); + m_lcase = std::move(*lower); + } + + if (v.size() == 0) + return; + + // Build a dictionary of char-to-last distances in the search string + // (zero indicates that the char is not in needle) + size_t last_char_pos = m_ucase.size()-1; + for (size_t i = 0; i < last_char_pos; ++i) { + // we never jump longer increments than 255 chars, even if needle is longer (to fit in one byte) + uint8_t jump = last_char_pos-i < 255 ? static_cast(last_char_pos-i) : 255; + + unsigned char uc = m_ucase[i]; + unsigned char lc = m_lcase[i]; + m_charmap[uc] = jump; + m_charmap[lc] = jump; + } + + } + + void init() override + { + clear_leaf_state(); + + m_dD = 100.0; + + StringNodeBase::init(); + } + + + size_t find_first_local(size_t start, size_t end) override + { + ContainsIns cond; + + for (size_t s = start; s < end; ++s) { + StringData t = get_string(s); + // The current behaviour is to return all results when querying for a null string. + // See comment above Query_NextGen_StringConditions on why every string including "" contains null. + if (!bool(m_value)) { + return s; + } + if (cond(StringData(m_value), m_ucase.data(), m_lcase.data(), m_charmap, t)) + return s; + } + return not_found; + } + + virtual std::string describe_condition() const override + { + return ContainsIns::description(); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new StringNode(*this, patches)); + } + + StringNode(const StringNode& from, QueryNodeHandoverPatches* patches) + : StringNodeBase(from, patches) + , m_charmap(from.m_charmap) + , m_ucase(from.m_ucase) + , m_lcase(from.m_lcase) + { + } + +protected: + std::array m_charmap; + std::string m_ucase; + std::string m_lcase; +}; + +class StringNodeEqualBase : public StringNodeBase { +public: + StringNodeEqualBase(StringData v, size_t column) + : StringNodeBase(v, column) + { + } + StringNodeEqualBase(const StringNodeEqualBase& from, QueryNodeHandoverPatches* patches) + : StringNodeBase(from, patches) + { + } + ~StringNodeEqualBase() noexcept override + { + deallocate(); + } + + void deallocate() noexcept; + void init() override; + size_t find_first_local(size_t start, size_t end) override; + + virtual std::string describe_condition() const override + { + return Equal::description(); + } + +protected: + inline BinaryData str_to_bin(const StringData& s) noexcept + { + return BinaryData(s.data(), s.size()); + } + + virtual void _search_index_init() = 0; + virtual size_t _find_first_local(size_t start, size_t end) = 0; + + size_t m_key_ndx = not_found; + size_t m_last_indexed; + + // Used for linear scan through enum-string + SequentialGetter m_cse; + + // Used for index lookup + std::unique_ptr m_index_matches; + bool m_index_matches_destroy = false; + std::unique_ptr> m_index_getter; + size_t m_results_start; + size_t m_results_end; + size_t m_last_start; +}; + + +// Specialization for Equal condition on Strings - we specialize because we can utilize indexes (if they exist) for +// Equal. +// Future optimization: make specialization for greater, notequal, etc +template <> +class StringNode : public StringNodeEqualBase { +public: + using StringNodeEqualBase::StringNodeEqualBase; + + void _search_index_init() override; + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new StringNode(*this, patches)); + } + +private: + size_t _find_first_local(size_t start, size_t end) override; +}; + + +// Specialization for EqualIns condition on Strings - we specialize because we can utilize indexes (if they exist) for +// EqualIns. +template <> +class StringNode : public StringNodeEqualBase { +public: + StringNode(StringData v, size_t column) + : StringNodeEqualBase(v, column) + { + auto upper = case_map(v, true); + auto lower = case_map(v, false); + if (!upper || !lower) { + error_code = "Malformed UTF-8: " + std::string(v); + } + else { + m_ucase = std::move(*upper); + m_lcase = std::move(*lower); + } + } + + void _search_index_init() override; + + virtual std::string describe_condition() const override + { + return EqualIns::description(); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new StringNode(*this, patches)); + } + + StringNode(const StringNode& from, QueryNodeHandoverPatches* patches) + : StringNodeEqualBase(from, patches) + , m_ucase(from.m_ucase) + , m_lcase(from.m_lcase) + { + } + +private: + std::string m_ucase; + std::string m_lcase; + + size_t _find_first_local(size_t start, size_t end) override; +}; + + +// OR node contains at least two node pointers: Two or more conditions to OR +// together in m_conditions, and the next AND condition (if any) in m_child. +// +// For 'second.equal(23).begin_group().first.equal(111).Or().first.equal(222).end_group().third().equal(555)', this +// will first set m_conditions[0] = left-hand-side through constructor, and then later, when .first.equal(222) is +// invoked, invocation will set m_conditions[1] = right-hand-side through Query& Query::Or() (see query.cpp). +// In there, m_child is also set to next AND condition (if any exists) following the OR. +class OrNode : public ParentNode { +public: + OrNode(std::unique_ptr condition) + { + m_dT = 50.0; + if (condition) + m_conditions.emplace_back(std::move(condition)); + } + + OrNode(const OrNode& other, QueryNodeHandoverPatches* patches) + : ParentNode(other, patches) + { + for (const auto& condition : other.m_conditions) { + m_conditions.emplace_back(condition->clone(patches)); + } + } + + void table_changed() override + { + for (auto& condition : m_conditions) { + condition->set_table(*m_table); + } + } + + void verify_column() const override + { + for (auto& condition : m_conditions) { + condition->verify_column(); + } + } + std::string describe(util::serializer::SerialisationState& state) const override + { + if (m_conditions.size() >= 2) { + + } + std::string s; + for (size_t i = 0; i < m_conditions.size(); ++i) { + if (m_conditions[i]) { + s += m_conditions[i]->describe_expression(state); + if (i != m_conditions.size() - 1) { + s += " or "; + } + } + } + if (m_conditions.size() > 1) { + s = "(" + s + ")"; + } + return s; + } + + + void init() override + { + ParentNode::init(); + + m_dD = 10.0; + + m_start.clear(); + m_start.resize(m_conditions.size(), 0); + + m_last.clear(); + m_last.resize(m_conditions.size(), 0); + + m_was_match.clear(); + m_was_match.resize(m_conditions.size(), false); + + std::vector v; + for (auto& condition : m_conditions) { + condition->init(); + v.clear(); + condition->gather_children(v); + } + } + + size_t find_first_local(size_t start, size_t end) override + { + if (start >= end) + return not_found; + + size_t index = not_found; + + for (size_t c = 0; c < m_conditions.size(); ++c) { + // out of order search; have to discard cached results + if (start < m_start[c]) { + m_last[c] = 0; + m_was_match[c] = false; + } + // already searched this range and didn't match + else if (m_last[c] >= end) + continue; + // already search this range and *did* match + else if (m_was_match[c] && m_last[c] >= start) { + if (index > m_last[c]) + index = m_last[c]; + continue; + } + + m_start[c] = start; + size_t fmax = std::max(m_last[c], start); + size_t f = m_conditions[c]->find_first(fmax, end); + m_was_match[c] = f != not_found; + m_last[c] = f == not_found ? end : f; + if (f != not_found && index > m_last[c]) + index = m_last[c]; + } + + return index; + } + + std::string validate() override + { + if (error_code != "") + return error_code; + if (m_conditions.size() == 0) + return "Missing left-hand side of OR"; + if (m_conditions.size() == 1) + return "Missing right-hand side of OR"; + std::string s; + if (m_child != 0) + s = m_child->validate(); + if (s != "") + return s; + for (size_t i = 0; i < m_conditions.size(); ++i) { + s = m_conditions[i]->validate(); + if (s != "") + return s; + } + return ""; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new OrNode(*this, patches)); + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + for (auto it = m_conditions.rbegin(); it != m_conditions.rend(); ++it) + (*it)->apply_handover_patch(patches, group); + + ParentNode::apply_handover_patch(patches, group); + } + + std::vector> m_conditions; + +private: + // start index of the last find for each cond + std::vector m_start; + // last looked at index of the lasft find for each cond + // is a matching index if m_was_match is true + std::vector m_last; + std::vector m_was_match; +}; + + +class NotNode : public ParentNode { +public: + NotNode(std::unique_ptr condition) + : m_condition(std::move(condition)) + { + m_dT = 50.0; + } + + void table_changed() override + { + m_condition->set_table(*m_table); + } + + void verify_column() const override + { + m_condition->verify_column(); + } + + void init() override + { + ParentNode::init(); + + m_dD = 10.0; + + std::vector v; + + m_condition->init(); + v.clear(); + m_condition->gather_children(v); + + // Heuristics bookkeeping: + m_known_range_start = 0; + m_known_range_end = 0; + m_first_in_known_range = not_found; + } + + size_t find_first_local(size_t start, size_t end) override; + + std::string validate() override + { + if (error_code != "") + return error_code; + if (m_condition == 0) + return "Missing argument to Not"; + std::string s; + if (m_child != 0) + s = m_child->validate(); + if (s != "") + return s; + s = m_condition->validate(); + if (s != "") + return s; + return ""; + } + + virtual std::string describe(util::serializer::SerialisationState& state) const override + { + if (m_condition) { + return "!(" + m_condition->describe_expression(state) + ")"; + } + return "!()"; + } + + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new NotNode(*this, patches)); + } + + NotNode(const NotNode& from, QueryNodeHandoverPatches* patches) + : ParentNode(from, patches) + , m_condition(from.m_condition ? from.m_condition->clone(patches) : nullptr) + , m_known_range_start(from.m_known_range_start) + , m_known_range_end(from.m_known_range_end) + , m_first_in_known_range(from.m_first_in_known_range) + { + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + m_condition->apply_handover_patch(patches, group); + ParentNode::apply_handover_patch(patches, group); + } + + std::unique_ptr m_condition; + +private: + // FIXME This heuristic might as well be reused for all condition nodes. + size_t m_known_range_start; + size_t m_known_range_end; + size_t m_first_in_known_range; + + bool evaluate_at(size_t rowndx); + void update_known(size_t start, size_t end, size_t first); + size_t find_first_loop(size_t start, size_t end); + size_t find_first_covers_known(size_t start, size_t end); + size_t find_first_covered_by_known(size_t start, size_t end); + size_t find_first_overlap_lower(size_t start, size_t end); + size_t find_first_overlap_upper(size_t start, size_t end); + size_t find_first_no_overlap(size_t start, size_t end); +}; + + +// Compare two columns with eachother row-by-row +template +class TwoColumnsNode : public ParentNode { +public: + using TConditionValue = typename ColType::value_type; + + TwoColumnsNode(size_t column1, size_t column2) + { + m_dT = 100.0; + m_condition_column_idx1 = column1; + m_condition_column_idx2 = column2; + } + + ~TwoColumnsNode() noexcept override + { + delete[] m_value.data(); + } + + void table_changed() override + { + m_getter1.init(&get_column(m_condition_column_idx1)); + m_getter2.init(&get_column(m_condition_column_idx2)); + } + + void verify_column() const override + { + do_verify_column(m_getter1.m_column, m_condition_column_idx1); + do_verify_column(m_getter2.m_column, m_condition_column_idx2); + } + + virtual std::string describe(util::serializer::SerialisationState& state) const override + { + REALM_ASSERT(m_getter1.m_column != nullptr && m_getter2.m_column != nullptr); + return state.describe_column(ParentNode::m_table, m_getter1.m_column->get_column_index()) + + " " + describe_condition() + " " + + state.describe_column(ParentNode::m_table,m_getter2.m_column->get_column_index()); + } + + virtual std::string describe_condition() const override + { + return TConditionFunction::description(); + } + + void init() override + { + ParentNode::init(); + m_dD = 100.0; + } + + size_t find_first_local(size_t start, size_t end) override + { + size_t s = start; + + while (s < end) { + if (std::is_same::value) { + // For int64_t we've created an array intrinsics named compare_leafs which template expands bitwidths + // of boths arrays to make Get faster. + m_getter1.cache_next(s); + m_getter2.cache_next(s); + + QueryState qs; + bool resume = m_getter1.m_leaf_ptr->template compare_leafs( + m_getter2.m_leaf_ptr, s - m_getter1.m_leaf_start, m_getter1.local_end(end), 0, &qs, + CallbackDummy()); + + if (resume) + s = m_getter1.m_leaf_end; + else + return to_size_t(qs.m_state) + m_getter1.m_leaf_start; + } + else { +// This is for float and double. + +#if 0 && defined(REALM_COMPILER_AVX) +// AVX has been disabled because of array alignment (see https://app.asana.com/0/search/8836174089724/5763107052506) +// +// For AVX you can call things like if (sseavx<1>()) to test for AVX, and then utilize _mm256_movemask_ps (VC) +// or movemask_cmp_ps (gcc/clang) +// +// See https://github.com/rrrlasse/realm/tree/AVX for an example of utilizing AVX for a two-column search which has +// been benchmarked to: floats: 288 ms vs 552 by using AVX compared to 2-level-unrolled FPU loop. doubles: 415 ms vs +// 475 (more bandwidth bound). Tests against SSE have not been performed; AVX may not pay off. Please benchmark +#endif + + TConditionValue v1 = m_getter1.get_next(s); + TConditionValue v2 = m_getter2.get_next(s); + TConditionFunction C; + + if (C(v1, v2)) + return s; + else + s++; + } + } + return not_found; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new TwoColumnsNode(*this, patches)); + } + + TwoColumnsNode(const TwoColumnsNode& from, QueryNodeHandoverPatches* patches) + : ParentNode(from, patches) + , m_value(from.m_value) + , m_condition_column(from.m_condition_column) + , m_column_type(from.m_column_type) + , m_condition_column_idx1(from.m_condition_column_idx1) + , m_condition_column_idx2(from.m_condition_column_idx2) + { + if (m_condition_column) + m_condition_column_idx = m_condition_column->get_column_index(); + copy_getter(m_getter1, m_condition_column_idx1, from.m_getter1, patches); + copy_getter(m_getter2, m_condition_column_idx2, from.m_getter2, patches); + } + +private: + BinaryData m_value; + const BinaryColumn* m_condition_column = nullptr; + ColumnType m_column_type; + + size_t m_condition_column_idx1 = not_found; + size_t m_condition_column_idx2 = not_found; + + SequentialGetter m_getter1; + SequentialGetter m_getter2; +}; + + +// For Next-Generation expressions like col1 / col2 + 123 > col4 * 100. +class ExpressionNode : public ParentNode { + +public: + ExpressionNode(std::unique_ptr); + + size_t find_first_local(size_t start, size_t end) override; + + void table_changed() override; + void verify_column() const override; + + virtual std::string describe(util::serializer::SerialisationState& state) const override; + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override; + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override; + +private: + ExpressionNode(const ExpressionNode& from, QueryNodeHandoverPatches* patches); + + std::unique_ptr m_expression; +}; + + +struct LinksToNodeHandoverPatch : public QueryNodeHandoverPatch { + std::unique_ptr m_target_row; + size_t m_origin_column; +}; + +class LinksToNode : public ParentNode { +public: + LinksToNode(size_t origin_column_index, const ConstRow& target_row) + : m_origin_column(origin_column_index) + , m_target_row(target_row) + { + m_dD = 10.0; + m_dT = 50.0; + } + + void table_changed() override + { + m_column_type = m_table->get_column_type(m_origin_column); + m_column = &const_cast(m_table.get())->get_column_link_base(m_origin_column); + REALM_ASSERT(m_column_type == type_Link || m_column_type == type_LinkList); + } + + void verify_column() const override + { + do_verify_column(m_column, m_origin_column); + } + + virtual std::string describe(util::serializer::SerialisationState&) const override + { + throw SerialisationError("Serialising a query which links to an object is currently unsupported."); + // We can do something like the following when core gets stable keys + //return describe_column() + " " + describe_condition() + " " + util::serializer::print_value(m_target_row.get_index()); + } + virtual std::string describe_condition() const override + { + return "links to"; + } + + + size_t find_first_local(size_t start, size_t end) override + { + REALM_ASSERT(m_column); + if (!m_target_row.is_attached()) + return not_found; + + if (m_column_type == type_Link) { + LinkColumn& cl = static_cast(*m_column); + return cl.find_first(m_target_row.get_index() + 1, start, + end); // LinkColumn stores link to row N as the integer N + 1 + } + else if (m_column_type == type_LinkList) { + LinkListColumn& cll = static_cast(*m_column); + + for (size_t i = start; i < end; i++) { + LinkViewRef lv = cll.get(i); + if (lv->find(m_target_row.get_index()) != not_found) + return i; + } + } + + return not_found; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(patches ? new LinksToNode(*this, patches) : new LinksToNode(*this)); + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + REALM_ASSERT(patches.size()); + std::unique_ptr abstract_patch = std::move(patches.back()); + patches.pop_back(); + + auto patch = dynamic_cast(abstract_patch.get()); + REALM_ASSERT(patch); + + m_origin_column = patch->m_origin_column; + m_target_row.apply_and_consume_patch(patch->m_target_row, group); + + ParentNode::apply_handover_patch(patches, group); + } + +private: + size_t m_origin_column = npos; + ConstRow m_target_row; + LinkColumnBase* m_column = nullptr; + DataType m_column_type; + + LinksToNode(const LinksToNode& source, QueryNodeHandoverPatches* patches) + : ParentNode(source, patches) + { + auto patch = std::make_unique(); + patch->m_origin_column = source.m_column->get_column_index(); + ConstRow::generate_patch(source.m_target_row, patch->m_target_row); + patches->push_back(std::move(patch)); + } +}; + +} // namespace realm + +#endif // REALM_QUERY_ENGINE_HPP diff --git a/Pods/Realm/include/core/realm/query_expression.hpp b/Pods/Realm/include/core/realm/query_expression.hpp new file mode 100644 index 0000000000..330cc03657 --- /dev/null +++ b/Pods/Realm/include/core/realm/query_expression.hpp @@ -0,0 +1,3892 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +/* +This file lets you write queries in C++ syntax like: Expression* e = (first + 1 / second >= third + 12.3); + +Type conversion/promotion semantics is the same as in the C++ expressions, e.g float + int > double == float + +(float)int > double. + + +Grammar: +----------------------------------------------------------------------------------------------------------------------- + Expression: Subexpr2 Compare Subexpr2 + operator! Expression + + Subexpr2: Value + Columns + Subexpr2 Operator Subexpr2 + power(Subexpr2) // power(x) = x * x, as example of unary operator + + Value: T + + Operator>: +, -, *, / + + Compare: ==, !=, >=, <=, >, < + + T: bool, int, int64_t, float, double, StringData + + +Class diagram +----------------------------------------------------------------------------------------------------------------------- +Subexpr2 + void evaluate(size_t i, ValueBase* destination) + +Compare: public Subexpr2 + size_t find_first(size_t start, size_t end) // main method that executes query + + unique_ptr m_left; // left expression subtree + unique_ptr m_right; // right expression subtree + +Operator: public Subexpr2 + void evaluate(size_t i, ValueBase* destination) + unique_ptr m_left; // left expression subtree + unique_ptr m_right; // right expression subtree + +Value: public Subexpr2 + void evaluate(size_t i, ValueBase* destination) + T m_v[8]; + +Columns: public Subexpr2 + void evaluate(size_t i, ValueBase* destination) + SequentialGetter sg; // class bound to a column, lets you read values in a fast way + Table* m_table; + +class ColumnAccessor<>: public Columns + + +Call diagram: +----------------------------------------------------------------------------------------------------------------------- +Example of 'table.first > 34.6 + table.second': + +size_t Compare::find_first()-------------+ + | | + | | + | | + +--> Columns::evaluate() +--------> Operator::evaluate() + | | + Value::evaluate() Columns::evaluate() + +Operator, Value and Columns have an evaluate(size_t i, ValueBase* destination) method which returns a Value +containing 8 values representing table rows i...i + 7. + +So Value contains 8 concecutive values and all operations are based on these chunks. This is +to save overhead by virtual calls needed for evaluating a query that has been dynamically constructed at runtime. + + +Memory allocation: +----------------------------------------------------------------------------------------------------------------------- +Subexpressions created by the end-user are stack allocated. They are cloned to the heap when passed to UnaryOperator, +Operator, and Compare. Those types own the clones and deallocate them when destroyed. + + +Caveats, notes and todos +----------------------------------------------------------------------------------------------------------------------- + * Perhaps disallow columns from two different tables in same expression + * The name Columns (with s) an be confusing because we also have Column (without s) + * We have Columns::m_table, Query::m_table and ColumnAccessorBase::m_table that point at the same thing, even with + ColumnAccessor<> extending Columns. So m_table is redundant, but this is in order to keep class dependencies and + entanglement low so that the design is flexible (if you perhaps later want a Columns class that is not dependent + on ColumnAccessor) + +Nulls +----------------------------------------------------------------------------------------------------------------------- +First note that at array level, nulls are distinguished between non-null in different ways: +String: + m_data == 0 && m_size == 0 + +Integer, Bool, OldDateTime stored in ArrayIntNull: + value == get(0) (entry 0 determins a magic value that represents nulls) + +Float/double: + null::is_null(value) which tests if value bit-matches one specific bit pattern reserved for null + +The Columns class encapsulates all this into a simple class that, for any type T has + evaluate(size_t index) that reads values from a column, taking nulls in count + get(index) + set(index) + is_null(index) + set_null(index) +*/ + +#ifndef REALM_QUERY_EXPRESSION_HPP +#define REALM_QUERY_EXPRESSION_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// Normally, if a next-generation-syntax condition is supported by the old query_engine.hpp, a query_engine node is +// created because it's faster (by a factor of 5 - 10). Because many of our existing next-generation-syntax unit +// unit tests are indeed simple enough to fallback to old query_engine, query_expression gets low test coverage. Undef +// flag to get higher query_expression test coverage. This is a good idea to try out each time you develop on/modify +// query_expression. + +#define REALM_OLDQUERY_FALLBACK + +namespace realm { + +template +T minimum(T a, T b) +{ + return a < b ? a : b; +} + +#ifdef REALM_OLDQUERY_FALLBACK +// Hack to avoid template instantiation errors. See create(). Todo, see if we can simplify only_numeric somehow +namespace _impl { + +template +inline T only_numeric(U in) +{ + return static_cast(util::unwrap(in)); +} + +template +inline int only_numeric(const StringData&) +{ + REALM_ASSERT(false); + return 0; +} + +template +inline int only_numeric(const BinaryData&) +{ + REALM_ASSERT(false); + return 0; +} + +template +inline StringData only_string_op_types(T in) +{ + REALM_ASSERT(false); + static_cast(in); + return StringData(); +} + +inline BinaryData only_string_op_types(BinaryData in) +{ + return in; +} + +template <> +inline StringData only_string_op_types(StringData in) +{ + return in; +} + +template +inline T no_timestamp(U in) +{ + return static_cast(util::unwrap(in)); +} + +template +inline int no_timestamp(const Timestamp&) +{ + REALM_ASSERT(false); + return 0; +} + +} // namespace _impl + +#endif // REALM_OLDQUERY_FALLBACK + +template +struct Plus { + T operator()(T v1, T v2) const + { + return v1 + v2; + } + static std::string description() + { + return "+"; + } + typedef T type; +}; + +template +struct Minus { + T operator()(T v1, T v2) const + { + return v1 - v2; + } + static std::string description() + { + return "-"; + } + typedef T type; +}; + +template +struct Div { + T operator()(T v1, T v2) const + { + return v1 / v2; + } + static std::string description() + { + return "/"; + } + typedef T type; +}; + +template +struct Mul { + T operator()(T v1, T v2) const + { + return v1 * v2; + } + static std::string description() + { + return "*"; + } + typedef T type; +}; + +// Unary operator +template +struct Pow { + T operator()(T v) const + { + return v * v; + } + static std::string description() + { + return "^"; + } + typedef T type; +}; + +// Finds a common type for T1 and T2 according to C++ conversion/promotion in arithmetic (float + int => float, etc) +template ::is_integer || std::is_same::value, + bool T2_is_int = std::numeric_limits::is_integer || std::is_same::value, + bool T1_is_widest = (sizeof(T1) > sizeof(T2) || std::is_same::value)> +struct Common; +template +struct Common { + typedef T1 type; +}; +template +struct Common { + typedef T2 type; +}; +template +struct Common { + typedef T1 type; +}; +template +struct Common { + typedef T2 type; +}; + + +struct RowIndex { + enum DetachedTag { + Detached, + }; + + explicit RowIndex() + : m_row_index(npos) + { + } + explicit RowIndex(size_t row_index) + : m_row_index(row_index) + { + } + RowIndex(DetachedTag) + : m_row_index() + { + } + + bool is_attached() const + { + return bool(m_row_index); + } + bool is_null() const + { + return is_attached() && *m_row_index == npos; + } + + bool operator==(const RowIndex& other) const + { + // Row indexes that are detached are never equal to any other row index. + if (!is_attached() || !other.is_attached()) + return false; + return m_row_index == other.m_row_index; + } + bool operator!=(const RowIndex& other) const + { + return !(*this == other); + } +private: + util::Optional m_row_index; +}; + +struct ValueBase { + static const size_t default_size = 8; + virtual void export_bool(ValueBase& destination) const = 0; + virtual void export_Timestamp(ValueBase& destination) const = 0; + virtual void export_int(ValueBase& destination) const = 0; + virtual void export_float(ValueBase& destination) const = 0; + virtual void export_int64_t(ValueBase& destination) const = 0; + virtual void export_double(ValueBase& destination) const = 0; + virtual void export_StringData(ValueBase& destination) const = 0; + virtual void export_BinaryData(ValueBase& destination) const = 0; + virtual void export_RowIndex(ValueBase& destination) const = 0; + virtual void export_null(ValueBase& destination) const = 0; + virtual void import(const ValueBase& destination) = 0; + + // If true, all values in the class come from a link list of a single field in the parent table (m_table). If + // false, then values come from successive rows of m_table (query operations are operated on in bulks for speed) + bool m_from_link_list; + + // Number of values stored in the class. + size_t m_values; +}; + +class Expression { +public: + Expression() + { + } + virtual ~Expression() + { + } + + virtual size_t find_first(size_t start, size_t end) const = 0; + virtual void set_base_table(const Table* table) = 0; + virtual void verify_column() const = 0; + virtual const Table* get_base_table() const = 0; + virtual std::string description(util::serializer::SerialisationState& state) const = 0; + + virtual std::unique_ptr clone(QueryNodeHandoverPatches*) const = 0; + virtual void apply_handover_patch(QueryNodeHandoverPatches&, Group&) + { + } +}; + +template +std::unique_ptr make_expression(Args&&... args) +{ + return std::unique_ptr(new T(std::forward(args)...)); +} + +class Subexpr { +public: + virtual ~Subexpr() + { + } + + virtual std::unique_ptr clone(QueryNodeHandoverPatches* = nullptr) const = 0; + virtual void apply_handover_patch(QueryNodeHandoverPatches&, Group&) + { + } + + // When the user constructs a query, it always "belongs" to one single base/parent table (regardless of + // any links or not and regardless of any queries assembled with || or &&). When you do a Query::find(), + // then Query::m_table is set to this table, and set_base_table() is called on all Columns and LinkMaps in + // the query expression tree so that they can set/update their internals as required. + // + // During thread-handover of a Query, set_base_table() is also called to make objects point at the new table + // instead of the old one from the old thread. + virtual void set_base_table(const Table*) + { + } + + virtual void verify_column() const = 0; + virtual std::string description(util::serializer::SerialisationState& state) const = 0; + + // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression + // and + // binds it to a Query at a later time + virtual const Table* get_base_table() const + { + return nullptr; + } + + virtual void evaluate(size_t index, ValueBase& destination) = 0; +}; + +template +std::unique_ptr make_subexpr(Args&&... args) +{ + return std::unique_ptr(new T(std::forward(args)...)); +} + +template +class Columns; +template +class Value; +class ConstantStringValue; +template +class Subexpr2; +template +class Operator; +template +class UnaryOperator; +template +class SizeOperator; +template +class Compare; +template +class UnaryLinkCompare; +class ColumnAccessorBase; + + +// Handle cases where left side is a constant (int, float, int64_t, double, StringData) +template +Query create(L left, const Subexpr2& right) +{ +// Purpose of below code is to intercept the creation of a condition and test if it's supported by the old +// query_engine.hpp which is faster. If it's supported, create a query_engine.hpp node, otherwise create a +// query_expression.hpp node. +// +// This method intercepts only Value Subexpr2. Interception of Subexpr2 Subexpr is elsewhere. + +#ifdef REALM_OLDQUERY_FALLBACK // if not defined, then never fallback to query_engine.hpp; always use query_expression + const Columns* column = dynamic_cast*>(&right); + // TODO: recognize size operator expressions + // auto size_operator = dynamic_cast, Subexpr>*>(&right); + + if (column && ((std::numeric_limits::is_integer && std::numeric_limits::is_integer) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value)) && + !column->links_exist()) { + const Table* t = column->get_base_table(); + Query q = Query(*t); + + if (std::is_same::value) + q.greater(column->column_ndx(), _impl::only_numeric(left)); + else if (std::is_same::value) + q.less(column->column_ndx(), _impl::only_numeric(left)); + else if (std::is_same::value) + q.equal(column->column_ndx(), left); + else if (std::is_same::value) + q.not_equal(column->column_ndx(), left); + else if (std::is_same::value) + q.greater_equal(column->column_ndx(), _impl::only_numeric(left)); + else if (std::is_same::value) + q.less_equal(column->column_ndx(), _impl::only_numeric(left)); + else if (std::is_same::value) + q.equal(column->column_ndx(), _impl::only_string_op_types(left), false); + else if (std::is_same::value) + q.not_equal(column->column_ndx(), _impl::only_string_op_types(left), false); + else if (std::is_same::value) + q.begins_with(column->column_ndx(), _impl::only_string_op_types(left)); + else if (std::is_same::value) + q.begins_with(column->column_ndx(), _impl::only_string_op_types(left), false); + else if (std::is_same::value) + q.ends_with(column->column_ndx(), _impl::only_string_op_types(left)); + else if (std::is_same::value) + q.ends_with(column->column_ndx(), _impl::only_string_op_types(left), false); + else if (std::is_same::value) + q.contains(column->column_ndx(), _impl::only_string_op_types(left)); + else if (std::is_same::value) + q.contains(column->column_ndx(), _impl::only_string_op_types(left), false); + else if (std::is_same::value) + q.like(column->column_ndx(), _impl::only_string_op_types(left)); + else if (std::is_same::value) + q.like(column->column_ndx(), _impl::only_string_op_types(left), false); + else { + // query_engine.hpp does not support this Cond. Please either add support for it in query_engine.hpp or + // fallback to using use 'return new Compare<>' instead. + REALM_ASSERT(false); + } + // Return query_engine.hpp node + return q; + } + else +#endif + { + // Return query_expression.hpp node + using CommonType = typename Common::type; + using ValueType = + typename std::conditional::value, ConstantStringValue, Value>::type; + return make_expression>(make_subexpr(left), right.clone()); + } +} + + +// All overloads where left-hand-side is Subexpr2: +// +// left-hand-side operator right-hand-side +// Subexpr2 +, -, *, /, <, >, ==, !=, <=, >= R, Subexpr2 +// +// For L = R = {int, int64_t, float, double, StringData, Timestamp}: +template +class Overloads { + typedef typename Common::type CommonType; + + std::unique_ptr clone_subexpr() const + { + return static_cast&>(*this).clone(); + } + +public: + // Arithmetic, right side constant + Operator> operator+(R right) const + { + return {clone_subexpr(), make_subexpr>(right)}; + } + Operator> operator-(R right) const + { + return {clone_subexpr(), make_subexpr>(right)}; + } + Operator> operator*(R right) const + { + return {clone_subexpr(), make_subexpr>(right)}; + } + Operator> operator/(R right) const + { + return {clone_subexpr(), make_subexpr>(right)}; + } + + // Arithmetic, right side subexpression + Operator> operator+(const Subexpr2& right) const + { + return {clone_subexpr(), right.clone()}; + } + Operator> operator-(const Subexpr2& right) const + { + return {clone_subexpr(), right.clone()}; + } + Operator> operator*(const Subexpr2& right) const + { + return {clone_subexpr(), right.clone()}; + } + Operator> operator/(const Subexpr2& right) const + { + return {clone_subexpr(), right.clone()}; + } + + // Compare, right side constant + Query operator>(R right) + { + return create(right, static_cast&>(*this)); + } + Query operator<(R right) + { + return create(right, static_cast&>(*this)); + } + Query operator>=(R right) + { + return create(right, static_cast&>(*this)); + } + Query operator<=(R right) + { + return create(right, static_cast&>(*this)); + } + Query operator==(R right) + { + return create(right, static_cast&>(*this)); + } + Query operator!=(R right) + { + return create(right, static_cast&>(*this)); + } + + // Purpose of this method is to intercept the creation of a condition and test if it's supported by the old + // query_engine.hpp which is faster. If it's supported, create a query_engine.hpp node, otherwise create a + // query_expression.hpp node. + // + // This method intercepts Subexpr2 Subexpr2 only. Value Subexpr2 is intercepted elsewhere. + template + Query create2(const Subexpr2& right) + { +#ifdef REALM_OLDQUERY_FALLBACK // if not defined, never fallback query_engine; always use query_expression + // Test if expressions are of type Columns. Other possibilities are Value and Operator. + const Columns* left_col = dynamic_cast*>(static_cast*>(this)); + const Columns* right_col = dynamic_cast*>(&right); + + // query_engine supports 'T-column ' for T = {int64_t, float, double}, op = {<, >, ==, !=, <=, + // >=}, + // but only if both columns are non-nullable, and aren't in linked tables. + if (left_col && right_col && std::is_same::value && !left_col->is_nullable() && + !right_col->is_nullable() && !left_col->links_exist() && !right_col->links_exist() && + !std::is_same::value) { + const Table* t = left_col->get_base_table(); + Query q = Query(*t); + + if (std::numeric_limits::is_integer || std::is_same::value) { + if (std::is_same::value) + q.less_int(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.greater_int(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.equal_int(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.not_equal_int(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.less_equal_int(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.greater_equal_int(left_col->column_ndx(), right_col->column_ndx()); + else { + REALM_ASSERT(false); + } + } + else if (std::is_same::value) { + if (std::is_same::value) + q.less_float(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.greater_float(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.equal_float(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.not_equal_float(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.less_equal_float(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.greater_equal_float(left_col->column_ndx(), right_col->column_ndx()); + else { + REALM_ASSERT(false); + } + } + else if (std::is_same::value) { + if (std::is_same::value) + q.less_double(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.greater_double(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.equal_double(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.not_equal_double(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.less_equal_double(left_col->column_ndx(), right_col->column_ndx()); + else if (std::is_same::value) + q.greater_equal_double(left_col->column_ndx(), right_col->column_ndx()); + else { + REALM_ASSERT(false); + } + } + else { + REALM_ASSERT(false); + } + // Return query_engine.hpp node + return q; + } + else +#endif + { + // Return query_expression.hpp node + return make_expression::type>>(clone_subexpr(), right.clone()); + } + } + + // Compare, right side subexpression + Query operator==(const Subexpr2& right) + { + return create2(right); + } + Query operator!=(const Subexpr2& right) + { + return create2(right); + } + Query operator>(const Subexpr2& right) + { + return create2(right); + } + Query operator<(const Subexpr2& right) + { + return create2(right); + } + Query operator>=(const Subexpr2& right) + { + return create2(right); + } + Query operator<=(const Subexpr2& right) + { + return create2(right); + } +}; + +// With this wrapper class we can define just 20 overloads inside Overloads instead of 5 * 20 = 100. Todo: We +// can +// consider if it's simpler/better to remove this class completely and just list all 100 overloads manually anyway. +template +class Subexpr2 : public Subexpr, + public Overloads, + public Overloads, + public Overloads, + public Overloads, + public Overloads, + public Overloads, + public Overloads, + public Overloads, + public Overloads, + public Overloads { +public: + virtual ~Subexpr2() + { + } + +#define RLM_U2(t, o) using Overloads::operator o; +#define RLM_U(o) \ + RLM_U2(int, o) \ + RLM_U2(float, o) \ + RLM_U2(double, o) \ + RLM_U2(int64_t, o) \ + RLM_U2(StringData, o) RLM_U2(bool, o) RLM_U2(OldDateTime, o) RLM_U2(Timestamp, o) RLM_U2(null, o) + RLM_U(+) RLM_U(-) RLM_U(*) RLM_U(/) RLM_U(>) RLM_U(<) RLM_U(==) RLM_U(!=) RLM_U(>=) RLM_U(<=) +}; + +// Subexpr2 only provides equality comparisons. Their implementations can be found later in this file. +template <> +class Subexpr2 : public Subexpr { +}; + +template <> +class Subexpr2 : public Subexpr, public Overloads { +public: + Query equal(StringData sd, bool case_sensitive = true); + Query equal(const Subexpr2& col, bool case_sensitive = true); + Query not_equal(StringData sd, bool case_sensitive = true); + Query not_equal(const Subexpr2& col, bool case_sensitive = true); + Query begins_with(StringData sd, bool case_sensitive = true); + Query begins_with(const Subexpr2& col, bool case_sensitive = true); + Query ends_with(StringData sd, bool case_sensitive = true); + Query ends_with(const Subexpr2& col, bool case_sensitive = true); + Query contains(StringData sd, bool case_sensitive = true); + Query contains(const Subexpr2& col, bool case_sensitive = true); + Query like(StringData sd, bool case_sensitive = true); + Query like(const Subexpr2& col, bool case_sensitive = true); +}; + +template <> +class Subexpr2 : public Subexpr, public Overloads { +public: + Query equal(BinaryData sd, bool case_sensitive = true); + Query equal(const Subexpr2& col, bool case_sensitive = true); + Query not_equal(BinaryData sd, bool case_sensitive = true); + Query not_equal(const Subexpr2& col, bool case_sensitive = true); + Query begins_with(BinaryData sd, bool case_sensitive = true); + Query begins_with(const Subexpr2& col, bool case_sensitive = true); + Query ends_with(BinaryData sd, bool case_sensitive = true); + Query ends_with(const Subexpr2& col, bool case_sensitive = true); + Query contains(BinaryData sd, bool case_sensitive = true); + Query contains(const Subexpr2& col, bool case_sensitive = true); + Query like(BinaryData sd, bool case_sensitive = true); + Query like(const Subexpr2& col, bool case_sensitive = true); +}; + + +/* +This class is used to store N values of type T = {int64_t, bool, OldDateTime or StringData}, and allows an entry +to be null too. It's used by the Value class for internal storage. + +To indicate nulls, we could have chosen a separate bool vector or some other bitmask construction. But for +performance, we customize indication of nulls to match the same indication that is used in the persisted database +file + +Queries in query_expression.hpp execute by processing chunks of 8 rows at a time. Assume you have a column: + + price (int) = {1, 2, 3, null, 1, 6, 6, 9, 5, 2, null} + +And perform a query: + + Query q = (price + 2 == 5); + +query_expression.hpp will then create a NullableVector = {5, 5, 5, 5, 5, 5, 5, 5} and then read values +NullableVector = {1, 2, 3, null, 1, 6, 6, 9} from the column, and then perform `+` and `==` on these chunks. + +See the top of this file for more information on all this. + +Assume the user specifies the null constant in a query: + +Query q = (price == null) + +The query system will then construct a NullableVector of type `null` (NullableVector). This allows compile +time optimizations for these cases. +*/ + +template +struct NullableVector { + using Underlying = typename util::RemoveOptional::type; + using t_storage = + typename std::conditional::value || std::is_same::value, + int64_t, Underlying>::type; + + NullableVector() + { + } + + NullableVector& operator=(const NullableVector& other) + { + if (this != &other) { + init(other.m_size); + realm::safe_copy_n(other.m_first, other.m_size, m_first); + m_null = other.m_null; + } + return *this; + } + + NullableVector(const NullableVector& other) + { + init(other.m_size); + realm::safe_copy_n(other.m_first, other.m_size, m_first); + m_null = other.m_null; + } + + ~NullableVector() + { + dealloc(); + } + + T operator[](size_t index) const + { + REALM_ASSERT_3(index, <, m_size); + return static_cast(m_first[index]); + } + + inline bool is_null(size_t index) const + { + REALM_ASSERT((std::is_same::value)); + return m_first[index] == m_null; + } + + inline void set_null(size_t index) + { + REALM_ASSERT((std::is_same::value)); + m_first[index] = m_null; + } + + template + typename std::enable_if::value, void>::type set(size_t index, t_storage value) + { + REALM_ASSERT((std::is_same::value)); + + // If value collides with magic null value, then switch to a new unique representation for null + if (REALM_UNLIKELY(value == m_null)) { + // adding a prime will generate 2^64 unique values. Todo: Only works on 2's complement architecture + uint64_t candidate = static_cast(m_null) + 0xfffffffbULL; + while (std::find(m_first, m_first + m_size, static_cast(candidate)) != m_first + m_size) + candidate += 0xfffffffbULL; + std::replace(m_first, m_first + m_size, m_null, static_cast(candidate)); + } + m_first[index] = value; + } + + template + typename std::enable_if::value, + void>::type + set(size_t index, t_storage value) + { + m_first[index] = value; + } + + inline util::Optional get(size_t index) const + { + if (is_null(index)) + return util::none; + + return util::make_optional((*this)[index]); + } + + inline void set(size_t index, util::Optional value) + { + if (value) { + Underlying v = *value; + set(index, v); + } + else { + set_null(index); + } + } + + void fill(T value) + { + for (size_t t = 0; t < m_size; t++) { + if (std::is_same::value) + set_null(t); + else + set(t, value); + } + } + + void init(size_t size) + { + if (size == m_size) + return; + + dealloc(); + m_size = size; + if (m_size > 0) { + if (m_size > prealloc) + m_first = reinterpret_cast(new t_storage[m_size]); + else + m_first = m_cache; + } + } + + void init(size_t size, T values) + { + init(size); + fill(values); + } + + void dealloc() + { + if (m_first) { + if (m_size > prealloc) + delete[] m_first; + m_first = nullptr; + } + } + + t_storage m_cache[prealloc]; + t_storage* m_first = &m_cache[0]; + size_t m_size = 0; + + int64_t m_null = reinterpret_cast(&m_null); // choose magic value to represent nulls +}; + +// Double +// NOTE: fails in gcc 4.8 without `inline`. Do not remove. Same applies for all methods below. +template <> +inline bool NullableVector::is_null(size_t index) const +{ + return null::is_null_float(m_first[index]); +} + +template <> +inline void NullableVector::set_null(size_t index) +{ + m_first[index] = null::get_null_float(); +} + +// Float +template <> +inline bool NullableVector::is_null(size_t index) const +{ + return null::is_null_float(m_first[index]); +} + +template <> +inline void NullableVector::set_null(size_t index) +{ + m_first[index] = null::get_null_float(); +} + + +// Null +template <> +inline void NullableVector::set_null(size_t) +{ + return; +} +template <> +inline bool NullableVector::is_null(size_t) const +{ + return true; +} + + +// OldDateTime +template <> +inline bool NullableVector::is_null(size_t index) const +{ + return m_first[index].get_olddatetime() == m_null; +} + + +template <> +inline void NullableVector::set_null(size_t index) +{ + m_first[index] = m_null; +} + +// StringData + +template <> +inline bool NullableVector::is_null(size_t index) const +{ + return m_first[index].is_null(); +} + +template <> +inline void NullableVector::set_null(size_t index) +{ + m_first[index] = StringData(); +} + +// BinaryData + +template <> +inline bool NullableVector::is_null(size_t index) const +{ + return m_first[index].is_null(); +} + +template <> +inline void NullableVector::set_null(size_t index) +{ + m_first[index] = BinaryData(); +} + +// RowIndex +template <> +inline bool NullableVector::is_null(size_t index) const +{ + return m_first[index].is_null(); +} +template <> +inline void NullableVector::set_null(size_t index) +{ + m_first[index] = RowIndex(); +} + + +// Timestamp + +template <> +inline bool NullableVector::is_null(size_t index) const +{ + return m_first[index].is_null(); +} + +template <> +inline void NullableVector::set_null(size_t index) +{ + m_first[index] = Timestamp{}; +} + +// ConstTableRef +template <> +inline bool NullableVector::is_null(size_t index) const +{ + return !bool(m_first[index]); +} +template <> +inline void NullableVector::set_null(size_t index) +{ + m_first[index].reset(); +} + +template +struct OperatorOptionalAdapter { + template + util::Optional operator()(const util::Optional& left, const util::Optional& right) + { + if (!left || !right) + return util::none; + return Operator()(*left, *right); + } + + template + util::Optional operator()(const util::Optional& arg) + { + if (!arg) + return util::none; + return Operator()(*arg); + } +}; + + +struct TrueExpression : Expression { + size_t find_first(size_t start, size_t end) const override + { + REALM_ASSERT(start <= end); + if (start != end) + return start; + + return realm::not_found; + } + void set_base_table(const Table*) override + { + } + const Table* get_base_table() const override + { + return nullptr; + } + void verify_column() const override + { + } + std::string description(util::serializer::SerialisationState&) const override + { + return "TRUEPREDICATE"; + } + std::unique_ptr clone(QueryNodeHandoverPatches*) const override + { + return std::unique_ptr(new TrueExpression(*this)); + } +}; + + +struct FalseExpression : Expression { + size_t find_first(size_t, size_t) const override + { + return realm::not_found; + } + void set_base_table(const Table*) override + { + } + void verify_column() const override + { + } + std::string description(util::serializer::SerialisationState&) const override + { + return "FALSEPREDICATE"; + } + const Table* get_base_table() const override + { + return nullptr; + } + std::unique_ptr clone(QueryNodeHandoverPatches*) const override + { + return std::unique_ptr(new FalseExpression(*this)); + } +}; + + +// Stores N values of type T. Can also exchange data with other ValueBase of different types +template +class Value : public ValueBase, public Subexpr2 { +public: + Value() + { + init(false, ValueBase::default_size, T()); + } + Value(T v) + { + init(false, ValueBase::default_size, v); + } + + Value(bool from_link_list, size_t values) + { + init(from_link_list, values, T()); + } + + Value(bool from_link_list, size_t values, T v) + { + init(from_link_list, values, v); + } + + Value(const Value&) = default; + Value& operator=(const Value&) = default; + + void init(bool from_link_list, size_t values, T v) + { + m_storage.init(values, v); + ValueBase::m_from_link_list = from_link_list; + ValueBase::m_values = values; + } + + void init(bool from_link_list, size_t values) + { + m_storage.init(values); + ValueBase::m_from_link_list = from_link_list; + ValueBase::m_values = values; + } + + void verify_column() const override + { + } + + virtual std::string description(util::serializer::SerialisationState&) const override + { + if (ValueBase::m_from_link_list) { + return util::serializer::print_value(util::to_string(ValueBase::m_values) + + (ValueBase::m_values == 1 ? " value" : " values")); + } + if (m_storage.m_size > 0) { + return util::serializer::print_value(m_storage[0]); + } + return ""; + } + + void evaluate(size_t, ValueBase& destination) override + { + destination.import(*this); + } + + + template + REALM_FORCEINLINE void fun(const Value* left, const Value* right) + { + OperatorOptionalAdapter o; + + if (!left->m_from_link_list && !right->m_from_link_list) { + // Operate on values one-by-one (one value is one row; no links) + size_t min = std::min(left->m_values, right->m_values); + init(false, min); + + for (size_t i = 0; i < min; i++) { + m_storage.set(i, o(left->m_storage.get(i), right->m_storage.get(i))); + } + } + else if (left->m_from_link_list && right->m_from_link_list) { + // FIXME: Many-to-many links not supported yet. Need to specify behaviour + REALM_ASSERT_DEBUG(false); + } + else if (!left->m_from_link_list && right->m_from_link_list) { + // Right values come from link. Left must come from single row. + REALM_ASSERT_DEBUG(left->m_values > 0); + init(true, right->m_values); + + auto left_value = left->m_storage.get(0); + for (size_t i = 0; i < right->m_values; i++) { + m_storage.set(i, o(left_value, right->m_storage.get(i))); + } + } + else if (left->m_from_link_list && !right->m_from_link_list) { + // Same as above, but with left values coming from links + REALM_ASSERT_DEBUG(right->m_values > 0); + init(true, left->m_values); + + auto right_value = right->m_storage.get(0); + for (size_t i = 0; i < left->m_values; i++) { + m_storage.set(i, o(left->m_storage.get(i), right_value)); + } + } + } + + template + REALM_FORCEINLINE void fun(const Value* value) + { + init(value->m_from_link_list, value->m_values); + + OperatorOptionalAdapter o; + for (size_t i = 0; i < value->m_values; i++) { + m_storage.set(i, o(value->m_storage.get(i))); + } + } + + + // Below import and export methods are for type conversion between float, double, int64_t, etc. + template + typename std::enable_if::value>::type REALM_FORCEINLINE + export2(ValueBase& destination) const + { + Value& d = static_cast&>(destination); + d.init(ValueBase::m_from_link_list, ValueBase::m_values, D()); + for (size_t t = 0; t < ValueBase::m_values; t++) { + if (m_storage.is_null(t)) + d.m_storage.set_null(t); + else { + d.m_storage.set(t, static_cast(m_storage[t])); + } + } + } + + template + typename std::enable_if::value>::type REALM_FORCEINLINE export2(ValueBase&) const + { + // export2 is instantiated for impossible conversions like T=StringData, D=int64_t. These are never + // performed at runtime but would result in a compiler error if we did not provide this implementation. + REALM_ASSERT_DEBUG(false); + } + + REALM_FORCEINLINE void export_Timestamp(ValueBase& destination) const override + { + export2(destination); + } + + REALM_FORCEINLINE void export_bool(ValueBase& destination) const override + { + export2(destination); + } + + REALM_FORCEINLINE void export_int64_t(ValueBase& destination) const override + { + export2(destination); + } + + REALM_FORCEINLINE void export_float(ValueBase& destination) const override + { + export2(destination); + } + + REALM_FORCEINLINE void export_int(ValueBase& destination) const override + { + export2(destination); + } + + REALM_FORCEINLINE void export_double(ValueBase& destination) const override + { + export2(destination); + } + REALM_FORCEINLINE void export_StringData(ValueBase& destination) const override + { + export2(destination); + } + REALM_FORCEINLINE void export_BinaryData(ValueBase& destination) const override + { + export2(destination); + } + REALM_FORCEINLINE void export_RowIndex(ValueBase& destination) const override + { + export2(destination); + } + REALM_FORCEINLINE void export_null(ValueBase& destination) const override + { + Value& d = static_cast&>(destination); + d.init(m_from_link_list, m_values); + } + + REALM_FORCEINLINE void import(const ValueBase& source) override + { + if (std::is_same::value) + source.export_int(*this); + else if (std::is_same::value) + source.export_Timestamp(*this); + else if (std::is_same::value) + source.export_bool(*this); + else if (std::is_same::value) + source.export_float(*this); + else if (std::is_same::value) + source.export_double(*this); + else if (std::is_same::value || std::is_same::value || + std::is_same::value) + source.export_int64_t(*this); + else if (std::is_same::value) + source.export_StringData(*this); + else if (std::is_same::value) + source.export_BinaryData(*this); + else if (std::is_same::value) + source.export_RowIndex(*this); + else if (std::is_same::value) + source.export_null(*this); + else + REALM_ASSERT_DEBUG(false); + } + + // Given a TCond (==, !=, >, <, >=, <=) and two Value, return index of first match + template + REALM_FORCEINLINE static size_t compare(Value* left, Value* right) + { + TCond c; + + if (!left->m_from_link_list && !right->m_from_link_list) { + // Compare values one-by-one (one value is one row; no link lists) + size_t min = minimum(left->ValueBase::m_values, right->ValueBase::m_values); + for (size_t m = 0; m < min; m++) { + + if (c(left->m_storage[m], right->m_storage[m], left->m_storage.is_null(m), + right->m_storage.is_null(m))) + return m; + } + } + else if (left->m_from_link_list && right->m_from_link_list) { + // FIXME: Many-to-many links not supported yet. Need to specify behaviour + REALM_ASSERT_DEBUG(false); + } + else if (!left->m_from_link_list && right->m_from_link_list) { + // Right values come from link list. Left must come from single row. Semantics: Match if at least 1 + // linked-to-value fulfills the condition + REALM_ASSERT_DEBUG(left->m_values > 0); + for (size_t r = 0; r < right->m_values; r++) { + if (c(left->m_storage[0], right->m_storage[r], left->m_storage.is_null(0), + right->m_storage.is_null(r))) + return 0; + } + } + else if (left->m_from_link_list && !right->m_from_link_list) { + // Same as above, but with left values coming from link list. + REALM_ASSERT_DEBUG(right->m_values > 0); + for (size_t l = 0; l < left->m_values; l++) { + if (c(left->m_storage[l], right->m_storage[0], left->m_storage.is_null(l), + right->m_storage.is_null(0))) + return 0; + } + } + + return not_found; // no match + } + + std::unique_ptr clone(QueryNodeHandoverPatches*) const override + { + return make_subexpr>(*this); + } + + NullableVector m_storage; +}; + +class ConstantStringValue : public Value { +public: + ConstantStringValue(const StringData& string) + : Value() + , m_string(string.is_null() ? util::none : util::make_optional(std::string(string))) + { + init(false, ValueBase::default_size, m_string); + } + + std::unique_ptr clone(QueryNodeHandoverPatches*) const override + { + return std::unique_ptr(new ConstantStringValue(*this)); + } + +private: + ConstantStringValue(const ConstantStringValue& other) + : Value() + , m_string(other.m_string) + { + init(other.m_from_link_list, other.m_values, m_string); + } + + util::Optional m_string; +}; + +// All overloads where left-hand-side is L: +// +// left-hand-side operator right-hand-side +// L +, -, *, /, <, >, ==, !=, <=, >= Subexpr2 +// +// For L = R = {int, int64_t, float, double, Timestamp}: +// Compare numeric values +template +Query operator>(double left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator>(float left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator>(int left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator>(int64_t left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator>(Timestamp left, const Subexpr2& right) +{ + return create(left, right); +} + +template +Query operator<(double left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator<(float left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator<(int left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator<(int64_t left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator<(Timestamp left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator==(double left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator==(float left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator==(int left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator==(int64_t left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator==(Timestamp left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator>=(double left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator>=(float left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator>=(int left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator>=(int64_t left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator>=(Timestamp left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator<=(double left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator<=(float left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator<=(int left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator<=(int64_t left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator<=(Timestamp left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator!=(double left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator!=(float left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator!=(int left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator!=(int64_t left, const Subexpr2& right) +{ + return create(left, right); +} +template +Query operator!=(Timestamp left, const Subexpr2& right) +{ + return create(left, right); +} + +// Arithmetic +template +Operator::type>> operator+(double left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator+(float left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator+(int left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator+(int64_t left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator-(double left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator-(float left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator-(int left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator-(int64_t left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator*(double left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator*(float left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator*(int left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator*(int64_t left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator/(double left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator/(float left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator/(int left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} +template +Operator::type>> operator/(int64_t left, const Subexpr2& right) +{ + return {make_subexpr>(left), right.clone()}; +} + +// Unary operators +template +UnaryOperator> power(const Subexpr2& left) +{ + return {left.clone()}; +} + +// Classes used for LinkMap (see below). +struct LinkMapFunction { + // Your consume() method is given row index of the linked-to table as argument, and you must return whether or + // not you want the LinkMapFunction to exit (return false) or continue (return true) harvesting the link tree + // for the current main table row index (it will be a link tree if you have multiple type_LinkList columns + // in a link()->link() query. + virtual bool consume(size_t row_index) = 0; +}; + +struct FindNullLinks : public LinkMapFunction { + bool consume(size_t row_index) override + { + static_cast(row_index); + m_has_link = true; + return false; // we've found a row index, so this can't be a null-link, so exit link harvesting + } + + bool m_has_link = false; +}; + +struct MakeLinkVector : public LinkMapFunction { + MakeLinkVector(std::vector& result) + : m_links(result) + { + } + + bool consume(size_t row_index) override + { + m_links.push_back(row_index); + return true; // continue evaluation + } + std::vector& m_links; +}; + +struct CountLinks : public LinkMapFunction { + bool consume(size_t) override + { + m_link_count++; + return true; + } + + size_t result() const + { + return m_link_count; + } + + size_t m_link_count = 0; +}; + +struct CountBacklinks : public LinkMapFunction { + CountBacklinks(const Table* t) + : m_table(t) + { + } + + bool consume(size_t row_index) override + { + m_link_count += m_table->get_backlink_count(row_index); + return true; + } + + size_t result() const + { + return m_link_count; + } + + const Table* m_table; + size_t m_link_count = 0; +}; + + +/* +The LinkMap and LinkMapFunction classes are used for query conditions on links themselves (contrary to conditions on +the value payload they point at). + +MapLink::map_links() takes a row index of the link column as argument and follows any link chain stated in the query +(through the link()->link() methods) until the final payload table is reached, and then applies LinkMapFunction on +the linked-to row index(es). + +If all link columns are type_Link, then LinkMapFunction is only invoked for a single row index. If one or more +columns are type_LinkList, then it may result in multiple row indexes. + +The reason we use this map pattern is that we can exit the link-tree-traversal as early as possible, e.g. when we've +found the first link that points to row '5'. Other solutions could be a std::vector harvest_all_links(), or an +iterator pattern. First solution can't exit, second solution requires internal state. +*/ +class LinkMap { +public: + LinkMap() = default; + LinkMap(const Table* table, std::vector columns) + : m_link_column_indexes(std::move(columns)) + { + set_base_table(table); + } + + LinkMap(LinkMap const& other, QueryNodeHandoverPatches* patches) + : LinkMap(other) + { + if (!patches) + return; + + m_link_column_indexes.clear(); + const Table* table = base_table(); + m_tables.clear(); + for (auto column : m_link_columns) { + m_link_column_indexes.push_back(column->get_column_index()); + if (table->get_real_column_type(m_link_column_indexes.back()) == col_type_BackLink) + table = &static_cast(column)->get_origin_table(); + else + table = &static_cast(column)->get_target_table(); + } + } + + void set_base_table(const Table* table) + { + if (table == base_table()) + return; + + m_tables.clear(); + m_tables.push_back(table); + m_link_columns.clear(); + m_link_types.clear(); + m_only_unary_links = true; + + for (size_t link_column_index : m_link_column_indexes) { + // Link column can be either LinkList or single Link + const Table* t = m_tables.back(); + ColumnType type = t->get_real_column_type(link_column_index); + REALM_ASSERT(Table::is_link_type(type) || type == col_type_BackLink); + m_link_types.push_back(type); + + if (type == col_type_LinkList) { + const LinkListColumn& cll = t->get_column_link_list(link_column_index); + m_link_columns.push_back(&cll); + m_only_unary_links = false; + m_tables.push_back(&cll.get_target_table()); + } + else if (type == col_type_Link) { + const LinkColumn& cl = t->get_column_link(link_column_index); + m_link_columns.push_back(&cl); + m_tables.push_back(&cl.get_target_table()); + } + else if (type == col_type_BackLink) { + const BacklinkColumn& bl = t->get_column_backlink(link_column_index); + m_link_columns.push_back(&bl); + m_only_unary_links = false; + m_tables.push_back(&bl.get_origin_table()); + } + } + } + + void verify_columns() const + { + for (size_t i = 0; i < m_link_column_indexes.size(); i++) { + m_tables[i]->verify_column(m_link_column_indexes[i], m_link_columns[i]); + } + } + + virtual std::string description(util::serializer::SerialisationState& state) const + { + std::string s; + for (size_t i = 0; i < m_link_column_indexes.size(); ++i) { + if (i < m_tables.size() && m_tables[i]) { + s += state.get_column_name(m_tables[i]->get_table_ref(), m_link_column_indexes[i]); + if (i != m_link_column_indexes.size() - 1) { + s += util::serializer::value_separator; + } + } + } + return s; + } + + std::vector get_links(size_t index) + { + std::vector res; + get_links(index, res); + return res; + } + + size_t count_links(size_t row) + { + CountLinks counter; + map_links(row, counter); + return counter.result(); + } + + size_t count_all_backlinks(size_t row) + { + CountBacklinks counter(target_table()); + map_links(row, counter); + return counter.result(); + } + + void map_links(size_t row, LinkMapFunction& lm) + { + map_links(0, row, lm); + } + + bool only_unary_links() const + { + return m_only_unary_links; + } + + const Table* base_table() const + { + return m_tables.empty() ? nullptr : m_tables[0]; + } + + const Table* target_table() const + { + REALM_ASSERT(!m_tables.empty()); + return m_tables.back(); + } + + bool links_exist() const + { + return !m_link_columns.empty(); + } + + std::vector m_link_columns; + +private: + void map_links(size_t column, size_t row, LinkMapFunction& lm) + { + bool last = (column + 1 == m_link_columns.size()); + ColumnType type = m_link_types[column]; + if (type == col_type_Link) { + const LinkColumn& cl = *static_cast(m_link_columns[column]); + size_t r = to_size_t(cl.get(row)); + if (r == 0) + return; + r--; // LinkColumn stores link to row N as N + 1 + if (last) { + bool continue2 = lm.consume(r); + if (!continue2) + return; + } + else + map_links(column + 1, r, lm); + } + else if (type == col_type_LinkList) { + const LinkListColumn& cll = *static_cast(m_link_columns[column]); + ConstLinkViewRef lvr = cll.get(row); + for (size_t t = 0; t < lvr->size(); t++) { + size_t r = lvr->get(t).get_index(); + if (last) { + bool continue2 = lm.consume(r); + if (!continue2) + return; + } + else + map_links(column + 1, r, lm); + } + } + else if (type == col_type_BackLink) { + const BacklinkColumn& bl = *static_cast(m_link_columns[column]); + size_t count = bl.get_backlink_count(row); + for (size_t i = 0; i < count; ++i) { + size_t r = bl.get_backlink(row, i); + if (last) { + bool continue2 = lm.consume(r); + if (!continue2) + return; + } + else + map_links(column + 1, r, lm); + } + } + } + + + void get_links(size_t row, std::vector& result) + { + MakeLinkVector mlv = MakeLinkVector(result); + map_links(row, mlv); + } + + std::vector m_link_column_indexes; + std::vector m_link_types; + std::vector m_tables; + bool m_only_unary_links = true; + + template + friend Query compare(const Subexpr2&, const ConstRow&); +}; + +template +Query string_compare(const Subexpr2& left, T right, bool case_insensitive); +template +Query string_compare(const Subexpr2& left, const Subexpr2& right, bool case_insensitive); + +template +Value make_value_for_link(bool only_unary_links, size_t size) +{ + Value value; + if (only_unary_links) { + REALM_ASSERT(size <= 1); + value.init(false, 1); + value.m_storage.set_null(0); + } + else { + value.init(true, size); + } + return value; +} + + +// If we add a new Realm type T and quickly want Query support for it, then simply inherit from it like +// `template <> class Columns : public SimpleQuerySupport` and you're done. Any operators of the set +// { ==, >=, <=, !=, >, < } that are supported by T will be supported by the "query expression syntax" +// automatically. NOTE: This method of Query support will be slow because it goes through Table::get. +// To get faster Query support, either add SequentialGetter support (faster) or create a query_engine.hpp +// node for it (super fast). + +template +class SimpleQuerySupport : public Subexpr2 { +public: + SimpleQuerySupport(size_t column, const Table* table, std::vector links = {}) + : m_column_ndx(column) + , m_link_map(table, std::move(links)) + { + m_column = &m_link_map.target_table()->get_column_base(m_column_ndx); + } + + bool is_nullable() const noexcept + { + return m_link_map.base_table()->is_nullable(m_column->get_column_index()); + } + + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + + void set_base_table(const Table* table) override + { + if (table != get_base_table()) { + m_link_map.set_base_table(table); + m_column = &m_link_map.target_table()->get_column_base(m_column_ndx); + } + } + + void verify_column() const override + { + // verify links + m_link_map.verify_columns(); + // verify target table + const Table* target_table = m_link_map.target_table(); + if (target_table && m_column_ndx != npos) { + target_table->verify_column(m_column_ndx, m_column); + } + } + + void evaluate(size_t index, ValueBase& destination) override + { + Value& d = static_cast&>(destination); + size_t col = column_ndx(); + + if (links_exist()) { + std::vector links = m_link_map.get_links(index); + Value v = make_value_for_link(m_link_map.only_unary_links(), links.size()); + + for (size_t t = 0; t < links.size(); t++) { + size_t link_to = links[t]; + v.m_storage.set(t, m_link_map.target_table()->template get(col, link_to)); + } + destination.import(v); + } + else { + // Not a link column + const Table* target_table = m_link_map.target_table(); + for (size_t t = 0; t < destination.m_values && index + t < target_table->size(); t++) { + d.m_storage.set(t, target_table->get(col, index + t)); + } + } + } + + bool links_exist() const + { + return m_link_map.m_link_columns.size() > 0; + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + return state.describe_columns(m_link_map, m_column_ndx); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches = nullptr) const override + { + return make_subexpr>(static_cast&>(*this), patches); + } + + SimpleQuerySupport(SimpleQuerySupport const& other, QueryNodeHandoverPatches* patches) + : Subexpr2(other) + , m_column_ndx(other.m_column_ndx) + , m_column(other.m_column) + , m_link_map(other.m_link_map, patches) + { + if (patches && m_column) { + m_column_ndx = column_ndx(); + m_column = nullptr; + } + } + + size_t column_ndx() const + { + return m_column->get_column_index(); + } + + SizeOperator> size() + { + return SizeOperator>(this->clone(nullptr)); + } + +private: + // Column index of payload column of m_table + mutable size_t m_column_ndx; + const ColumnBase* m_column; + LinkMap m_link_map; +}; + + +template <> +class Columns : public SimpleQuerySupport { + using SimpleQuerySupport::SimpleQuerySupport; +}; + +template <> +class Columns : public SimpleQuerySupport { + using SimpleQuerySupport::SimpleQuerySupport; +}; + +template <> +class Columns : public SimpleQuerySupport { +public: + Columns(size_t column, const Table* table, std::vector links = {}) + : SimpleQuerySupport(column, table, links) + { + } + + Columns(Columns const& other, QueryNodeHandoverPatches* patches = nullptr) + : SimpleQuerySupport(other, patches) + { + } + + Columns(Columns&& other) + : SimpleQuerySupport(other) + { + } +}; + +template +Query string_compare(const Subexpr2& left, T right, bool case_sensitive) +{ + StringData sd(right); + if (case_sensitive) + return create(sd, left); + else + return create(sd, left); +} + +template +Query string_compare(const Subexpr2& left, const Subexpr2& right, bool case_sensitive) +{ + if (case_sensitive) + return make_expression>(right.clone(), left.clone()); + else + return make_expression>(right.clone(), left.clone()); +} + +template +Query binary_compare(const Subexpr2& left, T right, bool case_sensitive) +{ + BinaryData data(right); + if (case_sensitive) + return create(data, left); + else + return create(data, left); +} + +template +Query binary_compare(const Subexpr2& left, const Subexpr2& right, bool case_sensitive) +{ + if (case_sensitive) + return make_expression>(right.clone(), left.clone()); + else + return make_expression>(right.clone(), left.clone()); +} + + +// Columns == Columns +inline Query operator==(const Columns& left, const Columns& right) +{ + return string_compare(left, right, true); +} + +// Columns != Columns +inline Query operator!=(const Columns& left, const Columns& right) +{ + return string_compare(left, right, true); +} + +// String == Columns +template +Query operator==(T left, const Columns& right) +{ + return operator==(right, left); +} + +// String != Columns +template +Query operator!=(T left, const Columns& right) +{ + return operator!=(right, left); +} + +// Columns == String +template +Query operator==(const Columns& left, T right) +{ + return string_compare(left, right, true); +} + +// Columns != String +template +Query operator!=(const Columns& left, T right) +{ + return string_compare(left, right, true); +} + + +inline Query operator==(const Columns& left, BinaryData right) +{ + return create(right, left); +} + +inline Query operator==(BinaryData left, const Columns& right) +{ + return create(left, right); +} + +inline Query operator!=(const Columns& left, BinaryData right) +{ + return create(right, left); +} + +inline Query operator!=(BinaryData left, const Columns& right) +{ + return create(left, right); +} + + +// This class is intended to perform queries on the *pointers* of links, contrary to performing queries on *payload* +// in linked-to tables. Queries can be "find first link that points at row X" or "find first null-link". Currently +// only "find first null link" and "find first non-null link" is supported. More will be added later. When we add +// more, I propose to remove the template argument from this class and instead template it by +// a criteria-class (like the FindNullLinks class below in find_first()) in some generalized fashion. +template +class UnaryLinkCompare : public Expression { +public: + UnaryLinkCompare(LinkMap lm) + : m_link_map(std::move(lm)) + { + } + + void set_base_table(const Table* table) override + { + m_link_map.set_base_table(table); + } + + void verify_column() const override + { + m_link_map.verify_columns(); + } + + // Return main table of query (table on which table->where()... is invoked). Note that this is not the same as + // any linked-to payload tables + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + + size_t find_first(size_t start, size_t end) const override + { + for (; start < end;) { + FindNullLinks fnl; + m_link_map.map_links(start, fnl); + if (fnl.m_has_link == has_links) + return start; + + start++; + } + + return not_found; + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + return state.describe_columns(m_link_map, realm::npos) + (has_links ? " != NULL" : " == NULL"); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new UnaryLinkCompare(*this, patches)); + } + +private: + UnaryLinkCompare(const UnaryLinkCompare& other, QueryNodeHandoverPatches* patches = nullptr) + : Expression(other) + , m_link_map(other.m_link_map, patches) + { + } + + mutable LinkMap m_link_map; +}; + +class LinkCount : public Subexpr2 { +public: + LinkCount(LinkMap link_map) + : m_link_map(std::move(link_map)) + { + } + LinkCount(LinkCount const& other, QueryNodeHandoverPatches* patches) + : Subexpr2(other) + , m_link_map(other.m_link_map, patches) + { + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return make_subexpr(*this, patches); + } + + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + + void set_base_table(const Table* table) override + { + m_link_map.set_base_table(table); + } + + void verify_column() const override + { + m_link_map.verify_columns(); + } + + void evaluate(size_t index, ValueBase& destination) override + { + size_t count = m_link_map.count_links(index); + destination.import(Value(false, 1, count)); + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + return state.describe_columns(m_link_map, realm::npos) + util::serializer::value_separator + "@count"; + } + +private: + LinkMap m_link_map; +}; + +// Gives a count of all backlinks across all columns for the specified row. +// The unused template parameter is a hack to avoid a circular dependency between table.hpp and query_expression.hpp. +template +class BacklinkCount : public Subexpr2 { +public: + BacklinkCount(LinkMap link_map) + : m_link_map(std::move(link_map)) + { + } + BacklinkCount(const Table* table, std::vector links = {}) + : m_link_map(table, std::move(links)) + { + } + BacklinkCount(BacklinkCount const& other, QueryNodeHandoverPatches* patches) + : Subexpr2(other) + , m_link_map(other.m_link_map, patches) + { + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return make_subexpr >(*this, patches); + } + + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + + void set_base_table(const Table* table) override + { + m_link_map.set_base_table(table); + } + + void verify_column() const override + { + m_link_map.verify_columns(); + } + + void evaluate(size_t index, ValueBase& destination) override + { + size_t count; + if (m_link_map.links_exist()) { + count = m_link_map.count_all_backlinks(index); + } + else { + count = m_link_map.target_table()->get_backlink_count(index); + } + destination.import(Value(false, 1, count)); + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + std::string s; + if (m_link_map.links_exist()) { + s += state.describe_columns(m_link_map, realm::npos) + util::serializer::value_separator; + } + s += "@links.@count"; + return s; + } +private: + LinkMap m_link_map; +}; + + +template +class SizeOperator : public Subexpr2 { +public: + SizeOperator(std::unique_ptr left) + : m_expr(std::move(left)) + { + } + + // See comment in base class + void set_base_table(const Table* table) override + { + m_expr->set_base_table(table); + } + + void verify_column() const override + { + m_expr->verify_column(); + } + + // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression + // and binds it to a Query at a later time + const Table* get_base_table() const override + { + return m_expr->get_base_table(); + } + + // destination = operator(left) + void evaluate(size_t index, ValueBase& destination) override + { + REALM_ASSERT_DEBUG(dynamic_cast*>(&destination) != nullptr); + Value* d = static_cast*>(&destination); + REALM_ASSERT(d); + + Value v; + m_expr->evaluate(index, v); + + size_t sz = v.m_values; + d->init(v.m_from_link_list, sz); + + for (size_t i = 0; i < sz; i++) { + auto elem = v.m_storage.get(i); + if (!elem) { + d->m_storage.set_null(i); + } + else { + d->m_storage.set(i, oper()(*elem)); + } + } + } + + std::string description(util::serializer::SerialisationState& state) const override + { + if (m_expr) { + return m_expr->description(state) + util::serializer::value_separator + "@size"; + } + return "@size"; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new SizeOperator(*this, patches)); + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + m_expr->apply_handover_patch(patches, group); + } + +private: + SizeOperator(const SizeOperator& other, QueryNodeHandoverPatches* patches) + : m_expr(other.m_expr->clone(patches)) + { + } + + typedef typename oper::type T; + std::unique_ptr m_expr; +}; + +struct ConstantRowValueHandoverPatch : public QueryNodeHandoverPatch { + std::unique_ptr row_patch; +}; + +class ConstantRowValue : public Subexpr2 { +public: + ConstantRowValue(const ConstRow& row) + : m_row(row) + { + } + + void set_base_table(const Table*) override + { + } + + void verify_column() const override + { + } + + const Table* get_base_table() const override + { + return nullptr; + } + + void evaluate(size_t, ValueBase& destination) override + { + if (m_row.is_attached()) { + Value v(RowIndex(m_row.get_index())); + destination.import(v); + } + else { + Value v(RowIndex::Detached); + destination.import(v); + } + } + + virtual std::string description(util::serializer::SerialisationState&) const override + { + throw SerialisationError("Serialising a query which links to an object is currently unsupported."); + // TODO: we can do something like the following when core gets stable keys: + //if (!m_row.is_attached()) { + // return util::serializer::print_value("detached object"); + //} + //return util::serializer::print_value(m_row.get_index()); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new ConstantRowValue(*this, patches)); + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + REALM_ASSERT(patches.size()); + std::unique_ptr abstract_patch = std::move(patches.back()); + patches.pop_back(); + + auto patch = dynamic_cast(abstract_patch.get()); + REALM_ASSERT(patch); + + m_row.apply_and_consume_patch(patch->row_patch, group); + } + +private: + ConstantRowValue(const ConstantRowValue& source, QueryNodeHandoverPatches* patches) + : m_row(patches ? ConstRow() : source.m_row) + { + if (!patches) + return; + + std::unique_ptr patch(new ConstantRowValueHandoverPatch); + ConstRow::generate_patch(source.m_row, patch->row_patch); + patches->emplace_back(patch.release()); + } + + ConstRow m_row; +}; + +template +class SubColumns; + +// This is for LinkList and BackLink too since they're declared as typedefs of Link. +template <> +class Columns : public Subexpr2 { +public: + Query is_null() + { + if (m_link_map.m_link_columns.size() > 1) + throw util::runtime_error("Combining link() and is_null() is currently not supported"); + // Todo, it may be useful to support the above, but we would need to figure out an intuitive behaviour + return make_expression>(m_link_map); + } + + Query is_not_null() + { + if (m_link_map.m_link_columns.size() > 1) + throw util::runtime_error("Combining link() and is_not_null() is currently not supported"); + // Todo, it may be useful to support the above, but we would need to figure out an intuitive behaviour + return make_expression>(m_link_map); + } + + LinkCount count() const + { + return LinkCount(m_link_map); + } + + template + BacklinkCount backlink_count() const + { + return BacklinkCount(m_link_map); + } + + template + SubColumns column(size_t column_ndx) const + { + return SubColumns(Columns(column_ndx, m_link_map.target_table()), m_link_map); + } + + const LinkMap& link_map() const + { + return m_link_map; + } + + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + void set_base_table(const Table* table) override + { + m_link_map.set_base_table(table); + } + + void verify_column() const override + { + m_link_map.verify_columns(); + } + + std::string description(util::serializer::SerialisationState& state) const override + { + return state.describe_columns(m_link_map, realm::npos); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new Columns(*this, patches)); + } + + void evaluate(size_t index, ValueBase& destination) override; + + +private: + LinkMap m_link_map; + friend class Table; + + Columns(size_t column_ndx, const Table* table, const std::vector& links = {}) + : m_link_map(table, links) + { + static_cast(column_ndx); + } + Columns(const Columns& other, QueryNodeHandoverPatches* patches) + : Subexpr2(other) + , m_link_map(other.m_link_map, patches) + { + } +}; + +template +class ListColumns; +template +class ListColumnAggregate; +namespace aggregate_operations { +template +class Minimum; +template +class Maximum; +template +class Sum; +template +class Average; +} + +template <> +class Columns : public Subexpr2 { +public: + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + + void set_base_table(const Table* table) override + { + m_link_map.set_base_table(table); + m_column = &m_link_map.target_table()->get_column_table(m_column_ndx); + } + + void verify_column() const override + { + m_link_map.verify_columns(); + m_link_map.target_table()->verify_column(m_column_ndx, m_column); + } + + std::string description(util::serializer::SerialisationState&) const override + { + throw SerialisationError("Serialisation of query expressions involving subtables is not yet supported."); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new Columns(*this, patches)); + } + + void evaluate(size_t index, ValueBase& destination) override + { + evaluate_internal(index, destination, ValueBase::default_size); + } + + void evaluate_internal(size_t index, ValueBase& destination, size_t nb_elements); + + template + ListColumns column(size_t ndx) const + { + return ListColumns(ndx, Columns(*this, nullptr)); + } + + template + ListColumns list() const + { + return column(0); + } + + SizeOperator> size() + { + return SizeOperator>(this->clone(nullptr)); + } + +private: + LinkMap m_link_map; + size_t m_column_ndx; + const SubtableColumn* m_column = nullptr; + friend class Table; + template + friend class ListColumnsBase; + template + friend class ListColumnAggregate; + + Columns(size_t column_ndx, const Table* table, const std::vector& links = {}) + : m_link_map(table, links) + , m_column_ndx(column_ndx) + , m_column(&m_link_map.target_table()->get_column_table(column_ndx)) + { + } + + Columns(const Columns& other, QueryNodeHandoverPatches* patches) + : Subexpr2(other) + , m_link_map(other.m_link_map, patches) + , m_column_ndx(other.m_column_ndx) + , m_column(other.m_column) + { + if (m_column && patches) + m_column_ndx = m_column->get_column_index(); + } +}; + +template +class ListColumnsBase : public Subexpr2 { +public: + ListColumnsBase(size_t column_ndx, Columns column) + : m_column_ndx(column_ndx) + , m_subtable_column(std::move(column)) + { + } + + ListColumnsBase(const ListColumnsBase& other, QueryNodeHandoverPatches* patches) + : m_column_ndx(other.m_column_ndx) + , m_subtable_column(other.m_subtable_column, patches) + { + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return make_subexpr>(*this, patches); + } + + const Table* get_base_table() const override + { + return m_subtable_column.get_base_table(); + } + + void set_base_table(const Table* table) override + { + m_subtable_column.set_base_table(table); + } + + void verify_column() const override + { + m_subtable_column.verify_column(); + } + + void evaluate(size_t index, ValueBase& destination) override + { + Value subtables; + m_subtable_column.evaluate_internal(index, subtables, 1); + size_t sz = 0; + for (size_t i = 0; i < subtables.m_values; i++) { + auto val = subtables.m_storage[i]; + if (val) + sz += val->size(); + } + auto v = make_value_for_link::type>(false, sz); + size_t k = 0; + for (size_t i = 0; i < subtables.m_values; i++) { + auto table = subtables.m_storage[i]; + if (table) { + size_t s = table->size(); + for (size_t j = 0; j < s; j++) { + if (!table->is_null(m_column_ndx, j)) { + v.m_storage.set(k++, table->get(m_column_ndx, j)); + } + } + } + } + destination.import(v); + } + + virtual std::string description(util::serializer::SerialisationState&) const override + { + throw SerialisationError("Serialisation of subtable expressions is not yet supported."); + } + + ListColumnAggregate> min() const + { + return {m_column_ndx, m_subtable_column}; + } + + ListColumnAggregate> max() const + { + return {m_column_ndx, m_subtable_column}; + } + + ListColumnAggregate> sum() const + { + return {m_column_ndx, m_subtable_column}; + } + + ListColumnAggregate> average() const + { + return {m_column_ndx, m_subtable_column}; + } + + +private: + // Storing the column index here could be a potential problem if the column + // changes id due to insertion/deletion. + size_t m_column_ndx; + Columns m_subtable_column; +}; + +template +class ListColumns : public ListColumnsBase { +public: + using ListColumnsBase::ListColumnsBase; +}; + +template <> +class ListColumns : public ListColumnsBase { +public: + ListColumns(size_t column_ndx, Columns column) + : ListColumnsBase(column_ndx, column) + { + } + + ListColumns(const ListColumnsBase& other, QueryNodeHandoverPatches* patches) + : ListColumnsBase(other, patches) + { + } + + ListColumns(ListColumns&& other) + : ListColumnsBase(other) + { + } +}; + +template +class ListColumnAggregate : public Subexpr2 { +public: + using R = typename Operation::ResultType; + + ListColumnAggregate(size_t column_ndx, Columns column) + : m_column_ndx(column_ndx) + , m_subtable_column(std::move(column)) + { + } + + ListColumnAggregate(const ListColumnAggregate& other, QueryNodeHandoverPatches* patches) + : m_column_ndx(other.m_column_ndx) + , m_subtable_column(other.m_subtable_column, patches) + { + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return make_subexpr(*this, patches); + } + + const Table* get_base_table() const override + { + return m_subtable_column.get_base_table(); + } + + void set_base_table(const Table* table) override + { + m_subtable_column.set_base_table(table); + } + + void verify_column() const override + { + m_subtable_column.verify_column(); + } + + void evaluate(size_t index, ValueBase& destination) override + { + Value subtables; + m_subtable_column.evaluate_internal(index, subtables, 1); + REALM_ASSERT_DEBUG(subtables.m_values > 0 || subtables.m_from_link_list); + size_t sz = subtables.m_values; + // The result is an aggregate value for each table + auto v = make_value_for_link(!subtables.m_from_link_list, sz); + for (unsigned i = 0; i < sz; i++) { + auto table = subtables.m_storage[i]; + Operation op; + if (table) { + size_t s = table->size(); + for (unsigned j = 0; j < s; j++) { + op.accumulate(table->get(m_column_ndx, j)); + } + } + if (op.is_null()) { + v.m_storage.set_null(i); + } + else { + v.m_storage.set(i, op.result()); + } + } + destination.import(v); + } + + virtual std::string description(util::serializer::SerialisationState&) const override + { + throw SerialisationError("Serialisation of queries involving subtable expressions is not yet supported."); + } + +private: + size_t m_column_ndx; + Columns m_subtable_column; +}; + +template +Query compare(const Subexpr2& left, const ConstRow& row) +{ + static_assert(std::is_same::value || std::is_same::value, + "Links can only be compared for equality."); + const Columns* column = dynamic_cast*>(&left); + if (column) { + const LinkMap& link_map = column->link_map(); + REALM_ASSERT(link_map.target_table() == row.get_table() || !row.is_attached()); +#ifdef REALM_OLDQUERY_FALLBACK + if (link_map.m_link_columns.size() == 1) { + // We can fall back to Query::links_to for != and == operations on links, but only + // for == on link lists. This is because negating query.links_to() is equivalent to + // to "ALL linklist != row" rather than the "ANY linklist != row" semantics we're after. + if (link_map.m_link_types[0] == col_type_Link || + (link_map.m_link_types[0] == col_type_LinkList && std::is_same::value)) { + const Table* t = column->get_base_table(); + Query query(*t); + + if (std::is_same::value) { + // Negate the following `links_to`. + query.Not(); + } + query.links_to(link_map.m_link_column_indexes[0], row); + return query; + } + } +#endif + } + return make_expression>(left.clone(), make_subexpr(row)); +} + +inline Query operator==(const Subexpr2& left, const ConstRow& row) +{ + return compare(left, row); +} +inline Query operator!=(const Subexpr2& left, const ConstRow& row) +{ + return compare(left, row); +} +inline Query operator==(const ConstRow& row, const Subexpr2& right) +{ + return compare(right, row); +} +inline Query operator!=(const ConstRow& row, const Subexpr2& right) +{ + return compare(right, row); +} + +template +Query compare(const Subexpr2& left, null) +{ + static_assert(std::is_same::value || std::is_same::value, + "Links can only be compared for equality."); + return make_expression>(left.clone(), make_subexpr>()); +} + +inline Query operator==(const Subexpr2& left, null) +{ + return compare(left, null()); +} +inline Query operator!=(const Subexpr2& left, null) +{ + return compare(left, null()); +} +inline Query operator==(null, const Subexpr2& right) +{ + return compare(right, null()); +} +inline Query operator!=(null, const Subexpr2& right) +{ + return compare(right, null()); +} + + +template +class Columns : public Subexpr2 { +public: + using ColType = typename ColumnTypeTraits::column_type; + + Columns(size_t column, const Table* table, std::vector links = {}) + : m_link_map(table, std::move(links)) + , m_column_ndx(column) + , m_nullable(m_link_map.target_table()->is_nullable(m_column_ndx)) + { + } + + Columns(const Columns& other, QueryNodeHandoverPatches* patches = nullptr) + : m_link_map(other.m_link_map, patches) + , m_column_ndx(other.m_column_ndx) + , m_nullable(other.m_nullable) + { + if (!other.m_sg) + return; + + if (patches) { + m_column_ndx = other.get_column_base().get_column_index(); + } + else { + if (m_nullable && std::is_same::value) { + init(&other.get_column_base()); + } + else { + init(&other.get_column_base()); + } + } + } + + Columns& operator=(const Columns& other) + { + if (this != &other) { + m_link_map = other.m_link_map; + m_sg.reset(); + m_column_ndx = other.m_column_ndx; + m_nullable = other.m_nullable; + } + return *this; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return make_subexpr>(*this, patches); + } + + // See comment in base class + void set_base_table(const Table* table) override + { + if (m_sg && table == get_base_table()) + return; + + m_link_map.set_base_table(table); + m_nullable = m_link_map.target_table()->is_nullable(m_column_ndx); + + const ColumnBase* c = &m_link_map.target_table()->get_column_base(m_column_ndx); + if (m_nullable && std::is_same::value) { + init(c); + } + else { + init(c); + } + } + + void verify_column() const override + { + // verify links + m_link_map.verify_columns(); + // verify target table + const Table* target_table = m_link_map.target_table(); + if (target_table && m_column_ndx != npos) { + target_table->verify_column(m_column_ndx, &get_column_base()); + } + } + + template + void init(const ColumnBase* c) + { + REALM_ASSERT_DEBUG(dynamic_cast(c)); + if (m_sg == nullptr) { + m_sg.reset(new SequentialGetter()); + } + static_cast&>(*m_sg).init(static_cast(c)); + } + + // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression + // and binds it to a Query at a later time + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + + template + void evaluate_internal(size_t index, ValueBase& destination) + { + REALM_ASSERT_DEBUG(m_sg.get()); + REALM_ASSERT_DEBUG(dynamic_cast*>(m_sg.get())); + + using U = typename ColType2::value_type; + auto sgc = static_cast*>(m_sg.get()); + REALM_ASSERT_DEBUG(sgc->m_column); + + if (links_exist()) { + // LinkList with more than 0 values. Create Value with payload for all fields + + std::vector links = m_link_map.get_links(index); + auto v = make_value_for_link::type>(m_link_map.only_unary_links(), + links.size()); + + for (size_t t = 0; t < links.size(); t++) { + size_t link_to = links[t]; + sgc->cache_next(link_to); + + if (sgc->m_column->is_null(link_to)) + v.m_storage.set_null(t); + else + v.m_storage.set(t, sgc->get_next(link_to)); + } + destination.import(v); + } + else { + // Not a Link column + // make sequential getter load the respective leaf to access data at column row 'index' + sgc->cache_next(index); + size_t colsize = sgc->m_column->size(); + + // Now load `ValueBase::default_size` rows from from the leaf into m_storage. If it's an integer + // leaf, then it contains the method get_chunk() which copies these values in a super fast way (first + // case of the `if` below. Otherwise, copy the values one by one in a for-loop (the `else` case). + if (std::is_same::value && index + ValueBase::default_size <= sgc->m_leaf_end) { + Value v; + + // If you want to modify 'default_size' then update Array::get_chunk() + REALM_ASSERT_3(ValueBase::default_size, ==, 8); + + auto sgc_2 = static_cast*>(m_sg.get()); + sgc_2->m_leaf_ptr->get_chunk(index - sgc->m_leaf_start, v.m_storage.m_first); + + destination.import(v); + } + else { + size_t rows = colsize - index; + if (rows > ValueBase::default_size) + rows = ValueBase::default_size; + Value::type> v(false, rows); + + for (size_t t = 0; t < rows; t++) + v.m_storage.set(t, sgc->get_next(index + t)); + + destination.import(v); + } + } + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + return state.describe_columns(m_link_map, m_column_ndx); + } + + // Load values from Column into destination + void evaluate(size_t index, ValueBase& destination) override + { + if (m_nullable && std::is_same::value) { + evaluate_internal(index, destination); + } + else { + evaluate_internal(index, destination); + } + } + + bool links_exist() const + { + return m_link_map.m_link_columns.size() > 0; + } + + bool is_nullable() const + { + return m_nullable; + } + + size_t column_ndx() const noexcept + { + return m_sg ? get_column_base().get_column_index() : m_column_ndx; + } + +private: + LinkMap m_link_map; + + // Fast (leaf caching) value getter for payload column (column in table on which query condition is executed) + std::unique_ptr m_sg; + + // Column index of payload column of m_table + size_t m_column_ndx; + + // set to false by default for stand-alone Columns declaration that are not yet associated with any table + // or oclumn. Call init() to update it or use a constructor that takes table + column index as argument. + bool m_nullable = false; + + const ColumnBase& get_column_base() const noexcept + { + if (m_nullable && std::is_same::value) + return *static_cast&>(*m_sg).m_column; + else + return *static_cast&>(*m_sg).m_column; + } +}; + +template +class SubColumnAggregate; + +template +class SubColumns : public Subexpr { +public: + SubColumns(Columns column, LinkMap link_map) + : m_column(std::move(column)) + , m_link_map(std::move(link_map)) + { + } + + std::unique_ptr clone(QueryNodeHandoverPatches*) const override + { + return make_subexpr>(*this); + } + + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + + void set_base_table(const Table* table) override + { + m_link_map.set_base_table(table); + m_column.set_base_table(m_link_map.target_table()); + } + + void verify_column() const override + { + m_link_map.verify_columns(); + m_column.verify_column(); + } + + void evaluate(size_t, ValueBase&) override + { + // SubColumns can only be used in an expression in conjunction with its aggregate methods. + REALM_ASSERT(false); + } + + virtual std::string description(util::serializer::SerialisationState&) const override + { + return ""; // by itself there are no conditions, see SubColumnAggregate + } + + SubColumnAggregate> min() const + { + return {m_column, m_link_map}; + } + + SubColumnAggregate> max() const + { + return {m_column, m_link_map}; + } + + SubColumnAggregate> sum() const + { + return {m_column, m_link_map}; + } + + SubColumnAggregate> average() const + { + return {m_column, m_link_map}; + } + +private: + Columns m_column; + LinkMap m_link_map; +}; + +template +class SubColumnAggregate : public Subexpr2 { +public: + SubColumnAggregate(Columns column, LinkMap link_map) + : m_column(std::move(column)) + , m_link_map(std::move(link_map)) + { + } + SubColumnAggregate(SubColumnAggregate const& other, QueryNodeHandoverPatches* patches) + : m_column(other.m_column, patches) + , m_link_map(other.m_link_map, patches) + { + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return make_subexpr(*this, patches); + } + + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + + void set_base_table(const Table* table) override + { + m_link_map.set_base_table(table); + m_column.set_base_table(m_link_map.target_table()); + } + + void verify_column() const override + { + m_link_map.verify_columns(); + m_column.verify_column(); + } + + void evaluate(size_t index, ValueBase& destination) override + { + std::vector links = m_link_map.get_links(index); + std::sort(links.begin(), links.end()); + + Operation op; + for (size_t link_index = 0; link_index < links.size();) { + Value value; + size_t link = links[link_index]; + m_column.evaluate(link, value); + + // Columns::evaluate fetches values in chunks of ValueBase::default_size. Process all values + // within the chunk that came from rows that we link to. + const auto& value_storage = value.m_storage; + for (size_t value_index = 0; value_index < value.m_values;) { + if (!value_storage.is_null(value_index)) { + op.accumulate(value_storage[value_index]); + } + if (++link_index >= links.size()) { + break; + } + + size_t previous_link = link; + link = links[link_index]; + value_index += link - previous_link; + } + } + if (op.is_null()) { + destination.import(Value(false, 1, null())); + } + else { + destination.import(Value(false, 1, op.result())); + } + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + util::serializer::SerialisationState empty_state; + return state.describe_columns(m_link_map, realm::npos) + util::serializer::value_separator + Operation::description() + util::serializer::value_separator + m_column.description(empty_state); + } + +private: + Columns m_column; + LinkMap m_link_map; +}; + +struct SubQueryCountHandoverPatch : QueryNodeHandoverPatch { + QueryHandoverPatch m_query; +}; + +class SubQueryCount : public Subexpr2 { +public: + SubQueryCount(Query q, LinkMap link_map) + : m_query(std::move(q)) + , m_link_map(std::move(link_map)) + { + } + + const Table* get_base_table() const override + { + return m_link_map.base_table(); + } + + void set_base_table(const Table* table) override + { + m_link_map.set_base_table(table); + } + + void verify_column() const override + { + m_link_map.verify_columns(); + } + + void evaluate(size_t index, ValueBase& destination) override + { + std::vector links = m_link_map.get_links(index); + std::sort(links.begin(), links.end()); + + size_t count = std::accumulate(links.begin(), links.end(), size_t(0), [this](size_t running_count, size_t link) { + return running_count + m_query.count(link, link + 1, 1); + }); + + destination.import(Value(false, 1, size_t(count))); + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + REALM_ASSERT(m_link_map.base_table() != nullptr); + std::string target = state.describe_columns(m_link_map, realm::npos); + std::string var_name = state.get_variable_name(m_link_map.base_table()->get_table_ref()); + state.subquery_prefix_list.push_back(var_name); + std::string desc = "SUBQUERY(" + target + ", " + var_name + ", " + m_query.get_description(state) + ")" + + util::serializer::value_separator + "@count"; + state.subquery_prefix_list.pop_back(); + return desc; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + if (patches) + return std::unique_ptr(new SubQueryCount(*this, patches)); + + return make_subexpr(*this); + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + REALM_ASSERT(patches.size()); + std::unique_ptr abstract_patch = std::move(patches.back()); + patches.pop_back(); + + auto patch = dynamic_cast(abstract_patch.get()); + REALM_ASSERT(patch); + + m_query.apply_patch(patch->m_query, group); + } + +private: + SubQueryCount(const SubQueryCount& other, QueryNodeHandoverPatches* patches) + : m_link_map(other.m_link_map, patches) + { + std::unique_ptr patch(new SubQueryCountHandoverPatch); + m_query = Query(other.m_query, patch->m_query, ConstSourcePayload::Copy); + patches->emplace_back(patch.release()); + } + + Query m_query; + LinkMap m_link_map; +}; + +// The unused template parameter is a hack to avoid a circular dependency between table.hpp and query_expression.hpp. +template +class SubQuery { +public: + SubQuery(Columns link_column, Query query) + : m_query(std::move(query)) + , m_link_map(link_column.link_map()) + { + REALM_ASSERT(m_link_map.target_table() == m_query.get_table()); + } + + SubQueryCount count() const + { + return SubQueryCount(m_query, m_link_map); + } + +private: + Query m_query; + LinkMap m_link_map; +}; + +namespace aggregate_operations { +template +class BaseAggregateOperation { + static_assert(std::is_same::value || std::is_same::value || std::is_same::value, + "Numeric aggregates can only be used with subcolumns of numeric types"); + +public: + using ResultType = R; + + void accumulate(T value) + { + m_count++; + m_result = Derived::apply(m_result, value); + } + + bool is_null() const + { + return m_count == 0; + } + ResultType result() const + { + return m_result; + } + +protected: + size_t m_count = 0; + ResultType m_result = Derived::initial_value(); +}; + +template +class Minimum : public BaseAggregateOperation> { +public: + static T initial_value() + { + return std::numeric_limits::max(); + } + static T apply(T a, T b) + { + return std::min(a, b); + } + static std::string description() + { + return "@min"; + } +}; + +template +class Maximum : public BaseAggregateOperation> { +public: + static T initial_value() + { + return std::numeric_limits::min(); + } + static T apply(T a, T b) + { + return std::max(a, b); + } + static std::string description() + { + return "@max"; + } +}; + +template +class Sum : public BaseAggregateOperation> { +public: + static T initial_value() + { + return T(); + } + static T apply(T a, T b) + { + return a + b; + } + bool is_null() const + { + return false; + } + static std::string description() + { + return "@sum"; + } +}; + +template +class Average : public BaseAggregateOperation, double> { + using Base = BaseAggregateOperation, double>; + +public: + static double initial_value() + { + return 0; + } + static double apply(double a, T b) + { + return a + b; + } + double result() const + { + return Base::m_result / Base::m_count; + } + static std::string description() + { + return "@avg"; + } + +}; +} + +template +class UnaryOperator : public Subexpr2 { +public: + UnaryOperator(std::unique_ptr left) + : m_left(std::move(left)) + { + } + + UnaryOperator(const UnaryOperator& other, QueryNodeHandoverPatches* patches) + : m_left(other.m_left->clone(patches)) + { + } + + UnaryOperator& operator=(const UnaryOperator& other) + { + if (this != &other) { + m_left = other.m_left->clone(); + } + return *this; + } + + UnaryOperator(UnaryOperator&&) = default; + UnaryOperator& operator=(UnaryOperator&&) = default; + + // See comment in base class + void set_base_table(const Table* table) override + { + m_left->set_base_table(table); + } + + void verify_column() const override + { + m_left->verify_column(); + } + + // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression + // and binds it to a Query at a later time + const Table* get_base_table() const override + { + return m_left->get_base_table(); + } + + // destination = operator(left) + void evaluate(size_t index, ValueBase& destination) override + { + Value result; + Value left; + m_left->evaluate(index, left); + result.template fun(&left); + destination.import(result); + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + if (m_left) { + return m_left->description(state); + } + return ""; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return make_subexpr(*this, patches); + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + m_left->apply_handover_patch(patches, group); + } + +private: + typedef typename oper::type T; + std::unique_ptr m_left; +}; + + +template +class Operator : public Subexpr2 { +public: + Operator(std::unique_ptr left, std::unique_ptr right) + : m_left(std::move(left)) + , m_right(std::move(right)) + { + } + + Operator(const Operator& other, QueryNodeHandoverPatches* patches) + : m_left(other.m_left->clone(patches)) + , m_right(other.m_right->clone(patches)) + { + } + + Operator& operator=(const Operator& other) + { + if (this != &other) { + m_left = other.m_left->clone(); + m_right = other.m_right->clone(); + } + return *this; + } + + Operator(Operator&&) = default; + Operator& operator=(Operator&&) = default; + + // See comment in base class + void set_base_table(const Table* table) override + { + m_left->set_base_table(table); + m_right->set_base_table(table); + } + + void verify_column() const override + { + m_left->verify_column(); + m_right->verify_column(); + } + + // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression + // and + // binds it to a Query at a later time + const Table* get_base_table() const override + { + const Table* l = m_left->get_base_table(); + const Table* r = m_right->get_base_table(); + + // Queries do not support multiple different tables; all tables must be the same. + REALM_ASSERT(l == nullptr || r == nullptr || l == r); + + // nullptr pointer means expression which isn't yet associated with any table, or is a Value + return l ? l : r; + } + + // destination = operator(left, right) + void evaluate(size_t index, ValueBase& destination) override + { + Value result; + Value left; + Value right; + m_left->evaluate(index, left); + m_right->evaluate(index, right); + result.template fun(&left, &right); + destination.import(result); + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + std::string s; + if (m_left) { + s += m_left->description(state); + } + s += (" " + oper::description() + " "); + if (m_right) { + s += m_right->description(state); + } + return s; + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return make_subexpr(*this, patches); + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + m_right->apply_handover_patch(patches, group); + m_left->apply_handover_patch(patches, group); + } + +private: + typedef typename oper::type T; + std::unique_ptr m_left; + std::unique_ptr m_right; +}; + + +template +class Compare : public Expression { +public: + Compare(std::unique_ptr left, std::unique_ptr right) + : m_left(std::move(left)) + , m_right(std::move(right)) + { + } + + // See comment in base class + void set_base_table(const Table* table) override + { + m_left->set_base_table(table); + m_right->set_base_table(table); + } + + void verify_column() const override + { + m_left->verify_column(); + m_right->verify_column(); + } + + // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression + // and + // binds it to a Query at a later time + const Table* get_base_table() const override + { + const Table* l = m_left->get_base_table(); + const Table* r = m_right->get_base_table(); + + // All main tables in each subexpression of a query (table.columns() or table.link()) must be the same. + REALM_ASSERT(l == nullptr || r == nullptr || l == r); + + // nullptr pointer means expression which isn't yet associated with any table, or is a Value + return l ? l : r; + } + + size_t find_first(size_t start, size_t end) const override + { + size_t match; + Value right; + Value left; + + for (; start < end;) { + m_left->evaluate(start, left); + m_right->evaluate(start, right); + match = Value::template compare(&left, &right); + + if (match != not_found && match + start < end) + return start + match; + + size_t rows = + (left.m_from_link_list || right.m_from_link_list) ? 1 : minimum(right.m_values, left.m_values); + start += rows; + } + + return not_found; // no match + } + + virtual std::string description(util::serializer::SerialisationState& state) const override + { + if (std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value) { + // these string conditions have the arguments reversed but the order is important + // operations ==, and != can be reversed because the produce the same results both ways + return util::serializer::print_value(m_right->description(state) + " " + TCond::description() + + " " + m_left->description(state)); + } + return util::serializer::print_value(m_left->description(state) + " " + TCond::description() + + " " + m_right->description(state)); + } + + std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override + { + return std::unique_ptr(new Compare(*this, patches)); + } + + void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override + { + m_right->apply_handover_patch(patches, group); + m_left->apply_handover_patch(patches, group); + } + +private: + Compare(const Compare& other, QueryNodeHandoverPatches* patches) + : m_left(other.m_left->clone(patches)) + , m_right(other.m_right->clone(patches)) + { + } + + std::unique_ptr m_left; + std::unique_ptr m_right; +}; +} +#endif // REALM_QUERY_EXPRESSION_HPP diff --git a/Pods/Realm/include/core/realm/query_operators.hpp b/Pods/Realm/include/core/realm/query_operators.hpp new file mode 100644 index 0000000000..203af84176 --- /dev/null +++ b/Pods/Realm/include/core/realm/query_operators.hpp @@ -0,0 +1,71 @@ +/************************************************************************* + * + * Copyright 2017 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_QUERY_OPERATORS_HPP +#define REALM_QUERY_OPERATORS_HPP + +#include +#include +#include +#include + +namespace realm { + +// This is not supported in the general case +template +struct Size; + +template <> +struct Size { + int64_t operator()(StringData v) const + { + return v.size(); + } + typedef StringData type; +}; + +template <> +struct Size { + int64_t operator()(BinaryData v) const + { + return v.size(); + } + typedef BinaryData type; +}; + +template <> +struct Size { + int64_t operator()(ConstTableRef v) const + { + return v->size(); + } + typedef ConstTableRef type; +}; + +template <> +struct Size { + int64_t operator()(ConstLinkViewRef v) const + { + return v->size(); + } + typedef ConstLinkViewRef type; +}; + +} // namespace realm + +#endif // REALM_QUERY_OPERATORS_HPP diff --git a/Pods/Realm/include/core/realm/realm_nmmintrin.h b/Pods/Realm/include/core/realm/realm_nmmintrin.h new file mode 100644 index 0000000000..8144da61dc --- /dev/null +++ b/Pods/Realm/include/core/realm/realm_nmmintrin.h @@ -0,0 +1,182 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_NMMINTRIN_H +#define REALM_NMMINTRIN_H + +/* + We must support runtime detection of CPU support of SSE when distributing Realm as a closed source library. + + This is a problem on gcc and llvm: To use SSE intrinsics we need to pass -msse on the command line (to get offered + __builtin_ accessors used by intrinsics functions). However, the -msse flag allows gcc to emit SSE instructions + in its code generation/optimization. This is unwanted because the binary would crash on non-SSE CPUs. + + Since there exists no flag in gcc that enables intrinsics but probits SSE in code generation, we define our + own intrinsics to be assembled by the back end assembler and omit passing -msse to gcc. +*/ + +#ifndef _MSC_VER + +#ifdef REALM_COMPILER_SSE +#include // SSE2 (using __m128i) +#endif + +namespace realm { + +#if 0 +#ifdef REALM_COMPILER_AVX +typedef float __m256 __attribute__((__vector_size__(32), __may_alias__)); +typedef double __m256d __attribute__((__vector_size__(32), __may_alias__)); + +const int _CMP_EQ_OQ = 0x00; // Equal (ordered, non-signaling) +const int _CMP_NEQ_OQ = 0x0c; // Not-equal (ordered, non-signaling) +const int _CMP_LT_OQ = 0x11; // Less-than (ordered, non-signaling) +const int _CMP_LE_OQ = 0x12; // Less-than-or-equal (ordered, non-signaling) +const int _CMP_GE_OQ = 0x1d; // Greater-than-or-equal (ordered, non-signaling) +const int _CMP_GT_OQ = 0x1e; // Greater-than (ordered, non-signaling) + + +template +static int movemask_cmp_ps(__m256* y1, __m256* y2) +{ + int ret; + __asm__("vmovaps %0, %%ymm0" : : "m"(*y1) : "%xmm0" ); + __asm__("vmovaps %0, %%ymm1" : : "m"(*y2) : "%xmm1" ); + __asm__("vcmpps %0, %%ymm0, %%ymm1, %%ymm0" : : "I"(op) : "%xmm0" ); + __asm__("vmovmskps %%ymm0, %0" : "=r"(ret) : : ); + return ret; +} + +template +static inline int movemask_cmp_pd(__m256d* y1, __m256d* y2) +{ + int ret; + __asm__("vmovapd %0, %%ymm0" : : "m"(*y1) : "%xmm0" ); + __asm__("vmovapd %0, %%ymm1" : : "m"(*y2) : "%xmm1" ); + __asm__("vcmppd %0, %%ymm0, %%ymm1, %%ymm0" : : "I"(op) : "%xmm0" ); + __asm__("vmovmskpd %%ymm0, %0" : "=r"(ret) : : ); + return ret; +} + + + +static inline int movemask_cmp_ps(__m256* y1, __m256* y2, int op) +{ + // todo, use constexpr; + if (op == _CMP_EQ_OQ) + return movemask_cmp_ps<_CMP_NEQ_OQ>(y1, y2); + else if (op == _CMP_NEQ_OQ) + return movemask_cmp_ps<_CMP_NEQ_OQ>(y1, y2); + else if (op == _CMP_LT_OQ) + return movemask_cmp_ps<_CMP_LT_OQ>(y1, y2); + else if (op == _CMP_LE_OQ) + return movemask_cmp_ps<_CMP_LE_OQ>(y1, y2); + else if (op == _CMP_GE_OQ) + return movemask_cmp_ps<_CMP_GE_OQ>(y1, y2); + else if (op == _CMP_GT_OQ) + return movemask_cmp_ps<_CMP_GT_OQ>(y1, y2); + + REALM_ASSERT(false); + return 0; +} + +static inline int movemask_cmp_pd(__m256d* y1, __m256d* y2, int op) +{ + // todo, use constexpr; + if (op == _CMP_EQ_OQ) + return movemask_cmp_pd<_CMP_NEQ_OQ>(y1, y2); + else if (op == _CMP_NEQ_OQ) + return movemask_cmp_pd<_CMP_NEQ_OQ>(y1, y2); + else if (op == _CMP_LT_OQ) + return movemask_cmp_pd<_CMP_LT_OQ>(y1, y2); + else if (op == _CMP_LE_OQ) + return movemask_cmp_pd<_CMP_LE_OQ>(y1, y2); + else if (op == _CMP_GE_OQ) + return movemask_cmp_pd<_CMP_GE_OQ>(y1, y2); + else if (op == _CMP_GT_OQ) + return movemask_cmp_pd<_CMP_GT_OQ>(y1, y2); + + REALM_ASSERT(false); + return 0; +} + + +#endif +#endif + +// Instructions introduced by SSE 3 and 4.2 +static inline __m128i _mm_cmpgt_epi64(__m128i xmm1, __m128i xmm2) +{ + __asm__("pcmpgtq %1, %0" : "+x" (xmm1) : "xm" (xmm2)); + return xmm1; +} + +static inline __m128i _mm_cmpeq_epi64(__m128i xmm1, __m128i xmm2) +{ + __asm__("pcmpeqq %1, %0" : "+x" (xmm1) : "xm" (xmm2)); + return xmm1; +} + +static inline __m128i __attribute__((always_inline)) _mm_min_epi8(__m128i xmm1, __m128i xmm2) +{ + __asm__("pminsb %1, %0" : "+x" (xmm1) : "xm" (xmm2)); + return xmm1; +} + +static inline __m128i __attribute__((always_inline)) _mm_max_epi8(__m128i xmm1, __m128i xmm2) +{ + __asm__("pmaxsb %1, %0" : "+x" (xmm1) : "xm" (xmm2)); + return xmm1; +} + +static inline __m128i __attribute__((always_inline)) _mm_max_epi32(__m128i xmm1, __m128i xmm2) +{ + __asm__("pmaxsd %1, %0" : "+x" (xmm1) : "xm" (xmm2)); + return xmm1; +} + +static inline __m128i __attribute__((always_inline)) _mm_min_epi32(__m128i xmm1, __m128i xmm2) +{ + __asm__("pminsd %1, %0" : "+x" (xmm1) : "xm" (xmm2)); + return xmm1; +} + +static inline __m128i __attribute__((always_inline)) _mm_cvtepi8_epi16(__m128i xmm2) +{ + __m128i xmm1; + __asm__("pmovsxbw %1, %0" : "=x" (xmm1) : "xm" (xmm2) : "xmm1"); + return xmm1; +} +static inline __m128i __attribute__((always_inline)) _mm_cvtepi16_epi32(__m128i xmm2) +{ + __m128i xmm1; + asm("pmovsxwd %1, %0" : "=x" (xmm1) : "xm" (xmm2)); + return xmm1; +} + +static inline __m128i __attribute__((always_inline)) _mm_cvtepi32_epi64(__m128i xmm2) +{ + __m128i xmm1; + __asm__("pmovsxdq %1, %0" : "=x" (xmm1) : "xm" (xmm2)); + return xmm1; +} + +} // namespace realm + +#endif +#endif diff --git a/Pods/Realm/include/core/realm/replication.hpp b/Pods/Realm/include/core/realm/replication.hpp new file mode 100644 index 0000000000..f68a9afd8a --- /dev/null +++ b/Pods/Realm/include/core/realm/replication.hpp @@ -0,0 +1,514 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_REPLICATION_HPP +#define REALM_REPLICATION_HPP + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace realm { +namespace util { +class Logger; +} + +// FIXME: Be careful about the possibility of one modification function being called by another where both do +// transaction logging. + +// FIXME: The current table/subtable selection scheme assumes that a TableRef of a subtable is not accessed after any +// modification of one of its ancestor tables. + +// FIXME: Checking on same Table* requires that ~Table checks and nullifies on match. Another option would be to store +// m_selected_table as a TableRef. Yet another option would be to assign unique identifiers to each Table instance via +// Allocator. Yet another option would be to explicitely invalidate subtables recursively when parent is modified. + +/// Replication is enabled by passing an instance of an implementation of this +/// class to the SharedGroup constructor. +class Replication : public _impl::TransactLogConvenientEncoder, protected _impl::TransactLogStream { +public: + // Be sure to keep this type aligned with what is actually used in + // SharedGroup. + using version_type = _impl::History::version_type; + using InputStream = _impl::NoCopyInputStream; + class TransactLogApplier; + class Interrupted; // Exception + class SimpleIndexTranslator; + + virtual std::string get_database_path() = 0; + + /// Called during construction of the associated SharedGroup object. + /// + /// \param shared_group The assocoated SharedGroup object. + virtual void initialize(SharedGroup& shared_group) = 0; + + /// Called by the associated SharedGroup object when a session is + /// initiated. A *session* is a sequence of of temporally overlapping + /// accesses to a specific Realm file, where each access consists of a + /// SharedGroup object through which the Realm file is open. Session + /// initiation occurs during the first opening of the Realm file within such + /// a session. + /// + /// Session initiation fails if this function throws. + /// + /// \param version The current version of the associated Realm. Out-of-Realm + /// history implementation can use this to trim off history entries that + /// were successfully added to the history, but for which the corresponding + /// subsequent commits on the Realm file failed. + /// + /// The default implementation does nothing. + virtual void initiate_session(version_type version) = 0; + + /// Called by the associated SharedGroup object when a session is + /// terminated. See initiate_session() for the definition of a + /// session. Session termination occurs upon closing the Realm through the + /// last SharedGroup object within the session. + /// + /// The default implementation does nothing. + virtual void terminate_session() noexcept = 0; + + /// \defgroup replication_transactions + //@{ + + /// From the point of view of the Replication class, a transaction is + /// initiated when, and only when the associated SharedGroup object calls + /// initiate_transact() and the call is successful. The associated + /// SharedGroup object must terminate every initiated transaction either by + /// calling finalize_commit() or by calling abort_transact(). It may only + /// call finalize_commit(), however, after calling prepare_commit(), and + /// only when prepare_commit() succeeds. If prepare_commit() fails (i.e., + /// throws) abort_transact() must still be called. + /// + /// The associated SharedGroup object is supposed to terminate a transaction + /// as soon as possible, and is required to terminate it before attempting + /// to initiate a new one. + /// + /// initiate_transact() is called by the associated SharedGroup object as + /// part of the initiation of a transaction, and at a time where the caller + /// has acquired exclusive write access to the local Realm. The Replication + /// implementation is allowed to perform "precursor transactions" on the + /// local Realm at this time. During the initiated transaction, the + /// associated SharedGroup object must inform the Replication object of all + /// modifying operations by calling set_value() and friends. + /// + /// FIXME: There is currently no way for implementations to perform + /// precursor transactions, since a regular transaction would cause a dead + /// lock when it tries to acquire a write lock. Consider giving access to + /// special non-locking precursor transactions via an extra argument to this + /// function. + /// + /// prepare_commit() serves as the first phase of a two-phase commit. This + /// function is called by the associated SharedGroup object immediately + /// before the commit operation on the local Realm. The associated + /// SharedGroup object will then, as the second phase, either call + /// finalize_commit() or abort_transact() depending on whether the commit + /// operation succeeded or not. The Replication implementation is allowed to + /// modify the Realm via the associated SharedGroup object at this time + /// (important to in-Realm histories). + /// + /// initiate_transact() and prepare_commit() are allowed to block the + /// calling thread if, for example, they need to communicate over the + /// network. If a calling thread is blocked in one of these functions, it + /// must be possible to interrupt the blocking operation by having another + /// thread call interrupt(). The contract is as follows: When interrupt() is + /// called, then any execution of initiate_transact() or prepare_commit(), + /// initiated before the interruption, must complete without blocking, or + /// the execution must be aborted by throwing an Interrupted exception. If + /// initiate_transact() or prepare_commit() throws Interrupted, it counts as + /// a failed operation. + /// + /// finalize_commit() is called by the associated SharedGroup object + /// immediately after a successful commit operation on the local Realm. This + /// happens at a time where modification of the Realm is no longer possible + /// via the associated SharedGroup object. In the case of in-Realm + /// histories, the changes are automatically finalized as part of the commit + /// operation performed by the caller prior to the invocation of + /// finalize_commit(), so in that case, finalize_commit() might not need to + /// do anything. + /// + /// abort_transact() is called by the associated SharedGroup object to + /// terminate a transaction without committing. That is, any transaction + /// that is not terminated by finalize_commit() is terminated by + /// abort_transact(). This could be due to an explicit rollback, or due to a + /// failed commit attempt. + /// + /// Note that finalize_commit() and abort_transact() are not allowed to + /// throw. + /// + /// \param current_version The version of the snapshot that the current + /// transaction is based on. + /// + /// \param history_updated Pass true only when the history has already been + /// updated to reflect the currently bound snapshot, such as when + /// _impl::History::update_early_from_top_ref() was called during the + /// transition from a read transaction to the current write transaction. + /// + /// \return prepare_commit() returns the version of the new snapshot + /// produced by the transaction. + /// + /// \throw Interrupted Thrown by initiate_transact() and prepare_commit() if + /// a blocking operation was interrupted. + + void initiate_transact(version_type current_version, bool history_updated); + version_type prepare_commit(version_type current_version); + void finalize_commit() noexcept; + void abort_transact() noexcept; + + //@} + + + /// Interrupt any blocking call to a function in this class. This function + /// may be called asyncronously from any thread, but it may not be called + /// from a system signal handler. + /// + /// Some of the public function members of this class may block, but only + /// when it it is explicitely stated in the documention for those functions. + /// + /// FIXME: Currently we do not state blocking behaviour for all the + /// functions that can block. + /// + /// After any function has returned with an interruption indication, the + /// only functions that may safely be called are abort_transact() and the + /// destructor. If a client, after having received an interruption + /// indication, calls abort_transact() and then clear_interrupt(), it may + /// resume normal operation through this Replication object. + void interrupt() noexcept; + + /// May be called by a client to reset this Replication object after an + /// interrupted transaction. It is not an error to call this function in a + /// situation where no interruption has occured. + void clear_interrupt() noexcept; + + /// Apply a changeset to the specified group. + /// + /// \param changeset The changes to be applied. + /// + /// \param group The destination group to apply the changeset to. + /// + /// \param logger If specified, and the library was compiled in debug mode, + /// then a line describing each individual operation is writted to the + /// specified logger. + /// + /// \throw BadTransactLog If the changeset could not be successfully parsed, + /// or ended prematurely. + static void apply_changeset(InputStream& changeset, Group& group, util::Logger* logger = nullptr); + + /// CAUTION: These values are stored in Realm files, so value reassignment + /// is not allowed. + enum HistoryType { + /// No history available. No support for either continuous transactions + /// or inter-client synchronization. + hist_None = 0, + + /// Out-of-Realm history supporting continuous transactions. + /// + /// NOTE: This history type is no longer in use. The value needs to stay + /// reserved in case someone tries to open an old Realm file. + hist_OutOfRealm = 1, + + /// In-Realm history supporting continuous transactions + /// (make_in_realm_history()). + hist_InRealm = 2, + + /// In-Realm history supporting continuous transactions and client-side + /// synchronization protocol (realm::sync::ClientHistory). + hist_SyncClient = 3, + + /// In-Realm history supporting continuous transactions and server-side + /// synchronization protocol (realm::_impl::ServerHistory). + hist_SyncServer = 4 + }; + + /// Returns the type of history maintained by this Replication + /// implementation, or \ref hist_None if no history is maintained by it. + /// + /// This type is used to ensure that all session participants agree on + /// history type, and that the Realm file contains a compatible type of + /// history, at the beginning of a new session. + /// + /// As a special case, if there is no top array (Group::m_top) at the + /// beginning of a new session, then the history type is still undecided and + /// all history types (as returned by get_history_type()) are threfore + /// allowed for the session initiator. Note that this case only arises if + /// there was no preceding session, or if no transaction was sucessfully + /// committed during any of the preceding sessions. As soon as a transaction + /// is successfully committed, the Realm contains at least a top array, and + /// from that point on, the history type is generally fixed, although still + /// subject to certain allowed changes (as mentioned below). + /// + /// For the sake of backwards compatibility with older Realm files that does + /// not store any history type, the following rule shall apply: + /// + /// - If the top array of a Realm file (Group::m_top) does not contain a + /// history type, because it is too short, it shall be understood as + /// implicitly storing the type \ref hist_None. + /// + /// Note: In what follows, the meaning of *preceding session* is: The last + /// preceding session that modified the Realm by sucessfully committing a + /// new snapshot. + /// + /// It shall be allowed to switch to a \ref hist_InRealm history if the + /// stored history type is \ref hist_None. This can be done simply by adding + /// a new history to the Realm file. This is possible because histories of + /// this type a transient in nature, and need not survive from one session + /// to the next. + /// + /// On the other hand, as soon as a history of type \ref hist_InRealm is + /// added to a Realm file, that history type is binding for all subsequent + /// sessions. In theory, this constraint is not necessary, and a later + /// switch to \ref hist_None would be possible because of the transient + /// nature of it, however, because the \ref hist_InRealm history remains in + /// the Realm file, there are practical complications, and for that reason, + /// such switching shall not be supported. + /// + /// The \ref hist_SyncClient history type can only be used if the stored + /// history type is also \ref hist_SyncClient, or when there is no top array + /// yet. Likewise, the \ref hist_SyncServer history type can only be used if + /// the stored history type is also \ref hist_SyncServer, or when there is + /// no top array yet. Additionally, when the stored history type is \ref + /// hist_SyncClient or \ref hist_SyncServer, then all subsequent sessions + /// must have the same type. These restrictions apply because such a history + /// needs to be maintained persistently across sessions. + /// + /// In general, if there is no stored history type (no top array) at the + /// beginning of a new session, or if the stored type disagrees with what is + /// returned by get_history_type() (which is possible due to particular + /// allowed changes of history type), the actual history type (as returned + /// by get_history_type()) used during that session, must be stored in the + /// Realm during the first successfully committed transaction in that + /// session. But note that there is still no need to expand the top array to + /// store the history type \ref hist_None, due to the rule mentioned above. + /// + /// This function must return \ref hist_None when, and only when + /// get_history() returns null. + virtual HistoryType get_history_type() const noexcept = 0; + + /// Returns the schema version of the history maintained by this Replication + /// implementation, or 0 if no history is maintained by it. All session + /// participants must agree on history schema version. + /// + /// Must return 0 if get_history_type() returns \ref hist_None. + virtual int get_history_schema_version() const noexcept = 0; + + /// Implementation may assume that this function is only ever called with a + /// stored schema version that is less than what was returned by + /// get_history_schema_version(). + virtual bool is_upgradable_history_schema(int stored_schema_version) const noexcept = 0; + + /// The implementation may assume that this function is only ever called if + /// is_upgradable_history_schema() was called with the same stored schema + /// version, and returned true. This implies that the specified stored + /// schema version is always strictly less than what was returned by + /// get_history_schema_version(). + virtual void upgrade_history_schema(int stored_schema_version) = 0; + + /// Returns an object that gives access to the history of changesets in a + /// way that allows for continuous transactions to work + /// (Group::advance_transact() in particular). + /// + /// This function must return null when, and only when get_history_type() + /// returns \ref hist_None. + virtual _impl::History* get_history() = 0; + + /// Returns false by default, but must return true if, and only if this + /// history object represents a session participant that is a sync + /// agent. This is used to enforce the "maximum one sync agent per session" + /// constraint. + virtual bool is_sync_agent() const noexcept; + + virtual ~Replication() noexcept + { + } + +protected: + Replication(); + + + //@{ + + /// do_initiate_transact() is called by initiate_transact(), and likewise + /// for do_prepare_commit), do_finalize_commit(), and do_abort_transact(). + /// + /// With respect to exception safety, the Replication implementation has two + /// options: It can prepare to accept the accumulated changeset in + /// do_prepapre_commit() by allocating all required resources, and delay the + /// actual acceptance to do_finalize_commit(), which requires that the final + /// acceptance can be done without any risk of failure. Alternatively, the + /// Replication implementation can fully accept the changeset in + /// do_prepapre_commit() (allowing for failure), and then discard that + /// changeset during the next invocation of do_initiate_transact() if + /// `current_version` indicates that the previous transaction failed. + + virtual void do_initiate_transact(version_type current_version, bool history_updated) = 0; + virtual version_type do_prepare_commit(version_type orig_version) = 0; + virtual void do_finalize_commit() noexcept = 0; + virtual void do_abort_transact() noexcept = 0; + + //@} + + + virtual void do_interrupt() noexcept = 0; + + virtual void do_clear_interrupt() noexcept = 0; + + friend class _impl::TransactReverser; +}; + + +class Replication::Interrupted : public std::exception { +public: + const char* what() const noexcept override + { + return "Interrupted"; + } +}; + + +class TrivialReplication : public Replication { +public: + ~TrivialReplication() noexcept + { + } + +protected: + typedef Replication::version_type version_type; + + TrivialReplication(const std::string& database_file); + + virtual version_type prepare_changeset(const char* data, size_t size, version_type orig_version) = 0; + virtual void finalize_changeset() noexcept = 0; + + static void apply_changeset(const char* data, size_t size, SharedGroup& target, util::Logger* logger = nullptr); + + bool is_history_updated() const noexcept; + + BinaryData get_uncommitted_changes() const noexcept; + + std::string get_database_path() override; + void initialize(SharedGroup&) override; + void do_initiate_transact(version_type, bool) override; + version_type do_prepare_commit(version_type orig_version) override; + void do_finalize_commit() noexcept override; + void do_abort_transact() noexcept override; + void do_interrupt() noexcept override; + void do_clear_interrupt() noexcept override; + void transact_log_reserve(size_t n, char** new_begin, char** new_end) override; + void transact_log_append(const char* data, size_t size, char** new_begin, char** new_end) override; + +private: + const std::string m_database_file; + util::Buffer m_transact_log_buffer; + bool m_history_updated; + void internal_transact_log_reserve(size_t, char** new_begin, char** new_end); + + size_t transact_log_size(); +}; + + +// Implementation: + +inline Replication::Replication() + : _impl::TransactLogConvenientEncoder(static_cast<_impl::TransactLogStream&>(*this)) +{ +} + +inline void Replication::initiate_transact(version_type current_version, bool history_updated) +{ + do_initiate_transact(current_version, history_updated); + reset_selection_caches(); +} + +inline Replication::version_type Replication::prepare_commit(version_type orig_version) +{ + return do_prepare_commit(orig_version); +} + +inline void Replication::finalize_commit() noexcept +{ + do_finalize_commit(); +} + +inline void Replication::abort_transact() noexcept +{ + do_abort_transact(); +} + +inline void Replication::interrupt() noexcept +{ + do_interrupt(); +} + +inline void Replication::clear_interrupt() noexcept +{ + do_clear_interrupt(); +} + +inline bool Replication::is_sync_agent() const noexcept +{ + return false; +} + +inline TrivialReplication::TrivialReplication(const std::string& database_file) + : m_database_file(database_file) +{ +} + +inline bool TrivialReplication::is_history_updated() const noexcept +{ + return m_history_updated; +} + +inline BinaryData TrivialReplication::get_uncommitted_changes() const noexcept +{ + const char* data = m_transact_log_buffer.data(); + size_t size = write_position() - data; + return BinaryData(data, size); +} + +inline size_t TrivialReplication::transact_log_size() +{ + return write_position() - m_transact_log_buffer.data(); +} + +inline void TrivialReplication::transact_log_reserve(size_t n, char** new_begin, char** new_end) +{ + internal_transact_log_reserve(n, new_begin, new_end); +} + +inline void TrivialReplication::internal_transact_log_reserve(size_t n, char** new_begin, char** new_end) +{ + char* data = m_transact_log_buffer.data(); + size_t size = write_position() - data; + m_transact_log_buffer.reserve_extra(size, n); + data = m_transact_log_buffer.data(); // May have changed + *new_begin = data + size; + *new_end = data + m_transact_log_buffer.size(); +} + +} // namespace realm + +#endif // REALM_REPLICATION_HPP diff --git a/Pods/Realm/include/core/realm/row.hpp b/Pods/Realm/include/core/realm/row.hpp new file mode 100644 index 0000000000..c1439b73d0 --- /dev/null +++ b/Pods/Realm/include/core/realm/row.hpp @@ -0,0 +1,862 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_ROW_HPP +#define REALM_ROW_HPP + +#include + +#include +#include +#include +#include +#include + +namespace realm { + +template +class BasicRow; + + +/// This class is a "mixin" and contains the common set of functions for several +/// distinct row-like classes. +/// +/// There is a direct and natural correspondance between the functions in this +/// class and functions in Table of the same name. For example: +/// +/// table[i].get_int(j) == table.get_int(i,j) +/// +/// The effect of calling most of the row accessor functions on a detached +/// accessor is unspecified and may lead to general corruption, and/or a +/// crash. The exceptions are is_attached(), detach(), get_table(), get_index(), +/// and the destructor. Note however, that get_index() will still return an +/// unspecified value for a deatched accessor. +/// +/// When a row accessor is evaluated in a boolean context, it evaluates to true +/// if, and only if it is attached. +/// +/// \tparam T A const or non-const table type (currently either `Table` or +/// `const Table`). +/// +/// \tparam R A specific row accessor class (BasicRow or BasicRowExpr) providing +/// members `T* impl_get_table() const`, `size_t impl_get_row_ndx() +/// const`, and `void impl_detach()`. Neither are allowed to throw. +/// +/// \sa Table +/// \sa BasicRow +template +class RowFuncs { +public: + typedef T table_type; + + typedef BasicTableRef ConstTableRef; + typedef BasicTableRef TableRef; // Same as ConstTableRef if `T` is 'const' + + typedef typename util::CopyConst::type L; + using ConstLinkViewRef = std::shared_ptr; + using LinkViewRef = std::shared_ptr; // Same as ConstLinkViewRef if `T` is 'const' + + int_fast64_t get_int(size_t col_ndx) const noexcept; + bool get_bool(size_t col_ndx) const noexcept; + float get_float(size_t col_ndx) const noexcept; + double get_double(size_t col_ndx) const noexcept; + StringData get_string(size_t col_ndx) const noexcept; + BinaryData get_binary(size_t col_ndx) const noexcept; + OldDateTime get_olddatetime(size_t col_ndx) const noexcept; + Timestamp get_timestamp(size_t col_ndx) const noexcept; + ConstTableRef get_subtable(size_t col_ndx) const; + TableRef get_subtable(size_t col_ndx); + size_t get_subtable_size(size_t col_ndx) const noexcept; + size_t get_link(size_t col_ndx) const noexcept; + bool is_null_link(size_t col_ndx) const noexcept; + bool is_null(size_t col_ndx) const noexcept; + ConstLinkViewRef get_linklist(size_t col_ndx) const; + LinkViewRef get_linklist(size_t col_ndx); + bool linklist_is_empty(size_t col_ndx) const noexcept; + size_t get_link_count(size_t col_ndx) const noexcept; + Mixed get_mixed(size_t col_ndx) const noexcept; + DataType get_mixed_type(size_t col_ndx) const noexcept; + + template + U get(size_t col_ndx) const noexcept; + + void set_int(size_t col_ndx, int_fast64_t value); + void set_int_unique(size_t col_ndx, int_fast64_t value); + void add_int(size_t col_ndx, int_fast64_t value); + void set_bool(size_t col_ndx, bool value); + void set_float(size_t col_ndx, float value); + void set_double(size_t col_ndx, double value); + void set_string(size_t col_ndx, StringData value); + void set_string_unique(size_t col_ndx, StringData value); + void set_binary(size_t col_ndx, BinaryData value); + void set_olddatetime(size_t col_ndx, OldDateTime value); + void set_timestamp(size_t col_ndx, Timestamp value); + void set_subtable(size_t col_ndx, const Table* value); + void set_link(size_t col_ndx, size_t value); + void nullify_link(size_t col_ndx); + void set_mixed(size_t col_ndx, Mixed value); + void set_mixed_subtable(size_t col_ndx, const Table* value); + void set_null(size_t col_ndx); + void set_null_unique(size_t col_ndx); + + template + void set(size_t col_ndx, U&& value, bool is_default = false); + + template + void set_unique(size_t col_ndx, U&& value); + + void insert_substring(size_t col_ndx, size_t pos, StringData); + void remove_substring(size_t col_ndx, size_t pos, size_t size); + + //@{ + /// Note that these operations will cause the row accessor to be detached. + void remove(); + void move_last_over(); + //@} + + size_t get_backlink_count() const noexcept; + size_t get_backlink_count(const Table& src_table, size_t src_col_ndx) const noexcept; + size_t get_backlink(const Table& src_table, size_t src_col_ndx, size_t backlink_ndx) const noexcept; + + size_t get_column_count() const noexcept; + DataType get_column_type(size_t col_ndx) const noexcept; + StringData get_column_name(size_t col_ndx) const noexcept; + size_t get_column_index(StringData name) const noexcept; + + /// Returns true if, and only if this accessor is currently attached to a + /// row. + /// + /// A row accesor may get detached from the underlying row for various + /// reasons (see below). When it does, it no longer refers to anything, and + /// can no longer be used, except for calling is_attached(), detach(), + /// get_table(), get_index(), and the destructor. The consequences of + /// calling other methods on a detached row accessor are unspecified. There + /// are a few Realm functions (Table::find_pkey_int()) that return a + /// detached row accessor to indicate a 'null' result. In all other cases, + /// however, row accessors obtained by calling functions in the Realm API + /// are always in the 'attached' state immediately upon return from those + /// functions. + /// + /// A row accessor becomes detached if the underlying row is removed, if the + /// associated table accessor becomes detached, or if the detach() method is + /// called. A row accessor does not become detached for any other reason. + bool is_attached() const noexcept; + + /// Detach this accessor from the row it was attached to. This function has + /// no effect if the accessor was already detached (idempotency). + void detach() noexcept; + + /// The table containing the row to which this accessor is currently + /// bound. For a detached accessor, the returned value is null. + const table_type* get_table() const noexcept; + table_type* get_table() noexcept; + + /// The index of the row to which this accessor is currently bound. For a + /// detached accessor, the returned value is unspecified. + size_t get_index() const noexcept; + + explicit operator bool() const noexcept; + +private: + const T* table() const noexcept; + T* table() noexcept; + size_t row_ndx() const noexcept; +}; + + +/// This class is a special kind of row accessor. It differes from a real row +/// accessor (BasicRow) by having a trivial and fast copy constructor and +/// descructor. It is supposed to be used as the return type of functions such +/// as Table::operator[](), and then to be used as a basis for constructing a +/// real row accessor. Objects of this class are intended to only ever exist as +/// temporaries. +/// +/// In contrast to a real row accessor (`BasicRow`), objects of this class do +/// not keep the parent table "alive", nor are they maintained (adjusted) across +/// row insertions and row removals like real row accessors are. +/// +/// \sa BasicRow +template +class BasicRowExpr : public RowFuncs> { +public: + BasicRowExpr() noexcept = default; + + template + BasicRowExpr(const BasicRowExpr&) noexcept; + + template + BasicRowExpr(const BasicRow&) noexcept; + +private: + T* m_table = nullptr; // nullptr if detached. + size_t m_row_ndx = 0; // Undefined if detached. + + BasicRowExpr(T*, size_t init_row_ndx) noexcept; + + T* impl_get_table() const noexcept; + size_t impl_get_row_ndx() const noexcept; + void impl_detach() noexcept; + + // Make impl_get_table(), impl_get_row_ndx(), and impl_detach() accessible + // from RowFuncs. + friend class RowFuncs>; + + // Make m_table and m_row_ndx accessible from BasicRowExpr(const + // BasicRowExpr&) for any U. + template + friend class BasicRowExpr; + + // Make m_table and m_row_ndx accessible from + // BasicRow::BaicRow(BasicRowExpr) for any U. + template + friend class BasicRow; + + // Make BasicRowExpr(T*, size_t) accessible from Table. + friend class Table; +}; + +// fwd decl +class Group; + +class RowBase { +protected: + TableRef m_table; // nullptr if detached. + size_t m_row_ndx; // Undefined if detached. + + void attach(Table*, size_t row_ndx) noexcept; + void reattach(Table*, size_t row_ndx) noexcept; + void impl_detach() noexcept; + + RowBase() + { + } + + RowBase(const RowBase&) = delete; + using HandoverPatch = RowBaseHandoverPatch; + + RowBase(const RowBase& source, HandoverPatch& patch); + +public: + static void generate_patch(const RowBase& source, HandoverPatch& patch); + void apply_patch(HandoverPatch& patch, Group& group); + +private: + RowBase* m_prev = nullptr; // nullptr if first, undefined if detached. + RowBase* m_next = nullptr; // nullptr if last, undefined if detached. + + // Table needs to be able to modify m_table and m_row_ndx. + friend class Table; +}; + + +/// An accessor class for table rows (a.k.a. a "row accessor"). +/// +/// For as long as it remains attached, a row accessor will keep the parent +/// table accessor alive. In case the lifetime of the parent table is not +/// managed by reference counting (such as when the table is an automatic +/// variable on the stack), the destruction of the table will cause all +/// remaining row accessors to be detached. +/// +/// While attached, a row accessor is bound to a particular row of the parent +/// table. If that row is removed, the accesssor becomes detached. If rows are +/// inserted or removed before it (at lower row index), then the accessor is +/// automatically adjusted to account for the change in index of the row to +/// which the accessor is bound. In other words, a row accessor is bound to the +/// contents of a row, not to a row index. See also is_attached(). +/// +/// Row accessors are created and used as follows: +/// +/// Row row = table[7]; // 8th row of `table` +/// ConstRow crow = ctable[2]; // 3rd row of const `ctable` +/// Row first_row = table.front(); +/// Row last_row = table.back(); +/// +/// float v = row.get_float(1); // Get the float in the 2nd column +/// row.set_string(0, "foo"); // Update the string in the 1st column +/// +/// Table* t = row.get_table(); // The parent table +/// size_t i = row.get_index(); // The current row index +/// +/// \sa RowFuncs +template +class BasicRow : private RowBase, public RowFuncs> { +public: + BasicRow() noexcept; + + template + BasicRow(BasicRowExpr) noexcept; + + BasicRow(const BasicRow&) noexcept; + + template + BasicRow(const BasicRow&) noexcept; + + template + BasicRow& operator=(BasicRowExpr) noexcept; + + template + BasicRow& operator=(BasicRow) noexcept; + + BasicRow& operator=(const BasicRow&) noexcept; + + ~BasicRow() noexcept; + +private: + T* impl_get_table() const noexcept; + size_t impl_get_row_ndx() const noexcept; + + // Make impl_get_table(), impl_get_row_ndx(), and impl_detach() accessible + // from RowFuncs. + friend class RowFuncs>; + + // Make m_table and m_row_ndx accessible from BasicRow(const BasicRow&) + // for any U. + template + friend class BasicRow; + + // Make m_table and m_row_ndx accessible from BasicRowExpr(const + // BasicRow&) for any U. + template + friend class BasicRowExpr; + +public: + std::unique_ptr> clone_for_handover(std::unique_ptr& patch) const + { + patch.reset(new HandoverPatch); + std::unique_ptr> retval(new BasicRow(*this, *patch)); + return retval; + } + + static void generate_patch(const BasicRow& row, std::unique_ptr& patch) + { + patch.reset(new HandoverPatch); + RowBase::generate_patch(row, *patch); + } + + void apply_and_consume_patch(std::unique_ptr& patch, Group& group) + { + apply_patch(*patch, group); + patch.reset(); + } + + void apply_patch(HandoverPatch& patch, Group& group) + { + RowBase::apply_patch(patch, group); + } + +private: + BasicRow(const BasicRow& source, HandoverPatch& patch) + : RowBase(source, patch) + { + } + friend class SharedGroup; +}; + +typedef BasicRow
Row; +typedef BasicRow ConstRow; + + +// Implementation + +template +inline int_fast64_t RowFuncs::get_int(size_t col_ndx) const noexcept +{ + return table()->get_int(col_ndx, row_ndx()); +} + +template +inline bool RowFuncs::get_bool(size_t col_ndx) const noexcept +{ + return table()->get_bool(col_ndx, row_ndx()); +} + +template +inline float RowFuncs::get_float(size_t col_ndx) const noexcept +{ + return table()->get_float(col_ndx, row_ndx()); +} + +template +inline double RowFuncs::get_double(size_t col_ndx) const noexcept +{ + return table()->get_double(col_ndx, row_ndx()); +} + +template +inline StringData RowFuncs::get_string(size_t col_ndx) const noexcept +{ + return table()->get_string(col_ndx, row_ndx()); +} + +template +inline BinaryData RowFuncs::get_binary(size_t col_ndx) const noexcept +{ + return table()->get_binary(col_ndx, row_ndx()); +} + +template +inline OldDateTime RowFuncs::get_olddatetime(size_t col_ndx) const noexcept +{ + return table()->get_olddatetime(col_ndx, row_ndx()); +} + +template +inline Timestamp RowFuncs::get_timestamp(size_t col_ndx) const noexcept +{ + return table()->get_timestamp(col_ndx, row_ndx()); +} + +template +inline typename RowFuncs::ConstTableRef RowFuncs::get_subtable(size_t col_ndx) const +{ + return table()->get_subtable(col_ndx, row_ndx()); // Throws +} + +template +inline typename RowFuncs::TableRef RowFuncs::get_subtable(size_t col_ndx) +{ + return table()->get_subtable(col_ndx, row_ndx()); // Throws +} + +template +inline size_t RowFuncs::get_subtable_size(size_t col_ndx) const noexcept +{ + return table()->get_subtable_size(col_ndx, row_ndx()); +} + +template +inline size_t RowFuncs::get_link(size_t col_ndx) const noexcept +{ + return table()->get_link(col_ndx, row_ndx()); +} + +template +inline bool RowFuncs::is_null_link(size_t col_ndx) const noexcept +{ + return table()->is_null_link(col_ndx, row_ndx()); +} + +template +inline bool RowFuncs::is_null(size_t col_ndx) const noexcept +{ + return table()->is_null(col_ndx, row_ndx()); +} + +template +inline typename RowFuncs::ConstLinkViewRef RowFuncs::get_linklist(size_t col_ndx) const +{ + return table()->get_linklist(col_ndx, row_ndx()); // Throws +} + +template +inline typename RowFuncs::LinkViewRef RowFuncs::get_linklist(size_t col_ndx) +{ + return table()->get_linklist(col_ndx, row_ndx()); // Throws +} + +template +inline bool RowFuncs::linklist_is_empty(size_t col_ndx) const noexcept +{ + return table()->linklist_is_empty(col_ndx, row_ndx()); +} + +template +inline size_t RowFuncs::get_link_count(size_t col_ndx) const noexcept +{ + return table()->get_link_count(col_ndx, row_ndx()); +} + +template +inline Mixed RowFuncs::get_mixed(size_t col_ndx) const noexcept +{ + return table()->get_mixed(col_ndx, row_ndx()); +} + +template +inline DataType RowFuncs::get_mixed_type(size_t col_ndx) const noexcept +{ + return table()->get_mixed_type(col_ndx, row_ndx()); +} + +template +template +inline U RowFuncs::get(size_t col_ndx) const noexcept +{ + return table()->template get(col_ndx, row_ndx()); +} + +template +inline void RowFuncs::set_int(size_t col_ndx, int_fast64_t value) +{ + table()->set_int(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_int_unique(size_t col_ndx, int_fast64_t value) +{ + table()->set_int_unique(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::add_int(size_t col_ndx, int_fast64_t value) +{ + table()->add_int(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_bool(size_t col_ndx, bool value) +{ + table()->set_bool(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_float(size_t col_ndx, float value) +{ + table()->set_float(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_double(size_t col_ndx, double value) +{ + table()->set_double(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_string(size_t col_ndx, StringData value) +{ + table()->set_string(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_string_unique(size_t col_ndx, StringData value) +{ + table()->set_string_unique(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_binary(size_t col_ndx, BinaryData value) +{ + table()->set_binary(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_olddatetime(size_t col_ndx, OldDateTime value) +{ + table()->set_olddatetime(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_timestamp(size_t col_ndx, Timestamp value) +{ + table()->set_timestamp(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_subtable(size_t col_ndx, const Table* value) +{ + table()->set_subtable(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_link(size_t col_ndx, size_t value) +{ + table()->set_link(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::nullify_link(size_t col_ndx) +{ + table()->nullify_link(col_ndx, row_ndx()); // Throws +} + +template +inline void RowFuncs::set_mixed(size_t col_ndx, Mixed value) +{ + table()->set_mixed(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_mixed_subtable(size_t col_ndx, const Table* value) +{ + table()->set_mixed_subtable(col_ndx, row_ndx(), value); // Throws +} + +template +inline void RowFuncs::set_null(size_t col_ndx) +{ + table()->set_null(col_ndx, row_ndx()); // Throws +} + +template +inline void RowFuncs::set_null_unique(size_t col_ndx) +{ + table()->set_null_unique(col_ndx, row_ndx()); // Throws +} + +template +template +inline void RowFuncs::set(size_t col_ndx, U&& value, bool is_default) +{ + table()->set(col_ndx, row_ndx(), std::forward(value), is_default); // Throws +} + +template +template +inline void RowFuncs::set_unique(size_t col_ndx, U&& value) +{ + table()->set_unique(col_ndx, row_ndx(), std::forward(value)); // Throws +} + +template +inline void RowFuncs::insert_substring(size_t col_ndx, size_t pos, StringData value) +{ + table()->insert_substring(col_ndx, row_ndx(), pos, value); // Throws +} + +template +inline void RowFuncs::remove_substring(size_t col_ndx, size_t pos, size_t size) +{ + table()->remove_substring(col_ndx, row_ndx(), pos, size); // Throws +} + +template +inline void RowFuncs::remove() +{ + table()->remove(row_ndx()); // Throws +} + +template +inline void RowFuncs::move_last_over() +{ + table()->move_last_over(row_ndx()); // Throws +} + +template +inline size_t RowFuncs::get_backlink_count() const noexcept +{ + return table()->get_backlink_count(row_ndx()); +} + +template +inline size_t RowFuncs::get_backlink_count(const Table& src_table, size_t src_col_ndx) const noexcept +{ + return table()->get_backlink_count(row_ndx(), src_table, src_col_ndx); +} + +template +inline size_t RowFuncs::get_backlink(const Table& src_table, size_t src_col_ndx, size_t backlink_ndx) const + noexcept +{ + return table()->get_backlink(row_ndx(), src_table, src_col_ndx, backlink_ndx); +} + +template +inline size_t RowFuncs::get_column_count() const noexcept +{ + return table()->get_column_count(); +} + +template +inline DataType RowFuncs::get_column_type(size_t col_ndx) const noexcept +{ + return table()->get_column_type(col_ndx); +} + +template +inline StringData RowFuncs::get_column_name(size_t col_ndx) const noexcept +{ + return table()->get_column_name(col_ndx); +} + +template +inline size_t RowFuncs::get_column_index(StringData name) const noexcept +{ + return table()->get_column_index(name); +} + +template +inline bool RowFuncs::is_attached() const noexcept +{ + return static_cast(this)->impl_get_table(); +} + +template +inline void RowFuncs::detach() noexcept +{ + static_cast(this)->impl_detach(); +} + +template +inline const T* RowFuncs::get_table() const noexcept +{ + return table(); +} + +template +inline T* RowFuncs::get_table() noexcept +{ + return table(); +} + +template +inline size_t RowFuncs::get_index() const noexcept +{ + return row_ndx(); +} + +template +inline RowFuncs::operator bool() const noexcept +{ + return is_attached(); +} + +template +inline const T* RowFuncs::table() const noexcept +{ + return static_cast(this)->impl_get_table(); +} + +template +inline T* RowFuncs::table() noexcept +{ + return static_cast(this)->impl_get_table(); +} + +template +inline size_t RowFuncs::row_ndx() const noexcept +{ + return static_cast(this)->impl_get_row_ndx(); +} + + +template +template +inline BasicRowExpr::BasicRowExpr(const BasicRowExpr& expr) noexcept + : m_table(expr.m_table) + , m_row_ndx(expr.m_row_ndx) +{ +} + +template +template +inline BasicRowExpr::BasicRowExpr(const BasicRow& row) noexcept + : m_table(row.m_table.get()) + , m_row_ndx(row.m_row_ndx) +{ +} + +template +inline BasicRowExpr::BasicRowExpr(T* init_table, size_t init_row_ndx) noexcept + : m_table(init_table) + , m_row_ndx(init_row_ndx) +{ +} + +template +inline T* BasicRowExpr::impl_get_table() const noexcept +{ + return m_table; +} + +template +inline size_t BasicRowExpr::impl_get_row_ndx() const noexcept +{ + return m_row_ndx; +} + +template +inline void BasicRowExpr::impl_detach() noexcept +{ + m_table = nullptr; +} + + +template +inline BasicRow::BasicRow() noexcept +{ +} + +template +inline BasicRow::BasicRow(const BasicRow& row) noexcept + : RowBase() +{ + attach(const_cast(row.m_table.get()), row.m_row_ndx); +} + +template +template +inline BasicRow::BasicRow(BasicRowExpr expr) noexcept +{ + T* expr_table = expr.m_table; // Check that pointer types are compatible + attach(const_cast(expr_table), expr.m_row_ndx); +} + +template +template +inline BasicRow::BasicRow(const BasicRow& row) noexcept +{ + T* row_table = row.m_table.get(); // Check that pointer types are compatible + attach(const_cast(row_table), row.m_row_ndx); +} + +template +template +inline BasicRow& BasicRow::operator=(BasicRowExpr expr) noexcept +{ + T* expr_table = expr.m_table; // Check that pointer types are compatible + reattach(const_cast(expr_table), expr.m_row_ndx); + return *this; +} + +template +template +inline BasicRow& BasicRow::operator=(BasicRow row) noexcept +{ + T* row_table = row.m_table.get(); // Check that pointer types are compatible + reattach(const_cast(row_table), row.m_row_ndx); + return *this; +} + +template +inline BasicRow& BasicRow::operator=(const BasicRow& row) noexcept +{ + reattach(const_cast(row.m_table.get()), row.m_row_ndx); + return *this; +} + +template +inline BasicRow::~BasicRow() noexcept +{ + RowBase::impl_detach(); +} + +template +inline T* BasicRow::impl_get_table() const noexcept +{ + return m_table.get(); +} + +template +inline size_t BasicRow::impl_get_row_ndx() const noexcept +{ + return m_row_ndx; +} + +} // namespace realm + +#endif // REALM_ROW_HPP diff --git a/Pods/Realm/include/core/realm/spec.hpp b/Pods/Realm/include/core/realm/spec.hpp new file mode 100644 index 0000000000..6b793f0856 --- /dev/null +++ b/Pods/Realm/include/core/realm/spec.hpp @@ -0,0 +1,388 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_SPEC_HPP +#define REALM_SPEC_HPP + +#include +#include +#include +#include +#include +#include + +namespace realm { + +class Table; + +class Spec { +public: + ~Spec() noexcept; + + Allocator& get_alloc() const noexcept; + + bool has_strong_link_columns() noexcept; + + void insert_column(size_t column_ndx, ColumnType type, StringData name, ColumnAttr attr = col_attr_None); + void rename_column(size_t column_ndx, StringData new_name); + + /// Erase the column at the specified index, and move columns at + /// succeeding indexes to the next lower index. + /// + /// This function is guaranteed to *never* throw if the spec is + /// used in a non-transactional context, or if the spec has + /// already been successfully modified within the current write + /// transaction. + void erase_column(size_t column_ndx); + + //@{ + // If a new Spec is constructed from the returned subspec + // reference, it is the responsibility of the application that the + // parent Spec object (this) is kept alive for at least as long as + // the new Spec object. + Spec* get_subtable_spec(size_t column_ndx) noexcept; + //@} + + // Column info + size_t get_column_count() const noexcept; + size_t get_public_column_count() const noexcept; + DataType get_public_column_type(size_t column_ndx) const noexcept; + ColumnType get_column_type(size_t column_ndx) const noexcept; + StringData get_column_name(size_t column_ndx) const noexcept; + + /// Returns size_t(-1) if the specified column is not found. + size_t get_column_index(StringData name) const noexcept; + + // Column Attributes + ColumnAttr get_column_attr(size_t column_ndx) const noexcept; + + size_t get_subspec_ndx(size_t column_ndx) const noexcept; + ref_type get_subspec_ref(size_t subspec_ndx) const noexcept; + Spec* get_subspec_by_ndx(size_t subspec_ndx) noexcept; + const Spec* get_subspec_by_ndx(size_t subspec_ndx) const noexcept; + + // Auto Enumerated string columns + void upgrade_string_to_enum(size_t column_ndx, ref_type keys_ref, ArrayParent*& keys_parent, size_t& keys_ndx); + size_t get_enumkeys_ndx(size_t column_ndx) const noexcept; + ref_type get_enumkeys_ref(size_t column_ndx, ArrayParent** keys_parent = nullptr, + size_t* keys_ndx = nullptr) noexcept; + + // Links + size_t get_opposite_link_table_ndx(size_t column_ndx) const noexcept; + void set_opposite_link_table_ndx(size_t column_ndx, size_t table_ndx); + + // Backlinks + bool has_backlinks() const noexcept; + size_t first_backlink_column_index() const noexcept; + size_t backlink_column_count() const noexcept; + void set_backlink_origin_column(size_t backlink_col_ndx, size_t origin_col_ndx); + size_t get_origin_column_ndx(size_t backlink_col_ndx) const noexcept; + size_t find_backlink_column(size_t origin_table_ndx, size_t origin_col_ndx) const noexcept; + + /// Get position in `Table::m_columns` of the specified column. It may be + /// different from the specified logical column index due to the presence of + /// search indexes, since their top refs are stored in Table::m_columns as + /// well. + size_t get_column_ndx_in_parent(size_t column_ndx) const; + + //@{ + /// Compare two table specs for equality. + bool operator==(const Spec&) const noexcept; + bool operator!=(const Spec&) const noexcept; + //@} + + void detach() noexcept; + void destroy() noexcept; + + size_t get_ndx_in_parent() const noexcept; + void set_ndx_in_parent(size_t) noexcept; + +#ifdef REALM_DEBUG + void verify() const; + void to_dot(std::ostream&, StringData title = StringData()) const; +#endif + +private: + // Underlying array structure. + // + // `m_subspecs` contains one entry for each subtable column, one entry for + // each link or link list columns, two entries for each backlink column, and + // zero entries for all other column types. For subtable columns the entry + // is a ref pointing to the subtable spec, for link and link list columns it + // is the group-level table index of the target table, and for backlink + // columns the first entry is the group-level table index of the origin + // table, and the second entry is the index of the origin column in the + // origin table. + Array m_top; + ArrayInteger m_types; // 1st slot in m_top + ArrayString m_names; // 2nd slot in m_top + ArrayInteger m_attr; // 3rd slot in m_top + Array m_subspecs; // 4th slot in m_top (optional) + Array m_enumkeys; // 5th slot in m_top (optional) + struct SubspecPtr { + SubspecPtr(bool is_spec_ptr = false) + : m_is_spec_ptr(is_spec_ptr) + { + } + std::unique_ptr m_spec; + bool m_is_spec_ptr; + }; + using SubspecPtrs = std::vector; + SubspecPtrs m_subspec_ptrs; + bool m_has_strong_link_columns; + + Spec(Allocator&) noexcept; // Unattached + + bool init(ref_type) noexcept; + void init(MemRef) noexcept; + void update_has_strong_link_columns() noexcept; + void reset_subspec_ptrs(); + void adj_subspec_ptrs(); + + // Returns true in case the ref has changed. + bool init_from_parent() noexcept; + + ref_type get_ref() const noexcept; + + /// Called in the context of Group::commit() to ensure that + /// attached table accessors stay valid across a commit. Please + /// note that this works only for non-transactional commits. Table + /// accessors obtained during a transaction are always detached + /// when the transaction ends. + bool update_from_parent(size_t old_baseline) noexcept; + + void set_parent(ArrayParent*, size_t ndx_in_parent) noexcept; + + void set_column_type(size_t column_ndx, ColumnType type); + void set_column_attr(size_t column_ndx, ColumnAttr attr); + + /// Construct an empty spec and return just the reference to the + /// underlying memory. + static MemRef create_empty_spec(Allocator&); + + struct ColumnInfo { + size_t m_column_ref_ndx = 0; ///< Index within Table::m_columns + bool m_has_search_index = false; + }; + + ColumnInfo get_column_info(size_t column_ndx) const noexcept; + + size_t get_subspec_ndx_after(size_t column_ndx, size_t skip_column_ndx) const noexcept; + size_t get_subspec_entries_for_col_type(ColumnType type) const noexcept; + bool has_subspec() const noexcept; + + // Returns false if the spec has no columns, otherwise it returns + // true and sets `type` to the type of the first column. + static bool get_first_column_type_from_ref(ref_type, Allocator&, ColumnType& type) noexcept; + + friend class Replication; + friend class Group; + friend class Table; +}; + +// Implementation: + +inline Allocator& Spec::get_alloc() const noexcept +{ + return m_top.get_alloc(); +} + +inline bool Spec::has_strong_link_columns() noexcept +{ + return m_has_strong_link_columns; +} + +inline ref_type Spec::get_subspec_ref(size_t subspec_ndx) const noexcept +{ + REALM_ASSERT(subspec_ndx < m_subspecs.size()); + + // Note that this addresses subspecs directly, indexing + // by number of sub-table columns + return m_subspecs.get_as_ref(subspec_ndx); +} + +// Uninitialized Spec (call init() to init) +inline Spec::Spec(Allocator& alloc) noexcept + : m_top(alloc) + , m_types(alloc) + , m_names(alloc) + , m_attr(alloc) + , m_subspecs(alloc) + , m_enumkeys(alloc) +{ +} + +inline Spec* Spec::get_subtable_spec(size_t column_ndx) noexcept +{ + REALM_ASSERT(column_ndx < get_column_count()); + REALM_ASSERT(get_column_type(column_ndx) == col_type_Table); + size_t subspec_ndx = get_subspec_ndx(column_ndx); + return get_subspec_by_ndx(subspec_ndx); +} + +inline const Spec* Spec::get_subspec_by_ndx(size_t subspec_ndx) const noexcept +{ + return const_cast(this)->get_subspec_by_ndx(subspec_ndx); +} + +inline bool Spec::init_from_parent() noexcept +{ + ref_type ref = m_top.get_ref_from_parent(); + return init(ref); +} + +inline void Spec::destroy() noexcept +{ + m_top.destroy_deep(); +} + +inline size_t Spec::get_ndx_in_parent() const noexcept +{ + return m_top.get_ndx_in_parent(); +} + +inline void Spec::set_ndx_in_parent(size_t ndx) noexcept +{ + m_top.set_ndx_in_parent(ndx); +} + +inline ref_type Spec::get_ref() const noexcept +{ + return m_top.get_ref(); +} + +inline void Spec::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept +{ + m_top.set_parent(parent, ndx_in_parent); +} + +inline void Spec::rename_column(size_t column_ndx, StringData new_name) +{ + REALM_ASSERT(column_ndx < m_types.size()); + m_names.set(column_ndx, new_name); +} + +inline size_t Spec::get_column_count() const noexcept +{ + // This is the total count of columns, including backlinks (not public) + return m_types.size(); +} + +inline size_t Spec::get_public_column_count() const noexcept +{ + // Backlinks are the last columns, and do not have names, so getting + // the number of names gives us the count of user facing columns + return m_names.size(); +} + +inline ColumnType Spec::get_column_type(size_t ndx) const noexcept +{ + REALM_ASSERT(ndx < get_column_count()); + return ColumnType(m_types.get(ndx)); +} + +inline void Spec::set_column_type(size_t column_ndx, ColumnType type) +{ + REALM_ASSERT(column_ndx < get_column_count()); + + // At this point we only support upgrading to string enum + REALM_ASSERT(ColumnType(m_types.get(column_ndx)) == col_type_String); + REALM_ASSERT(type == col_type_StringEnum); + + m_types.set(column_ndx, type); // Throws + + update_has_strong_link_columns(); +} + +inline ColumnAttr Spec::get_column_attr(size_t ndx) const noexcept +{ + REALM_ASSERT(ndx < get_column_count()); + return ColumnAttr(m_attr.get(ndx)); +} + +inline void Spec::set_column_attr(size_t column_ndx, ColumnAttr attr) +{ + REALM_ASSERT(column_ndx < get_column_count()); + + // At this point we only allow one attr at a time + // so setting it will overwrite existing. In the future + // we will allow combinations. + m_attr.set(column_ndx, attr); + + update_has_strong_link_columns(); +} + +inline StringData Spec::get_column_name(size_t ndx) const noexcept +{ + REALM_ASSERT(ndx < get_column_count()); + return m_names.get(ndx); +} + +inline size_t Spec::get_column_index(StringData name) const noexcept +{ + return m_names.find_first(name); +} + +inline bool Spec::get_first_column_type_from_ref(ref_type top_ref, Allocator& alloc, ColumnType& type) noexcept +{ + const char* top_header = alloc.translate(top_ref); + ref_type types_ref = to_ref(Array::get(top_header, 0)); + const char* types_header = alloc.translate(types_ref); + if (Array::get_size_from_header(types_header) == 0) + return false; + type = ColumnType(Array::get(types_header, 0)); + return true; +} + +inline bool Spec::has_backlinks() const noexcept +{ + // backlinks are always last and do not have names. + return m_names.size() < m_types.size(); + + // Fixme: It's bad design that backlinks are stored and recognized like this. Backlink columns + // should be a column type like any other, and we should find another way to hide them away from + // the user. +} + +inline size_t Spec::first_backlink_column_index() const noexcept +{ + return m_names.size(); +} + +inline size_t Spec::backlink_column_count() const noexcept +{ + return m_types.size() - m_names.size(); +} + +// Spec will have a subspec when it contains a column which is one of: +// link, linklist, backlink, or subtable. It is possible for m_top.size() +// to contain an entry for m_subspecs (at index 3) but this reference +// may be empty if the spec contains enumkeys (at index 4) but no subspec types. +inline bool Spec::has_subspec() const noexcept +{ + return (m_top.size() >= 4) && (m_top.get_as_ref(3) != 0); +} + +inline bool Spec::operator!=(const Spec& s) const noexcept +{ + return !(*this == s); +} + +} // namespace realm + +#endif // REALM_SPEC_HPP diff --git a/Pods/Realm/include/core/realm/string_data.hpp b/Pods/Realm/include/core/realm/string_data.hpp new file mode 100644 index 0000000000..a617ebe75f --- /dev/null +++ b/Pods/Realm/include/core/realm/string_data.hpp @@ -0,0 +1,379 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_STRING_HPP +#define REALM_STRING_HPP + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace realm { + +/// A reference to a chunk of character data. +/// +/// An instance of this class can be thought of as a type tag on a region of +/// memory. It does not own the referenced memory, nor does it in any other way +/// attempt to manage the lifetime of it. +/// +/// A null character inside the referenced region is considered a part of the +/// string by Realm. +/// +/// For compatibility with C-style strings, when a string is stored in a Realm +/// database, it is always followed by a terminating null character, regardless +/// of whether the string itself has internal null characters. This means that +/// when a StringData object is extracted from Realm, the referenced region is +/// guaranteed to be followed immediately by an extra null character, but that +/// null character is not inside the referenced region. Therefore, all of the +/// following forms are guaranteed to return a pointer to a null-terminated +/// string: +/// +/// \code{.cpp} +/// +/// group.get_table_name(...).data() +/// table.get_column_name().data() +/// table.get_string(...).data() +/// table.get_mixed(...).get_string().data() +/// +/// \endcode +/// +/// Note that in general, no assumptions can be made about what follows a string +/// that is referenced by a StringData object, or whether anything follows it at +/// all. In particular, the receiver of a StringData object cannot assume that +/// the referenced string is followed by a null character unless there is an +/// externally provided guarantee. +/// +/// This class makes it possible to distinguish between a 'null' reference and a +/// reference to the empty string (see is_null()). +/// +/// \sa BinaryData +/// \sa Mixed +class StringData { +public: + /// Construct a null reference. + StringData() noexcept; + + /// If \a external_data is 'null', \a data_size must be zero. + StringData(const char* external_data, size_t data_size) noexcept; + + template + StringData(const std::basic_string&); + + template + operator std::basic_string() const; + + // StringData does not store data, callers must manage their own strings. + template + StringData(const std::basic_string&&) = delete; + + template + StringData(const util::Optional>&); + + StringData(const null&) noexcept; + + /// Initialize from a zero terminated C style string. Pass null to construct + /// a null reference. + StringData(const char* c_str) noexcept; + + char operator[](size_t i) const noexcept; + + const char* data() const noexcept; + size_t size() const noexcept; + + /// Is this a null reference? + /// + /// An instance of StringData is a null reference when, and only when the + /// stored size is zero (size()) and the stored pointer is the null pointer + /// (data()). + /// + /// In the case of the empty string, the stored size is still zero, but the + /// stored pointer is **not** the null pointer. It could for example point + /// to the empty string literal. Note that the actual value of the pointer + /// is immaterial in this case (as long as it is not zero), because when the + /// size is zero, it is an error to dereference the pointer. + /// + /// Conversion of a StringData object to `bool` yields the logical negation + /// of the result of calling this function. In other words, a StringData + /// object is converted to true if it is not the null reference, otherwise + /// it is converted to false. + bool is_null() const noexcept; + + friend bool operator==(const StringData&, const StringData&) noexcept; + friend bool operator!=(const StringData&, const StringData&) noexcept; + + //@{ + /// Trivial bytewise lexicographical comparison. + friend bool operator<(const StringData&, const StringData&) noexcept; + friend bool operator>(const StringData&, const StringData&) noexcept; + friend bool operator<=(const StringData&, const StringData&) noexcept; + friend bool operator>=(const StringData&, const StringData&) noexcept; + //@} + + bool begins_with(StringData) const noexcept; + bool ends_with(StringData) const noexcept; + bool contains(StringData) const noexcept; + bool contains(StringData d, const std::array &charmap) const noexcept; + + // Wildcard matching ('?' for single char, '*' for zero or more chars) + // case insensitive version in unicode.hpp + bool like(StringData) const noexcept; + + //@{ + /// Undefined behavior if \a n, \a i, or i+n is greater than + /// size(). + StringData prefix(size_t n) const noexcept; + StringData suffix(size_t n) const noexcept; + StringData substr(size_t i, size_t n) const noexcept; + StringData substr(size_t i) const noexcept; + //@} + + template + friend std::basic_ostream& operator<<(std::basic_ostream&, const StringData&); + + explicit operator bool() const noexcept; + +private: + const char* m_data; + size_t m_size; + + static bool matchlike(const StringData& text, const StringData& pattern) noexcept; + static bool matchlike_ins(const StringData& text, const StringData& pattern_upper, + const StringData& pattern_lower) noexcept; + + friend bool string_like_ins(StringData, StringData) noexcept; + friend bool string_like_ins(StringData, StringData, StringData) noexcept; +}; + + +// Implementation: + +inline StringData::StringData() noexcept + : m_data(nullptr) + , m_size(0) +{ +} + +inline StringData::StringData(const char* external_data, size_t data_size) noexcept + : m_data(external_data) + , m_size(data_size) +{ + REALM_ASSERT_DEBUG(external_data || data_size == 0); +} + +template +inline StringData::StringData(const std::basic_string& s) + : m_data(s.data()) + , m_size(s.size()) +{ +} + +template +inline StringData::operator std::basic_string() const +{ + return std::basic_string(m_data, m_size); +} + +template +inline StringData::StringData(const util::Optional>& s) + : m_data(s ? s->data() : nullptr) + , m_size(s ? s->size() : 0) +{ +} + +inline StringData::StringData(const null&) noexcept + : m_data(nullptr) + , m_size(0) +{ +} + +inline StringData::StringData(const char* c_str) noexcept + : m_data(c_str) + , m_size(0) +{ + if (c_str) + m_size = std::char_traits::length(c_str); +} + +inline char StringData::operator[](size_t i) const noexcept +{ + return m_data[i]; +} + +inline const char* StringData::data() const noexcept +{ + return m_data; +} + +inline size_t StringData::size() const noexcept +{ + return m_size; +} + +inline bool StringData::is_null() const noexcept +{ + return !m_data; +} + +inline bool operator==(const StringData& a, const StringData& b) noexcept +{ + return a.m_size == b.m_size && a.is_null() == b.is_null() && safe_equal(a.m_data, a.m_data + a.m_size, b.m_data); +} + +inline bool operator!=(const StringData& a, const StringData& b) noexcept +{ + return !(a == b); +} + +inline bool operator<(const StringData& a, const StringData& b) noexcept +{ + if (a.is_null() && !b.is_null()) { + // Null strings are smaller than all other strings, and not + // equal to empty strings. + return true; + } + return std::lexicographical_compare(a.m_data, a.m_data + a.m_size, b.m_data, b.m_data + b.m_size); +} + +inline bool operator>(const StringData& a, const StringData& b) noexcept +{ + return b < a; +} + +inline bool operator<=(const StringData& a, const StringData& b) noexcept +{ + return !(b < a); +} + +inline bool operator>=(const StringData& a, const StringData& b) noexcept +{ + return !(a < b); +} + +inline bool StringData::begins_with(StringData d) const noexcept +{ + if (is_null() && !d.is_null()) + return false; + return d.m_size <= m_size && safe_equal(m_data, m_data + d.m_size, d.m_data); +} + +inline bool StringData::ends_with(StringData d) const noexcept +{ + if (is_null() && !d.is_null()) + return false; + return d.m_size <= m_size && safe_equal(m_data + m_size - d.m_size, m_data + m_size, d.m_data); +} + +inline bool StringData::contains(StringData d) const noexcept +{ + if (is_null() && !d.is_null()) + return false; + + return d.m_size == 0 || std::search(m_data, m_data + m_size, d.m_data, d.m_data + d.m_size) != m_data + m_size; +} + +/// This method takes an array that maps chars to distance that can be moved (and zero for chars not in needle), +/// allowing the method to apply Boyer-Moore for quick substring search +/// The map is calculated in the StringNode class (so it can be reused across searches) +inline bool StringData::contains(StringData d, const std::array &charmap) const noexcept +{ + if (is_null() && !d.is_null()) + return false; + + size_t needle_size = d.size(); + if (needle_size == 0) + return true; + + // Prepare vars to avoid lookups in loop + size_t last_char_pos = d.size()-1; + unsigned char lastChar = d[last_char_pos]; + + // Do Boyer-Moore search + size_t p = last_char_pos; + while (p < m_size) { + unsigned char c = m_data[p]; // Get candidate for last char + + if (c == lastChar) { + StringData candidate = substr(p-needle_size+1, needle_size); + if (candidate == d) + return true; // text found! + } + + // If we don't have a match, see how far we can move char_pos + if (charmap[c] == 0) + p += needle_size; // char was not present in search string + else + p += charmap[c]; + } + + return false; +} + +inline bool StringData::like(StringData d) const noexcept +{ + if (is_null() || d.is_null()) { + return (is_null() && d.is_null()); + } + + return matchlike(*this, d); +} + +inline StringData StringData::prefix(size_t n) const noexcept +{ + return substr(0, n); +} + +inline StringData StringData::suffix(size_t n) const noexcept +{ + return substr(m_size - n); +} + +inline StringData StringData::substr(size_t i, size_t n) const noexcept +{ + return StringData(m_data + i, n); +} + +inline StringData StringData::substr(size_t i) const noexcept +{ + return substr(i, m_size - i); +} + +template +inline std::basic_ostream& operator<<(std::basic_ostream& out, const StringData& d) +{ + for (const char* i = d.m_data; i != d.m_data + d.m_size; ++i) + out << *i; + return out; +} + +inline StringData::operator bool() const noexcept +{ + return !is_null(); +} + +} // namespace realm + +#endif // REALM_STRING_HPP diff --git a/Pods/Realm/include/core/realm/sync/changeset.hpp b/Pods/Realm/include/core/realm/sync/changeset.hpp new file mode 100644 index 0000000000..c1a4381815 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/changeset.hpp @@ -0,0 +1,653 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2017] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_SYNC_CHANGESET_HPP +#define REALM_SYNC_CHANGESET_HPP + +#include +#include + +#include + +namespace realm { +namespace sync { + +using InternStrings = std::vector; + +struct BadChangesetError : ExceptionWithBacktrace { + const char* m_message; + BadChangesetError() : BadChangesetError("Bad changeset") {} + BadChangesetError(const char* msg) : m_message(msg) {} + const char* message() const noexcept override + { + return m_message; + } +}; + +struct Changeset { + struct Range; + using timestamp_type = uint_fast64_t; + using file_ident_type = uint_fast64_t; + using version_type = uint_fast64_t; // FIXME: Get from `History`. + + Changeset(); + struct share_buffers_tag {}; + Changeset(const Changeset&, share_buffers_tag); + Changeset(Changeset&&) = default; + Changeset& operator=(Changeset&&) = default; + Changeset(const Changeset&) = delete; + Changeset& operator=(const Changeset&) = delete; + + InternString intern_string(StringData); // Slow! + StringData string_data() const noexcept; + + util::StringBuffer& string_buffer() noexcept; + const util::StringBuffer& string_buffer() const noexcept; + const InternStrings& interned_strings() const noexcept; + InternStrings& interned_strings() noexcept; + + StringBufferRange get_intern_string(InternString) const noexcept; + util::Optional try_get_intern_string(InternString) const noexcept; + util::Optional try_get_string(StringBufferRange) const noexcept; + StringData get_string(StringBufferRange) const noexcept; + StringData get_string(InternString) const noexcept; + StringBufferRange append_string(StringData); + + // Interface to imitate std::vector: + template struct IteratorImpl; + using iterator = IteratorImpl; + using const_iterator = IteratorImpl; + using value_type = Instruction; + iterator begin() noexcept; + iterator end() noexcept; + const_iterator begin() const noexcept; + const_iterator end() const noexcept; + const_iterator cbegin() const noexcept; + const_iterator cend() const noexcept; + bool empty() const noexcept; + + /// Size of the Changeset, not counting tombstones. + /// + /// FIXME: This is an O(n) operation. + size_t size() const noexcept; + + void clear() noexcept; + + //@{ + /// Insert instructions, invalidating all iterators. + iterator insert(const_iterator pos, Instruction); + template + iterator insert(const_iterator pos, InputIt begin, InputIt end); + //@} + + /// Erase an instruction, invalidating all iterators. + iterator erase(const_iterator); + + /// Insert an instruction at the end, invalidating all iterators. + void push_back(const Instruction&); + + //@{ + /// Insert instructions at \a position without invalidating other + /// iterators. + /// + /// Only iterators created before any call to `insert_stable()` may be + /// considered stable across calls to `insert_stable()`. In addition, + /// "iterator stability" has a very specific meaning here: Other copies of + /// \a position in the program will point to the newly inserted elements + /// after calling `insert_stable()`, rather than point to the value at the + /// position prior to insertion. This is different from, say, a tree + /// structure, where iterator stability signifies the property that + /// iterators keep pointing to the same element after insertion before or + /// after that position. + /// + /// For the purpose of supporting `ChangesetIndex`, and the OT merge + /// algorithm, these semantics are acceptable, since prepended instructions + /// can never create new object or table references. + iterator insert_stable(const_iterator position, Instruction); + template + iterator insert_stable(const_iterator position, InputIt begin, InputIt end); + //@} + + /// Erase instruction at \a position without invalidating other iterators. + /// If erasing the object would invalidate other iterators, it is turned + /// into a tombstone instead, and subsequent derefencing of the iterator + /// will return `nullptr`. An iterator pointing to a tombstone remains valid + /// and can be incremented. + /// + /// Only iterators created before any call to `insert_stable()` may be + /// considered stable across calls to `erase_stable()`. If other copies of + /// \a position exist in the program, they will either point to the + /// subsequent element if that element was previously inserted with + /// `insert_stable()`, or otherwise it will be turned into a tombstone. + iterator erase_stable(const_iterator position); + +#if REALM_DEBUG + struct Reflector; + struct Printer; + void verify() const; + void print(std::ostream&) const; + void print() const; // prints to std::err +#endif + + /// The version that this changeset produced. Note: This may not be the + /// version produced by this changeset on the client on which this changeset + /// originated, but may for instance be the version produced on the server + /// after receiving and re-sending this changeset to another client. + version_type version = 0; + + /// On clients, the last integrated server version. On the server, this is + /// the last integrated client version. + version_type last_integrated_remote_version = 0; + + /// Timestamp at origin when the original untransformed changeset was + /// produced. + timestamp_type origin_timestamp = 0; + + /// The identifier of the file in the context of which the original + /// untransformed changeset was produced. + file_ident_type origin_file_ident = 0; + +private: + struct MultiInstruction { + std::vector instructions; + }; + static_assert(sizeof(MultiInstruction) <= Instruction::max_instruction_size, "Instruction::max_instruction_size too low"); + + // In order to achieve iterator semi-stability (just enough to be able to + // run the merge algorithm while maintaining a ChangesetIndex), a Changeset + // is really a list of lists. A Changeset is a vector of + // `InstructionContainer`s, and each `InstructionContainer` represents 0-N + // "real" instructions. + // + // As an optimization, there is a special case for when the + // `InstructionContainer` represents exactly 1 instruction, in which case it + // is represented inside the `InstructionContainer` without any additional + // allocations or indirections. The `InstructionContainer` derived from + // the `Instruction` struct, and co-opts the `type` field such that if the + // (invalid) value of `type` is 0xff, the contents of the `Instruction` are + // instead interpreted as an instance of `MultiInstruction`, which holds + // a vector of `Instruction`s. + // + // The size of the `MultiInstruction` may also be zero, in which case it is + // considered a "tombstone" - always as a result of a call to + // `Changeset::erase_stable()`. The potential existence of these tombstones + // is the reason that the value type of `Changeset::iterator` is + // `Instruction*`, rather than `Instruction&`. + // + // FIXME: It would be better if `Changeset::iterator::value_type` could be + // `util::Optional`, but this is prevented by a bug in + // `util::Optional`. + struct InstructionContainer : Instruction { + InstructionContainer(); + InstructionContainer(const Instruction& instr); + InstructionContainer(InstructionContainer&&) noexcept; + InstructionContainer(const InstructionContainer&); + ~InstructionContainer(); + InstructionContainer& operator=(InstructionContainer&&) noexcept; + InstructionContainer& operator=(const InstructionContainer&); + + bool is_multi() const noexcept; + void convert_to_multi(); + void insert(size_t position, Instruction instr); + void erase(size_t position); + size_t size() const noexcept; + + Instruction& at(size_t pos) noexcept; + const Instruction& at(size_t pos) const noexcept; + + MultiInstruction& get_multi() noexcept; + const MultiInstruction& get_multi() const noexcept; + }; + + std::vector m_instructions; + std::shared_ptr m_string_buffer; + std::shared_ptr m_strings; + + iterator const_iterator_to_iterator(const_iterator); +}; + +/// An iterator type that hides the implementation details of the support for +/// iterator stability. +/// +/// A `Changeset::iterator` is composed of an +/// `std::vector::iterator` and a `size_t` representing +/// the index into the current `InstructionContainer`. If that container is +/// empty, and the position is zero, the iterator is pointing to a tombstone. +template +struct Changeset::IteratorImpl { + using list_type = std::vector; + using inner_iterator_type = std::conditional_t; + + // reference_type is a pointer because we have no way to create a reference + // to a tombstone instruction. Alternatively, it could have been + // `util::Optional`, but that runs into other issues. + using reference_type = std::conditional_t; + + using pointer_type = std::conditional_t; + using difference_type = std::ptrdiff_t; + + IteratorImpl() : m_pos(0) {} + IteratorImpl(const IteratorImpl& other) : m_inner(other.m_inner), m_pos(other.m_pos) {} + template + IteratorImpl(const IteratorImpl& other, std::enable_if_t* = nullptr) + : m_inner(other.m_inner), m_pos(other.m_pos) {} + IteratorImpl(inner_iterator_type inner, size_t pos = 0) : m_inner(inner), m_pos(pos) {} + + IteratorImpl& operator++() + { + ++m_pos; + if (m_pos >= m_inner->size()) { + ++m_inner; + m_pos = 0; + } + return *this; + } + + IteratorImpl operator++(int) + { + auto copy = *this; + ++(*this); + return copy; + } + + IteratorImpl& operator--() + { + if (m_pos == 0) { + --m_inner; + m_pos = m_inner->size(); + if (m_pos != 0) + --m_pos; + } + else { + --m_pos; + } + return *this; + } + + IteratorImpl operator--(int) + { + auto copy = *this; + --(*this); + return copy; + } + + reference_type operator*() const + { + if (m_inner->size()) { + return &m_inner->at(m_pos); + } + // It was a tombstone. + return nullptr; + } + + pointer_type operator->() const + { + if (m_inner->size()) { + return &m_inner->at(m_pos); + } + // It was a tombstone. + return nullptr; + } + + bool operator==(const IteratorImpl& other) const + { + return m_inner == other.m_inner && m_pos == other.m_pos; + } + + bool operator!=(const IteratorImpl& other) const + { + return !(*this == other); + } + + bool operator<(const IteratorImpl& other) const + { + if (m_inner == other.m_inner) + return m_pos < other.m_pos; + return m_inner < other.m_inner; + } + + bool operator<=(const IteratorImpl& other) const + { + if (m_inner == other.m_inner) + return m_pos <= other.m_pos; + return m_inner < other.m_inner; + } + + bool operator>(const IteratorImpl& other) const + { + if (m_inner == other.m_inner) + return m_pos > other.m_pos; + return m_inner > other.m_inner; + } + + bool operator>=(const IteratorImpl& other) const + { + if (m_inner == other.m_inner) + return m_pos >= other.m_pos; + return m_inner > other.m_inner; + } + + inner_iterator_type m_inner; + size_t m_pos; +}; + +struct Changeset::Range { + iterator begin; + iterator end; +}; + +#if REALM_DEBUG +struct Changeset::Reflector { + struct Tracer { + virtual void name(StringData) = 0; + virtual void field(StringData, StringData) = 0; + virtual void field(StringData, ObjectID) = 0; + virtual void field(StringData, int64_t) = 0; + virtual void field(StringData, double) = 0; + virtual void after_each() {} + virtual void before_each() {} + }; + + Reflector(Tracer& tracer, const Changeset& log) : + m_tracer(tracer), m_log(log) + {} + + void visit_all() const; +private: + Tracer& m_tracer; + const Changeset& m_log; + + friend struct Instruction; // permit access for visit() +#define REALM_DEFINE_REFLECTOR_VISITOR(X) void operator()(const Instruction::X&) const; + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DEFINE_REFLECTOR_VISITOR) +#undef REALM_DEFINE_REFLECTOR_VISITOR +}; + +struct Changeset::Printer : Changeset::Reflector::Tracer { + explicit Printer(std::ostream& os) : m_out(os) + {} + + // ChangesetReflector::Tracer interface: + void name(StringData) final; + void field(StringData, StringData) final; + void field(StringData, ObjectID) final; + void field(StringData, int64_t) final; + void field(StringData, double) final; + void after_each() final; + +private: + std::ostream& m_out; + bool m_first = true; + void pad_or_ellipsis(StringData, int width) const; + void print_field(StringData name, std::string value); +}; +#endif // REALM_DEBUG + + + +/// Implementation: + +inline Changeset::iterator Changeset::begin() noexcept +{ + return m_instructions.begin(); +} + +inline Changeset::iterator Changeset::end() noexcept +{ + return m_instructions.end(); +} + +inline Changeset::const_iterator Changeset::begin() const noexcept +{ + return m_instructions.begin(); +} + +inline Changeset::const_iterator Changeset::end() const noexcept +{ + return m_instructions.end(); +} + +inline Changeset::const_iterator Changeset::cbegin() const noexcept +{ + return m_instructions.cbegin(); +} + +inline Changeset::const_iterator Changeset::cend() const noexcept +{ + return m_instructions.end(); +} + +inline bool Changeset::empty() const noexcept +{ + return size() == 0; +} + +inline size_t Changeset::size() const noexcept +{ + size_t sum = 0; + for (auto& x: m_instructions) + sum += x.size(); + return sum; +} + +inline void Changeset::clear() noexcept +{ + m_instructions.clear(); +} + +inline util::Optional Changeset::try_get_intern_string(InternString string) const noexcept +{ + if (string.value >= m_strings->size()) + return util::none; + return (*m_strings)[string.value]; +} + +inline StringBufferRange Changeset::get_intern_string(InternString string) const noexcept +{ + auto str = try_get_intern_string(string); + REALM_ASSERT(str); + return *str; +} + +inline InternStrings& Changeset::interned_strings() noexcept +{ + return *m_strings; +} + +inline const InternStrings& Changeset::interned_strings() const noexcept +{ + return *m_strings; +} + +inline util::StringBuffer& Changeset::string_buffer() noexcept +{ + return *m_string_buffer; +} + +inline const util::StringBuffer& Changeset::string_buffer() const noexcept +{ + return *m_string_buffer; +} + +inline util::Optional Changeset::try_get_string(StringBufferRange range) const noexcept +{ + if (range.offset > m_string_buffer->size()) + return util::none; + if (range.offset + range.size > m_string_buffer->size()) + return util::none; + return StringData{m_string_buffer->data() + range.offset, range.size}; +} + +inline StringData Changeset::get_string(StringBufferRange range) const noexcept +{ + auto string = try_get_string(range); + REALM_ASSERT(string); + return *string; +} + +inline StringData Changeset::get_string(InternString string) const noexcept +{ + return get_string(get_intern_string(string)); +} + +inline StringData Changeset::string_data() const noexcept +{ + return StringData{m_string_buffer->data(), m_string_buffer->size()}; +} + +inline StringBufferRange Changeset::append_string(StringData string) +{ + m_string_buffer->reserve(1024); // we expect more strings + size_t offset = m_string_buffer->size(); + m_string_buffer->append(string.data(), string.size()); + return StringBufferRange{uint32_t(offset), uint32_t(string.size())}; +} + +inline Changeset::iterator Changeset::insert(const_iterator pos, Instruction instr) +{ + Instruction* p = &instr; + return insert(pos, p, p + 1); +} + +template +inline Changeset::iterator Changeset::insert(const_iterator pos, InputIt begin, InputIt end) +{ + if (pos.m_pos == 0) + return m_instructions.insert(pos.m_inner, begin, end); + return insert_stable(pos, begin, end); +} + +inline Changeset::iterator Changeset::erase(const_iterator pos) +{ + if (pos.m_inner->size() <= 1) + return m_instructions.erase(pos.m_inner); + return erase_stable(pos); +} + +inline Changeset::iterator Changeset::insert_stable(const_iterator pos, Instruction instr) +{ + Instruction* p = &instr; + return insert_stable(pos, p, p + 1); +} + +template +inline Changeset::iterator Changeset::insert_stable(const_iterator cpos, InputIt begin, InputIt end) +{ + iterator pos = const_iterator_to_iterator(cpos); + size_t i = 0; + for (auto it = begin; it != end; ++it, ++i) { + pos.m_inner->insert(pos.m_pos + i, *it); + } + return pos; +} + +inline Changeset::iterator Changeset::erase_stable(const_iterator cpos) +{ + auto pos = const_iterator_to_iterator(cpos); + auto begin = m_instructions.begin(); + auto end = m_instructions.end(); + REALM_ASSERT(pos.m_inner >= begin); + REALM_ASSERT(pos.m_inner < end); + pos.m_inner->erase(pos.m_pos); + if (pos.m_pos >= pos.m_inner->size()) { + do { + ++pos.m_inner; + } while (pos.m_inner != end && pos.m_inner->size() == 0); + pos.m_pos = 0; + } + return pos; +} + +inline void Changeset::push_back(const Instruction& instr) +{ + m_instructions.emplace_back(instr); +} + +inline auto Changeset::const_iterator_to_iterator(const_iterator cpos) -> iterator +{ + size_t offset = cpos.m_inner - m_instructions.cbegin(); + return iterator{m_instructions.begin() + offset, cpos.m_pos}; +} + +inline Changeset::InstructionContainer::~InstructionContainer() +{ + if (is_multi()) { + get_multi().~MultiInstruction(); + } + // Instruction subtypes are required to be POD-types (trivially + // destructible), and this is checked by a static_assert in + // instructions.hpp. Therefore, it is safe to do nothing if this is not a + // multi-instruction. +} + +inline bool Changeset::InstructionContainer::is_multi() const noexcept +{ + return type == Type(InstrTypeMultiInstruction); +} + +inline size_t Changeset::InstructionContainer::size() const noexcept +{ + if (is_multi()) + return get_multi().instructions.size(); + return 1; +} + +inline Instruction& Changeset::InstructionContainer::at(size_t pos) noexcept +{ + REALM_ASSERT(pos < size()); + if (is_multi()) + return get_multi().instructions[pos]; + return *this; +} + +inline const Instruction& Changeset::InstructionContainer::at(size_t pos) const noexcept +{ + REALM_ASSERT(pos < size()); + if (is_multi()) + return get_multi().instructions[pos]; + return *this; +} + +inline Changeset::MultiInstruction& Changeset::InstructionContainer::get_multi() noexcept +{ + REALM_ASSERT(is_multi()); + return *reinterpret_cast(&m_storage); +} + +inline const Changeset::MultiInstruction& Changeset::InstructionContainer::get_multi() const noexcept +{ + REALM_ASSERT(is_multi()); + return *reinterpret_cast(&m_storage); +} + +} // namespace sync +} // namespace realm + +namespace std { + +template +struct iterator_traits> { + using difference_type = std::ptrdiff_t; + using iterator_category = std::bidirectional_iterator_tag; +}; + +} // namespace std + +#endif // REALM_SYNC_CHANGESET_HPP diff --git a/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp b/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp new file mode 100644 index 0000000000..3d003be8da --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp @@ -0,0 +1,40 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#include + +#ifndef REALM_SYNC_CHANGESET_COOKER_HPP +#define REALM_SYNC_CHANGESET_COOKER_HPP + +namespace realm { +namespace sync { + +/// Copy raw changesets unmodified. +class TrivialChangesetCooker: public ClientHistory::ChangesetCooker { +public: + bool cook_changeset(const Group&, const char* changeset, + std::size_t changeset_size, + util::AppendBuffer&) override; +}; + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_CHANGESET_COOKER_HPP diff --git a/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp b/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp new file mode 100644 index 0000000000..d443862f00 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp @@ -0,0 +1,109 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2017] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_SYNC_CHANGESET_ENCODER_HPP +#define REALM_SYNC_CHANGESET_ENCODER_HPP + +#include + +namespace realm { +namespace sync { + +struct ChangesetEncoder: InstructionHandler { + util::AppendBuffer release() noexcept; + void reset() noexcept; + const util::AppendBuffer& buffer() const noexcept; + InternString intern_string(StringData); + + void set_intern_string(uint32_t index, StringBufferRange) override; + // FIXME: This doesn't copy the input, but the drawback is that there can + // only be a single StringBufferRange per instruction. Luckily, no + // instructions exist that require two or more. + StringBufferRange add_string_range(StringData) override; + void operator()(const Instruction&) override; + +#define REALM_DEFINE_INSTRUCTION_HANDLER(X) void operator()(const Instruction::X&); + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DEFINE_INSTRUCTION_HANDLER) +#undef REALM_DEFINE_INSTRUCTION_HANDLER + +protected: + template static void encode(E& encoder, const Instruction&); + + StringData get_string(StringBufferRange) const noexcept; + +private: + template + void append(Instruction::Type t, Args&&...); + void append_string(StringBufferRange); // does not intern the string + void append_bytes(const void*, size_t); + + template void append_int(T); + template char* encode_int(char* buffer, T value); + void append_payload(const Instruction::Payload&); + void append_value(DataType); + void append_value(bool); + void append_value(uint8_t); + void append_value(int64_t); + void append_value(uint32_t); + void append_value(uint64_t); + void append_value(float); + void append_value(double); + void append_value(InternString); + void append_value(sync::ObjectID); + void append_value(Timestamp); + + util::AppendBuffer m_buffer; + std::unordered_map m_intern_strings_rev; + StringData m_string_range; +}; + +void encode_changeset(const Changeset&, util::AppendBuffer& out_buffer); + + + + +// Implementation + +inline const util::AppendBuffer& ChangesetEncoder::buffer() const noexcept +{ + return m_buffer; +} + +inline void ChangesetEncoder::operator()(const Instruction& instr) +{ + encode(*this, instr); // Throws +} + +template inline void ChangesetEncoder::encode(E& encoder, const Instruction& instr) +{ + instr.visit(encoder); // Throws +} + +inline StringData ChangesetEncoder::get_string(StringBufferRange range) const noexcept +{ + const char* data = m_string_range.data() + range.offset; + std::size_t size = std::size_t(range.size); + return StringData{data, size}; +} + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_CHANGESET_ENCODER_HPP diff --git a/Pods/Realm/include/core/realm/sync/changeset_parser.hpp b/Pods/Realm/include/core/realm/sync/changeset_parser.hpp new file mode 100644 index 0000000000..f331569893 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/changeset_parser.hpp @@ -0,0 +1,47 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2017] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_SYNC_CHANGESET_PARSER_HPP +#define REALM_SYNC_CHANGESET_PARSER_HPP + +#include +#include + +namespace realm { +namespace sync { + +struct ChangesetParser { + /// Throws BadChangesetError if parsing fails. + /// + /// FIXME: Consider using std::error_code instead of throwing exceptions on + /// parse errors. + void parse(_impl::NoCopyInputStream&, InstructionHandler&); +private: + struct State; +}; + +void parse_changeset(_impl::NoCopyInputStream&, Changeset& out_log); +void parse_changeset(_impl::InputStream&, Changeset& out_log); + + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_CHANGESET_PARSER_HPP diff --git a/Pods/Realm/include/core/realm/sync/client.hpp b/Pods/Realm/include/core/realm/sync/client.hpp new file mode 100644 index 0000000000..c7fb1bf1c0 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/client.hpp @@ -0,0 +1,1113 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2012] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_SYNC_CLIENT_HPP +#define REALM_SYNC_CLIENT_HPP + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace realm { +namespace sync { + +/// Supported protocols: +/// +/// Protocol URL scheme Default port +/// ----------------------------------------------------------------------------------- +/// realm "realm:" 7800 (80 if Client::Config::enable_default_port_hack) +/// realm_ssl "realms:" 7801 (443 if Client::Config::enable_default_port_hack) +/// +enum class Protocol { + realm, + realm_ssl +}; + + +class Client { +public: + enum class Error; + + enum class ReconnectMode { + /// This is the mode that should always be used in production. In this + /// mode the client uses a scheme for determining a reconnect delay that + /// prevents it from creating too many connection requests in a short + /// amount of time (i.e., a server hammering protection mechanism). + normal, + + /// For testing purposes only. + /// + /// Never reconnect automatically after the connection is closed due to + /// an error. Allow immediate reconnect if the connection was closed + /// voluntarily (e.g., due to sessions being abandoned). + /// + /// In this mode, Client::cancel_reconnect_delay() and + /// Session::cancel_reconnect_delay() can still be used to trigger + /// another reconnection attempt (with no delay) after an error has + /// caused the connection to be closed. + testing + }; + + using port_type = util::network::Endpoint::port_type; + using RoundtripTimeHandler = void(milliseconds_type roundtrip_time); + + // FIXME: The default values for `connect_timeout`, `ping_keepalive_period`, + // and `pong_keepalive_timeout` ought to be much lower (2 minutes, 1 minute, + // and 2 minutes) than they are. Their current values are due to the fact + // that the server is single threaded, and that some operations take more + // than 5 minutes to complete. + static constexpr milliseconds_type default_connect_timeout = 600000; // 10 minutes + static constexpr milliseconds_type default_connection_linger_time = 30000; // 30 seconds + static constexpr milliseconds_type default_ping_keepalive_period = 600000; // 10 minutes + static constexpr milliseconds_type default_pong_keepalive_timeout = 600000; // 10 minutes + static constexpr milliseconds_type default_fast_reconnect_limit = 60000; // 1 minute + + struct Config { + Config() {} + + /// The maximum number of Realm files that will be kept open + /// concurrently by this client. The client keeps a cache of open Realm + /// files for efficiency reasons. + long max_open_files = 256; + + /// An optional logger to be used by the client. If no logger is + /// specified, the client will use an instance of util::StderrLogger + /// with the log level threshold set to util::Logger::Level::info. The + /// client does not require a thread-safe logger, and it guarantees that + /// all logging happens either on behalf of the constructor or on behalf + /// of the invocation of run(). + util::Logger* logger = nullptr; + + /// Use ports 80 and 443 by default instead of 7800 and 7801 + /// respectively. Ideally, these default ports should have been made + /// available via a different URI scheme instead (http/https or ws/wss). + bool enable_default_port_hack = true; + + /// For testing purposes only. + ReconnectMode reconnect_mode = ReconnectMode::normal; + + /// Create a separate connection for each session. For testing purposes + /// only. + /// + /// FIXME: This setting needs to be true for now, due to limitations in + /// the load balancer. + bool one_connection_per_session = true; + + /// Do not access the local file system. Sessions will act as if + /// initiated on behalf of an empty (or nonexisting) local Realm + /// file. Received DOWNLOAD messages will be accepted, but otherwise + /// ignored. No UPLOAD messages will be generated. For testing purposes + /// only. + bool dry_run = false; + + /// The default changeset cooker to be used by new sessions. Can be + /// overridden by Session::Config::changeset_cooker. + /// + /// \sa make_client_history(), TrivialChangesetCooker. + std::shared_ptr changeset_cooker; + + /// The maximum number of milliseconds to allow for a connection to + /// become fully established. This includes the time to resolve the + /// network address, the TCP connect operation, the SSL handshake, and + /// the WebSocket handshake. + milliseconds_type connect_timeout = default_connect_timeout; + + /// The number of milliseconds to keep a connection open after all + /// sessions have been abandoned (or suspended by errors). + /// + /// The purpose of this linger time is to avoid close/reopen cycles + /// during short periods of time where there are no sessions interested + /// in using the connection. + /// + /// If the connection gets closed due to an error before the linger time + /// expires, the connection will be kept closed until there are sessions + /// willing to use it again. + milliseconds_type connection_linger_time = default_connection_linger_time; + + /// The client will send PING messages periodically to allow the server + /// to detect dead connections (heartbeat). This parameter specifies the + /// time, in milliseconds, between these PING messages. When scheduling + /// the next PING message, the client will deduct a small random amount + /// from the specified value to help spread the load on the server from + /// many clients. + milliseconds_type ping_keepalive_period = default_ping_keepalive_period; + + /// Whenever the server receives a PING message, it is supposed to + /// respond with a PONG messsage to allow the client to detect dead + /// connections (heartbeat). This parameter specifies the time, in + /// milliseconds, that the client will wait for the PONG response + /// message before it assumes that the connection is dead, and + /// terminates it. + milliseconds_type pong_keepalive_timeout = default_pong_keepalive_timeout; + + /// The maximum amount of time, in milliseconds, since the loss of a + /// prior connection, for a new connection to be considered a *fast + /// reconnect*. + /// + /// In general, when a client establishes a connection to the server, + /// the uploading process remains suspended until the initial + /// downloading process completes (as if by invocation of + /// Session::async_wait_for_download_completion()). However, to avoid + /// unnecessary latency in change propagation during ongoing + /// application-level activity, if the new connection is established + /// less than a certain amount of time (`fast_reconnect_limit`) since + /// the client was previously connected to the server, then the + /// uploading process will be activated immediately. + /// + /// For now, the purpose of the general delaying of the activation of + /// the uploading process, is to increase the chance of multiple initial + /// transactions on the client-side, to be uploaded to, and processed by + /// the server as a single unit. In the longer run, the intention is + /// that the client should upload transformed (from reciprocal history), + /// rather than original changesets when applicable to reduce the need + /// for changeset to be transformed on both sides. The delaying of the + /// upload process will increase the number of cases where this is + /// possible. + /// + /// FIXME: Currently, the time between connections is not tracked across + /// sessions, so if the application closes its session, and opens a new + /// one immediately afterwards, the activation of the upload process + /// will be delayed unconditionally. + milliseconds_type fast_reconnect_limit = default_fast_reconnect_limit; + + /// Set to true to completely disable delaying of the upload process. In + /// this mode, the upload process will be activated immediately, and the + /// value of `fast_reconnect_limit` is ignored. + /// + /// For testing purposes only. + bool disable_upload_activation_delay = false; + + /// If enable_upload_log_compaction is true, every changeset will be + /// compacted before it is uploaded to the server. Compaction will + /// reduce the size of a changeset if the same field is set multiple + /// times or if newly created objects are deleted within the same + /// transaction. Log compaction increeses CPU usage and memory + /// consumption. + bool enable_upload_log_compaction = true; + + /// Set the `TCP_NODELAY` option on all TCP/IP sockets. This disables + /// the Nagle algorithm. Disabling it, can in some cases be used to + /// decrease latencies, but possibly at the expense of scalability. Be + /// sure to research the subject before you enable this option. + bool tcp_no_delay = false; + + /// The specified function will be called whenever a PONG message is + /// received on any connection. The round-trip time in milliseconds will + /// be pased to the function. The specified function will always be + /// called by the client's event loop thread, i.e., the thread that + /// calls `Client::run()`. This feature is mainly for testing purposes. + std::function roundtrip_time_handler; + }; + + /// \throw util::EventLoop::Implementation::NotAvailable if no event loop + /// implementation was specified, and + /// util::EventLoop::Implementation::get_default() throws it. + Client(Config = {}); + Client(Client&&) noexcept; + ~Client() noexcept; + + /// Run the internal event-loop of the client. At most one thread may + /// execute run() at any given time. The call will not return until somebody + /// calls stop(). + void run(); + + /// See run(). + /// + /// Thread-safe. + void stop() noexcept; + + /// \brief Cancel current or next reconnect delay for all servers. + /// + /// This corresponds to calling Session::cancel_reconnect_delay() on all + /// bound sessions, but will also cancel reconnect delays applying to + /// servers for which there are currently no bound sessions. + /// + /// Thread-safe. + void cancel_reconnect_delay(); + + /// \brief Wait for session termination to complete. + /// + /// Wait for termination of all sessions whose termination was initiated + /// prior this call (the completion condition), or until the client's event + /// loop thread exits from Client::run(), whichever happens + /// first. Termination of a session can be initiated implicitly (e.g., via + /// destruction of the session object), or explicitly by Session::detach(). + /// + /// Note: After session termination (when this function returns true) no + /// session specific callback function can be called or continue to execute, + /// and the client is guaranteed to no longer have a Realm file open on + /// behalf of the terminated session. + /// + /// CAUTION: If run() returns while a wait operation is in progress, this + /// waiting function will return immediately, even if the completion + /// condition is not yet satisfied. The completion condition is guaranteed + /// to be satisfied only when these functions return true. If it returns + /// false, session specific callback functions may still be executing or get + /// called, and the associated Realm files may still not have been closed. + /// + /// If a new wait operation is initiated while another wait operation is in + /// progress by another thread, the waiting period of fist operation may, or + /// may not get extended. The application must not assume either. + /// + /// Note: Session termination does not imply that the client has received an + /// UNBOUND message from the server (see the protocol specification). This + /// may happen later. + /// + /// \return True only if the completion condition was satisfied. False if + /// the client's event loop thread exited from Client::run() in which case + /// the completion condition may, or may not have been satisfied. + /// + /// Note: These functions are fully thread-safe. That is, they may be called + /// by any thread, and by multiple threads concurrently. + bool wait_for_session_terminations_or_client_stopped(); + + /// Returns false if the specified URL is invalid. + bool decompose_server_url(const std::string& url, Protocol& protocol, std::string& address, + port_type& port, std::string& path) const; + +private: + class Impl; + std::unique_ptr m_impl; + friend class Session; +}; + + +class BadServerUrl; // Exception + + +/// \brief Client-side representation of a Realm file synchronization session. +/// +/// A synchronization session deals with precisely one local Realm file. To +/// synchronize multiple local Realm files, you need multiple sessions. +/// +/// A session object is always associated with a particular client object (\ref +/// Client). The application must ensure that the destruction of the associated +/// client object never happens before the destruction of the session +/// object. The consequences of a violation are unspecified. +/// +/// A session object is always associated with a particular local Realm file, +/// however, a session object does not represent a session until it is bound to +/// a server side Realm, i.e., until bind() is called. From the point of view of +/// the thread that calls bind(), the session starts precisely when the +/// execution of bind() starts, i.e., before bind() returns. +/// +/// At most one session is allowed to exist for a particular local Realm file +/// (file system inode) at any point in time. Multiple session objects may +/// coexists for a single file, as long as bind() has been called on at most one +/// of them. Additionally, two bound session objects for the same file are +/// allowed to exist at different times, if they have no overlap in time (in +/// their bound state), as long as they are associated with the same client +/// object, or with two different client objects that do not overlap in +/// time. This means, in particular, that it is an error to create two bound +/// session objects for the same local Realm file, it they are associated with +/// two different client objects that overlap in time, even if the session +/// objects do not overlap in time (in their bound state). It is the +/// responsibility of the application to ensure that these rules are adhered +/// to. The consequences of a violation are unspecified. +/// +/// Thread-safety: It is safe for multiple threads to construct, use (with some +/// exceptions), and destroy session objects concurrently, regardless of whether +/// those session objects are associated with the same, or with different Client +/// objects. Please note that some of the public member functions are fully +/// thread-safe, while others are not. +/// +/// Callback semantics: All session specific callback functions will be executed +/// by the event loop thread, i.e., the thread that calls Client::run(). No +/// callback function will be called before Session::bind() is called. Callback +/// functions that are specified prior to calling bind() (e.g., any passed to +/// set_progress_handler()) may start to execute before bind() returns, as long +/// as some thread is executing Client::run(). Likewise, completion handlers, +/// such as those passed to async_wait_for_sync_completion() may start to +/// execute before the submitting function returns. All session specific +/// callback functions (including completion handlers) are guaranteed to no +/// longer be executing when session termination completes, and they are +/// guaranteed to not be called after session termination completes. Termination +/// is an event that completes asynchronously with respect to the application, +/// but is initiated by calling detach(), or implicitely by destroying a session +/// object. After having initiated one or more session terminations, the +/// application can wait for those terminations to complete by calling +/// Client::wait_for_session_terminations_or_client_stopped(). Since callback +/// functinos are always executed by the event loop thread, they are also +/// guaranteed to not be executing after Client::run() has returned. +class Session { +public: + using port_type = util::network::Endpoint::port_type; + using SyncTransactCallback = void(VersionID old_version, VersionID new_version); + using ProgressHandler = void(std::uint_fast64_t downloaded_bytes, + std::uint_fast64_t downloadable_bytes, + std::uint_fast64_t uploaded_bytes, + std::uint_fast64_t uploadable_bytes, + std::uint_fast64_t progress_version, + std::uint_fast64_t snapshot_version); + using WaitOperCompletionHandler = std::function; + using SSLVerifyCallback = bool(const std::string& server_address, + port_type server_port, + const char* pem_data, + size_t pem_size, + int preverify_ok, + int depth); + + class Config { + public: + Config() {} + + /// server_address is the fully qualified host name, or IP address of + /// the server. + std::string server_address = "localhost"; + + /// server_port is the port at which the server listens. If server_port + /// is zero, the default port for the specified protocol is used. See \ref + /// Protocol for information on default ports. + port_type server_port = 0; + + /// server_path is the virtual path by which the server identifies the + /// Realm. This path must always be an absolute path, and must therefore + /// always contain a leading slash (`/`). Further more, each segment of the + /// virtual path must consist of one or more characters that are either + /// alpha-numeric or in (`_`, `-`, `.`), and each segment is not allowed to + /// equal `.` or `..`, and must not end with `.realm`, `.realm.lock`, or + /// `.realm.management`. These rules are necessary because the server + /// currently reserves the right to use the specified path as part of the + /// file system path of a Realm file. It is expected that these rules will + /// be significantly relaxed in the future by completely decoupling the + /// virtual paths from actual file system paths. + std::string server_path = "/"; + + /// The protocol used for communicating with the server. See \ref Protocol. + Protocol protocol = Protocol::realm; + + /// url_prefix is a prefix that is prepended to the server_path + /// in the HTTP GET request that initiates a sync connection. The value + /// specified here must match with the server's expectation. Changing + /// the value of url_prefix should be matched with a corresponding + /// change of the server side proxy. + std::string url_prefix = "/realm-sync"; + + /// authorization_header_name is the name of the HTTP header containing + /// the Realm access token. The value of the HTTP header is + /// "Realm-Access-Token version=1 token=....". + /// authorization_header_name does not participate in session + /// multiplexing partitioning. + std::string authorization_header_name = "Authorization"; + + /// custom_http_headers is a map of custom HTTP headers. The keys of the map + /// are HTTP header names, and the values are the corresponding HTTP + /// header values. + /// If "Authorization" is used as a custom header name, + /// authorization_header_name must be set to anther value. + std::map custom_http_headers; + + /// Sessions can be multiplexed over the same TCP/SSL connection. + /// Sessions might share connection if they have identical server_address, + /// server_port, and protocol. multiplex_ident is a parameter that allows + /// finer control over session multiplexing. If two sessions have distinct + /// multiplex_ident, they will never share connection. The typical use of + /// multilex_ident is to give sessions with incompatible SSL requirements + /// distinct multiplex_idents. + /// multiplex_ident can be any string and the value has no meaning except + /// for partitioning the sessions. + std::string multiplex_ident; + + /// verify_servers_ssl_certificate controls whether the server + /// certificate is verified for SSL connections. It should generally be + /// true in production. + bool verify_servers_ssl_certificate = true; + + /// ssl_trust_certificate_path is the path of a trust/anchor + /// certificate used by the client to verify the server certificate. + /// ssl_trust_certificate_path is only used if the protocol is ssl and + /// verify_servers_ssl_certificate is true. + /// + /// A server certificate is verified by first checking that the + /// certificate has a valid signature chain back to a trust/anchor + /// certificate, and secondly checking that the server_address matches + /// a host name contained in the certificate. The host name of the + /// certificate is stored in either Common Name or the Alternative + /// Subject Name (DNS section). + /// + /// If ssl_trust_certificate_path is None (default), ssl_verify_callback + /// (see below) is used if set, and the default device trust/anchor + /// store is used otherwise. + Optional ssl_trust_certificate_path; + + /// If Client::Config::ssl_verify_callback is set, that function is called + /// to verify the certificate, unless verify_servers_ssl_certificate is + /// false. + + /// ssl_verify_callback is used to implement custom SSL certificate + /// verification. it is only used if the protocol is SSL, + /// verify_servers_ssl_certificate is true and ssl_trust_certificate_path + /// is None. + /// + /// The signature of ssl_verify_callback is + /// + /// bool(const std::string& server_address, + /// port_type server_port, + /// const char* pem_data, + /// size_t pem_size, + /// int preverify_ok, + /// int depth); + /// + /// server address and server_port is the address and port of the server + /// that a SSL connection is being established to. They are identical to + /// the server_address and server_port set in this config file and are + /// passed for convenience. + /// pem_data is the certificate of length pem_size in + /// the PEM format. preverify_ok is OpenSSL's preverification of the + /// certificate. preverify_ok is either 0, or 1. If preverify_ok is 1, + /// OpenSSL has accepted the certificate and it will generally be safe + /// to trust that certificate. depth represents the position of the + /// certificate in the certificate chain sent by the server. depth = 0 + /// represents the actual server certificate that should contain the + /// host name(server address) of the server. The highest depth is the + /// root certificate. + /// The callback function will receive the certificates starting from + /// the root certificate and moving down the chain until it reaches the + /// server's own certificate with a host name. The depth of the last + /// certificate is 0. The depth of the first certificate is chain + /// length - 1. + /// + /// The return value of the callback function decides whether the + /// client accepts the certificate. If the return value is false, the + /// processing of the certificate chain is interrupted and the SSL + /// connection is rejected. If the return value is true, the verification + /// process continues. If the callback function returns true for all + /// presented certificates including the depth == 0 certificate, the + /// SSL connection is accepted. + /// + /// A recommended way of using the callback function is to return true + /// if preverify_ok = 1 and depth > 0, + /// always check the host name if depth = 0, + /// and use an independent verification step if preverify_ok = 0. + /// + /// Another possible way of using the callback is to collect all the + /// certificates until depth = 0, and present the entire chain for + /// independent verification. + std::function ssl_verify_callback; + + /// signed_user_token is a cryptographically signed token describing the + /// identity and access rights of the current user. + std::string signed_user_token; + + /// If not null, overrides whatever is specified by + /// Client::Config::changeset_cooker. + /// + /// The shared ownership over the cooker will be relinquished shortly + /// after the destruction of the session object as long as the event + /// loop of the client is being executed (Client::run()). + /// + /// CAUTION: ChangesetCooker::cook_changeset() of the specified cooker + /// may get called before the call to bind() returns, and it may get + /// called (or continue to execute) after the session object is + /// destroyed. Please see "Callback semantics" section under Client for + /// more on this. + /// + /// \sa make_client_history(), TrivialChangesetCooker. + std::shared_ptr changeset_cooker; + + /// The encryption key the SharedGroup will be opened with. + Optional> encryption_key; + }; + + /// \brief Start a new session for the specified client-side Realm. + /// + /// Note that the session is not fully activated until you call bind(). Also + /// note that if you call set_sync_transact_callback(), it must be done + /// before calling bind(). + /// + /// \param realm_path The file-system path of a local client-side Realm + /// file. + Session(Client&, std::string realm_path, Config = {}); + + /// This leaves the right-hand side session object detached. See "Thread + /// safety" section under detach(). + Session(Session&&) noexcept; + + /// Create a detached session object (see detach()). + Session() noexcept; + + /// Implies detachment. See "Thread safety" section under detach(). + ~Session() noexcept; + + /// Detach the object on the left-hand side, then "steal" the session from + /// the object on the right-hand side, if there is one. This leaves the + /// object on the right-hand side detached. See "Thread safety" section + /// under detach(). + Session& operator=(Session&&) noexcept; + + /// Detach this sesion object from the client object (Client). If the + /// session object is already detached, this function has no effect + /// (idempotency). + /// + /// Detachment initiates session termination, which is an event that takes + /// place shortly therafter in the context of the client's event loop + /// thread. + /// + /// A detached session object may be destroyed, move-assigned to, and moved + /// from. Apart from that, it is an error to call any function other than + /// detach() on a detached session object. + /// + /// Thread safety: Detachment is not a thread-safe operation. This means + /// that detach() may not be executed by two threads concurrently, and may + /// not execute concurrently with object destruction. Additionally, + /// detachment must not execute concurrently with a moving operation + /// involving the session object on the left or right-hand side. See move + /// constructor and assigment operator. + void detach() noexcept; + + /// \brief Set a function to be called when the local Realm has changed due + /// to integration of a downloaded changeset. + /// + /// Specify the callback function that will be called when one or more + /// transactions are performed to integrate downloaded changesets into the + /// client-side Realm, that is associated with this session. + /// + /// The callback function will always be called by the thread that executes + /// the event loop (Client::run()), but not until bind() is called. If the + /// callback function throws an exception, that exception will "travel" out + /// through Client::run(). + /// + /// Note: Any call to this function must have returned before bind() is + /// called. If this function is called multiple times, each call overrides + /// the previous setting. + /// + /// Note: This function is **not thread-safe**. That is, it is an error if + /// it is called while another thread is executing any member function on + /// the same Session object. + /// + /// CAUTION: The specified callback function may get called before the call + /// to bind() returns, and it may get called (or continue to execute) after + /// the session object is destroyed. Please see "Callback semantics" section + /// under Session for more on this. + void set_sync_transact_callback(std::function); + + /// \brief Set a handler to monitor the state of download and upload + /// progress. + /// + /// The handler must have signature + /// + /// void(uint_fast64_t downloaded_bytes, uint_fast64_t downloadable_bytes, + /// uint_fast64_t uploaded_bytes, uint_fast64_t uploadable_bytes, + /// uint_fast64_t progress_version); + /// + /// downloaded_bytes is the size in bytes of all downloaded changesets. + /// downloadable_bytes is the size in bytes of the part of the server + /// history that do not originate from this client. + /// + /// uploaded_bytes is the size in bytes of all locally produced changesets + /// that have been received and acknowledged by the server. + /// uploadable_bytes is the size in bytes of all locally produced changesets. + /// + /// Due to the nature of the merge rules, it is possible that the size of an + /// uploaded changeset uploaded from one client is not equal to the size of + /// the changesets that other clients will download. + /// + /// Typical uses of this function: + /// + /// Upload completion can be checked by + /// + /// bool upload_complete = (uploaded_bytes == uploadable_bytes); + /// + /// Download completion could be checked by + /// + /// bool download_complete = (downloaded_bytes == downloadable_bytes); + /// + /// However, download completion might never be reached because the server + /// can receive new changesets from other clients. + /// An alternative strategy is to cache downloadable_bytes from the callback, + /// and use the cached value as the threshold. + /// + /// bool download_complete = (downloaded_bytes == cached_downloadable_bytes); + /// + /// Upload progress can be calculated by caching an initial value of + /// uploaded_bytes from the last, or next, callback. Then + /// + /// double upload_progress = + /// (uploaded_bytes - initial_uploaded_bytes) + /// ------------------------------------------- + /// (uploadable_bytes - initial_uploaded_bytes) + /// + /// Download progress can be calculates similarly: + /// + /// double download_progress = + /// (downloaded_bytes - initial_downloaded_bytes) + /// ----------------------------------------------- + /// (downloadable_bytes - initial_downloaded_bytes) + /// + /// progress_version is 0 at the start of a session. When at least one + /// DOWNLOAD message has been received from the server, progress_version is + /// positive. progress_version can be used to ensure that the reported + /// progress contains information obtained from the server in the current + /// session. The server will send a message as soon as possible, and the + /// progress handler will eventually be called with a positive progress_version + /// unless the session is interrupted before a message from the server has + /// been received. + /// + /// The handler is called on the event loop thread.The handler after bind(), + /// after each DOWNLOAD message, and after each local transaction + /// (nonsync_transact_notify). + /// + /// set_progress_handler() is not thread safe and it must be called before + /// bind() is called. Subsequent calls to set_progress_handler() overwrite + /// the previous calls. Typically, this function is called once per session. + /// + /// CAUTION: The specified callback function may get called before the call + /// to bind() returns, and it may get called (or continue to execute) after + /// the session object is destroyed. Please see "Callback semantics" section + /// under Session for more on this. + void set_progress_handler(std::function); + + enum class ConnectionState { disconnected, connecting, connected }; + + /// \brief Information about an error causing a session to be temporarily + /// disconnected from the server. + /// + /// In general, the connection will be automatically reestablished + /// later. Whether this happens quickly, generally depends on \ref + /// is_fatal. If \ref is_fatal is true, it means that the error is deemed to + /// be of a kind that is likely to persist, and cause all future reconnect + /// attempts to fail. In that case, if another attempt is made at + /// reconnecting, the delay will be substantial (at least an hour). + /// + /// \ref error_code specifies the error that caused the connection to be + /// closed. For the list of errors reported by the server, see \ref + /// ProtocolError (or `protocol.md`). For the list of errors corresponding + /// to protocol violations that are detected by the client, see + /// Client::Error. The error may also be a system level error, or an error + /// from one of the potential intermediate protocol layers (SSL or + /// WebSocket). + /// + /// \ref detailed_message is the most detailed message available to describe + /// the error. It is generally equal to `error_code.message()`, but may also + /// be a more specific message (one that provides extra context). The + /// purpose of this message is mostly to aid in debugging. For non-debugging + /// purposes, `error_code.message()` should generally be considered + /// sufficient. + /// + /// \sa set_connection_state_change_listener(). + struct ErrorInfo { + std::error_code error_code; + bool is_fatal; + const std::string& detailed_message; + }; + + using ConnectionStateChangeListener = void(ConnectionState, const ErrorInfo*); + + /// \brief Install a connection state change listener. + /// + /// Sets a function to be called whenever the state of the underlying + /// network connection changes between "disconnected", "connecting", and + /// "connected". The initial state is always "disconnected". The next state + /// after "disconnected" is always "connecting". The next state after + /// "connecting" is either "connected" or "disconnected". The next state + /// after "connected" is always "disconnected". A switch to the + /// "disconnected" state only happens when an error occurs. + /// + /// Whenever the installed function is called, an ErrorInfo object is passed + /// when, and only when the passed state is ConnectionState::disconnected. + /// + /// When multiple sessions share a single connection, the state changes will + /// be reported for each session in turn. + /// + /// The callback function will always be called by the thread that executes + /// the event loop (Client::run()), but not until bind() is called. If the + /// callback function throws an exception, that exception will "travel" out + /// through Client::run(). + /// + /// Note: Any call to this function must have returned before bind() is + /// called. If this function is called multiple times, each call overrides + /// the previous setting. + /// + /// Note: This function is **not thread-safe**. That is, it is an error if + /// it is called while another thread is executing any member function on + /// the same Session object. + /// + /// CAUTION: The specified callback function may get called before the call + /// to bind() returns, and it may get called (or continue to execute) after + /// the session object is destroyed. Please see "Callback semantics" section + /// under Session for more on this. + void set_connection_state_change_listener(std::function); + + //@{ + /// Deprecated! Use set_connection_state_change_listener() instead. + using ErrorHandler = void(std::error_code, bool is_fatal, const std::string& detailed_message); + void set_error_handler(std::function); + //@} + + /// @{ \brief Bind this session to the specified server side Realm. + /// + /// No communication takes place on behalf of this session before the + /// session is bound, but as soon as the session becomes bound, the server + /// will start to push changes to the client, and vice versa. + /// + /// If a callback function was set using set_sync_transact_callback(), then + /// that callback function will start to be called as changesets are + /// downloaded and integrated locally. It is important to understand that + /// callback functions are executed by the event loop thread (Client::run()) + /// and the callback function may therefore be called before bind() returns. + /// + /// Note: It is an error if this function is called more than once per + /// Session object. + /// + /// Note: This function is **not thread-safe**. That is, it is an error if + /// it is called while another thread is executing any member function on + /// the same Session object. + /// + /// bind() binds this session to the specified server side Realm using the + /// parameters specified in the Session::Config object. + /// + /// The two other forms of bind() are convenience functions. + /// void bind(std::string server_address, std::string server_path, + /// std::string signed_user_token, port_type server_port = 0, + /// Protocol protocol = Protocol::realm); + /// replaces the corresponding parameters from the Session::Config object + /// before the session is bound. + /// void bind(std::string server_url, std::string signed_user_token) parses + /// the \param server_url and replaces the parameters in the Session::Config object + /// before the session is bound. + /// + /// \param server_url For example "realm://sync.realm.io/test". See + /// server_address, server_path, and server_port in Session::Config for information + /// about the individual components of the URL. See \ref Protocol for the list of + /// available URL schemes and the associated default ports. + /// + /// \throw BadServerUrl if the specified server URL is malformed. + void bind(); + void bind(std::string server_url, std::string signed_user_token); + void bind(std::string server_address, std::string server_path, + std::string signed_user_token, port_type server_port = 0, + Protocol protocol = Protocol::realm); + /// @} + + /// \brief Refresh the access token associated with this session. + /// + /// This causes the REFRESH protocol message to be sent to the server. See + /// \ref Protocol. + /// + /// In an on-going session the application may expect the access token to + /// expire at a certain time and schedule acquisition of a fresh access + /// token (using a refresh token or by other means) in due time to provide a + /// better user experience, and seamless connectivity to the server. + /// + /// If the application does not proactively refresh an expiring token, the + /// session will eventually be disconnected. The application can detect this + /// by monitoring the connection state + /// (set_connection_state_change_listener()), and check whether the error + /// code is `ProtocolError::token_expired`. Such a session can then be + /// revived by calling refresh() with a newly acquired access token. + /// + /// Due to protocol techicalities, a race condition exists that can cause a + /// session to become, and remain disconnected after a new access token has + /// been passed to refresh(). The application can work around this race + /// condition by detecting the `ProtocolError::token_expired` error, and + /// always initiate a token renewal in this case. + /// + /// It is an error to call this function before calling `Client::bind()`. + /// + /// Note: This function is thread-safe. + /// + /// \param signed_user_token A cryptographically signed token describing the + /// identity and access rights of the current user. See \ref Protocol. + void refresh(std::string signed_user_token); + + /// \brief Inform the synchronization agent about changes of local origin. + /// + /// This function must be called by the application after a transaction + /// performed on its behalf, that is, after a transaction that is not + /// performed to integrate a changeset that was downloaded from the server. + /// + /// It is an error to call this function before bind() has been called, and + /// has returned. + /// + /// Note: This function is fully thread-safe. That is, it may be called by + /// any thread, and by multiple threads concurrently. + void nonsync_transact_notify(version_type new_version); + + /// @{ \brief Wait for upload, download, or upload+download completion. + /// + /// async_wait_for_upload_completion() initiates an asynchronous wait for + /// upload to complete, async_wait_for_download_completion() initiates an + /// asynchronous wait for download to complete, and + /// async_wait_for_sync_completion() initiates an asynchronous wait for + /// upload and download to complete. + /// + /// Upload is considered complete when all non-empty changesets of local + /// origin have been uploaded to the server, and the server has acknowledged + /// reception of them. Changesets of local origin introduced after the + /// initiation of the session (after bind() is called) will generally not be + /// considered for upload unless they are announced to this client through + /// nonsync_transact_notify() prior to the initiation of the wait operation, + /// i.e., prior to the invocation of async_wait_for_upload_completion() or + /// async_wait_for_sync_completion(). Unannounced changesets may get picked + /// up, but there is no guarantee that they will be, however, if a certain + /// changeset is announced, then all previous changesets are implicitly + /// announced. Also all preexisting changesets are implicitly announced + /// when the session is initiated. + /// + /// Download is considered complete when all non-empty changesets of remote + /// origin have been downloaded from the server, and integrated into the + /// local Realm state. To know what is currently outstanding on the server, + /// the client always sends a special "marker" message to the server, and + /// waits until it has downloaded all outstanding changesets that were + /// present on the server at the time when the server received that marker + /// message. Each call to async_wait_for_download_completion() and + /// async_wait_for_sync_completion() therefore requires a full client <-> + /// server round-trip. + /// + /// If a new wait operation is initiated while another wait operation is in + /// progress by another thread, the waiting period of first operation may, + /// or may not get extended. The application must not assume either. The + /// application may assume, however, that async_wait_for_upload_completion() + /// will not affect the waiting period of + /// async_wait_for_download_completion(), and vice versa. + /// + /// It is an error to call these functions before bind() has been called, + /// and has returned. + /// + /// The specified completion handlers will always be executed by the thread + /// that executes the event loop (the thread that calls Client::run()). If + /// the handler throws an exception, that exception will "travel" out + /// through Client::run(). + /// + /// If incomplete wait operations exist when the session is terminated, + /// those wait operations will be canceled. Session termination is an event + /// that happens in the context of the client's event loop thread shortly + /// after the destruction of the session object. The std::error_code + /// argument passed to the completion handler of a canceled wait operation + /// will be `util::error::operation_aborted`. For uncanceled wait operations + /// it will be `std::error_code{}`. Note that as long as the client's event + /// loop thread is running, all completion handlers will be called + /// regardless of whether the operations get canceled or not. + /// + /// CAUTION: The specified completion handlers may get called before the + /// call to the waiting function returns, and it may get called (or continue + /// to execute) after the session object is destroyed. Please see "Callback + /// semantics" section under Session for more on this. + /// + /// Note: These functions are fully thread-safe. That is, they may be called + /// by any thread, and by multiple threads concurrently. + void async_wait_for_sync_completion(WaitOperCompletionHandler); + void async_wait_for_upload_completion(WaitOperCompletionHandler); + void async_wait_for_download_completion(WaitOperCompletionHandler); + /// @} + + /// @{ \brief Synchronous wait for upload or download completion. + /// + /// These functions are synchronous equivalents to + /// async_wait_for_upload_completion() and + /// async_wait_for_download_completion() respectively. This means that they + /// block the caller until the completion condition is satisfied, or the + /// client's event loop thread exits from Client::run(), whichever happens + /// first. + /// + /// It is an error to call these functions before bind() has been called, + /// and has returned. + /// + /// CAUTION: If Client::run() returns while a wait operation is in progress, + /// these waiting functions return immediately, even if the completion + /// condition is not yet satisfied. The completion condition is guaranteed + /// to be satisfied only when these functions return true. + /// + /// \return True only if the completion condition was satisfied. False if + /// the client's event loop thread exited from Client::run() in which case + /// the completion condition may, or may not have been satisfied. + /// + /// Note: These functions are fully thread-safe. That is, they may be called + /// by any thread, and by multiple threads concurrently. + bool wait_for_upload_complete_or_client_stopped(); + bool wait_for_download_complete_or_client_stopped(); + /// @} + + /// \brief Cancel the current or next reconnect delay for the server + /// associated with this session. + /// + /// When the network connection is severed, or an attempt to establish + /// connection fails, a certain delay will take effect before the client + /// will attempt to reestablish the connection. This delay will generally + /// grow with the number of unsuccessful reconnect attempts, and can grow to + /// over a minute. In some cases however, the application will know when it + /// is a good time to stop waiting and retry immediately. One example is + /// when a device has been offline for a while, and the operating system + /// then tells the application that network connectivity has been restored. + /// + /// Clearly, this function should not be called too often and over extended + /// periods of time, as that would effectively disable the built-in "server + /// hammering" protection. + /// + /// It is an error to call this function before bind() has been called, and + /// has returned. + /// + /// This function is fully thread-safe. That is, it may be called by any + /// thread, and by multiple threads concurrently. + void cancel_reconnect_delay(); + + /// \brief Change address of server for this session. + void override_server(std::string address, port_type); + +private: + class Impl; + Impl* m_impl = nullptr; + + void abandon() noexcept; + void async_wait_for(bool upload_completion, bool download_completion, + WaitOperCompletionHandler); +}; + + +/// \brief Protocol errors discovered by the client. +/// +/// These errors will terminate the network connection (disconnect all sessions +/// associated with the affected connection), and the error will be reported to +/// the application via the connection state change listeners of the affected +/// sessions. +enum class Client::Error { + connection_closed = 100, ///< Connection closed (no error) + unknown_message = 101, ///< Unknown type of input message + bad_syntax = 102, ///< Bad syntax in input message head + limits_exceeded = 103, ///< Limits exceeded in input message + bad_session_ident = 104, ///< Bad session identifier in input message + bad_message_order = 105, ///< Bad input message order + bad_client_file_ident = 106, ///< Bad client file identifier (IDENT) + bad_progress = 107, ///< Bad progress information (DOWNLOAD) + bad_changeset_header_syntax = 108, ///< Bad syntax in changeset header (DOWNLOAD) + bad_changeset_size = 109, ///< Bad changeset size in changeset header (DOWNLOAD) + bad_origin_file_ident = 110, ///< Bad origin file identifier in changeset header (DOWNLOAD) + bad_server_version = 111, ///< Bad server version in changeset header (DOWNLOAD) + bad_changeset = 112, ///< Bad changeset (DOWNLOAD) + bad_request_ident = 113, ///< Bad request identifier (MARK) + bad_error_code = 114, ///< Bad error code (ERROR), + bad_compression = 115, ///< Bad compression (DOWNLOAD) + bad_client_version = 116, ///< Bad last integrated client version in changeset header (DOWNLOAD) + ssl_server_cert_rejected = 117, ///< SSL server certificate rejected + pong_timeout = 118, ///< Timeout on reception of PONG respone message + bad_client_file_ident_salt = 119, ///< Bad client file identifier salt (IDENT) + bad_file_ident = 120, ///< Bad file identifier (ALLOC) + connect_timeout = 121, ///< Sync connection was not fully established in time + bad_timestamp = 122, ///< Bad timestamp (PONG) +}; + +const std::error_category& client_error_category() noexcept; + +std::error_code make_error_code(Client::Error) noexcept; + +} // namespace sync +} // namespace realm + +namespace std { + +template<> struct is_error_code_enum { + static const bool value = true; +}; + +} // namespace std + +namespace realm { +namespace sync { + + + +// Implementation + +class BadServerUrl: public std::exception { +public: + const char* what() const noexcept override + { + return "Bad server URL"; + } +}; + +inline Session::Session(Session&& sess) noexcept: + m_impl{sess.m_impl} +{ + sess.m_impl = nullptr; +} + +inline Session::Session() noexcept +{ +} + +inline Session::~Session() noexcept +{ + if (m_impl) + abandon(); +} + +inline Session& Session::operator=(Session&& sess) noexcept +{ + if (m_impl) + abandon(); + m_impl = sess.m_impl; + sess.m_impl = nullptr; + return *this; +} + +inline void Session::detach() noexcept +{ + if (m_impl) + abandon(); + m_impl = nullptr; +} + +inline void Session::set_error_handler(std::function handler) +{ + auto handler_2 = [handler=std::move(handler)](ConnectionState state, + const ErrorInfo* error_info) { + if (state != ConnectionState::disconnected) + return; + REALM_ASSERT(error_info); + std::error_code ec = error_info->error_code; + bool is_fatal = error_info->is_fatal; + const std::string& detailed_message = error_info->detailed_message; + handler(ec, is_fatal, detailed_message); // Throws + }; + set_connection_state_change_listener(std::move(handler_2)); // Throws +} + +inline void Session::async_wait_for_sync_completion(WaitOperCompletionHandler handler) +{ + bool upload_completion = true, download_completion = true; + async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws +} + +inline void Session::async_wait_for_upload_completion(WaitOperCompletionHandler handler) +{ + bool upload_completion = true, download_completion = false; + async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws +} + +inline void Session::async_wait_for_download_completion(WaitOperCompletionHandler handler) +{ + bool upload_completion = false, download_completion = true; + async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws +} + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_CLIENT_HPP diff --git a/Pods/Realm/include/core/realm/sync/crypto.hpp b/Pods/Realm/include/core/realm/sync/crypto.hpp new file mode 100644 index 0000000000..40ade0efb0 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/crypto.hpp @@ -0,0 +1,51 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_SYNC_CRYPTO_HPP +#define REALM_SYNC_CRYPTO_HPP + +#include +#include + +#include +#include + +namespace realm { +namespace sync { +namespace crypto { + +/// The digest functions calculate the message digest of the input in \param +/// in_buffer of size \param in_buffer_size. The digest is placed in \param +/// out_buffer. The caller must guarantee that the output buffer is large +/// enough to contain the digest. +/// +/// The functions throw if the underlying platform dependent implementations +/// throw. Typically, exceptions are "out of memory" errors. +/// +/// sha1() calculates the SHA-1 hash value of output size 20. +/// sha256() calculates the SHA-256 hash value of output size 32. +void sha1(const char* in_buffer, size_t in_buffer_size, unsigned char* out_buffer); +void sha256(const char* in_buffer, size_t in_buffer_size, unsigned char* out_buffer); + +} // namespace crypto +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_CRYPTO_HPP diff --git a/Pods/Realm/include/core/realm/sync/crypto_server.hpp b/Pods/Realm/include/core/realm/sync/crypto_server.hpp new file mode 100644 index 0000000000..c241a7117d --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/crypto_server.hpp @@ -0,0 +1,91 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_SYNC_CRYPTO_SERVER_HPP +#define REALM_SYNC_CRYPTO_SERVER_HPP + +#include +#include + +#include +#include + +namespace realm { +namespace sync { + +struct CryptoError: std::runtime_error { + CryptoError(std::string message) : std::runtime_error(std::move(message)) {} +}; + +/// This class represents a public/private keypair, or more commonly a single public +/// key used for verifying signatures. +/// +/// Only RSA keys are supported for now. +/// +/// Its methods correspond roughly to the EVP_PKEY_* set of functionality found in +/// the OpenSSL library. +class PKey { +public: + PKey(PKey&&); + PKey& operator=(PKey&&); + ~PKey(); + + /// Load RSA public key from \a pemfile. + static PKey load_public(const std::string& pemfile); + /// Load RSA public key from a PEM buffer + static PKey load_public(BinaryData pem_buffer); + + /// Load RSA public/private keypair from \a pemfile. + static PKey load_private(const std::string& pemfile); + /// Load RSA public/private keypair from a PEM buffer + static PKey load_private(BinaryData pem_buffer); + + /// Whether or not the key can be used for signing. + /// + /// True if the private part is loaded. + bool can_sign() const noexcept; + + /// Whether or not the key can be used for verifying. + /// + /// Always true for RSA keys. + bool can_verify() const noexcept; + + /// Sign \a message with the loaded key, if the private part is + /// loaded. Store the signed message as binary data in \a signature. + /// + /// If a private key is not loaded, throws an exception of type CryptoError. + void sign(BinaryData message, util::Buffer& signature) const; + + /// Verify that \a signature is a valid digest of \a message. + /// + /// Returns true if the signature is valid, otherwise false. If an error occurs while + /// attempting verification, an exception of type CryptoError is thrown. + bool verify(BinaryData message, BinaryData signature) const; + +private: + PKey(); + struct Impl; + std::unique_ptr m_impl; +}; + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_CRYPTO_SERVER_HPP diff --git a/Pods/Realm/include/core/realm/sync/feature_token.hpp b/Pods/Realm/include/core/realm/sync/feature_token.hpp new file mode 100644 index 0000000000..86db015a45 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/feature_token.hpp @@ -0,0 +1,69 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2012] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_SYNC_FEATURE_TOKEN_HPP +#define REALM_SYNC_FEATURE_TOKEN_HPP + +#include + +#if !REALM_MOBILE && !defined(REALM_EXCLUDE_FEATURE_TOKENS) +#define REALM_HAVE_FEATURE_TOKENS 1 +#else +#define REALM_HAVE_FEATURE_TOKENS 0 +#endif + +#if REALM_HAVE_FEATURE_TOKENS + +#include + +#include + +namespace realm { +namespace sync { + +class FeatureGate { +public: + + // The constructor takes a JWT token as argument. + // The constructor throws a std::runtime_error if + // the token is invalid. An invalid token is a token + // that has bad syntax, is not signed by Realm, or is + // expired. + FeatureGate(StringData token); + + // Constructs a feature gate without any features. + FeatureGate(); + ~FeatureGate(); + + FeatureGate(FeatureGate&&); + FeatureGate& operator=(FeatureGate&&); + + bool has_feature(StringData feature_name); + +private: + struct Impl; + std::unique_ptr m_impl; +}; + + +} // namespace sync +} // namespace realm + +#endif // REALM_HAVE_FEATURE_TOKENS +#endif // REALM_SYNC_FEATURE_TOKEN_HPP diff --git a/Pods/Realm/include/core/realm/sync/history.hpp b/Pods/Realm/include/core/realm/sync/history.hpp new file mode 100644 index 0000000000..7b221b4b6c --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/history.hpp @@ -0,0 +1,399 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#include +#include + +#include +#include +#include +#include + +#ifndef REALM_SYNC_HISTORY_HPP +#define REALM_SYNC_HISTORY_HPP + +namespace realm { +namespace sync { + +struct VersionInfo { + /// Realm snapshot version. + version_type realm_version = 0; + + /// The synchronization version corresponding to `realm_version`. + /// + /// In the context of the client-side history type `sync_version.version` + /// will currently always be equal to `realm_version` and + /// `sync_version.salt` will always be zero. + SaltedVersion sync_version = {0, 0}; +}; + + +class ClientHistoryBase : + public InstructionReplication { +public: + using SyncTransactCallback = void(VersionID old_version, VersionID new_version); + + /// Get the version of the latest snapshot of the associated Realm, as well + /// as the client file identifier and the synchronization progress as they + /// are stored in that snapshot. + /// + /// Note: The value of `progress.upload.last_integrated_server_version` may + /// currently be wrong when the caller is the synchronization client + /// (`_impl::ClientImplBase`), in the sense that the server version number + /// may not actually be the version upon which the client version was based. + /// On the client, it must therefore only be used in a limited capacity, + /// namely to report download progress to the server. The number reflects a + /// lower bound on the server version that any changeset produced by the + /// client in the future can be based upon. The caller passes the returned + /// value back to find_uploadable_changesets() or set_sync_progress(), so if + /// the history implementation does not care about the value of + /// `progress.upload.last_integrated_server_version`, it is allowed to not + /// persist it. However, the implementation of find_uploadable_changesets() + /// must still be prepared for its value to be determined by an incoming + /// DOWNLOAD message, rather than being whatever was returned by + /// get_status(). + /// + /// The returned current client version is the version produced by the last + /// changeset in the history. The type of version returned here, is the one + /// that identifies an entry in the sync history. Whether this is the same + /// as the snapshot number of the Realm file depends on the history + /// implementation. + /// + /// The returned client file identifier is the one that was last stored by + /// set_client_file_ident(). If no identifier has been stored yet, the + /// `ident` field of \a client_file_ident is set to zero. + /// + /// The returned SyncProgress is the one that was last stored by + /// set_sync_progress(), or {} if set_sync_progress() has never been called + /// for the associated Realm file. + virtual void get_status(version_type& current_client_version, + SaltedFileIdent& client_file_ident, + SyncProgress& progress) const = 0; + + /// Stores the server assigned client file identifier in the associated + /// Realm file, such that it is available via get_status() during future + /// synchronization sessions. It is an error to set this identifier more + /// than once per Realm file. + /// + /// \param client_file_ident The server assigned client-side file + /// identifier. A client-side file identifier is a non-zero positive integer + /// strictly less than 2**64. The server guarantees that all client-side + /// file identifiers generated on behalf of a particular server Realm are + /// unique with respect to each other. The server is free to generate + /// identical identifiers for two client files if they are associated with + /// different server Realms. + /// + /// The client is required to obtain the file identifier before engaging in + /// synchronization proper, and it must store the identifier and use it to + /// reestablish the connection between the client file and the server file + /// when engaging in future synchronization sessions. + virtual void set_client_file_ident(SaltedFileIdent client_file_ident) = 0; + + /// Stores the SyncProgress progress in the associated Realm file in a way + /// that makes it available via get_status() during future synchronization + /// sessions. Progress is reported by the server in the DOWNLOAD message. + /// + /// See struct SyncProgress for a description of \param progress. + /// + /// Note: The implementation is not obligated to store the value of + /// `progress.upload.last_integrated_server_version`, however, if the + /// implementation chooses to not store it, then its value will be + /// unreliable when passed to the implementation through functions such as + /// find_uploadable_changesets(). It may, or may not be the value last + /// returned for it by get_status(). + virtual void set_sync_progress(const SyncProgress& progress, VersionInfo&) = 0; + +/* + /// Get the first history entry whose changeset produced a version that + /// succeeds `begin_version` and, and does not succeed `end_version`, whose + /// changeset was not produced by integration of a changeset received from + /// the server, and whose changeset was not empty. + /// + /// \param begin_version, end_version The range of versions to consider. If + /// `begin_version` is equal to `end_version`, this is the empty range. If + /// `begin_version` is zero, it means that everything preceding + /// `end_version` is to be considered, which is again the empty range if + /// `end_version` is also zero. Zero is a special value in that no changeset + /// produces that version. It is an error if `end_version` precedes + /// `begin_version`, or if `end_version` is zero and `begin_version` is not. + /// + /// \param buffer Owner of memory referenced by entry.changeset upon return. + /// + /// \return The version produced by the changeset of the located history + /// entry, or zero if no history entry exists matching the specified + /// criteria. + virtual version_type find_history_entry_for_upload(version_type begin_version, + version_type end_version, + HistoryEntry& entry, + std::unique_ptr& buffer) const = 0; +*/ + + + struct UploadChangeset { + timestamp_type origin_timestamp; + file_ident_type origin_file_ident; + UploadCursor progress; + ChunkedBinaryData changeset; + std::unique_ptr buffer; + }; + + /// \brief Scan through the history for changesets to be uploaded. + /// + /// This function scans the history for changesets to be uploaded, i.e., for + /// changesets that are not empty, and were not produced by integration of + /// changesets recieved from the server. The scan begins at the position + /// specified by the initial value of \a upload_progress.client_version, and + /// ends no later than at the position specified by \a end_version. + /// + /// The implementation is allowed to end the scan before \a end_version, + /// such as to limit the combined size of returned changesets. However, if + /// the specified range contains any changesets that are supposed to be + /// uploaded, this function must return at least one. + /// + /// Upon return, \a upload_progress will have been updated to point to the + /// position from which the next scan should resume. This must be a position + /// after the last returned changeset, and before any remaining changesets + /// that are supposed to be uploaded, although never a position that + /// succeeds \a end_version. + /// + /// The value passed as \a upload_progress by the caller, must either be one + /// that was produced by an earlier invocation of + /// find_uploadable_changesets(), one that was returned by get_status(), or + /// one that was received by the client in a DOWNLOAD message from the + /// server. When the value comes from a DOWNLOAD message, it is supposed to + /// reflect a value of UploadChangeset::progress produced by an earlier + /// invocation of find_uploadable_changesets(). + /// + /// For changesets of local origin, UploadChangeset::origin_file_ident will + /// be zero. + virtual std::vector find_uploadable_changesets(UploadCursor& upload_progress, + version_type end_version) const = 0; + + using RemoteChangeset = Transformer::RemoteChangeset; + + // FIXME: Apparently, this feature is expected by object store, but why? + // What is it ultimately used for? (@tgoyne) + class SyncTransactReporter { + public: + virtual void report_sync_transact(VersionID old_version, VersionID new_version) = 0; + protected: + ~SyncTransactReporter() {} + }; + + enum class IntegrationError { + bad_origin_file_ident, + bad_changeset + }; + + /// \brief Integrate a sequence of changesets received from the server using + /// a single Realm transaction. + /// + /// Each changeset will be transformed as if by a call to + /// Transformer::transform_remote_changeset(), and then applied to the + /// associated Realm. + /// + /// As a final step, each changeset will be added to the local history (list + /// of applied changesets). + /// + /// This function checks whether the specified changesets specify valid + /// remote origin file identifiers and whether the changesets contain valid + /// sequences of instructions. The caller must already have ensured that the + /// origin file identifiers are strictly positive and not equal to the file + /// identifier assigned to this client by the server. + /// + /// If any of the changesets are invalid, this function returns false and + /// sets `integration_error` to the appropriate value. If they are all + /// deemed valid, this function updates \a version_info to reflect the new + /// version produced by the transaction. + /// + /// \param progress is the SyncProgress received in the download message. + /// Progress will be persisted along with the changesets. + /// + /// \param num_changesets The number of passed changesets. Must be non-zero. + /// + /// \param transact_reporter An optional callback which will be called with the + /// version immediately processing the sync transaction and that of the sync + /// transaction. + virtual bool integrate_server_changesets(const SyncProgress& progress, + const RemoteChangeset* changesets, + std::size_t num_changesets, VersionInfo& new_version, + IntegrationError& integration_error, util::Logger&, + SyncTransactReporter* transact_reporter = nullptr) = 0; + +protected: + ClientHistoryBase(const std::string& realm_path); +}; + + + +class ClientHistory : public ClientHistoryBase { +public: + class ChangesetCooker; + class Config; + + /// Get the persisted upload/download progress in bytes. + virtual void get_upload_download_bytes(std::uint_fast64_t& downloaded_bytes, + std::uint_fast64_t& downloadable_bytes, + std::uint_fast64_t& uploaded_bytes, + std::uint_fast64_t& uploadable_bytes, + std::uint_fast64_t& snapshot_version) = 0; + + /// See set_cooked_progress(). + struct CookedProgress { + std::int_fast64_t changeset_index = 0; + std::int_fast64_t intrachangeset_progress = 0; + }; + + /// Returns the persisted progress that was last stored by + /// set_cooked_progress(). + /// + /// Initially, until explicitly modified, both + /// `CookedProgress::changeset_index` and + /// `CookedProgress::intrachangeset_progress` are zero. + virtual CookedProgress get_cooked_progress() const = 0; + + /// Persistently stores the point of progress of the consumer of cooked + /// changesets. + /// + /// As well as allowing for later retrieval, the specification of the point + /// of progress of the consumer of cooked changesets also has the effect of + /// trimming obsolete cooked changesets from the Realm file. Indeed, if this + /// function is never called, but cooked changesets are continually being + /// produced, then the Realm file will grow without bounds. + /// + /// Behavior is undefined if the specified index + /// (CookedProgress::changeset_index) is lower than the index returned by + /// get_cooked_progress(). + /// + /// The intrachangeset progress field + /// (CookedProgress::intrachangeset_progress) will be faithfully persisted, + /// but will otherwise be treated as an opaque object by the history + /// internals. + virtual void set_cooked_progress(CookedProgress) = 0; + + /// Get the number of cooked changesets so far produced for this Realm. This + /// is the number of cooked changesets that are currently in the Realm file + /// plus the number of cooked changesets that have been trimmed off so far. + virtual std::int_fast64_t get_num_cooked_changesets() const = 0; + + /// Fetch the cooked changeset at the specified index. + /// + /// Cooked changesets are made available in the order they are produced by + /// the changeset cooker (ChangesetCooker). + /// + /// Behaviour is undefined if the specified index is less than the index + /// (CookedProgress::changeset_index) returned by get_cooked_progress(), or + /// if it is greater than, or equal to the toal number of cooked changesets + /// (as returned by get_num_cooked_changesets()). + /// + /// The callee must append the bytes of the located cooked changeset to the + /// specified buffer, which does not have to be empty initially. + virtual void get_cooked_changeset(std::int_fast64_t index, + util::AppendBuffer&) const = 0; + +protected: + ClientHistory(const std::string& realm_path); +}; + + +/// \brief Abstract interface for changeset cookers. +/// +/// Note, it is completely up to the application to decide what a cooked +/// changeset is. History objects (instances of ClientHistory) are required to +/// treat cooked changesets as opaque entities. For an example of a concrete +/// changeset cooker, see TrivialChangesetCooker which defines the cooked +/// changesets to be identical copies of the raw changesets. +class ClientHistory::ChangesetCooker { +public: + /// \brief An opportunity to produce a cooked changeset. + /// + /// When the implementation chooses to produce a cooked changeset, it must + /// write the cooked changeset to the specified buffer, and return + /// true. When the implementation chooses not to produce a cooked changeset, + /// it must return false. The implementation is allowed to write to the + /// buffer, and return false, and in that case, the written data will be + /// ignored. + /// + /// \param prior_state The state of the local Realm on which the specified + /// raw changeset is based. + /// + /// \param changeset, changeset_size The raw changeset. + /// + /// \param buffer The buffer to which the cooked changeset must be written. + /// + /// \return True if a cooked changeset was produced. Otherwise false. + virtual bool cook_changeset(const Group& prior_state, + const char* changeset, std::size_t changeset_size, + util::AppendBuffer& buffer) = 0; +}; + + +class ClientHistory::Config { +public: + Config() {} + + /// Must be set to true if, and only if the created history object + /// represents (is owned by) the sync agent of the specified Realm file. At + /// most one such instance is allowed to participate in a Realm file access + /// session at any point in time. Ordinarily the sync agent is encapsulated + /// by the sync::Client class, and the history instance representing the + /// agent is created transparently by sync::Client (one history instance per + /// sync::Session object). + bool owner_is_sync_agent = false; + + /// If a changeset cooker is specified, then the created history object will + /// allow for a cooked changeset to be produced for each changeset of remote + /// origin; that is, for each changeset that is integrated during the + /// execution of ClientHistory::integrate_remote_changesets(). If no + /// changeset cooker is specified, then no cooked changesets will be + /// produced on behalf of the created history object. + /// + /// ClientHistory::integrate_remote_changesets() will pass each incoming + /// changeset to the cooker after operational transformation; that is, when + /// the chageset is ready to be applied to the local Realm state. + std::shared_ptr changeset_cooker; +}; + +/// \brief Create a "sync history" implementation of the realm::Replication +/// interface. +/// +/// The intended role for such an object is as a plugin for new +/// realm::SharedGroup objects. +std::unique_ptr make_client_history(const std::string& realm_path, + ClientHistory::Config = {}); + + + +// Implementation + +inline ClientHistoryBase::ClientHistoryBase(const std::string& realm_path): + InstructionReplication{realm_path} // Throws +{ +} + +inline ClientHistory::ClientHistory(const std::string& realm_path): + ClientHistoryBase{realm_path} // Throws +{ +} + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_HISTORY_HPP diff --git a/Pods/Realm/include/core/realm/sync/instruction_applier.hpp b/Pods/Realm/include/core/realm/sync/instruction_applier.hpp new file mode 100644 index 0000000000..62d64d983f --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/instruction_applier.hpp @@ -0,0 +1,126 @@ +/************************************************************************* + * + * Copyright 2017 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_SYNC_IMPL_INSTRUCTION_APPLIER_HPP +#define REALM_SYNC_IMPL_INSTRUCTION_APPLIER_HPP + +#include +#include +#include +#include + +namespace realm { +namespace sync { + +struct Changeset; + +struct InstructionApplier { + explicit InstructionApplier(Group& group) noexcept; + + /// Throws BadChangesetError if application fails due to a problem with the + /// changeset. + /// + /// FIXME: Consider using std::error_code instead of throwing + /// BadChangesetError. + void apply(const Changeset& log, util::Logger* logger); + + void begin_apply(const Changeset& log, util::Logger* logger) noexcept; + void end_apply() noexcept; + +protected: + StringData get_string(InternString) const; + StringData get_string(StringBufferRange) const; +#define REALM_DECLARE_INSTRUCTION_HANDLER(X) void operator()(const Instruction::X&); + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DECLARE_INSTRUCTION_HANDLER) +#undef REALM_DECLARE_INSTRUCTION_HANDLER + friend struct Instruction; // to allow visitor + + template static void apply(A& applier, const Changeset& log, util::Logger* logger); + + Group& m_group; +private: + const Changeset* m_log = nullptr; + util::Logger* m_logger = nullptr; + TableRef m_selected_table; + TableRef m_selected_array; + LinkViewRef m_selected_link_list; + TableRef m_link_target_table; + TableInfoCache m_table_info; + + template + void log(const char* fmt, Args&&... args) + { + if (m_logger) { + m_logger->trace(fmt, std::forward(args)...); // Throws + } + } + + void bad_transaction_log(const char*) const; // Throws + + TableRef table_for_class_name(StringData) const; // Throws +}; + + + + +// Implementation + +inline InstructionApplier::InstructionApplier(Group& group) noexcept: + m_group(group), + m_table_info(m_group) +{ +} + +inline void InstructionApplier::begin_apply(const Changeset& log, util::Logger* logger) noexcept +{ + m_log = &log; + m_logger = logger; +} + +inline void InstructionApplier::end_apply() noexcept +{ + m_log = nullptr; + m_logger = nullptr; + m_selected_table = TableRef{}; + m_selected_array = TableRef{}; + m_selected_link_list = LinkViewRef{}; + m_link_target_table = TableRef{}; +} + +template +inline void InstructionApplier::apply(A& applier, const Changeset& log, util::Logger* logger) +{ + applier.begin_apply(log, logger); + for (auto instr: log) { + if (!instr) + continue; + instr->visit(applier); // Throws + } + applier.end_apply(); + +} + +inline void InstructionApplier::apply(const Changeset& log, util::Logger* logger) +{ + apply(*this, log, logger); // Throws +} + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_IMPL_INSTRUCTION_APPLIER_HPP diff --git a/Pods/Realm/include/core/realm/sync/instruction_replication.hpp b/Pods/Realm/include/core/realm/sync/instruction_replication.hpp new file mode 100644 index 0000000000..243bf21505 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/instruction_replication.hpp @@ -0,0 +1,202 @@ +/************************************************************************* + * + * Copyright 2017 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_SYNC_IMPL_INSTRUCTION_REPLICATION_HPP +#define REALM_SYNC_IMPL_INSTRUCTION_REPLICATION_HPP + +#include +#include +#include +#include + +namespace realm { +namespace sync { + + +class InstructionReplication: public TrivialReplication, public ObjectIDProvider { +public: + explicit InstructionReplication(const std::string& realm_path); + void set_short_circuit(bool) noexcept; + bool is_short_circuited() const noexcept; + + // reset() resets the encoder, the selected tables and the cache. It is + // called by do_initiate_transact(), but can be called at the other times + // as well. + virtual void reset(); + + ChangesetEncoder& get_instruction_encoder() noexcept; + + //@{ + /// Generate instructions for Object Store tables. These must be called + /// prior to calling the equivalent functions in Core's API. When creating a + /// class-like table, `add_class()` must be called prior to + /// `Group::insert_group_level_table()`. Similarly, `create_object()` or + /// `create_object_with_primary_key()` must be called prior to + /// `Table::insert_empty_row()` and/or `Table::set_int_unique()` or + /// `Table::set_string_unique()` or `Table::set_null_unique()`. + /// + /// If a class-like table is added, or an object-like row is inserted, + /// without calling these methods first, an exception will be thrown. + /// + /// A "class-like table" is defined as a table whose name begins with + /// "class_" (this is the convention used by Object Store). Non-class-like + /// tables can be created and modified using Core's API without calling + /// these functions, because they do not result in instructions being + /// emitted. + void add_class(StringData table_name); + void add_class_with_primary_key(StringData table_name, DataType pk_type, StringData pk_field, bool nullable); + void create_object(const Table*, ObjectID); + void create_object_with_primary_key(const Table*, ObjectID, StringData); + void create_object_with_primary_key(const Table*, ObjectID, int_fast64_t); + void create_object_with_primary_key(const Table*, ObjectID, realm::util::None); + void prepare_erase_table(StringData table_name); + //@} + + // TrivialReplication interface: + void initialize(SharedGroup&) override; + + // TransactLogConvenientEncoder interface: + void insert_group_level_table(size_t table_ndx, size_t num_tables, StringData name) override; + void erase_group_level_table(size_t table_ndx, size_t num_tables) override; + void rename_group_level_table(size_t table_ndx, StringData new_name) override; + void insert_column(const Descriptor&, size_t col_ndx, DataType type, StringData name, LinkTargetInfo& link, + bool nullable = false) override; + void erase_column(const Descriptor&, size_t col_ndx) override; + void rename_column(const Descriptor&, size_t col_ndx, StringData name) override; + + void set_int(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value, _impl::Instruction variant) override; + void add_int(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value) override; + void set_bool(const Table*, size_t col_ndx, size_t ndx, bool value, _impl::Instruction variant) override; + void set_float(const Table*, size_t col_ndx, size_t ndx, float value, _impl::Instruction variant) override; + void set_double(const Table*, size_t col_ndx, size_t ndx, double value, _impl::Instruction variant) override; + void set_string(const Table*, size_t col_ndx, size_t ndx, StringData value, _impl::Instruction variant) override; + void set_binary(const Table*, size_t col_ndx, size_t ndx, BinaryData value, _impl::Instruction variant) override; + void set_olddatetime(const Table*, size_t col_ndx, size_t ndx, OldDateTime value, + _impl::Instruction variant) override; + void set_timestamp(const Table*, size_t col_ndx, size_t ndx, Timestamp value, _impl::Instruction variant) override; + void set_table(const Table*, size_t col_ndx, size_t ndx, _impl::Instruction variant) override; + void set_mixed(const Table*, size_t col_ndx, size_t ndx, const Mixed& value, _impl::Instruction variant) override; + void set_link(const Table*, size_t col_ndx, size_t ndx, size_t value, _impl::Instruction variant) override; + void set_null(const Table*, size_t col_ndx, size_t ndx, _impl::Instruction variant) override; + void set_link_list(const LinkView&, const IntegerColumn& values) override; + void insert_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, StringData) override; + void erase_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, size_t size) override; + void insert_empty_rows(const Table*, size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows) override; + void add_row_with_key(const Table*, size_t row_ndx, size_t prior_num_rows, size_t key_col_ndx, int64_t key) override; + void erase_rows(const Table*, size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rowsp, + bool is_move_last_over) override; + void swap_rows(const Table*, size_t row_ndx_1, size_t row_ndx_2) override; + void move_row(const Table*, size_t row_ndx_1, size_t row_ndx_2) override; + void merge_rows(const Table*, size_t row_ndx, size_t new_row_ndx) override; + void add_search_index(const Descriptor&, size_t col_ndx) override; + void remove_search_index(const Descriptor&, size_t col_ndx) override; + void set_link_type(const Table*, size_t col_ndx, LinkType) override; + void clear_table(const Table*, size_t prior_num_rows) override; + void optimize_table(const Table*) override; + void link_list_set(const LinkView&, size_t ndx, size_t value) override; + void link_list_insert(const LinkView&, size_t ndx, size_t value) override; + void link_list_move(const LinkView&, size_t from_ndx, size_t to_ndx) override; + void link_list_swap(const LinkView&, size_t ndx_1, size_t ndx_2) override; + void link_list_erase(const LinkView&, size_t ndx) override; + void link_list_clear(const LinkView&) override; + void nullify_link(const Table*, size_t col_ndx, size_t ndx) override; + void link_list_nullify(const LinkView&, size_t ndx) override; + +protected: + // Replication interface: + void do_initiate_transact(version_type current_version, bool history_updated) override; +private: + bool m_short_circuit = false; + + ChangesetEncoder m_encoder; + SharedGroup* m_sg = nullptr; + std::unique_ptr m_cache; + + enum class TableBehavior { + Class, + Array, + Ignore + }; + + // FIXME: The base class already caches this. + ConstTableRef m_selected_table; + TableBehavior m_selected_table_behavior; // cache + ConstLinkViewRef m_selected_link_list = nullptr; + + // Consistency checks: + std::string m_table_being_created; + std::string m_table_being_created_primary_key; + std::string m_table_being_erased; + util::Optional m_object_being_created; + + void unsupported_instruction(); // Throws TransformError + TableBehavior select_table(const Table*); + TableBehavior select_table(const Descriptor&); + bool select_link_list(const LinkView&); // returns true if table behavior != ignored + + TableBehavior get_table_behavior(const Table*) const; + + template + void set(const Table*, size_t row_ndx, size_t col_ndx, T payload, + _impl::Instruction variant); + template + void set_pk(const Table*, size_t row_ndx, size_t col_ndx, T payload, + _impl::Instruction variant); + template + auto as_payload(T value); + template + void emit(T instruction); +}; + +inline void InstructionReplication::set_short_circuit(bool b) noexcept +{ + m_short_circuit = b; +} + +inline bool InstructionReplication::is_short_circuited() const noexcept +{ + return m_short_circuit; +} + +inline ChangesetEncoder& InstructionReplication::get_instruction_encoder() noexcept +{ + return m_encoder; +} + +// Temporarily short-circuit replication +class TempShortCircuitReplication { +public: + TempShortCircuitReplication(InstructionReplication& bridge): m_bridge(bridge) + { + m_was_short_circuited = bridge.is_short_circuited(); + bridge.set_short_circuit(true); + } + + ~TempShortCircuitReplication() + { + m_bridge.set_short_circuit(m_was_short_circuited); + } +private: + InstructionReplication& m_bridge; + bool m_was_short_circuited; +}; + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_IMPL_INSTRUCTION_REPLICATION_HPP diff --git a/Pods/Realm/include/core/realm/sync/instructions.hpp b/Pods/Realm/include/core/realm/sync/instructions.hpp new file mode 100644 index 0000000000..fc9ce253be --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/instructions.hpp @@ -0,0 +1,415 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_IMPL_INSTRUCTIONS_HPP +#define REALM_IMPL_INSTRUCTIONS_HPP + +#include +#include +#include // string conversion, debug prints +#include // shared_ptr +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace realm { +namespace sync { + +// CAUTION: Any change to the order or number of instructions is a +// protocol-breaking change! +#define REALM_FOR_EACH_INSTRUCTION_TYPE(X) \ + X(SelectTable) \ + X(SelectField) \ + X(AddTable) \ + X(EraseTable) \ + X(CreateObject) \ + X(EraseObject) \ + X(Set) \ + X(AddInteger) \ + X(InsertSubstring) \ + X(EraseSubstring) \ + X(ClearTable) \ + X(AddColumn) \ + X(EraseColumn) \ + X(ArraySet) \ + X(ArrayInsert) \ + X(ArrayMove) \ + X(ArraySwap) \ + X(ArrayErase) \ + X(ArrayClear) \ + + +enum class ContainerType { + None = 0, + Reserved0 = 1, + Array = 2, + Set = 3, + Dictionary = 4, +}; + +struct Instruction { + // Base classes for instructions with common fields. They enable the merge + // algorithm to reuse some code without resorting to templates, and can be + // combined to allow optimal memory layout of instructions (size <= 64). + struct PayloadInstructionBase; + struct ObjectInstructionBase; + struct FieldInstructionBase; + +#define REALM_DECLARE_INSTRUCTION_STRUCT(X) struct X; + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DECLARE_INSTRUCTION_STRUCT) +#undef REALM_DECLARE_INSTRUCTION_STRUCT + + enum class Type: uint8_t { +#define REALM_DEFINE_INSTRUCTION_TYPE(X) X, + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DEFINE_INSTRUCTION_TYPE) +#undef REALM_DEFINE_INSTRUCTION_TYPE + }; + + struct Payload; + template struct GetType; + template struct GetInstructionType; + + Instruction() {} + template + Instruction(T instr); + + static const size_t max_instruction_size = 64; + std::aligned_storage_t m_storage; + Type type; + + template + auto visit(F&& lambda); + template + auto visit(F&& lambda) const; + + template T& get_as() + { + REALM_ASSERT(type == GetInstructionType::value); + return *reinterpret_cast(&m_storage); + } + + template + const T& get_as() const + { + return const_cast(this)->template get_as(); + } + + bool operator==(const Instruction& other) const noexcept; + bool operator!=(const Instruction& other) const noexcept + { + return !(*this == other); + } +}; + +// 0x3f is the largest value that fits in a single byte in the variable-length +// encoded integer instruction format. +static constexpr uint8_t InstrTypeInternString = 0x3f; + +// This instruction code is only ever used internally by the Changeset class +// to allow insertion/removal while keeping iterators stable. Should never +// make it onto the wire. +static constexpr uint8_t InstrTypeMultiInstruction = 0xff; + +struct StringBufferRange { + uint32_t offset, size; +}; + +struct InternString { + static const InternString npos; + explicit constexpr InternString(uint32_t v = uint32_t(-1)): value(v) {} + + uint32_t value; + + bool operator==(const InternString& other) const noexcept { return value == other.value; } +}; + +struct Instruction::Payload { + struct Link { + sync::ObjectID target; // can be nothing = null + InternString target_table; + }; + + union Data { + bool boolean; + int64_t integer; + float fnum; + double dnum; + StringBufferRange str; + Timestamp timestamp; + Link link; + + Data() noexcept {} + Data(const Data&) noexcept = default; + Data& operator=(const Data&) noexcept = default; + }; + Data data; + int8_t type; // -1 = null, -2 = implicit_nullify + + Payload(): Payload(realm::util::none) {} + explicit Payload(bool value) noexcept: type(type_Bool) { data.boolean = value; } + explicit Payload(int64_t value) noexcept: type(type_Int) { data.integer = value; } + explicit Payload(float value) noexcept: type(type_Float) { data.fnum = value; } + explicit Payload(double value) noexcept: type(type_Double) { data.dnum = value; } + explicit Payload(Timestamp value) noexcept: type(type_Timestamp) { data.timestamp = value; } + explicit Payload(Link value) noexcept: type(type_Link) { data.link = value; } + explicit Payload(StringBufferRange value) noexcept: type(type_String) { data.str = value; } + explicit Payload(realm::util::None, bool implicit_null = false) noexcept { + type = (implicit_null ? -2 : -1); + } + + Payload(const Payload&) noexcept = default; + Payload& operator=(const Payload&) noexcept = default; + + bool is_null() const; + bool is_implicit_null() const; +}; + +struct Instruction::ObjectInstructionBase { + sync::ObjectID object; +}; + +struct Instruction::FieldInstructionBase + : Instruction::ObjectInstructionBase +{ + InternString field; +}; + +struct Instruction::PayloadInstructionBase { + Payload payload; +}; + + +struct Instruction::SelectTable { + InternString table; +}; + +struct Instruction::SelectField + : Instruction::FieldInstructionBase +{ + InternString link_target_table; +}; + +struct Instruction::AddTable { + InternString table; + InternString primary_key_field; + DataType primary_key_type; + bool has_primary_key; + bool primary_key_nullable; +}; + +struct Instruction::EraseTable { + InternString table; +}; + +struct Instruction::CreateObject + : Instruction::PayloadInstructionBase + , Instruction::ObjectInstructionBase +{ + bool has_primary_key; +}; + +struct Instruction::EraseObject + : Instruction::ObjectInstructionBase +{}; + +struct Instruction::Set + : Instruction::PayloadInstructionBase + , Instruction::FieldInstructionBase +{ + bool is_default; +}; + +struct Instruction::AddInteger + : Instruction::FieldInstructionBase +{ + int64_t value; +}; + +struct Instruction::InsertSubstring + : Instruction::FieldInstructionBase +{ + StringBufferRange value; + uint32_t pos; +}; + +struct Instruction::EraseSubstring + : Instruction::FieldInstructionBase +{ + uint32_t pos; + uint32_t size; +}; + +struct Instruction::ClearTable { +}; + +struct Instruction::ArraySet { + Instruction::Payload payload; + uint32_t ndx; + uint32_t prior_size; +}; + +struct Instruction::ArrayInsert { + // payload carries the value in case of LinkList + // payload is empty in case of Array, Dict or any other container type + Instruction::Payload payload; + uint32_t ndx; + uint32_t prior_size; +}; + +struct Instruction::ArrayMove { + uint32_t ndx_1; + uint32_t ndx_2; +}; + +struct Instruction::ArrayErase { + uint32_t ndx; + uint32_t prior_size; + bool implicit_nullify; +}; + +struct Instruction::ArraySwap { + uint32_t ndx_1; + uint32_t ndx_2; +}; + +struct Instruction::ArrayClear { + uint32_t prior_size; +}; + + +// If container_type != ContainerType::none, creates a subtable: +// +---+---+-------+ +// | a | b | c | +// +---+---+-------+ +// | | | +---+ | +// | | | | v | | +// | | | +---+ | +// | 1 | 2 | | 3 | | +// | | | | 4 | | +// | | | | 5 | | +// | | | +---+ | +// +---+---+-------+ +struct Instruction::AddColumn { + InternString field; + InternString link_target_table; + DataType type; + ContainerType container_type; + bool nullable; +}; + +struct Instruction::EraseColumn { + InternString field; +}; + +struct InstructionHandler { + /// Notify the handler that an InternString meta-instruction was found. + virtual void set_intern_string(uint32_t index, StringBufferRange) = 0; + + /// Notify the handler of the string value. The handler guarantees that the + /// returned string range is valid at least until the next invocation of + /// add_string_range(). + /// + /// Instances of `StringBufferRange` passed to operator() after invoking + /// this function are assumed to refer to ranges in this buffer. + virtual StringBufferRange add_string_range(StringData) = 0; + + /// Handle an instruction. + virtual void operator()(const Instruction&) = 0; +}; + + +/// Implementation: + +#if !defined(__GNUC__) || defined(__clang__) || __GNUC__ > 4 // GCC 4.x does not support std::is_trivially_copyable +#define REALM_CHECK_TRIVIALLY_COPYABLE(X) static_assert(std::is_trivially_copyable::value, #X" Instructions must be trivially copyable."); + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_CHECK_TRIVIALLY_COPYABLE) +#undef REALM_CHECK_TRIVIALLY_COPYABLE +#endif // __GNUC__ + +#ifdef _WIN32 // FIXME: Fails in VS. +#define REALM_CHECK_INSTRUCTION_SIZE(X) +#else +#define REALM_CHECK_INSTRUCTION_SIZE(X) static_assert(sizeof(Instruction::X) <= Instruction::max_instruction_size, #X" Instruction too big."); + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_CHECK_INSTRUCTION_SIZE) +#undef REALM_CHECK_INSTRUCTION_SIZE +#endif + +#define REALM_DEFINE_INSTRUCTION_GET_TYPE(X) \ + template <> struct Instruction::GetType { using Type = Instruction::X; }; \ + template <> struct Instruction::GetInstructionType { static const Instruction::Type value = Instruction::Type::X; }; + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DEFINE_INSTRUCTION_GET_TYPE) +#undef REALM_DEFINE_INSTRUCTION_GET_TYPE + + +template +Instruction::Instruction(T instr): type(GetInstructionType::value) +{ + new(&m_storage) T(std::move(instr)); +} + +template +auto Instruction::visit(F&& lambda) +{ + switch (type) { +#define REALM_VISIT_INSTRUCTION(X) \ + case Type::X: return lambda(get_as()); + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_VISIT_INSTRUCTION) +#undef REALM_VISIT_INSTRUCTION + } + REALM_UNREACHABLE(); +} + +inline bool Instruction::operator==(const Instruction& other) const noexcept +{ + if (type != other.type) + return false; + size_t valid_size; + switch (type) { +#define REALM_COMPARE_INSTRUCTION(X) \ + case Type::X: valid_size = sizeof(Instruction::X); break; + REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_COMPARE_INSTRUCTION) +#undef REALM_COMPARE_INSTRUCTION + default: REALM_UNREACHABLE(); + } + + // This relies on all instruction types being PODs to work. + return std::memcmp(&m_storage, &other.m_storage, valid_size) == 0; +} + +template +auto Instruction::visit(F&& lambda) const +{ + return const_cast(this)->visit(std::forward(lambda)); +} + +std::ostream& operator<<(std::ostream&, Instruction::Type); + +} // namespace _impl +} // namespace realm + +#endif // REALM_IMPL_INSTRUCTIONS_HPP diff --git a/Pods/Realm/include/core/realm/sync/object.hpp b/Pods/Realm/include/core/realm/sync/object.hpp new file mode 100644 index 0000000000..a9d13028eb --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/object.hpp @@ -0,0 +1,256 @@ +/************************************************************************* + * + * Copyright 2017 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_SYNC_OBJECT_HPP +#define REALM_SYNC_OBJECT_HPP + +#include +#include +#include +#include + +#include + +#include + +/// This file presents a convenience API for making changes to a Realm file that +/// adhere to the conventions of assigning stable IDs to every object. + +namespace realm { + +class Group; + +namespace sync { + +class SyncHistory; + +static const char object_id_column_name[] = "!OID"; +static const char array_value_column_name[] = "!ARRAY_VALUE"; // FIXME call Jorgen + +struct TableInfoCache; + +/// Determine whether the Group has a sync-type history, and therefore whether +/// it supports globally stable object IDs. +/// +/// The Group does not need to be in a transaction. +bool has_object_ids(const Group&); + +/// Determine whether object IDs for objects without primary keys are globally +/// stable. This is true if and only if the Group has been in touch with the +/// server (or is the server), and will remain true forever thereafter. +/// +/// It is an error to call this function for groups that do not have object IDs +/// (i.e. where `has_object_ids()` returns false). +/// +/// The Group is assumed to be in a read transaction. +bool is_object_id_stability_achieved(const Group&); + +/// Create a table with an object ID column. +/// +/// It is an error to add tables to Groups with a sync history type directly. +/// This function or related functions must be used instead. +/// +/// The resulting table will be born with 1 column, which is a column used +/// in the maintenance of object IDs. +/// +/// NOTE: The table name must begin with the prefix "class_" in accordance with +/// Object Store conventions. +/// +/// The Group must be in a write transaction. +TableRef create_table(Group&, StringData name); + +/// Create a table with an object ID column and a primary key column. +/// +/// It is an error to add tables to Groups with a sync history type directly. +/// This function or related functions must be used instead. +/// +/// The resulting table will be born with 2 columns, which is a column used +/// in the maintenance of object IDs and the requested primary key column. +/// The primary key column must have either integer or string type, and it +/// will be given the name provided in the argument \a pk_column_name. +/// +/// The 'pk' metadata table is updated with information about the primary key +/// column. If the 'pk' table does not yet exist, it is created. +/// +/// Please note: The 'pk' metadata table will not be synchronized directly, +/// so subsequent updates to it will be lost (as they constitute schema-breaking +/// changes). +/// +/// NOTE: The table name must begin with the prefix "class_" in accordance with +/// Object Store conventions. +/// +/// The Group must be in a write transaction. +TableRef create_table_with_primary_key(Group&, StringData name, DataType pk_type, + StringData pk_column_name, bool nullable = false); + + +//@{ +/// Erase table and update metadata. +/// +/// It is an error to erase tables via the Group API, because it does not +/// correctly update metadata tables (such as the `pk` table). +void erase_table(Group&, StringData name); +void erase_table(Group&, TableRef); +//@} + +/// Create an array column with the specified element type. +/// +/// The result will be a column of type type_Table with one subcolumn named +/// "!ARRAY_VALUE" of the specified element type. +/// +/// Return the column index of the inserted array column. +size_t add_array_column(Table&, DataType element_type, StringData column_name); + + +//@{ +/// Calculate the object ID from the argument, where the argument is a primary +/// key value. +ObjectID object_id_for_primary_key(StringData); +ObjectID object_id_for_primary_key(util::Optional); +//@} + +/// Determine whether it is safe to call `object_id_for_row()` on tables without +/// primary keys. If the table has a primary key, always returns true. +bool has_globally_stable_object_ids(const Table&); + +bool table_has_primary_key(const TableInfoCache&, const Table&); + +/// Get the globally unique object ID for the row. +/// +/// If the table has a primary key, this is guaranteed to succeed. Otherwise, if +/// the server has not been contacted yet (`has_globally_stable_object_ids()` +/// returns false), an exception is thrown. +ObjectID object_id_for_row(const TableInfoCache&, const Table&, size_t); + +/// Get the index of the row with the object ID. +/// +/// \returns realm::npos if the object does not exist in the table. +size_t row_for_object_id(const TableInfoCache&, const Table&, ObjectID); + +//@{ +/// Add a row to the table and populate the object ID with an appropriate value. +/// +/// In the variant which takes an ObjectID parameter, a check is performed to see +/// if the object already exists. If it does, the row index of the existing object +/// is returned. +/// +/// If the table has a primary key column, an exception is thrown. +/// +/// \returns the row index of the object. +size_t create_object(const TableInfoCache&, Table&); +size_t create_object(const TableInfoCache&, Table&, ObjectID); +//@} + +//@{ +/// Create an object with a primary key value and populate the object ID with an +/// appropriate value. +/// +/// If the table does not have a primary key column (as indicated by the Object +/// Store's metadata in the special "pk" table), or the type of the primary key +/// column does not match the argument provided, an exception is thrown. +/// +/// The primary key column's value is populated with the appropriate +/// `set_int_unique()`, `set_string_unique()`, or `set_null_unique()` method +/// called on \a table. +/// +/// If an object with the given primary key value already exists, its row number +/// is returned without creating any new objects. +/// +/// These are convenience functions, equivalent to the following: +/// - Add an empty row to the table. +/// - Obtain an `ObjectID` with `object_id_for_primary_key()`. +/// - Obtain a local object ID with `global_to_local_object_id()`. +/// - Store the local object ID in the object ID column. +/// - Call `set_int_unique()`,`set_string_unique()`, or `set_null_unique()` +/// to set the primary key value. +/// +/// \returns the row index of the created object. +size_t create_object_with_primary_key(const TableInfoCache&, Table&, util::Optional primary_key); +size_t create_object_with_primary_key(const TableInfoCache&, Table&, StringData primary_key); +//@} + +struct TableInfoCache { + const Group& m_group; + + // Implicit conversion deliberately allowed for the purpose of calling the above + // functions without constructing a cache manually. + TableInfoCache(const Group&); + TableInfoCache(TableInfoCache&&) noexcept = default; + + struct TableInfo { + struct VTable; + + StringData name; + const VTable* vtable; + size_t object_id_index; + size_t primary_key_index; + DataType primary_key_type = DataType(-1); + bool primary_key_nullable = false; + mutable size_t last_row_index = size_t(-1); + mutable ObjectID last_object_id; + + void clear_last_object() const + { + last_row_index = size_t(-1); + last_object_id = {}; + } + }; + + mutable std::vector> m_table_info; + + const TableInfo& get_table_info(const Table&) const; + const TableInfo& get_table_info(size_t table_index) const; + void clear(); + void verify(); +}; + + +/// Migrate a server-side Realm file whose history type is +/// `Replication::hist_SyncServer` and whose history schema version is 0 (i.e., +/// Realm files without stable identifiers). +void import_from_legacy_format(const Group& old_group, Group& new_group, util::Logger&); + +using TableNameBuffer = std::array; +StringData table_name_to_class_name(StringData); +StringData class_name_to_table_name(StringData, TableNameBuffer&); + + +// Implementation: + +inline StringData table_name_to_class_name(StringData table_name) +{ + REALM_ASSERT(table_name.begins_with("class_")); + return table_name.substr(6); +} + + +inline StringData class_name_to_table_name(StringData class_name, TableNameBuffer& buffer) +{ + constexpr const char class_prefix[] = "class_"; + constexpr size_t class_prefix_len = sizeof(class_prefix) - 1; + char* p = std::copy_n(class_prefix, class_prefix_len, buffer.data()); + size_t len = std::min(class_name.size(), buffer.size() - class_prefix_len); + std::copy_n(class_name.data(), len, p); + return StringData(buffer.data(), class_prefix_len + len); +} + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_OBJECT_HPP + diff --git a/Pods/Realm/include/core/realm/sync/object_id.hpp b/Pods/Realm/include/core/realm/sync/object_id.hpp new file mode 100644 index 0000000000..c0028b8796 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/object_id.hpp @@ -0,0 +1,287 @@ +/************************************************************************* + * + * Copyright 2017 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_SYNC_OBJECT_ID_HPP +#define REALM_SYNC_OBJECT_ID_HPP + +#include // std::hash +#include +#include // operator<< +#include +#include + +#include + +#include +#include +#include + +// Only set this to one when testing the code paths that exercise object ID +// hash collisions. It artificially limits the "optimistic" local ID to use +// only the lower 15 bits of the ID rather than the lower 63 bits, making it +// feasible to generate collisions within reasonable time. +#define REALM_EXERCISE_OBJECT_ID_COLLISION 0 + +namespace realm { + +class Group; + +namespace sync { + +/// ObjectIDs are globally unique, and up to 128 bits wide. They are represented +/// as two 64-bit integers, each of which may frequently be small, for best +/// on-wire compressibility. +struct ObjectID { + constexpr ObjectID(uint64_t hi, uint64_t lo); + static ObjectID from_string(StringData); + + // FIXME: Remove "empty" ObjectIDs, wrap in Optional instead. + constexpr ObjectID(realm::util::None = realm::util::none); + constexpr ObjectID(const ObjectID&) noexcept = default; + ObjectID& operator=(const ObjectID&) noexcept = default; + + constexpr uint64_t lo() const { return m_lo; } + constexpr uint64_t hi() const { return m_hi; } + + std::string to_string() const; + + constexpr bool operator<(const ObjectID& other) const; + constexpr bool operator==(const ObjectID& other) const; + constexpr bool operator!=(const ObjectID& other) const; + +private: + uint64_t m_lo; + uint64_t m_hi; +}; + +/// Implementors of this interface should define a way to map from 128-bit +/// on-write ObjectIDs to local 64-bit object IDs. +/// +/// The three object ID types are: +/// a. Object IDs for objects in tables without primary keys. +/// b. Object IDs for objects in tables with integer primary keys. +/// c. Object IDs for objects in tables with other primary key types. +/// +/// For integer primary keys (b), the Object ID is just the integer value. +/// +/// For objects without primary keys (a), a "squeezed" tuple of the +/// client_file_ident and a peer-local sequence number is used as the local +/// Object ID. The on-write Object ID is the "unsqueezed" format. The methods on +/// this interface ending in "_squeezed" aid in the creation and conversion of +/// these IDs. +/// +/// For objects with other types of primary keys (c), the ObjectID +/// is a 128-bit hash of the primary key value. However, the local object ID +/// must be a 64-bit integer, because that is the maximum size integer that +/// Realm is able to store. The solution is to optimistically use the lower 63 +/// bits of the on-wire Object ID, and use a local ID with the upper 64th bit +/// set when there is a collision in the lower 63 bits between two different +/// hash values. +class ObjectIDProvider { +public: + using LocalObjectID = int_fast64_t; + + /// Calculate optimistic local ID that may collide with others. It is up to + /// the caller to ensure that collisions are detected and that + /// allocate_local_id_after_collision() is called to obtain a non-colliding + /// ID. + static LocalObjectID get_optimistic_local_id_hashed(ObjectID global_id); + + /// Find the local 64-bit object ID for the provided global 128-bit ID. + virtual LocalObjectID global_to_local_object_id_hashed(size_t table_ndx, ObjectID global_id) const = 0; + + /// After a local ID collision has been detected, this function may be + /// called to obtain a non-colliding local ID in such a way that subsequence + /// calls to global_to_local_object_id() will return the correct local ID + /// for both \a incoming_id and \a colliding_id. + virtual LocalObjectID allocate_local_id_after_hash_collision(size_t table_ndx, + ObjectID incoming_id, + ObjectID colliding_id, + LocalObjectID colliding_local_id) = 0; + static LocalObjectID make_tagged_local_id_after_hash_collision(uint64_t sequence_number); + virtual void free_local_id_after_hash_collision(size_t table_ndx, ObjectID object_id) = 0; + + /// Some Object IDs are generated as a tuple of the client_file_ident and a + /// local sequence number. This function takes the next number in the + /// sequence for the given table and returns an appropriate globally unique + /// ObjectID. + virtual ObjectID allocate_object_id_squeezed(size_t table_ndx) = 0; + static LocalObjectID global_to_local_object_id_squeezed(ObjectID); + static ObjectID local_to_global_object_id_squeezed(LocalObjectID); + + virtual void table_erased(size_t table_ndx) = 0; + + virtual int_fast64_t get_client_file_ident() const = 0; +}; + +// ObjectIDSet is a set of (table name, object id) +class ObjectIDSet { +public: + + void insert(StringData table, ObjectID object_id); + void erase(StringData table, ObjectID object_id); + bool contains(StringData table, ObjectID object_id) const noexcept; + + // A map from table name to a set of object ids. + std::map, std::less<>> m_objects; +}; + +// FieldSet is a set of fields in tables. A field is defined by a +// table name, a column in the table and an object id for the row. +class FieldSet { +public: + + void insert(StringData table, StringData column, ObjectID object_id); + void erase(StringData table, StringData column, ObjectID object_id); + bool contains(StringData table, ObjectID object_id) const noexcept; + bool contains(StringData table, StringData column, ObjectID object_id) const noexcept; + + // A map from table name to a map from column name to a set of + // object ids. + std::map< + std::string, + std::map, std::less<>>, + std::less<> + > m_fields; +}; + +struct GlobalID { + StringData table_name; + ObjectID object_id; + + bool operator==(const GlobalID& other) const; + bool operator!=(const GlobalID& other) const; + bool operator<(const GlobalID& other) const; +}; + +/// Implementation: + + +constexpr ObjectID::ObjectID(uint64_t hi, uint64_t lo): m_lo(lo), m_hi(hi) +{ +} + +constexpr ObjectID::ObjectID(realm::util::None): m_lo(-1), m_hi(-1) +{ +} + +constexpr bool ObjectID::operator<(const ObjectID& other) const +{ + return (m_hi == other.m_hi) ? (m_lo < other.m_lo) : (m_hi < other.m_hi); +} + +constexpr bool ObjectID::operator==(const ObjectID& other) const +{ + return m_hi == other.m_hi && m_lo == other.m_lo; +} + +constexpr bool ObjectID::operator!=(const ObjectID& other) const +{ + return !(*this == other); +} + +inline bool GlobalID::operator==(const GlobalID& other) const +{ + return table_name == other.table_name && object_id == other.object_id; +} + +inline bool GlobalID::operator!=(const GlobalID& other) const +{ + return !(*this == other); +} + +inline bool GlobalID::operator<(const GlobalID& other) const +{ + if (table_name == other.table_name) + return object_id < other.object_id; + return table_name < other.table_name; +} + + +std::ostream& operator<<(std::ostream&, const realm::sync::ObjectID&); + +inline ObjectIDProvider::LocalObjectID +ObjectIDProvider::get_optimistic_local_id_hashed(ObjectID global_id) +{ +#if REALM_EXERCISE_OBJECT_ID_COLLISION + const uint64_t optimistic_mask = 0xff; +#else + const uint64_t optimistic_mask = 0x7fffffffffffffff; +#endif + static_assert(optimistic_mask < 0x8000000000000000, "optimistic Object ID mask must leave the 64th bit zero"); + return global_id.lo() & optimistic_mask; +} + +inline ObjectIDProvider::LocalObjectID +ObjectIDProvider::make_tagged_local_id_after_hash_collision(uint64_t sequence_number) +{ + REALM_ASSERT(sequence_number < 0x8000000000000000); + return 0x8000000000000000 | sequence_number; +} + +inline ObjectIDProvider::LocalObjectID +ObjectIDProvider::global_to_local_object_id_squeezed(ObjectID object_id) +{ + REALM_ASSERT(object_id.hi() <= std::numeric_limits::max()); + REALM_ASSERT(object_id.lo() <= std::numeric_limits::max()); + + uint64_t a = object_id.lo() & 0xff; + uint64_t b = (object_id.hi() & 0xff) << 8; + uint64_t c = (object_id.lo() & 0xffffff00) << 8; + uint64_t d = (object_id.hi() & 0xffffff00) << 32; + union { + uint64_t u; + int64_t s; + } bitcast; + bitcast.u = a | b | c | d; + return bitcast.s; +} + +inline ObjectID +ObjectIDProvider::local_to_global_object_id_squeezed(LocalObjectID squeezed) +{ + union { + uint64_t u; + int64_t s; + } bitcast; + bitcast.s = squeezed; + + uint64_t u = bitcast.u; + + uint64_t lo = (u & 0xff) | ((u & 0xffffff0000) >> 8); + uint64_t hi = ((u & 0xff00) >> 8) | ((u & 0xffffff0000000000) >> 32); + return ObjectID{hi, lo}; +} + +} // namespace sync +} // namespace realm + +namespace std { + +template <> +struct hash { + size_t operator()(realm::sync::ObjectID oid) const + { + return std::hash{}(oid.lo()) ^ std::hash{}(oid.hi()); + } +}; + +} // namespace std + +#endif // REALM_SYNC_OBJECT_ID_HPP + diff --git a/Pods/Realm/include/core/realm/sync/permissions.hpp b/Pods/Realm/include/core/realm/sync/permissions.hpp new file mode 100644 index 0000000000..f042956124 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/permissions.hpp @@ -0,0 +1,403 @@ + +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_SYNC_PERMISSIONS_HPP +#define REALM_SYNC_PERMISSIONS_HPP + +#include + +#include +#include +#include + +#include + +namespace realm { +namespace sync { + +/// Permissions Schema: +/// +/// class___Role: +/// string name PRIMARY_KEY; +/// User[] members; +/// +/// class___Permission: +/// __Role role; +/// bool canRead; +/// bool canUpdate; +/// bool canDelete; +/// bool canSetPermissions; +/// bool canQuery; +/// bool canCreate; +/// bool canModifySchema; +/// +/// class___Realm: +/// int id PRIMARY_KEY = 0; // singleton object +/// __Permission[] permissions; +/// +/// class___User: +/// string id PRIMARY_KEY; +/// __Role role; +/// +/// class___Class: +/// string name PRIMARY_KEY; +/// __Permission[] permissions; +/// +/// class_: +/// __Permission[] ; +/// __Role ; +/// + +static constexpr char g_roles_table_name[] = "class___Role"; +static constexpr char g_permissions_table_name[] = "class___Permission"; +static constexpr char g_users_table_name[] = "class___User"; +static constexpr char g_classes_table_name[] = "class___Class"; +static constexpr char g_realms_table_name[] = "class___Realm"; + + +/// Create the permissions schema if it doesn't already exist. +void create_permissions_schema(Group&); + +/// Set up the basic "everyone" role and default permissions. The default is to +/// set up some very permissive defaults, where "everyone" can do everything. +void set_up_basic_permissions(Group&, bool permissive = true); + +void set_up_basic_permissions_for_class(Group&, StringData class_name, bool permissive = true); + +/// Set up some basic permissions for the class. The default is to set up some +/// very permissive default, where "everyone" can do everything in the class. +// void set_up_basic_default_permissions_for_class(Group&, TableRef klass, bool permissive = true); + +/// Return the index of the ACL in the class, if one exists. If no ACL column is +/// defined in the class, returns `npos`. +size_t find_permissions_column(const Group&, ConstTableRef); + +//@{ +/// Convenience functions to check permisions data +/// The functions must be called inside a read (or write) transaction. +bool permissions_schema_exist(const Group&); + +bool user_exist(const Group&, StringData user_id); +//@} + +//@{ +/// Convenience function to modify permission data. +/// +/// When a role or user has not already been defined in the Realm, these +/// functions create them on-demand. +void set_realm_permissions_for_role(Group&, StringData role_name, + uint_least32_t privileges); +void set_class_permissions_for_role(Group&, StringData class_name, + StringData role_name, uint_least32_t privileges); +// void set_default_object_permissions_for_role(Group&, StringData class_name, +// StringData role_name, +// uint_least32_t privileges); +void set_object_permissions_for_role(Group&, TableRef table, size_t row_ndx, + StringData role_name, uint_least32_t privileges); + +void add_user_to_role(Group&, StringData user_id, StringData role_name); +//@} + +/// The Privilege enum is intended to be used in a bitfield. +enum class Privilege : uint_least32_t { + None = 0, + + /// The user can read the object (i.e. it can participate in the user's + /// subscription. + /// + /// NOTE: On objects, it is a prerequisite that the object's class is also + /// readable by the user. + /// + /// FIXME: Until we get asynchronous links, any object that is reachable + /// through links from another readable/queryable object is also readable, + /// regardless of whether the user specifically does not have read access. + Read = 1, + + /// The user can modify the fields of the object. + /// + /// NOTE: On objects, it is a prerequisite that the object's class is also + /// updatable by the user. When applied to a Class object, it does not + /// imply that the user can modify the schema of the class, only the + /// objects of that class. + /// + /// NOTE: This does not imply the SetPermissions privilege. + Update = 2, + + /// The user can delete the object. + /// + /// NOTE: When applied to a Class object, it has no effect on whether + /// objects of that class can be deleted by the user. + /// + /// NOTE: This implies the ability to implicitly nullify links pointing + /// to the object from other objects, even if the user does not have + /// permission to modify those objects in the normal way. + Delete = 4, + + //@{ + /// The user can modify the object's permissions. + /// + /// NOTE: The user will only be allowed to assign permissions at or below + /// their own privilege level. + SetPermissions = 8, + Share = SetPermissions, + //@} + + /// When applied to a Class object, the user can query objects in that + /// class. + /// + /// Has no effect when applied to objects other than Class. + Query = 16, + + /// When applied to a Class object, the user may create objects in that + /// class. + /// + /// NOTE: The user implicitly has Update and SetPermissions + /// (but not necessarily Delete permission) within the same + /// transaction as the object was created. + /// + /// NOTE: Even when a user has CreateObject rights, a CreateObject + /// operation may still be rejected by the server, if the object has a + /// primary key and the object already exists, but is not accessible by the + /// user. + Create = 32, + + /// When applied as a "Realm" privilege, the user can add classes and add + /// columns to classes. + /// + /// NOTE: When applied to a class or object, this has no effect. + ModifySchema = 64, + + /// + /// Aggregate permissions for compatibility: + /// + Download = Read | Query, + Upload = Update | Delete | Create, + DeleteRealm = Upload, // FIXME: This seems overly permissive +}; + +inline constexpr uint_least32_t operator|(Privilege a, Privilege b) +{ + return static_cast(a) | static_cast(b); +} + +inline constexpr uint_least32_t operator|(uint_least32_t a, Privilege b) +{ + return a | static_cast(b); +} + +inline constexpr uint_least32_t operator&(Privilege a, Privilege b) +{ + return static_cast(a) & static_cast(b); +} + +inline constexpr uint_least32_t operator&(uint_least32_t a, Privilege b) +{ + return a & static_cast(b); +} + +inline uint_least32_t& operator|=(uint_least32_t& a, Privilege b) +{ + return a |= static_cast(b); +} + +inline constexpr uint_least32_t operator~(Privilege p) +{ + return ~static_cast(p); +} + +struct PermissionsCache { + /// Each element is the index of a row in the `class___Roles` table. + using RoleList = std::vector; + + PermissionsCache(const Group& g, StringData user_identity, bool is_admin = false); + + bool is_admin() const noexcept; + + /// Leaves out any role that has no permission objects linking to it. + RoleList get_users_list_of_roles(); + + /// Get Realm-level privileges for the current user. + /// + /// The user must have Read access at the Realm level to be able to see + /// anything in the file. + /// + /// The user must have Update access at the Realm level to be able to make + /// any changes at all in the Realm file. + /// + /// If no Realm-level permissions are defined, no access is granted for any + /// user. + uint_least32_t get_realm_privileges(); + + /// Get class-level privileges for the current user and the given class. + /// + /// If the class does not have any class-level privileges defined, no access + /// is granted to the class. + /// + /// Calling this function is equivalent to calling `get_object_privileges()` + /// with an object of the type `__Class`. + /// + /// NOTE: This function only considers class-level permissions. It does not + /// mask the returned value by the Realm-level permissions. See `can()`. + uint_least32_t get_class_privileges(StringData class_name); + + /// Get object-level privileges for the current user and the given object. + /// + /// If the object's class has an ACL property (a linklist to the + /// `__Permission` class), and it isn't empty, the user's privileges is the + /// OR'ed privileges for the intersection of roles that have a defined + /// permission on the object and the roles of which the user is a member. + /// + /// If the object's ACL property is empty (but the column exists), no access + /// is granted to anyone. + /// + /// If the object does not exist in the table, the returned value is + /// equivalent to that of an object with an empty ACL property, i.e. no + /// privileges are granted. Note that the existence of the column is checked + /// first, so an absent ACL property (granting all privileges) takes + /// precedence over an absent object (granting no privileges) in terms of + /// calculating permissions. + /// + /// NOTE: This function only considers object-level permissions (per-object + /// ACLs or default object permissions). It does not mask the returned value + /// by the object's class-level permissions, or by the Realm-level + /// permissions. See `can()`. + uint_least32_t get_object_privileges(GlobalID); + + /// Get object-level privileges without adding it to the cache. + uint_least32_t get_object_privileges_nocache(GlobalID); + + //@{ + /// Check permissions for the object, taking all levels of permission into + /// account. + /// + /// This method only returns `true` if the user has Realm-level access to + /// the object, class-level access to the object, and object-level access to + /// the object. + /// + /// In the version where the first argument is a mask of privileges, the + /// method only returns `true` when all privileges are satisfied. + bool can(Privilege privilege, GlobalID object_id); + bool can(uint_least32_t privileges, GlobalID object_id); + //@} + + /// Invalidate all cache entries pertaining to the object. + /// + /// The object may be an instance of `__Class`. + void object_permissions_modified(GlobalID); + + /// Register the object as created in this transaction, meaning that the + /// user gets full privileges until the end of the transaction. + void object_created(GlobalID); + + /// Invalidate all cache entries pertaining to the class. + // void default_object_permissions_modified(StringData class_name); + + /// Invalidate all cached permissions. + void clear(); + + /// Check that all cache permissions correspond to the current permission + /// state in the database. + void verify(); + +private: + const Group& group; + TableInfoCache cache; + std::string user_id; + bool m_is_admin; + util::Optional realm_privileges; + std::map object_privileges; + ObjectIDSet created_objects; + + // uint_least32_t get_default_object_privileges(ConstTableRef); + uint_least32_t get_privileges_for_permissions(ConstLinkViewRef); + friend struct InstructionApplierWithPermissionCheck; +}; + +inline bool PermissionsCache::is_admin() const noexcept +{ + return m_is_admin; +} + +/// PermissionCorrections is a struct that describes some changes that must be +/// sent to the client because the client tried to perform changes to a database +/// that it wasn't allowed to make. +struct PermissionCorrections { + using TableColumnSet = std::map>, std::less<>>; + using TableSet = std::set>; + + // Objects that a client tried to delete without being allowed. + ObjectIDSet recreate_objects; + + // Objects that a client tried to create without being allowed. + ObjectIDSet erase_objects; + + // Fields that were illegally modified by the client and must be reset. + // + // Objects mentioned in `recreate_objects` and `erase_objects` are not + // mentioned here. + FieldSet reset_fields; + + // Columns that were illegally added by the client. + TableColumnSet erase_columns; + + // Columns that were illegally removed by the client. + TableColumnSet recreate_columns; + + // Tables that were illegally added by the client. + // std::set erase_tables; + TableSet erase_tables; + + // Tables that were illegally removed by the client. + TableSet recreate_tables; +}; + +// Function for printing out a permission correction object. Useful for debugging purposes. +std::ostream& operator<<(std::ostream&, const PermissionCorrections&); + + + +/// InstructionApplierWithPermissionCheck conditionally applies each +/// instruction, and builds a `PermissionCorrections` struct based on the +/// illicit changes. The member `m_corrections` can be used to synthesize a +/// changeset that can be sent to the client to revert the illicit changes that +/// were detected by the applier. +struct InstructionApplierWithPermissionCheck { + explicit InstructionApplierWithPermissionCheck(Group& reference_realm, + bool is_admin, + StringData user_identity); + ~InstructionApplierWithPermissionCheck(); + + /// Apply \a incoming_changeset, checking permissions in the process. + /// Populates `m_corrections`. + void apply(const Changeset& incoming_changeset, util::Logger*); + + PermissionCorrections m_corrections; + +private: + struct Impl; + std::unique_ptr m_impl; +}; + +} // namespace sync +} // namespace realm + + +#endif // REALM_SYNC_PERMISSIONS_HPP diff --git a/Pods/Realm/include/core/realm/sync/protocol.hpp b/Pods/Realm/include/core/realm/sync/protocol.hpp new file mode 100644 index 0000000000..004acd03d3 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/protocol.hpp @@ -0,0 +1,285 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_SYNC_PROTOCOL_HPP +#define REALM_SYNC_PROTOCOL_HPP + +#include +#include + +#include + + + +// NOTE: The protocol specification is in `/doc/protocol.md` + + +namespace realm { +namespace sync { + +// Protocol versions: +// +// 1 Initial version. +// +// 2 Introduces the UNBOUND message (sent from server to client in +// response to a BIND message). +// +// 3 Introduces the ERROR message (sent from server to client before the +// server closes a connection). Introduces MARK message from client to +// server, and MARK response message from server to client as a way for the +// client to wait for download to complete. +// +// 4 User token and signature are now passed as a single string (see +// /doc/protocol.md for details). Also, `application_ident` parameter +// removed from IDENT message. +// +// 5 IDENT message renamed to CLIENT, and ALLOC message (client->server) +// renamed to IDENT. Also, parameter added to CLIENT +// message. Also, the protocol has been changed to make the clients +// acquisition of a server allocated file identifier pair be part of a +// session from the servers point of view. File identifier and version +// parameters moved from the BIND message to a new IDENT message sent by +// client when it has obtained the file identifier pair. Both the new IDENT +// message and the ALLOC message sent by the server are now properly +// associated with a session. +// +// 6 Server session IDs have been added to the IDENT, DOWNLOAD, and PROGRESS +// messages, and the "Divergent history" error code was added as an +// indication that a server version / session ID pair does not match the +// server's history. +// +// 7 FIXME: Who introduced version 7? Please describe what changed. +// +// 8 Error code (`bad_authentication`) moved from 200-range to 300-range +// because it is now session specific. Other error codes were renumbered. +// +// 9 New format of the DOWNLOAD message to support progress reporting on the +// client +// +// 10 Error codes reordered (now categorized as either connection or session +// level errors). +// +// 11 Bugfixes in Link List and ChangeLinkTargets merge rules, that +// make previous versions incompatible. +// +// 12 FIXME What was 12? +// +// 13 Bugfixes in Link List and ChangeLinkTargets merge rules, that +// make previous versions incompatible. +// +// 14 Further bugfixes related to primary keys and link lists. Add support for +// LinkListSwap. +// +// 15 Deleting an object with a primary key deletes all objects on other +// with the same primary key. +// +// 16 Downloadable bytes added to DOWNLOAD message. It is used for download progress +// by the client +// +// 17 Added PING and PONG messages. It is used for rtt monitoring and dead +// connection detection by both the client and the server. +// +// 18 Enhanced the session_ident to accept values of size up to at least 63 bits. +// +// 19 New instruction log format with stable object IDs and arrays of +// primitives (Generalized LinkList* commands to Container* commands) +// Message format is identical to version 18. +// +// 20 Added support for log compaction in DOWNLOAD message. +// +// 21 Removed "class_" prefix in instructions referencing tables. +// +// 22 Fixed a bug in the merge rule of MOVE vs SWAP. +// +// 23 Introduced full support for session specific ERROR messages. Removed the +// obsolete concept of a "server file identifier". Added support for relayed +// subtier client file identifier allocation. For this purpose, the message +// that was formerly known as ALLOC was renamed to IDENT, and a new ALLOC +// message was added in both directions. Added the ability for an UPLOAD +// message to carry a per-changeset origin client file identifier. Added +// `` parameter to DOWNLOAD message. Added new error +// codes 215 "Unsupported session-level feature" and 216 "Bad origin client +// file identifier (UPLOAD)". +// +// 24 Support schema-breaking instructions. Official support for partial sync. +// +// 25 Include "last server version" in the UPLOAD message for history trimming +// on the server. + +constexpr int get_current_protocol_version() noexcept +{ + return 25; +} + + +// These integer types are selected so that they accomodate the requirements of +// the protocol specification (`/doc/protocol.md`). +using file_ident_type = std::uint_fast64_t; +using version_type = Replication::version_type; +using salt_type = std::int_fast64_t; +using timestamp_type = std::uint_fast64_t; +using session_ident_type = std::uint_fast64_t; +using request_ident_type = std::uint_fast64_t; +using milliseconds_type = std::int_fast64_t; + +constexpr file_ident_type get_max_file_ident() +{ + return 0x0'7FFF'FFFF'FFFF'FFFF; +} + + +struct SaltedFileIdent { + file_ident_type ident; + /// History divergence and identity spoofing protection. + salt_type salt; +}; + +struct SaltedVersion { + version_type version; + /// History divergence protection. + salt_type salt; +}; + + +/// \brief A client's reference to a position in the server-side history. +/// +/// A download cursor refers to a position in the server-side history. If +/// `server_version` is zero, the position is at the beginning of the history, +/// otherwise the position is after the entry whose changeset produced that +/// version. In general, positions are to be understood as places between two +/// adjacent history entries. +/// +/// `last_integrated_client_version` is the version produced on the client by +/// the last changeset that was sent to the server and integrated into the +/// server-side Realm state at the time indicated by the history position +/// specified by `server_version`, or zero if no changesets from the client were +/// integrated by the server at that point in time. +struct DownloadCursor { + version_type server_version; + version_type last_integrated_client_version; +}; + + +/// \brief The server's reference to a position in the client-side history. +/// +/// An upload cursor refers to a position in the client-side history. If +/// `client_version` is zero, the position is at the beginning of the history, +/// otherwise the position is after the entry whose changeset produced that +/// version. In general, positions are to be understood as places between two +/// adjacent history entries. +/// +/// `last_integrated_server_version` is the version produced on the server by +/// the last changeset that was sent to the client and integrated into the +/// client-side Realm state at the time indicated by the history position +/// specified by `client_version`, or zero if no changesets from the server were +/// integrated by the client at that point in time. +struct UploadCursor { + version_type client_version; + version_type last_integrated_server_version; +}; + + +/// A client's record of the current point of progress of the synchronization +/// process. The client must store this persistently in the local Realm file. +struct SyncProgress { + SaltedVersion latest_server_version{0, 0}; + DownloadCursor download{0, 0}; + UploadCursor upload{0, 0}; + std::int_fast64_t downloadable_bytes = 0; +}; + + + +/// \brief Protocol errors discovered by the server, and reported to the client +/// by way of ERROR messages. +/// +/// These errors will be reported to the client-side application via the error +/// handlers of the affected sessions. +/// +/// ATTENTION: Please remember to update is_session_level_error() when +/// adding/removing error codes. +enum class ProtocolError { + // Connection level and protocol errors + connection_closed = 100, // Connection closed (no error) + other_error = 101, // Other connection level error + unknown_message = 102, // Unknown type of input message + bad_syntax = 103, // Bad syntax in input message head + limits_exceeded = 104, // Limits exceeded in input message + wrong_protocol_version = 105, // Wrong protocol version (CLIENT) + bad_session_ident = 106, // Bad session identifier in input message + reuse_of_session_ident = 107, // Overlapping reuse of session identifier (BIND) + bound_in_other_session = 108, // Client file bound in other session (IDENT) + bad_message_order = 109, // Bad input message order + bad_decompression = 110, // Error in decompression (UPLOAD) + bad_changeset_header_syntax = 111, // Bad syntax in a changeset header (UPLOAD) + bad_changeset_size = 112, // Bad size specified in changeset header (UPLOAD) + bad_changesets = 113, // Bad changesets (UPLOAD) + + // Session level errors + session_closed = 200, // Session closed (no error) + other_session_error = 201, // Other session level error + token_expired = 202, // Access token expired + bad_authentication = 203, // Bad user authentication (BIND, REFRESH) + illegal_realm_path = 204, // Illegal Realm path (BIND) + no_such_realm = 205, // No such Realm (BIND) + permission_denied = 206, // Permission denied (BIND, REFRESH) + bad_server_file_ident = 207, // Bad server file identifier (IDENT) (obsolete!) + bad_client_file_ident = 208, // Bad client file identifier (IDENT) + bad_server_version = 209, // Bad server version (IDENT, UPLOAD) + bad_client_version = 210, // Bad client version (IDENT, UPLOAD) + diverging_histories = 211, // Diverging histories (IDENT) + bad_changeset = 212, // Bad changeset (UPLOAD) + superseded = 213, // Superseded by new session for same client-side file (deprecated) + disabled_session = 213, // Alias for `superseded` (deprecated) + partial_sync_disabled = 214, // Partial sync disabled (BIND) + unsupported_session_feature = 215, // Unsupported session-level feature + bad_origin_file_ident = 216, // Bad origin file identifier (UPLOAD) +}; + +inline constexpr bool is_session_level_error(ProtocolError error) +{ + return int(error) >= 200 && int(error) <= 299; +} + +/// Returns null if the specified protocol error code is not defined by +/// ProtocolError. +const char* get_protocol_error_message(int error_code) noexcept; + +const std::error_category& protocol_error_category() noexcept; + +std::error_code make_error_code(ProtocolError) noexcept; + +} // namespace sync +} // namespace realm + +namespace std { + +template<> struct is_error_code_enum { + static const bool value = true; +}; + +} // namespace std + +namespace realm { +namespace sync { + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_PROTOCOL_HPP diff --git a/Pods/Realm/include/core/realm/sync/transform.hpp b/Pods/Realm/include/core/realm/sync/transform.hpp new file mode 100644 index 0000000000..8809c38884 --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/transform.hpp @@ -0,0 +1,292 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_SYNC_TRANSFORM_HPP +#define REALM_SYNC_TRANSFORM_HPP + +#include + +#include +#include +#include +#include +#include + +namespace realm { +namespace sync { + +struct Changeset; + +/// Represents an entry in the history of changes in a sync-enabled Realm +/// file. Server and client use different history formats, but this class is +/// used both on the server and the client side. Each history entry corresponds +/// to a version of the Realm state. For server and client-side histories, these +/// versions are referred to as *server versions* and *client versions* +/// respectively. These versions may, or may not correspond to Realm snapshot +/// numbers (on the server-side they currently do not). +/// +/// FIXME: Move this class into a separate header +/// (``). +class HistoryEntry { +public: + /// The time of origination of the changes referenced by this history entry, + /// meassured as the number of milliseconds since 2015-01-01T00:00:00Z, not + /// including leap seconds. For changes of local origin, this is the local + /// time at the point when the local transaction was committed. For changes + /// of remote origin, it is the remote time of origin at the peer (client or + /// server) identified by `origin_file_ident`. + timestamp_type origin_timestamp; + + /// The identifier of the file in the context of which the initial + /// untransformed changeset originated, or zero if the changeset originated + /// on the local peer (client or server). + /// + /// For example, when a changeset "travels" from a file with identifier 2 on + /// client A, through a file with identifier 1 on the server, to a file with + /// identifier 3 on client B, then `origin_file_ident` will be 0 on client + /// A, 2 on the server, and 2 on client B. On the other hand, if the server + /// was the originator of the changeset, then `origin_file_ident` would be + /// zero on the server, and 1 on both clients. + file_ident_type origin_file_ident; + + /// For changes of local origin on the client side, this is the last server + /// version integrated locally prior to this history entry. In other words, + /// it is a copy of `remote_version` of the last preceding history entry + /// that carries changes of remote origin, or zero if there is no such + /// preceding history entry. + /// + /// For changes of local origin on the server-side, this is always zero. + /// + /// For changes of remote origin, this is the version produced within the + /// remote-side Realm file by the change that gave rise to this history + /// entry. The remote-side Realm file is not always the same Realm file from + /// which the change originated. On the client side, the remote side is + /// always the server side, and `remote_version` is always a server version + /// (since clients do not speak directly to each other). On the server side, + /// the remote side is always a client side, and `remote_version` is always + /// a client version. + version_type remote_version; + + /// Referenced memory is not owned by this class. + ChunkedBinaryData changeset; +}; + + + +/// The interface between the sync history and the operational transformer +/// (Transformer) for the purpose of transforming changesets received from a +/// particular *remote peer*. +class TransformHistory { +public: + /// Get the first history entry where the produced version is greater than + /// `begin_version` and less than or equal to `end_version`, and whose + /// changeset is neither empty, nor produced by integration of a changeset + /// received from the remote peer associated with this history. + /// + /// If \a buffer is non-null, memory will be allocated and transferred to + /// \a buffer. The changeset will be copied into the newly allocated memory. + /// + /// If \a buffer is null, the changeset is not copied out of the Realm, + /// and entry.changeset.data() does not point to the changeset. + /// The changeset in the Realm could be chunked, hence it is not possible + /// to point to it with BinaryData. entry.changeset.size() always gives the + /// size of the changeset. + /// + /// \param begin_version, end_version The range of versions to consider. If + /// `begin_version` is equal to `end_version`, it is the empty range. If + /// `begin_version` is zero, it means that everything preceeding + /// `end_version` is to be considered, which is again the empty range if + /// `end_version` is also zero. Zero is a special value in that no changeset + /// produces that version. It is an error if `end_version` precedes + /// `begin_version`, or if `end_version` is zero and `begin_version` is not. + /// + /// \return The version produced by the changeset of the located history + /// entry, or zero if no history entry exists matching the specified and + /// implied criteria. + virtual version_type find_history_entry(version_type begin_version, version_type end_version, + HistoryEntry& entry) const noexcept = 0; + + /// Get the specified reciprocal changeset. The targeted history entry is + /// the one whose untransformed changeset produced the specified version. + virtual ChunkedBinaryData get_reciprocal_transform(version_type version) const = 0; + + /// Replace the specified reciprocally transformed changeset. The targeted + /// history entry is the one whose untransformed changeset produced the + /// specified version. + /// + /// \param encoded_changeset The new reciprocally transformed changeset. + virtual void set_reciprocal_transform(version_type version, BinaryData encoded_changeset) = 0; + + virtual ~TransformHistory() noexcept {} +}; + + + +class TransformError; // Exception + +class Transformer { +public: + class RemoteChangeset; + class Reporter; + + /// Produce operationally transformed versions of the specified changesets, + /// which are assumed to be received from a particular remote peer, P, + /// represented by the specified transform history. Note that P is not + /// necessarily the peer on which the changes originated. + /// + /// Operational transformation is carried out between the specified + /// changesets and all causally unrelated changesets in the local history. A + /// changeset in the local history is causally unrelated if, and only if it + /// occurs after the local changeset that produced + /// `remote_changeset.last_integrated_local_version` and is not a produced + /// by integration of a changeset received from P. This assumes that + /// `remote_changeset.last_integrated_local_version` is set to the local + /// version produced by the last local changeset, that was integrated by P + /// before P produced the specified changeset. + /// + /// The operational transformation is reciprocal (two-way), so it also + /// transforms the causally unrelated local changesets. This process does + /// not modify the history itself (the changesets available through + /// TransformHistory::get_history_entry()), instead the reciprocally + /// transformed changesets are stored separately, and individually for each + /// remote peer, such that they can participate in transformation of the + /// next incoming changeset from P. + /// + /// In general, if A and B are two causally unrelated (alternative) + /// changesets based on the same version V, then the operational + /// transformation between A and B produces changesets A' and B' such that + /// both of the concatenated changesets A + B' and B + A' produce the same + /// final state when applied to V. Operational transformation is meaningful + /// only when carried out between alternative changesets based on the same + /// version. + /// + /// \param local_file_ident The identifier of the local Realm file. The + /// transformer uses this as the actual origin file identifier for + /// changesets where HistoryEntry::origin_file_ident is zero, i.e., when the + /// changeset is of local origin. The specified identifier must never be + /// zero. + /// + /// \return The size of the transformed version of the specified + /// changesets. Upon return, the transformed changesets are concatenated + /// and placed in \a output_buffer. + /// + /// \throw TransformError Thrown if operational transformation fails due to + /// a problem with the specified changeset. + /// + /// FIXME: Consider using std::error_code instead of throwing + /// TransformError. + virtual void transform_remote_changesets(TransformHistory&, + file_ident_type local_file_ident, + version_type current_local_version, + Changeset* changesets, + std::size_t num_changesets, + Reporter* = nullptr) = 0; + + virtual ~Transformer() noexcept {} +}; + +std::unique_ptr make_transformer(); + + + +class Transformer::RemoteChangeset { +public: + /// The version produced on the remote peer by this changeset. + /// + /// On the server, the remote peer is the client from which the changeset + /// originated, and `remote_version` is the client version produced by the + /// changeset on that client. + /// + /// On a client, the remote peer is the server, and `remote_version` is the + /// server version produced by this changeset on the server. Since the + /// server is never the originator of changes, this changeset must in turn + /// have been produced on the server by integration of a changeset uploaded + /// by some other client. + version_type remote_version = 0; + + /// The last local version that has been integrated into `remote_version`. + /// + /// A local version, L, has been integrated into a remote version, R, when, + /// and only when L is the latest local version such that all preceeding + /// changesets in the local history have been integrated by the remote peer + /// prior to R. + /// + /// On the server, this is the last server version integrated into the + /// client version `remote_version`. On a client, it is the last client + /// version integrated into the server version `remote_version`. + version_type last_integrated_local_version = 0; + + /// The changeset itself. + ChunkedBinaryData data; + + /// Same meaning as `HistoryEntry::origin_timestamp`. + timestamp_type origin_timestamp = 0; + + /// Same meaning as `HistoryEntry::origin_file_ident`. + file_ident_type origin_file_ident = 0; + + /// If the changeset was compacted during download, the size of the original + /// changeset. + size_t original_changeset_size = 0; + + RemoteChangeset() {} + RemoteChangeset(version_type rv, version_type lv, ChunkedBinaryData d, timestamp_type ot, + file_ident_type fi); +}; + + + +class Transformer::Reporter { +public: + virtual void on_changesets_merged(long num_merges) = 0; +}; + + + +void parse_remote_changeset(const Transformer::RemoteChangeset&, Changeset&); + + + + +// Implementation + +class TransformError: public std::runtime_error { +public: + TransformError(const std::string& message): + std::runtime_error(message) + { + } +}; + +inline Transformer::RemoteChangeset::RemoteChangeset(version_type rv, version_type lv, + ChunkedBinaryData d, timestamp_type ot, + file_ident_type fi): + remote_version(rv), + last_integrated_local_version(lv), + data(d), + origin_timestamp(ot), + origin_file_ident(fi) +{ +} + +} // namespace sync +} // namespace realm + +#endif // REALM_SYNC_TRANSFORM_HPP diff --git a/Pods/Realm/include/core/realm/sync/version.hpp b/Pods/Realm/include/core/realm/sync/version.hpp new file mode 100644 index 0000000000..ce5817948d --- /dev/null +++ b/Pods/Realm/include/core/realm/sync/version.hpp @@ -0,0 +1,34 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2013] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_SYNC_VERSION_HPP +#define REALM_SYNC_VERSION_HPP + +#include + +#define REALM_SYNC_VER_MAJOR 3 +#define REALM_SYNC_VER_MINOR 12 +#define REALM_SYNC_VER_PATCH 2 +#define REALM_SYNC_PRODUCT_NAME "realm-sync" + +#define REALM_SYNC_VER_STRING REALM_QUOTE(REALM_SYNC_VER_MAJOR) "." \ + REALM_QUOTE(REALM_SYNC_VER_MINOR) "." REALM_QUOTE(REALM_SYNC_VER_PATCH) +#define REALM_SYNC_VER_CHUNK "[" REALM_SYNC_PRODUCT_NAME "-" REALM_SYNC_VER_STRING "]" + +#endif // REALM_SYNC_VERSION_HPP diff --git a/Pods/Realm/include/core/realm/table.hpp b/Pods/Realm/include/core/realm/table.hpp new file mode 100644 index 0000000000..d4833cb5d8 --- /dev/null +++ b/Pods/Realm/include/core/realm/table.hpp @@ -0,0 +1,2796 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_TABLE_HPP +#define REALM_TABLE_HPP + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace realm { + +class BacklinkColumn; +template +class BacklinkCount; +class BinaryColumy; +class ConstTableView; +class Group; +class LinkColumn; +class LinkColumnBase; +class LinkListColumn; +class LinkView; +class SortDescriptor; +class StringIndex; +class TableView; +class TableViewBase; +class TimestampColumn; +template +class Columns; +template +class SubQuery; +struct LinkTargetInfo; + +struct SubTable { +}; +struct Link { +}; +typedef Link LinkList; +typedef Link BackLink; + +namespace _impl { +class TableFriend; +} +namespace metrics { +class QueryInfo; +} + +class Replication; + + +/// FIXME: Table assignment (from any group to any group) could be made aliasing +/// safe as follows: Start by cloning source table into target allocator. On +/// success, assign, and then deallocate any previous structure at the target. +/// +/// FIXME: It might be desirable to have a 'table move' feature between two +/// places inside the same group (say from a subtable or a mixed column to group +/// level). This could be done in a very efficient manner. +/// +/// FIXME: When compiling in debug mode, all public non-static table functions +/// should REALM_ASSERT(is_attached()). +class Table { +public: + /// Construct a new freestanding top-level table with static + /// lifetime. + /// + /// This constructor should be used only when placing a table + /// instance on the stack, and it is then the responsibility of + /// the application that there are no objects of type TableRef or + /// ConstTableRef that refer to it, or to any of its subtables, + /// when it goes out of scope. To create a top-level table with + /// dynamic lifetime, use Table::create() instead. + Table(Allocator& = Allocator::get_default()); + + /// Construct a copy of the specified table as a new freestanding + /// top-level table with static lifetime. + /// + /// This constructor should be used only when placing a table + /// instance on the stack, and it is then the responsibility of + /// the application that there are no objects of type TableRef or + /// ConstTableRef that refer to it, or to any of its subtables, + /// when it goes out of scope. To create a top-level table with + /// dynamic lifetime, use Table::copy() instead. + Table(const Table&, Allocator& = Allocator::get_default()); + + ~Table() noexcept; + + Allocator& get_alloc() const; + + /// Construct a new freestanding top-level table with dynamic lifetime. + static TableRef create(Allocator& = Allocator::get_default()); + + /// Construct a copy of the specified table as a new freestanding top-level + /// table with dynamic lifetime. + TableRef copy(Allocator& = Allocator::get_default()) const; + + /// Returns true if, and only if this accessor is currently attached to an + /// underlying table. + /// + /// A table accessor may get detached from the underlying row for various + /// reasons (see below). When it does, it no longer refers to anything, and + /// can no longer be used, except for calling is_attached(). The + /// consequences of calling other non-static functions on a detached table + /// accessor are unspecified. Table accessors obtained by calling functions in + /// the Realm API are always in the 'attached' state immediately upon + /// return from those functions. + /// + /// A table accessor of a free-standing table never becomes detached (except + /// during its eventual destruction). A group-level table accessor becomes + /// detached if the underlying table is removed from the group, or when the + /// group accessor is destroyed. A subtable accessor becomes detached if the + /// underlying subtable is removed, or if the parent table accessor is + /// detached. A table accessor does not become detached for any other reason + /// than those mentioned here. + /// + /// FIXME: High level language bindings will probably want to be able to + /// explicitely detach a group and all tables of that group if any modifying + /// operation fails (e.g. memory allocation failure) (and something similar + /// for freestanding tables) since that leaves the group in state where any + /// further access is disallowed. This way they will be able to reliably + /// intercept any attempt at accessing such a failed group. + /// + /// FIXME: The C++ documentation must state that if any modifying operation + /// on a group (incl. tables, subtables, and specs) or on a free standing + /// table (incl. subtables and specs) fails, then any further access to that + /// group (except ~Group()) or freestanding table (except ~Table()) has + /// undefined behaviour and is considered an error on behalf of the + /// application. Note that even Table::is_attached() is disallowed in this + /// case. + bool is_attached() const noexcept; + + /// Get the name of this table, if it has one. Only group-level tables have + /// names. For a table of any other kind, this function returns the empty + /// string. + StringData get_name() const noexcept; + + // Whether or not elements can be null. + bool is_nullable(size_t col_ndx) const; + + // Returns the link type for the given column. + // Throws an LogicError if target column is not a link column. + LinkType get_link_type(size_t col_ndx) const; + + //@{ + /// Conventience functions for inspecting the dynamic table type. + /// + /// These functions behave as if they were called on the descriptor returned + /// by get_descriptor(). + size_t get_column_count() const noexcept; + DataType get_column_type(size_t column_ndx) const noexcept; + StringData get_column_name(size_t column_ndx) const noexcept; + size_t get_column_index(StringData name) const noexcept; + typedef util::Optional> BacklinkOrigin; + BacklinkOrigin find_backlink_origin(StringData origin_table_name, StringData origin_col_name) const noexcept; + //@} + + //@{ + /// Convenience functions for manipulating the dynamic table type. + /// + /// These function must be called only for tables with independent dynamic + /// type. A table has independent dynamic type if the function + /// has_shared_type() returns false. A table that is a direct member of a + /// group has independent dynamic type. So does a free-standing table, and a + /// subtable in a column of type 'mixed'. All other tables have shared + /// dynamic type. The consequences of calling any of these functions for a + /// table with shared dynamic type are undefined. + /// + /// Apart from that, these functions behave as if they were called on the + /// descriptor returned by get_descriptor(). Note especially that the + /// `_link` suffixed functions must be used when inserting link-type + /// columns. + /// + /// If you need to change the shared dynamic type of the subtables in a + /// subtable column, consider using the API offered by the Descriptor class. + /// + /// \sa has_shared_type() + /// \sa get_descriptor() + + size_t add_column(DataType type, StringData name, bool nullable = false, DescriptorRef* subdesc = nullptr); + void insert_column(size_t column_ndx, DataType type, StringData name, bool nullable = false, + DescriptorRef* subdesc = nullptr); + + // Todo, these prototypes only exist for backwards compatibility. We should remove them because they are error + // prone (optional arguments and implicit bool to null-ptr conversion) + size_t add_column(DataType type, StringData name, DescriptorRef* subdesc) + { + return add_column(type, name, false, subdesc); + } + void insert_column(size_t column_ndx, DataType type, StringData name, DescriptorRef* subdesc) + { + insert_column(column_ndx, type, name, false, subdesc); + } + + size_t add_column_link(DataType type, StringData name, Table& target, LinkType link_type = link_Weak); + void insert_column_link(size_t column_ndx, DataType type, StringData name, Table& target, + LinkType link_type = link_Weak); + void remove_column(size_t column_ndx); + void rename_column(size_t column_ndx, StringData new_name); + //@} + //@{ + + /// has_search_index() returns true if, and only if a search index has been + /// added to the specified column. Rather than throwing, it returns false if + /// the table accessor is detached or the specified index is out of range. + /// + /// add_search_index() adds a search index to the specified column of the + /// table. It has no effect if a search index has already been added to the + /// specified column (idempotency). + /// + /// remove_search_index() removes the search index from the specified column + /// of the table. It has no effect if the specified column has no search + /// index. The search index cannot be removed from the primary key of a + /// table. + /// + /// This table must be a root table; that is, it must have an independent + /// descriptor. Freestanding tables, group-level tables, and subtables in a + /// column of type 'mixed' are all examples of root tables. See add_column() + /// for more on this. If you want to manipulate subtable indexes, you must use + /// the Descriptor interface. + /// + /// \param column_ndx The index of a column of the table. + + bool has_search_index(size_t column_ndx) const noexcept; + void add_search_index(size_t column_ndx); + void remove_search_index(size_t column_ndx); + + //@} + + //@{ + /// Get the dynamic type descriptor for this table. + /// + /// Every table has an associated descriptor that specifies its dynamic + /// type. For simple tables, that is, tables without subtable columns, the + /// dynamic type can be inspected and modified directly using member + /// functions such as get_column_count() and add_column(). For more complex + /// tables, the type is best managed through the associated descriptor + /// object which is returned by this function. + /// + /// \sa has_shared_type() + DescriptorRef get_descriptor(); + ConstDescriptorRef get_descriptor() const; + //@} + + //@{ + /// Get the dynamic type descriptor for the column with the + /// specified index. That column must have type 'table'. + /// + /// This is merely a shorthand for calling `get_subdescriptor(column_ndx)` + /// on the descriptor returned by `get_descriptor()`. + DescriptorRef get_subdescriptor(size_t column_ndx); + ConstDescriptorRef get_subdescriptor(size_t column_ndx) const; + //@} + + //@{ + /// Get access to an arbitrarily nested dynamic type descriptor. + /// + /// The returned descriptor is the one you would get by calling + /// Descriptor::get_subdescriptor() once for each entry in the specified + /// path, starting with the descriptor returned by get_descriptor(). The + /// path is allowed to be empty. + typedef std::vector path_vec; + DescriptorRef get_subdescriptor(const path_vec& path); + ConstDescriptorRef get_subdescriptor(const path_vec& path) const; + //@} + + //@{ + /// Convenience functions for manipulating nested table types. + /// + /// These functions behave as if they were called on the descriptor returned + /// by `get_subdescriptor(path)`. These function must be called only on + /// tables with independent dynamic type. + /// + /// \return The value returned by add_subcolumn(), is the index of + /// the added column within the descriptor referenced by the + /// specified path. + /// + /// \sa Descriptor::add_column() + /// \sa has_shared_type() + size_t add_subcolumn(const path_vec& path, DataType type, StringData name); + void insert_subcolumn(const path_vec& path, size_t column_ndx, DataType type, StringData name); + void remove_subcolumn(const path_vec& path, size_t column_ndx); + void rename_subcolumn(const path_vec& path, size_t column_ndx, StringData new_name); + //@} + + /// Does this table share its type with other tables? + /// + /// Tables that are direct members of groups have independent + /// dynamic types. The same is true for free-standing tables and + /// subtables in coulmns of type 'mixed'. For such tables, this + /// function returns false. + /// + /// When a table has a column of type 'table', the cells in that + /// column contain subtables. All those subtables have the same + /// dynamic type, and they share a single type descriptor. For all + /// such subtables, this function returns true. See + /// Descriptor::is_root() for more on this. + /// + /// Please note that Table functions that modify the dynamic type + /// directly, such as add_column(), are only allowed to be used on + /// tables with non-shared type. If you need to modify a shared + /// type, you will have to do that through the descriptor returned + /// by get_descriptor(), but note that it will then affect all the + /// tables sharing that descriptor. + /// + /// \sa get_descriptor() + /// \sa Descriptor::is_root() + bool has_shared_type() const noexcept; + + + template + Columns column(size_t column); // FIXME: Should this one have been declared noexcept? + template + Columns column(const Table& origin, size_t origin_column_ndx); + // BacklinkCount is a total count per row and therefore not attached to a specific column + template + BacklinkCount get_backlink_count(); + + template + SubQuery column(size_t column, Query subquery); + template + SubQuery column(const Table& origin, size_t origin_column_ndx, Query subquery); + + // Table size and deletion + bool is_empty() const noexcept; + size_t size() const noexcept; + + typedef BasicRowExpr
RowExpr; + typedef BasicRowExpr ConstRowExpr; + + RowExpr get(size_t row_ndx) noexcept; + ConstRowExpr get(size_t row_ndx) const noexcept; + + RowExpr front() noexcept; + ConstRowExpr front() const noexcept; + + RowExpr back() noexcept; + ConstRowExpr back() const noexcept; + + RowExpr operator[](size_t row_ndx) noexcept; + ConstRowExpr operator[](size_t row_ndx) const noexcept; + + + //@{ + + /// Row handling. + /// + /// remove() removes the specified row from the table and shifts all rows at + /// higher index to fill the vacated slot. This operation assumes that the + /// table is ordered, and it is therefore allowed only on tables **without** + /// link columns, as link columns are only allowed in unordered tables. + /// + /// move_last_over() removes the specified row from the table, and if it is + /// not the last row in the table, it then moves the last row into the + /// vacated slot. This operation assumes that the table is unordered, and it + /// may therfore be used on tables with link columns. + /// + /// remove_recursive() will delete linked rows if the removed link was the + /// last one holding on to the row in question. This will be done recursively. + /// + /// The removal of a row from an unordered table (move_last_over()) may + /// cause other linked rows to be cascade-removed. The clearing of a table + /// may also cause linked rows to be cascade-removed, but in this respect, + /// the effect is exactly as if each row had been removed individually. See + /// Descriptor::set_link_type() for details. + + size_t add_empty_row(size_t num_rows = 1); + void insert_empty_row(size_t row_ndx, size_t num_rows = 1); + size_t add_row_with_key(size_t col_ndx, util::Optional key); + size_t add_row_with_keys(size_t col_1_ndx, int64_t key1, size_t col_2_ndx, StringData key2); + void remove(size_t row_ndx); + void remove_recursive(size_t row_ndx); + void remove_last(); + void move_last_over(size_t row_ndx); + void clear(); + void swap_rows(size_t row_ndx_1, size_t row_ndx_2); + void move_row(size_t from_ndx, size_t to_ndx); + //@} + + /// Replaces all links to \a row_ndx with links to \a new_row_ndx. + /// + /// This operation is usually followed by Table::move_last_over() + /// as part of Table::set_int_unique() or Table::set_string_unique() + /// or Table::set_null_unique() detecting a collision. + /// + /// \sa Table::move_last_over() + /// \sa Table::set_int_unique() + /// \sa Table::set_string_unique() + /// \sa Table::set_null_unique() + void merge_rows(size_t row_ndx, size_t new_row_ndx); + + //@{ + + /// Get cell values. + /// Will assert if the requested type does not match the column type. + /// + /// When fetching from a nullable column and the value is null, a default + /// value will be returned, except for object like types (StringData, + /// BinaryData, Timestamp) which have support for storing nulls. In that + /// case, call the `is_null()` method on the returned object to check + /// whether the stored value was null. If nullability matters and returning + /// a default value is unacceptable, check Table::is_null() before getting a + /// cell value. + /// + /// \sa Table::is_nullable(size_t col_ndx) + /// \sa Table::is_null(size_t col_ndx, size_t row_ndx) + /// \sa StringData::is_null() + int64_t get_int(size_t column_ndx, size_t row_ndx) const noexcept; + bool get_bool(size_t column_ndx, size_t row_ndx) const noexcept; + OldDateTime get_olddatetime(size_t column_ndx, size_t row_ndx) const noexcept; + float get_float(size_t column_ndx, size_t row_ndx) const noexcept; + double get_double(size_t column_ndx, size_t row_ndx) const noexcept; + StringData get_string(size_t column_ndx, size_t row_ndx) const noexcept; + BinaryData get_binary(size_t column_ndx, size_t row_ndx) const noexcept; + BinaryIterator get_binary_iterator(size_t column_ndx, size_t row_ndx) const noexcept; + Mixed get_mixed(size_t column_ndx, size_t row_ndx) const noexcept; + DataType get_mixed_type(size_t column_ndx, size_t row_ndx) const noexcept; + Timestamp get_timestamp(size_t column_ndx, size_t row_ndx) const noexcept; + + //@} + + /// Return data from position 'pos' and onwards. If the blob is distributed + /// across multiple arrays, you will only get data from one array. 'pos' + /// will be updated to be an index to next available data. It will be 0 + /// if no more data. + BinaryData get_binary_at(size_t col_ndx, size_t ndx, size_t& pos) const noexcept; + + template + T get(size_t c, size_t r) const noexcept; + + size_t get_link(size_t column_ndx, size_t row_ndx) const noexcept; + bool is_null_link(size_t column_ndx, size_t row_ndx) const noexcept; + LinkViewRef get_linklist(size_t column_ndx, size_t row_ndx); + ConstLinkViewRef get_linklist(size_t column_ndx, size_t row_ndx) const; + size_t get_link_count(size_t column_ndx, size_t row_ndx) const noexcept; + bool linklist_is_empty(size_t column_ndx, size_t row_ndx) const noexcept; + bool is_null(size_t column_ndx, size_t row_ndx) const noexcept; + + TableRef get_link_target(size_t column_ndx) noexcept; + ConstTableRef get_link_target(size_t column_ndx) const noexcept; + + //@{ + + /// Set cell values. + /// + /// It is an error to specify a column index, row index, or string position + /// that is out of range. + /// + /// The number of bytes in a string value must not exceed `max_string_size`, + /// and the number of bytes in a binary data value must not exceed + /// `max_binary_size`. String must also contain valid UTF-8 encodings. These + /// requirements also apply when modifying a string with insert_substring() + /// and remove_substring(), and for strings in a mixed columnt. Passing, or + /// producing an oversized string or binary data value will cause an + /// exception to be thrown. + /// + /// The "unique" variants (set_int_unique(), set_string_unique(), set_null_unique()) + /// are intended to be used in the implementation of primary key support. They + /// check if the given column already contains one or more values that are + /// equal to \a value, and if there are conflicts, it calls + /// Table::merge_rows() for the row_ndx to be replaced by the + /// existing row, followed by a Table::move_last_over() of row_ndx. The + /// return value is always a row index of a row that contains \a value in + /// the specified column, possibly different from \a row_ndx if a conflict + /// occurred. Users intending to implement primary keys must therefore + /// manually check for duplicates if they want to raise an error instead. + /// + /// NOTE: It is an error to call either function after adding elements to a + /// linklist in the object. In general, calling set_int_unique() or + /// set_string_unique() or set_null_unique() should be the first thing that + /// happens after creating a row. These limitations are imposed by limitations + /// in the Realm Object Server and may be relaxed in the future. A violation of + /// these rules results in a LogicError being thrown. + /// + /// add_int() adds a 64-bit signed integer to the current value of the + /// cell. If the addition would cause signed integer overflow or + /// underflow, the addition "wraps around" with semantics similar to + /// unsigned integer arithmetic, such that Table::max_integer + 1 == + /// Table::min_integer and Table::min_integer - 1 == Table::max_integer. + /// Note that the wrapping is platform-independent (all platforms wrap in + /// the same way regardless of integer representation). If the existing + /// value in the cell is null, a LogicError exception is thrown. + /// + /// insert_substring() inserts the specified string into the currently + /// stored string at the specified position. The position must be less than + /// or equal to the size of the currently stored string. + /// + /// remove_substring() removes the specified byte range from the currently + /// stored string. The beginning of the range (\a pos) must be less than or + /// equal to the size of the currently stored string. If the specified range + /// extends beyond the end of the currently stored string, it will be + /// silently clamped. + /// + /// String level modifications performed via insert_substring() and + /// remove_substring() are mergable and subject to operational + /// transformation. That is, the effect of two causally unrelated + /// modifications will in general both be retained during synchronization. + + static const size_t max_string_size = 0xFFFFF8 - Array::header_size - 1; + static const size_t max_binary_size = 0xFFFFF8 - Array::header_size; + + // FIXME: These limits should be chosen independently of the underlying + // platform's choice to define int64_t and independent of the integer + // representation. The current values only work for 2's complement, which is + // not guaranteed by the standard. + static constexpr int_fast64_t max_integer = std::numeric_limits::max(); + static constexpr int_fast64_t min_integer = std::numeric_limits::min(); + + template + void set(size_t c, size_t r, T value, bool is_default = false); + + template + size_t set_unique(size_t c, size_t r, T value); + + void set_int(size_t column_ndx, size_t row_ndx, int_fast64_t value, bool is_default = false); + size_t set_int_unique(size_t column_ndx, size_t row_ndx, int_fast64_t value); + void set_bool(size_t column_ndx, size_t row_ndx, bool value, bool is_default = false); + void set_olddatetime(size_t column_ndx, size_t row_ndx, OldDateTime value, bool is_default = false); + void set_timestamp(size_t column_ndx, size_t row_ndx, Timestamp value, bool is_default = false); + template + void set_enum(size_t column_ndx, size_t row_ndx, E value); + void set_float(size_t column_ndx, size_t row_ndx, float value, bool is_default = false); + void set_double(size_t column_ndx, size_t row_ndx, double value, bool is_default = false); + void set_string(size_t column_ndx, size_t row_ndx, StringData value, bool is_default = false); + size_t set_string_unique(size_t column_ndx, size_t row_ndx, StringData value); + void set_binary(size_t column_ndx, size_t row_ndx, BinaryData value, bool is_default = false); + void set_mixed(size_t column_ndx, size_t row_ndx, Mixed value, bool is_default = false); + void set_link(size_t column_ndx, size_t row_ndx, size_t target_row_ndx, bool is_default = false); + void nullify_link(size_t column_ndx, size_t row_ndx); + void set_null(size_t column_ndx, size_t row_ndx, bool is_default = false); + void set_null_unique(size_t col_ndx, size_t row_ndx); + + // Sync needs to store blobs bigger than 16 M. This function can be used for that. Data should be read + // out again using the get_binary_at() function. Should not be used for user data as normal get_binary() + // will just return null if the data is bigger than the limit. + void set_binary_big(size_t column_ndx, size_t row_ndx, BinaryData value, bool is_default = false); + + void add_int(size_t column_ndx, size_t row_ndx, int_fast64_t value); + + void insert_substring(size_t col_ndx, size_t row_ndx, size_t pos, StringData); + void remove_substring(size_t col_ndx, size_t row_ndx, size_t pos, size_t substring_size = realm::npos); + + //@} + + /// Assumes that the specified column is a subtable column (in + /// particular, not a mixed column) and that the specified table + /// has a spec that is compatible with that column, that is, the + /// number of columns must be the same, and corresponding columns + /// must have identical data types (as returned by + /// get_column_type()). + void set_subtable(size_t col_ndx, size_t row_ndx, const Table*); + void set_mixed_subtable(size_t col_ndx, size_t row_ndx, const Table*); + + + // Sub-tables (works on columns whose type is either 'subtable' or + // 'mixed', for a value in a mixed column that is not a subtable, + // get_subtable() returns null, get_subtable_size() returns zero, + // and clear_subtable() replaces the value with an empty table.) + // Currently, subtables of subtables are not supported. + TableRef get_subtable(size_t column_ndx, size_t row_ndx); + ConstTableRef get_subtable(size_t column_ndx, size_t row_ndx) const; + size_t get_subtable_size(size_t column_ndx, size_t row_ndx) const noexcept; + void clear_subtable(size_t column_ndx, size_t row_ndx); + + // Backlinks + size_t get_backlink_count(size_t row_ndx, bool only_strong_links = false) const noexcept; + size_t get_backlink_count(size_t row_ndx, const Table& origin, size_t origin_col_ndx) const noexcept; + size_t get_backlink(size_t row_ndx, const Table& origin, size_t origin_col_ndx, size_t backlink_ndx) const + noexcept; + + + //@{ + + /// If this accessor is attached to a subtable, then that subtable has a + /// parent table, and the subtable either resides in a column of type + /// `table` or of type `mixed` in that parent. In that case + /// get_parent_table() returns a reference to the accessor associated with + /// the parent, and get_parent_row_index() returns the index of the row in + /// which the subtable resides. In all other cases (free-standing and + /// group-level tables), get_parent_table() returns null and + /// get_parent_row_index() returns realm::npos. + /// + /// If this accessor is attached to a subtable, and \a column_ndx_out is + /// specified, then `*column_ndx_out` is set to the index of the column of + /// the parent table in which the subtable resides. If this accessor is not + /// attached to a subtable, then `*column_ndx_out` will retain its original + /// value upon return. + + TableRef get_parent_table(size_t* column_ndx_out = nullptr) noexcept; + ConstTableRef get_parent_table(size_t* column_ndx_out = nullptr) const noexcept; + size_t get_parent_row_index() const noexcept; + + //@} + + + /// Only group-level unordered tables can be used as origins or targets of + /// links. + bool is_group_level() const noexcept; + + /// If this table is a group-level table, then this function returns the + /// index of this table within the group. Otherwise it returns realm::npos. + size_t get_index_in_group() const noexcept; + + // Aggregate functions + size_t count_int(size_t column_ndx, int64_t value) const; + size_t count_string(size_t column_ndx, StringData value) const; + size_t count_float(size_t column_ndx, float value) const; + size_t count_double(size_t column_ndx, double value) const; + + int64_t sum_int(size_t column_ndx) const; + double sum_float(size_t column_ndx) const; + double sum_double(size_t column_ndx) const; + int64_t maximum_int(size_t column_ndx, size_t* return_ndx = nullptr) const; + float maximum_float(size_t column_ndx, size_t* return_ndx = nullptr) const; + double maximum_double(size_t column_ndx, size_t* return_ndx = nullptr) const; + OldDateTime maximum_olddatetime(size_t column_ndx, size_t* return_ndx = nullptr) const; + Timestamp maximum_timestamp(size_t column_ndx, size_t* return_ndx = nullptr) const; + int64_t minimum_int(size_t column_ndx, size_t* return_ndx = nullptr) const; + float minimum_float(size_t column_ndx, size_t* return_ndx = nullptr) const; + double minimum_double(size_t column_ndx, size_t* return_ndx = nullptr) const; + OldDateTime minimum_olddatetime(size_t column_ndx, size_t* return_ndx = nullptr) const; + Timestamp minimum_timestamp(size_t column_ndx, size_t* return_ndx = nullptr) const; + double average_int(size_t column_ndx, size_t* value_count = nullptr) const; + double average_float(size_t column_ndx, size_t* value_count = nullptr) const; + double average_double(size_t column_ndx, size_t* value_count = nullptr) const; + + // Searching + template + size_t find_first(size_t column_ndx, T value) const; + + size_t find_first_link(size_t target_row_index) const; + size_t find_first_int(size_t column_ndx, int64_t value) const; + size_t find_first_bool(size_t column_ndx, bool value) const; + size_t find_first_olddatetime(size_t column_ndx, OldDateTime value) const; + size_t find_first_timestamp(size_t column_ndx, Timestamp value) const; + size_t find_first_float(size_t column_ndx, float value) const; + size_t find_first_double(size_t column_ndx, double value) const; + size_t find_first_string(size_t column_ndx, StringData value) const; + size_t find_first_binary(size_t column_ndx, BinaryData value) const; + size_t find_first_null(size_t column_ndx) const; + + TableView find_all_link(size_t target_row_index); + ConstTableView find_all_link(size_t target_row_index) const; + TableView find_all_int(size_t column_ndx, int64_t value); + ConstTableView find_all_int(size_t column_ndx, int64_t value) const; + TableView find_all_bool(size_t column_ndx, bool value); + ConstTableView find_all_bool(size_t column_ndx, bool value) const; + TableView find_all_olddatetime(size_t column_ndx, OldDateTime value); + ConstTableView find_all_olddatetime(size_t column_ndx, OldDateTime value) const; + TableView find_all_float(size_t column_ndx, float value); + ConstTableView find_all_float(size_t column_ndx, float value) const; + TableView find_all_double(size_t column_ndx, double value); + ConstTableView find_all_double(size_t column_ndx, double value) const; + TableView find_all_string(size_t column_ndx, StringData value); + ConstTableView find_all_string(size_t column_ndx, StringData value) const; + TableView find_all_binary(size_t column_ndx, BinaryData value); + ConstTableView find_all_binary(size_t column_ndx, BinaryData value) const; + TableView find_all_null(size_t column_ndx); + ConstTableView find_all_null(size_t column_ndx) const; + + /// The following column types are supported: String, Integer, OldDateTime, Bool + TableView get_distinct_view(size_t column_ndx); + ConstTableView get_distinct_view(size_t column_ndx) const; + + TableView get_sorted_view(size_t column_ndx, bool ascending = true); + ConstTableView get_sorted_view(size_t column_ndx, bool ascending = true) const; + + TableView get_sorted_view(SortDescriptor order); + ConstTableView get_sorted_view(SortDescriptor order) const; + + TableView get_range_view(size_t begin, size_t end); + ConstTableView get_range_view(size_t begin, size_t end) const; + + TableView get_backlink_view(size_t row_ndx, Table* src_table, size_t src_col_ndx); + + + // Pivot / aggregate operation types. Experimental! Please do not document method publicly. + enum AggrType { + aggr_count, + aggr_sum, + aggr_avg, + aggr_min, + aggr_max, + }; + + // Simple pivot aggregate method. Experimental! Please do not document method publicly. + void aggregate(size_t group_by_column, size_t aggr_column, AggrType op, Table& result, + const IntegerColumn* viewrefs = nullptr) const; + + /// Report the current versioning counter for the table. The versioning counter is guaranteed to + /// change when the contents of the table changes after advance_read() or promote_to_write(), or + /// immediately after calls to methods which change the table. The term "change" means "change of + /// value": The storage layout of the table may change, for example due to optimization, but this + /// is not considered a change of a value. This means that you *cannot* use a non-changing version + /// count to indicate that object addresses (e.g. strings, binary data) remain the same. + /// The versioning counter *may* change (but is not required to do so) when another table linked + /// from this table, or linking to this table, is changed. The version counter *may* also change + /// without any apparent reason. + uint_fast64_t get_version_counter() const noexcept; + +private: + template + TableView find_all(size_t column_ndx, T value); + +public: + //@{ + /// Find the lower/upper bound according to a column that is + /// already sorted in ascending order. + /// + /// For an integer column at index 0, and an integer value '`v`', + /// lower_bound_int(0,v) returns the index '`l`' of the first row + /// such that `get_int(0,l) ≥ v`, and upper_bound_int(0,v) + /// returns the index '`u`' of the first row such that + /// `get_int(0,u) > v`. In both cases, if no such row is found, + /// the returned value is the number of rows in the table. + /// + /// 3 3 3 4 4 4 5 6 7 9 9 9 + /// ^ ^ ^ ^ ^ + /// | | | | | + /// | | | | -- Lower and upper bound of 15 + /// | | | | + /// | | | -- Lower and upper bound of 8 + /// | | | + /// | | -- Upper bound of 4 + /// | | + /// | -- Lower bound of 4 + /// | + /// -- Lower and upper bound of 1 + /// + /// These functions are similar to std::lower_bound() and + /// std::upper_bound(). + /// + /// The string versions assume that the column is sorted according + /// to StringData::operator<(). + size_t lower_bound_int(size_t column_ndx, int64_t value) const noexcept; + size_t upper_bound_int(size_t column_ndx, int64_t value) const noexcept; + size_t lower_bound_bool(size_t column_ndx, bool value) const noexcept; + size_t upper_bound_bool(size_t column_ndx, bool value) const noexcept; + size_t lower_bound_float(size_t column_ndx, float value) const noexcept; + size_t upper_bound_float(size_t column_ndx, float value) const noexcept; + size_t lower_bound_double(size_t column_ndx, double value) const noexcept; + size_t upper_bound_double(size_t column_ndx, double value) const noexcept; + size_t lower_bound_string(size_t column_ndx, StringData value) const noexcept; + size_t upper_bound_string(size_t column_ndx, StringData value) const noexcept; + //@} + + // Queries + // Using where(tv) is the new method to perform queries on TableView. The 'tv' can have any order; it does not + // need to be sorted, and, resulting view retains its order. + Query where(TableViewBase* tv = nullptr) + { + return Query(*this, tv); + } + + // FIXME: We need a ConstQuery class or runtime check against modifications in read transaction. + Query where(TableViewBase* tv = nullptr) const + { + return Query(*this, tv); + } + + // Perform queries on a LinkView. The returned Query holds a reference to lv. + Query where(const LinkViewRef& lv) + { + return Query(*this, lv); + } + + //@{ + /// WARNING: The link() and backlink() methods will alter a state on the Table object and return a reference to itself. + /// Be aware if assigning the return value of link() to a variable; this might be an error! + + /// This is an error: + + /// Table& cats = owners->link(1); + /// auto& dogs = owners->link(2); + + /// Query q = person_table->where() + /// .and_query(cats.column(5).equal("Fido")) + /// .Or() + /// .and_query(dogs.column(6).equal("Meowth")); + + /// Instead, do this: + + /// Query q = owners->where() + /// .and_query(person_table->link(1).column(5).equal("Fido")) + /// .Or() + /// .and_query(person_table->link(2).column(6).equal("Meowth")); + + /// The two calls to link() in the errorneous example will append the two values 0 and 1 to an internal vector in the + /// owners table, and we end up with three references to that same table: owners, cats and dogs. They are all the same + /// table, its vector has the values {0, 1}, so a query would not make any sense. + Table& link(size_t link_column); + Table& backlink(const Table& origin, size_t origin_col_ndx); + //@} + + // Optimizing. enforce == true will enforce enumeration of all string columns; + // enforce == false will auto-evaluate if they should be enumerated or not + void optimize(bool enforce = false); + + /// Write this table (or a slice of this table) to the specified + /// output stream. + /// + /// The output will have the same format as any other Realm + /// database file, such as those produced by Group::write(). In + /// this case, however, the resulting database file will contain + /// exactly one table, and that table will contain only the + /// specified slice of the source table (this table). + /// + /// The new table will always have the same dynamic type (see + /// Descriptor) as the source table (this table), and unless it is + /// overridden (\a override_table_name), the new table will have + /// the same name as the source table (see get_name()). Indexes + /// (see add_search_index()) will not be carried over to the new + /// table. + /// + /// \param out The destination output stream buffer. + /// + /// \param offset Index of first row to include (if `slice_size > + /// 0`). Must be less than, or equal to size(). + /// + /// \param slice_size Number of rows to include. May be zero. If + /// `slice_size > size() - offset`, then the effective size of + /// the written slice will be `size() - offset`. + /// + /// \param override_table_name Custom name to write out instead of + /// the actual table name. + /// + /// \throw std::out_of_range If `offset > size()`. + /// + /// FIXME: While this function does provided a maximally efficient + /// way of serializing part of a table, it offers little in terms + /// of general utility. This is unfortunate, because it pulls + /// quite a large amount of code into the core library to support + /// it. + void write(std::ostream& out, size_t offset = 0, size_t slice_size = npos, + StringData override_table_name = StringData()) const; + + // Conversion + void to_json(std::ostream& out, size_t link_depth = 0, + std::map* renames = nullptr) const; + void to_string(std::ostream& out, size_t limit = 500) const; + void row_to_string(size_t row_ndx, std::ostream& out) const; + + // Get a reference to this table + TableRef get_table_ref() + { + return TableRef(this); + } + ConstTableRef get_table_ref() const + { + return ConstTableRef(this); + } + + /// \brief Compare two tables for equality. + /// + /// Two tables are equal if they have equal descriptors + /// (`Descriptor::operator==()`) and equal contents. Equal descriptors imply + /// that the two tables have the same columns in the same order. Equal + /// contents means that the two tables must have the same number of rows, + /// and that for each row index, the two rows must have the same values in + /// each column. + /// + /// In mixed columns, both the value types and the values are required to be + /// equal. + /// + /// For a particular row and column, if the two values are themselves tables + /// (subtable and mixed columns) value equality implies a recursive + /// invocation of `Table::operator==()`. + bool operator==(const Table&) const; + + /// \brief Compare two tables for inequality. + /// + /// See operator==(). + bool operator!=(const Table& t) const; + + /// A subtable in a column of type 'table' (which shares descriptor with + /// other subtables in the same column) is initially in a degenerate state + /// where it takes up a minimal amout of space. This function returns true + /// if, and only if the table accessor is attached to such a subtable. This + /// function is mainly intended for debugging purposes. + bool is_degenerate() const; + + /// Compute the sum of the sizes in number of bytes of all the array nodes + /// that currently make up this table. See also + /// Group::compute_aggregate_byte_size(). + /// + /// If this table accessor is the detached state, this function returns + /// zero. + size_t compute_aggregated_byte_size() const noexcept; + + // Debug + void verify() const; +#ifdef REALM_DEBUG + void to_dot(std::ostream&, StringData title = StringData()) const; + void print() const; + MemStats stats() const; + void dump_node_structure() const; // To std::cerr (for GDB) + void dump_node_structure(std::ostream&, int level) const; +#endif + + class Parent; + using HandoverPatch = TableHandoverPatch; + static void generate_patch(const Table* ref, std::unique_ptr& patch); + static TableRef create_from_and_consume_patch(std::unique_ptr& patch, Group& group); + +protected: + /// Get a pointer to the accessor of the specified subtable. The + /// accessor will be created if it does not already exist. + /// + /// The returned table pointer must **always** end up being + /// wrapped in some instantiation of BasicTableRef<>. + TableRef get_subtable_tableref(size_t col_ndx, size_t row_ndx); + + /// See non-const get_subtable_tableref(). + ConstTableRef get_subtable_tableref(size_t col_ndx, size_t row_ndx) const; + + /// Compare the rows of two tables under the assumption that the two tables + /// have the same number of columns, and the same data type at each column + /// index (as expressed through the DataType enum). + bool compare_rows(const Table&) const; + + void set_into_mixed(Table* parent, size_t col_ndx, size_t row_ndx) const; + + void check_lists_are_empty(size_t row_ndx) const; + +private: + class SliceWriter; + + // Number of rows in this table + size_t m_size; + + // Underlying array structure. `m_top` is in use only for root tables; that + // is, for tables with independent descriptor. `m_columns` contains a ref + // for each column and search index in order of the columns. A search index + // ref always occurs immediately after the ref of the column to which the + // search index belongs. + // + // A subtable column (a column of type `type_table`) is essentially just a + // column of 'refs' pointing to the root node of each subtable. + // + // To save space in the database file, a subtable in such a column always + // starts out in a degenerate form where nothing is allocated on its behalf, + // and a null 'ref' is stored in the corresponding slot of the column. A + // subtable remains in this degenerate state until the first row is added to + // the subtable. + // + // For this scheme to work, it must be (and is) possible to create a table + // accessor that refers to a degenerate subtable. A table accessor (instance + // of `Table`) refers to a degenerate subtable if, and only if `m_columns` + // is unattached. + // + // FIXME: The fact that `m_columns` may be detached means that many + // functions (even non-modifying functions) need to check for that before + // accessing the contents of the table. This incurs a runtime + // overhead. Consider whether this overhead can be eliminated by having + // `Table::m_columns` always attached to something, and then detect the + // degenerate state in a different way. + Array m_top; + Array m_columns; // 2nd slot in m_top (for root tables) + + // Management class for the spec object. Only if the table has an independent + // spec, the spec object should be deleted when the table object is deleted. + // If the table has a shared spec, the spec object is managed by the spec object + // of the containing table. + class SpecPtr { + public: + ~SpecPtr() + { + optionally_delete(); + } + void manage(Spec* ptr) + { + optionally_delete(); + m_p = ptr; + m_is_managed = true; + } + void detach() + { + if (m_is_managed) { + m_p->detach(); + } + } + SpecPtr& operator=(Spec* ptr) + { + optionally_delete(); + m_p = ptr; + m_is_managed = false; + return *this; + } + Spec* operator->() const + { + return m_p; + } + Spec* get() const + { + return m_p; + } + Spec& operator*() const + { + return *m_p; + } + operator bool() const + { + return m_p != nullptr; + } + bool is_managed() const + { + return m_is_managed; + } + + private: + Spec* m_p = nullptr; + bool m_is_managed = false; + + void optionally_delete() + { + if (m_is_managed) { + delete m_p; + } + } + }; + + SpecPtr m_spec; // 1st slot in m_top (for root tables) + + // Is guaranteed to be empty for a detached accessor. Otherwise it is empty + // when the table accessor is attached to a degenerate subtable (unattached + // `m_columns`), otherwise it contains precisely one column accessor for + // each column in the table, in order. + // + // In some cases an entry may be null. This is currently possible only in + // connection with Group::advance_transact(), but it means that several + // member functions must be prepared to handle these null entries; in + // particular, detach(), ~Table(), functions called on behalf of detach() + // and ~Table(), and functiones called on behalf of + // Group::advance_transact(). + typedef std::vector column_accessors; + column_accessors m_cols; + + mutable std::atomic m_ref_count; + + // If this table is a root table (has independent descriptor), + // then Table::m_descriptor refers to the accessor of its + // descriptor when, and only when the descriptor accessor + // exists. This is used to ensure that at most one descriptor + // accessor exists for each underlying descriptor at any given + // point in time. Subdescriptors are kept unique by means of a + // registry in the parent descriptor. Table::m_descriptor is + // always null for tables with shared descriptor. + mutable std::weak_ptr m_descriptor; + + // Table view instances + // Access needs to be protected by m_accessor_mutex + typedef std::vector views; + mutable views m_views; + + // Points to first bound row accessor, or is null if there are none. + mutable RowBase* m_row_accessors = nullptr; + + // Mutex which must be locked any time the row accessor chain or m_views is used + mutable util::Mutex m_accessor_mutex; + + // Used for queries: Items are added with link() method during buildup of query + mutable std::vector m_link_chain; + + /// Used only in connection with Group::advance_transact() and + /// Table::refresh_accessor_tree(). + mutable bool m_mark; + + mutable uint_fast64_t m_version; + + void erase_row(size_t row_ndx, bool is_move_last_over); + void batch_erase_rows(const IntegerColumn& row_indexes, bool is_move_last_over); + void do_remove(size_t row_ndx, bool broken_reciprocal_backlinks); + void do_move_last_over(size_t row_ndx, bool broken_reciprocal_backlinks); + void do_swap_rows(size_t row_ndx_1, size_t row_ndx_2); + void do_move_row(size_t from_ndx, size_t to_ndx); + void do_merge_rows(size_t row_ndx, size_t new_row_ndx); + void do_clear(bool broken_reciprocal_backlinks); + size_t do_set_link(size_t col_ndx, size_t row_ndx, size_t target_row_ndx); + template + size_t do_find_unique(ColType& col, size_t ndx, T&& value, bool& conflict); + template + size_t do_set_unique_null(ColType& col, size_t ndx, bool& conflict); + template + size_t do_set_unique(ColType& column, size_t row_ndx, T&& value, bool& conflict); + + void _add_search_index(size_t column_ndx); + void _remove_search_index(size_t column_ndx); + + void rebuild_search_index(size_t current_file_format_version); + + // Upgrades OldDateTime columns to Timestamp columns + void upgrade_olddatetime(); + + // Indicate that the current global state version has been "observed". Until this + // happens, bumping of the global version counter can be bypassed, as any query + // checking for a version change will see the older version change anyways. + // Also returns the table-local version. + uint64_t observe_version() const noexcept; + + /// Update the version of this table and all tables which have links to it. + /// This causes all views referring to those tables to go out of sync, so that + /// calls to sync_if_needed() will bring the view up to date by reexecuting the + /// query. + /// + /// \param bump_global chooses whether the global versioning counter must be + /// bumped first as part of the update. This is the normal mode of operation, + /// when a change is made to the table. When calling recursively (following links + /// or going to the parent table), the parameter should be set to false to correctly + /// prune traversal. + void bump_version(bool bump_global = true) const noexcept; + + /// Disable copying assignment. + /// + /// It could easily be implemented by calling assign(), but the + /// non-checking nature of the low-level dynamically typed API + /// makes it too risky to offer this feature as an + /// operator. + /// + /// FIXME: assign() has not yet been implemented, but the + /// intention is that it will copy the rows of the argument table + /// into this table after clearing the original contents, and for + /// target tables without a shared spec, it would also copy the + /// spec. For target tables with shared spec, it would be an error + /// to pass an argument table with an incompatible spec, but + /// assign() would not check for spec compatibility. This would + /// make it ideal as a basis for implementing operator=() for + /// typed tables. + Table& operator=(const Table&) = delete; + + /// Used when constructing an accessor whose lifetime is going to be managed + /// by reference counting. The lifetime of accessors of free-standing tables + /// allocated on the stack by the application is not managed by reference + /// counting, so that is a case where this tag must **not** be specified. + class ref_count_tag { + }; + + /// Create an uninitialized accessor whose lifetime is managed by reference + /// counting. + Table(ref_count_tag, Allocator&); + + void init(ref_type top_ref, ArrayParent*, size_t ndx_in_parent, bool skip_create_column_accessors = false); + void init(Spec* shared_spec, ArrayParent* parent_column, size_t parent_row_ndx); + + static void do_insert_column(Descriptor&, size_t col_ndx, DataType type, StringData name, + LinkTargetInfo& link_target_info, bool nullable = false); + static void do_insert_column_unless_exists(Descriptor&, size_t col_ndx, DataType type, StringData name, + LinkTargetInfo& link, bool nullable = false, + bool* was_inserted = nullptr); + static void do_erase_column(Descriptor&, size_t col_ndx); + static void do_rename_column(Descriptor&, size_t col_ndx, StringData name); + + static void do_add_search_index(Descriptor&, size_t col_ndx); + static void do_remove_search_index(Descriptor&, size_t col_ndx); + + struct InsertSubtableColumns; + struct EraseSubtableColumns; + struct RenameSubtableColumns; + + void insert_root_column(size_t col_ndx, DataType type, StringData name, LinkTargetInfo& link_target, + bool nullable = false); + void erase_root_column(size_t col_ndx); + void do_insert_root_column(size_t col_ndx, ColumnType, StringData name, bool nullable = false); + void do_erase_root_column(size_t col_ndx); + void do_set_link_type(size_t col_ndx, LinkType); + void insert_backlink_column(size_t origin_table_ndx, size_t origin_col_ndx, size_t backlink_col_ndx); + void erase_backlink_column(size_t origin_table_ndx, size_t origin_col_ndx); + void update_link_target_tables(size_t old_col_ndx_begin, size_t new_col_ndx_begin); + void update_link_target_tables_after_column_move(size_t moved_from, size_t moved_to); + + struct SubtableUpdater { + virtual void update(const SubtableColumn&, Array& subcolumns) = 0; + virtual void update_accessor(Table&) = 0; + virtual ~SubtableUpdater() + { + } + }; + static void update_subtables(Descriptor&, SubtableUpdater*); + void update_subtables(const size_t* col_path_begin, const size_t* col_path_end, SubtableUpdater*); + + struct AccessorUpdater { + virtual void update(Table&) = 0; + virtual void update_parent(Table&) = 0; + virtual ~AccessorUpdater() + { + } + }; + void update_accessors(const size_t* col_path_begin, const size_t* col_path_end, AccessorUpdater&); + + void create_degen_subtab_columns(); + ColumnBase* create_column_accessor(ColumnType, size_t col_ndx, size_t ndx_in_parent); + void destroy_column_accessors() noexcept; + + /// Called in the context of Group::commit() to ensure that + /// attached table accessors stay valid across a commit. Please + /// note that this works only for non-transactional commits. Table + /// accessors obtained during a transaction are always detached + /// when the transaction ends. + void update_from_parent(size_t old_baseline) noexcept; + + // Support function for conversions + void to_string_header(std::ostream& out, std::vector& widths) const; + void to_string_row(size_t row_ndx, std::ostream& out, const std::vector& widths) const; + + // recursive methods called by to_json, to follow links + void to_json(std::ostream& out, size_t link_depth, std::map& renames, + std::vector& followed) const; + void to_json_row(size_t row_ndx, std::ostream& out, size_t link_depth, + std::map& renames, std::vector& followed) const; + void to_json_row(size_t row_ndx, std::ostream& out, size_t link_depth = 0, + std::map* renames = nullptr) const; + + // Detach accessor from underlying table. Caller must ensure that + // a reference count exists upon return, for example by obtaining + // an extra reference count before the call. + // + // This function puts this table accessor into the detached + // state. This detaches it from the underlying structure of array + // nodes. It also recursively detaches accessors for subtables, + // and the type descriptor accessor. When this function returns, + // is_attached() will return false. + // + // This function may be called for a table accessor that is + // already in the detached state (idempotency). + // + // It is also valid to call this function for a table accessor + // that has not yet been detached, but whose underlying structure + // of arrays have changed in an unpredictable/unknown way. This + // kind of change generally happens when a modifying table + // operation fails, and also when one transaction is ended and a + // new one is started. + void detach() noexcept; + + /// Detach and remove all attached row, link list, and subtable + /// accessors. This function does not discard the descriptor accessor, if + /// any, and it does not discard column accessors either. + void discard_child_accessors() noexcept; + + void discard_row_accessors() noexcept; + + // Detach the type descriptor accessor if it exists. + void discard_desc_accessor() noexcept; + + void bind_ptr() const noexcept; + void unbind_ptr() const noexcept; + + void register_view(const TableViewBase* view); + void unregister_view(const TableViewBase* view) noexcept; + void move_registered_view(const TableViewBase* old_addr, const TableViewBase* new_addr) noexcept; + void discard_views() noexcept; + + void register_row_accessor(RowBase*) const noexcept; + void unregister_row_accessor(RowBase*) const noexcept; + void do_unregister_row_accessor(RowBase*) const noexcept; + + class UnbindGuard; + + ColumnType get_real_column_type(size_t column_ndx) const noexcept; + + /// If this table is a group-level table, the parent group is returned, + /// otherwise null is returned. + Group* get_parent_group() const noexcept; + + const ColumnBase& get_column_base(size_t column_ndx) const noexcept; + ColumnBase& get_column_base(size_t column_ndx); + + const ColumnBaseWithIndex& get_column_base_indexed(size_t ndx) const noexcept; + ColumnBaseWithIndex& get_column_base_indexed(size_t ndx); + + template + T& get_column(size_t ndx); + + template + const T& get_column(size_t ndx) const noexcept; + + IntegerColumn& get_column(size_t column_ndx); + const IntegerColumn& get_column(size_t column_ndx) const noexcept; + IntNullColumn& get_column_int_null(size_t column_ndx); + const IntNullColumn& get_column_int_null(size_t column_ndx) const noexcept; + FloatColumn& get_column_float(size_t column_ndx); + const FloatColumn& get_column_float(size_t column_ndx) const noexcept; + DoubleColumn& get_column_double(size_t column_ndx); + const DoubleColumn& get_column_double(size_t column_ndx) const noexcept; + StringColumn& get_column_string(size_t column_ndx); + const StringColumn& get_column_string(size_t column_ndx) const noexcept; + BinaryColumn& get_column_binary(size_t column_ndx); + const BinaryColumn& get_column_binary(size_t column_ndx) const noexcept; + StringEnumColumn& get_column_string_enum(size_t column_ndx); + const StringEnumColumn& get_column_string_enum(size_t column_ndx) const noexcept; + SubtableColumn& get_column_table(size_t column_ndx); + const SubtableColumn& get_column_table(size_t column_ndx) const noexcept; + MixedColumn& get_column_mixed(size_t column_ndx); + const MixedColumn& get_column_mixed(size_t column_ndx) const noexcept; + TimestampColumn& get_column_timestamp(size_t column_ndx); + const TimestampColumn& get_column_timestamp(size_t column_ndx) const noexcept; + const LinkColumnBase& get_column_link_base(size_t ndx) const noexcept; + LinkColumnBase& get_column_link_base(size_t ndx); + const LinkColumn& get_column_link(size_t ndx) const noexcept; + LinkColumn& get_column_link(size_t ndx); + const LinkListColumn& get_column_link_list(size_t ndx) const noexcept; + LinkListColumn& get_column_link_list(size_t ndx); + const BacklinkColumn& get_column_backlink(size_t ndx) const noexcept; + BacklinkColumn& get_column_backlink(size_t ndx); + + void verify_column(size_t col_ndx, const ColumnBase* col) const; + + void instantiate_before_change(); + void validate_column_type(const ColumnBase& col, ColumnType expected_type, size_t ndx) const; + + static size_t get_size_from_ref(ref_type top_ref, Allocator&) noexcept; + static size_t get_size_from_ref(ref_type spec_ref, ref_type columns_ref, Allocator&) noexcept; + + const Table* get_parent_table_ptr(size_t* column_ndx_out = nullptr) const noexcept; + Table* get_parent_table_ptr(size_t* column_ndx_out = nullptr) noexcept; + + /// Create an empty table with independent spec and return just + /// the reference to the underlying memory. + static ref_type create_empty_table(Allocator&); + + /// Create a column of the specified type, fill it with the + /// specified number of default values, and return just the + /// reference to the underlying memory. + static ref_type create_column(ColumnType column_type, size_t num_default_values, bool nullable, Allocator&); + + /// Construct a copy of the columns array of this table using the + /// specified allocator and return just the ref to that array. + /// + /// In the clone, no string column will be of the enumeration + /// type. + ref_type clone_columns(Allocator&) const; + + /// Construct a complete copy of this table (including its spec) + /// using the specified allocator and return just the ref to the + /// new top array. + ref_type clone(Allocator&) const; + + /// True for `col_type_Link` and `col_type_LinkList`. + static bool is_link_type(ColumnType) noexcept; + + void connect_opposite_link_columns(size_t link_col_ndx, Table& target_table, size_t backlink_col_ndx) noexcept; + + //@{ + + /// Cascading removal of strong links. + /// + /// cascade_break_backlinks_to() removes all backlinks pointing to the row + /// at \a row_ndx. Additionally, if this causes the number of **strong** + /// backlinks originating from a particular opposite row (target row of + /// corresponding forward link) to drop to zero, and that row is not already + /// in \a state.rows, then that row is added to \a state.rows, and + /// cascade_break_backlinks_to() is called recursively for it. This + /// operation is the first half of the cascading row removal operation. The + /// second half is performed by passing the resulting contents of \a + /// state.rows to remove_backlink_broken_rows(). + /// + /// Operations that trigger cascading row removal due to explicit removal of + /// one or more rows (the *initiating rows*), should add those rows to \a + /// rows initially, and then call cascade_break_backlinks_to() once for each + /// of them in turn. This is opposed to carrying out the explicit row + /// removals independently, which is also possible, but does require that + /// any initiating rows, that end up in \a state.rows due to link cycles, + /// are removed before passing \a state.rows to + /// remove_backlink_broken_rows(). In the case of clear(), where all rows of + /// a table are explicitly removed, it is better to use + /// cascade_break_backlinks_to_all_rows(), and then carry out the table + /// clearing as an independent step. For operations that trigger cascading + /// row removal for other reasons than explicit row removal, \a state.rows + /// must be empty initially, but cascade_break_backlinks_to() must still be + /// called for each of the initiating rows. + /// + /// When the last non-recursive invocation of cascade_break_backlinks_to() + /// returns, all forward links originating from a row in \a state.rows have + /// had their reciprocal backlinks removed, so remove_backlink_broken_rows() + /// does not perform reciprocal backlink removal at all. Additionally, all + /// remaining backlinks originating from rows in \a state.rows are + /// guaranteed to point to rows that are **not** in \a state.rows. This is + /// true because any backlink that was pointing to a row in \a state.rows + /// has been removed by one of the invocations of + /// cascade_break_backlinks_to(). The set of forward links, that correspond + /// to these remaining backlinks, is precisely the set of forward links that + /// need to be removed/nullified by remove_backlink_broken_rows(), which it + /// does by way of reciprocal forward link removal. Note also, that while + /// all the rows in \a state.rows can have remaining **weak** backlinks + /// originating from them, only the initiating rows in \a state.rows can + /// have remaining **strong** backlinks originating from them. This is true + /// because a non-initiating row is added to \a state.rows only when the + /// last backlink originating from it is lost. + /// + /// Each row removal is replicated individually (as opposed to one + /// replication instruction for the entire cascading operation). This is + /// done because it provides an easy way for Group::advance_transact() to + /// know which tables are affected by the cascade. Note that this has + /// several important consequences: First of all, the replication log + /// receiver must execute the row removal instructions in a non-cascading + /// fashion, meaning that there will be an asymmetry between the two sides + /// in how the effect of the cascade is brought about. While this is fine + /// for simple 1-to-1 replication, it may end up interfering badly with + /// *transaction merging*, when that feature is introduced. Imagine for + /// example that the cascade initiating operation gets canceled during + /// conflict resolution, but some, or all of the induced row removals get to + /// stay. That would break causal consistency. It is important, however, for + /// transaction merging that the cascaded row removals are explicitly + /// mentioned in the replication log, such that they can be used to adjust + /// row indexes during the *operational transform*. + /// + /// cascade_break_backlinks_to_all_rows() has the same affect as calling + /// cascade_break_backlinks_to() once for each row in the table. When + /// calling this function, \a state.stop_on_table must be set to the origin + /// table (origin table of corresponding forward links), and \a + /// state.stop_on_link_list_column must be null. + /// + /// It is immaterial which table remove_backlink_broken_rows() is called on, + /// as long it that table is in the same group as the removed rows. + + void cascade_break_backlinks_to(size_t row_ndx, CascadeState& state); + void cascade_break_backlinks_to_all_rows(CascadeState& state); + void remove_backlink_broken_rows(const CascadeState&); + + //@} + + /// Used by query. Follows chain of link columns and returns final target table + const Table* get_link_chain_target(const std::vector& link_chain) const; + + /// Remove the specified row by the 'move last over' method. + void do_move_last_over(size_t row_ndx); + + // Precondition: 1 <= end - begin + size_t* record_subtable_path(size_t* begin, size_t* end) const noexcept; + + /// Check if an accessor exists for the specified subtable. If it does, + /// return a pointer to it, otherwise return null. This function assumes + /// that the specified column index in a valid index into `m_cols` but does + /// not otherwise assume more than minimal accessor consistency (see + /// AccessorConsistencyLevels.) + TableRef get_subtable_accessor(size_t col_ndx, size_t row_ndx) noexcept; + + /// Unless the column accessor is missing, this function returns the + /// accessor for the target table of the specified link-type column. The + /// column accessor is said to be missing if `m_cols[col_ndx]` is null, and + /// this can happen only during certain operations such as the updating of + /// the accessor tree when a read transaction is advanced. Note that for + /// link type columns, the target table accessor exists when, and only when + /// the origin table accessor exists. This function assumes that the + /// specified column index in a valid index into `m_cols` and that the + /// column is a link-type column. Beyond that, it assume nothing more than + /// minimal accessor consistency (see AccessorConsistencyLevels.) + Table* get_link_target_table_accessor(size_t col_ndx) noexcept; + + void discard_subtable_accessor(size_t col_ndx, size_t row_ndx) noexcept; + + void adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept; + void adj_acc_erase_row(size_t row_ndx) noexcept; + void adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; + void adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept; + void adj_acc_merge_rows(size_t old_row_ndx, size_t new_row_ndx) noexcept; + + /// Adjust this table accessor and its subordinates after move_last_over() + /// (or its inverse). + /// + /// First, any row, subtable, or link list accessors registered as being at + /// \a to_row_ndx will be detached, as that row is assumed to have been + /// replaced. Next, any row, subtable, or link list accessors registered as + /// being at \a from_row_ndx, will be reregistered as being at \a + /// to_row_ndx, as the row at \a from_row_ndx is assumed to have been moved + /// to \a to_row_ndx. + /// + /// Crucially, if \a to_row_ndx is equal to \a from_row_ndx, then row, + /// subtable, or link list accessors at that row are **still detached**. + /// + /// Additionally, this function causes all link-adjacent tables to be marked + /// (dirty). Two tables are link-adjacent if one is the target table of a + /// link column of the other table. Note that this marking follows these + /// relations in both directions, but only to a depth of one. + /// + /// When this function is used in connection with move_last_over(), set \a + /// to_row_ndx to the index of the row to be removed, and set \a + /// from_row_ndx to the index of the last row in the table. As mentioned + /// earlier, this function can also be used in connection with the **inverse + /// of** move_last_over(), which is an operation that vacates a row by + /// moving its contents into a new last row of the table. In that case, set + /// \a to_row_ndx to one plus the index of the last row in the table, and + /// set \a from_row_ndx to the index of the row to be vacated. + /// + /// This function is used as part of Table::refresh_accessor_tree() to + /// promote the state of the accessors from Minimal Consistency into + /// Structural Correspondence, so it must be able to execute without + /// accessing the underlying array nodes. + void adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; + + void adj_acc_clear_root_table() noexcept; + void adj_acc_clear_nonroot_table() noexcept; + void adj_row_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept; + void adj_row_acc_erase_row(size_t row_ndx) noexcept; + void adj_row_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; + void adj_row_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept; + void adj_row_acc_merge_rows(size_t old_row_ndx, size_t new_row_ndx) noexcept; + + /// Called by adj_acc_move_over() to adjust row accessors. + void adj_row_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; + + void adj_insert_column(size_t col_ndx); + void adj_erase_column(size_t col_ndx) noexcept; + + bool is_marked() const noexcept; + void mark() noexcept; + void unmark() noexcept; + void recursive_mark() noexcept; + void mark_link_target_tables(size_t col_ndx_begin) noexcept; + void mark_opposite_link_tables() noexcept; + + Replication* get_repl() noexcept; + + void set_ndx_in_parent(size_t ndx_in_parent) noexcept; + + /// Refresh the part of the accessor tree that is rooted at this + /// table. Subtable accessors will be refreshed only if they are marked + /// (Table::m_mark), and this applies recursively to subtables of + /// subtables. All refreshed table accessors (including this one) will be + /// unmarked upon return. + /// + /// The following conditions are necessary and sufficient for the proper + /// operation of this function: + /// + /// - This table must be a group-level table, or a subtable. It must not be + /// a free-standing table (because a free-standing table has no parent). + /// + /// - The `index in parent` property is correct. The `index in parent` + /// property of the table is the `index in parent` property of + /// `m_columns` for subtables with shared descriptor, and the `index in + /// parent` property of `m_top` for all other tables. + /// + /// - If this table has shared descriptor, then the `index in parent` + /// property of the contained spec accessor is correct. + /// + /// - The parent accessor is in a valid state (already refreshed). If the + /// parent is a group, then the group accessor (excluding its table + /// accessors) must be in a valid state. If the parent is a table, then + /// the table accessor (excluding its subtable accessors) must be in a + /// valid state. + /// + /// - Every descendant subtable accessor is marked if it needs to be + /// refreshed, or if it has a descendant accessor that needs to be + /// refreshed. + /// + /// - This table accessor, as well as all its descendant accessors, are in + /// structural correspondence with the underlying node hierarchy whose + /// root ref is stored in the parent (see AccessorConsistencyLevels). + void refresh_accessor_tree(); + + void refresh_spec_accessor(); + + void refresh_column_accessors(size_t col_ndx_begin = 0); + + // Look for link columns starting from col_ndx_begin. + // If a link column is found, follow the link and update it's + // backlink column accessor if it is in different table. + void refresh_link_target_accessors(size_t col_ndx_begin = 0); + + bool is_cross_table_link_target() const noexcept; + std::recursive_mutex* get_parent_accessor_management_lock() const; +#ifdef REALM_DEBUG + void to_dot_internal(std::ostream&) const; +#endif + + friend class SubtableNode; + friend class _impl::TableFriend; + friend class Query; + friend class metrics::QueryInfo; + template + friend class util::bind_ptr; + template + friend class SimpleQuerySupport; + friend class LangBindHelper; + friend class TableViewBase; + template + friend class Columns; + friend class Columns; + friend class ParentNode; + template + friend class SequentialGetter; + friend struct util::serializer::SerialisationState; + friend class RowBase; + friend class LinksToNode; + friend class LinkMap; + friend class LinkView; + friend class Group; +}; + +class Table::Parent : public ArrayParent { +public: + ~Parent() noexcept override + { + } + +protected: + virtual StringData get_child_name(size_t child_ndx) const noexcept; + + /// If children are group-level tables, then this function returns the + /// group. Otherwise it returns null. + virtual Group* get_parent_group() noexcept; + + /// If children are subtables, then this function returns the + /// parent table. Otherwise it returns null. + /// + /// If \a column_ndx_out is not null, this function must assign the index of + /// the column within the parent table to `*column_ndx_out` when , and only + /// when this table parent is a column in a parent table. + virtual Table* get_parent_table(size_t* column_ndx_out = nullptr) noexcept; + + virtual Spec* get_subtable_spec() noexcept; + + /// Must be called whenever a child table accessor is about to be destroyed. + /// + /// Note that the argument is a pointer to the child Table rather than its + /// `ndx_in_parent` property. This is because only minimal accessor + /// consistency can be assumed by this function. + virtual void child_accessor_destroyed(Table* child) noexcept = 0; + + + virtual size_t* record_subtable_path(size_t* begin, size_t* end) noexcept; + virtual std::recursive_mutex* get_accessor_management_lock() noexcept = 0; + + friend class Table; +}; + + +// Implementation: + + +inline uint_fast64_t Table::get_version_counter() const noexcept +{ + return observe_version(); +} + +inline uint64_t Table::observe_version() const noexcept +{ + m_top.get_alloc().observe_version(); + return m_version; +} + +inline void Table::bump_version(bool bump_global) const noexcept +{ + if (bump_global) { + // This is only set on initial entry through an operation on the same + // table. recursive calls (via parent or via backlinks) must be done + // with bump_global=false. + m_top.get_alloc().bump_global_version(); + } + if (m_top.get_alloc().should_propagate_version(m_version)) { + if (const Table* parent = get_parent_table_ptr()) + parent->bump_version(false); + // Recurse through linked tables, use m_mark to avoid infinite recursion + for (auto& column_ptr : m_cols) { + // We may meet a null pointer in place of a backlink column, pending + // replacement with a new one. This can happen ONLY when creation of + // the corresponding forward link column in the origin table is + // pending as well. In this case it is ok to just ignore the zeroed + // backlink column, because the origin table is guaranteed to also + // be refreshed/marked dirty and hence have it's version bumped. + if (column_ptr != nullptr) + column_ptr->bump_link_origin_table_version(); + } + } +} + +inline void Table::remove(size_t row_ndx) +{ + bool is_move_last_over = false; + erase_row(row_ndx, is_move_last_over); // Throws +} + +inline void Table::move_last_over(size_t row_ndx) +{ + bool is_move_last_over = true; + erase_row(row_ndx, is_move_last_over); // Throws +} + +inline void Table::remove_last() +{ + if (!is_empty()) + remove(size() - 1); +} + +// A good place to start if you want to understand the memory ordering +// chosen for the operations below is http://preshing.com/20130922/acquire-and-release-fences/ +inline void Table::bind_ptr() const noexcept +{ + m_ref_count.fetch_add(1, std::memory_order_relaxed); +} + +inline void Table::unbind_ptr() const noexcept +{ + // The delete operation runs the destructor, and the destructor + // must always see all changes to the object being deleted. + // Within each thread, we know that unbind_ptr will always happen after + // any changes, so it is a convenient place to do a release. + // The release will then be observed by the acquire fence in + // the case where delete is actually called (the count reaches 0) + if (m_ref_count.fetch_sub(1, std::memory_order_release) != 1) { + return; + } + + std::atomic_thread_fence(std::memory_order_acquire); + + std::recursive_mutex* lock = get_parent_accessor_management_lock(); + if (lock) { + std::lock_guard lg(*lock); + if (m_ref_count == 0) + delete this; + } + else { + delete this; + } +} + +inline void Table::register_view(const TableViewBase* view) +{ + util::LockGuard lock(m_accessor_mutex); + // Casting away constness here - operations done on tableviews + // through m_views are all internal and preserving "some" kind + // of logical constness. + m_views.push_back(const_cast(view)); +} + +inline bool Table::is_attached() const noexcept +{ + // Note that it is not possible to tie the state of attachment of a table to + // the state of attachment of m_top, because tables with shared spec do not + // have a 'top' array. Neither is it possible to tie it to the state of + // attachment of m_columns, because subtables with shared spec start out in + // a degenerate form where they do not have a 'columns' array. For these + // reasons, it is neccessary to define the notion of attachment for a table + // as follows: A table is attached if, and ony if m_column stores a non-null + // parent pointer. This works because even for degenerate subtables, + // m_columns is initialized with the correct parent pointer. + return m_columns.has_parent(); +} + +inline StringData Table::get_name() const noexcept +{ + REALM_ASSERT(is_attached()); + const Array& real_top = m_top.is_attached() ? m_top : m_columns; + ArrayParent* parent = real_top.get_parent(); + if (!parent) + return StringData(""); + size_t index_in_parent = real_top.get_ndx_in_parent(); + REALM_ASSERT(dynamic_cast(parent)); + return static_cast(parent)->get_child_name(index_in_parent); +} + +inline size_t Table::get_column_count() const noexcept +{ + REALM_ASSERT(is_attached()); + return m_spec->get_public_column_count(); +} + +inline StringData Table::get_column_name(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, get_column_count()); + return m_spec->get_column_name(ndx); +} + +inline size_t Table::get_column_index(StringData name) const noexcept +{ + REALM_ASSERT(is_attached()); + return m_spec->get_column_index(name); +} + +inline ColumnType Table::get_real_column_type(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, m_spec->get_column_count()); + return m_spec->get_column_type(ndx); +} + +inline DataType Table::get_column_type(size_t ndx) const noexcept +{ + REALM_ASSERT_3(ndx, <, m_spec->get_column_count()); + return m_spec->get_public_column_type(ndx); +} + +template +inline Col& Table::get_column(size_t ndx) +{ + ColumnBase& col = get_column_base(ndx); +#ifdef REALM_DEBUG + validate_column_type(col, col_type, ndx); +#endif + REALM_ASSERT(typeid(Col) == typeid(col)); + return static_cast(col); +} + +template +inline const Col& Table::get_column(size_t ndx) const noexcept +{ + const ColumnBase& col = get_column_base(ndx); +#ifdef REALM_DEBUG + validate_column_type(col, col_type, ndx); +#endif + REALM_ASSERT(typeid(Col) == typeid(col)); + return static_cast(col); +} + +inline bool Table::has_shared_type() const noexcept +{ + REALM_ASSERT(is_attached()); + return !m_top.is_attached(); +} + +inline void Table::verify_column(size_t col_ndx, const ColumnBase* col) const +{ + // Check if the column exists at the expected location + if (REALM_LIKELY(col_ndx < m_cols.size() && m_cols[col_ndx] == col)) + return; + // The column might be elsewhere in the list + for (auto c : m_cols) { + if (c == col) + return; + } + throw LogicError(LogicError::column_does_not_exist); +} + +class Table::UnbindGuard { +public: + UnbindGuard(Table* table) noexcept + : m_table(table) + { + } + + ~UnbindGuard() noexcept + { + if (m_table) + m_table->unbind_ptr(); + } + + Table& operator*() const noexcept + { + return *m_table; + } + + Table* operator->() const noexcept + { + return m_table; + } + + Table* get() const noexcept + { + return m_table; + } + + Table* release() noexcept + { + Table* table = m_table; + m_table = nullptr; + return table; + } + +private: + Table* m_table; +}; + + +inline Table::Table(Allocator& alloc) + : m_top(alloc) + , m_columns(alloc) +{ + m_ref_count = 1; // Explicitly managed lifetime + + ref_type ref = create_empty_table(alloc); // Throws + Parent* parent = nullptr; + size_t ndx_in_parent = 0; + init(ref, parent, ndx_in_parent); +} + +inline Table::Table(const Table& t, Allocator& alloc) + : m_top(alloc) + , m_columns(alloc) +{ + m_ref_count = 1; // Explicitly managed lifetime + + ref_type ref = t.clone(alloc); // Throws + Parent* parent = nullptr; + size_t ndx_in_parent = 0; + init(ref, parent, ndx_in_parent); +} + +inline Table::Table(ref_count_tag, Allocator& alloc) + : m_top(alloc) + , m_columns(alloc) +{ + m_ref_count = 0; // Lifetime managed by reference counting +} + +inline Allocator& Table::get_alloc() const +{ + return m_top.get_alloc(); +} + +inline TableRef Table::create(Allocator& alloc) +{ + std::unique_ptr
table(new Table(ref_count_tag(), alloc)); // Throws + ref_type ref = create_empty_table(alloc); // Throws + Parent* parent = nullptr; + size_t ndx_in_parent = 0; + table->init(ref, parent, ndx_in_parent); // Throws + return table.release()->get_table_ref(); +} + +inline TableRef Table::copy(Allocator& alloc) const +{ + std::unique_ptr
table(new Table(ref_count_tag(), alloc)); // Throws + ref_type ref = clone(alloc); // Throws + Parent* parent = nullptr; + size_t ndx_in_parent = 0; + table->init(ref, parent, ndx_in_parent); // Throws + return table.release()->get_table_ref(); +} + +// For use by queries +template +inline Columns Table::column(size_t column_ndx) +{ + std::vector link_chain = std::move(m_link_chain); + m_link_chain.clear(); + + // Check if user-given template type equals Realm type. Todo, we should clean up and reuse all our + // type traits (all the is_same() cases below). + const Table* table = get_link_chain_target(link_chain); + + realm::DataType ct = table->get_column_type(column_ndx); + if (std::is_same::value && ct != type_Int) + throw LogicError(LogicError::type_mismatch); + else if (std::is_same::value && ct != type_Bool) + throw LogicError(LogicError::type_mismatch); + else if (std::is_same::value && ct != type_OldDateTime) + throw LogicError(LogicError::type_mismatch); + else if (std::is_same::value && ct != type_Float) + throw LogicError(LogicError::type_mismatch); + else if (std::is_same::value && ct != type_Double) + throw LogicError(LogicError::type_mismatch); + + if (std::is_same::value || std::is_same::value || std::is_same::value) { + link_chain.push_back(column_ndx); + } + + return Columns(column_ndx, this, std::move(link_chain)); +} + +template +inline Columns Table::column(const Table& origin, size_t origin_col_ndx) +{ + static_assert(std::is_same::value, ""); + + size_t origin_table_ndx = origin.get_index_in_group(); + const Table& current_target_table = *get_link_chain_target(m_link_chain); + size_t backlink_col_ndx = current_target_table.m_spec->find_backlink_column(origin_table_ndx, origin_col_ndx); + + std::vector link_chain = std::move(m_link_chain); + m_link_chain.clear(); + link_chain.push_back(backlink_col_ndx); + + return Columns(backlink_col_ndx, this, std::move(link_chain)); +} + +template +inline BacklinkCount Table::get_backlink_count() +{ + std::vector link_chain = std::move(m_link_chain); + m_link_chain.clear(); + return BacklinkCount(this, std::move(link_chain)); +} + +template +SubQuery Table::column(size_t column_ndx, Query subquery) +{ + static_assert(std::is_same::value, "A subquery must involve a link list or backlink column"); + return SubQuery(column(column_ndx), std::move(subquery)); +} + +template +SubQuery Table::column(const Table& origin, size_t origin_col_ndx, Query subquery) +{ + static_assert(std::is_same::value, "A subquery must involve a link list or backlink column"); + return SubQuery(column(origin, origin_col_ndx), std::move(subquery)); +} + +inline Table& Table::link(size_t link_column) +{ + m_link_chain.push_back(link_column); + return *this; +} + +inline Table& Table::backlink(const Table& origin, size_t origin_col_ndx) +{ + size_t origin_table_ndx = origin.get_index_in_group(); + const Table& current_target_table = *get_link_chain_target(m_link_chain); + size_t backlink_col_ndx = current_target_table.m_spec->find_backlink_column(origin_table_ndx, origin_col_ndx); + return link(backlink_col_ndx); +} + +inline bool Table::is_empty() const noexcept +{ + return m_size == 0; +} + +inline size_t Table::size() const noexcept +{ + return m_size; +} + +inline Table::RowExpr Table::get(size_t row_ndx) noexcept +{ + REALM_ASSERT_3(row_ndx, <, size()); + return RowExpr(this, row_ndx); +} + +inline Table::ConstRowExpr Table::get(size_t row_ndx) const noexcept +{ + REALM_ASSERT_3(row_ndx, <, size()); + return ConstRowExpr(this, row_ndx); +} + +inline Table::RowExpr Table::front() noexcept +{ + return get(0); +} + +inline Table::ConstRowExpr Table::front() const noexcept +{ + return get(0); +} + +inline Table::RowExpr Table::back() noexcept +{ + return get(m_size - 1); +} + +inline Table::ConstRowExpr Table::back() const noexcept +{ + return get(m_size - 1); +} + +inline Table::RowExpr Table::operator[](size_t row_ndx) noexcept +{ + return get(row_ndx); +} + +inline Table::ConstRowExpr Table::operator[](size_t row_ndx) const noexcept +{ + return get(row_ndx); +} + +inline size_t Table::add_empty_row(size_t num_rows) +{ + size_t row_ndx = m_size; + insert_empty_row(row_ndx, num_rows); // Throws + return row_ndx; // Return index of first new row +} + +inline ConstTableRef Table::get_subtable_tableref(size_t col_ndx, size_t row_ndx) const +{ + return const_cast(this)->get_subtable_tableref(col_ndx, row_ndx); // Throws +} + +inline bool Table::is_null_link(size_t col_ndx, size_t row_ndx) const noexcept +{ + return get_link(col_ndx, row_ndx) == realm::npos; +} + +inline ConstTableRef Table::get_link_target(size_t col_ndx) const noexcept +{ + return const_cast(this)->get_link_target(col_ndx); +} + +template +inline void Table::set_enum(size_t column_ndx, size_t row_ndx, E value) +{ + set_int(column_ndx, row_ndx, value); +} + +inline void Table::nullify_link(size_t col_ndx, size_t row_ndx) +{ + set_link(col_ndx, row_ndx, realm::npos); +} + +inline TableRef Table::get_subtable(size_t column_ndx, size_t row_ndx) +{ + return get_subtable_tableref(column_ndx, row_ndx); +} + +inline ConstTableRef Table::get_subtable(size_t column_ndx, size_t row_ndx) const +{ + return get_subtable_tableref(column_ndx, row_ndx); +} + +inline ConstTableRef Table::get_parent_table(size_t* column_ndx_out) const noexcept +{ + return ConstTableRef(get_parent_table_ptr(column_ndx_out)); +} + +inline TableRef Table::get_parent_table(size_t* column_ndx_out) noexcept +{ + return TableRef(get_parent_table_ptr(column_ndx_out)); +} + +inline bool Table::is_group_level() const noexcept +{ + return bool(get_parent_group()); +} + +inline bool Table::operator==(const Table& t) const +{ + return *m_spec == *t.m_spec && compare_rows(t); // Throws +} + +inline bool Table::operator!=(const Table& t) const +{ + return !(*this == t); // Throws +} + +inline bool Table::is_degenerate() const +{ + if (!is_attached()) { + throw LogicError{LogicError::detached_accessor}; + } + + return !m_columns.is_attached(); +} + +inline void Table::set_into_mixed(Table* parent, size_t col_ndx, size_t row_ndx) const +{ + parent->set_mixed_subtable(col_ndx, row_ndx, this); +} + +inline size_t Table::get_size_from_ref(ref_type top_ref, Allocator& alloc) noexcept +{ + const char* top_header = alloc.translate(top_ref); + std::pair p = Array::get_two(top_header, 0); + ref_type spec_ref = to_ref(p.first), columns_ref = to_ref(p.second); + return get_size_from_ref(spec_ref, columns_ref, alloc); +} + +inline Table* Table::get_parent_table_ptr(size_t* column_ndx_out) noexcept +{ + const Table* parent = const_cast(this)->get_parent_table_ptr(column_ndx_out); + return const_cast(parent); +} + +inline bool Table::is_link_type(ColumnType col_type) noexcept +{ + return col_type == col_type_Link || col_type == col_type_LinkList; +} + +inline size_t* Table::record_subtable_path(size_t* begin, size_t* end) const noexcept +{ + const Array& real_top = m_top.is_attached() ? m_top : m_columns; + size_t index_in_parent = real_top.get_ndx_in_parent(); + REALM_ASSERT_3(begin, <, end); + *begin++ = index_in_parent; + ArrayParent* parent = real_top.get_parent(); + REALM_ASSERT(parent); + REALM_ASSERT(dynamic_cast(parent)); + return static_cast(parent)->record_subtable_path(begin, end); +} + +inline size_t* Table::Parent::record_subtable_path(size_t* begin, size_t*) noexcept +{ + return begin; +} + +inline bool Table::is_marked() const noexcept +{ + return m_mark; +} + +inline void Table::mark() noexcept +{ + m_mark = true; +} + +inline void Table::unmark() noexcept +{ + m_mark = false; +} + +inline Replication* Table::get_repl() noexcept +{ + return m_top.get_alloc().get_replication(); +} + +inline void Table::set_ndx_in_parent(size_t ndx_in_parent) noexcept +{ + if (m_top.is_attached()) { + // Root table (independent descriptor) + m_top.set_ndx_in_parent(ndx_in_parent); + } + else { + // Subtable with shared descriptor + m_columns.set_ndx_in_parent(ndx_in_parent); + } +} + +// Declare our explicit specializations so that the inline wrappers don't try +// to instantiate them +template<> int64_t Table::get(size_t, size_t) const noexcept; +template<> util::Optional Table::get>(size_t, size_t) const noexcept; +template<> bool Table::get(size_t, size_t) const noexcept; +template<> Optional Table::get>(size_t, size_t) const noexcept; +template<> float Table::get(size_t, size_t) const noexcept; +template<> util::Optional Table::get>(size_t, size_t) const noexcept; +template<> double Table::get(size_t, size_t) const noexcept; +template<> util::Optional Table::get>(size_t, size_t) const noexcept; +template<> OldDateTime Table::get(size_t, size_t) const noexcept; +template<> Timestamp Table::get(size_t, size_t) const noexcept; +template<> StringData Table::get(size_t, size_t) const noexcept; +template<> BinaryData Table::get(size_t, size_t) const noexcept; +template<> BinaryIterator Table::get(size_t, size_t) const noexcept; +template<> Mixed Table::get(size_t, size_t) const noexcept; + +template<> void Table::set(size_t, size_t, int64_t, bool); +template<> void Table::set(size_t, size_t, bool, bool); +template<> void Table::set(size_t, size_t, float, bool); +template<> void Table::set(size_t, size_t, double, bool); +template<> void Table::set(size_t, size_t, OldDateTime, bool); +template<> void Table::set(size_t, size_t, Timestamp, bool); +template<> void Table::set(size_t, size_t, StringData, bool); +template<> void Table::set(size_t, size_t, BinaryData, bool); +template<> void Table::set(size_t, size_t, Mixed, bool); +template<> void Table::set(size_t, size_t, null, bool); + +template<> size_t Table::set_unique(size_t, size_t, int64_t); +template<> size_t Table::set_unique(size_t, size_t, StringData); +template<> size_t Table::set_unique(size_t, size_t, null); + + +inline int64_t Table::get_int(size_t col_ndx, size_t ndx) const noexcept +{ + if (is_nullable(col_ndx)) + return get>(col_ndx, ndx).value_or(0); + else + return get(col_ndx, ndx); +} + +inline size_t Table::set_int_unique(size_t col_ndx, size_t ndx, int_fast64_t value) +{ + return set_unique(col_ndx, ndx, value); +} + +inline void Table::set_int(size_t col_ndx, size_t ndx, int_fast64_t value, bool is_default) +{ + return set(col_ndx, ndx, value, is_default); +} + +inline Timestamp Table::get_timestamp(size_t col_ndx, size_t ndx) const noexcept +{ + return get(col_ndx, ndx); +} + +inline void Table::set_timestamp(size_t col_ndx, size_t ndx, Timestamp value, bool is_default) +{ + return set(col_ndx, ndx, value, is_default); +} + +inline bool Table::get_bool(size_t col_ndx, size_t ndx) const noexcept +{ + if (is_nullable(col_ndx)) + return get>(col_ndx, ndx).value_or(false); + else + return get(col_ndx, ndx); +} + +inline void Table::set_bool(size_t col_ndx, size_t ndx, bool value, bool is_default) +{ + return set(col_ndx, ndx, value, is_default); +} + +inline OldDateTime Table::get_olddatetime(size_t col_ndx, size_t ndx) const noexcept +{ + return get(col_ndx, ndx); +} + +inline void Table::set_olddatetime(size_t col_ndx, size_t ndx, OldDateTime value, bool is_default) +{ + return set(col_ndx, ndx, value, is_default); +} + +inline float Table::get_float(size_t col_ndx, size_t ndx) const noexcept +{ + float f = get(col_ndx, ndx); + return null::is_null_float(f) ? 0.0f : f; +} + +inline void Table::set_float(size_t col_ndx, size_t ndx, float value, bool is_default) +{ + return set(col_ndx, ndx, value, is_default); +} + +inline double Table::get_double(size_t col_ndx, size_t ndx) const noexcept +{ + double d = get(col_ndx, ndx); + return null::is_null_float(d) ? 0.0 : d; +} + +inline void Table::set_double(size_t col_ndx, size_t ndx, double value, bool is_default) +{ + return set(col_ndx, ndx, value, is_default); +} + +inline StringData Table::get_string(size_t col_ndx, size_t ndx) const noexcept +{ + return get(col_ndx, ndx); +} + +inline void Table::set_string(size_t col_ndx, size_t ndx, StringData value, bool is_default) +{ + return set(col_ndx, ndx, value, is_default); +} + +inline size_t Table::set_string_unique(size_t col_ndx, size_t ndx, StringData value) +{ + return set_unique(col_ndx, ndx, value); +} + +inline BinaryData Table::get_binary(size_t col_ndx, size_t ndx) const noexcept +{ + return get(col_ndx, ndx); +} + +inline BinaryIterator Table::get_binary_iterator(size_t col_ndx, size_t ndx) const noexcept +{ + return get(col_ndx, ndx); +} + +inline void Table::set_binary(size_t col_ndx, size_t ndx, BinaryData value, bool is_default) +{ + set(col_ndx, ndx, value, is_default); +} + +inline Mixed Table::get_mixed(size_t col_ndx, size_t ndx) const noexcept +{ + return get(col_ndx, ndx); +} + +inline void Table::set_mixed(size_t col_ndx, size_t ndx, Mixed value, bool is_default) +{ + set(col_ndx, ndx, value, is_default); +} + +inline void Table::set_null(size_t col_ndx, size_t ndx, bool is_default) +{ + set(col_ndx, ndx, null(), is_default); +} + +inline void Table::set_null_unique(size_t col_ndx, size_t ndx) +{ + set_unique(col_ndx, ndx, null()); +} + + +// This class groups together information about the target of a link column +// This is not a valid link if the target table == nullptr +struct LinkTargetInfo { + LinkTargetInfo(Table* target = nullptr, size_t backlink_ndx = realm::npos) + : m_target_table(target) + , m_backlink_col_ndx(backlink_ndx) + { + } + bool is_valid() const + { + return (m_target_table != nullptr); + } + Table* m_target_table; + size_t m_backlink_col_ndx; // a value of npos indicates the backlink should be appended +}; + +// The purpose of this class is to give internal access to some, but +// not all of the non-public parts of the Table class. +class _impl::TableFriend { +public: + typedef Table::UnbindGuard UnbindGuard; + + static ref_type create_empty_table(Allocator& alloc) + { + return Table::create_empty_table(alloc); // Throws + } + + static ref_type clone(const Table& table, Allocator& alloc) + { + return table.clone(alloc); // Throws + } + + static ref_type clone_columns(const Table& table, Allocator& alloc) + { + return table.clone_columns(alloc); // Throws + } + + static Table* create_accessor(Allocator& alloc, ref_type top_ref, Table::Parent* parent, size_t ndx_in_parent) + { + std::unique_ptr
table(new Table(Table::ref_count_tag(), alloc)); // Throws + table->init(top_ref, parent, ndx_in_parent); // Throws + return table.release(); + } + + static Table* create_accessor(Spec* shared_spec, Table::Parent* parent_column, size_t parent_row_ndx) + { + Allocator& alloc = shared_spec->get_alloc(); + std::unique_ptr
table(new Table(Table::ref_count_tag(), alloc)); // Throws + table->init(shared_spec, parent_column, parent_row_ndx); // Throws + return table.release(); + } + + // Intended to be used only by Group::create_table_accessor() + static Table* create_incomplete_accessor(Allocator& alloc, ref_type top_ref, Table::Parent* parent, + size_t ndx_in_parent) + { + std::unique_ptr
table(new Table(Table::ref_count_tag(), alloc)); // Throws + bool skip_create_column_accessors = true; + table->init(top_ref, parent, ndx_in_parent, skip_create_column_accessors); // Throws + return table.release(); + } + + // Intended to be used only by Group::create_table_accessor() + static void complete_accessor(Table& table) + { + table.refresh_column_accessors(); // Throws + } + + static void set_top_parent(Table& table, ArrayParent* parent, size_t ndx_in_parent) noexcept + { + table.m_top.set_parent(parent, ndx_in_parent); + } + + static void update_from_parent(Table& table, size_t old_baseline) noexcept + { + table.update_from_parent(old_baseline); + } + + static void detach(Table& table) noexcept + { + table.detach(); + } + + static void discard_row_accessors(Table& table) noexcept + { + table.discard_row_accessors(); + } + + static void discard_child_accessors(Table& table) noexcept + { + table.discard_child_accessors(); + } + + static void discard_subtable_accessor(Table& table, size_t col_ndx, size_t row_ndx) noexcept + { + table.discard_subtable_accessor(col_ndx, row_ndx); + } + + static void bind_ptr(Table& table) noexcept + { + table.bind_ptr(); + } + + static void unbind_ptr(Table& table) noexcept + { + table.unbind_ptr(); + } + + static bool compare_rows(const Table& a, const Table& b) + { + return a.compare_rows(b); // Throws + } + + static size_t get_size_from_ref(ref_type ref, Allocator& alloc) noexcept + { + return Table::get_size_from_ref(ref, alloc); + } + + static size_t get_size_from_ref(ref_type spec_ref, ref_type columns_ref, Allocator& alloc) noexcept + { + return Table::get_size_from_ref(spec_ref, columns_ref, alloc); + } + + static Spec& get_spec(Table& table) noexcept + { + return *table.m_spec; + } + + static const Spec& get_spec(const Table& table) noexcept + { + return *table.m_spec; + } + + static ColumnBase& get_column(const Table& table, size_t col_ndx) + { + return *table.m_cols[col_ndx]; + } + + static void do_remove(Table& table, size_t row_ndx) + { + bool broken_reciprocal_backlinks = false; + table.do_remove(row_ndx, broken_reciprocal_backlinks); // Throws + } + + static void do_move_last_over(Table& table, size_t row_ndx) + { + bool broken_reciprocal_backlinks = false; + table.do_move_last_over(row_ndx, broken_reciprocal_backlinks); // Throws + } + + static void do_swap_rows(Table& table, size_t row_ndx_1, size_t row_ndx_2) + { + table.do_swap_rows(row_ndx_1, row_ndx_2); // Throws + } + + static void do_move_row(Table& table, size_t from_ndx, size_t to_ndx) + { + table.do_move_row(from_ndx, to_ndx); // Throws + } + + static void do_merge_rows(Table& table, size_t row_ndx, size_t new_row_ndx) + { + table.do_merge_rows(row_ndx, new_row_ndx); // Throws + } + + static void do_clear(Table& table) + { + bool broken_reciprocal_backlinks = false; + table.do_clear(broken_reciprocal_backlinks); // Throws + } + + static void do_set_link(Table& table, size_t col_ndx, size_t row_ndx, size_t target_row_ndx) + { + table.do_set_link(col_ndx, row_ndx, target_row_ndx); // Throws + } + + static size_t get_backlink_count(const Table& table, size_t row_ndx, bool only_strong_links) noexcept + { + return table.get_backlink_count(row_ndx, only_strong_links); + } + + static void cascade_break_backlinks_to(Table& table, size_t row_ndx, CascadeState& state) + { + table.cascade_break_backlinks_to(row_ndx, state); // Throws + } + + static void remove_backlink_broken_rows(Table& table, const CascadeState& rows) + { + table.remove_backlink_broken_rows(rows); // Throws + } + + static size_t* record_subtable_path(const Table& table, size_t* begin, size_t* end) noexcept + { + return table.record_subtable_path(begin, end); + } + + static void insert_column(Descriptor& desc, size_t column_ndx, DataType type, StringData name, + LinkTargetInfo& link, bool nullable = false) + { + Table::do_insert_column(desc, column_ndx, type, name, link, nullable); // Throws + } + + static void insert_column_unless_exists(Descriptor& desc, size_t column_ndx, DataType type, StringData name, + LinkTargetInfo link, bool nullable = false, bool* was_inserted = nullptr) + { + Table::do_insert_column_unless_exists(desc, column_ndx, type, name, link, nullable, was_inserted); // Throws + } + + static void erase_column(Descriptor& desc, size_t column_ndx) + { + Table::do_erase_column(desc, column_ndx); // Throws + } + + static void rename_column(Descriptor& desc, size_t column_ndx, StringData name) + { + Table::do_rename_column(desc, column_ndx, name); // Throws + } + + static void add_search_index(Descriptor& desc, size_t column_ndx) + { + Table::do_add_search_index(desc, column_ndx); // Throws + } + + static void remove_search_index(Descriptor& desc, size_t column_ndx) + { + Table::do_remove_search_index(desc, column_ndx); // Throws + } + + static void set_link_type(Table& table, size_t column_ndx, LinkType link_type) + { + table.do_set_link_type(column_ndx, link_type); // Throws + } + + static void erase_row(Table& table, size_t row_ndx, bool is_move_last_over) + { + table.erase_row(row_ndx, is_move_last_over); // Throws + } + + static void batch_erase_rows(Table& table, const IntegerColumn& row_indexes, bool is_move_last_over) + { + table.batch_erase_rows(row_indexes, is_move_last_over); // Throws + } + + static TableRef get_subtable_accessor(Table& table, size_t col_ndx, size_t row_ndx) noexcept + { + return table.get_subtable_accessor(col_ndx, row_ndx); + } + + static const Table* get_link_target_table_accessor(const Table& table, size_t col_ndx) noexcept + { + return const_cast(table).get_link_target_table_accessor(col_ndx); + } + + static Table* get_link_target_table_accessor(Table& table, size_t col_ndx) noexcept + { + return table.get_link_target_table_accessor(col_ndx); + } + + static void adj_acc_insert_rows(Table& table, size_t row_ndx, size_t num_rows) noexcept + { + table.adj_acc_insert_rows(row_ndx, num_rows); + } + + static void adj_acc_erase_row(Table& table, size_t row_ndx) noexcept + { + table.adj_acc_erase_row(row_ndx); + } + + static void adj_acc_swap_rows(Table& table, size_t row_ndx_1, size_t row_ndx_2) noexcept + { + table.adj_acc_swap_rows(row_ndx_1, row_ndx_2); + } + + static void adj_acc_move_row(Table& table, size_t from_ndx, size_t to_ndx) noexcept + { + table.adj_acc_move_row(from_ndx, to_ndx); + } + + static void adj_acc_merge_rows(Table& table, size_t row_ndx_1, size_t row_ndx_2) noexcept + { + table.adj_acc_merge_rows(row_ndx_1, row_ndx_2); + } + + static void adj_acc_move_over(Table& table, size_t from_row_ndx, size_t to_row_ndx) noexcept + { + table.adj_acc_move_over(from_row_ndx, to_row_ndx); + } + + static void adj_acc_clear_root_table(Table& table) noexcept + { + table.adj_acc_clear_root_table(); + } + + static void adj_acc_clear_nonroot_table(Table& table) noexcept + { + table.adj_acc_clear_nonroot_table(); + } + + static void adj_insert_column(Table& table, size_t col_ndx) + { + table.adj_insert_column(col_ndx); // Throws + } + + static void adj_add_column(Table& table) + { + size_t num_cols = table.m_cols.size(); + table.adj_insert_column(num_cols); // Throws + } + + static void adj_erase_column(Table& table, size_t col_ndx) noexcept + { + table.adj_erase_column(col_ndx); + } + + static bool is_marked(const Table& table) noexcept + { + return table.is_marked(); + } + + static void mark(Table& table) noexcept + { + table.mark(); + } + + static void unmark(Table& table) noexcept + { + table.unmark(); + } + + static void recursive_mark(Table& table) noexcept + { + table.recursive_mark(); + } + + static void mark_link_target_tables(Table& table, size_t col_ndx_begin) noexcept + { + table.mark_link_target_tables(col_ndx_begin); + } + + static void mark_opposite_link_tables(Table& table) noexcept + { + table.mark_opposite_link_tables(); + } + + static DescriptorRef get_root_table_desc_accessor(Table& root_table) noexcept + { + return root_table.m_descriptor.lock(); + } + + typedef Table::AccessorUpdater AccessorUpdater; + static void update_accessors(Table& table, const size_t* col_path_begin, const size_t* col_path_end, + AccessorUpdater& updater) + { + table.update_accessors(col_path_begin, col_path_end, updater); // Throws + } + + static void refresh_accessor_tree(Table& table) + { + table.refresh_accessor_tree(); // Throws + } + + static void refresh_spec_accessor(Table& table) + { + table.refresh_spec_accessor(); // Throws + } + + static void set_ndx_in_parent(Table& table, size_t ndx_in_parent) noexcept + { + table.set_ndx_in_parent(ndx_in_parent); + } + + static bool is_link_type(ColumnType type) noexcept + { + return Table::is_link_type(type); + } + + static void bump_version(Table& table, bool bump_global = true) noexcept + { + table.bump_version(bump_global); + } + + static bool is_cross_table_link_target(const Table& table) + { + return table.is_cross_table_link_target(); + } + + static Group* get_parent_group(const Table& table) noexcept + { + return table.get_parent_group(); + } + + static Replication* get_repl(Table& table) noexcept + { + return table.get_repl(); + } + + static void register_view(Table& table, const TableViewBase* view) + { + table.register_view(view); // Throws + } + + static void unregister_view(Table& table, const TableViewBase* view) noexcept + { + table.unregister_view(view); + } +}; + + +} // namespace realm + +#endif // REALM_TABLE_HPP diff --git a/Pods/Realm/include/core/realm/table_ref.hpp b/Pods/Realm/include/core/realm/table_ref.hpp new file mode 100644 index 0000000000..6e5c02b6cb --- /dev/null +++ b/Pods/Realm/include/core/realm/table_ref.hpp @@ -0,0 +1,481 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_TABLE_REF_HPP +#define REALM_TABLE_REF_HPP + +#include +#include + +#include + +namespace realm { + + +class Table; + + +/// A reference-counting "smart pointer" for referring to table +/// accessors. +/// +/// The purpose of this smart pointer is to keep the referenced table +/// accessor alive for as long as anybody is referring to it, however, +/// for stack allocated table accessors, the lifetime is necessarily +/// determined by scope (see below). +/// +/// Please take note of the distinction between a "table" and a "table +/// accessor" here. A table accessor is an instance of `Table`, +/// and it may, or may not be attached to an +/// actual table at any specific point in time, but this state of +/// attachment of the accessor has nothing to do with the function of +/// the smart pointer. Also, in the rest of the documentation of this +/// class, whenever you see `Table::%foo`, you are supposed to read it +/// as, `Table::%foo`. +/// +/// +/// Table accessors are either created directly by an application via +/// a call to one of the public table constructors, or they are +/// created internally by the Realm library, such as when the +/// application calls Group::get_table(), Table::get_subtable(), or +/// Table::create(). +/// +/// Applications can safely assume that all table accessors, created +/// internally by the Realm library, have a lifetime that is managed +/// by reference counting. This means that the application can prolong +/// the lifetime of *such* table accessors indefinitely by holding on +/// to at least one smart pointer, but note that the guarantee of the +/// continued existence of the accessor, does not imply that the +/// accessor remains attached to the underlying table (see +/// Table::is_attached() for details). Accessors whose lifetime are +/// controlled by reference counting are destroyed exactly when the +/// reference count drops to zero. +/// +/// When an application creates a new table accessor by a direct call +/// to one of the public constructors, the lifetime of that table +/// accessor is *not*, and cannot be managed by reference +/// counting. This is true regardless of the way the accessor is +/// created (i.e., regardless of whether it is an automatic variable +/// on the stack, or created on the heap using `new`). However, for +/// convenience, but with one important caveat, it is still possible +/// to use smart pointers to refer to such accessors. The caveat is +/// that no smart pointers are allowed to refer to the accessor at the +/// point in time when its destructor is called. It is entirely the +/// responsibility of the application to ensure that this requirement +/// is met. Failing to do so, will result in undefined +/// behavior. Finally, please note that an application is always free +/// to use Table::create() as an alternative to creating free-standing +/// top-level tables on the stack, and that this is indeed neccessary +/// when fully reference counted lifetimes are required. +/// +/// So, at any time, and for any table accessor, an application can +/// call Table::get_table_ref() to obtain a smart pointer that refers +/// to that table, however, while that is always possible and safe, it +/// is not always possible to extend the lifetime of an accessor by +/// holding on to a smart pointer. The question of whether that is +/// possible, depends directly on the way the accessor was created. +/// +/// +/// Apart from keeping track of the number of references, these smart +/// pointers behaves almost exactly like regular pointers. In +/// particular, it is possible to dereference a TableRef and get a +/// `Table&` out of it, however, if you are not careful, this can +/// easily lead to dangling references: +/// +/// \code{.cpp} +/// +/// Table& sub_1 = *(table.get_subtable(0,0)); +/// sub_1.add_empty_row(); // Oops, sub_1 may be dangling! +/// +/// \endcode +/// +/// Whether `sub_1` is actually dangling in the example above will +/// depend on whether other references to the same subtable accessor +/// already exist, but it is never wise to rely in this. Here is a +/// safe and proper alternative: +/// +/// \code{.cpp} +/// +/// TableRef sub_2 = table.get_subtable(0,0); +/// sub_2.add_empty_row(); // Safe! +/// +/// void do_something(Table&); +/// do_something(*(table.get_subtable(0,0))); // Also safe! +/// +/// \endcode +/// +/// +/// \sa Table +/// \sa TableRef +template +class BasicTableRef : util::bind_ptr { +public: + constexpr BasicTableRef() noexcept + { + } + ~BasicTableRef() noexcept + { + } + + // Copy construct + BasicTableRef(const BasicTableRef& r) noexcept + : util::bind_ptr(r) + { + } + template + BasicTableRef(const BasicTableRef& r) noexcept + : util::bind_ptr(r) + { + } + + // Copy assign + BasicTableRef& operator=(const BasicTableRef&) noexcept; + template + BasicTableRef& operator=(const BasicTableRef&) noexcept; + + // Move construct + BasicTableRef(BasicTableRef&& r) noexcept + : util::bind_ptr(std::move(r)) + { + } + template + BasicTableRef(BasicTableRef&& r) noexcept + : util::bind_ptr(std::move(r)) + { + } + + // Move assign + BasicTableRef& operator=(BasicTableRef&&) noexcept; + template + BasicTableRef& operator=(BasicTableRef&&) noexcept; + + //@{ + /// Comparison + template + bool operator==(const BasicTableRef&) const noexcept; + + template + bool operator==(U*) const noexcept; + + template + bool operator!=(const BasicTableRef&) const noexcept; + + template + bool operator!=(U*) const noexcept; + + template + bool operator<(const BasicTableRef&) const noexcept; + + template + bool operator<(U*) const noexcept; + + template + bool operator>(const BasicTableRef&) const noexcept; + + template + bool operator>(U*) const noexcept; + + template + bool operator<=(const BasicTableRef&) const noexcept; + + template + bool operator<=(U*) const noexcept; + + template + bool operator>=(const BasicTableRef&) const noexcept; + + template + bool operator>=(U*) const noexcept; +//@} + +// Dereference +#ifdef __clang__ + // Clang has a bug that causes it to effectively ignore the 'using' declaration. + T& operator*() const noexcept + { + return util::bind_ptr::operator*(); + } +#else + using util::bind_ptr::operator*; +#endif + using util::bind_ptr::operator->; + + using util::bind_ptr::operator bool; + + T* get() const noexcept + { + return util::bind_ptr::get(); + } + void reset() noexcept + { + util::bind_ptr::reset(); + } + void reset(T* t) noexcept + { + util::bind_ptr::reset(t); + } + + void swap(BasicTableRef& r) noexcept + { + this->util::bind_ptr::swap(r); + } + friend void swap(BasicTableRef& a, BasicTableRef& b) noexcept + { + a.swap(b); + } + + template + friend BasicTableRef unchecked_cast(BasicTableRef
) noexcept; + + template + friend BasicTableRef unchecked_cast(BasicTableRef) noexcept; + +private: + template + struct GetRowAccType { + typedef void type; + }; + + typedef typename GetRowAccType::type RowAccessor; + +public: + /// Same as 'table[i]' where 'table' is the referenced table. + RowAccessor operator[](size_t i) const noexcept + { + return (*this->get())[i]; + } + + explicit BasicTableRef(T* t) noexcept + : util::bind_ptr(t) + { + } + + T* release() { return util::bind_ptr::release(); } +private: + friend class SubtableColumnBase; + friend class Table; + friend class Group; + + template + friend class BasicTableRef; + + typedef typename util::bind_ptr::casting_move_tag casting_move_tag; + template + BasicTableRef(BasicTableRef* r, casting_move_tag) noexcept + : util::bind_ptr(r, casting_move_tag()) + { + } +}; + + +typedef BasicTableRef
TableRef; +typedef BasicTableRef ConstTableRef; + + +template +inline std::basic_ostream& operator<<(std::basic_ostream& out, const BasicTableRef& p) +{ + out << static_cast(&*p); + return out; +} + +template +inline BasicTableRef unchecked_cast(TableRef t) noexcept +{ + return BasicTableRef(&t, typename BasicTableRef::casting_move_tag()); +} + +template +inline BasicTableRef unchecked_cast(ConstTableRef t) noexcept +{ + return BasicTableRef(&t, typename BasicTableRef::casting_move_tag()); +} + + +//@{ +/// Comparison +template +bool operator==(T*, const BasicTableRef&) noexcept; +template +bool operator!=(T*, const BasicTableRef&) noexcept; +template +bool operator<(T*, const BasicTableRef&) noexcept; +template +bool operator>(T*, const BasicTableRef&) noexcept; +template +bool operator<=(T*, const BasicTableRef&) noexcept; +template +bool operator>=(T*, const BasicTableRef&) noexcept; +//@} + + +// Implementation: + +template +inline BasicTableRef& BasicTableRef::operator=(const BasicTableRef& r) noexcept +{ + this->util::bind_ptr::operator=(r); + return *this; +} + +template +template +inline BasicTableRef& BasicTableRef::operator=(const BasicTableRef& r) noexcept +{ + this->util::bind_ptr::operator=(r); + return *this; +} + +template +inline BasicTableRef& BasicTableRef::operator=(BasicTableRef&& r) noexcept +{ + this->util::bind_ptr::operator=(std::move(r)); + return *this; +} + +template +template +inline BasicTableRef& BasicTableRef::operator=(BasicTableRef&& r) noexcept +{ + this->util::bind_ptr::operator=(std::move(r)); + return *this; +} + +template +template +bool BasicTableRef::operator==(const BasicTableRef& p) const noexcept +{ + return get() == p.get(); +} + +template +template +bool BasicTableRef::operator==(U* p) const noexcept +{ + return get() == p; +} + +template +template +bool BasicTableRef::operator!=(const BasicTableRef& p) const noexcept +{ + return get() != p.get(); +} + +template +template +bool BasicTableRef::operator!=(U* p) const noexcept +{ + return get() != p; +} + +template +template +bool BasicTableRef::operator<(const BasicTableRef& p) const noexcept +{ + return get() < p.get(); +} + +template +template +bool BasicTableRef::operator<(U* p) const noexcept +{ + return get() < p; +} + +template +template +bool BasicTableRef::operator>(const BasicTableRef& p) const noexcept +{ + return get() > p.get(); +} + +template +template +bool BasicTableRef::operator>(U* p) const noexcept +{ + return get() > p; +} + +template +template +bool BasicTableRef::operator<=(const BasicTableRef& p) const noexcept +{ + return get() <= p.get(); +} + +template +template +bool BasicTableRef::operator<=(U* p) const noexcept +{ + return get() <= p; +} + +template +template +bool BasicTableRef::operator>=(const BasicTableRef& p) const noexcept +{ + return get() >= p.get(); +} + +template +template +bool BasicTableRef::operator>=(U* p) const noexcept +{ + return get() >= p; +} + +template +bool operator==(T* a, const BasicTableRef& b) noexcept +{ + return b == a; +} + +template +bool operator!=(T* a, const BasicTableRef& b) noexcept +{ + return b != a; +} + +template +bool operator<(T* a, const BasicTableRef& b) noexcept +{ + return b > a; +} + +template +bool operator>(T* a, const BasicTableRef& b) noexcept +{ + return b < a; +} + +template +bool operator<=(T* a, const BasicTableRef& b) noexcept +{ + return b >= a; +} + +template +bool operator>=(T* a, const BasicTableRef& b) noexcept +{ + return b <= a; +} + + +} // namespace realm + +#endif // REALM_TABLE_REF_HPP diff --git a/Pods/Realm/include/core/realm/table_view.hpp b/Pods/Realm/include/core/realm/table_view.hpp new file mode 100644 index 0000000000..f63fd0e110 --- /dev/null +++ b/Pods/Realm/include/core/realm/table_view.hpp @@ -0,0 +1,1612 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_TABLE_VIEW_HPP +#define REALM_TABLE_VIEW_HPP + +#include +#include +#include +#include +#include + +namespace realm { + +// Views, tables and synchronization between them: +// +// Views are built through queries against either tables or another view. +// Views may be restricted to only hold entries provided by another view. +// this other view is called the "restricting view". +// Views may be sorted in ascending or descending order of values in one ore more columns. +// +// Views remember the query from which it was originally built. +// Views remember the table from which it was originally built. +// Views remember a restricting view if one was used when it was originally built. +// Views remember the sorting criteria (columns and direction) +// +// A view may be operated in one of two distinct modes: *reflective* and *imperative*. +// Sometimes the term "reactive" is used instead of "reflective" with the same meaning. +// +// Reflective views: +// - A reflective view *always* *reflect* the result of running the query. +// If the underlying tables or tableviews change, the reflective view changes as well. +// A reflective view may need to rerun the query it was generated from, a potentially +// costly operation which happens on demand. +// - It does not matter whether changes are explicitly done within the transaction, or +// occur implicitly as part of advance_read() or promote_to_write(). +// +// Imperative views: +// - An imperative view only *initially* holds the result of the query. An imperative +// view *never* reruns the query. To force the view to match it's query (by rerunning it), +// the view must be operated in reflective mode. +// An imperative view can be modified explicitly. References can be added, removed or +// changed. +// +// - In imperative mode, the references in the view tracks movement of the referenced data: +// If you delete an entry which is referenced from a view, said reference is detached, +// not removed. +// - It does not matter whether the delete is done in-line (as part of the current transaction), +// or if it is done implicitly as part of advance_read() or promote_to_write(). +// +// The choice between reflective and imperative views might eventually be represented by a +// switch on the tableview, but isn't yet. For now, clients (bindings) must call sync_if_needed() +// to get reflective behavior. +// +// Use cases: +// +// 1. Presenting data +// The first use case (and primary motivator behind the reflective view) is to just track +// and present the state of the database. In this case, the view is operated in reflective +// mode, it is not modified within the transaction, and it is not used to modify data in +// other parts of the database. +// +// 2. Handover +// The second use case is "handover." The implicit rerun of the query in our first use case +// may be too costly to be acceptable on the main thread. Instead you want to run the query +// on a worker thread, but display it on the main thread. To achieve this, you need two +// SharedGroups locked on to the same version of the database. If you have that, you can +// *handover* a view from one thread/SharedGroup to the other. +// +// Handover is a two-step procedure. First, the accessors are *exported* from one SharedGroup, +// called the sourcing group, then it is *imported* into another SharedGroup, called the +// receiving group. The thread associated with the sourcing SharedGroup will be +// responsible for the export operation, while the thread associated with the receiving +// SharedGroup will do the import operation. +// +// 3. Iterating a view and changing data +// The third use case (and a motivator behind the imperative view) is when you want +// to make changes to the database in accordance with a query result. Imagine you want to +// find all employees with a salary below a limit and raise their salaries to the limit (pseudocode): +// +// promote_to_write(); +// view = table.where().less_than(salary_column,limit).find_all(); +// for (size_t i = 0; i < view.size(); ++i) { +// view.set_int(salary_column, i, limit); +// // add this to get reflective mode: view.sync_if_needed(); +// } +// commit_and_continue_as_read(); +// +// This is idiomatic imperative code and it works if the view is operated in imperative mode. +// +// If the view is operated in reflective mode, the behaviour surprises most people: When the +// first salary is changed, the entry no longer fullfills the query, so it is dropped from the +// view implicitly. view[0] is removed, view[1] moves to view[0] and so forth. But the next +// loop iteration has i=1 and refers to view[1], thus skipping view[0]. The end result is that +// every other employee get a raise, while the others don't. +// +// 4. Iterating intermixed with implicit updates +// This leads us to use case 4, which is similar to use case 3, but uses promote_to_write() +// intermixed with iterating a view. This is actually quite important to some, who do not want +// to end up with a large write transaction. +// +// view = table.where().less_than(salary_column,limit).find_all(); +// for (size_t i = 0; i < view.size(); ++i) { +// promote_to_write(); +// view.set_int(salary_column, i, limit); +// commit_and_continue_as_write(); +// } +// +// Anything can happen at the call to promote_to_write(). The key question then becomes: how +// do we support a safe way of realising the original goal (raising salaries) ? +// +// using the imperative operating mode: +// +// view = table.where().less_than(salary_column,limit).find_all(); +// for (size_t i = 0; i < view.size(); ++i) { +// promote_to_write(); +// // add r.sync_if_needed(); to get reflective mode +// if (r.is_row_attached(i)) { +// Row r = view[i]; +// r.set_int(salary_column, limit); +// } +// commit_and_continue_as_write(); +// } +// +// This is safe, and we just aim for providing low level safety: is_row_attached() can tell +// if the reference is valid, and the references in the view continue to point to the +// same object at all times, also following implicit updates. The rest is up to the +// application logic. +// +// It is important to see, that there is no guarantee that all relevant employees get +// their raise in cases whith concurrent updates. At every call to promote_to_write() new +// employees may be added to the underlying table, but as the view is in imperative mode, +// these new employees are not added to the view. Also at promote_to_write() an existing +// employee could recieve a (different, larger) raise which would then be overwritten and lost. +// However, these are problems that you should expect, since the activity is spread over multiple +// transactions. + + +/// Common base class for TableView and ConstTableView. +class TableViewBase : public RowIndexes { +public: + // - not in use / implemented yet: ... explicit calls to sync_if_needed() must be used + // to get 'reflective' mode. + // enum mode { mode_Reflective, mode_Imperative }; + // void set_operating_mode(mode); + // mode get_operating_mode(); + bool is_empty() const noexcept; + + // Tells if the table that this TableView points at still exists or has been deleted. + bool is_attached() const noexcept; + + bool is_row_attached(size_t row_ndx) const noexcept; + size_t size() const noexcept; + size_t num_attached_rows() const noexcept; + + // Get the query used to create this TableView + // The query will have a null source table if this tv was not created from + // a query + const Query& get_query() const noexcept; + + // Column information + const ColumnBase& get_column_base(size_t index) const; + + size_t get_column_count() const noexcept; + StringData get_column_name(size_t column_ndx) const noexcept; + size_t get_column_index(StringData name) const; + DataType get_column_type(size_t column_ndx) const noexcept; + + // Getting values + int64_t get_int(size_t column_ndx, size_t row_ndx) const noexcept; + bool get_bool(size_t column_ndx, size_t row_ndx) const noexcept; + OldDateTime get_olddatetime(size_t column_ndx, size_t row_ndx) const noexcept; + Timestamp get_timestamp(size_t column_ndx, size_t row_ndx) const noexcept; + float get_float(size_t column_ndx, size_t row_ndx) const noexcept; + double get_double(size_t column_ndx, size_t row_ndx) const noexcept; + StringData get_string(size_t column_ndx, size_t row_ndx) const noexcept; + BinaryData get_binary(size_t column_ndx, size_t row_ndx) const noexcept; + Mixed get_mixed(size_t column_ndx, size_t row_ndx) const noexcept; + DataType get_mixed_type(size_t column_ndx, size_t row_ndx) const noexcept; + size_t get_link(size_t column_ndx, size_t row_ndx) const noexcept; + + // Links + bool is_null_link(size_t column_ndx, size_t row_ndx) const noexcept; + + // Subtables + size_t get_subtable_size(size_t column_ndx, size_t row_ndx) const noexcept; + + // Searching + template + size_t find_first(size_t column_ndx, T value) const; + + size_t find_first_int(size_t column_ndx, int64_t value) const; + size_t find_first_bool(size_t column_ndx, bool value) const; + size_t find_first_olddatetime(size_t column_ndx, OldDateTime value) const; + size_t find_first_float(size_t column_ndx, float value) const; + size_t find_first_double(size_t column_ndx, double value) const; + size_t find_first_string(size_t column_ndx, StringData value) const; + size_t find_first_binary(size_t column_ndx, BinaryData value) const; + size_t find_first_timestamp(size_t column_ndx, Timestamp value) const; + + // Aggregate functions. count_target is ignored by all except Count. Hack because of bug in optional + // arguments in clang and vs2010 (fixed in 2012) + template + R aggregate(R (ColType::*aggregateMethod)(size_t, size_t, size_t, size_t*) const, size_t column_ndx, + T count_target, size_t* return_ndx = nullptr) const; + + int64_t sum_int(size_t column_ndx) const; + int64_t maximum_int(size_t column_ndx, size_t* return_ndx = nullptr) const; + int64_t minimum_int(size_t column_ndx, size_t* return_ndx = nullptr) const; + double average_int(size_t column_ndx, size_t* value_count = nullptr) const; + size_t count_int(size_t column_ndx, int64_t target) const; + + double sum_float(size_t column_ndx) const; + float maximum_float(size_t column_ndx, size_t* return_ndx = nullptr) const; + float minimum_float(size_t column_ndx, size_t* return_ndx = nullptr) const; + double average_float(size_t column_ndx, size_t* value_count = nullptr) const; + size_t count_float(size_t column_ndx, float target) const; + + double sum_double(size_t column_ndx) const; + double maximum_double(size_t column_ndx, size_t* return_ndx = nullptr) const; + double minimum_double(size_t column_ndx, size_t* return_ndx = nullptr) const; + double average_double(size_t column_ndx, size_t* value_count = nullptr) const; + size_t count_double(size_t column_ndx, double target) const; + + OldDateTime maximum_olddatetime(size_t column_ndx, size_t* return_ndx = nullptr) const; + OldDateTime minimum_olddatetime(size_t column_ndx, size_t* return_ndx = nullptr) const; + + Timestamp minimum_timestamp(size_t column_ndx, size_t* return_ndx = nullptr) const; + Timestamp maximum_timestamp(size_t column_ndx, size_t* return_ndx = nullptr) const; + size_t count_timestamp(size_t column_ndx, Timestamp target) const; + + // Simple pivot aggregate method. Experimental! Please do not + // document method publicly. + void aggregate(size_t group_by_column, size_t aggr_column, Table::AggrType op, Table& result) const; + + // Get row index in the source table this view is "looking" at. + size_t get_source_ndx(size_t row_ndx) const noexcept; + + /// Search this view for the specified source table row (specified by its + /// index in the source table). If found, the index of that row within this + /// view is returned, otherwise `realm::not_found` is returned. + size_t find_by_source_ndx(size_t source_ndx) const noexcept; + + // Conversion + void to_json(std::ostream&) const; + void to_string(std::ostream&, size_t limit = 500) const; + void row_to_string(size_t row_ndx, std::ostream&) const; + + // Determine if the view is 'in sync' with the underlying table + // as well as other views used to generate the view. Note that updates + // through views maintains synchronization between view and table. + // It doesnt by itself maintain other views as well. So if a view + // is generated from another view (not a table), updates may cause + // that view to be outdated, AND as the generated view depends upon + // it, it too will become outdated. + bool is_in_sync() const; + + // Tells if this TableView depends on a LinkList or row that has been deleted. + bool depends_on_deleted_object() const; + + // Synchronize a view to match a table or tableview from which it + // has been derived. Synchronization is achieved by rerunning the + // query used to generate the view. If derived from another view, that + // view will be synchronized as well. + // + // "live" or "reactive" views are implemented by calling sync_if_needed + // before any of the other access-methods whenever the view may have become + // outdated. + // + // This will make the TableView empty and in sync with the highest possible table version + // if the TableView depends on an object (LinkView or row) that has been deleted. + uint_fast64_t sync_if_needed() const; + + // Sort m_row_indexes according to one column + void sort(size_t column, bool ascending = true); + + // Sort m_row_indexes according to multiple columns + void sort(SortDescriptor order); + + // Remove rows that are duplicated with respect to the column set passed as argument. + // distinct() will preserve the original order of the row pointers, also if the order is a result of sort() + // If two rows are indentical (for the given set of distinct-columns), then the last row is removed. + // You can call sync_if_needed() to update the distinct view, just like you can for a sorted view. + // Each time you call distinct() it will compound on the previous calls + void distinct(size_t column); + void distinct(DistinctDescriptor columns); + void limit(LimitDescriptor limit); + + // Replace the order of sort and distinct operations, bypassing manually + // calling sort and distinct. This is a convenience method for bindings. + void apply_descriptor_ordering(DescriptorOrdering new_ordering); + + // Gets a readable and parsable string which completely describes the sort and + // distinct operations applied to this view. + std::string get_descriptor_ordering_description() const; + + // Returns whether the rows are guaranteed to be in table order. + // This is true only of unsorted TableViews created from either: + // - Table::find_all() + // - Query::find_all() when the query is not restricted to a view. + bool is_in_table_order() const; + + virtual ~TableViewBase() noexcept; + + virtual std::unique_ptr clone() const = 0; + +protected: + // This TableView can be "born" from 4 different sources: + // - LinkView + // - Query::find_all() + // - Table::get_distinct_view() + // - Table::get_backlink_view() + // Return the version of the source it was created from. + uint64_t outside_version() const; + + void do_sync(); + + // Null if, and only if, the view is detached. + mutable TableRef m_table; + + // The link column that this view contain backlinks for. + const BacklinkColumn* m_linked_column = nullptr; + // The target row that rows in this view link to. + ConstRow m_linked_row; + + // If this TableView was created from a LinkView, then this reference points to it. Otherwise it's 0 + mutable ConstLinkViewRef m_linkview_source; + + // m_distinct_column_source != npos if this view was created from distinct values in a column of m_table. + size_t m_distinct_column_source = npos; + + // Stores the ordering criteria of applied sort and distinct operations. + DescriptorOrdering m_descriptor_ordering; + + // A valid query holds a reference to its table which must match our m_table. + // hence we can use a query with a null table reference to indicate that the view + // was NOT generated by a query, but follows a table directly. + Query m_query; + // parameters for findall, needed to rerun the query + size_t m_start; + size_t m_end; + size_t m_limit; + + mutable util::Optional m_last_seen_version; + + size_t m_num_detached_refs = 0; + /// Construct null view (no memory allocated). + TableViewBase(); + + /// Construct empty view, ready for addition of row indices. + TableViewBase(Table* parent); + TableViewBase(Table* parent, Query& query, size_t start, size_t end, size_t limit); + TableViewBase(Table* parent, size_t column, BasicRowExpr row); + TableViewBase(Table* parent, ConstLinkViewRef link_view); + + enum DistinctViewTag { DistinctView }; + TableViewBase(DistinctViewTag, Table* parent, size_t column_ndx); + + /// Copy constructor. + TableViewBase(const TableViewBase&); + + /// Move constructor. + TableViewBase(TableViewBase&&) noexcept; + + TableViewBase& operator=(const TableViewBase&); + TableViewBase& operator=(TableViewBase&&) noexcept; + + template + static R find_all_integer(V*, size_t, int64_t); + + template + static R find_all_float(V*, size_t, float); + + template + static R find_all_double(V*, size_t, double); + + template + static R find_all_string(V*, size_t, StringData); + + using HandoverPatch = TableViewHandoverPatch; + + // handover machinery entry points based on dynamic type. These methods: + // a) forward their calls to the static type entry points. + // b) new/delete patch data structures. + virtual std::unique_ptr clone_for_handover(std::unique_ptr& patch, + ConstSourcePayload mode) const = 0; + + virtual std::unique_ptr clone_for_handover(std::unique_ptr& patch, + MutableSourcePayload mode) = 0; + + void apply_and_consume_patch(std::unique_ptr& patch, Group& group) + { + apply_patch(*patch, group); + patch.reset(); + } + // handover machinery entry points based on static type + void apply_patch(HandoverPatch& patch, Group& group); + TableViewBase(const TableViewBase& source, HandoverPatch& patch, ConstSourcePayload mode); + TableViewBase(TableViewBase& source, HandoverPatch& patch, MutableSourcePayload mode); + +private: + void allocate_row_indexes(); + void detach() const noexcept; // may have to remove const + size_t find_first_integer(size_t column_ndx, int64_t value) const; + template + Timestamp minmax_timestamp(size_t column_ndx, size_t* return_ndx) const; + + friend class Table; + friend class Query; + friend class SharedGroup; + + // Called by table to adjust any row references: + void adj_row_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept; + void adj_row_acc_erase_row(size_t row_ndx) noexcept; + void adj_row_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; + void adj_row_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; + void adj_row_acc_move_row(size_t from_row_ndx, size_t to_row_ndx) noexcept; + void adj_row_acc_clear() noexcept; +}; + + +inline void TableViewBase::detach() const noexcept // may have to remove const +{ + m_table = TableRef(); +} + + +class ConstTableView; + + +enum class RemoveMode { ordered, unordered }; + + +/// A TableView gives read and write access to the parent table. +/// +/// A 'const TableView' cannot be changed (e.g. sorted), nor can the +/// parent table be modified through it. +/// +/// A TableView is both copyable and movable. +class TableView : public TableViewBase { +public: + using TableViewBase::TableViewBase; + + TableView() = default; + + // Rows + typedef BasicRowExpr
RowExpr; + typedef BasicRowExpr ConstRowExpr; + RowExpr get(size_t row_ndx) noexcept; + ConstRowExpr get(size_t row_ndx) const noexcept; + RowExpr front() noexcept; + ConstRowExpr front() const noexcept; + RowExpr back() noexcept; + ConstRowExpr back() const noexcept; + RowExpr operator[](size_t row_ndx) noexcept; + ConstRowExpr operator[](size_t row_ndx) const noexcept; + + // Setting values + void set_int(size_t column_ndx, size_t row_ndx, int64_t value); + void set_bool(size_t column_ndx, size_t row_ndx, bool value); + void set_olddatetime(size_t column_ndx, size_t row_ndx, OldDateTime value); + void set_timestamp(size_t column_ndx, size_t row_ndx, Timestamp value); + template + void set_enum(size_t column_ndx, size_t row_ndx, E value); + void set_float(size_t column_ndx, size_t row_ndx, float value); + void set_double(size_t column_ndx, size_t row_ndx, double value); + void set_string(size_t column_ndx, size_t row_ndx, StringData value); + void set_binary(size_t column_ndx, size_t row_ndx, BinaryData value); + void set_mixed(size_t column_ndx, size_t row_ndx, Mixed value); + void set_subtable(size_t column_ndx, size_t row_ndx, const Table* table); + void set_link(size_t column_ndx, size_t row_ndx, size_t target_row_ndx); + + // Subtables + TableRef get_subtable(size_t column_ndx, size_t row_ndx); + ConstTableRef get_subtable(size_t column_ndx, size_t row_ndx) const; + void clear_subtable(size_t column_ndx, size_t row_ndx); + + // Links + TableRef get_link_target(size_t column_ndx) noexcept; + ConstTableRef get_link_target(size_t column_ndx) const noexcept; + void nullify_link(size_t column_ndx, size_t row_ndx); + + /// \defgroup table_view_removes + //@{ + /// \brief Remove the specified row (or rows) from the underlying table. + /// + /// remove() removes the specified row from the underlying table, + /// remove_last() removes the last row in the table view from the underlying + /// table, and clear removes all the rows in the table view from the + /// underlying table. + /// + /// When rows are removed from the underlying table, they will by necessity + /// also be removed from the table view. + /// + /// The order of the remaining rows in the the table view will be maintained + /// regardless of the value passed for \a underlying_mode. + /// + /// \param row_ndx The index within this table view of the row to be + /// removed. + /// + /// \param underlying_mode If set to RemoveMode::ordered (the default), the + /// rows will be removed from the underlying table in a way that maintains + /// the order of the remaining rows in the underlying table. If set to + /// RemoveMode::unordered, the order of the remaining rows in the underlying + /// table will not in general be maintaind, but the operation will generally + /// be much faster. In any case, the order of remaining rows in the table + /// view will not be affected. + void remove(size_t row_ndx, RemoveMode underlying_mode = RemoveMode::ordered); + void remove_last(RemoveMode underlying_mode = RemoveMode::ordered); + void clear(RemoveMode underlying_mode = RemoveMode::ordered); + //@} + + // Searching (Int and String) + TableView find_all_int(size_t column_ndx, int64_t value); + ConstTableView find_all_int(size_t column_ndx, int64_t value) const; + TableView find_all_bool(size_t column_ndx, bool value); + ConstTableView find_all_bool(size_t column_ndx, bool value) const; + TableView find_all_olddatetime(size_t column_ndx, OldDateTime value); + ConstTableView find_all_olddatetime(size_t column_ndx, OldDateTime value) const; + TableView find_all_float(size_t column_ndx, float value); + ConstTableView find_all_float(size_t column_ndx, float value) const; + TableView find_all_double(size_t column_ndx, double value); + ConstTableView find_all_double(size_t column_ndx, double value) const; + TableView find_all_string(size_t column_ndx, StringData value); + ConstTableView find_all_string(size_t column_ndx, StringData value) const; + // FIXME: Need: TableView find_all_binary(size_t column_ndx, BinaryData value); + // FIXME: Need: ConstTableView find_all_binary(size_t column_ndx, BinaryData value) const; + + Table& get_parent() noexcept; + const Table& get_parent() const noexcept; + + std::unique_ptr clone() const override + { + return std::unique_ptr(new TableView(*this)); + } + + std::unique_ptr clone_for_handover(std::unique_ptr& patch, + ConstSourcePayload mode) const override + { + patch.reset(new HandoverPatch); + std::unique_ptr retval(new TableView(*this, *patch, mode)); + return retval; + } + + std::unique_ptr clone_for_handover(std::unique_ptr& patch, + MutableSourcePayload mode) override + { + patch.reset(new HandoverPatch); + std::unique_ptr retval(new TableView(*this, *patch, mode)); + return retval; + } + +private: + TableView(Table& parent); + TableView(Table& parent, Query& query, size_t start, size_t end, size_t limit); + TableView(Table& parent, ConstLinkViewRef); + + TableView(DistinctViewTag, Table& parent, size_t column_ndx); + + TableView find_all_integer(size_t column_ndx, int64_t value); + ConstTableView find_all_integer(size_t column_ndx, int64_t value) const; + + friend class ConstTableView; + friend class Table; + friend class Query; + friend class TableViewBase; + friend class LinkView; +}; + + +/// A ConstTableView gives read access to the parent table, but no +/// write access. The view itself, though, can be changed, for +/// example, it can be sorted. +/// +/// Note that methods are declared 'const' if, and only if they leave +/// the view unmodified, and this is irrespective of whether they +/// modify the parent table. +/// +/// A ConstTableView has both copy and move semantics. See TableView +/// for more on this. +class ConstTableView : public TableViewBase { +public: + using TableViewBase::TableViewBase; + + ConstTableView() = default; + + ConstTableView(const TableView&); + ConstTableView(TableView&&); + ConstTableView& operator=(const TableView&); + ConstTableView& operator=(TableView&&); + + // Rows + typedef BasicRowExpr ConstRowExpr; + ConstRowExpr get(size_t row_ndx) const noexcept; + ConstRowExpr front() const noexcept; + ConstRowExpr back() const noexcept; + ConstRowExpr operator[](size_t row_ndx) const noexcept; + + // Subtables + ConstTableRef get_subtable(size_t column_ndx, size_t row_ndx) const; + + // Links + ConstTableRef get_link_target(size_t column_ndx) const noexcept; + + // Searching (Int and String) + ConstTableView find_all_int(size_t column_ndx, int64_t value) const; + ConstTableView find_all_bool(size_t column_ndx, bool value) const; + ConstTableView find_all_olddatetime(size_t column_ndx, OldDateTime value) const; + ConstTableView find_all_float(size_t column_ndx, float value) const; + ConstTableView find_all_double(size_t column_ndx, double value) const; + ConstTableView find_all_string(size_t column_ndx, StringData value) const; + + const Table& get_parent() const noexcept; + + std::unique_ptr clone() const override + { + return std::unique_ptr(new ConstTableView(*this)); + } + + std::unique_ptr clone_for_handover(std::unique_ptr& patch, + ConstSourcePayload mode) const override + { + patch.reset(new HandoverPatch); + std::unique_ptr retval(new ConstTableView(*this, *patch, mode)); + return retval; + } + + std::unique_ptr clone_for_handover(std::unique_ptr& patch, + MutableSourcePayload mode) override + { + patch.reset(new HandoverPatch); + std::unique_ptr retval(new ConstTableView(*this, *patch, mode)); + return retval; + } + +private: + ConstTableView(const Table& parent); + + ConstTableView find_all_integer(size_t column_ndx, int64_t value) const; + + friend class TableView; + friend class Table; + friend class Query; + friend class TableViewBase; +}; + + +// ================================================================================================ +// TableViewBase Implementation: + +inline const Query& TableViewBase::get_query() const noexcept +{ + return m_query; +} + +inline bool TableViewBase::is_empty() const noexcept +{ + return m_row_indexes.is_empty(); +} + +inline bool TableViewBase::is_attached() const noexcept +{ + return bool(m_table); +} + +inline bool TableViewBase::is_row_attached(size_t row_ndx) const noexcept +{ + return m_row_indexes.get(row_ndx) != detached_ref; +} + +inline size_t TableViewBase::size() const noexcept +{ + return m_row_indexes.size(); +} + +inline size_t TableViewBase::num_attached_rows() const noexcept +{ + return m_row_indexes.size() - m_num_detached_refs; +} + +inline size_t TableViewBase::get_source_ndx(size_t row_ndx) const noexcept +{ + return to_size_t(m_row_indexes.get(row_ndx)); +} + +inline size_t TableViewBase::find_by_source_ndx(size_t source_ndx) const noexcept +{ + REALM_ASSERT(source_ndx < m_table->size()); + return m_row_indexes.find_first(source_ndx); +} + +inline void TableViewBase::allocate_row_indexes() +{ + // FIXME: This code is unreasonably complicated because it uses `IntegerColumn` as + // a free-standing container, and beause `IntegerColumn` does not conform to the + // RAII idiom (nor should it). + Allocator& alloc = m_row_indexes.get_alloc(); + _impl::DeepArrayRefDestroyGuard ref_guard(alloc); + ref_guard.reset(IntegerColumn::create(alloc)); // Throws + m_table->register_view(this); // Throws + m_row_indexes.init_from_ref(alloc, ref_guard.release()); +} + +inline TableViewBase::TableViewBase() + : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) // Throws +{ + ref_type ref = IntegerColumn::create(m_row_indexes.get_alloc()); // Throws + m_row_indexes.get_root_array()->init_from_ref(ref); +} + +inline TableViewBase::TableViewBase(Table* parent) + : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) + , m_table(parent->get_table_ref()) // Throws + , m_last_seen_version(m_table ? util::make_optional(m_table->m_version) : util::none) +{ + allocate_row_indexes(); +} + +inline TableViewBase::TableViewBase(Table* parent, Query& query, size_t start, size_t end, size_t limit) + : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) // Throws + , m_table(parent->get_table_ref()) + , m_query(query) + , m_start(start) + , m_end(end) + , m_limit(limit) + , m_last_seen_version(outside_version()) +{ + allocate_row_indexes(); +} + +inline TableViewBase::TableViewBase(Table* parent, size_t column, BasicRowExpr row) + : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) + , m_table(parent->get_table_ref()) // Throws + , m_linked_column(&parent->get_column_link_base(column).get_backlink_column()) + , m_linked_row(row) + , m_last_seen_version(m_table ? util::make_optional(m_table->m_version) : util::none) +{ + allocate_row_indexes(); +} + +inline TableViewBase::TableViewBase(DistinctViewTag, Table* parent, size_t column_ndx) + : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) + , m_table(parent->get_table_ref()) // Throws + , m_distinct_column_source(column_ndx) + , m_last_seen_version(m_table ? util::make_optional(m_table->m_version) : util::none) +{ + REALM_ASSERT(m_distinct_column_source != npos); + + allocate_row_indexes(); +} + +inline TableViewBase::TableViewBase(Table* parent, ConstLinkViewRef link_view) + : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) + , m_table(parent->get_table_ref()) // Throws + , m_linkview_source(std::move(link_view)) + , m_last_seen_version(m_table ? util::make_optional(m_table->m_version) : util::none) +{ + REALM_ASSERT(m_linkview_source); + + allocate_row_indexes(); +} + +inline TableViewBase::TableViewBase(const TableViewBase& tv) + : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) + , m_table(tv.m_table) + , m_linked_column(tv.m_linked_column) + , m_linked_row(tv.m_linked_row) + , m_linkview_source(tv.m_linkview_source) + , m_distinct_column_source(tv.m_distinct_column_source) + , m_descriptor_ordering(std::move(tv.m_descriptor_ordering)) + , m_query(tv.m_query) + , m_start(tv.m_start) + , m_end(tv.m_end) + , m_limit(tv.m_limit) + , m_last_seen_version(tv.m_last_seen_version) + , m_num_detached_refs(tv.m_num_detached_refs) +{ + // FIXME: This code is unreasonably complicated because it uses `IntegerColumn` as + // a free-standing container, and because `IntegerColumn` does not conform to the + // RAII idiom (nor should it). + Allocator& alloc = m_row_indexes.get_alloc(); + MemRef mem = tv.m_row_indexes.get_root_array()->clone_deep(alloc); // Throws + _impl::DeepArrayRefDestroyGuard ref_guard(mem.get_ref(), alloc); + if (m_table) + m_table->register_view(this); // Throws + m_row_indexes.init_from_mem(alloc, mem); + ref_guard.release(); + RowIndexes::m_limit_count = tv.m_limit_count; +} + +inline TableViewBase::TableViewBase(TableViewBase&& tv) noexcept + : RowIndexes(std::move(tv.m_row_indexes)) + , m_table(std::move(tv.m_table)) + , m_linked_column(tv.m_linked_column) + , m_linked_row(tv.m_linked_row) + , m_linkview_source(std::move(tv.m_linkview_source)) + , m_distinct_column_source(tv.m_distinct_column_source) + , m_descriptor_ordering(std::move(tv.m_descriptor_ordering)) + , m_query(std::move(tv.m_query)) + , m_start(tv.m_start) + , m_end(tv.m_end) + , m_limit(tv.m_limit) + , + // if we are created from a table view which is outdated, take care to use the outdated + // version number so that we can later trigger a sync if needed. + m_last_seen_version(tv.m_last_seen_version) + , m_num_detached_refs(tv.m_num_detached_refs) +{ + RowIndexes::m_limit_count = tv.m_limit_count; + if (m_table) + m_table->move_registered_view(&tv, this); +} + +inline TableViewBase::~TableViewBase() noexcept +{ + if (m_table) { + m_table->unregister_view(this); + m_table = TableRef(); + } + m_row_indexes.destroy(); // Shallow +} + +inline TableViewBase& TableViewBase::operator=(TableViewBase&& tv) noexcept +{ + if (m_table) + m_table->unregister_view(this); + m_table = std::move(tv.m_table); + if (m_table) + m_table->move_registered_view(&tv, this); + + m_row_indexes.move_assign(tv.m_row_indexes); + m_limit_count = tv.m_limit_count; + m_query = std::move(tv.m_query); + m_num_detached_refs = tv.m_num_detached_refs; + m_last_seen_version = tv.m_last_seen_version; + m_start = tv.m_start; + m_end = tv.m_end; + m_limit = tv.m_limit; + m_linked_column = tv.m_linked_column; + m_linked_row = tv.m_linked_row; + m_linkview_source = std::move(tv.m_linkview_source); + m_descriptor_ordering = std::move(tv.m_descriptor_ordering); + m_distinct_column_source = tv.m_distinct_column_source; + + return *this; +} + +inline TableViewBase& TableViewBase::operator=(const TableViewBase& tv) +{ + if (this == &tv) + return *this; + + if (m_table != tv.m_table) { + if (m_table) + m_table->unregister_view(this); + m_table = tv.m_table; + if (m_table) + m_table->register_view(this); + } + + Allocator& alloc = m_row_indexes.get_alloc(); + MemRef mem = tv.m_row_indexes.get_root_array()->clone_deep(alloc); // Throws + _impl::DeepArrayRefDestroyGuard ref_guard(mem.get_ref(), alloc); + m_row_indexes.destroy(); + m_row_indexes.get_root_array()->init_from_mem(mem); + ref_guard.release(); + m_limit_count = tv.m_limit_count; + + m_query = tv.m_query; + m_num_detached_refs = tv.m_num_detached_refs; + m_last_seen_version = tv.m_last_seen_version; + m_start = tv.m_start; + m_end = tv.m_end; + m_limit = tv.m_limit; + m_linked_column = tv.m_linked_column; + m_linked_row = tv.m_linked_row; + m_linkview_source = tv.m_linkview_source; + m_descriptor_ordering = tv.m_descriptor_ordering; + m_distinct_column_source = tv.m_distinct_column_source; + + return *this; +} + +#define REALM_ASSERT_COLUMN(column_ndx) \ + REALM_ASSERT(m_table); \ + REALM_ASSERT(column_ndx < m_table->get_column_count()) + +#define REALM_ASSERT_ROW(row_ndx) \ + REALM_ASSERT(m_table); \ + REALM_ASSERT(row_ndx < m_row_indexes.size()) + +#define REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, column_type) \ + REALM_ASSERT_COLUMN(column_ndx); \ + REALM_DIAG_PUSH(); \ + REALM_DIAG_IGNORE_TAUTOLOGICAL_COMPARE(); \ + REALM_ASSERT(m_table->get_column_type(column_ndx) == column_type || \ + (m_table->get_column_type(column_ndx) == type_OldDateTime && column_type == type_Int)); \ + REALM_DIAG_POP() + +#define REALM_ASSERT_INDEX(column_ndx, row_ndx) \ + REALM_ASSERT_COLUMN(column_ndx); \ + REALM_ASSERT(row_ndx < m_row_indexes.size()) + +#define REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, column_type) \ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, column_type); \ + REALM_ASSERT(row_ndx < m_row_indexes.size()) + +#define REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx) \ + REALM_ASSERT_COLUMN(column_ndx); \ + REALM_DIAG_PUSH(); \ + REALM_DIAG_IGNORE_TAUTOLOGICAL_COMPARE(); \ + REALM_ASSERT(m_table->get_column_type(column_ndx) == type_Table || \ + (m_table->get_column_type(column_ndx) == type_Mixed)); \ + REALM_DIAG_POP(); \ + REALM_ASSERT(row_ndx < m_row_indexes.size()) + +// Column information + +inline const ColumnBase& TableViewBase::get_column_base(size_t index) const +{ + return m_table->get_column_base(index); +} + +inline size_t TableViewBase::get_column_count() const noexcept +{ + REALM_ASSERT(m_table); + return m_table->get_column_count(); +} + +inline StringData TableViewBase::get_column_name(size_t column_ndx) const noexcept +{ + REALM_ASSERT(m_table); + return m_table->get_column_name(column_ndx); +} + +inline size_t TableViewBase::get_column_index(StringData name) const +{ + REALM_ASSERT(m_table); + return m_table->get_column_index(name); +} + +inline DataType TableViewBase::get_column_type(size_t column_ndx) const noexcept +{ + REALM_ASSERT(m_table); + return m_table->get_column_type(column_ndx); +} + + +// Getters + + +inline int64_t TableViewBase::get_int(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX(column_ndx, row_ndx); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_int(column_ndx, to_size_t(real_ndx)); +} + +inline bool TableViewBase::get_bool(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Bool); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_bool(column_ndx, to_size_t(real_ndx)); +} + +inline OldDateTime TableViewBase::get_olddatetime(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_OldDateTime); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_olddatetime(column_ndx, to_size_t(real_ndx)); +} + +inline Timestamp TableViewBase::get_timestamp(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Timestamp); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_timestamp(column_ndx, to_size_t(real_ndx)); +} + +inline float TableViewBase::get_float(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Float); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_float(column_ndx, to_size_t(real_ndx)); +} + +inline double TableViewBase::get_double(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Double); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_double(column_ndx, to_size_t(real_ndx)); +} + +inline StringData TableViewBase::get_string(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_String); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_string(column_ndx, to_size_t(real_ndx)); +} + +inline BinaryData TableViewBase::get_binary(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Binary); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_binary(column_ndx, to_size_t(real_ndx)); +} + +inline Mixed TableViewBase::get_mixed(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Mixed); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_mixed(column_ndx, to_size_t(real_ndx)); +} + +inline DataType TableViewBase::get_mixed_type(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Mixed); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_mixed_type(column_ndx, to_size_t(real_ndx)); +} + +inline size_t TableViewBase::get_subtable_size(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_subtable_size(column_ndx, to_size_t(real_ndx)); +} + +inline size_t TableViewBase::get_link(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Link); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_link(column_ndx, to_size_t(real_ndx)); +} + +inline TableRef TableView::get_link_target(size_t column_ndx) noexcept +{ + return m_table->get_link_target(column_ndx); +} + +inline ConstTableRef TableView::get_link_target(size_t column_ndx) const noexcept +{ + return m_table->get_link_target(column_ndx); +} + +inline ConstTableRef ConstTableView::get_link_target(size_t column_ndx) const noexcept +{ + return m_table->get_link_target(column_ndx); +} + +inline bool TableViewBase::is_null_link(size_t column_ndx, size_t row_ndx) const noexcept +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Link); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->is_null_link(column_ndx, to_size_t(real_ndx)); +} + + +// Searching + + +inline size_t TableViewBase::find_first_int(size_t column_ndx, int64_t value) const +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Int); + return find_first_integer(column_ndx, value); +} + +inline size_t TableViewBase::find_first_bool(size_t column_ndx, bool value) const +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Bool); + return find_first_integer(column_ndx, value ? 1 : 0); +} + +inline size_t TableViewBase::find_first_olddatetime(size_t column_ndx, OldDateTime value) const +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_OldDateTime); + return find_first_integer(column_ndx, int64_t(value.get_olddatetime())); +} + +inline size_t TableViewBase::find_first_integer(size_t column_ndx, int64_t value) const +{ + return find_first(column_ndx, value); +} + +inline size_t TableViewBase::find_first_float(size_t column_ndx, float value) const +{ + return find_first(column_ndx, value); +} + +inline size_t TableViewBase::find_first_double(size_t column_ndx, double value) const +{ + return find_first(column_ndx, value); +} + +inline size_t TableViewBase::find_first_string(size_t column_ndx, StringData value) const +{ + return find_first(column_ndx, value); +} + +inline size_t TableViewBase::find_first_binary(size_t column_ndx, BinaryData value) const +{ + return find_first(column_ndx, value); +} + +inline size_t TableViewBase::find_first_timestamp(size_t column_ndx, Timestamp value) const +{ + return find_first(column_ndx, value); +} + + +template +R TableViewBase::find_all_integer(V* view, size_t column_ndx, int64_t value) +{ + typedef typename std::remove_const::type TNonConst; + return view->m_table->where(const_cast(view)).equal(column_ndx, value).find_all(); +} + +template +R TableViewBase::find_all_float(V* view, size_t column_ndx, float value) +{ + typedef typename std::remove_const::type TNonConst; + return view->m_table->where(const_cast(view)).equal(column_ndx, value).find_all(); +} + +template +R TableViewBase::find_all_double(V* view, size_t column_ndx, double value) +{ + typedef typename std::remove_const::type TNonConst; + return view->m_table->where(const_cast(view)).equal(column_ndx, value).find_all(); +} + +template +R TableViewBase::find_all_string(V* view, size_t column_ndx, StringData value) +{ + typedef typename std::remove_const::type TNonConst; + return view->m_table->where(const_cast(view)).equal(column_ndx, value).find_all(); +} + + +//-------------------------- TableView, ConstTableView implementation: + +inline ConstTableView::ConstTableView(const TableView& tv) + : TableViewBase(tv) +{ +} + +inline ConstTableView::ConstTableView(TableView&& tv) + : TableViewBase(std::move(tv)) +{ +} + +inline void TableView::remove_last(RemoveMode underlying_mode) +{ + if (!is_empty()) + remove(size() - 1, underlying_mode); +} + +inline Table& TableView::get_parent() noexcept +{ + return *m_table; +} + +inline const Table& TableView::get_parent() const noexcept +{ + return *m_table; +} + +inline const Table& ConstTableView::get_parent() const noexcept +{ + return *m_table; +} + +inline TableView::TableView(Table& parent) + : TableViewBase(&parent) +{ +} + +inline TableView::TableView(Table& parent, Query& query, size_t start, size_t end, size_t limit) + : TableViewBase(&parent, query, start, end, limit) +{ +} + +inline TableView::TableView(Table& parent, ConstLinkViewRef link_view) +: TableViewBase(&parent, std::move(link_view)) +{ +} + +inline TableView::TableView(TableViewBase::DistinctViewTag, Table& parent, size_t column_ndx) + : TableViewBase(TableViewBase::DistinctView, &parent, column_ndx) +{ +} + +inline ConstTableView::ConstTableView(const Table& parent) + : TableViewBase(const_cast(&parent)) +{ +} + +inline ConstTableView& ConstTableView::operator=(const TableView& tv) +{ + TableViewBase::operator=(tv); + return *this; +} + +inline ConstTableView& ConstTableView::operator=(TableView&& tv) +{ + TableViewBase::operator=(std::move(tv)); + return *this; +} + + +// - string +inline TableView TableView::find_all_string(size_t column_ndx, StringData value) +{ + return TableViewBase::find_all_string(this, column_ndx, value); +} + +inline ConstTableView TableView::find_all_string(size_t column_ndx, StringData value) const +{ + return TableViewBase::find_all_string(this, column_ndx, value); +} + +inline ConstTableView ConstTableView::find_all_string(size_t column_ndx, StringData value) const +{ + return TableViewBase::find_all_string(this, column_ndx, value); +} + +// - float +inline TableView TableView::find_all_float(size_t column_ndx, float value) +{ + return TableViewBase::find_all_float(this, column_ndx, value); +} + +inline ConstTableView TableView::find_all_float(size_t column_ndx, float value) const +{ + return TableViewBase::find_all_float(this, column_ndx, value); +} + +inline ConstTableView ConstTableView::find_all_float(size_t column_ndx, float value) const +{ + return TableViewBase::find_all_float(this, column_ndx, value); +} + + +// - double +inline TableView TableView::find_all_double(size_t column_ndx, double value) +{ + return TableViewBase::find_all_double(this, column_ndx, value); +} + +inline ConstTableView TableView::find_all_double(size_t column_ndx, double value) const +{ + return TableViewBase::find_all_double(this, column_ndx, value); +} + +inline ConstTableView ConstTableView::find_all_double(size_t column_ndx, double value) const +{ + return TableViewBase::find_all_double(this, column_ndx, value); +} + + +// -- 3 variants of the 3 find_all_{int, bool, date} all based on integer + +inline TableView TableView::find_all_integer(size_t column_ndx, int64_t value) +{ + return TableViewBase::find_all_integer(this, column_ndx, value); +} + +inline ConstTableView TableView::find_all_integer(size_t column_ndx, int64_t value) const +{ + return TableViewBase::find_all_integer(this, column_ndx, value); +} + +inline ConstTableView ConstTableView::find_all_integer(size_t column_ndx, int64_t value) const +{ + return TableViewBase::find_all_integer(this, column_ndx, value); +} + + +inline TableView TableView::find_all_int(size_t column_ndx, int64_t value) +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Int); + return find_all_integer(column_ndx, value); +} + +inline TableView TableView::find_all_bool(size_t column_ndx, bool value) +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Bool); + return find_all_integer(column_ndx, value ? 1 : 0); +} + +inline TableView TableView::find_all_olddatetime(size_t column_ndx, OldDateTime value) +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_OldDateTime); + return find_all_integer(column_ndx, int64_t(value.get_olddatetime())); +} + + +inline ConstTableView TableView::find_all_int(size_t column_ndx, int64_t value) const +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Int); + return find_all_integer(column_ndx, value); +} + +inline ConstTableView TableView::find_all_bool(size_t column_ndx, bool value) const +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Bool); + return find_all_integer(column_ndx, value ? 1 : 0); +} + +inline ConstTableView TableView::find_all_olddatetime(size_t column_ndx, OldDateTime value) const +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_OldDateTime); + return find_all_integer(column_ndx, int64_t(value.get_olddatetime())); +} + + +inline ConstTableView ConstTableView::find_all_int(size_t column_ndx, int64_t value) const +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Int); + return find_all_integer(column_ndx, value); +} + +inline ConstTableView ConstTableView::find_all_bool(size_t column_ndx, bool value) const +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Bool); + return find_all_integer(column_ndx, value ? 1 : 0); +} + +inline ConstTableView ConstTableView::find_all_olddatetime(size_t column_ndx, OldDateTime value) const +{ + REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_OldDateTime); + return find_all_integer(column_ndx, int64_t(value.get_olddatetime())); +} + + +// Rows + + +inline TableView::RowExpr TableView::get(size_t row_ndx) noexcept +{ + REALM_ASSERT_ROW(row_ndx); + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get(to_size_t(real_ndx)); +} + +inline TableView::ConstRowExpr TableView::get(size_t row_ndx) const noexcept +{ + REALM_ASSERT_ROW(row_ndx); + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get(to_size_t(real_ndx)); +} + +inline ConstTableView::ConstRowExpr ConstTableView::get(size_t row_ndx) const noexcept +{ + REALM_ASSERT_ROW(row_ndx); + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get(to_size_t(real_ndx)); +} + +inline TableView::RowExpr TableView::front() noexcept +{ + return get(0); +} + +inline TableView::ConstRowExpr TableView::front() const noexcept +{ + return get(0); +} + +inline ConstTableView::ConstRowExpr ConstTableView::front() const noexcept +{ + return get(0); +} + +inline TableView::RowExpr TableView::back() noexcept +{ + size_t last_row_ndx = size() - 1; + return get(last_row_ndx); +} + +inline TableView::ConstRowExpr TableView::back() const noexcept +{ + size_t last_row_ndx = size() - 1; + return get(last_row_ndx); +} + +inline ConstTableView::ConstRowExpr ConstTableView::back() const noexcept +{ + size_t last_row_ndx = size() - 1; + return get(last_row_ndx); +} + +inline TableView::RowExpr TableView::operator[](size_t row_ndx) noexcept +{ + return get(row_ndx); +} + +inline TableView::ConstRowExpr TableView::operator[](size_t row_ndx) const noexcept +{ + return get(row_ndx); +} + +inline ConstTableView::ConstRowExpr ConstTableView::operator[](size_t row_ndx) const noexcept +{ + return get(row_ndx); +} + + +// Subtables + + +inline TableRef TableView::get_subtable(size_t column_ndx, size_t row_ndx) +{ + REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_subtable(column_ndx, to_size_t(real_ndx)); +} + +inline ConstTableRef TableView::get_subtable(size_t column_ndx, size_t row_ndx) const +{ + REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_subtable(column_ndx, to_size_t(real_ndx)); +} + +inline ConstTableRef ConstTableView::get_subtable(size_t column_ndx, size_t row_ndx) const +{ + REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->get_subtable(column_ndx, to_size_t(real_ndx)); +} + +inline void TableView::clear_subtable(size_t column_ndx, size_t row_ndx) +{ + REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + return m_table->clear_subtable(column_ndx, to_size_t(real_ndx)); +} + + +// Setters + + +inline void TableView::set_int(size_t column_ndx, size_t row_ndx, int64_t value) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Int); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_int(column_ndx, to_size_t(real_ndx), value); +} + +inline void TableView::set_bool(size_t column_ndx, size_t row_ndx, bool value) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Bool); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_bool(column_ndx, to_size_t(real_ndx), value); +} + +inline void TableView::set_olddatetime(size_t column_ndx, size_t row_ndx, OldDateTime value) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_OldDateTime); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_olddatetime(column_ndx, to_size_t(real_ndx), value); +} + +inline void TableView::set_timestamp(size_t column_ndx, size_t row_ndx, Timestamp value) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Timestamp); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_timestamp(column_ndx, to_size_t(real_ndx), value); +} + +inline void TableView::set_float(size_t column_ndx, size_t row_ndx, float value) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Float); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_float(column_ndx, to_size_t(real_ndx), value); +} + +inline void TableView::set_double(size_t column_ndx, size_t row_ndx, double value) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Double); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_double(column_ndx, to_size_t(real_ndx), value); +} + +template +inline void TableView::set_enum(size_t column_ndx, size_t row_ndx, E value) +{ + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_int(column_ndx, real_ndx, value); +} + +inline void TableView::set_string(size_t column_ndx, size_t row_ndx, StringData value) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_String); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_string(column_ndx, to_size_t(real_ndx), value); +} + +inline void TableView::set_binary(size_t column_ndx, size_t row_ndx, BinaryData value) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Binary); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_binary(column_ndx, to_size_t(real_ndx), value); +} + +inline void TableView::set_mixed(size_t column_ndx, size_t row_ndx, Mixed value) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Mixed); + + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_mixed(column_ndx, to_size_t(real_ndx), value); +} + +inline void TableView::set_subtable(size_t column_ndx, size_t row_ndx, const Table* value) +{ + REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_subtable(column_ndx, to_size_t(real_ndx), value); +} + +inline void TableView::set_link(size_t column_ndx, size_t row_ndx, size_t target_row_ndx) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Link); + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->set_link(column_ndx, to_size_t(real_ndx), target_row_ndx); +} + +inline void TableView::nullify_link(size_t column_ndx, size_t row_ndx) +{ + REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Link); + const int64_t real_ndx = m_row_indexes.get(row_ndx); + REALM_ASSERT(real_ndx != detached_ref); + m_table->nullify_link(column_ndx, to_size_t(real_ndx)); +} + +} // namespace realm + +#endif // REALM_TABLE_VIEW_HPP diff --git a/Pods/Realm/include/core/realm/timestamp.hpp b/Pods/Realm/include/core/realm/timestamp.hpp new file mode 100644 index 0000000000..1e847e4698 --- /dev/null +++ b/Pods/Realm/include/core/realm/timestamp.hpp @@ -0,0 +1,167 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_TIMESTAMP_HPP +#define REALM_TIMESTAMP_HPP + +#include +#include +#include +#include + +namespace realm { + +class Timestamp { +public: + // Construct from the number of seconds and nanoseconds since the UNIX epoch: 00:00:00 UTC on 1 January 1970 + // + // To split a native nanosecond representation, only division and modulo are necessary: + // + // s = native_nano / nanoseconds_per_second + // n = native_nano % nanoseconds_per_second + // Timestamp ts(s, n); + // + // To convert back into native nanosecond representation, simple multiply and add: + // + // native_nano = ts.s * nanoseconds_per_second + ts.n + // + // Specifically this allows the nanosecond part to become negative (only) for Timestamps before the UNIX epoch. + // Usually this will not need special attention, but for reference, valid Timestamps will have one of the + // following sign combinations: + // + // s | n + // ----- + // + | + + // + | 0 + // 0 | + + // 0 | 0 + // 0 | - + // - | 0 + // - | - + // + // Examples: + // The UNIX epoch is constructed by Timestamp(0, 0) + // Relative times are constructed as follows: + // +1 second is constructed by Timestamp(1, 0) + // +1 nanosecond is constructed by Timestamp(0, 1) + // +1.1 seconds (1100 milliseconds after the epoch) is constructed by Timestamp(1, 100000000) + // -1.1 seconds (1100 milliseconds before the epoch) is constructed by Timestamp(-1, -100000000) + // + Timestamp(int64_t seconds, int32_t nanoseconds) + : m_seconds(seconds) + , m_nanoseconds(nanoseconds) + , m_is_null(false) + { + REALM_ASSERT_EX(-nanoseconds_per_second < nanoseconds && nanoseconds < nanoseconds_per_second, nanoseconds); + const bool both_non_negative = seconds >= 0 && nanoseconds >= 0; + const bool both_non_positive = seconds <= 0 && nanoseconds <= 0; + REALM_ASSERT_EX(both_non_negative || both_non_positive, both_non_negative, both_non_positive); + } + Timestamp(realm::null) + : m_is_null(true) + { + } + Timestamp() + : Timestamp(null{}) + { + } + + bool is_null() const + { + return m_is_null; + } + + int64_t get_seconds() const noexcept + { + REALM_ASSERT(!m_is_null); + return m_seconds; + } + + int32_t get_nanoseconds() const noexcept + { + REALM_ASSERT(!m_is_null); + return m_nanoseconds; + } + + // Note that only == and != operators work if one of the Timestamps are null! Else use realm::Greater, + // realm::Less, etc, instead. This is in order to collect all treatment of null behaviour in a single place for all + // types (query_conditions.hpp) to ensure that all types sort and compare null vs. non-null in the same manner, + // especially for int/float where we cannot override operators. This design is open for discussion, though, + // because it has usability drawbacks + bool operator==(const Timestamp& rhs) const + { + if (is_null() && rhs.is_null()) + return true; + + if (is_null() != rhs.is_null()) + return false; + + return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; + } + bool operator!=(const Timestamp& rhs) const + { + return !(*this == rhs); + } + bool operator>(const Timestamp& rhs) const + { + REALM_ASSERT(!is_null()); + REALM_ASSERT(!rhs.is_null()); + return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); + } + bool operator<(const Timestamp& rhs) const + { + REALM_ASSERT(!is_null()); + REALM_ASSERT(!rhs.is_null()); + return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); + } + bool operator<=(const Timestamp& rhs) const + { + REALM_ASSERT(!is_null()); + REALM_ASSERT(!rhs.is_null()); + return *this < rhs || *this == rhs; + } + bool operator>=(const Timestamp& rhs) const + { + REALM_ASSERT(!is_null()); + REALM_ASSERT(!rhs.is_null()); + return *this > rhs || *this == rhs; + } + Timestamp& operator=(const Timestamp& rhs) = default; + + template + friend std::basic_ostream& operator<<(std::basic_ostream& out, const Timestamp&); + static constexpr int32_t nanoseconds_per_second = 1000000000; + +private: + int64_t m_seconds; + int32_t m_nanoseconds; + bool m_is_null; +}; + +// LCOV_EXCL_START +template +inline std::basic_ostream& operator<<(std::basic_ostream& out, const Timestamp& d) +{ + out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")"; + return out; +} +// LCOV_EXCL_STOP + +} // namespace realm + +#endif // REALM_TIMESTAMP_HPP diff --git a/Pods/Realm/include/core/realm/unicode.hpp b/Pods/Realm/include/core/realm/unicode.hpp new file mode 100644 index 0000000000..d8b3d33901 --- /dev/null +++ b/Pods/Realm/include/core/realm/unicode.hpp @@ -0,0 +1,163 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UNICODE_HPP +#define REALM_UNICODE_HPP + +#include +#include +#include + +#include +#include +#include + + +namespace realm { + +enum string_compare_method_t { + STRING_COMPARE_CORE, + STRING_COMPARE_CPP11, + STRING_COMPARE_CALLBACK, + STRING_COMPARE_CORE_SIMILAR +}; + +extern StringCompareCallback string_compare_callback; +extern string_compare_method_t string_compare_method; + +// Description for set_string_compare_method(): +// +// Short summary: iOS language binding: call +// set_string_compare_method() for fast but slightly inaccurate sort in some countries, or +// set_string_compare_method(2, callbackptr) for slow but precise sort (see callbackptr below) +// +// Different countries ('locales') have different sorting order for strings and letters. Because there unfortunatly +// doesn't exist any unified standardized way to compare strings in C++ on multiple platforms, we need this method. +// +// It determins how sorting a TableView by a String column must take place. The 'method' argument can be: +// +// 0: Fast core-only compare (no OS/framework calls). LIMITATIONS: Works only upto 'Latin Extended 2' (unicodes +// 0...591). Also, sorting order is according to 'en_US' so it may be slightly inaccurate for some countries. +// 'callback' argument is ignored. +// +// Return value: Always 'true' +// +// 1: Native C++11 method if core is compiled as C++11. Gives precise sorting according +// to user's current locale. LIMITATIONS: Currently works only on Windows and on Linux with clang. Does NOT work on +// iOS (due to only 'C' locale being available in CoreFoundation, which puts 'Z' before 'a'). Unknown if works on +// Windows Phone / Android. Furthermore it does NOT work on Linux with gcc 4.7 or 4.8 (lack of c++11 feature that +// can convert utf8->wstring without calls to setlocale()). +// +// Return value: 'true' if supported, otherwise 'false' (if so, then previous setting, if any, is preserved). +// +// 2: Callback method. Language binding / C++ user must provide a utf-8 callback method of prototype: +// bool callback(const char* string1, const char* string2) where 'callback' must return bool(string1 < string2). +// +// Return value: Always 'true' +// +// Default is method = 0 if the function is never called +// +// NOT THREAD SAFE! Call once during initialization or make sure it's not called simultaneously with different +// arguments. The setting is remembered per-process; it does NOT need to be called prior to each sort +bool set_string_compare_method(string_compare_method_t method, StringCompareCallback callback); + + +// Return size in bytes of utf8 character. No error checking +size_t sequence_length(char lead); + +// Limitations for case insensitive string search +// Case insensitive search (equal, begins_with, ends_with, like and contains) +// only works for unicodes 0...0x7f which is the same as the 0...127 +// ASCII character set (letters a-z and A-Z). + +// In does *not* work for the 0...255 ANSI character set that contains +// characters from many European countries like Germany, France, Denmark, +// etc. + +// It also does not work for characters from non-western countries like +// Japan, Russia, Arabia, etc. + +// If there exists characters outside the ASCII range either in the text +// to be searched for, or in the Realm string column which is searched +// in, then the compare yields a random result such that the row may or +// may not be included in the result set. + +// Return bool(string1 < string2) +bool utf8_compare(StringData string1, StringData string2); + +// Return unicode value of character. +uint32_t utf8value(const char* character); + +inline bool equal_sequence(const char*& begin, const char* end, const char* begin2); + +// FIXME: The current approach to case insensitive comparison requires +// that case mappings can be done in a way that does not change he +// number of bytes used to encode the individual Unicode +// character. This is not generally the case, so, as far as I can see, +// this approach has no future. +// +// FIXME: The current approach to case insensitive comparison relies +// on checking each "haystack" character against the corresponding +// character in both a lower cased and an upper cased version of the +// "needle". While this leads to efficient comparison, it ignores the +// fact that "case folding" is the only correct approach to case +// insensitive comparison in a locale agnostic Unicode +// environment. +// +// See +// http://www.w3.org/International/wiki/Case_folding +// http://userguide.icu-project.org/transforms/casemappings#TOC-Case-Folding. +// +// The ideal API would probably be something like this: +// +// case_fold: utf_8 -> case_folded +// equal_case_fold: (needle_case_folded, single_haystack_entry_utf_8) -> found +// search_case_fold: (needle_case_folded, huge_haystack_string_utf_8) -> found_at_position +// +// The case folded form would probably be using UTF-32 or UTF-16. + + +/// If successful, returns a string of the same size as \a source. +/// Returns none if invalid UTF-8 encoding was encountered. +util::Optional case_map(StringData source, bool upper); + +enum IgnoreErrorsTag { IgnoreErrors }; +std::string case_map(StringData source, bool upper, IgnoreErrorsTag); + +/// Assumes that the sizes of \a needle_upper and \a needle_lower are +/// identical to the size of \a haystack. Returns false if the needle +/// is different from the haystack. +bool equal_case_fold(StringData haystack, const char* needle_upper, const char* needle_lower); + +/// Assumes that the sizes of \a needle_upper and \a needle_lower are +/// both equal to \a needle_size. Returns haystack.size() if the +/// needle was not found. +size_t search_case_fold(StringData haystack, const char* needle_upper, const char* needle_lower, size_t needle_size); + +/// Assumes that the sizes of \a needle_upper and \a needle_lower are +/// both equal to \a needle_size. Returns false if the +/// needle was not found. +bool contains_ins(StringData haystack, const char* needle_upper, const char* needle_lower, size_t needle_size, const std::array &charmap); + +/// Case insensitive wildcard matching ('?' for single char, '*' for zero or more chars) +bool string_like_ins(StringData text, StringData pattern) noexcept; +bool string_like_ins(StringData text, StringData upper, StringData lower) noexcept; + +} // namespace realm + +#endif // REALM_UNICODE_HPP diff --git a/Pods/Realm/include/core/realm/util/aes_cryptor.hpp b/Pods/Realm/include/core/realm/util/aes_cryptor.hpp new file mode 100644 index 0000000000..86adb96c97 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/aes_cryptor.hpp @@ -0,0 +1,101 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#if REALM_ENABLE_ENCRYPTION + +#if REALM_PLATFORM_APPLE +#include +#elif defined(_WIN32) +#include +#include +#include +#pragma comment(lib, "bcrypt.lib") +#else +#include +#include +#endif + +namespace realm { +namespace util { + +struct iv_table; +class EncryptedFileMapping; + +class AESCryptor { +public: + AESCryptor(const uint8_t* key); + ~AESCryptor() noexcept; + + void set_file_size(off_t new_size); + + bool read(FileDesc fd, off_t pos, char* dst, size_t size); + void write(FileDesc fd, off_t pos, const char* src, size_t size) noexcept; + +private: + enum EncryptionMode { +#if REALM_PLATFORM_APPLE + mode_Encrypt = kCCEncrypt, + mode_Decrypt = kCCDecrypt +#elif defined(_WIN32) + mode_Encrypt = 0, + mode_Decrypt = 1 +#else + mode_Encrypt = AES_ENCRYPT, + mode_Decrypt = AES_DECRYPT +#endif + }; + +#if REALM_PLATFORM_APPLE + CCCryptorRef m_encr; + CCCryptorRef m_decr; +#elif defined(_WIN32) + BCRYPT_KEY_HANDLE m_aes_key_handle; +#else + AES_KEY m_ectx; + AES_KEY m_dctx; +#endif + + uint8_t m_hmacKey[32]; + std::vector m_iv_buffer; + std::unique_ptr m_rw_buffer; + std::unique_ptr m_dst_buffer; + + void calc_hmac(const void* src, size_t len, uint8_t* dst, const uint8_t* key) const; + bool check_hmac(const void* data, size_t len, const uint8_t* hmac) const; + void crypt(EncryptionMode mode, off_t pos, char* dst, const char* src, const char* stored_iv) noexcept; + iv_table& get_iv_table(FileDesc fd, off_t data_pos) noexcept; +}; + +struct SharedFileInfo { + FileDesc fd; + AESCryptor cryptor; + std::vector mappings; + + SharedFileInfo(const uint8_t* key, FileDesc file_descriptor); +}; +} +} + +#endif // REALM_ENABLE_ENCRYPTION diff --git a/Pods/Realm/include/core/realm/util/any.hpp b/Pods/Realm/include/core/realm/util/any.hpp new file mode 100644 index 0000000000..5ac72b2367 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/any.hpp @@ -0,0 +1,165 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2017 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifndef REALM_UTIL_ANY_HPP +#define REALM_UTIL_ANY_HPP + +#include +#include +#include +#include + +#include + +namespace realm { +namespace util { + +using bad_cast = ExceptionWithBacktrace; + +// A naive implementation of C++17's std::any +// This does not perform the small-object optimization or make any particular +// attempt at being performant +class Any final { +public: + // Constructors + + Any() = default; + Any(Any&&) noexcept = default; + ~Any() = default; + Any& operator=(Any&&) noexcept = default; + + Any(Any const& rhs) + : m_value(rhs.m_value ? rhs.m_value->copy() : nullptr) + { + } + + template::type, Any>::value>::type> + Any(T&& value) + : m_value(std::make_unique::type>>(std::forward(value))) + { + } + + Any& operator=(Any const& rhs) + { + m_value = rhs.m_value ? rhs.m_value->copy() : nullptr; + return *this; + } + + template::type, Any>::value>::type> + Any& operator=(T&& value) + { + m_value = std::make_unique::type>>(std::forward(value)); + return *this; + } + + // Modifiers + + void reset() noexcept { m_value.reset(); } + void swap(Any& rhs) noexcept { std::swap(m_value, rhs.m_value); } + + // Observers + + bool has_value() const noexcept { return m_value != nullptr; } + std::type_info const& type() const noexcept { return m_value ? m_value->type() : typeid(void); } + +private: + struct ValueBase { + virtual ~ValueBase() noexcept { } + virtual std::type_info const& type() const noexcept = 0; + virtual std::unique_ptr copy() const = 0; + }; + template + struct Value : ValueBase { + T value; + template Value(U&& v) : value(std::forward(v)) { } + + std::type_info const& type() const noexcept override { return typeid(T); } + std::unique_ptr copy() const override + { + return std::make_unique>(value); + } + }; + std::unique_ptr m_value; + + template + friend const T* any_cast(const Any* operand) noexcept; + template + friend T* any_cast(Any* operand) noexcept; + + template + const T* cast() const noexcept + { + return &static_cast*>(m_value.get())->value; + } + + template + T* cast() noexcept + { + return &static_cast*>(m_value.get())->value; + } +}; + +template +T any_cast(Any const& value) +{ + auto ptr = any_cast::type>::type>(&value); + if (!ptr) + throw bad_cast(); + return *ptr; +} + +template +T any_cast(Any& value) +{ + auto ptr = any_cast::type>(&value); + if (!ptr) + throw bad_cast(); + return *ptr; +} + +template +T any_cast(Any&& value) +{ + auto ptr = any_cast::type>(&value); + if (!ptr) + throw bad_cast(); + return std::move(*ptr); +} + +template +T* any_cast(Any* value) noexcept +{ + return value && value->type() == typeid(T) ? value->cast() : nullptr; +} + +template +const T* any_cast(const Any* value) noexcept +{ + return value && value->type() == typeid(T) ? value->cast() : nullptr; +} +} // namespace util +} // namespace realm + +namespace std { +inline void swap(realm::util::Any& lhs, realm::util::Any& rhs) noexcept +{ + lhs.swap(rhs); +} +} // namespace std + +#endif // REALM_UTIL_ANY_HPP diff --git a/Pods/Realm/include/core/realm/util/assert.hpp b/Pods/Realm/include/core/realm/util/assert.hpp new file mode 100644 index 0000000000..5e750664be --- /dev/null +++ b/Pods/Realm/include/core/realm/util/assert.hpp @@ -0,0 +1,107 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_ASSERT_HPP +#define REALM_UTIL_ASSERT_HPP + +#include +#include + +#if REALM_ENABLE_ASSERTIONS || defined(REALM_DEBUG) +#define REALM_ASSERTIONS_ENABLED 1 +#else +#define REALM_ASSERTIONS_ENABLED 0 +#endif + +#define REALM_ASSERT_RELEASE(condition) \ + (REALM_LIKELY(condition) ? static_cast(0) \ + : realm::util::terminate("Assertion failed: " #condition, __FILE__, __LINE__)) + +#if REALM_ASSERTIONS_ENABLED +#define REALM_ASSERT(condition) REALM_ASSERT_RELEASE(condition) +#else +#define REALM_ASSERT(condition) static_cast(sizeof bool(condition)) +#endif + +#ifdef REALM_DEBUG +#define REALM_ASSERT_DEBUG(condition) REALM_ASSERT_RELEASE(condition) +#else +#define REALM_ASSERT_DEBUG(condition) static_cast(sizeof bool(condition)) +#endif + +#define REALM_STRINGIFY(X) #X + +#define REALM_ASSERT_RELEASE_EX(condition, ...) \ + (REALM_LIKELY(condition) ? static_cast(0) \ + : realm::util::terminate_with_info("Assertion failed: " #condition, __LINE__, __FILE__, \ + REALM_STRINGIFY((__VA_ARGS__)), __VA_ARGS__)) + +#ifdef REALM_DEBUG +#define REALM_ASSERT_DEBUG_EX REALM_ASSERT_RELEASE_EX +#else +#define REALM_ASSERT_DEBUG_EX(condition, ...) static_cast(sizeof bool(condition)) +#endif + +// Becase the assert is used in noexcept methods, it's a bad idea to allocate +// buffer space for the message so therefore we must pass it to terminate which +// will 'cerr' it for us without needing any buffer +#if REALM_ENABLE_ASSERTIONS || defined(REALM_DEBUG) + +#define REALM_ASSERT_EX REALM_ASSERT_RELEASE_EX + +#define REALM_ASSERT_3(left, cmp, right) \ + (REALM_LIKELY((left)cmp(right)) ? static_cast(0) \ + : realm::util::terminate("Assertion failed: " \ + "" #left " " #cmp " " #right, \ + __FILE__, __LINE__, left, right)) + +#define REALM_ASSERT_7(left1, cmp1, right1, logical, left2, cmp2, right2) \ + (REALM_LIKELY(((left1)cmp1(right1))logical((left2)cmp2(right2))) \ + ? static_cast(0) \ + : realm::util::terminate("Assertion failed: " \ + "" #left1 " " #cmp1 " " #right1 " " #logical " " \ + "" #left2 " " #cmp2 " " #right2, \ + __FILE__, __LINE__, left1, right1, left2, right2)) + +#define REALM_ASSERT_11(left1, cmp1, right1, logical1, left2, cmp2, right2, logical2, left3, cmp3, right3) \ + (REALM_LIKELY(((left1)cmp1(right1))logical1((left2)cmp2(right2)) logical2((left3)cmp3(right3))) \ + ? static_cast(0) \ + : realm::util::terminate("Assertion failed: " \ + "" #left1 " " #cmp1 " " #right1 " " #logical1 " " \ + "" #left2 " " #cmp2 " " #right2 " " #logical2 " " \ + "" #left3 " " #cmp3 " " #right3, \ + __FILE__, __LINE__, left1, right1, left2, right2, left3, right3)) +#else +#define REALM_ASSERT_EX(condition, ...) static_cast(sizeof bool(condition)) +#define REALM_ASSERT_3(left, cmp, right) static_cast(sizeof bool((left)cmp(right))) +#define REALM_ASSERT_7(left1, cmp1, right1, logical, left2, cmp2, right2) \ + static_cast(sizeof bool(((left1)cmp1(right1))logical((left2)cmp2(right2)))) +#define REALM_ASSERT_11(left1, cmp1, right1, logical1, left2, cmp2, right2, logical2, left3, cmp3, right3) \ + static_cast(sizeof bool(((left1)cmp1(right1))logical1((left2)cmp2(right2)) logical2((left3)cmp3(right3)))) +#endif + +#define REALM_UNREACHABLE() realm::util::terminate("Unreachable code", __FILE__, __LINE__) +#ifdef REALM_COVER +#define REALM_COVER_NEVER(x) false +#define REALM_COVER_ALWAYS(x) true +#else +#define REALM_COVER_NEVER(x) (x) +#define REALM_COVER_ALWAYS(x) (x) +#endif + +#endif // REALM_UTIL_ASSERT_HPP diff --git a/Pods/Realm/include/core/realm/util/backtrace.hpp b/Pods/Realm/include/core/realm/util/backtrace.hpp new file mode 100644 index 0000000000..801102392d --- /dev/null +++ b/Pods/Realm/include/core/realm/util/backtrace.hpp @@ -0,0 +1,226 @@ +/************************************************************************* + * + * Copyright 2018 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_BACKTRACE_HPP +#define REALM_UTIL_BACKTRACE_HPP + +#include +#include +#include + +namespace realm { +namespace util { + +/// Backtrace encapsulates a stack trace, usually as captured by `backtrace()` +/// and `backtrace_symbols()` (or platform-specific equivalents). +struct Backtrace { + /// Capture a symbolicated stack trace, excluding the call to `capture()` + /// itself. If any error occurs while capturing the stack trace or + /// translating symbol names, a `Backtrace` object is returned containing a + /// single line describing the error. + /// + /// This function only allocates memory as part of calling + /// `backtrace_symbols()` (or the current platform's equivalent). + static Backtrace capture() noexcept; + + /// Print the backtrace to the stream. Each line is separated by a newline. + /// The format of the output is unspecified. + void print(std::ostream&) const; + + /// Construct an empty stack trace. + Backtrace() noexcept + { + } + + /// Move constructor. This operation cannot fail. + Backtrace(Backtrace&&) noexcept; + + /// Copy constructor. See the copy assignment operator. + Backtrace(const Backtrace&) noexcept; + + ~Backtrace(); + + /// Move assignment operator. This operation cannot fail. + Backtrace& operator=(Backtrace&&) noexcept; + + /// Copy assignment operator. Copying a `Backtrace` object may result in a + /// memory allocation. If such an allocation fails, the backtrace is + /// replaced with a single line describing the error. + Backtrace& operator=(const Backtrace&) noexcept; + +private: + Backtrace(void* memory, const char* const* strs, size_t len) + : m_memory(memory) + , m_strs(strs) + , m_len(len) + { + } + Backtrace(void* memory, size_t len) + : m_memory(memory) + , m_strs(static_cast(memory)) + , m_len(len) + { + } + + // m_memory is a pointer to the memory block returned by + // `backtrace_symbols()`. It is usually equal to `m_strs`, except in the + // case where an error has occurred and `m_strs` points to statically + // allocated memory describing the error. + // + // When `m_memory` is non-null, the memory is owned by this object. + void* m_memory = nullptr; + + // A pointer to a list of string pointers describing the stack trace (same + // format as returned by `backtrace_symbols()`). + const char* const* m_strs = nullptr; + + // Number of entries in this stack trace. + size_t m_len = 0; +}; + +namespace detail { + +class ExceptionWithBacktraceBase { +public: + ExceptionWithBacktraceBase() + : m_backtrace(util::Backtrace::capture()) + { + } + const util::Backtrace& backtrace() const noexcept + { + return m_backtrace; + } + virtual const char* message() const noexcept = 0; + +protected: + util::Backtrace m_backtrace; + // Cannot use Optional here, because Optional wants to use + // ExceptionWithBacktrace. + mutable bool m_has_materialized_message = false; + mutable std::string m_materialized_message; + + // Render the message and the backtrace into m_message_with_backtrace. If an + // exception is thrown while rendering the message, the message without the + // backtrace will be returned. + const char* materialize_message() const noexcept; +}; + +} // namespace detail + +/// Base class for exceptions that record a stack trace of where they were +/// thrown. +/// +/// The template argument is expected to be an exception type conforming to the +/// standard library exception API (`std::exception` and friends). +/// +/// It is possible to opt in to exception backtraces in two ways, (a) as part of +/// the exception type, in which case the backtrace will always be included for +/// all exceptions of that type, or (b) at the call-site of an opaque exception +/// type, in which case it is up to the throw-site to decide whether a backtrace +/// should be included. +/// +/// Example (a): +/// ``` +/// class MyException : ExceptionWithBacktrace { +/// public: +/// const char* message() const noexcept override +/// { +/// return "MyException error message"; +/// } +/// }; +/// +/// ... +/// +/// try { +/// throw MyException{}; +/// } +/// catch (const MyException& ex) { +/// // Print the backtrace without the message: +/// std::cerr << ex.backtrace() << "\n"; +/// // Print the exception message and the backtrace: +/// std::cerr << ex.what() << "\n"; +/// // Print the exception message without the backtrace: +/// std::cerr << ex.message() << "\n"; +/// } +/// ``` +/// +/// Example (b): +/// ``` +/// class MyException : std::exception { +/// public: +/// const char* what() const noexcept override +/// { +/// return "MyException error message"; +/// } +/// }; +/// +/// ... +/// +/// try { +/// throw ExceptionWithBacktrace{}; +/// } +/// catch (const MyException& ex) { +/// // Print the exception message and the backtrace: +/// std::cerr << ex.what() << "\n"; +/// } +/// ``` +template +class ExceptionWithBacktrace : public Base, public detail::ExceptionWithBacktraceBase { +public: + template + inline ExceptionWithBacktrace(Args&&... args) + : Base(std::forward(args)...) + , detail::ExceptionWithBacktraceBase() // backtrace captured here + { + } + + /// Return the message of the exception, including the backtrace of where + /// the exception was thrown. + const char* what() const noexcept final + { + return materialize_message(); + } + + /// Return the message of the exception without the backtrace. The default + /// implementation calls `Base::what()`. + const char* message() const noexcept override + { + return Base::what(); + } +}; + +// Wrappers for standard exception types with backtrace support +using runtime_error = ExceptionWithBacktrace; +using range_error = ExceptionWithBacktrace; +using overflow_error = ExceptionWithBacktrace; +using underflow_error = ExceptionWithBacktrace; +using bad_alloc = ExceptionWithBacktrace; +using invalid_argument = ExceptionWithBacktrace; +using out_of_range = ExceptionWithBacktrace; +using logic_error = ExceptionWithBacktrace; + +} // namespace util +} // namespace realm + +inline std::ostream& operator<<(std::ostream& os, const realm::util::Backtrace& bt) +{ + bt.print(os); + return os; +} + +#endif // REALM_UTIL_BACKTRACE_HPP diff --git a/Pods/Realm/include/core/realm/util/base64.hpp b/Pods/Realm/include/core/realm/util/base64.hpp new file mode 100644 index 0000000000..8d808a6d7c --- /dev/null +++ b/Pods/Realm/include/core/realm/util/base64.hpp @@ -0,0 +1,79 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_BASE64_HPP +#define REALM_UTIL_BASE64_HPP + +#include +#include +#include + +namespace realm { +namespace util { + + +/// base64_encode() encodes the bnary data in \param in_buffer of size \param in_buffer_size. +/// The encoded data is placed in \param out_buffer. The size of \param \out_buffer is passed in +/// \param out_buffer_size. The output buffer \param out_buffer must be +/// large enough to hold the base64 encoded data. The size can be obtained from the function +/// base64_encoded_size. \param out_buffer_size is only used to assert that the output buffer is +/// large enough. +size_t base64_encode(const char *in_buffer, size_t in_buffer_size, char* out_buffer, size_t out_buffer_size) noexcept; + +/// base64_encoded_size() returns the exact size of the base64 encoded +/// data as a function of the size of the input data. +inline size_t base64_encoded_size(size_t in_buffer_size) noexcept +{ + return 4 * ((in_buffer_size + 2) / 3); +} + + +/// Decode base64-encoded string in input, and places the result in out_buffer. +/// The length of the out_buffer must be at least 3 * input.size() / 4. +/// +/// The input must be padded base64 (i.e. the number of non-whitespace +/// characters in the input must be a multiple of 4). Whitespace (spaces, tabs, +/// newlines) is ignored. +/// +/// The algorithm stops when the first character not in the base64 character +/// set is encountered, or when the end of the input is reached. +/// +/// \returns the number of successfully decoded bytes written to out_buffer, or +/// none if the whole input was not valid base64. +Optional base64_decode(StringData input, char* out_buffer, size_t out_buffer_len) noexcept; + +/// Return an upper bound on the decoded size of a Base64-encoded data +/// stream of length \a base64_size. The returned value is suitable for +/// allocation of buffers containing decoded data. +inline size_t base64_decoded_size(size_t base64_size) noexcept +{ + return (base64_size * 3 + 3) / 4; +} + + + +/// base64_decode_to_vector() is a convenience function that decodes \param +/// encoded and returns the result in a std::vector with the correct size. +/// This function returns none if the input is invalid. +Optional> base64_decode_to_vector(StringData encoded); + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_BASE64_HPP + diff --git a/Pods/Realm/include/core/realm/util/basic_system_errors.hpp b/Pods/Realm/include/core/realm/util/basic_system_errors.hpp new file mode 100644 index 0000000000..8f7a626eaf --- /dev/null +++ b/Pods/Realm/include/core/realm/util/basic_system_errors.hpp @@ -0,0 +1,89 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_BASIC_SYSTEM_ERRORS_HPP +#define REALM_UTIL_BASIC_SYSTEM_ERRORS_HPP + +#include +#include + + +namespace realm { +namespace util { +namespace error { + +enum basic_system_errors { + /// Address family not supported by protocol. + address_family_not_supported = EAFNOSUPPORT, + + /// Invalid argument. + invalid_argument = EINVAL, + + /// Cannot allocate memory. + no_memory = ENOMEM, + + /// Operation cancelled. + operation_aborted = ECANCELED, + + /// Connection aborted. + connection_aborted = ECONNABORTED, + + /// Connection reset by peer + connection_reset = ECONNRESET, + + /// Broken pipe + broken_pipe = EPIPE, + + /// Resource temporarily unavailable + resource_unavailable_try_again = EAGAIN, +}; + +std::error_code make_error_code(basic_system_errors) noexcept; + +} // namespace error +} // namespace util +} // namespace realm + +namespace std { + +template <> +class is_error_code_enum { +public: + static const bool value = true; +}; + +} // namespace std + +namespace realm { +namespace util { + +std::error_code make_basic_system_error_code(int) noexcept; + + +// implementation + +inline std::error_code make_basic_system_error_code(int err) noexcept +{ + using namespace error; + return make_error_code(basic_system_errors(err)); +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_BASIC_SYSTEM_ERRORS_HPP diff --git a/Pods/Realm/include/core/realm/util/bind_ptr.hpp b/Pods/Realm/include/core/realm/util/bind_ptr.hpp new file mode 100644 index 0000000000..e5b8a99b12 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/bind_ptr.hpp @@ -0,0 +1,484 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_BIND_PTR_HPP +#define REALM_UTIL_BIND_PTR_HPP + +#include +#include +#include +#include + +#include +#include + + +namespace realm { +namespace util { + +class bind_ptr_base { +public: + struct adopt_tag { + }; +}; + + +/// A generic intrusive smart pointer that binds itself explicitely to +/// the target object. +/// +/// This class is agnostic towards what 'binding' means for the target +/// object, but a common use is 'reference counting'. See RefCountBase +/// for an example of that. +/// +/// This smart pointer implementation assumes that the target object +/// destructor never throws. +template +class bind_ptr : public bind_ptr_base { +public: + constexpr bind_ptr() noexcept + : m_ptr(nullptr) + { + } + ~bind_ptr() noexcept + { + unbind(); + } + + explicit bind_ptr(T* p) noexcept + { + bind(p); + } + template + explicit bind_ptr(U* p) noexcept + { + bind(p); + } + + bind_ptr(T* p, adopt_tag) noexcept + { + m_ptr = p; + } + template + bind_ptr(U* p, adopt_tag) noexcept + { + m_ptr = p; + } + + // Copy construct + bind_ptr(const bind_ptr& p) noexcept + { + bind(p.m_ptr); + } + template + bind_ptr(const bind_ptr& p) noexcept + { + bind(p.m_ptr); + } + + // Copy assign + bind_ptr& operator=(const bind_ptr& p) noexcept + { + bind_ptr(p).swap(*this); + return *this; + } + template + bind_ptr& operator=(const bind_ptr& p) noexcept + { + bind_ptr(p).swap(*this); + return *this; + } + + // Move construct + bind_ptr(bind_ptr&& p) noexcept + : m_ptr(p.release()) + { + } + template + bind_ptr(bind_ptr&& p) noexcept + : m_ptr(p.release()) + { + } + + // Move assign + bind_ptr& operator=(bind_ptr&& p) noexcept + { + bind_ptr(std::move(p)).swap(*this); + return *this; + } + template + bind_ptr& operator=(bind_ptr&& p) noexcept + { + bind_ptr(std::move(p)).swap(*this); + return *this; + } + + //@{ + // Comparison + template + bool operator==(const bind_ptr&) const noexcept; + + template + bool operator==(U*) const noexcept; + + template + bool operator!=(const bind_ptr&) const noexcept; + + template + bool operator!=(U*) const noexcept; + + template + bool operator<(const bind_ptr&) const noexcept; + + template + bool operator<(U*) const noexcept; + + template + bool operator>(const bind_ptr&) const noexcept; + + template + bool operator>(U*) const noexcept; + + template + bool operator<=(const bind_ptr&) const noexcept; + + template + bool operator<=(U*) const noexcept; + + template + bool operator>=(const bind_ptr&) const noexcept; + + template + bool operator>=(U*) const noexcept; + //@} + + // Dereference + T& operator*() const noexcept + { + return *m_ptr; + } + T* operator->() const noexcept + { + return m_ptr; + } + + explicit operator bool() const noexcept + { + return m_ptr != 0; + } + + T* get() const noexcept + { + return m_ptr; + } + void reset() noexcept + { + bind_ptr().swap(*this); + } + void reset(T* p) noexcept + { + bind_ptr(p).swap(*this); + } + template + void reset(U* p) noexcept + { + bind_ptr(p).swap(*this); + } + + T* release() noexcept + { + T* const p = m_ptr; + m_ptr = nullptr; + return p; + } + + void swap(bind_ptr& p) noexcept + { + std::swap(m_ptr, p.m_ptr); + } + friend void swap(bind_ptr& a, bind_ptr& b) noexcept + { + a.swap(b); + } + +protected: + struct casting_move_tag { + }; + template + bind_ptr(bind_ptr* p, casting_move_tag) noexcept + : m_ptr(static_cast(p->release())) + { + } + +private: + T* m_ptr; + + void bind(T* p) noexcept + { + if (p) + p->bind_ptr(); + m_ptr = p; + } + void unbind() noexcept + { + if (m_ptr) + m_ptr->unbind_ptr(); + } + + template + friend class bind_ptr; +}; + + +template +inline std::basic_ostream& operator<<(std::basic_ostream& out, const bind_ptr& p) +{ + out << static_cast(p.get()); + return out; +} + + +//@{ +// Comparison +template +bool operator==(T*, const bind_ptr&) noexcept; +template +bool operator!=(T*, const bind_ptr&) noexcept; +template +bool operator<(T*, const bind_ptr&) noexcept; +template +bool operator>(T*, const bind_ptr&) noexcept; +template +bool operator<=(T*, const bind_ptr&) noexcept; +template +bool operator>=(T*, const bind_ptr&) noexcept; +//@} + + +/// Polymorphic convenience base class for reference counting objects. +/// +/// Together with bind_ptr, this class delivers simple instrusive +/// reference counting. +/// +/// \sa bind_ptr +class RefCountBase { +public: + RefCountBase() noexcept + : m_ref_count(0) + { + } + virtual ~RefCountBase() noexcept + { + REALM_ASSERT(m_ref_count == 0); + } + + RefCountBase(const RefCountBase&) = delete; + RefCountBase(RefCountBase&&) = delete; + + void operator=(const RefCountBase&) = delete; + void operator=(RefCountBase&&) = delete; + +protected: + void bind_ptr() const noexcept + { + ++m_ref_count; + } + void unbind_ptr() const noexcept + { + if (--m_ref_count == 0) + delete this; + } + +private: + mutable unsigned long m_ref_count; + + template + friend class bind_ptr; +}; + + +/// Same as RefCountBase, but this one makes the copying of, and the +/// destruction of counted references thread-safe. +/// +/// \sa RefCountBase +/// \sa bind_ptr +class AtomicRefCountBase { +public: + AtomicRefCountBase() noexcept + : m_ref_count(0) + { + } + virtual ~AtomicRefCountBase() noexcept + { + REALM_ASSERT(m_ref_count == 0); + } + + AtomicRefCountBase(const AtomicRefCountBase&) = delete; + AtomicRefCountBase(AtomicRefCountBase&&) = delete; + + void operator=(const AtomicRefCountBase&) = delete; + void operator=(AtomicRefCountBase&&) = delete; + +protected: + // FIXME: Operators ++ and -- as used below use + // std::memory_order_seq_cst. This can be optimized. + void bind_ptr() const noexcept + { + ++m_ref_count; + } + void unbind_ptr() const noexcept + { + if (--m_ref_count == 0) { + delete this; + } + } + +private: + mutable std::atomic m_ref_count; + + template + friend class bind_ptr; +}; + + +// Implementation: + +template +template +bool bind_ptr::operator==(const bind_ptr& p) const noexcept +{ + return m_ptr == p.m_ptr; +} + +template +template +bool bind_ptr::operator==(U* p) const noexcept +{ + return m_ptr == p; +} + +template +template +bool bind_ptr::operator!=(const bind_ptr& p) const noexcept +{ + return m_ptr != p.m_ptr; +} + +template +template +bool bind_ptr::operator!=(U* p) const noexcept +{ + return m_ptr != p; +} + +template +template +bool bind_ptr::operator<(const bind_ptr& p) const noexcept +{ + return m_ptr < p.m_ptr; +} + +template +template +bool bind_ptr::operator<(U* p) const noexcept +{ + return m_ptr < p; +} + +template +template +bool bind_ptr::operator>(const bind_ptr& p) const noexcept +{ + return m_ptr > p.m_ptr; +} + +template +template +bool bind_ptr::operator>(U* p) const noexcept +{ + return m_ptr > p; +} + +template +template +bool bind_ptr::operator<=(const bind_ptr& p) const noexcept +{ + return m_ptr <= p.m_ptr; +} + +template +template +bool bind_ptr::operator<=(U* p) const noexcept +{ + return m_ptr <= p; +} + +template +template +bool bind_ptr::operator>=(const bind_ptr& p) const noexcept +{ + return m_ptr >= p.m_ptr; +} + +template +template +bool bind_ptr::operator>=(U* p) const noexcept +{ + return m_ptr >= p; +} + +template +bool operator==(T* a, const bind_ptr& b) noexcept +{ + return b == a; +} + +template +bool operator!=(T* a, const bind_ptr& b) noexcept +{ + return b != a; +} + +template +bool operator<(T* a, const bind_ptr& b) noexcept +{ + return b > a; +} + +template +bool operator>(T* a, const bind_ptr& b) noexcept +{ + return b < a; +} + +template +bool operator<=(T* a, const bind_ptr& b) noexcept +{ + return b >= a; +} + +template +bool operator>=(T* a, const bind_ptr& b) noexcept +{ + return b <= a; +} + + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_BIND_PTR_HPP diff --git a/Pods/Realm/include/core/realm/util/buffer.hpp b/Pods/Realm/include/core/realm/util/buffer.hpp new file mode 100644 index 0000000000..024510ec65 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/buffer.hpp @@ -0,0 +1,301 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_BUFFER_HPP +#define REALM_UTIL_BUFFER_HPP + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace realm { +namespace util { + + +/// A simple buffer concept that owns a region of memory and knows its +/// size. +template +class Buffer { +public: + Buffer() noexcept + : m_size(0) + { + } + explicit Buffer(size_t initial_size); + Buffer(Buffer&&) noexcept = default; + ~Buffer() noexcept + { + } + + Buffer& operator=(Buffer&&) noexcept = default; + + T& operator[](size_t i) noexcept + { + return m_data[i]; + } + const T& operator[](size_t i) const noexcept + { + return m_data[i]; + } + + T* data() noexcept + { + return m_data.get(); + } + const T* data() const noexcept + { + return m_data.get(); + } + size_t size() const noexcept + { + return m_size; + } + + /// False iff the data() returns null. + explicit operator bool() const noexcept + { + return bool(m_data); + } + + /// Discards the original contents. + void set_size(size_t new_size); + + /// \param new_size Specifies the new buffer size. + /// \param copy_begin, copy_end Specifies a range of element + /// values to be retained. \a copy_end must be less than, or equal + /// to size(). + /// + /// \param copy_to Specifies where the retained range should be + /// copied to. `\a copy_to + \a copy_end - \a copy_begin` must be + /// less than, or equal to \a new_size. + void resize(size_t new_size, size_t copy_begin, size_t copy_end, size_t copy_to); + + void reserve(size_t used_size, size_t min_capacity); + + void reserve_extra(size_t used_size, size_t min_extra_capacity); + + T* release() noexcept; + + friend void swap(Buffer& a, Buffer& b) noexcept + { + using std::swap; + swap(a.m_data, b.m_data); + swap(a.m_size, b.m_size); + } + +private: + std::unique_ptr m_data; + size_t m_size; +}; + + +/// A buffer that can be efficiently resized. It acheives this by +/// using an underlying buffer that may be larger than the logical +/// size, and is automatically expanded in progressively larger steps. +template +class AppendBuffer { +public: + AppendBuffer() noexcept; + ~AppendBuffer() noexcept + { + } + + AppendBuffer(AppendBuffer&&) noexcept = default; + AppendBuffer& operator=(AppendBuffer&&) noexcept = default; + + /// Returns the current size of the buffer. + size_t size() const noexcept; + + /// Gives read and write access to the elements. + T* data() noexcept; + + /// Gives read access the elements. + const T* data() const noexcept; + + /// Append the specified elements. This increases the size of this + /// buffer by \a append_data_size. If the caller has previously requested + /// a minimum capacity that is greater than, or equal to the + /// resulting size, this function is guaranteed to not throw. + void append(const T* append_data, size_t append_data_size); + + /// If the specified size is less than the current size, then the + /// buffer contents is truncated accordingly. If the specified + /// size is greater than the current size, then the extra elements + /// will have undefined values. If the caller has previously + /// requested a minimum capacity that is greater than, or equal to + /// the specified size, this function is guaranteed to not throw. + void resize(size_t new_size); + + /// This operation does not change the size of the buffer as + /// returned by size(). If the specified capacity is less than the + /// current capacity, this operation has no effect. + void reserve(size_t min_capacity); + + /// Set the size to zero. The capacity remains unchanged. + void clear() noexcept; + + /// Release the underlying buffer and reset the size. Note: The returned + /// buffer may be larger than the amount of data appended to this buffer. + /// Callers should call `size()` prior to releasing the buffer to know the + /// usable/logical size. + Buffer release() noexcept; + +private: + util::Buffer m_buffer; + size_t m_size; +}; + + +// Implementation: + +class BufferSizeOverflow : public std::exception { +public: + const char* what() const noexcept override + { + return "Buffer size overflow"; + } +}; + +template +inline Buffer::Buffer(size_t initial_size) + : m_data(new T[initial_size]) // Throws + , m_size(initial_size) +{ +} + +template +inline void Buffer::set_size(size_t new_size) +{ + m_data.reset(new T[new_size]); // Throws + m_size = new_size; +} + +template +inline void Buffer::resize(size_t new_size, size_t copy_begin, size_t copy_end, size_t copy_to) +{ + std::unique_ptr new_data(new T[new_size]); // Throws + realm::safe_copy_n(m_data.get() + copy_begin, copy_end - copy_begin, new_data.get() + copy_to); + m_data.reset(new_data.release()); + m_size = new_size; +} + +template +inline void Buffer::reserve(size_t used_size, size_t min_capacity) +{ + size_t current_capacity = m_size; + if (REALM_LIKELY(current_capacity >= min_capacity)) + return; + size_t new_capacity = current_capacity; + + // Use growth factor 1.5. + if (REALM_UNLIKELY(int_multiply_with_overflow_detect(new_capacity, 3))) + new_capacity = std::numeric_limits::max(); + new_capacity /= 2; + + if (REALM_UNLIKELY(new_capacity < min_capacity)) + new_capacity = min_capacity; + resize(new_capacity, 0, used_size, 0); // Throws +} + +template +inline void Buffer::reserve_extra(size_t used_size, size_t min_extra_capacity) +{ + size_t min_capacity = used_size; + if (REALM_UNLIKELY(int_add_with_overflow_detect(min_capacity, min_extra_capacity))) + throw BufferSizeOverflow(); + reserve(used_size, min_capacity); // Throws +} + +template +inline T* Buffer::release() noexcept +{ + m_size = 0; + return m_data.release(); +} + + +template +inline AppendBuffer::AppendBuffer() noexcept + : m_size(0) +{ +} + +template +inline size_t AppendBuffer::size() const noexcept +{ + return m_size; +} + +template +inline T* AppendBuffer::data() noexcept +{ + return m_buffer.data(); +} + +template +inline const T* AppendBuffer::data() const noexcept +{ + return m_buffer.data(); +} + +template +inline void AppendBuffer::append(const T* append_data, size_t append_data_size) +{ + m_buffer.reserve_extra(m_size, append_data_size); // Throws + realm::safe_copy_n(append_data, append_data_size, m_buffer.data() + m_size); + m_size += append_data_size; +} + +template +inline void AppendBuffer::reserve(size_t min_capacity) +{ + m_buffer.reserve(m_size, min_capacity); +} + +template +inline void AppendBuffer::resize(size_t new_size) +{ + reserve(new_size); + m_size = new_size; +} + +template +inline void AppendBuffer::clear() noexcept +{ + m_size = 0; +} + +template +inline Buffer AppendBuffer::release() noexcept +{ + m_size = 0; + return std::move(m_buffer); +} + + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_BUFFER_HPP diff --git a/Pods/Realm/include/core/realm/util/buffer_stream.hpp b/Pods/Realm/include/core/realm/util/buffer_stream.hpp new file mode 100644 index 0000000000..65feb8bf42 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/buffer_stream.hpp @@ -0,0 +1,146 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_BUFFER_STREAM_HPP +#define REALM_UTIL_BUFFER_STREAM_HPP + +#include + +namespace realm { +namespace util { + + +template, class A = std::allocator > +class BasicResettableExpandableOutputStreambuf: public std::basic_stringbuf { +public: + using char_type = typename std::basic_stringbuf::char_type; + + /// Reset current writing position (std::basic_streambuf::pptr()) to the + /// beginning of the output buffer without reallocating buffer memory. + void reset() noexcept; + + /// Get a pointer to the beginning of the output buffer + /// (std::basic_streambuf::pbase()). Note that this will change as the + /// buffer is reallocated. + char_type* data() noexcept; + const char_type* data() const noexcept; + + /// Get the number of bytes written to the output buffer since the creation + /// of the stream buffer, or since the last invocation of reset() + /// (std::basic_streambuf::pptr() - std::basic_streambuf::pbase()). + std::streamsize size() const noexcept; +}; + + +template, class A = std::allocator > +class BasicResettableExpandableBufferOutputStream: public std::basic_ostream { +public: + using char_type = typename std::basic_ostream::char_type; + + BasicResettableExpandableBufferOutputStream(); + + /// Calls BasicResettableExpandableOutputStreambuf::reset(). + void reset() noexcept; + + /// Calls BasicResettableExpandableOutputStreambuf::data(). + char_type* data() noexcept; + const char_type* data() const noexcept; + + /// Calls BasicResettableExpandableOutputStreambuf::size(). + std::streamsize size() const noexcept; + +private: + BasicResettableExpandableOutputStreambuf m_streambuf; +}; + + +using ResettableExpandableBufferOutputStream = BasicResettableExpandableBufferOutputStream; + + + + +// Implementation + +template +inline void BasicResettableExpandableOutputStreambuf::reset() noexcept +{ + char_type* pbeg = this->pbase(); + char_type* pend = this->epptr(); + this->setp(pbeg, pend); +} + +template +inline typename BasicResettableExpandableOutputStreambuf::char_type* +BasicResettableExpandableOutputStreambuf::data() noexcept +{ + return this->pbase(); +} + +template +inline const typename BasicResettableExpandableOutputStreambuf::char_type* +BasicResettableExpandableOutputStreambuf::data() const noexcept +{ + return this->pbase(); +} + +template +inline std::streamsize BasicResettableExpandableOutputStreambuf::size() const noexcept +{ + std::streamsize s = std::streamsize(this->pptr() - this->pbase()); + return s; +} + +template +inline BasicResettableExpandableBufferOutputStream:: +BasicResettableExpandableBufferOutputStream(): + std::basic_ostream(&m_streambuf) // Throws +{ +} + +template +inline void BasicResettableExpandableBufferOutputStream::reset() noexcept +{ + m_streambuf.reset(); +} + +template +inline typename BasicResettableExpandableBufferOutputStream::char_type* +BasicResettableExpandableBufferOutputStream::data() noexcept +{ + return m_streambuf.data(); +} + +template +inline const typename BasicResettableExpandableBufferOutputStream::char_type* +BasicResettableExpandableBufferOutputStream::data() const noexcept +{ + return m_streambuf.data(); +} + +template +inline std::streamsize BasicResettableExpandableBufferOutputStream::size() const noexcept +{ + return m_streambuf.size(); +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_BUFFER_STREAM_HPP diff --git a/Pods/Realm/include/core/realm/util/call_with_tuple.hpp b/Pods/Realm/include/core/realm/util/call_with_tuple.hpp new file mode 100644 index 0000000000..7d2eab06b1 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/call_with_tuple.hpp @@ -0,0 +1,66 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_CALL_WITH_TUPLE_HPP +#define REALM_UTIL_CALL_WITH_TUPLE_HPP + +#include +#include + +namespace realm { +namespace _impl { + +/// \cond doxygen_skip +/// Doxygen warns about a recursive class relation, but this is intentional. + +template +struct Indexes { +}; +template +struct GenIndexes : GenIndexes { +}; +template +struct GenIndexes<0, I...> { + typedef Indexes type; +}; + +/// \endcond + +template +auto call_with_tuple(F func, std::tuple args, Indexes) -> decltype(func(std::get(args)...)) +{ + static_cast(args); // Prevent GCC warning when tuple is empty + return func(std::get(args)...); +} + +} // namespace _impl + +namespace util { + +template +auto call_with_tuple(F func, std::tuple args) + -> decltype(_impl::call_with_tuple(std::move(func), std::move(args), + typename _impl::GenIndexes::type())) +{ + return _impl::call_with_tuple(std::move(func), std::move(args), typename _impl::GenIndexes::type()); +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_CALL_WITH_TUPLE_HPP diff --git a/Pods/Realm/include/core/realm/util/cf_ptr.hpp b/Pods/Realm/include/core/realm/util/cf_ptr.hpp new file mode 100644 index 0000000000..a1ec431f1b --- /dev/null +++ b/Pods/Realm/include/core/realm/util/cf_ptr.hpp @@ -0,0 +1,108 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_CF_PTR_HPP +#define REALM_UTIL_CF_PTR_HPP + +#include + +#if REALM_PLATFORM_APPLE + +#include + +namespace realm { +namespace util { + +template +class CFPtr { +public: + explicit CFPtr(Ref ref = nullptr) noexcept + : m_ref(ref) + { + } + + CFPtr(CFPtr&& rg) noexcept + : m_ref(rg.m_ref) + { + rg.m_ref = nullptr; + } + + ~CFPtr() noexcept + { + if (m_ref) + CFRelease(m_ref); + } + + CFPtr& operator=(CFPtr&& rg) noexcept + { + REALM_ASSERT(!m_ref || m_ref != rg.m_ref); + if (m_ref) + CFRelease(m_ref); + m_ref = rg.m_ref; + rg.m_ref = nullptr; + return *this; + } + + explicit operator bool() const noexcept + { + return bool(m_ref); + } + + Ref get() const noexcept + { + return m_ref; + } + + Ref release() noexcept + { + Ref ref = m_ref; + m_ref = nullptr; + return ref; + } + + void reset(Ref ref = nullptr) noexcept + { + REALM_ASSERT(!m_ref || m_ref != ref); + if (m_ref) + CFRelease(m_ref); + m_ref = ref; + } + +private: + Ref m_ref; +}; + +template +CFPtr adoptCF(Ref ptr) +{ + return CFPtr(ptr); +} + +template +CFPtr retainCF(Ref ptr) +{ + CFRetain(ptr); + return CFPtr(ptr); +} +} +} + + +#endif // REALM_PLATFORM_APPLE + +#endif // REALM_UTIL_CF_PTR_HPP diff --git a/Pods/Realm/include/core/realm/util/circular_buffer.hpp b/Pods/Realm/include/core/realm/util/circular_buffer.hpp new file mode 100644 index 0000000000..4ae07cc756 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/circular_buffer.hpp @@ -0,0 +1,1011 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_CIRCULAR_BUFFER_HPP +#define REALM_UTIL_CIRCULAR_BUFFER_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace realm { +namespace util { + +/// \brief A container backed by a "circular buffer". +/// +/// This container is similar to std::deque in that it offers efficient element +/// insertion and removal at both ends. Insertion at either end occurs in +/// amortized constant time. Removal at either end occurs in constant time. +/// +/// As opposed to std::deque, this container allows for reservation of buffer +/// space, such that value insertion can be guaranteed to not reallocate buffer +/// memory, and to not throw. +/// +/// More specifically, a single insert operation, that inserts zero or more +/// values at either end, is guaranteed to not reallocate buffer memory if the +/// prior capacity (capacity()) is greater than, or equal to the prior size +/// (size()) plus the number of inserted values. Further more, such an operation +/// is guaranteed to not throw if the capacity is sufficient, and the relevant +/// constructor of the value type does not throw, and, in the case of inserting +/// a range of values specified as a pair of iterators, if no exception is +/// thrown while operating on those iterators. +/// +/// This container uses a single contiguous chunk of memory as backing storage, +/// but it allows for the logical sequence of values to wrap around from the +/// end, to the beginning of that chunk. Because the logical sequence of values +/// can have a storage-wise discontinuity of this kind, this container does not +/// meet the requirements of `ContiguousContainer` (as defined by C++17). +/// +/// When the first element is removed (pop_front()), iterators pointing to the +/// removed element will be invalidated. All other iterators, including "end +/// iterators" (end()), will remain valid. +/// +/// When the last element is removed (pop_back()), iterators pointing to the +/// removed element will become "end iterators" (end()), and "end iterators" +/// will be invalidated. All other iterators will remain valid. +/// +/// When an element is inserted at the front (push_front()), and the prior +/// capacity (capacity()) is strictly greater than the prior size (size()), all +/// iterators remain valid. +/// +/// When an element is inserted at the back (push_back()), and the prior +/// capacity (capacity()) is strictly greater than the prior size (size()), "end +/// iterators" (end()) become iterators to the inserted element, and all other +/// iterators remain valid. +/// +/// Operations pop_front(), pop_back(), and clear(), are guaranteed to leave the +/// capacity unchanged. +/// +/// Iterators are of the "random access" kind (std::random_access_iterator_tag). +template class CircularBuffer { +private: + template class Iter; + + template using RequireIter = + std::enable_if_t::iterator_category, + std::input_iterator_tag>::value>; + +public: + static_assert(std::is_nothrow_destructible::value, ""); + + using value_type = T; + using size_type = std::size_t; + using reference = value_type&; + using const_reference = const value_type&; + using iterator = Iter; + using const_iterator = Iter; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + CircularBuffer() noexcept; + CircularBuffer(const CircularBuffer&); + CircularBuffer(CircularBuffer&&) noexcept; + CircularBuffer(std::initializer_list); + explicit CircularBuffer(size_type size); + CircularBuffer(size_type size, const T& value); + template> CircularBuffer(I begin, I end); + ~CircularBuffer() noexcept; + + CircularBuffer& operator=(const CircularBuffer&); + CircularBuffer& operator=(CircularBuffer&&) noexcept; + CircularBuffer& operator=(std::initializer_list); + + void assign(std::initializer_list); + void assign(size_type size, const T& value); + template> void assign(I begin, I end); + + // Element access + + reference at(size_type); + const_reference at(size_type) const; + + reference operator[](size_type) noexcept; + const_reference operator[](size_type) const noexcept; + + reference front() noexcept; + const_reference front() const noexcept; + + reference back() noexcept; + const_reference back() const noexcept; + + // Iterators + + iterator begin() noexcept; + const_iterator begin() const noexcept; + const_iterator cbegin() const noexcept; + + iterator end() noexcept; + const_iterator end() const noexcept; + const_iterator cend() const noexcept; + + reverse_iterator rbegin() noexcept; + const_reverse_iterator rbegin() const noexcept; + const_reverse_iterator crbegin() const noexcept; + + reverse_iterator rend() noexcept; + const_reverse_iterator rend() const noexcept; + const_reverse_iterator crend() const noexcept; + + // Size / capacity + + bool empty() const noexcept; + size_type size() const noexcept; + size_type capacity() const noexcept; + + void reserve(size_type capacity); + void shrink_to_fit(); + + // Modifiers + + reference push_front(const T&); + reference push_back(const T&); + + reference push_front(T&&); + reference push_back(T&&); + + template reference emplace_front(Args&&...); + template reference emplace_back(Args&&...); + + void pop_front() noexcept; + void pop_back() noexcept; + + // FIXME: emplace(const_iterator i, ...) -> j = unwrap(i.m_index); if (j >= (m_size+1)/2) insert_near_back(j, ...); else insert_near_front(j, ...); + + void clear() noexcept; + void resize(size_type size); + void resize(size_type size, const T& value); + + void swap(CircularBuffer&) noexcept; + + // Comparison + + template bool operator==(const CircularBuffer&) const + noexcept(noexcept(std::declval() == std::declval())); + template bool operator!=(const CircularBuffer&) const + noexcept(noexcept(std::declval() == std::declval())); + template bool operator<(const CircularBuffer&) const + noexcept(noexcept(std::declval() < std::declval())); + template bool operator>(const CircularBuffer&) const + noexcept(noexcept(std::declval() < std::declval())); + template bool operator<=(const CircularBuffer&) const + noexcept(noexcept(std::declval() < std::declval())); + template bool operator>=(const CircularBuffer&) const + noexcept(noexcept(std::declval() < std::declval())); + +private: + using Strut = typename std::aligned_storage::type; + std::unique_ptr m_memory_owner; + + // Index of first element in allocated memory chunk. + size_type m_begin = 0; + + // The number of elements within the allocated memory chunk, that are + // currently in use, i.e., the logical size of the circular buffer. + size_type m_size = 0; + + // Number of elements of type T that will fit into the currently allocated + // memory chunk. + // + // Except when m_size is zero, m_allocated_size must be strictly greater + // than m_size. This is required to ensure that the iterators returned by + // begin() and end() are equal only when the buffer is empty. + // + // INVARIANT: m_size == 0 ? m_allocated_size == 0 : m_size < m_allocated_size + size_type m_allocated_size = 0; + + T* get_memory_ptr() noexcept; + + // Assumption: index < m_allocated_size + size_type circular_inc(size_type index) noexcept; + size_type circular_dec(size_type index) noexcept; + size_type wrap(size_type index) noexcept; + size_type unwrap(size_type index) noexcept; + + template void copy(I begin, I end); + template void copy(I begin, I end, std::input_iterator_tag); + template void copy(I begin, I end, std::forward_iterator_tag); + + void destroy(size_type offset = 0) noexcept; + + void realloc(size_type new_allocated_size); +}; + + +template void swap(CircularBuffer&, CircularBuffer&) noexcept; + + + + +// Implementation + +template template class CircularBuffer::Iter : + public std::iterator { +public: + using difference_type = std::ptrdiff_t; + + Iter() noexcept + { + } + + template Iter(const Iter& i) noexcept + { + operator=(i); + } + + template Iter& operator=(const Iter& i) noexcept + { + // Check constness convertability + static_assert(std::is_convertible::value, ""); + m_buffer = i.m_buffer; + m_index = i.m_index; + return *this; + } + + U& operator*() const noexcept + { + T* memory = m_buffer->get_memory_ptr(); + return memory[m_index]; + } + + U* operator->() const noexcept + { + return &operator*(); + } + + U& operator[](difference_type i) const noexcept + { + Iter j = *this; + j += i; + return *j; + } + + Iter& operator++() noexcept + { + m_index = m_buffer->circular_inc(m_index); + return *this; + } + + Iter& operator--() noexcept + { + m_index = m_buffer->circular_dec(m_index); + return *this; + } + + Iter operator++(int) noexcept + { + size_type i = m_index; + operator++(); + return Iter{m_buffer, i}; + } + + Iter operator--(int) noexcept + { + size_type i = m_index; + operator--(); + return Iter{m_buffer, i}; + } + + Iter& operator+=(difference_type value) noexcept + { + // Care is needed to avoid unspecified arithmetic behaviour here. We can + // assume, however, that if `i` is the unwrapped (logical) index of the + // element pointed to by this iterator, then the mathematical value of i + // + value is representable in `size_type` (otherwise the resulting + // iterator would escape the boundaries of the buffer). We can therefore + // safely perform the addition in the unsigned domain of unwrapped + // element indexes, and rely on two's complement representation for + // negative values. + size_type i = m_buffer->unwrap(m_index); + i += size_type(value); + m_index = m_buffer->wrap(i); + return *this; + } + + Iter& operator-=(difference_type value) noexcept + { + // Care is needed to avoid unspecified arithmetic behaviour here. See + // the comment in the implementation of operator+=(). + size_type i = m_buffer->unwrap(m_index); + i -= size_type(value); + m_index = m_buffer->wrap(i); + return *this; + } + + Iter operator+(difference_type value) const noexcept + { + Iter i = *this; + i += value; + return i; + } + + Iter operator-(difference_type value) const noexcept + { + Iter i = *this; + i -= value; + return i; + } + + friend Iter operator+(difference_type value, const Iter& i) noexcept + { + Iter j = i; + j += value; + return j; + } + + template difference_type operator-(const Iter& i) const noexcept + { + REALM_ASSERT(m_buffer == i.m_buffer); + size_type i_1 = m_buffer->unwrap(m_index); + size_type i_2 = i.m_buffer->unwrap(i.m_index); + return from_twos_compl(size_type(i_1 - i_2)); + } + + template bool operator==(const Iter& i) const noexcept + { + REALM_ASSERT(m_buffer == i.m_buffer); + return (m_index == i.m_index); + } + + template bool operator!=(const Iter& i) const noexcept + { + return !operator==(i); + } + + template bool operator<(const Iter& i) const noexcept + { + REALM_ASSERT(m_buffer == i.m_buffer); + size_type i_1 = m_buffer->unwrap(m_index); + size_type i_2 = i.m_buffer->unwrap(i.m_index); + return (i_1 < i_2); + } + + template bool operator>(const Iter& i) const noexcept + { + return (i < *this); + } + + template bool operator<=(const Iter& i) const noexcept + { + return !operator>(i); + } + + template bool operator>=(const Iter& i) const noexcept + { + return !operator<(i); + } + +private: + CircularBuffer* m_buffer = nullptr; + + // Index of iterator position from beginning of allocated memory, i.e., from + // beginning of m_buffer->get_memory_ptr(). + size_type m_index = 0; + + Iter(CircularBuffer* buffer, size_type index) noexcept : + m_buffer{buffer}, + m_index{index} + { + } + + friend class CircularBuffer; + template friend class Iter; +}; + +template inline CircularBuffer::CircularBuffer() noexcept +{ +} + +template inline CircularBuffer::CircularBuffer(const CircularBuffer& buffer) +{ + try { + copy(buffer.begin(), buffer.end()); // Throws + } + catch (...) { + // If an exception was thrown above, the destructor will not be called, + // so we need to manually destroy the copies that were already made. + destroy(); + throw; + } +} + +template inline CircularBuffer::CircularBuffer(CircularBuffer&& buffer) noexcept : + m_memory_owner{std::move(buffer.m_memory_owner)}, + m_begin{buffer.m_begin}, + m_size{buffer.m_size}, + m_allocated_size{buffer.m_allocated_size} +{ + buffer.m_begin = 0; + buffer.m_size = 0; + buffer.m_allocated_size = 0; +} + +template inline CircularBuffer::CircularBuffer(std::initializer_list list) +{ + try { + copy(list.begin(), list.end()); // Throws + } + catch (...) { + // If an exception was thrown above, the destructor will not be called, + // so we need to manually destroy the copies that were already made. + destroy(); + throw; + } +} + +template inline CircularBuffer::CircularBuffer(size_type count) +{ + try { + resize(count); // Throws + } + catch (...) { + // If an exception was thrown above, the destructor will not be called, + // so we need to manually destroy the instances that were already + // created. + destroy(); + throw; + } +} + +template inline CircularBuffer::CircularBuffer(size_type count, const T& value) +{ + try { + resize(count, value); // Throws + } + catch (...) { + // If an exception was thrown above, the destructor will not be called, + // so we need to manually destroy the copies that were already made. + destroy(); + throw; + } +} + +template template inline CircularBuffer::CircularBuffer(I begin, I end) +{ + try { + copy(begin, end); // Throws + } + catch (...) { + // If an exception was thrown above, the destructor will not be called, + // so we need to manually destroy the copies that were already made. + destroy(); + throw; + } +} + +template inline CircularBuffer::~CircularBuffer() noexcept +{ + destroy(); +} + +template +inline auto CircularBuffer::operator=(const CircularBuffer& buffer) -> CircularBuffer& +{ + clear(); + copy(buffer.begin(), buffer.end()); // Throws + return *this; +} + +template +inline auto CircularBuffer::operator=(CircularBuffer&& buffer) noexcept -> CircularBuffer& +{ + destroy(); + m_memory_owner = std::move(buffer.m_memory_owner); + m_begin = buffer.m_begin; + m_size = buffer.m_size; + m_allocated_size = buffer.m_allocated_size; + buffer.m_begin = 0; + buffer.m_size = 0; + buffer.m_allocated_size = 0; + return *this; +} + +template +inline auto CircularBuffer::operator=(std::initializer_list list) -> CircularBuffer& +{ + clear(); + copy(list.begin(), list.end()); // Throws + return *this; +} + +template inline void CircularBuffer::assign(std::initializer_list list) +{ + clear(); + copy(list.begin(), list.end()); // Throws +} + +template inline void CircularBuffer::assign(size_type count, const T& value) +{ + clear(); + resize(count, value); // Throws +} + +template template inline void CircularBuffer::assign(I begin, I end) +{ + clear(); + copy(begin, end); // Throws +} + +template inline auto CircularBuffer::at(size_type i) -> reference +{ + if (REALM_LIKELY(i < m_size)) + return operator[](i); + throw util::out_of_range{"Index"}; +} + +template inline auto CircularBuffer::at(size_type i) const -> const_reference +{ + return const_cast(this)->at(i); // Throws +} + +template +inline auto CircularBuffer::operator[](size_type i) noexcept -> reference +{ + REALM_ASSERT(i < m_size); + T* memory = get_memory_ptr(); + size_type j = wrap(i); + return memory[j]; +} + +template +inline auto CircularBuffer::operator[](size_type i) const noexcept -> const_reference +{ + return const_cast(this)->operator[](i); +} + +template inline auto CircularBuffer::front() noexcept -> reference +{ + return operator[](0); +} + +template inline auto CircularBuffer::front() const noexcept -> const_reference +{ + return operator[](0); +} + +template inline auto CircularBuffer::back() noexcept -> reference +{ + return operator[](m_size-1); +} + +template +inline auto CircularBuffer::back() const noexcept -> const_reference +{ + return operator[](m_size-1); +} + +template inline auto CircularBuffer::begin() noexcept -> iterator +{ + return iterator{this, m_begin}; +} + +template inline auto CircularBuffer::begin() const noexcept -> const_iterator +{ + return const_cast(this)->begin(); +} + +template inline auto CircularBuffer::cbegin() const noexcept -> const_iterator +{ + return begin(); +} + +template inline auto CircularBuffer::end() noexcept -> iterator +{ + size_type i = wrap(m_size); + return iterator{this, i}; +} + +template inline auto CircularBuffer::end() const noexcept -> const_iterator +{ + return const_cast(this)->end(); +} + +template inline auto CircularBuffer::cend() const noexcept -> const_iterator +{ + return end(); +} + +template inline auto CircularBuffer::rbegin() noexcept -> reverse_iterator +{ + return std::reverse_iterator(end()); +} + +template inline auto CircularBuffer::rbegin() const noexcept -> const_reverse_iterator +{ + return const_cast(this)->rbegin(); +} + +template inline auto CircularBuffer::crbegin() const noexcept -> const_reverse_iterator +{ + return rbegin(); +} + +template inline auto CircularBuffer::rend() noexcept -> reverse_iterator +{ + return std::reverse_iterator(begin()); +} + +template inline auto CircularBuffer::rend() const noexcept -> const_reverse_iterator +{ + return const_cast(this)->rend(); +} + +template inline auto CircularBuffer::crend() const noexcept -> const_reverse_iterator +{ + return rend(); +} + +template inline bool CircularBuffer::empty() const noexcept +{ + return (m_size == 0); +} + +template inline auto CircularBuffer::size() const noexcept -> size_type +{ + return m_size; +} + +template void CircularBuffer::reserve(size_type capacity) +{ + if (capacity == 0) + return; + + // An extra element of capacity is needed such that the end iterator can + // always point one beyond the last element without becomeing equal to an + // iterator to the first element. + size_type min_allocated_size = capacity; + if (REALM_UNLIKELY(int_add_with_overflow_detect(min_allocated_size, 1))) + throw util::overflow_error{"Capacity"}; + + if (min_allocated_size <= m_allocated_size) + return; + + size_type new_allocated_size = m_allocated_size; + if (REALM_UNLIKELY(int_multiply_with_overflow_detect(new_allocated_size, 2))) + new_allocated_size = std::numeric_limits::max(); + if (new_allocated_size < min_allocated_size) + new_allocated_size = min_allocated_size; + realloc(new_allocated_size); // Throws +} + +template inline void CircularBuffer::shrink_to_fit() +{ + if (m_size > 0) { + // An extra element of capacity is needed such that the end iterator can + // always point one beyond the last element without becomeing equal to + // an iterator to the first element. + size_type new_allocated_size = m_size + 1; + if (new_allocated_size < m_allocated_size) + realloc(new_allocated_size); // Throws + } + else { + m_memory_owner.reset(); + m_begin = 0; + m_allocated_size = 0; + } +} + +template inline auto CircularBuffer::capacity() const noexcept -> size_type +{ + return (m_allocated_size > 0 ? m_allocated_size - 1 : 0); +} + +template inline auto CircularBuffer::push_front(const T& value) -> reference +{ + return emplace_front(value); // Throws +} + +template inline auto CircularBuffer::push_back(const T& value) -> reference +{ + return emplace_back(value); // Throws +} + +template inline auto CircularBuffer::push_front(T&& value) -> reference +{ + return emplace_front(value); // Throws +} + +template inline auto CircularBuffer::push_back(T&& value) -> reference +{ + return emplace_back(value); // Throws +} + +template +template inline auto CircularBuffer::emplace_front(Args&&... args) -> reference +{ + size_type new_size = m_size + 1; + reserve(new_size); // Throws + REALM_ASSERT(m_allocated_size > 0); + T* memory = get_memory_ptr(); + size_type i = circular_dec(m_begin); + new (&memory[i]) T(std::forward(args)...); // Throws + m_begin = i; + m_size = new_size; + return memory[i]; +} + +template +template inline auto CircularBuffer::emplace_back(Args&&... args) -> reference +{ + size_type new_size = m_size + 1; + reserve(new_size); // Throws + REALM_ASSERT(m_allocated_size > 0); + T* memory = get_memory_ptr(); + size_type i = wrap(m_size); + new (&memory[i]) T(std::forward(args)...); // Throws + m_size = new_size; + return memory[i]; +} + +template inline void CircularBuffer::pop_front() noexcept +{ + REALM_ASSERT(m_size > 0); + T* memory = get_memory_ptr(); + memory[m_begin].~T(); + m_begin = circular_inc(m_begin); + --m_size; +} + +template inline void CircularBuffer::pop_back() noexcept +{ + REALM_ASSERT(m_size > 0); + T* memory = get_memory_ptr(); + size_type new_size = m_size - 1; + size_type i = wrap(new_size); + memory[i].~T(); + m_size = new_size; +} + +template inline void CircularBuffer::clear() noexcept +{ + destroy(); + m_begin = 0; + m_size = 0; +} + +template inline void CircularBuffer::resize(size_type size) +{ + if (size <= m_size) { + size_type offset = size; + destroy(offset); + m_size = size; + return; + } + reserve(size); // Throws + T* memory = get_memory_ptr(); + size_type i = wrap(m_size); + do { + new (&memory[i]) T(); // Throws + i = circular_inc(i); + ++m_size; + } + while (m_size < size); +} + +template inline void CircularBuffer::resize(size_type size, const T& value) +{ + if (size <= m_size) { + size_type offset = size; + destroy(offset); + m_size = size; + return; + } + reserve(size); // Throws + T* memory = get_memory_ptr(); + size_type i = wrap(m_size); + do { + new (&memory[i]) T(value); // Throws + i = circular_inc(i); + ++m_size; + } + while (m_size < size); +} + +template inline void CircularBuffer::swap(CircularBuffer& buffer) noexcept +{ + std::swap(m_memory_owner, buffer.m_memory_owner); + std::swap(m_begin, buffer.m_begin); + std::swap(m_size, buffer.m_size); + std::swap(m_allocated_size, buffer.m_allocated_size); +} + +template template +inline bool CircularBuffer::operator==(const CircularBuffer& buffer) const + noexcept(noexcept(std::declval() == std::declval())) +{ + return std::equal(begin(), end(), buffer.begin(), buffer.end()); // Throws +} + +template template +inline bool CircularBuffer::operator!=(const CircularBuffer& buffer) const + noexcept(noexcept(std::declval() == std::declval())) +{ + return !operator==(buffer); // Throws +} + +template template +inline bool CircularBuffer::operator<(const CircularBuffer& buffer) const + noexcept(noexcept(std::declval() < std::declval())) +{ + return std::lexicographical_compare(begin(), end(), buffer.begin(), buffer.end()); // Throws +} + +template template +inline bool CircularBuffer::operator>(const CircularBuffer& buffer) const + noexcept(noexcept(std::declval() < std::declval())) +{ + return (buffer < *this); // Throws +} + +template template +inline bool CircularBuffer::operator<=(const CircularBuffer& buffer) const + noexcept(noexcept(std::declval() < std::declval())) +{ + return !operator>(buffer); // Throws +} + +template template +inline bool CircularBuffer::operator>=(const CircularBuffer& buffer) const + noexcept(noexcept(std::declval() < std::declval())) +{ + return !operator<(buffer); // Throws +} + +template inline T* CircularBuffer::get_memory_ptr() noexcept +{ + return static_cast(static_cast(m_memory_owner.get())); +} + +template +inline auto CircularBuffer::circular_inc(size_type index) noexcept -> size_type +{ + size_type index_2 = index + 1; + if (REALM_LIKELY(index_2 < m_allocated_size)) + return index_2; + return 0; +} + +template +inline auto CircularBuffer::circular_dec(size_type index) noexcept -> size_type +{ + if (REALM_LIKELY(index > 0)) + return index - 1; + return m_allocated_size - 1; +} + +template +inline auto CircularBuffer::wrap(size_type index) noexcept -> size_type +{ + size_type top = m_allocated_size - m_begin; + if (index < top) + return m_begin + index; + return index - top; +} + +template +inline auto CircularBuffer::unwrap(size_type index) noexcept -> size_type +{ + if (index >= m_begin) + return index - m_begin; + return m_allocated_size - (m_begin - index); +} + +template template inline void CircularBuffer::copy(I begin, I end) +{ + using iterator_category = typename std::iterator_traits::iterator_category; + copy(begin, end, iterator_category{}); // Throws +} + +template template +inline void CircularBuffer::copy(I begin, I end, std::input_iterator_tag) +{ + for (I j = begin; j != end; ++j) + push_back(*j); // Throws +} + +template template +inline void CircularBuffer::copy(I begin, I end, std::forward_iterator_tag) +{ + REALM_ASSERT(m_begin == 0); + REALM_ASSERT(m_size == 0); + size_type size = std::distance(begin, end); + reserve(size); // Throws + T* memory = get_memory_ptr(); + for (I i = begin; i != end; ++i) { + new (&memory[m_size]) T(*i); // Throws + ++m_size; + } +} + +template inline void CircularBuffer::destroy(size_type offset) noexcept +{ + T* memory = get_memory_ptr(); + size_type j = m_begin; + for (size_type i = offset; i < m_size; ++i) { + memory[j].~T(); + j = circular_inc(j); + } +} + +template void CircularBuffer::realloc(size_type new_allocated_size) +{ + REALM_ASSERT(new_allocated_size > 1); + REALM_ASSERT(new_allocated_size > m_size); + + // Allocate new buffer + std::unique_ptr new_memory_owner = + std::make_unique(new_allocated_size); // Throws + T* memory = get_memory_ptr(); + + // Move or copy elements to new buffer + { + T* new_memory = static_cast(static_cast(new_memory_owner.get())); + size_type i = 0; + try { + size_type j = m_begin; + while (i < m_size) { + new (&new_memory[i]) T(std::move_if_noexcept(memory[j])); // Throws + ++i; + j = circular_inc(j); + } + } + catch (...) { + // If an exception was thrown above, we know that elements were + // copied, and not moved (assuming that T is copy constructable if + // it is not nothrow move constructible), so we need to back out by + // destroying the copies that were already made. + for (size_type j = 0; j < i; ++j) + new_memory[j].~T(); + throw; + } + } + + // Destroy old elements + { + size_type j = m_begin; + for (size_type i = 0; i < m_size; ++i) { + memory[j].~T(); + j = circular_inc(j); + } + } + + m_memory_owner = std::move(new_memory_owner); + m_begin = 0; + m_allocated_size = new_allocated_size; +} + +template inline void swap(CircularBuffer& a, CircularBuffer& b) noexcept +{ + a.swap(b); +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_CIRCULAR_BUFFER_HPP + diff --git a/Pods/Realm/include/core/realm/util/compression.hpp b/Pods/Realm/include/core/realm/util/compression.hpp new file mode 100644 index 0000000000..475a641523 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/compression.hpp @@ -0,0 +1,159 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_COMPRESSION_HPP +#define REALM_UTIL_COMPRESSION_HPP + +#include +#include +#include +#include +#include +#include + +#include + +namespace realm { +namespace util { +namespace compression { + +enum class error { + out_of_memory = 1, + compress_buffer_too_small = 2, + compress_error = 3, + corrupt_input = 4, + incorrect_decompressed_size = 5, + decompress_error = 6 +}; + +const std::error_category& error_category() noexcept; + +std::error_code make_error_code(error) noexcept; + +} // namespace compression +} // namespace util +} // namespace realm + +namespace std { + +template<> struct is_error_code_enum { + static const bool value = true; +}; + +} // namespace std + +namespace realm { +namespace util { +namespace compression { + +class Alloc { +public: + // Returns null on "out of memory" + virtual void* alloc(size_t size) = 0; + virtual void free(void* addr) noexcept = 0; + virtual ~Alloc() {} +}; + +class CompressMemoryArena: public Alloc { +public: + void* alloc(size_t size) override final + { + size_t offset = m_offset; + size_t padding = offset % alignof (std::max_align_t); + if (padding > m_size - offset) + return nullptr; + offset += padding; + void* addr = m_buffer.get() + offset; + if (size > m_size - offset) + return nullptr; + m_offset = offset + size; + return addr; + } + + void free(void*) noexcept override final + { + // No-op + } + + void reset() noexcept + { + m_offset = 0; + } + + size_t size() const noexcept + { + return m_size; + } + + void resize(size_t size) + { + m_buffer = std::make_unique(size); // Throws + m_size = size; + m_offset = 0; + } + +private: + size_t m_size = 0, m_offset = 0; + std::unique_ptr m_buffer; +}; + + +/// compress_bound() calculates an upper bound on the size of the compressed +/// data. The caller can use this function to allocate memory buffer calling +/// compress(). \a uncompressed_buf is the buffer with uncompressed data. The +/// size of the uncompressed data is \a uncompressed_size. \a compression_level +/// is described under compress(). \a bound is set to the upper bound at +/// return. The returned error code is of category compression::error_category. +std::error_code compress_bound(const char* uncompressed_buf, size_t uncompressed_size, + size_t& bound, int compression_level = 1); + +/// compress() compresses the data in the \a uncompressed_buf of size \a +/// uncompressed_size into \a compressed_buf. compress() resizes \a +/// compressed_buf. At return, \a compressed_buf has the size of the compressed +/// data. \a compression_level is [1-9] with 1 the fastest for the current zlib +/// implementation. The returned error code is of category +/// compression::error_category. +std::error_code compress(const char* uncompressed_buf, size_t uncompressed_size, + char* compressed_buf, size_t compressed_buf_size, + size_t& compressed_size, int compression_level = 1, + Alloc* custom_allocator = nullptr); + +/// decompress() decompresses the data in \param compressed_buf of size \a +/// compresed_size into \a decompressed_buf. \a decompressed_size is the +/// expected size of the decompressed data. \a decompressed_buf must have size +/// at least \a decompressed_size. decompress() throws on errors, including the +/// error where the size of the decompressed data is unequal to +/// decompressed_size. The returned error code is of category +/// compression::error_category. +std::error_code decompress(const char* compressed_buf, size_t compressed_size, + char* decompressed_buf, size_t decompressed_size); + + +size_t allocate_and_compress(CompressMemoryArena& compress_memory_arena, + BinaryData uncompressed_buf, + std::vector& compressed_buf); + + + +} // namespace compression +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_COMPRESSION_HPP diff --git a/Pods/Realm/include/core/realm/util/config.h b/Pods/Realm/include/core/realm/util/config.h new file mode 100644 index 0000000000..90229b01f2 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/config.h @@ -0,0 +1,24 @@ +// Version information +#define REALM_VERSION "" + +// Specific headers +#define HAVE_MALLOC_H 0 + +// Realm-specific configuration +#define REALM_MAX_BPNODE_SIZE 1000 +/* #undef REALM_MAX_BPNODE_SIZE_DEBUG */ +#define REALM_ENABLE_ASSERTIONS 0 +#define REALM_ENABLE_ALLOC_SET_ZERO 0 +#define REALM_ENABLE_ENCRYPTION 1 +#define REALM_ENABLE_MEMDEBUG 0 +#define REALM_VALGRIND 0 +#define REALM_METRICS 1 +#define REALM_ASAN 0 +#define REALM_TSAN 0 + +#define REALM_INSTALL_PREFIX "/usr/local" +#define REALM_INSTALL_INCLUDEDIR "include" +#define REALM_INSTALL_BINDIR "bin" +#define REALM_INSTALL_LIBDIR "lib" +#define REALM_INSTALL_LIBEXECDIR "libexec" +#define REALM_INSTALL_EXEC_PREFIX "/usr/local" diff --git a/Pods/Realm/include/core/realm/util/demangle.hpp b/Pods/Realm/include/core/realm/util/demangle.hpp new file mode 100644 index 0000000000..7af4fb84ec --- /dev/null +++ b/Pods/Realm/include/core/realm/util/demangle.hpp @@ -0,0 +1,54 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_UTIL_DEMANGLE_HPP +#define REALM_UTIL_DEMANGLE_HPP + +#include +#include + +namespace realm { +namespace util { + + +/// Demangle the specified C++ ABI identifier. +/// +/// See for example +/// http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/namespaceabi.html +std::string demangle(const std::string&); + + +/// Get the demangled name of the specified type. +template inline std::string get_type_name() +{ + return demangle(typeid(T).name()); +} + + +/// Get the demangled name of the type of the specified argument. +template inline std::string get_type_name(const T& v) +{ + return demangle(typeid(v).name()); +} + + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_DEMANGLE_HPP diff --git a/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp b/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp new file mode 100644 index 0000000000..e110e97682 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp @@ -0,0 +1,176 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_ENCRYPTED_FILE_MAPPING_HPP +#define REALM_UTIL_ENCRYPTED_FILE_MAPPING_HPP + +#include +#include +#include + +#if REALM_ENABLE_ENCRYPTION + +typedef size_t (*Header_to_size)(const char* addr); + +#include + +namespace realm { +namespace util { + +struct SharedFileInfo; +class EncryptedFileMapping; + +class EncryptedFileMapping { +public: + // Adds the newly-created object to file.mappings iff it's successfully constructed + EncryptedFileMapping(SharedFileInfo& file, size_t file_offset, void* addr, size_t size, File::AccessMode access); + ~EncryptedFileMapping(); + + // Default implementations of copy/assign can trigger multiple destructions + EncryptedFileMapping(const EncryptedFileMapping&) = delete; + EncryptedFileMapping& operator=(const EncryptedFileMapping&) = delete; + + // Write all dirty pages to disk and mark them read-only + // Does not call fsync + void flush() noexcept; + + // Sync this file to disk + void sync() noexcept; + + // Make sure that memory in the specified range is synchronized with any + // changes made globally visible through call to write_barrier + void read_barrier(const void* addr, size_t size, UniqueLock& lock, Header_to_size header_to_size); + + // Ensures that any changes made to memory in the specified range + // becomes visible to any later calls to read_barrier() + void write_barrier(const void* addr, size_t size) noexcept; + + // Set this mapping to a new address and size + // Flushes any remaining dirty pages from the old mapping + void set(void* new_addr, size_t new_size, size_t new_file_offset); + + bool contains_page(size_t page_in_file) const; + size_t get_local_index_of_address(const void* addr, size_t offset = 0) const; + +private: + SharedFileInfo& m_file; + + size_t m_page_shift; + size_t m_blocks_per_page; + + void* m_addr = nullptr; + + size_t m_first_page; + + // MUST be of type char because of coherence issues when writing inside mutex and reading outside + // it. FIXME: We're investigating if this is good enough, or if we need further mechanisms + std::vector m_up_to_date_pages; + std::vector m_dirty_pages; + + File::AccessMode m_access; + +#ifdef REALM_DEBUG + std::unique_ptr m_validate_buffer; +#endif + + char* page_addr(size_t local_page_ndx) const noexcept; + + void mark_outdated(size_t local_page_ndx) noexcept; + bool copy_up_to_date_page(size_t local_page_ndx) noexcept; + void refresh_page(size_t local_page_ndx); + void write_page(size_t local_page_ndx) noexcept; + + void validate_page(size_t local_page_ndx) noexcept; + void validate() noexcept; +}; + +inline size_t EncryptedFileMapping::get_local_index_of_address(const void* addr, size_t offset) const +{ + REALM_ASSERT_EX(addr >= m_addr, addr, m_addr); + + size_t local_ndx = ((reinterpret_cast(addr) - reinterpret_cast(m_addr) + offset) >> m_page_shift); + REALM_ASSERT_EX(local_ndx < m_up_to_date_pages.size(), local_ndx, m_up_to_date_pages.size()); + return local_ndx; +} + +inline bool EncryptedFileMapping::contains_page(size_t page_in_file) const +{ + // first check for (page_in_file >= m_first_page) so that the following + // subtraction using unsigned types never wraps under 0 + return page_in_file >= m_first_page && page_in_file - m_first_page < m_up_to_date_pages.size(); +} + +inline void EncryptedFileMapping::read_barrier(const void* addr, size_t size, UniqueLock& lock, + Header_to_size header_to_size) +{ + size_t first_accessed_local_page = get_local_index_of_address(addr); + + // make sure the first page is available + // Checking before taking the lock is important to performance. + if (!m_up_to_date_pages[first_accessed_local_page]) { + if (!lock.holds_lock()) + lock.lock(); + // after taking the lock, we must repeat the check so that we never + // call refresh_page() on a page which is already up to date. + if (!m_up_to_date_pages[first_accessed_local_page]) + refresh_page(first_accessed_local_page); + } + + if (header_to_size) { + + // We know it's an array, and array headers are 8-byte aligned, so it is + // included in the first page which was handled above. + size = header_to_size(static_cast(addr)); + } + + size_t last_idx = get_local_index_of_address(addr, size == 0 ? 0 : size - 1); + size_t up_to_date_pages_size = m_up_to_date_pages.size(); + + // We already checked first_accessed_local_page above, so we start the loop + // at first_accessed_local_page + 1 to check the following page. + for (size_t idx = first_accessed_local_page + 1; idx <= last_idx && idx < up_to_date_pages_size; ++idx) { + if (!m_up_to_date_pages[idx]) { + if (!lock.holds_lock()) + lock.lock(); + // after taking the lock, we must repeat the check so that we never + // call refresh_page() on a page which is already up to date. + if (!m_up_to_date_pages[idx]) + refresh_page(idx); + } + } +} +} +} + +#endif // REALM_ENABLE_ENCRYPTION + +namespace realm { +namespace util { + +/// Thrown by EncryptedFileMapping if a file opened is non-empty and does not +/// contain valid encrypted data +struct DecryptionFailed : util::File::AccessError { + DecryptionFailed() + : util::File::AccessError("Decryption failed", std::string()) + { + } +}; +} +} + +#endif // REALM_UTIL_ENCRYPTED_FILE_MAPPING_HPP diff --git a/Pods/Realm/include/core/realm/util/enum.hpp b/Pods/Realm/include/core/realm/util/enum.hpp new file mode 100644 index 0000000000..c11d166a7a --- /dev/null +++ b/Pods/Realm/include/core/realm/util/enum.hpp @@ -0,0 +1,224 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_ENUM_HPP +#define REALM_UTIL_ENUM_HPP + +#include +#include +#include +#include + + +namespace realm { +namespace util { + +/// This template class allows you to endow a fundamental `enum` type with +/// information about how to print out the individual values, and how to parse +/// them. +/// +/// Here is an example: +/// +/// // Declaration +/// +/// enum class Color { orange, purple, brown }; +/// +/// struct ColorSpec { static EnumAssoc map[]; }; +/// using ColorEnum = Enum; +/// +/// // Implementation +/// +/// EnumAssoc ColorSpec::map[] = { +/// { int(Color::orange), "orange" }, +/// { int(Color::purple), "purple" }, +/// { int(Color::brown), "brown" }, +/// { 0, 0 } +/// }; +/// +/// // Application +/// +/// ColorEnum color = Color::purple; +/// +/// std::cout << color; // Write a color +/// std::cin >> color; // Read a color +/// +/// The current implementation is restricted to enumeration types whose values +/// can all be represented in a regular integer. +template class Enum { +public: + using base_enum_type = E; + + Enum(E = {}) noexcept; + + operator E() const noexcept; + + const std::string& str() const; + + bool str(const std::string*&) const noexcept; + + /// \return True if, and only if successful. + static bool parse(const std::string& string, E& value); + +private: + E m_value = E{}; +}; + +template +std::basic_ostream& operator<<(std::basic_ostream&, + const Enum&); + +template +std::basic_istream& operator>>(std::basic_istream&, + Enum&); + + +struct EnumAssoc { + const int value; + const char* const name; +}; + + + + +// Implementation + +} // namespace util + +namespace _impl { + +class EnumMapper { +public: + EnumMapper(const util::EnumAssoc*, bool ignore_case); + + bool parse(const std::string& string, int& value, bool ignore_case) const; + + std::map value_to_name; + std::map name_to_value; +}; + +template const EnumMapper& get_enum_mapper() +{ + static EnumMapper mapper{S::map, ignore_case}; // Throws + return mapper; +} + +} // namespace _impl + +namespace util { + +template +inline Enum::Enum(E value) noexcept : + m_value{value} +{ +} + +template +inline Enum::operator E() const noexcept +{ + return m_value; +} + +template +inline const std::string& Enum::str() const +{ + return _impl::get_enum_mapper().val_to_name.at(m_value); // Throws +} + +template +inline bool Enum::str(const std::string*& string) const noexcept +{ + const auto& value_to_name = _impl::get_enum_mapper().value_to_name; + auto i = value_to_name.find(int(m_value)); + if (i == value_to_name.end()) + return false; + string = &i->second; + return true; +} + +template +inline bool Enum::parse(const std::string& string, E& value) +{ + int value_2; + if (!_impl::get_enum_mapper().parse(string, value_2, ignore_case)) // Throws + return false; + value = E(value_2); + return true; +} + +template +inline std::basic_ostream& operator<<(std::basic_ostream& out, + const Enum& e) +{ + const std::string* string; + if (e.str(string)) { + out << *string; + } + else { + out << int(E(e)); + } + return out; +} + +template +std::basic_istream& operator>>(std::basic_istream& in, + Enum& e) +{ + if (in.bad() || in.fail()) + return in; + std::string string; + const std::ctype& ctype = std::use_facet>(in.getloc()); + C underscore(ctype.widen('_')); + for (;;) { + C ch; + // Allow white-spaces to be skipped when stream is configured + // that way + if (string.empty()) { + in >> ch; + } + else { + in.get(ch); + } + if (!in) { + if (in.bad()) + return in; + in.clear(in.rdstate() & ~std::ios_base::failbit); + break; + } + if (!ctype.is(std::ctype_base::alnum, ch) && ch != underscore) { + in.unget(); + break; + } + char ch_2 = ctype.narrow(ch, '\0'); + string += ch_2; + } + E value = E{}; + if (!Enum::parse(string, value)) { // Throws + in.setstate(std::ios_base::badbit); + } + else { + e = value; + } + return in; +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_ENUM_HPP diff --git a/Pods/Realm/include/core/realm/util/errno.hpp b/Pods/Realm/include/core/realm/util/errno.hpp new file mode 100644 index 0000000000..4907f369d1 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/errno.hpp @@ -0,0 +1,39 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_ERRNO_HPP +#define REALM_UTIL_ERRNO_HPP + +#include + +#include + + +namespace realm { +namespace util { + +// Get the error message for a given error code, and append it to `prefix` +inline std::string get_errno_msg(const char* prefix, int err) +{ + return prefix + make_basic_system_error_code(err).message(); +} + +} // namespace util +} // namespace realm + +#endif diff --git a/Pods/Realm/include/core/realm/util/features.h b/Pods/Realm/include/core/realm/util/features.h new file mode 100644 index 0000000000..2628903e1b --- /dev/null +++ b/Pods/Realm/include/core/realm/util/features.h @@ -0,0 +1,304 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_FEATURES_H +#define REALM_UTIL_FEATURES_H + +#ifdef _MSC_VER +#pragma warning(disable : 4800) // Visual Studio int->bool performance warnings +#endif + +#if defined(_WIN32) && !defined(NOMINMAX) +#define NOMINMAX +#endif + +#include + +/* The maximum number of elements in a B+-tree node. Applies to inner nodes and + * to leaves. The minimum allowable value is 2. + */ +#ifndef REALM_MAX_BPNODE_SIZE +#define REALM_MAX_BPNODE_SIZE 1000 +#endif + + +#define REALM_QUOTE_2(x) #x +#define REALM_QUOTE(x) REALM_QUOTE_2(x) + +/* See these links for information about feature check macroes in GCC, + * Clang, and MSVC: + * + * http://gcc.gnu.org/projects/cxx0x.html + * http://clang.llvm.org/cxx_status.html + * http://clang.llvm.org/docs/LanguageExtensions.html#checks-for-standard-language-features + * http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx + * http://sourceforge.net/p/predef/wiki/Compilers + */ + + +/* Compiler is GCC and version is greater than or equal to the specified version */ +#define REALM_HAVE_AT_LEAST_GCC(maj, min) \ + (__GNUC__ > (maj) || __GNUC__ == (maj) && __GNUC_MINOR__ >= (min)) + +#if defined(__clang__) +#define REALM_HAVE_CLANG_FEATURE(feature) __has_feature(feature) +#define REALM_HAVE_CLANG_WARNING(warning) __has_warning(warning) +#else +#define REALM_HAVE_CLANG_FEATURE(feature) 0 +#define REALM_HAVE_CLANG_WARNING(warning) 0 +#endif + +#ifdef __has_cpp_attribute +#define REALM_HAS_CPP_ATTRIBUTE(attr) __has_cpp_attribute(attr) +#else +#define REALM_HAS_CPP_ATTRIBUTE(attr) 0 +#endif + +#if REALM_HAS_CPP_ATTRIBUTE(clang::fallthrough) +#define REALM_FALLTHROUGH [[clang::fallthrough]] +#elif REALM_HAS_CPP_ATTRIBUTE(fallthrough) +#define REALM_FALLTHROUGH [[fallthrough]] +#else +#define REALM_FALLTHROUGH +#endif + +// This should be renamed to REALM_UNREACHABLE as soon as REALM_UNREACHABLE is renamed to +// REALM_ASSERT_NOT_REACHED which will better reflect its nature +#if defined(__GNUC__) || defined(__clang__) +#define REALM_COMPILER_HINT_UNREACHABLE __builtin_unreachable +#else +#define REALM_COMPILER_HINT_UNREACHABLE abort +#endif + +#if defined(__GNUC__) // clang or GCC +#define REALM_PRAGMA(v) _Pragma(REALM_QUOTE_2(v)) +#elif defined(_MSC_VER) // VS +#define REALM_PRAGMA(v) __pragma(v) +#else +#define REALM_PRAGMA(v) +#endif + +#if defined(__clang__) +#define REALM_DIAG(v) REALM_PRAGMA(clang diagnostic v) +#elif defined(__GNUC__) +#define REALM_DIAG(v) REALM_PRAGMA(GCC diagnostic v) +#else +#define REALM_DIAG(v) +#endif + +#define REALM_DIAG_PUSH() REALM_DIAG(push) +#define REALM_DIAG_POP() REALM_DIAG(pop) + +#ifdef _MSC_VER +#define REALM_VS_WARNING_DISABLE #pragma warning (default: 4297) +#endif + +#if REALM_HAVE_CLANG_WARNING("-Wtautological-compare") || REALM_HAVE_AT_LEAST_GCC(6, 0) +#define REALM_DIAG_IGNORE_TAUTOLOGICAL_COMPARE() REALM_DIAG(ignored "-Wtautological-compare") +#else +#define REALM_DIAG_IGNORE_TAUTOLOGICAL_COMPARE() +#endif + +#ifdef _MSC_VER +# define REALM_DIAG_IGNORE_UNSIGNED_MINUS() REALM_PRAGMA(warning(disable:4146)) +#else +#define REALM_DIAG_IGNORE_UNSIGNED_MINUS() +#endif + +/* Compiler is MSVC (Microsoft Visual C++) */ +#if defined(_MSC_VER) && _MSC_VER >= 1600 +#define REALM_HAVE_AT_LEAST_MSVC_10_2010 1 +#endif +#if defined(_MSC_VER) && _MSC_VER >= 1700 +#define REALM_HAVE_AT_LEAST_MSVC_11_2012 1 +#endif +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#define REALM_HAVE_AT_LEAST_MSVC_12_2013 1 +#endif + + +/* The way to specify that a function never returns. */ +#if REALM_HAVE_AT_LEAST_GCC(4, 8) || REALM_HAVE_CLANG_FEATURE(cxx_attributes) +#define REALM_NORETURN [[noreturn]] +#elif __GNUC__ +#define REALM_NORETURN __attribute__((noreturn)) +#elif defined(_MSC_VER) +#define REALM_NORETURN __declspec(noreturn) +#else +#define REALM_NORETURN +#endif + + +/* The way to specify that a variable or type is intended to possibly + * not be used. Use it to suppress a warning from the compiler. */ +#if __GNUC__ +#define REALM_UNUSED __attribute__((unused)) +#else +#define REALM_UNUSED +#endif + +/* The way to specify that a function is deprecated + * not be used. Use it to suppress a warning from the compiler. */ +#if __GNUC__ +#define REALM_DEPRECATED(x) [[deprecated(x)]] +#else +#define REALM_DEPRECATED(x) __declspec(deprecated(x)) +#endif + + +#if __GNUC__ || defined __INTEL_COMPILER +#define REALM_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#define REALM_LIKELY(expr) __builtin_expect(!!(expr), 1) +#else +#define REALM_UNLIKELY(expr) (expr) +#define REALM_LIKELY(expr) (expr) +#endif + + +#if defined(__GNUC__) || defined(__HP_aCC) +#define REALM_FORCEINLINE inline __attribute__((always_inline)) +#elif defined(_MSC_VER) +#define REALM_FORCEINLINE __forceinline +#else +#define REALM_FORCEINLINE inline +#endif + + +#if defined(__GNUC__) || defined(__HP_aCC) +#define REALM_NOINLINE __attribute__((noinline)) +#elif defined(_MSC_VER) +#define REALM_NOINLINE __declspec(noinline) +#else +#define REALM_NOINLINE +#endif + + +/* Thread specific data (only for POD types) */ +#if defined __clang__ +#define REALM_THREAD_LOCAL __thread +#else +#define REALM_THREAD_LOCAL thread_local +#endif + + +#if defined ANDROID +#define REALM_ANDROID 1 +#else +#define REALM_ANDROID 0 +#endif + +#if defined _WIN32 +# include +# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM) +# define REALM_WINDOWS 1 +# define REALM_UWP 0 +# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) +# define REALM_WINDOWS 0 +# define REALM_UWP 1 +# endif +#else +#define REALM_WINDOWS 0 +#define REALM_UWP 0 +#endif + +// Some documentation of the defines provided by Apple: +// http://developer.apple.com/library/mac/documentation/Porting/Conceptual/PortingUnix/compiling/compiling.html#//apple_ref/doc/uid/TP40002850-SW13 +#if defined __APPLE__ && defined __MACH__ +#define REALM_PLATFORM_APPLE 1 +/* Apple OSX and iOS (Darwin). */ +#include +#include +#if TARGET_OS_IPHONE == 1 +/* Device (iPhone or iPad) or simulator. */ +#define REALM_IOS 1 +#else +#define REALM_IOS 0 +#endif +#if TARGET_OS_WATCH == 1 +/* Device (Apple Watch) or simulator. */ +#define REALM_WATCHOS 1 +#else +#define REALM_WATCHOS 0 +#endif +#if TARGET_OS_TV +/* Device (Apple TV) or simulator. */ +#define REALM_TVOS 1 +#else +#define REALM_TVOS 0 +#endif +#else +#define REALM_PLATFORM_APPLE 0 +#define REALM_IOS 0 +#define REALM_WATCHOS 0 +#define REALM_TVOS 0 +#endif + +// asl_log is deprecated in favor of os_log as of the following versions: +// macos(10.12), ios(10.0), watchos(3.0), tvos(10.0) +// versions are defined in /usr/include/Availability.h +// __MAC_10_12 101200 +// __IPHONE_10_0 100000 +// __WATCHOS_3_0 30000 +// __TVOS_10_0 100000 +#if REALM_PLATFORM_APPLE \ + && ( \ + (REALM_IOS && defined(__IPHONE_OS_VERSION_MIN_REQUIRED) \ + && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000) \ + || (REALM_TVOS && defined(__TV_OS_VERSION_MIN_REQUIRED) \ + && __TV_OS_VERSION_MIN_REQUIRED >= 100000) \ + || (REALM_WATCHOS && defined(__WATCH_OS_VERSION_MIN_REQUIRED) \ + && __WATCH_OS_VERSION_MIN_REQUIRED >= 30000) \ + || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) \ + && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) \ + ) +#define REALM_APPLE_OS_LOG 1 +#else +#define REALM_APPLE_OS_LOG 0 +#endif + +#if REALM_ANDROID || REALM_IOS || REALM_WATCHOS || REALM_TVOS || REALM_UWP +#define REALM_MOBILE 1 +#else +#define REALM_MOBILE 0 +#endif + + +#if defined(REALM_DEBUG) && !defined(REALM_COOKIE_CHECK) +#define REALM_COOKIE_CHECK +#endif + +#if !REALM_IOS && !REALM_WATCHOS && !REALM_TVOS && !defined(_WIN32) && !REALM_ANDROID +#define REALM_ASYNC_DAEMON +#endif + +// We're in i686 mode +#if defined(__i386) || defined(__i386__) || defined(__i686__) || defined(_M_I86) || defined(_M_IX86) +#define REALM_ARCHITECTURE_X86_32 1 +#else +#define REALM_ARCHITECTURE_X86_32 0 +#endif + +// We're in amd64 mode +#if defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ + defined(_M_AMD64) +#define REALM_ARCHITECTURE_X86_64 1 +#else +#define REALM_ARCHITECTURE_X86_64 0 +#endif + +#endif /* REALM_UTIL_FEATURES_H */ diff --git a/Pods/Realm/include/core/realm/util/file.hpp b/Pods/Realm/include/core/realm/util/file.hpp new file mode 100644 index 0000000000..d85d222415 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/file.hpp @@ -0,0 +1,1314 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_FILE_HPP +#define REALM_UTIL_FILE_HPP + +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include // POSIX.1-2001 +#endif + +#if defined(_MSC_VER) && _MSC_VER >= 1900 // compiling with at least Visual Studio 2015 +#include +namespace std { + namespace filesystem = std::experimental::filesystem::v1; +} +#define REALM_HAVE_STD_FILESYSTEM 1 +#else +#define REALM_HAVE_STD_FILESYSTEM 0 +#endif + +#include +#include +#include +#include +#include + + +namespace realm { +namespace util { + +class EncryptedFileMapping; + +/// Create the specified directory in the file system. +/// +/// \throw File::AccessError If the directory could not be created. If +/// the reason corresponds to one of the exception types that are +/// derived from File::AccessError, the derived exception type is +/// thrown (as long as the underlying system provides the information +/// to unambiguously distinguish that particular reason). +void make_dir(const std::string& path); + +/// Same as make_dir() except that this one returns false, rather than throwing +/// an exception, if the specified directory already existed. If the directory +// did not already exist and was newly created, this returns true. +bool try_make_dir(const std::string& path); + +/// Remove the specified empty directory path from the file system. It is an +/// error if the specified path is not a directory, or if it is a nonempty +/// directory. In so far as the specified path is a directory, std::remove(const +/// char*) is equivalent to this function. +/// +/// \throw File::AccessError If the directory could not be removed. If the +/// reason corresponds to one of the exception types that are derived from +/// File::AccessError, the derived exception type is thrown (as long as the +/// underlying system provides the information to unambiguously distinguish that +/// particular reason). +void remove_dir(const std::string& path); + +/// Same as remove_dir() except that this one returns false, rather +/// than throwing an exception, if the specified directory did not +/// exist. If the directory did exist, and was deleted, this function +/// returns true. +bool try_remove_dir(const std::string& path); + +/// Remove the specified directory after removing all its contents. Files +/// (nondirectory entries) will be removed as if by a call to File::remove(), +/// and empty directories as if by a call to remove_dir(). +/// +/// \throw File::AccessError If removal of the directory, or any of its contents +/// fail. +/// +/// remove_dir_recursive() assumes that no other process or thread is making +/// simultaneous changes in the directory. +void remove_dir_recursive(const std::string& path); + +/// Same as remove_dir_recursive() except that this one returns false, rather +/// than throwing an exception, if the specified directory did not +/// exist. If the directory did exist, and was deleted, this function +/// returns true. +/// +/// try_remove_dir_recursive() assumes that no other process or thread is making +/// simultaneous changes in the directory. +bool try_remove_dir_recursive(const std::string& path); + +/// Create a new unique directory for temporary files. The absolute +/// path to the new directory is returned without a trailing slash. +std::string make_temp_dir(); + +size_t page_size(); + + +/// This class provides a RAII abstraction over the concept of a file +/// descriptor (or file handle). +/// +/// Locks are automatically and immediately released when the File +/// instance is closed. +/// +/// You can use CloseGuard and UnlockGuard to acheive exception-safe +/// closing or unlocking prior to the File instance being detroyed. +/// +/// A single File instance must never be accessed concurrently by +/// multiple threads. +/// +/// You can write to a file via an std::ostream as follows: +/// +/// \code{.cpp} +/// +/// File::Streambuf my_streambuf(&my_file); +/// std::ostream out(&my_strerambuf); +/// out << 7945.9; +/// +/// \endcode +class File { +public: + enum Mode { + mode_Read, ///< access_ReadOnly, create_Never (fopen: rb) + mode_Update, ///< access_ReadWrite, create_Never (fopen: rb+) + mode_Write, ///< access_ReadWrite, create_Auto, flag_Trunc (fopen: wb+) + mode_Append ///< access_ReadWrite, create_Auto, flag_Append (fopen: ab+) + }; + + /// Equivalent to calling open(const std::string&, Mode) on a + /// default constructed instance. + explicit File(const std::string& path, Mode = mode_Read); + + /// Create an instance that is not initially attached to an open + /// file. + File() noexcept; + + ~File() noexcept; + + File(File&&) noexcept; + File& operator=(File&&) noexcept; + + // Disable copying by l-value. Copying an open file will create a scenario + // where the same file descriptor will be opened once but closed twice. + File(const File&) = delete; + File& operator=(const File&) = delete; + + /// Calling this function on an instance that is already attached + /// to an open file has undefined behavior. + /// + /// \throw AccessError If the file could not be opened. If the + /// reason corresponds to one of the exception types that are + /// derived from AccessError, the derived exception type is thrown + /// (as long as the underlying system provides the information to + /// unambiguously distinguish that particular reason). + void open(const std::string& path, Mode = mode_Read); + + /// This function is idempotent, that is, it is valid to call it + /// regardless of whether this instance currently is attached to + /// an open file. + void close() noexcept; + + /// Check whether this File instance is currently attached to an + /// open file. + bool is_attached() const noexcept; + + enum AccessMode { + access_ReadOnly, + access_ReadWrite, + }; + + enum CreateMode { + create_Auto, ///< Create the file if it does not already exist. + create_Never, ///< Fail if the file does not already exist. + create_Must ///< Fail if the file already exists. + }; + + enum { + flag_Trunc = 1, ///< Truncate the file if it already exists. + flag_Append = 2 ///< Move to end of file before each write. + }; + + /// See open(const std::string&, Mode). + /// + /// Specifying access_ReadOnly together with a create mode that is + /// not create_Never, or together with a non-zero \a flags + /// argument, results in undefined behavior. Specifying flag_Trunc + /// together with create_Must results in undefined behavior. + void open(const std::string& path, AccessMode, CreateMode, int flags); + + /// Same as open(path, access_ReadWrite, create_Auto, 0), except + /// that this one returns an indication of whether a new file was + /// created, or an existing file was opened. + void open(const std::string& path, bool& was_created); + + /// Read data into the specified buffer and return the number of + /// bytes read. If the returned number of bytes is less than \a + /// size, then the end of the file has been reached. + /// + /// Calling this function on an instance, that is not currently + /// attached to an open file, has undefined behavior. + size_t read(char* data, size_t size); + static size_t read_static(FileDesc fd, char* data, size_t size); + + /// Write the specified data to this file. + /// + /// Calling this function on an instance, that is not currently + /// attached to an open file, has undefined behavior. + /// + /// Calling this function on an instance, that was opened in + /// read-only mode, has undefined behavior. + void write(const char* data, size_t size); + static void write_static(FileDesc fd, const char* data, size_t size); + + // Tells current file pointer of fd + static uint64_t get_file_pos(FileDesc fd); + + /// Calls write(s.data(), s.size()). + void write(const std::string& s) + { + write(s.data(), s.size()); + } + + /// Calls read(data, N). + template + size_t read(char (&data)[N]) + { + return read(data, N); + } + + /// Calls write(data(), N). + template + void write(const char (&data)[N]) + { + write(data, N); + } + + /// Plays the same role as off_t in POSIX + typedef int_fast64_t SizeType; + + /// Calling this function on an instance that is not attached to + /// an open file has undefined behavior. + SizeType get_size() const; + static SizeType get_size_static(FileDesc fd); + + /// If this causes the file to grow, then the new section will + /// have undefined contents. Setting the size with this function + /// does not necessarily allocate space on the target device. If + /// you want to ensure allocation, call alloc(). Calling this + /// function will generally affect the read/write offset + /// associated with this File instance. + /// + /// Calling this function on an instance that is not attached to + /// an open file has undefined behavior. Calling this function on + /// a file that is opened in read-only mode, is an error. + void resize(SizeType); + + /// Same effect as prealloc_if_supported(original_size, new_size); + /// + /// The downside is that this function is not guaranteed to have + /// atomic behaviour on all systems, that is, two processes, or + /// two threads should never call this function concurrently for + /// the same underlying file even though they access the file + /// through distinct File instances. + /// + /// \sa prealloc_if_supported() + void prealloc(size_t new_size); + + /// When supported by the system, allocate space on the target + /// device for the specified region of the file. If the region + /// extends beyond the current end of the file, the file size is + /// increased as necessary. + /// + /// On systems that do not support this operation, this function + /// has no effect. You may call is_prealloc_supported() to + /// determine if it is supported on your system. + /// + /// Calling this function on an instance, that is not attached to + /// an open file, has undefined behavior. Calling this function on + /// a file, that is opened in read-only mode, is an error. + /// + /// This function is guaranteed to have atomic behaviour, that is, + /// there is never any risk of the file size being reduced even + /// with concurrently executing invocations. + /// + /// \sa prealloc() + /// \sa is_prealloc_supported() + void prealloc_if_supported(SizeType offset, size_t size); + + /// See prealloc_if_supported(). + static bool is_prealloc_supported(); + + /// Reposition the read/write offset of this File + /// instance. Distinct File instances have separate independent + /// offsets, as long as the cucrrent process is not forked. + void seek(SizeType); + static void seek_static(FileDesc, SizeType); + + /// Flush in-kernel buffers to disk. This blocks the caller until the + /// synchronization operation is complete. On POSIX systems this function + /// calls `fsync()`. On Apple platforms if calls `fcntl()` with command + /// `F_FULLFSYNC`. + void sync(); + + /// Place an exclusive lock on this file. This blocks the caller + /// until all other locks have been released. + /// + /// Locks acquired on distinct File instances have fully recursive + /// behavior, even if they are acquired in the same process (or + /// thread) and are attached to the same underlying file. + /// + /// Calling this function on an instance that is not attached to + /// an open file, or on an instance that is already locked has + /// undefined behavior. + void lock_exclusive(); + + /// Place an shared lock on this file. This blocks the caller + /// until all other exclusive locks have been released. + /// + /// Locks acquired on distinct File instances have fully recursive + /// behavior, even if they are acquired in the same process (or + /// thread) and are attached to the same underlying file. + /// + /// Calling this function on an instance that is not attached to + /// an open file, or on an instance that is already locked has + /// undefined behavior. + void lock_shared(); + + /// Non-blocking version of lock_exclusive(). Returns true iff it + /// succeeds. + bool try_lock_exclusive(); + + /// Non-blocking version of lock_shared(). Returns true iff it + /// succeeds. + bool try_lock_shared(); + + /// Release a previously acquired lock on this file. This function + /// is idempotent. + void unlock() noexcept; + + /// Set the encryption key used for this file. Must be called before any + /// mappings are created or any data is read from or written to the file. + /// + /// \param key A 64-byte encryption key, or null to disable encryption. + void set_encryption_key(const char* key); + + /// Get the encryption key set by set_encryption_key(), + /// null_ptr if no key set. + const char* get_encryption_key(); + enum { + /// If possible, disable opportunistic flushing of dirted + /// pages of a memory mapped file to physical medium. On some + /// systems this cannot be disabled. On other systems it is + /// the default behavior. An explicit call to sync_map() will + /// flush the buffers regardless of whether this flag is + /// specified or not. + map_NoSync = 1 + }; + + /// Map this file into memory. The file is mapped as shared + /// memory. This allows two processes to interact under exatly the + /// same rules as applies to the interaction via regular memory of + /// multiple threads inside a single process. + /// + /// This File instance does not need to remain in existence after + /// the mapping is established. + /// + /// Multiple concurrent mappings may be created from the same File + /// instance. + /// + /// Specifying access_ReadWrite for a file that is opened in + /// read-only mode, is an error. + /// + /// Calling this function on an instance that is not attached to + /// an open file, or one that is attached to an empty file has + /// undefined behavior. + /// + /// Calling this function with a size that is greater than the + /// size of the file has undefined behavior. + void* map(AccessMode, size_t size, int map_flags = 0, size_t offset = 0) const; + + /// The same as unmap(old_addr, old_size) followed by map(a, + /// new_size, map_flags), but more efficient on some systems. + /// + /// The old address range must have been acquired by a call to + /// map() or remap() on this File instance, the specified access + /// mode and flags must be the same as the ones specified + /// previously, and this File instance must not have been reopend + /// in the meantime. Failing to adhere to these rules will result + /// in undefined behavior. + /// + /// If this function throws, the old address range will remain + /// mapped. + void* remap(void* old_addr, size_t old_size, AccessMode a, size_t new_size, int map_flags = 0, + size_t file_offset = 0) const; + +#if REALM_ENABLE_ENCRYPTION + void* map(AccessMode, size_t size, EncryptedFileMapping*& mapping, int map_flags = 0, size_t offset = 0) const; +#endif + /// Unmap the specified address range which must have been + /// previously returned by map(). + static void unmap(void* addr, size_t size) noexcept; + + /// Flush in-kernel buffers to disk. This blocks the caller until + /// the synchronization operation is complete. The specified + /// address range must be (a subset of) one that was previously returned by + /// map(). + static void sync_map(FileDesc fd, void* addr, size_t size); + + /// Check whether the specified file or directory exists. Note + /// that a file or directory that resides in a directory that the + /// calling process has no access to, will necessarily be reported + /// as not existing. + static bool exists(const std::string& path); + + /// Check whether the specified path exists and refers to a directory. If + /// the referenced file system object resides in an inaccessible directory, + /// this function returns false. + static bool is_dir(const std::string& path); + + /// Remove the specified file path from the file system. It is an error if + /// the specified path is a directory. If the specified file is a symbolic + /// link, the link is removed, leaving the liked file intact. In so far as + /// the specified path is not a directory, std::remove(const char*) is + /// equivalent to this function. + /// + /// The specified file must not be open by the calling process. If + /// it is, this function has undefined behaviour. Note that an + /// open memory map of the file counts as "the file being open". + /// + /// \throw AccessError If the specified directory entry could not + /// be removed. If the reason corresponds to one of the exception + /// types that are derived from AccessError, the derived exception + /// type is thrown (as long as the underlying system provides the + /// information to unambiguously distinguish that particular + /// reason). + static void remove(const std::string& path); + + /// Same as remove() except that this one returns false, rather + /// than throwing an exception, if the specified file does not + /// exist. If the file did exist, and was deleted, this function + /// returns true. + static bool try_remove(const std::string& path); + + /// Change the path of a directory entry. This can be used to + /// rename a file, and/or to move it from one directory to + /// another. This function is equivalent to std::rename(const + /// char*, const char*). + /// + /// \throw AccessError If the path of the directory entry could + /// not be changed. If the reason corresponds to one of the + /// exception types that are derived from AccessError, the derived + /// exception type is thrown (as long as the underlying system + /// provides the information to unambiguously distinguish that + /// particular reason). + static void move(const std::string& old_path, const std::string& new_path); + + /// Copy the file at the specified origin path to the specified target path. + static void copy(const std::string& origin_path, const std::string& target_path); + + /// Compare the two files at the specified paths for equality. Returns true + /// if, and only if they are equal. + static bool compare(const std::string& path_1, const std::string& path_2); + + /// Check whether two open file descriptors refer to the same + /// underlying file, that is, if writing via one of them, will + /// affect what is read from the other. In UNIX this boils down to + /// comparing inode numbers. + /// + /// Both instances have to be attached to open files. If they are + /// not, this function has undefined behavior. + bool is_same_file(const File&) const; + static bool is_same_file_static(FileDesc f1, FileDesc f2); + + // FIXME: Get rid of this method + bool is_removed() const; + + /// Resolve the specified path against the specified base directory. + /// + /// If \a path is absolute, or if \a base_dir is empty, \p path is returned + /// unmodified, otherwise \a path is resolved against \a base_dir. + /// + /// Examples (assuming POSIX): + /// + /// resolve("file", "dir") -> "dir/file" + /// resolve("../baz", "/foo/bar") -> "/foo/baz" + /// resolve("foo", ".") -> "./foo" + /// resolve(".", "/foo/") -> "/foo" + /// resolve("..", "foo") -> "." + /// resolve("../..", "foo") -> ".." + /// resolve("..", "..") -> "../.." + /// resolve("", "") -> "." + /// resolve("", "/") -> "/." + /// resolve("..", "/") -> "/." + /// resolve("..", "foo//bar") -> "foo" + /// + /// This function does not access the file system. + /// + /// \param path The path to be resolved. An empty string produces the same + /// result as as if "." was passed. The result has a trailing directory + /// separator (`/`) if, and only if this path has a trailing directory + /// separator. + /// + /// \param base_dir The base directory path, which may be relative or + /// absolute. A final directory separator (`/`) is optional. The empty + /// string is interpreted as a relative path. + static std::string resolve(const std::string& path, const std::string& base_dir); + + using ForEachHandler = std::function; + + /// Scan the specified directory recursivle, and report each file + /// (nondirectory entry) via the specified handler. + /// + /// The first argument passed to the handler is the name of a file (not the + /// whole path), and the second argument is the directory in which that file + /// resides. The directory will be specified as a path, and relative to \a + /// dir_path. The directory will be the empty string for files residing + /// directly in \a dir_path. + /// + /// If the handler returns false, scanning will be aborted immediately, and + /// for_each() will return false. Otherwise for_each() will return true. + /// + /// Scanning is done as if by a recursive set of DirScanner objects. + static bool for_each(const std::string& dir_path, ForEachHandler handler); + + struct UniqueID { +#ifdef _WIN32 // Windows version +// FIXME: This is not implemented for Windows +#else + // NDK r10e has a bug in sys/stat.h dev_t ino_t are 4 bytes, + // but stat.st_dev and st_ino are 8 bytes. So we just use uint64 instead. + uint_fast64_t device; + uint_fast64_t inode; +#endif + }; + // Return the unique id for the current opened file descriptor. + // Same UniqueID means they are the same file. + UniqueID get_unique_id() const; + // Return false if the file doesn't exist. Otherwise uid will be set. + static bool get_unique_id(const std::string& path, UniqueID& uid); + + class ExclusiveLock; + class SharedLock; + + template + class Map; + + class CloseGuard; + class UnlockGuard; + class UnmapGuard; + + class Streambuf; + + // Exceptions + class AccessError; + class PermissionDenied; + class NotFound; + class Exists; + +private: +#ifdef _WIN32 + void* m_fd; + bool m_have_lock; // Only valid when m_fd is not null +#else + int m_fd; +#endif + std::unique_ptr m_encryption_key = nullptr; + + bool lock(bool exclusive, bool non_blocking); + void open_internal(const std::string& path, AccessMode, CreateMode, int flags, bool* success); + + struct MapBase { + void* m_addr = nullptr; + size_t m_size = 0; + FileDesc m_fd; + + MapBase() noexcept; + ~MapBase() noexcept; + + // Disable copying. Copying an opened MapBase will create a scenario + // where the same memory will be mapped once but unmapped twice. + MapBase(const MapBase&) = delete; + MapBase& operator=(const MapBase&) = delete; + + void map(const File&, AccessMode, size_t size, int map_flags, size_t offset = 0); + void remap(const File&, AccessMode, size_t size, int map_flags); + void unmap() noexcept; + void sync(); +#if REALM_ENABLE_ENCRYPTION + util::EncryptedFileMapping* m_encrypted_mapping = nullptr; + inline util::EncryptedFileMapping* get_encrypted_mapping() const + { + return m_encrypted_mapping; + } +#else + inline util::EncryptedFileMapping* get_encrypted_mapping() const + { + return nullptr; + } +#endif + }; +}; + + +class File::ExclusiveLock { +public: + ExclusiveLock(File& f) + : m_file(f) + { + f.lock_exclusive(); + } + ~ExclusiveLock() noexcept + { + m_file.unlock(); + } + // Disable copying. It is not how this class should be used. + ExclusiveLock(const ExclusiveLock&) = delete; + ExclusiveLock& operator=(const ExclusiveLock&) = delete; + +private: + File& m_file; +}; + +class File::SharedLock { +public: + SharedLock(File& f) + : m_file(f) + { + f.lock_shared(); + } + ~SharedLock() noexcept + { + m_file.unlock(); + } + // Disable copying. It is not how this class should be used. + SharedLock(const SharedLock&) = delete; + SharedLock& operator=(const SharedLock&) = delete; + +private: + File& m_file; +}; + + +/// This class provides a RAII abstraction over the concept of a +/// memory mapped file. +/// +/// Once created, the Map instance makes no reference to the File +/// instance that it was based upon, and that File instance may be +/// destroyed before the Map instance is destroyed. +/// +/// Multiple concurrent mappings may be created from the same File +/// instance. +/// +/// You can use UnmapGuard to acheive exception-safe unmapping prior +/// to the Map instance being detroyed. +/// +/// A single Map instance must never be accessed concurrently by +/// multiple threads. +template +class File::Map : private MapBase { +public: + /// Equivalent to calling map() on a default constructed instance. + explicit Map(const File&, AccessMode = access_ReadOnly, size_t size = sizeof(T), int map_flags = 0); + + explicit Map(const File&, size_t offset, AccessMode = access_ReadOnly, size_t size = sizeof(T), + int map_flags = 0); + + /// Create an instance that is not initially attached to a memory + /// mapped file. + Map() noexcept; + + ~Map() noexcept; + + // Disable copying. Copying an opened Map will create a scenario + // where the same memory will be mapped once but unmapped twice. + Map(const Map&) = delete; + Map& operator=(const Map&) = delete; + + /// Move the mapping from another Map object to this Map object + File::Map& operator=(File::Map&& other) + { + if (m_addr) + unmap(); + m_addr = other.get_addr(); + m_size = other.m_size; + other.m_addr = 0; + other.m_size = 0; +#if REALM_ENABLE_ENCRYPTION + m_encrypted_mapping = other.m_encrypted_mapping; + other.m_encrypted_mapping = nullptr; +#endif + return *this; + } + + /// See File::map(). + /// + /// Calling this function on a Map instance that is already + /// attached to a memory mapped file has undefined behavior. The + /// returned pointer is the same as what will subsequently be + /// returned by get_addr(). + T* map(const File&, AccessMode = access_ReadOnly, size_t size = sizeof(T), int map_flags = 0, size_t offset = 0); + + /// See File::unmap(). This function is idempotent, that is, it is + /// valid to call it regardless of whether this instance is + /// currently attached to a memory mapped file. + void unmap() noexcept; + + /// See File::remap(). + /// + /// Calling this function on a Map instance that is not currently + /// attached to a memory mapped file has undefined behavior. The + /// returned pointer is the same as what will subsequently be + /// returned by get_addr(). + T* remap(const File&, AccessMode = access_ReadOnly, size_t size = sizeof(T), int map_flags = 0); + + /// See File::sync_map(). + /// + /// Calling this function on an instance that is not currently + /// attached to a memory mapped file, has undefined behavior. + void sync(); + + /// Check whether this Map instance is currently attached to a + /// memory mapped file. + bool is_attached() const noexcept; + + /// Returns a pointer to the beginning of the memory mapped file, + /// or null if this instance is not currently attached. + T* get_addr() const noexcept; + + /// Returns the size of the mapped region, or zero if this + /// instance does not currently refer to a memory mapped + /// file. When this instance refers to a memory mapped file, the + /// returned value will always be identical to the size passed to + /// the constructor or to map(). + size_t get_size() const noexcept; + + /// Release the currently attached memory mapped file from this + /// Map instance. The address range may then be unmapped later by + /// a call to File::unmap(). + T* release() noexcept; + +#if REALM_ENABLE_ENCRYPTION + /// Get the encrypted file mapping corresponding to this mapping + inline EncryptedFileMapping* get_encrypted_mapping() const + { + return m_encrypted_mapping; + } +#else + inline EncryptedFileMapping* get_encrypted_mapping() const + { + return nullptr; + } +#endif + + friend class UnmapGuard; +}; + + +class File::CloseGuard { +public: + CloseGuard(File& f) noexcept + : m_file(&f) + { + } + ~CloseGuard() noexcept + { + if (m_file) + m_file->close(); + } + void release() noexcept + { + m_file = nullptr; + } + // Disallow the default implementation of copy/assign, this is not how this + // class is intended to be used. For example we could get unexpected + // behaviour if one CloseGuard is copied and released but the other is not. + CloseGuard(const CloseGuard&) = delete; + CloseGuard& operator=(const CloseGuard&) = delete; + +private: + File* m_file; +}; + + +class File::UnlockGuard { +public: + UnlockGuard(File& f) noexcept + : m_file(&f) + { + } + ~UnlockGuard() noexcept + { + if (m_file) + m_file->unlock(); + } + void release() noexcept + { + m_file = nullptr; + } + // Disallow the default implementation of copy/assign, this is not how this + // class is intended to be used. For example we could get unexpected + // behaviour if one UnlockGuard is copied and released but the other is not. + UnlockGuard(const UnlockGuard&) = delete; + UnlockGuard& operator=(const UnlockGuard&) = delete; + +private: + File* m_file; +}; + + +class File::UnmapGuard { +public: + template + UnmapGuard(Map& m) noexcept + : m_map(&m) + { + } + ~UnmapGuard() noexcept + { + if (m_map) + m_map->unmap(); + } + void release() noexcept + { + m_map = nullptr; + } + // Disallow the default implementation of copy/assign, this is not how this + // class is intended to be used. For example we could get unexpected + // behaviour if one UnmapGuard is copied and released but the other is not. + UnmapGuard(const UnmapGuard&) = delete; + UnmapGuard& operator=(const UnmapGuard&) = delete; + +private: + MapBase* m_map; +}; + + +/// Only output is supported at this point. +class File::Streambuf : public std::streambuf { +public: + explicit Streambuf(File*); + ~Streambuf() noexcept; + + // Disable copying + Streambuf(const Streambuf&) = delete; + Streambuf& operator=(const Streambuf&) = delete; + +private: + static const size_t buffer_size = 4096; + + File& m_file; + std::unique_ptr const m_buffer; + + int_type overflow(int_type) override; + int sync() override; + pos_type seekpos(pos_type, std::ios_base::openmode) override; + void flush(); +}; + + +/// Used for any I/O related exception. Note the derived exception +/// types that are used for various specific types of errors. +class File::AccessError : public std::runtime_error { +public: + AccessError(const std::string& msg, const std::string& path); + + /// Return the associated file system path, or the empty string if there is + /// no associated file system path, or if the file system path is unknown. + std::string get_path() const; + +private: + std::string m_path; +}; + + +/// Thrown if the user does not have permission to open or create +/// the specified file in the specified access mode. +class File::PermissionDenied : public AccessError { +public: + PermissionDenied(const std::string& msg, const std::string& path); +}; + + +/// Thrown if the directory part of the specified path was not +/// found, or create_Never was specified and the file did no +/// exist. +class File::NotFound : public AccessError { +public: + NotFound(const std::string& msg, const std::string& path); +}; + + +/// Thrown if create_Always was specified and the file did already +/// exist. +class File::Exists : public AccessError { +public: + Exists(const std::string& msg, const std::string& path); +}; + + +class DirScanner { +public: + DirScanner(const std::string& path, bool allow_missing = false); + ~DirScanner() noexcept; + bool next(std::string& name); + +private: +#ifndef _WIN32 + DIR* m_dirp; +#elif REALM_HAVE_STD_FILESYSTEM + std::filesystem::directory_iterator m_iterator; +#endif +}; + + +// Implementation: + +inline File::File(const std::string& path, Mode m) +{ +#ifdef _WIN32 + m_fd = nullptr; +#else + m_fd = -1; +#endif + + open(path, m); +} + +inline File::File() noexcept +{ +#ifdef _WIN32 + m_fd = nullptr; +#else + m_fd = -1; +#endif +} + +inline File::~File() noexcept +{ + close(); +} + +inline File::File(File&& f) noexcept +{ +#ifdef _WIN32 + m_fd = f.m_fd; + m_have_lock = f.m_have_lock; + f.m_fd = nullptr; +#else + m_fd = f.m_fd; + f.m_fd = -1; +#endif + m_encryption_key = std::move(f.m_encryption_key); +} + +inline File& File::operator=(File&& f) noexcept +{ + close(); +#ifdef _WIN32 + m_fd = f.m_fd; + m_have_lock = f.m_have_lock; + f.m_fd = nullptr; +#else + m_fd = f.m_fd; + f.m_fd = -1; +#endif + m_encryption_key = std::move(f.m_encryption_key); + return *this; +} + +inline void File::open(const std::string& path, Mode m) +{ + AccessMode a = access_ReadWrite; + CreateMode c = create_Auto; + int flags = 0; + switch (m) { + case mode_Read: + a = access_ReadOnly; + c = create_Never; + break; + case mode_Update: + c = create_Never; + break; + case mode_Write: + flags = flag_Trunc; + break; + case mode_Append: + flags = flag_Append; + break; + } + open(path, a, c, flags); +} + +inline void File::open(const std::string& path, AccessMode am, CreateMode cm, int flags) +{ + open_internal(path, am, cm, flags, nullptr); +} + + +inline void File::open(const std::string& path, bool& was_created) +{ + while (1) { + bool success; + open_internal(path, access_ReadWrite, create_Must, 0, &success); + if (success) { + was_created = true; + return; + } + open_internal(path, access_ReadWrite, create_Never, 0, &success); + if (success) { + was_created = false; + return; + } + } +} + +inline bool File::is_attached() const noexcept +{ +#ifdef _WIN32 + return (m_fd != nullptr); +#else + return 0 <= m_fd; +#endif +} + +inline void File::lock_exclusive() +{ + lock(true, false); +} + +inline void File::lock_shared() +{ + lock(false, false); +} + +inline bool File::try_lock_exclusive() +{ + return lock(true, true); +} + +inline bool File::try_lock_shared() +{ + return lock(false, true); +} + +inline File::MapBase::MapBase() noexcept +{ + m_addr = nullptr; +} + +inline File::MapBase::~MapBase() noexcept +{ + unmap(); +} + +inline void File::MapBase::map(const File& f, AccessMode a, size_t size, int map_flags, size_t offset) +{ + REALM_ASSERT(!m_addr); +#if REALM_ENABLE_ENCRYPTION + m_addr = f.map(a, size, m_encrypted_mapping, map_flags, offset); +#else + m_addr = f.map(a, size, map_flags, offset); +#endif + m_size = size; + m_fd = f.m_fd; +} + +inline void File::MapBase::unmap() noexcept +{ + if (!m_addr) + return; + File::unmap(m_addr, m_size); + m_addr = nullptr; +#if REALM_ENABLE_ENCRYPTION + m_encrypted_mapping = nullptr; +#endif + m_fd = 0; +} + +inline void File::MapBase::remap(const File& f, AccessMode a, size_t size, int map_flags) +{ + REALM_ASSERT(m_addr); + + m_addr = f.remap(m_addr, m_size, a, size, map_flags); + m_size = size; + m_fd = f.m_fd; +} + +inline void File::MapBase::sync() +{ + REALM_ASSERT(m_addr); + + File::sync_map(m_fd, m_addr, m_size); +} + +template +inline File::Map::Map(const File& f, AccessMode a, size_t size, int map_flags) +{ + map(f, a, size, map_flags); +} + +template +inline File::Map::Map(const File& f, size_t offset, AccessMode a, size_t size, int map_flags) +{ + map(f, a, size, map_flags, offset); +} + +template +inline File::Map::Map() noexcept +{ +} + +template +inline File::Map::~Map() noexcept +{ +} + +template +inline T* File::Map::map(const File& f, AccessMode a, size_t size, int map_flags, size_t offset) +{ + MapBase::map(f, a, size, map_flags, offset); + return static_cast(m_addr); +} + +template +inline void File::Map::unmap() noexcept +{ + MapBase::unmap(); +} + +template +inline T* File::Map::remap(const File& f, AccessMode a, size_t size, int map_flags) +{ + MapBase::remap(f, a, size, map_flags); + return static_cast(m_addr); +} + +template +inline void File::Map::sync() +{ + MapBase::sync(); +} + +template +inline bool File::Map::is_attached() const noexcept +{ + return (m_addr != nullptr); +} + +template +inline T* File::Map::get_addr() const noexcept +{ + return static_cast(m_addr); +} + +template +inline size_t File::Map::get_size() const noexcept +{ + return m_addr ? m_size : 0; +} + +template +inline T* File::Map::release() noexcept +{ + T* addr = static_cast(m_addr); + m_addr = nullptr; + m_fd = 0; + return addr; +} + + +inline File::Streambuf::Streambuf(File* f) + : m_file(*f) + , m_buffer(new char[buffer_size]) +{ + char* b = m_buffer.get(); + setp(b, b + buffer_size); +} + +inline File::Streambuf::~Streambuf() noexcept +{ + try { + if (m_file.is_attached()) + flush(); + } + catch (...) { + // Errors deliberately ignored + } +} + +inline File::Streambuf::int_type File::Streambuf::overflow(int_type c) +{ + flush(); + if (c == traits_type::eof()) + return traits_type::not_eof(c); + *pptr() = traits_type::to_char_type(c); + pbump(1); + return c; +} + +inline int File::Streambuf::sync() +{ + flush(); + return 0; +} + +inline File::Streambuf::pos_type File::Streambuf::seekpos(pos_type pos, std::ios_base::openmode) +{ + flush(); + SizeType pos2 = 0; + if (int_cast_with_overflow_detect(std::streamsize(pos), pos2)) + throw util::overflow_error("Seek position overflow"); + m_file.seek(pos2); + return pos; +} + +inline void File::Streambuf::flush() +{ + size_t n = pptr() - pbase(); + if (n > 0) { + m_file.write(pbase(), n); + setp(m_buffer.get(), epptr()); + } +} + +inline File::AccessError::AccessError(const std::string& msg, const std::string& path) + : std::runtime_error(msg) + , m_path(path) +{ +} + +inline std::string File::AccessError::get_path() const +{ + return m_path; +} + +inline File::PermissionDenied::PermissionDenied(const std::string& msg, const std::string& path) + : AccessError(msg, path) +{ +} + +inline File::NotFound::NotFound(const std::string& msg, const std::string& path) + : AccessError(msg, path) +{ +} + +inline File::Exists::Exists(const std::string& msg, const std::string& path) + : AccessError(msg, path) +{ +} + +inline bool operator==(const File::UniqueID& lhs, const File::UniqueID& rhs) +{ +#ifdef _WIN32 // Windows version + throw util::runtime_error("Not yet supported"); +#else // POSIX version + return lhs.device == rhs.device && lhs.inode == rhs.inode; +#endif +} + +inline bool operator!=(const File::UniqueID& lhs, const File::UniqueID& rhs) +{ + return !(lhs == rhs); +} + +inline bool operator<(const File::UniqueID& lhs, const File::UniqueID& rhs) +{ +#ifdef _WIN32 // Windows version + throw util::runtime_error("Not yet supported"); +#else // POSIX version + if (lhs.device < rhs.device) + return true; + if (lhs.device > rhs.device) + return false; + if (lhs.inode < rhs.inode) + return true; + return false; +#endif +} + +inline bool operator>(const File::UniqueID& lhs, const File::UniqueID& rhs) +{ + return rhs < lhs; +} + +inline bool operator<=(const File::UniqueID& lhs, const File::UniqueID& rhs) +{ + return !(lhs > rhs); +} + +inline bool operator>=(const File::UniqueID& lhs, const File::UniqueID& rhs) +{ + return !(lhs < rhs); +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_FILE_HPP diff --git a/Pods/Realm/include/core/realm/util/file_mapper.hpp b/Pods/Realm/include/core/realm/util/file_mapper.hpp new file mode 100644 index 0000000000..488ae94122 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/file_mapper.hpp @@ -0,0 +1,120 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_FILE_MAPPER_HPP +#define REALM_UTIL_FILE_MAPPER_HPP + +#include +#include +#include +#include + +namespace realm { +namespace util { + +void* mmap(FileDesc fd, size_t size, File::AccessMode access, size_t offset, const char* encryption_key); +void munmap(void* addr, size_t size); +void* mremap(FileDesc fd, size_t file_offset, void* old_addr, size_t old_size, File::AccessMode a, size_t new_size, + const char* encryption_key); +void msync(FileDesc fd, void* addr, size_t size); + +// A function which may be given to encryption_read_barrier. If present, the read barrier is a +// a barrier for a full array. If absent, the read barrier is a barrier only for the address +// range give as argument. If the barrier is for a full array, it will read the array header +// and determine the address range from the header. +using HeaderToSize = size_t (*)(const char* addr); +class EncryptedFileMapping; + +#if REALM_ENABLE_ENCRYPTION + + +// This variant allows the caller to obtain direct access to the encrypted file mapping +// for optimization purposes. +void* mmap(FileDesc fd, size_t size, File::AccessMode access, size_t offset, const char* encryption_key, + EncryptedFileMapping*& mapping); + +void do_encryption_read_barrier(const void* addr, size_t size, HeaderToSize header_to_size, + EncryptedFileMapping* mapping); + +void do_encryption_write_barrier(const void* addr, size_t size, EncryptedFileMapping* mapping); + +void inline encryption_read_barrier(const void* addr, size_t size, EncryptedFileMapping* mapping, + HeaderToSize header_to_size = nullptr) +{ + if (mapping) + do_encryption_read_barrier(addr, size, header_to_size, mapping); +} + +void inline encryption_write_barrier(const void* addr, size_t size, EncryptedFileMapping* mapping) +{ + if (mapping) + do_encryption_write_barrier(addr, size, mapping); +} + + +extern util::Mutex& mapping_mutex; + +inline void do_encryption_read_barrier(const void* addr, size_t size, HeaderToSize header_to_size, + EncryptedFileMapping* mapping) +{ + UniqueLock lock(mapping_mutex, defer_lock_tag()); + mapping->read_barrier(addr, size, lock, header_to_size); +} + +inline void do_encryption_write_barrier(const void* addr, size_t size, EncryptedFileMapping* mapping) +{ + LockGuard lock(mapping_mutex); + mapping->write_barrier(addr, size); +} + + +#else +void inline encryption_read_barrier(const void*, size_t, EncryptedFileMapping*, HeaderToSize header_to_size = nullptr) +{ + static_cast(header_to_size); +} +void inline encryption_write_barrier(const void*, size_t) +{ +} +void inline encryption_write_barrier(const void*, size_t, EncryptedFileMapping*) +{ +} +#endif + +// helpers for encrypted Maps +template +void encryption_read_barrier(File::Map& map, size_t index, size_t num_elements = 1) +{ + T* addr = map.get_addr(); + encryption_read_barrier(addr + index, sizeof(T) * num_elements, map.get_encrypted_mapping()); +} + +template +void encryption_write_barrier(File::Map& map, size_t index, size_t num_elements = 1) +{ + T* addr = map.get_addr(); + encryption_write_barrier(addr + index, sizeof(T) * num_elements, map.get_encrypted_mapping()); +} + +File::SizeType encrypted_size_to_data_size(File::SizeType size) noexcept; +File::SizeType data_size_to_encrypted_size(File::SizeType size) noexcept; + +size_t round_up_to_page_size(size_t size) noexcept; +} +} +#endif diff --git a/Pods/Realm/include/core/realm/util/flat_map.hpp b/Pods/Realm/include/core/realm/util/flat_map.hpp new file mode 100644 index 0000000000..a3d6b540d6 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/flat_map.hpp @@ -0,0 +1,201 @@ + +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2017] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_FLAT_MAP_HPP +#define REALM_UTIL_FLAT_MAP_HPP + +#include +#include // std::pair +#include // std::lower_bound etc. +#include + +#include + +namespace realm { +namespace util { + +template >, class Cmp = std::less<>> +struct FlatMap { + using value_type = std::pair; + using key_type = K; + using mapped_type = V; + FlatMap() {} + FlatMap(const FlatMap&) = default; + FlatMap(FlatMap&&) = default; + FlatMap& operator=(const FlatMap&) = default; + FlatMap& operator=(FlatMap&&) = default; + + V& at(K key) + { + auto it = lower_bound(key); + if (it == end() || it->first != key) + it = m_data.emplace(it, std::move(key), V{}); // Throws + return it->second; + } + + const V& at(const K& key) const + { + auto it = find(key); + if (it == end()) + throw util::out_of_range("no such key"); + return it->second; + } + + V& operator[](const K& key) + { + return at(key); // Throws + } + + using iterator = typename Container::iterator; + using const_iterator = typename Container::const_iterator; + iterator begin() noexcept { return m_data.begin(); } + iterator end() noexcept { return m_data.end(); } + const_iterator begin() const noexcept { return m_data.begin(); } + const_iterator end() const noexcept { return m_data.end(); } + + + bool empty() const noexcept { return m_data.empty(); } + size_t size() const noexcept { return m_data.size(); } + void clear() noexcept { m_data.clear(); } + + std::pair insert(value_type value) + { + auto it = lower_bound(value.first); + if (it != end() && it->first == value.first) { + return std::make_pair(it, false); + } + return std::make_pair(m_data.emplace(it, std::move(value)), true); // Throws + } + + template + std::pair insert(P pair) + { + return insert(value_type{std::get<0>(pair), std::get<1>(pair)}); + } + + template + void insert(InputIt first, InputIt last) + { + for (auto it = first; it != last; ++it) { + insert(*it); + } + } + + template + std::pair emplace(Args&&... args) + { + value_type value{std::forward(args)...}; + return insert(std::move(value)); + } + + template + std::pair emplace_hint(const_iterator pos, Args&&... args) + { + static_cast(pos); // FIXME: TODO + return emplace(std::forward(args)...); + } + + iterator erase(const_iterator pos) noexcept(std::is_nothrow_move_assignable::value) + { + return m_data.erase(pos); + } + + iterator erase(const_iterator first, const_iterator last) noexcept(std::is_nothrow_move_assignable::value) + { + return m_data.erase(first, last); + } + + size_t erase(const K& key) noexcept(std::is_nothrow_move_assignable::value) + { + auto it = find(key); + if (it != end()) { + erase(it); + return 1; + } + return 0; + } + + void swap(FlatMap& other) + { + m_data.swap(other.m_data); + } + + template + size_t count(const Key& key) const noexcept + { + return find(key) == end() ? 0 : 1; + } + + template + iterator find(const Key& key) noexcept + { + const FlatMap* This = this; + const_iterator pos = This->find(key); + return iterator{begin() + (pos - This->begin())}; + } + + template + const_iterator find(const Key& key) const noexcept + { + auto it = lower_bound(key); + if (it != end() && it->first != key) { + return end(); + } + return it; + } + + template + iterator lower_bound(const Key& key) noexcept + { + const FlatMap* This = this; + const_iterator pos = This->lower_bound(key); + return iterator{begin() + (pos - This->begin())}; + } + + template + const_iterator lower_bound(const Key& key) const noexcept + { + auto it = std::lower_bound(begin(), end(), key, [](const value_type& a, const Key& b) { + return Cmp{}(a.first, b); + }); + return it; + } + + // FIXME: Not implemented yet. + template + iterator upper_bound(const Key&) noexcept; + // FIXME: Not implemented yet. + template + const_iterator upper_bound(const Key&) const noexcept; + + void reserve(size_t size) + { + m_data.reserve(size); // Throws + } + +private: + Container m_data; +}; + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_FLAT_MAP_HPP diff --git a/Pods/Realm/include/core/realm/util/hex_dump.hpp b/Pods/Realm/include/core/realm/util/hex_dump.hpp new file mode 100644 index 0000000000..08f5d2b34c --- /dev/null +++ b/Pods/Realm/include/core/realm/util/hex_dump.hpp @@ -0,0 +1,54 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_HEX_DUMP_HPP +#define REALM_UTIL_HEX_DUMP_HPP + +#include +#include +#include +#include +#include +#include + +#include + +namespace realm { +namespace util { + +template +std::string hex_dump(const T* data, size_t size, const char* separator = " ", int min_digits = -1) +{ + using U = typename std::make_unsigned::type; + + if (min_digits < 0) + min_digits = (std::numeric_limits::digits + 3) / 4; + + std::ostringstream out; + for (const T* i = data; i != data + size; ++i) { + if (i != data) + out << separator; + out << std::setw(min_digits) << std::setfill('0') << std::hex << std::uppercase << util::promote(U(*i)); + } + return out.str(); +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_HEX_DUMP_HPP diff --git a/Pods/Realm/include/core/realm/util/http.hpp b/Pods/Realm/include/core/realm/util/http.hpp new file mode 100644 index 0000000000..5b15fe663a --- /dev/null +++ b/Pods/Realm/include/core/realm/util/http.hpp @@ -0,0 +1,525 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_HTTP_HPP +#define REALM_UTIL_HTTP_HPP + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace realm { +namespace util { +enum class HTTPParserError { + None = 0, + ContentTooLong, + HeaderLineTooLong, + MalformedResponse, + MalformedRequest, + BadRequest, +}; +std::error_code make_error_code(HTTPParserError); +} // namespace util +} // namespace realm + +namespace std { + template<> + struct is_error_code_enum: std::true_type {}; +} + +namespace realm { +namespace util { + +/// See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html +/// +/// It is guaranteed that the backing integer value of this enum corresponds +/// to the numerical code representing the status. +enum class HTTPStatus { + Unknown = 0, + + Continue = 100, + SwitchingProtocols = 101, + + Ok = 200, + Created = 201, + Accepted = 202, + NonAuthoritative = 203, + NoContent = 204, + ResetContent = 205, + PartialContent = 206, + + MultipleChoices = 300, + MovedPermanently = 301, + Found = 302, + SeeOther = 303, + NotModified = 304, + UseProxy = 305, + SwitchProxy = 306, + TemporaryRedirect = 307, + PermanentRedirect = 308, + + BadRequest = 400, + Unauthorized = 401, + PaymentRequired = 402, + Forbidden = 403, + NotFound = 404, + MethodNotAllowed = 405, + NotAcceptable = 406, + ProxyAuthenticationRequired = 407, + RequestTimeout = 408, + Conflict = 409, + Gone = 410, + LengthRequired = 411, + PreconditionFailed = 412, + PayloadTooLarge = 413, + UriTooLong = 414, + UnsupportedMediaType = 415, + RangeNotSatisfiable = 416, + ExpectationFailed = 417, + ImATeapot = 418, + MisdirectedRequest = 421, + UpgradeRequired = 426, + PreconditionRequired = 428, + TooManyRequests = 429, + RequestHeaderFieldsTooLarge = 431, + UnavailableForLegalReasons = 451, + + InternalServerError = 500, + NotImplemented = 501, + BadGateway = 502, + ServiceUnavailable = 503, + GatewayTimeout = 504, + HttpVersionNotSupported = 505, + VariantAlsoNegotiates = 506, + NotExtended = 510, + NetworkAuthenticationRequired = 511, +}; + +bool valid_http_status_code(unsigned int code); + +/// See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html +enum class HTTPMethod { + Options, + Get, + Head, + Post, + Put, + Delete, + Trace, + Connect, +}; + +struct HTTPAuthorization { + std::string scheme; + std::map values; +}; + +HTTPAuthorization parse_authorization(const std::string&); + +struct CaseInsensitiveCompare { + bool operator()(const std::string& a, const std::string& b) const + { + auto cmp = [](char lhs, char rhs) { + return std::tolower(lhs, std::locale::classic()) < + std::tolower(rhs, std::locale::classic()); + }; + return std::lexicographical_compare(begin(a), end(a), begin(b), end(b), cmp); + } +}; + +/// Case-insensitive map suitable for storing HTTP headers. +using HTTPHeaders = std::map; + +struct HTTPRequest { + HTTPMethod method = HTTPMethod::Get; + HTTPHeaders headers; + std::string path; + + /// If the request object has a body, the Content-Length header MUST be + /// set to a string representation of the number of bytes in the body. + /// FIXME: Relax this restriction, and also support Transfer-Encoding + /// and other HTTP/1.1 features. + Optional body; +}; + +struct HTTPResponse { + HTTPStatus status = HTTPStatus::Unknown; + HTTPHeaders headers; + + // A body is only read from the response stream if the server sent the + // Content-Length header. + // FIXME: Support other transfer methods, including Transfer-Encoding and + // HTTP/1.1 features. + Optional body; +}; + + +/// Serialize HTTP request to output stream. +std::ostream& operator<<(std::ostream&, const HTTPRequest&); +/// Serialize HTTP response to output stream. +std::ostream& operator<<(std::ostream&, const HTTPResponse&); +/// Serialize HTTP method to output stream ("GET", "POST", etc.). +std::ostream& operator<<(std::ostream&, HTTPMethod); +/// Serialize HTTP status to output stream, include reason string ("200 OK" etc.) +std::ostream& operator<<(std::ostream&, HTTPStatus); + +struct HTTPParserBase { + util::Logger& logger; + + // FIXME: Generally useful? + struct CallocDeleter { + void operator()(void* ptr) + { + std::free(ptr); + } + }; + + HTTPParserBase(util::Logger& logger_2): + logger {logger_2} + { + // Allocating read buffer with calloc to avoid accidentally spilling + // data from other sessions in case of a buffer overflow exploit. + m_read_buffer.reset(static_cast(std::calloc(read_buffer_size, 1))); + } + virtual ~HTTPParserBase() {} + + std::string m_write_buffer; + std::unique_ptr m_read_buffer; + Optional m_found_content_length; + static const size_t read_buffer_size = 8192; + static const size_t max_header_line_length = read_buffer_size; + + /// Parses the contents of m_read_buffer as a HTTP header line, + /// and calls on_header() as appropriate. on_header() will be called at + /// most once per invocation. + /// Returns false if the contents of m_read_buffer is not a valid HTTP + /// header line. + bool parse_header_line(size_t len); + + virtual std::error_code on_first_line(StringData line) = 0; + virtual void on_header(StringData key, StringData value) = 0; + virtual void on_body(StringData body) = 0; + virtual void on_complete(std::error_code = std::error_code{}) = 0; + + /// If the input matches a known HTTP method string, return the appropriate + /// HTTPMethod enum value. Otherwise, returns none. + static Optional parse_method_string(StringData method); + + /// Interpret line as the first line of an HTTP request. If the return value + /// is true, out_method and out_uri have been assigned the appropriate + /// values found in the request line. + static bool parse_first_line_of_request(StringData line, HTTPMethod& out_method, + StringData& out_uri); + + /// Interpret line as the first line of an HTTP response. If the return + /// value is true, out_status and out_reason have been assigned the + /// appropriate values found in the response line. + static bool parse_first_line_of_response(StringData line, HTTPStatus& out_status, + StringData& out_reason, util::Logger& logger); + + void set_write_buffer(const HTTPRequest&); + void set_write_buffer(const HTTPResponse&); +}; + +template +struct HTTPParser: protected HTTPParserBase { + explicit HTTPParser(Socket& socket, util::Logger& logger): + HTTPParserBase(logger), + m_socket(socket) + {} + + void read_first_line() + { + auto handler = [this](std::error_code ec, size_t n) { + if (ec == error::operation_aborted) { + return; + } + if (ec) { + on_complete(ec); + return; + } + ec = on_first_line(StringData(m_read_buffer.get(), n)); + if (ec) { + on_complete(ec); + return; + } + read_headers(); + }; + m_socket.async_read_until(m_read_buffer.get(), max_header_line_length, '\n', + std::move(handler)); + } + + void read_headers() + { + auto handler = [this](std::error_code ec, size_t n) { + if (ec == error::operation_aborted) { + return; + } + if (ec) { + on_complete(ec); + return; + } + if (n <= 2) { + read_body(); + return; + } + if (!parse_header_line(n)) { + on_complete(HTTPParserError::BadRequest); + return; + } + + // FIXME: Limit the total size of headers. Apache uses 8K. + read_headers(); + }; + m_socket.async_read_until(m_read_buffer.get(), max_header_line_length, '\n', + std::move(handler)); + } + + void read_body() + { + if (m_found_content_length) { + // FIXME: Support longer bodies. + // FIXME: Support multipart and other body types (no body shaming). + if (*m_found_content_length > read_buffer_size) { + on_complete(HTTPParserError::ContentTooLong); + return; + } + + auto handler = [this](std::error_code ec, size_t n) { + if (ec == error::operation_aborted) { + return; + } + if (!ec) { + on_body(StringData(m_read_buffer.get(), n)); + } + on_complete(ec); + }; + m_socket.async_read(m_read_buffer.get(), *m_found_content_length, + std::move(handler)); + } + else { + // No body, just finish. + on_complete(); + } + } + + void write_buffer(std::function handler) + { + m_socket.async_write(m_write_buffer.data(), m_write_buffer.size(), + std::move(handler)); + } + + Socket& m_socket; +}; + +template +struct HTTPClient: protected HTTPParser { + using Handler = void(HTTPResponse, std::error_code); + + explicit HTTPClient(Socket& socket, util::Logger& logger) : HTTPParser(socket, logger) {} + + /// Serialize and send \a request over the connected socket asynchronously. + /// + /// When the response has been received, or an error occurs, \a handler will + /// be invoked with the appropriate parameters. The HTTPResponse object + /// passed to \a handler will only be complete in non-error conditions, but + /// may be partially populated. + /// + /// It is an error to start a request before the \a handler of a previous + /// request has been invoked. It is permitted to call async_request() from + /// the handler, unless an error has been reported representing a condition + /// where the underlying socket is no longer able to communicate (for + /// example, if it has been closed). + /// + /// If a request is already in progress, an exception will be thrown. + /// + /// This method is *NOT* thread-safe. + void async_request(const HTTPRequest& request, std::function handler) + { + if (REALM_UNLIKELY(m_handler)) { + throw util::runtime_error("Request already in progress."); + } + this->set_write_buffer(request); + m_handler = std::move(handler); + this->write_buffer([this](std::error_code ec, size_t bytes_written) { + static_cast(bytes_written); + if (ec == error::operation_aborted) { + return; + } + if (ec) { + this->on_complete(ec); + return; + } + this->read_first_line(); + }); + } + +private: + std::function m_handler; + HTTPResponse m_response; + + std::error_code on_first_line(StringData line) override final + { + HTTPStatus status; + StringData reason; + if (this->parse_first_line_of_response(line, status, reason, this->logger)) { + m_response.status = status; + static_cast(reason); // Ignore for now. + return std::error_code{}; + } + return HTTPParserError::MalformedResponse; + } + + void on_header(StringData key, StringData value) override final + { + // FIXME: Multiple headers with the same key should show up as a + // comma-separated list of their values, rather than overwriting. + m_response.headers[std::string(key)] = std::string(value); + } + + void on_body(StringData body) override final + { + m_response.body = std::string(body); + } + + void on_complete(std::error_code ec) override final + { + auto handler = std::move(m_handler); + m_handler = nullptr; + handler(std::move(m_response), ec); + } +}; + +template +struct HTTPServer: protected HTTPParser { + using RequestHandler = void(HTTPRequest, std::error_code); + using RespondHandler = void(std::error_code); + + explicit HTTPServer(Socket& socket, util::Logger& logger): HTTPParser(socket, logger) + {} + + /// Receive a request on the underlying socket asynchronously. + /// + /// This function starts an asynchronous read operation and keeps reading + /// until an HTTP request has been received. \a handler is invoked when a + /// request has been received, or an error occurs. + /// + /// After a request is received, callers MUST invoke async_send_response() + /// to provide the client with a valid HTTP response, unless the error + /// passed to the handler represents a condition where the underlying socket + /// is no longer able to communicate (for example, if it has been closed). + /// + /// It is an error to attempt to receive a request before any previous + /// requests have been fully responded to, i.e. the \a handler argument of + /// async_send_response() must have been invoked before attempting to + /// receive the next request. + /// + /// This function is *NOT* thread-safe. + void async_receive_request(std::function handler) + { + if (REALM_UNLIKELY(m_request_handler)) { + throw util::runtime_error("Response already in progress."); + } + m_request_handler = std::move(handler); + this->read_first_line(); + } + + /// Send an HTTP response to a client asynchronously. + /// + /// This function starts an asynchronous write operation on the underlying + /// socket. \a handler is invoked when the response has been written to the + /// socket, or an error occurs. + /// + /// It is an error to call async_receive_request() again before \a handler + /// has been invoked, and it is an error to call async_send_response() + /// before the \a handler of a previous invocation has been invoked. + /// + /// This function is *NOT* thread-safe. + void async_send_response(const HTTPResponse& response, + std::function handler) + { + if (REALM_UNLIKELY(!m_request_handler)) { + throw util::runtime_error("No request in progress."); + } + if (m_respond_handler) { + // FIXME: Proper exception type. + throw util::runtime_error("Already responding to request"); + } + m_respond_handler = std::move(handler); + this->set_write_buffer(response); + this->write_buffer([this](std::error_code ec, size_t) { + if (ec == error::operation_aborted) { + return; + } + m_request_handler = nullptr; + auto handler = std::move(m_respond_handler); + handler(ec); + });; + } + +private: + std::function m_request_handler; + std::function m_respond_handler; + HTTPRequest m_request; + + std::error_code on_first_line(StringData line) override final + { + HTTPMethod method; + StringData uri; + if (this->parse_first_line_of_request(line, method, uri)) { + m_request.method = method; + m_request.path = uri; + return std::error_code{}; + } + return HTTPParserError::MalformedRequest; + } + + void on_header(StringData key, StringData value) override final + { + // FIXME: Multiple headers with the same key should show up as a + // comma-separated list of their values, rather than overwriting. + m_request.headers[std::string(key)] = std::string(value); + } + + void on_body(StringData body) override final + { + m_request.body = std::string(body); + } + + void on_complete(std::error_code ec) override final + { + // Deliberately not nullifying m_request_handler so that we can + // check for invariants in async_send_response. + m_request_handler(std::move(m_request), ec); + } +}; + +} // namespace util +} // namespace realm + + +#endif // REALM_UTIL_HTTP_HPP + diff --git a/Pods/Realm/include/core/realm/util/inspect.hpp b/Pods/Realm/include/core/realm/util/inspect.hpp new file mode 100644 index 0000000000..84a669db61 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/inspect.hpp @@ -0,0 +1,76 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_INSPECT_HPP +#define REALM_UTIL_INSPECT_HPP + +#include + +namespace realm { +namespace util { + +// LCOV_EXCL_START +// +// Because these are templated functions, every combination of output stream +// type and value(s) type(s) generates a new function. This makes LCOV/GCOVR +// report over 70 functions in this file, with only 6.6% function coverage, +// even though line coverage is at 100%. + +template +void inspect_value(OS& os, const T& value) +{ + os << value; +} + +template +void inspect_value(OS& os, const std::string& value) +{ + // FIXME: Escape the string. + os << "\"" << value << "\""; +} + +template +void inspect_value(OS& os, const char* value) +{ + // FIXME: Escape the string. + os << "\"" << value << "\""; +} + +template +void inspect_all(OS&) +{ + // No-op +} + +/// Convert all arguments to strings, and quote string arguments. +template +void inspect_all(OS& os, First&& first, Args&&... args) +{ + inspect_value(os, std::forward(first)); + if (sizeof...(Args) != 0) { + os << ", "; + } + inspect_all(os, std::forward(args)...); +} + +// LCOV_EXCL_STOP + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_INSPECT_HPP diff --git a/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp b/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp new file mode 100644 index 0000000000..0e5b5866b3 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp @@ -0,0 +1,151 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_INTERPROCESS_CONDVAR +#define REALM_UTIL_INTERPROCESS_CONDVAR + + +#include +#include +#include +#include +#include +#include +#include + +// Condvar Emulation is required if RobustMutex emulation is enabled +#if defined(REALM_ROBUST_MUTEX_EMULATION) || defined(_WIN32) +#define REALM_CONDVAR_EMULATION +#endif + +namespace realm { +namespace util { + + +/// Condition variable for use in synchronization monitors. +/// This condition variable uses emulation based on named pipes +/// for the inter-process case, if enabled by REALM_CONDVAR_EMULATION. +/// +/// FIXME: This implementation will never release/delete pipes. This is unlikely +/// to be a problem as long as only a modest number of different database names +/// are in use +/// +/// A InterprocessCondVar is always process shared. +class InterprocessCondVar { +public: + InterprocessCondVar(); + ~InterprocessCondVar() noexcept; + + // Disable copying. Copying an open file will create a scenario + // where the same file descriptor will be opened once but closed twice. + InterprocessCondVar(const InterprocessCondVar&) = delete; + InterprocessCondVar& operator=(const InterprocessCondVar&) = delete; + +/// To use the InterprocessCondVar, you also must place a structure of type +/// InterprocessCondVar::SharedPart in memory shared by multiple processes +/// or in a memory mapped file, and use set_shared_part() to associate +/// the condition variable with it's shared part. You must initialize +/// the shared part using InterprocessCondVar::init_shared_part(), but only before +/// first use and only when you have exclusive access to the shared part. + +#ifdef REALM_CONDVAR_EMULATION + struct SharedPart { +#ifdef _WIN32 + // Number of waiting threads. + int32_t m_waiters_count; + size_t m_was_broadcast; +#else + uint64_t signal_counter; + uint64_t wait_counter; +#endif + }; +#else + typedef CondVar SharedPart; +#endif + + /// You need to bind the emulation to a SharedPart in shared/mmapped memory. + /// The SharedPart is assumed to have been initialized (possibly by another process) + /// earlier through a call to init_shared_part. + void set_shared_part(SharedPart& shared_part, std::string path, std::string condvar_name, std::string tmp_path); + + /// Initialize the shared part of a process shared condition variable. + /// A process shared condition variables may be represented by any number of + /// InterprocessCondVar instances in any number of different processes, + /// all sharing a common SharedPart instance, which must be in shared memory. + static void init_shared_part(SharedPart& shared_part); + + /// Release any system resources allocated for the shared part. This should + /// be used *only* when you are certain, that nobody is using it. + void release_shared_part(); + + /// Wait for someone to call notify() or notify_all() on this condition + /// variable. The call to wait() may return spuriously, so the caller should + /// always re-evaluate the condition on which to wait and loop on wait() + /// if necessary. + void wait(InterprocessMutex& m, const struct timespec* tp); + + /// If any threads are waiting for this condition, wake up at least one. + /// (Current implementation may actually wake all :-O ). The caller must + /// hold the lock associated with the condvar at the time of calling notify() + void notify() noexcept; + + /// Wake up every thread that is currently waiting on this condition. + /// The caller must hold the lock associated with the condvar at the time + /// of calling notify_all(). + void notify_all() noexcept; + + /// Cleanup and release system resources if possible. + void close() noexcept; + +private: + // non-zero if a shared part has been registered (always 0 on process local instances) + SharedPart* m_shared_part = nullptr; +#ifdef REALM_CONDVAR_EMULATION + // keep the path to allocated system resource so we can remove them again + std::string m_resource_path; + // pipe used for emulation. When using a named pipe, m_fd_read is read-write and m_fd_write is unused. + // When using an anonymous pipe (currently only for tvOS) m_fd_read is read-only and m_fd_write is write-only. + int m_fd_read = -1; + int m_fd_write = -1; + +#ifdef _WIN32 + // Semaphore used to queue up threads waiting for the condition to + // become signaled. + HANDLE m_sema = 0; + // An auto-reset event used by the broadcast/signal thread to wait + // for all the waiting thread(s) to wake up and be released from the + // semaphore. + HANDLE m_waiters_done = 0; + std::string m_name; + + // Serialize access to m_waiters_count + InterprocessMutex m_waiters_lockcount; +#endif + +#endif +}; + + +// Implementation: + + +} // namespace util +} // namespace realm + + +#endif diff --git a/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp b/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp new file mode 100644 index 0000000000..b3af1c6cde --- /dev/null +++ b/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp @@ -0,0 +1,375 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_INTERPROCESS_MUTEX +#define REALM_UTIL_INTERPROCESS_MUTEX + +#include +#include +#include +#include +#include +#include +#include + +// Enable this only on platforms where it might be needed +#if REALM_PLATFORM_APPLE || REALM_ANDROID +#define REALM_ROBUST_MUTEX_EMULATION +#endif + +namespace realm { +namespace util { + +// fwd decl to support friend decl below +class InterprocessCondVar; + + +/// Emulation of a Robust Mutex. +/// A Robust Mutex is an interprocess mutex which will automatically +/// release any locks held by a process when it crashes. Contrary to +/// Posix robust mutexes, this robust mutex is not capable of informing +/// participants that they have been granted a lock after a crash of +/// the process holding it (though it could be added if needed). + +class InterprocessMutex { +public: + InterprocessMutex(); + ~InterprocessMutex() noexcept; + + // Disable copying. Copying a locked Mutex will create a scenario + // where the same file descriptor will be locked once but unlocked twice. + InterprocessMutex(const InterprocessMutex&) = delete; + InterprocessMutex& operator=(const InterprocessMutex&) = delete; + +#if defined(REALM_ROBUST_MUTEX_EMULATION) || defined(_WIN32) + struct SharedPart { + }; +#else + using SharedPart = RobustMutex; +#endif + + /// You need to bind the emulation to a SharedPart in shared/mmapped memory. + /// The SharedPart is assumed to have been initialized (possibly by another process) + /// elsewhere. + void set_shared_part(SharedPart& shared_part, const std::string& path, const std::string& mutex_name); + void set_shared_part(SharedPart& shared_part, File&& lock_file); + + /// Destroy shared object. Potentially release system resources. Caller must + /// ensure that the shared_part is not in use at the point of call. + void release_shared_part(); + + /// Lock the mutex. If the mutex is already locked, wait for it to be unlocked. + void lock(); + + /// Non-blocking attempt to lock the mutex. Returns true if the lock is obtained. + /// If the lock can not be obtained return false immediately. + bool try_lock(); + + /// Unlock the mutex + void unlock(); + + /// Attempt to check if the mutex is valid (only relevant if not emulating) + bool is_valid() noexcept; + + static bool is_robust_on_this_platform() + { +#ifdef REALM_ROBUST_MUTEX_EMULATION + return true; // we're faking it! +#else + return RobustMutex::is_robust_on_this_platform(); +#endif + } + +private: +#ifdef REALM_ROBUST_MUTEX_EMULATION + struct LockInfo { + File m_file; + Mutex m_local_mutex; + LockInfo() {} + ~LockInfo() noexcept; + // Disable copying. + LockInfo(const LockInfo&) = delete; + LockInfo& operator=(const LockInfo&) = delete; + }; + /// InterprocessMutex created on the same file (same inode on POSIX) share the same LockInfo. + /// LockInfo will be saved in a static map as a weak ptr and use the UniqueID as the key. + /// Operations on the map need to be protected by s_mutex + static std::map>* s_info_map; + static Mutex* s_mutex; + /// We manually initialize these static variables when first needed, + /// creating them on the heap so that they last for the entire lifetime + /// of the process. The destructor of these is never called; the + /// process will clean up their memory when exiting. It is not enough + /// to count instances of InterprocessMutex and clean up these statics when + /// the count reaches zero because the program can create more + /// InterprocessMutex instances before the process ends, so we really need + /// these variables for the entire lifetime of the process. + static std::once_flag s_init_flag; + static void initialize_statics(); + + /// Only used for release_shared_part + std::string m_filename; + File::UniqueID m_fileuid; + std::shared_ptr m_lock_info; + + /// Free the lock info hold by this instance. + /// If it is the last reference, underly resources will be freed as well. + void free_lock_info(); +#else + SharedPart* m_shared_part = nullptr; + +#ifdef _WIN32 + HANDLE m_handle = 0; +#endif + +#endif + friend class InterprocessCondVar; +}; + +inline InterprocessMutex::InterprocessMutex() +{ +#ifdef REALM_ROBUST_MUTEX_EMULATION + std::call_once(s_init_flag, initialize_statics); +#endif +} + +inline InterprocessMutex::~InterprocessMutex() noexcept +{ +#ifdef _WIN32 + if (m_handle) { + bool b = CloseHandle(m_handle); + REALM_ASSERT_RELEASE(b); + } +#endif + +#ifdef REALM_ROBUST_MUTEX_EMULATION + free_lock_info(); +#endif +} + +#ifdef REALM_ROBUST_MUTEX_EMULATION +inline InterprocessMutex::LockInfo::~LockInfo() noexcept +{ + if (m_file.is_attached()) { + m_file.close(); + } +} + +inline void InterprocessMutex::free_lock_info() +{ + // It has not been initialized yet. + if (!m_lock_info) + return; + + std::lock_guard guard(*s_mutex); + + m_lock_info.reset(); + if ((*s_info_map)[m_fileuid].expired()) { + s_info_map->erase(m_fileuid); + } + m_filename.clear(); +} + +inline void InterprocessMutex::initialize_statics() +{ + s_mutex = new Mutex(); + s_info_map = new std::map>(); +} +#endif + +inline void InterprocessMutex::set_shared_part(SharedPart& shared_part, const std::string& path, + const std::string& mutex_name) +{ +#ifdef REALM_ROBUST_MUTEX_EMULATION + static_cast(shared_part); + + free_lock_info(); + + m_filename = path + "." + mutex_name + ".mx"; + + std::lock_guard guard(*s_mutex); + + // Try to get the file uid if the file exists + if (File::get_unique_id(m_filename, m_fileuid)) { + auto result = s_info_map->find(m_fileuid); + if (result != s_info_map->end()) { + // File exists and the lock info has been created in the map. + m_lock_info = result->second.lock(); + return; + } + } + + // LockInfo has not been created yet. + m_lock_info = std::make_shared(); + // Always use mod_Write to open file and retreive the uid in case other process + // deletes the file. + m_lock_info->m_file.open(m_filename, File::mode_Write); + m_fileuid = m_lock_info->m_file.get_unique_id(); + + (*s_info_map)[m_fileuid] = m_lock_info; +#elif defined(_WIN32) + if (m_handle) { + bool b = CloseHandle(m_handle); + REALM_ASSERT_RELEASE(b); + } + // replace backslashes because they're significant in object namespace names + std::string path_escaped = path; + std::replace(path_escaped.begin(), path_escaped.end(), '\\', '/'); + std::string name = "Local\\realm_named_intermutex_" + path_escaped + mutex_name; + + std::wstring wname(name.begin(), name.end()); + m_handle = CreateMutexW(0, false, wname.c_str()); + if (!m_handle) { + throw std::system_error(GetLastError(), std::system_category(), "Error opening mutex"); + } +#else + m_shared_part = &shared_part; + static_cast(path); + static_cast(mutex_name); +#endif +} + +inline void InterprocessMutex::set_shared_part(SharedPart& shared_part, File&& lock_file) +{ +#ifdef REALM_ROBUST_MUTEX_EMULATION + static_cast(shared_part); + + free_lock_info(); + + std::lock_guard guard(*s_mutex); + + m_fileuid = lock_file.get_unique_id(); + auto result = s_info_map->find(m_fileuid); + if (result == s_info_map->end()) { + m_lock_info = std::make_shared(); + m_lock_info->m_file = std::move(lock_file); + (*s_info_map)[m_fileuid] = m_lock_info; + } + else { + // File exists and the lock info has been created in the map. + m_lock_info = result->second.lock(); + lock_file.close(); + } +#else + m_shared_part = &shared_part; + static_cast(lock_file); +#endif +} + +inline void InterprocessMutex::release_shared_part() +{ +#ifdef REALM_ROBUST_MUTEX_EMULATION + if (!m_filename.empty()) + File::try_remove(m_filename); + + free_lock_info(); +#else + m_shared_part = nullptr; +#endif +} + +inline void InterprocessMutex::lock() +{ +#ifdef REALM_ROBUST_MUTEX_EMULATION + std::unique_lock mutex_lock(m_lock_info->m_local_mutex); + m_lock_info->m_file.lock_exclusive(); + mutex_lock.release(); +#else + +#ifdef _WIN32 + DWORD d = WaitForSingleObject(m_handle, INFINITE); + REALM_ASSERT_RELEASE(d != WAIT_FAILED); +#else + REALM_ASSERT(m_shared_part); + m_shared_part->lock([]() {}); +#endif +#endif +} + +inline bool InterprocessMutex::try_lock() +{ +#ifdef REALM_ROBUST_MUTEX_EMULATION + std::unique_lock mutex_lock(m_lock_info->m_local_mutex, std::try_to_lock_t()); + if (!mutex_lock.owns_lock()) { + return false; + } + bool success = m_lock_info->m_file.try_lock_exclusive(); + if (success) { + mutex_lock.release(); + return true; + } + else { + return false; + } +#else + +#ifdef _WIN32 + DWORD ret = WaitForSingleObject(m_handle, 0); + REALM_ASSERT_RELEASE(ret != WAIT_FAILED); + + if (ret == WAIT_OBJECT_0) { + return true; + } + else { + return false; + } +#else + REALM_ASSERT(m_shared_part); + return m_shared_part->try_lock([]() {}); +#endif +#endif +} + + +inline void InterprocessMutex::unlock() +{ +#ifdef REALM_ROBUST_MUTEX_EMULATION + m_lock_info->m_file.unlock(); + m_lock_info->m_local_mutex.unlock(); +#else +#ifdef _WIN32 + bool b = ReleaseMutex(m_handle); + REALM_ASSERT_RELEASE(b); +#else + REALM_ASSERT(m_shared_part); + m_shared_part->unlock(); +#endif +#endif +} + + +inline bool InterprocessMutex::is_valid() noexcept +{ +#ifdef REALM_ROBUST_MUTEX_EMULATION + return true; +#elif defined(_WIN32) + // There is no safe way of testing if the m_handle mutex handle is valid on Windows, without having bad side effects + // for the cases where it is indeed invalid. If m_handle contains an arbitrary value, it might by coincidence be equal + // to a real live handle of another kind. This excludes a try_lock implementation and many other ideas. + return true; +#else + REALM_ASSERT(m_shared_part); + return m_shared_part->is_valid(); +#endif +} + + +} // namespace util +} // namespace realm + +#endif // #ifndef REALM_UTIL_INTERPROCESS_MUTEX diff --git a/Pods/Realm/include/core/realm/util/json_parser.hpp b/Pods/Realm/include/core/realm/util/json_parser.hpp new file mode 100644 index 0000000000..bc6664ae4b --- /dev/null +++ b/Pods/Realm/include/core/realm/util/json_parser.hpp @@ -0,0 +1,545 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_JSON_PARSER_HPP +#define REALM_UTIL_JSON_PARSER_HPP + +#include +#include +#include +#include + +#include + +namespace realm { +namespace util { + +/// A JSON parser that neither allocates heap memory nor throws exceptions. +/// +/// The parser takes as input a range of characters, and emits a stream of events +/// representing the structure of the JSON document. +/// +/// Parser errors are represented as `std::error_condition`s. +class JSONParser { +public: + using InputIterator = const char*; + + enum class EventType { + number, + string, + boolean, + null, + array_begin, + array_end, + object_begin, + object_end + }; + + using Range = StringData; + + struct Event { + EventType type; + Range range; + Event(EventType type): type(type) {} + + union { + bool boolean; + double number; + }; + + StringData escaped_string_value() const noexcept; + + /// Unescape the string value into \a buffer. + /// The type of this event must be EventType::string. + /// + /// \param buffer is a pointer to a buffer big enough to hold the + /// unescaped string value. The unescaped string is guaranteed to be + /// shorter than the escaped string, so escaped_string_value().size() can + /// be used as an upper bound. Unicode sequences of the form "\uXXXX" + /// will be converted to UTF-8 sequences. Note that the escaped form of + /// a unicode point takes exactly 6 bytes, which is also the maximum + /// possible length of a UTF-8 encoded codepoint. + StringData unescape_string(char* buffer) const noexcept; + }; + + enum class Error { + unexpected_token = 1, + unexpected_end_of_stream = 2 + }; + + JSONParser(StringData); + + /// Parse the input data, and call f repeatedly with an argument of type Event + /// representing the token that the parser encountered. + /// + /// The stream of events is "flat", which is to say that it is the responsibility + /// of the function f to keep track of any nested object structures as it deems + /// appropriate. + /// + /// This function is guaranteed to never throw, as long as f never throws. + template + std::error_condition parse(F&& f) noexcept(noexcept(f(std::declval()))); + + class ErrorCategory: public std::error_category { + public: + const char* name() const noexcept final; + std::string message(int) const final; + }; + static const ErrorCategory error_category; +private: + enum Token: char { + object_begin = '{', + object_end = '}', + array_begin = '[', + array_end = ']', + colon = ':', + comma = ',', + dquote = '"', + escape = '\\', + minus = '-', + space = ' ', + tab = '\t', + cr = '\r', + lf = '\n', + }; + + InputIterator m_current; + InputIterator m_end; + + template + std::error_condition parse_object(F&& f) noexcept(noexcept(f(std::declval()))); + template + std::error_condition parse_pair(F&& f) noexcept(noexcept(f(std::declval()))); + template + std::error_condition parse_array(F&& f) noexcept(noexcept(f(std::declval()))); + template + std::error_condition parse_number(F&& f) noexcept(noexcept(f(std::declval()))); + template + std::error_condition parse_string(F&& f) noexcept(noexcept(f(std::declval()))); + template + std::error_condition parse_value(F&& f) noexcept(noexcept(f(std::declval()))); + template + std::error_condition parse_boolean(F&& f) noexcept(noexcept(f(std::declval()))); + template + std::error_condition parse_null(F&& f) noexcept(noexcept(f(std::declval()))); + + std::error_condition expect_token(char, Range& out_range) noexcept; + std::error_condition expect_token(Token, Range& out_range) noexcept; + + // Returns true unless EOF was reached. + bool peek_char(char& out_c) noexcept; + bool peek_token(Token& out_t) noexcept; + bool is_whitespace(Token t) noexcept; + void skip_whitespace() noexcept; +}; + +std::error_condition make_error_condition(JSONParser::Error e); + +} // namespace util +} // namespace realm + +namespace std { +template<> +struct is_error_condition_enum { + static const bool value = true; +}; +} + +namespace realm { +namespace util { + +/// Implementation: + + +inline JSONParser::JSONParser(StringData input): + m_current(input.data()), m_end(input.data() + input.size()) +{ +} + +template +std::error_condition JSONParser::parse(F&& f) noexcept(noexcept(f(std::declval()))) +{ + return parse_value(f); +} + +template +std::error_condition JSONParser::parse_object(F&& f) noexcept(noexcept(f(std::declval()))) +{ + Event event{EventType::object_begin}; + auto ec = expect_token(Token::object_begin, event.range); + if (ec) + return ec; + ec = f(event); + if (ec) + return ec; + + while (true) { + ec = expect_token(Token::object_end, event.range); + if (!ec) { + // End of object + event.type = EventType::object_end; + ec = f(event); + if (ec) + return ec; + break; + } + + if (ec != Error::unexpected_token) + return ec; + + ec = parse_pair(f); + if (ec) + return ec; + + skip_whitespace(); + + Token t; + if (peek_token(t)) { + if (t == Token::object_end) { + // Fine, will terminate on next iteration + } + else if (t == Token::comma) + ++m_current; // OK, because peek_char returned true + else + return Error::unexpected_token; + } + else { + return Error::unexpected_end_of_stream; + } + } + + return std::error_condition{}; +} + +template +std::error_condition JSONParser::parse_pair(F&& f) noexcept(noexcept(f(std::declval()))) +{ + skip_whitespace(); + + auto ec = parse_string(f); + if (ec) + return ec; + + skip_whitespace(); + + Token t; + if (peek_token(t)) { + if (t == Token::colon) { + ++m_current; + } + else { + return Error::unexpected_token; + } + } + + return parse_value(f); +} + +template +std::error_condition JSONParser::parse_array(F&& f) noexcept(noexcept(f(std::declval()))) +{ + Event event{EventType::array_begin}; + auto ec = expect_token(Token::array_begin, event.range); + if (ec) + return ec; + ec = f(event); + if (ec) + return ec; + + while (true) { + ec = expect_token(Token::array_end, event.range); + if (!ec) { + // End of array + event.type = EventType::array_end; + ec = f(event); + if (ec) + return ec; + break; + } + + if (ec != Error::unexpected_token) + return ec; + + ec = parse_value(f); + if (ec) + return ec; + + skip_whitespace(); + + Token t; + if (peek_token(t)) { + if (t == Token::array_end) { + // Fine, will terminate next iteration. + } + else if (t == Token::comma) + ++m_current; // OK, because peek_char returned true + else + return Error::unexpected_token; + } + else { + return Error::unexpected_end_of_stream; + } + } + + return std::error_condition{}; +} + +template +std::error_condition JSONParser::parse_number(F&& f) noexcept(noexcept(f(std::declval()))) +{ + static const size_t buffer_size = 64; + char buffer[buffer_size] = {0}; + size_t bytes_to_copy = std::min(m_end - m_current, buffer_size - 1); + if (bytes_to_copy == 0) + return Error::unexpected_end_of_stream; + + if (std::isspace(*m_current)) { + // JSON has a different idea of what constitutes whitespace than isspace(), + // but strtod() uses isspace() to skip initial whitespace. We have already + // skipped whitespace that JSON considers valid, so if there is any whitespace + // at m_current now, it is invalid according to JSON, and so is an error. + return Error::unexpected_token; + } + + switch (m_current[0]) { + case 'N': + // strtod() parses "NAN", JSON does not. + case 'I': + // strtod() parses "INF", JSON does not. + case 'p': + case 'P': + // strtod() may parse exponent notation, JSON does not. + return Error::unexpected_token; + case '0': + if (bytes_to_copy > 2 && (m_current[1] == 'x' || m_current[1] == 'X')) { + // strtod() parses hexadecimal, JSON does not. + return Error::unexpected_token; + } + } + + std::copy(m_current, m_current + bytes_to_copy, buffer); + + char* endp = nullptr; + Event event{EventType::number}; + event.number = std::strtod(buffer, &endp); + + if (endp == buffer) { + return Error::unexpected_token; + } + size_t num_bytes_consumed = endp - buffer; + m_current += num_bytes_consumed; + return f(event); +} + +template +std::error_condition JSONParser::parse_string(F&& f) noexcept(noexcept(f(std::declval()))) +{ + InputIterator p = m_current; + if (p >= m_end) + return Error::unexpected_end_of_stream; + + auto count_num_escapes_backwards = [](const char* p, const char* begin) -> size_t { + size_t result = 0; + for (; p > begin && *p == Token::escape; ++p) + ++result; + return result; + }; + + Token t = static_cast(*p); + InputIterator inner_end; + if (t == Token::dquote) { + inner_end = m_current; + do { + inner_end = std::find(inner_end + 1, m_end, Token::dquote); + if (inner_end == m_end) + return Error::unexpected_end_of_stream; + } while (count_num_escapes_backwards(inner_end - 1, m_current) % 2 == 1); + + Event event{EventType::string}; + event.range = Range(m_current, inner_end - m_current + 1); + m_current = inner_end + 1; + return f(event); + } + return Error::unexpected_token; +} + +template +std::error_condition JSONParser::parse_boolean(F&& f) noexcept(noexcept(f(std::declval()))) +{ + auto first_nonalpha = std::find_if_not(m_current, m_end, [](auto c) { return std::isalpha(c); }); + + Event event{EventType::boolean}; + event.range = Range(m_current, first_nonalpha - m_current); + if (event.range == "true") { + event.boolean = true; + m_current += 4; + return f(event); + } + else if (event.range == "false") { + event.boolean = false; + m_current += 5; + return f(event); + } + + return Error::unexpected_token; +} + +template +std::error_condition JSONParser::parse_null(F&& f) noexcept(noexcept(f(std::declval()))) +{ + auto first_nonalpha = std::find_if_not(m_current, m_end, [](auto c) { return std::isalpha(c); }); + + Event event{EventType::null}; + event.range = Range(m_current, first_nonalpha - m_current); + if (event.range == "null") { + m_current += 4; + return f(event); + } + + return Error::unexpected_token; +} + +template +std::error_condition JSONParser::parse_value(F&& f) noexcept(noexcept(f(std::declval()))) +{ + skip_whitespace(); + + if (m_current >= m_end) + return Error::unexpected_end_of_stream; + + if (*m_current == Token::object_begin) + return parse_object(f); + + if (*m_current == Token::array_begin) + return parse_array(f); + + if (*m_current == 't' || *m_current == 'f') + return parse_boolean(f); + + if (*m_current == 'n') + return parse_null(f); + + if (*m_current == Token::dquote) + return parse_string(f); + + return parse_number(f); +} + +inline +bool JSONParser::is_whitespace(Token t) noexcept +{ + switch (t) { + case Token::space: + case Token::tab: + case Token::cr: + case Token::lf: + return true; + default: + return false; + } +} + +inline +void JSONParser::skip_whitespace() noexcept +{ + while (m_current < m_end && is_whitespace(static_cast(*m_current))) + ++m_current; +} + +inline +std::error_condition JSONParser::expect_token(char c, Range& out_range) noexcept +{ + skip_whitespace(); + if (m_current == m_end) + return Error::unexpected_end_of_stream; + if (*m_current == c) { + out_range = Range(m_current, 1); + ++m_current; + return std::error_condition{}; + } + return Error::unexpected_token; +} + +inline +std::error_condition JSONParser::expect_token(Token t, Range& out_range) noexcept +{ + return expect_token(static_cast(t), out_range); +} + +inline +bool JSONParser::peek_char(char& out_c) noexcept +{ + if (m_current < m_end) { + out_c = *m_current; + return true; + } + return false; +} + +inline +bool JSONParser::peek_token(Token& out_t) noexcept +{ + if (m_current < m_end) { + out_t = static_cast(*m_current); + return true; + } + return false; +} + +inline +StringData JSONParser::Event::escaped_string_value() const noexcept +{ + REALM_ASSERT(type == EventType::string); + REALM_ASSERT(range.size() >= 2); + return StringData(range.data() + 1, range.size() - 2); +} + +template +OS& operator<<(OS& os, JSONParser::EventType type) +{ + switch (type) { + case JSONParser::EventType::number: os << "number"; return os; + case JSONParser::EventType::string: os << "string"; return os; + case JSONParser::EventType::boolean: os << "boolean"; return os; + case JSONParser::EventType::null: os << "null"; return os; + case JSONParser::EventType::array_begin: os << "["; return os; + case JSONParser::EventType::array_end: os << "]"; return os; + case JSONParser::EventType::object_begin: os << "{"; return os; + case JSONParser::EventType::object_end: os << "}"; return os; + } + REALM_UNREACHABLE(); +} + +template +OS& operator<<(OS& os, const JSONParser::Event& e) { + os << e.type; + switch (e.type) { + case JSONParser::EventType::number: return os << "(" << e.number << ")"; + case JSONParser::EventType::string: return os << "(" << e.range << ")"; + case JSONParser::EventType::boolean: return os << "(" << e.boolean << ")"; + default: return os; + } +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_JSON_PARSER_HPP + diff --git a/Pods/Realm/include/core/realm/util/load_file.hpp b/Pods/Realm/include/core/realm/util/load_file.hpp new file mode 100644 index 0000000000..14090fcfa1 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/load_file.hpp @@ -0,0 +1,36 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_UTIL_LOAD_FILE_HPP +#define REALM_UTIL_LOAD_FILE_HPP + +#include + +namespace realm { +namespace util { + +// FIXME: These functions ought to be moved to in the +// realm-core repository. +std::string load_file(const std::string& path); +std::string load_file_and_chomp(const std::string& path); + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_LOAD_FILE_HPP diff --git a/Pods/Realm/include/core/realm/util/logger.hpp b/Pods/Realm/include/core/realm/util/logger.hpp new file mode 100644 index 0000000000..0946208f3d --- /dev/null +++ b/Pods/Realm/include/core/realm/util/logger.hpp @@ -0,0 +1,511 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_LOGGER_HPP +#define REALM_UTIL_LOGGER_HPP + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace realm { +namespace util { + + +/// All Logger objects store a reference to a LevelThreshold object which it +/// uses to efficiently query about the current log level threshold +/// (`level_threshold.get()`). All messages logged with a level that is lower +/// than the current threshold will be dropped. For the sake of efficiency, this +/// test happens before the message is formatted. +/// +/// A logger is not inherently thread-safe, but specific implementations can be +/// (see ThreadSafeLogger). For a logger to be thread-safe, the implementation +/// of do_log() must be thread-safe and the referenced LevelThreshold object +/// must have a thread-safe get() method. +/// +/// Examples: +/// +/// logger.error("Overlong message from master coordinator"); +/// logger.info("Listening for peers on %1:%2", listen_address, listen_port); +class Logger { +public: + template + void trace(const char* message, Params&&...); + template + void debug(const char* message, Params&&...); + template + void detail(const char* message, Params&&...); + template + void info(const char* message, Params&&...); + template + void warn(const char* message, Params&&...); + template + void error(const char* message, Params&&...); + template + void fatal(const char* message, Params&&...); + + /// Specifies criticality when passed to log(). Functions as a criticality + /// threshold when returned from LevelThreshold::get(). + /// + /// error Be silent unless when there is an error. + /// warn Be silent unless when there is an error or a warning. + /// info Reveal information about what is going on, but in a + /// minimalistic fashion to avoid general overhead from logging + /// and to keep volume down. + /// detail Same as 'info', but prioritize completeness over minimalism. + /// debug Reveal information that can aid debugging, no longer paying + /// attention to efficiency. + /// trace A version of 'debug' that allows for very high volume + /// output. + enum class Level { all, trace, debug, detail, info, warn, error, fatal, off }; + + template + void log(Level, const char* message, Params&&...); + + /// Shorthand for `int(level) >= int(level_threshold.get())`. + bool would_log(Level level) const noexcept; + + class LevelThreshold; + + const LevelThreshold& level_threshold; + + virtual ~Logger() noexcept; + +protected: + Logger(const LevelThreshold&) noexcept; + + static void do_log(Logger&, Level, std::string message); + + virtual void do_log(Level, std::string message) = 0; + + static const char* get_level_prefix(Level) noexcept; + +private: + struct State; + + template + REALM_NOINLINE void do_log(Level, const char* message, Params&&...); + void log_impl(State&); + template + void log_impl(State&, Param&&, Params&&...); + template + static void subst(State&, Param&&); +}; + +template +std::basic_ostream& operator<<(std::basic_ostream&, Logger::Level); + +template +std::basic_istream& operator>>(std::basic_istream&, Logger::Level&); + +class Logger::LevelThreshold { +public: + virtual Level get() const noexcept = 0; +}; + + +/// A root logger that is not thread-safe and allows for the log level threshold +/// to be changed over time. The initial log level threshold is +/// Logger::Level::info. +class RootLogger : private Logger::LevelThreshold, public Logger { +public: + void set_level_threshold(Level) noexcept; + +protected: + RootLogger(); + +private: + Level m_level_threshold = Level::info; + Level get() const noexcept override final; +}; + + +/// A logger that writes to STDERR. This logger is not thread-safe. +/// +/// Since this class is a RootLogger, it contains modifiable a log level +/// threshold. +class StderrLogger : public RootLogger { +protected: + void do_log(Level, std::string) override final; +}; + + +/// A logger that writes to a stream. This logger is not thread-safe. +/// +/// Since this class is a RootLogger, it contains modifiable a log level +/// threshold. +class StreamLogger : public RootLogger { +public: + explicit StreamLogger(std::ostream&) noexcept; + +protected: + void do_log(Level, std::string) override final; + +private: + std::ostream& m_out; +}; + + +/// A logger that writes to a file. This logger is not thread-safe. +/// +/// Since this class is a RootLogger, it contains modifiable a log level +/// threshold. +class FileLogger : public StreamLogger { +public: + explicit FileLogger(std::string path); + explicit FileLogger(util::File); + +private: + util::File m_file; + util::File::Streambuf m_streambuf; + std::ostream m_out; +}; + + +/// A thread-safe logger. This logger ignores the level threshold of the base +/// logger. Instead, it introduces new a LevelThreshold object with a fixed +/// value to achieve thread safety. +class ThreadSafeLogger : private Logger::LevelThreshold, public Logger { +public: + explicit ThreadSafeLogger(Logger& base_logger, Level = Level::info); + +protected: + void do_log(Level, std::string) override final; + +private: + const Level m_level_threshold; // Immutable for thread safety + Logger& m_base_logger; + Mutex m_mutex; + Level get() const noexcept override final; +}; + + +/// A logger that adds a fixed prefix to each message. This logger inherits the +/// LevelThreshold object of the specified base logger. This logger is +/// thread-safe if, and only if the base logger is thread-safe. +class PrefixLogger : public Logger { +public: + PrefixLogger(std::string prefix, Logger& base_logger) noexcept; + +protected: + void do_log(Level, std::string) override final; + +private: + const std::string m_prefix; + Logger& m_base_logger; +}; + + +// Implementation + +struct Logger::State { + Logger::Level m_level; + std::string m_message; + std::string m_search; + int m_param_num = 1; + std::ostringstream m_formatter; + std::locale m_locale = std::locale::classic(); + State(Logger::Level level, const char* s) + : m_level(level) + , m_message(s) + , m_search(m_message) + { + m_formatter.imbue(m_locale); + } +}; + +template +inline void Logger::trace(const char* message, Params&&... params) +{ + log(Level::trace, message, std::forward(params)...); // Throws +} + +template +inline void Logger::debug(const char* message, Params&&... params) +{ + log(Level::debug, message, std::forward(params)...); // Throws +} + +template +inline void Logger::detail(const char* message, Params&&... params) +{ + log(Level::detail, message, std::forward(params)...); // Throws +} + +template +inline void Logger::info(const char* message, Params&&... params) +{ + log(Level::info, message, std::forward(params)...); // Throws +} + +template +inline void Logger::warn(const char* message, Params&&... params) +{ + log(Level::warn, message, std::forward(params)...); // Throws +} + +template +inline void Logger::error(const char* message, Params&&... params) +{ + log(Level::error, message, std::forward(params)...); // Throws +} + +template +inline void Logger::fatal(const char* message, Params&&... params) +{ + log(Level::fatal, message, std::forward(params)...); // Throws +} + +template +inline void Logger::log(Level level, const char* message, Params&&... params) +{ + if (would_log(level)) + do_log(level, message, std::forward(params)...); // Throws +} + +inline bool Logger::would_log(Level level) const noexcept +{ + return int(level) >= int(level_threshold.get()); +} + +inline Logger::~Logger() noexcept +{ +} + +inline Logger::Logger(const LevelThreshold& lt) noexcept + : level_threshold(lt) +{ +} + +inline void Logger::do_log(Logger& logger, Level level, std::string message) +{ + logger.do_log(level, std::move(message)); // Throws +} + +template +void Logger::do_log(Level level, const char* message, Params&&... params) +{ + State state(level, message); + log_impl(state, std::forward(params)...); // Throws +} + +inline void Logger::log_impl(State& state) +{ + do_log(state.m_level, std::move(state.m_message)); // Throws +} + +template +inline void Logger::log_impl(State& state, Param&& param, Params&&... params) +{ + subst(state, std::forward(param)); // Throws + log_impl(state, std::forward(params)...); // Throws +} + +template +void Logger::subst(State& state, Param&& param) +{ + state.m_formatter << "%" << state.m_param_num; + std::string key = state.m_formatter.str(); + state.m_formatter.str(std::string()); + std::string::size_type j = state.m_search.find(key); + if (j != std::string::npos) { + state.m_formatter << std::forward(param); + std::string str = state.m_formatter.str(); + state.m_formatter.str(std::string()); + state.m_message.replace(j, key.size(), str); + state.m_search.replace(j, key.size(), std::string(str.size(), '\0')); + } + ++state.m_param_num; +} + +template +std::basic_ostream& operator<<(std::basic_ostream& out, Logger::Level level) +{ + switch (level) { + case Logger::Level::all: + out << "all"; + return out; + case Logger::Level::trace: + out << "trace"; + return out; + case Logger::Level::debug: + out << "debug"; + return out; + case Logger::Level::detail: + out << "detail"; + return out; + case Logger::Level::info: + out << "info"; + return out; + case Logger::Level::warn: + out << "warn"; + return out; + case Logger::Level::error: + out << "error"; + return out; + case Logger::Level::fatal: + out << "fatal"; + return out; + case Logger::Level::off: + out << "off"; + return out; + } + REALM_ASSERT(false); + return out; +} + +template +std::basic_istream& operator>>(std::basic_istream& in, Logger::Level& level) +{ + std::basic_string str; + auto check = [&](const char* name) { + size_t n = strlen(name); + if (n != str.size()) + return false; + for (size_t i = 0; i < n; ++i) { + if (in.widen(name[i]) != str[i]) + return false; + } + return true; + }; + if (in >> str) { + if (check("all")) { + level = Logger::Level::all; + } + else if (check("trace")) { + level = Logger::Level::trace; + } + else if (check("debug")) { + level = Logger::Level::debug; + } + else if (check("detail")) { + level = Logger::Level::detail; + } + else if (check("info")) { + level = Logger::Level::info; + } + else if (check("warn")) { + level = Logger::Level::warn; + } + else if (check("error")) { + level = Logger::Level::error; + } + else if (check("fatal")) { + level = Logger::Level::fatal; + } + else if (check("off")) { + level = Logger::Level::off; + } + else { + in.setstate(std::ios_base::failbit); + } + } + return in; +} + +inline void RootLogger::set_level_threshold(Level new_level_threshold) noexcept +{ + m_level_threshold = new_level_threshold; +} + +inline RootLogger::RootLogger() + : Logger::LevelThreshold() + , Logger(static_cast(*this)) +{ +} + +inline Logger::Level RootLogger::get() const noexcept +{ + return m_level_threshold; +} + +inline void StderrLogger::do_log(Level level, std::string message) +{ + std::cerr << get_level_prefix(level) << message << '\n'; // Throws + std::cerr.flush(); // Throws +} + +inline StreamLogger::StreamLogger(std::ostream& out) noexcept + : m_out(out) +{ +} + +inline void StreamLogger::do_log(Level level, std::string message) +{ + m_out << get_level_prefix(level) << message << '\n'; // Throws + m_out.flush(); // Throws +} + +inline FileLogger::FileLogger(std::string path) + : StreamLogger(m_out) + , m_file(path, util::File::mode_Write) // Throws + , m_streambuf(&m_file) // Throws + , m_out(&m_streambuf) // Throws +{ +} + +inline FileLogger::FileLogger(util::File file) + : StreamLogger(m_out) + , m_file(std::move(file)) + , m_streambuf(&m_file) // Throws + , m_out(&m_streambuf) // Throws +{ +} + +inline ThreadSafeLogger::ThreadSafeLogger(Logger& base_logger, Level threshold) + : Logger::LevelThreshold() + , Logger(static_cast(*this)) + , m_level_threshold(threshold) + , m_base_logger(base_logger) +{ +} + +inline void ThreadSafeLogger::do_log(Level level, std::string message) +{ + LockGuard l(m_mutex); + Logger::do_log(m_base_logger, level, message); // Throws +} + +inline Logger::Level ThreadSafeLogger::get() const noexcept +{ + return m_level_threshold; +} + +inline PrefixLogger::PrefixLogger(std::string prefix, Logger& base_logger) noexcept + : Logger(base_logger.level_threshold) + , m_prefix(std::move(prefix)) + , m_base_logger(base_logger) +{ +} + +inline void PrefixLogger::do_log(Level level, std::string message) +{ + Logger::do_log(m_base_logger, level, m_prefix + message); // Throws +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_LOGGER_HPP diff --git a/Pods/Realm/include/core/realm/util/memory_stream.hpp b/Pods/Realm/include/core/realm/util/memory_stream.hpp new file mode 100644 index 0000000000..51584e829a --- /dev/null +++ b/Pods/Realm/include/core/realm/util/memory_stream.hpp @@ -0,0 +1,212 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_MEMORY_STREAM_HPP +#define REALM_UTIL_MEMORY_STREAM_HPP + +#include +#include +#include +#include + +namespace realm { +namespace util { + +class MemoryInputStreambuf : public std::streambuf { +public: + MemoryInputStreambuf(); + ~MemoryInputStreambuf() noexcept; + + /// Behavior is undefined if the size of the specified buffer exceeds + /// PTRDIFF_MAX. + void set_buffer(const char* begin, const char* end) noexcept; + +private: + const char* m_begin; + const char* m_end; + const char* m_curr; + + int_type underflow() override; + int_type uflow() override; + int_type pbackfail(int_type) override; + std::streamsize showmanyc() override; + pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode) override; + pos_type seekpos(pos_type, std::ios_base::openmode) override; + + pos_type do_seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode); +}; + + +class MemoryOutputStreambuf : public std::streambuf { +public: + MemoryOutputStreambuf(); + ~MemoryOutputStreambuf() noexcept; + + /// Behavior is undefined if the size of the specified buffer exceeds + /// PTRDIFF_MAX. + void set_buffer(char* begin, char* end) noexcept; + + /// Returns the amount of data written to the buffer. + size_t size() const noexcept; +}; + + +class MemoryInputStream : public std::istream { +public: + MemoryInputStream(); + ~MemoryInputStream() noexcept; + + /// \{ Behavior is undefined if the size of the specified buffer exceeds + /// PTRDIFF_MAX. + void set_buffer(const char* begin, const char* end) noexcept; + template void set_buffer(const char (&buffer)[N]) noexcept; + void set_string(const std::string&) noexcept; + void set_c_string(const char* c_str) noexcept; + /// \} + +private: + MemoryInputStreambuf m_streambuf; +}; + + +class MemoryOutputStream : public std::ostream { +public: + MemoryOutputStream(); + ~MemoryOutputStream() noexcept; + + /// \{ Behavior is undefined if the size of the specified buffer exceeds + /// PTRDIFF_MAX. + void set_buffer(char* begin, char* end) noexcept; + template void set_buffer(char (&buffer)[N]) noexcept; + /// \} + + /// Returns the amount of data written to the underlying buffer. + size_t size() const noexcept; + +private: + MemoryOutputStreambuf m_streambuf; +}; + + +// Implementation + +inline MemoryInputStreambuf::MemoryInputStreambuf() + : m_begin(nullptr) + , m_end(nullptr) + , m_curr(nullptr) +{ +} + +inline MemoryInputStreambuf::~MemoryInputStreambuf() noexcept +{ +} + +inline void MemoryInputStreambuf::set_buffer(const char* begin, const char* end) noexcept +{ + m_begin = begin; + m_end = end; + m_curr = begin; +} + + +inline MemoryOutputStreambuf::MemoryOutputStreambuf() +{ +} + +inline MemoryOutputStreambuf::~MemoryOutputStreambuf() noexcept +{ +} + +inline void MemoryOutputStreambuf::set_buffer(char* begin, char* end) noexcept +{ + setp(begin, end); +} + +inline size_t MemoryOutputStreambuf::size() const noexcept +{ + return pptr() - pbase(); +} + + +inline MemoryInputStream::MemoryInputStream() + : std::istream(&m_streambuf) +{ +} + +inline MemoryInputStream::~MemoryInputStream() noexcept +{ +} + +inline void MemoryInputStream::set_buffer(const char* begin, const char* end) noexcept +{ + m_streambuf.set_buffer(begin, end); + clear(); +} + +template inline void MemoryInputStream::set_buffer(const char (&buffer)[N]) noexcept +{ + const char* begin = buffer; + const char* end = begin + N; + set_buffer(begin, end); +} + +inline void MemoryInputStream::set_string(const std::string& str) noexcept +{ + const char* begin = str.data(); + const char* end = begin + str.size(); + set_buffer(begin, end); +} + +inline void MemoryInputStream::set_c_string(const char* c_str) noexcept +{ + const char* begin = c_str; + const char* end = begin + traits_type::length(c_str); + set_buffer(begin, end); +} + + +inline MemoryOutputStream::MemoryOutputStream() + : std::ostream(&m_streambuf) +{ +} + +inline MemoryOutputStream::~MemoryOutputStream() noexcept +{ +} + +inline void MemoryOutputStream::set_buffer(char* begin, char* end) noexcept +{ + m_streambuf.set_buffer(begin, end); + clear(); +} + +template +inline void MemoryOutputStream::set_buffer(char (&buffer)[N]) noexcept +{ + set_buffer(buffer, buffer + N); +} + +inline size_t MemoryOutputStream::size() const noexcept +{ + return m_streambuf.size(); +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_MEMORY_STREAM_HPP diff --git a/Pods/Realm/include/core/realm/util/misc_errors.hpp b/Pods/Realm/include/core/realm/util/misc_errors.hpp new file mode 100644 index 0000000000..9335ba90bd --- /dev/null +++ b/Pods/Realm/include/core/realm/util/misc_errors.hpp @@ -0,0 +1,49 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_MISC_ERRORS_HPP +#define REALM_UTIL_MISC_ERRORS_HPP + +#include + + +namespace realm { +namespace util { +namespace error { + +enum misc_errors { + unknown = 1, +}; + +std::error_code make_error_code(misc_errors); + +} // namespace error +} // namespace util +} // namespace realm + +namespace std { + +template <> +class is_error_code_enum { +public: + static const bool value = true; +}; + +} // namespace std + +#endif // REALM_UTIL_MISC_ERRORS_HPP diff --git a/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp b/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp new file mode 100644 index 0000000000..e5f5d34980 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp @@ -0,0 +1,69 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_UTIL_MISC_EXT_ERRORS_HPP +#define REALM_UTIL_MISC_EXT_ERRORS_HPP + +#include + +namespace realm { +namespace util { + +/// FIXME: The intention is that this enum will be merged into, and subsumed by +/// util::MiscErrors in `` in the core library. +enum class MiscExtErrors { + /// End of input. + end_of_input = 1, + + /// Premature end of input. That is, end of input at an unexpected, or + /// illegal place in an input stream. + premature_end_of_input, + + /// Delimiter not found. + delim_not_found +}; + +class MiscExtErrorCategory : public std::error_category { +public: + const char* name() const noexcept override final; + std::string message(int) const override final; +}; + +/// The error category associated with MiscErrors. The name of this category is +/// `realm.util.misc_ext`. +extern MiscExtErrorCategory misc_ext_error_category; + +inline std::error_code make_error_code(MiscExtErrors err) +{ + return std::error_code(int(err), misc_ext_error_category); +} + +} // namespace util +} // namespace realm + +namespace std { + +template<> class is_error_code_enum { +public: + static const bool value = true; +}; + +} // namespace std + +#endif // REALM_UTIL_MISC_EXT_ERRORS_HPP diff --git a/Pods/Realm/include/core/realm/util/miscellaneous.hpp b/Pods/Realm/include/core/realm/util/miscellaneous.hpp new file mode 100644 index 0000000000..c45e4f3999 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/miscellaneous.hpp @@ -0,0 +1,49 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_MISCELLANEOUS_HPP +#define REALM_UTIL_MISCELLANEOUS_HPP + +#include + +namespace realm { +namespace util { + +// FIXME: Replace this with std::add_const_t when we switch over to C++14 by +// default. +/// \brief Adds const qualifier, unless T already has the const qualifier +template +using add_const_t = typename std::add_const::type; + +// FIXME: Replace this with std::as_const when we switch over to C++17 by +// default. +/// \brief Forms an lvalue reference to const T +template +constexpr add_const_t& as_const(T& v) noexcept +{ + return v; +} + +/// \brief Disallows rvalue arguments +template +add_const_t& as_const(const T&&) = delete; + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_MISCELLANEOUS_HPP diff --git a/Pods/Realm/include/core/realm/util/network.hpp b/Pods/Realm/include/core/realm/util/network.hpp new file mode 100644 index 0000000000..696b093d64 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/network.hpp @@ -0,0 +1,3707 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_UTIL_NETWORK_HPP +#define REALM_UTIL_NETWORK_HPP + +#include +#include +#include +#include +#include +#include + +#include + +#ifdef _WIN32 +# include +# include +# include +# include +# pragma comment(lib, "Ws2_32.lib") +#else +# include +# include +# include +#endif + +#include +#include +#include +#include +#include +#include +#include + +// Linux epoll +// +// Require Linux kernel version >= 2.6.27 such that we have epoll_create1(), +// `O_CLOEXEC`, and `EPOLLRDHUP`. +#if defined(__linux__) +# include +# if !defined(REALM_HAVE_EPOLL) +# if !defined(REALM_DISABLE_UTIL_NETWORK_EPOLL) +# if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27) +# define REALM_HAVE_EPOLL 1 +# endif +# endif +# endif +#endif +#if !defined(REALM_HAVE_EPOLL) +# define REALM_HAVE_EPOLL 0 +#endif + +// FreeBSD Kqueue. +// +// Available on Mac OS X, FreeBSD, NetBSD, OpenBSD +#if (defined(__MACH__) && defined(__APPLE__)) || defined(__FreeBSD__) || \ + defined(__NetBSD__) || defined(__OpenBSD__) +# if !defined(REALM_HAVE_KQUEUE) +# if !defined(REALM_DISABLE_UTIL_NETWORK_KQUEUE) +# define REALM_HAVE_KQUEUE 1 +# endif +# endif +#endif +#if !defined(REALM_HAVE_KQUEUE) +# define REALM_HAVE_KQUEUE 0 +#endif + + + +// FIXME: Unfinished business around `Address::m_ip_v6_scope_id`. + + +namespace realm { +namespace util { + +/// \brief TCP/IP networking API. +/// +/// The design of this networking API is heavily inspired by the ASIO C++ +/// library (http://think-async.com). +/// +/// +/// ### Thread safety +/// +/// A *service context* is a set of objects consisting of an instance of +/// Service, and all the objects that are associated with that instance (\ref +/// Resolver, \ref Socket`, \ref Acceptor`, \ref DeadlineTimer, \ref Trigger, +/// and \ref ssl::Stream). +/// +/// In general, it is unsafe for two threads to call functions on the same +/// object, or on different objects in the same service context. This also +/// applies to destructors. Notable exceptions are the fully thread-safe +/// functions, such as Service::post(), Service::stop(), and Service::reset(). +/// +/// On the other hand, it is always safe for two threads to call functions on +/// objects belonging to different service contexts. +/// +/// One implication of these rules is that at most one thread must execute run() +/// at any given time, and if one thread is executing run(), then no other +/// thread is allowed to access objects in the same service context (with the +/// mentioned exceptions). +/// +/// Unless otherwise specified, free-standing objects, such as \ref +/// StreamProtocol, \ref Address, \ref Endpoint, and \ref Endpoint::List are +/// fully thread-safe as long as they are not mutated. If one thread is mutating +/// such an object, no other thread may access it. Note that these free-standing +/// objects are not associcated with an instance of Service, and are therefore +/// not part of a service context. +/// +/// +/// ### Comparison with ASIO +/// +/// There is a crucial difference between the two libraries in regards to the +/// guarantees that are provided about the cancelability of asynchronous +/// operations. The Realm networking library (this library) considers an +/// asynchronous operation to be complete precisely when the completion handler +/// starts to execute, and it guarantees that such an operation is cancelable up +/// until that point in time. In particular, if `cancel()` is called on a socket +/// or a deadline timer object before the completion handler starts to execute, +/// then that operation will be canceled, and will receive +/// `error::operation_aborted`. This guarantee is possible to provide (and free +/// of ambiguities) precisely because this library prohibits multiple threads +/// from executing the event loop concurrently, and because `cancel()` is +/// allowed to be called only from a completion handler (executed by the event +/// loop thread) or while no thread is executing the event loop. This guarantee +/// allows for safe destruction of sockets and deadline timers as long as the +/// completion handlers react appropriately to `error::operation_aborted`, in +/// particular, that they do not attempt to access the socket or deadline timer +/// object in such cases. +/// +/// ASIO, on the other hand, allows for an asynchronous operation to complete +/// and become **uncancellable** before the completion handler starts to +/// execute. For this reason, it is possible with ASIO to get the completion +/// handler of an asynchronous wait operation to start executing and receive an +/// error code other than "operation aborted" at a point in time where +/// `cancel()` has already been called on the deadline timer object, or even at +/// a point in timer where the deadline timer has been destroyed. This seems +/// like an inevitable consequence of the fact that ASIO allows for multiple +/// threads to execute the event loop concurrently. This generally forces ASIO +/// applications to invent ways of extending the lifetime of deadline timer and +/// socket objects until the completion handler starts executing. +/// +/// IMPORTANT: Even if ASIO is used in a way where at most one thread executes +/// the event loop, there is still no guarantee that an asynchronous operation +/// remains cancelable up until the point in time where the completion handler +/// starts to execute. +namespace network { + +std::string host_name(); + + +class StreamProtocol; +class Address; +class Endpoint; +class Service; +class Resolver; +class SocketBase; +class Socket; +class Acceptor; +class DeadlineTimer; +class Trigger; +class ReadAheadBuffer; +namespace ssl { +class Stream; +} // namespace ssl + + +/// \brief An IP protocol descriptor. +class StreamProtocol { +public: + static StreamProtocol ip_v4(); + static StreamProtocol ip_v6(); + + bool is_ip_v4() const; + bool is_ip_v6() const; + + int protocol() const; + int family() const; + + StreamProtocol(); + ~StreamProtocol() noexcept {} + +private: + int m_family; + int m_socktype; + int m_protocol; + + friend class Service; + friend class SocketBase; +}; + + +/// \brief An IP address (IPv4 or IPv6). +class Address { +public: + bool is_ip_v4() const; + bool is_ip_v6() const; + + template + friend std::basic_ostream& operator<<(std::basic_ostream&, const Address&); + + Address(); + ~Address() noexcept {} + +private: + using ip_v4_type = in_addr; + using ip_v6_type = in6_addr; + union union_type { + ip_v4_type m_ip_v4; + ip_v6_type m_ip_v6; + }; + union_type m_union; + std::uint_least32_t m_ip_v6_scope_id = 0; + bool m_is_ip_v6 = false; + + friend Address make_address(const char*, std::error_code&) noexcept; + friend class Endpoint; +}; + +Address make_address(const char* c_str); +Address make_address(const char* c_str, std::error_code& ec) noexcept; +Address make_address(const std::string&); +Address make_address(const std::string&, std::error_code& ec) noexcept; + + +/// \brief An IP endpoint. +/// +/// An IP endpoint is a triplet (`protocol`, `address`, `port`). +class Endpoint { +public: + using port_type = std::uint_fast16_t; + class List; + + StreamProtocol protocol() const; + Address address() const; + port_type port() const; + + Endpoint(); + Endpoint(const StreamProtocol&, port_type); + Endpoint(const Address&, port_type); + ~Endpoint() noexcept {} + + using data_type = sockaddr; + data_type* data(); + const data_type* data() const; + +private: + StreamProtocol m_protocol; + + using sockaddr_base_type = sockaddr; + using sockaddr_ip_v4_type = sockaddr_in; + using sockaddr_ip_v6_type = sockaddr_in6; + union sockaddr_union_type { + sockaddr_base_type m_base; + sockaddr_ip_v4_type m_ip_v4; + sockaddr_ip_v6_type m_ip_v6; + }; + sockaddr_union_type m_sockaddr_union; + + friend class Service; + friend class Resolver; + friend class SocketBase; + friend class Socket; +}; + + +/// \brief A list of IP endpoints. +class Endpoint::List { +public: + using iterator = const Endpoint*; + + iterator begin() const noexcept; + iterator end() const noexcept; + std::size_t size() const noexcept; + bool empty() const noexcept; + + List() noexcept = default; + List(List&&) noexcept = default; + ~List() noexcept = default; + + List& operator=(List&&) noexcept = default; + +private: + Buffer m_endpoints; + + friend class Service; +}; + + +/// \brief TCP/IP networking service. +class Service { +public: + Service(); + ~Service() noexcept; + + /// \brief Execute the event loop. + /// + /// Execute completion handlers of completed asynchronous operations, or + /// wait for more completion handlers to become ready for + /// execution. Handlers submitted via post() are considered immeditely + /// ready. If there are no completion handlers ready for execution, and + /// there are no asynchronous operations in progress, run() returns. + /// + /// All completion handlers, including handlers submitted via post() will be + /// executed from run(), that is, by the thread that executes run(). If no + /// thread executes run(), then the completion handlers will not be + /// executed. + /// + /// Exceptions thrown by completion handlers will always propagate back + /// through run(). + /// + /// Syncronous operations (e.g., Socket::connect()) execute independently of + /// the event loop, and do not require that any thread calls run(). + void run(); + + /// @{ \brief Stop event loop execution. + /// + /// stop() puts the event loop into the stopped mode. If a thread is + /// currently executing run(), it will be made to return in a timely + /// fashion, that is, without further blocking. If a thread is currently + /// blocked in run(), it will be unblocked. Handlers that can be executed + /// immediately, may, or may not be executed before run() returns, but new + /// handlers submitted by these, will not be executed before run() + /// returns. Also, if a handler is submitted by a call to post, and that + /// call happens after stop() returns, then that handler is guaranteed to + /// not be executed before run() returns (assuming that reset() is not called + /// before run() returns). + /// + /// The event loop will remain in the stopped mode until reset() is + /// called. If reset() is called before run() returns, it may, or may not + /// cause run() to resume normal operation without returning. + /// + /// Both stop() and reset() are thread-safe, that is, they may be called by + /// any thread. Also, both of these function may be called from completion + /// handlers (including posted handlers). + void stop() noexcept; + void reset() noexcept; + /// @} + + /// \brief Submit a handler to be executed by the event loop thread. + /// + /// Register the sepcified completion handler for immediate asynchronous + /// execution. The specified handler will be executed by an expression on + /// the form `handler()`. If the the handler object is movable, it will + /// never be copied. Otherwise, it will be copied as necessary. + /// + /// This function is thread-safe, that is, it may be called by any + /// thread. It may also be called from other completion handlers. + /// + /// The handler will never be called as part of the execution of post(). It + /// will always be called by a thread that is executing run(). If no thread + /// is currently executing run(), the handler will not be executed until a + /// thread starts executing run(). If post() is called while another thread + /// is executing run(), the handler may be called before post() returns. If + /// post() is called from another completion handler, the submitted handler + /// is guaranteed to not be called during the execution of post(). + /// + /// Completion handlers added through post() will be executed in the order + /// that they are added. More precisely, if post() is called twice to add + /// two handlers, A and B, and the execution of post(A) ends before the + /// beginning of the execution of post(B), then A is guaranteed to execute + /// before B. + template void post(H handler); + + /// Argument `saturation` is the fraction of time that is not spent + /// sleeping. Argument `inefficiency` is the fraction of time not spent + /// sleeping, and not spent executing completion handlers. Both values are + /// guaranteed to always be in the range 0 to 1 (both inclusive). The value + /// passed as `inefficiency` is guaranteed to always be less than, or equal + /// to the value passed as `saturation`. + using EventLoopMetricsHandler = void(double saturation, double inefficiency); + + /// \brief Report event loop metrics via the specified handler. + /// + /// The handler will be called approximately every 30 seconds. + /// + /// report_event_loop_metrics() must be called prior to any invocation of + /// run(). report_event_loop_metrics() is not thread-safe. + /// + /// This feature is only available if + /// `REALM_UTIL_NETWORK_EVENT_LOOP_METRICS` was defined during + /// compilation. When the feature is not available, the specified handler + /// will never be called. + void report_event_loop_metrics(std::function); + +private: + enum class Want { nothing = 0, read, write }; + + template class OperQueue; + class Descriptor; + class AsyncOper; + class ResolveOperBase; + class WaitOperBase; + class TriggerExecOperBase; + class PostOperBase; + template class PostOper; + class IoOper; + class UnusedOper; // Allocated, but currently unused memory + + template class BasicStreamOps; + + struct OwnersOperDeleter { + void operator()(AsyncOper*) const noexcept; + }; + struct LendersOperDeleter { + void operator()(AsyncOper*) const noexcept; + }; + using OwnersOperPtr = std::unique_ptr; + using LendersOperPtr = std::unique_ptr; + using LendersResolveOperPtr = std::unique_ptr; + using LendersWaitOperPtr = std::unique_ptr; + using LendersIoOperPtr = std::unique_ptr; + + class IoReactor; + class Impl; + const std::unique_ptr m_impl; + + template + static std::unique_ptr alloc(OwnersOperPtr&, Args&&...); + + using PostOperConstr = PostOperBase*(void* addr, std::size_t size, Impl&, void* cookie); + void do_post(PostOperConstr, std::size_t size, void* cookie); + template + static PostOperBase* post_oper_constr(void* addr, std::size_t size, Impl&, void* cookie); + static void recycle_post_oper(Impl&, PostOperBase*) noexcept; + static void trigger_exec(Impl&, TriggerExecOperBase&) noexcept; + static void reset_trigger_exec(Impl&, TriggerExecOperBase&) noexcept; + + using clock = std::chrono::steady_clock; + + friend class Resolver; + friend class SocketBase; + friend class Socket; + friend class Acceptor; + friend class DeadlineTimer; + friend class Trigger; + friend class ReadAheadBuffer; + friend class ssl::Stream; +}; + + +template class Service::OperQueue { +public: + using LendersOperPtr = std::unique_ptr; + bool empty() const noexcept; + void push_back(LendersOperPtr) noexcept; + template void push_back(OperQueue&) noexcept; + LendersOperPtr pop_front() noexcept; + void clear() noexcept; + OperQueue() noexcept = default; + OperQueue(OperQueue&&) noexcept; + ~OperQueue() noexcept; +private: + Oper* m_back = nullptr; + template friend class OperQueue; +}; + + +class Service::Descriptor { +public: +#ifdef _WIN32 + using native_handle_type = SOCKET; +#else + using native_handle_type = int; +#endif + + Impl& service_impl; + + Descriptor(Impl& service) noexcept; + ~Descriptor() noexcept; + + /// \param in_blocking_mode Must be true if, and only if the passed file + /// descriptor refers to a file description in which the file status flag + /// O_NONBLOCK is not set. + /// + /// The passed file descriptor must have the file descriptor flag FD_CLOEXEC + /// set. + void assign(native_handle_type fd, bool in_blocking_mode) noexcept; + void close() noexcept; + native_handle_type release() noexcept; + + bool is_open() const noexcept; + + native_handle_type native_handle() const noexcept; + bool in_blocking_mode() const noexcept; + + void accept(Descriptor&, StreamProtocol, Endpoint*, std::error_code&) noexcept; + std::size_t read_some(char* buffer, std::size_t size, std::error_code&) noexcept; + std::size_t write_some(const char* data, std::size_t size, std::error_code&) noexcept; + + /// \tparam Oper An operation type inherited from IoOper with an initate() + /// function that initiates the operation and figures out whether it needs + /// to read from, or write to the underlying descriptor to + /// proceed. `initiate()` must return Want::read if the operation needs to + /// read, or Want::write if the operation needs to write. If the operation + /// completes immediately (e.g. due to a failure during initialization), + /// `initiate()` must return Want::nothing. + template + void initiate_oper(std::unique_ptr, Args&&...); + + void ensure_blocking_mode(); + void ensure_nonblocking_mode(); + +private: + native_handle_type m_fd = -1; + bool m_in_blocking_mode; // Not in nonblocking mode + +#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE + bool m_read_ready; + bool m_write_ready; + bool m_imminent_end_of_input; // Kernel has seen the end of input + bool m_is_registered; + OperQueue m_suspended_read_ops, m_suspended_write_ops; + + void deregister_for_async() noexcept; +#endif + + bool assume_read_would_block() const noexcept; + bool assume_write_would_block() const noexcept; + + void set_read_ready(bool) noexcept; + void set_write_ready(bool) noexcept; + + void set_nonblock_flag(bool value); + void add_initiated_oper(LendersIoOperPtr, Want); + + void do_close() noexcept; + native_handle_type do_release() noexcept; + + friend class IoReactor; +}; + + +class Resolver { +public: + class Query; + + Resolver(Service&); + ~Resolver() noexcept; + + /// Thread-safe. + Service& get_service() noexcept; + + /// @{ \brief Resolve the specified query to one or more endpoints. + Endpoint::List resolve(const Query&); + Endpoint::List resolve(const Query&, std::error_code&); + /// @} + + /// \brief Perform an asynchronous resolve operation. + /// + /// Initiate an asynchronous resolve operation. The completion handler will + /// be called when the operation completes. The operation completes when it + /// succeeds, or an error occurs. + /// + /// The completion handler is always executed by the event loop thread, + /// i.e., by a thread that is executing Service::run(). Conversely, the + /// completion handler is guaranteed to not be called while no thread is + /// executing Service::run(). The execution of the completion handler is + /// always deferred to the event loop, meaning that it never happens as a + /// synchronous side effect of the execution of async_resolve(), even when + /// async_resolve() is executed by the event loop thread. The completion + /// handler is guaranteed to be called eventually, as long as there is time + /// enough for the operation to complete or fail, and a thread is executing + /// Service::run() for long enough. + /// + /// The operation can be canceled by calling cancel(), and will be + /// automatically canceled if the resolver object is destroyed. If the + /// operation is canceled, it will fail with `error::operation_aborted`. The + /// operation remains cancelable up until the point in time where the + /// completion handler starts to execute. This means that if cancel() is + /// called before the completion handler starts to execute, then the + /// completion handler is guaranteed to have `error::operation_aborted` + /// passed to it. This is true regardless of whether cancel() is called + /// explicitly or implicitly, such as when the resolver is destroyed. + /// + /// The specified handler will be executed by an expression on the form + /// `handler(ec, endpoints)` where `ec` is the error code and `endpoints` is + /// an object of type `Endpoint::List`. If the the handler object is + /// movable, it will never be copied. Otherwise, it will be copied as + /// necessary. + /// + /// It is an error to start a new resolve operation (synchronous or + /// asynchronous) while an asynchronous resolve operation is in progress via + /// the same resolver object. An asynchronous resolve operation is + /// considered complete as soon as the completion handler starts to + /// execute. This means that a new resolve operation can be started from the + /// completion handler. + template void async_resolve(Query, H handler); + + /// \brief Cancel all asynchronous operations. + /// + /// Cause all incomplete asynchronous operations, that are associated with + /// this resolver (at most one), to fail with `error::operation_aborted`. An + /// asynchronous operation is complete precisely when its completion handler + /// starts executing. + /// + /// Completion handlers of canceled operations will become immediately ready + /// to execute, but will never be executed directly as part of the execution + /// of cancel(). + /// + /// Cancellation happens automatically when the resolver object is destroyed. + void cancel() noexcept; + +private: + template class ResolveOper; + + Service::Impl& m_service_impl; + + Service::OwnersOperPtr m_resolve_oper; + + void initiate_oper(Service::LendersResolveOperPtr); +}; + + +class Resolver::Query { +public: + enum { + /// Locally bound socket endpoint (server side) + passive = AI_PASSIVE, + + /// Ignore families without a configured non-loopback address + address_configured = AI_ADDRCONFIG + }; + + Query(std::string service_port, int init_flags = passive|address_configured); + Query(const StreamProtocol&, std::string service_port, + int init_flags = passive|address_configured); + Query(std::string host_name, std::string service_port, + int init_flags = address_configured); + Query(const StreamProtocol&, std::string host_name, std::string service_port, + int init_flags = address_configured); + + ~Query() noexcept; + + int flags() const; + StreamProtocol protocol() const; + std::string host() const; + std::string service() const; + +private: + int m_flags; + StreamProtocol m_protocol; + std::string m_host; // hostname + std::string m_service; // port + + friend class Service; +}; + + +class SocketBase { +public: + using native_handle_type = Service::Descriptor::native_handle_type; + + ~SocketBase() noexcept; + + /// Thread-safe. + Service& get_service() noexcept; + + bool is_open() const noexcept; + native_handle_type native_handle() const noexcept; + + /// @{ \brief Open the socket for use with the specified protocol. + /// + /// It is an error to call open() on a socket that is already open. + void open(const StreamProtocol&); + std::error_code open(const StreamProtocol&, std::error_code&); + /// @} + + /// \brief Close this socket. + /// + /// If the socket is open, it will be closed. If it is already closed (or + /// never opened), this function does nothing (idempotency). + /// + /// A socket is automatically closed when destroyed. + /// + /// When the socket is closed, any incomplete asynchronous operation will be + /// canceled (as if cancel() was called). + void close() noexcept; + + /// \brief Cancel all asynchronous operations. + /// + /// Cause all incomplete asynchronous operations, that are associated with + /// this socket, to fail with `error::operation_aborted`. An asynchronous + /// operation is complete precisely when its completion handler starts + /// executing. + /// + /// Completion handlers of canceled operations will become immediately ready + /// to execute, but will never be executed directly as part of the execution + /// of cancel(). + void cancel() noexcept; + + template + void get_option(O& opt) const; + + template + std::error_code get_option(O& opt, std::error_code&) const; + + template + void set_option(const O& opt); + + template + std::error_code set_option(const O& opt, std::error_code&); + + void bind(const Endpoint&); + std::error_code bind(const Endpoint&, std::error_code&); + + Endpoint local_endpoint() const; + Endpoint local_endpoint(std::error_code&) const; + + /// Release the ownership of this socket object over the native handle and + /// return the native handle to the caller. The caller assumes ownership + /// over the returned handle. The socket is left in a closed + /// state. Incomplete asynchronous operations will be canceled as if close() + /// had been called. + /// + /// If called on a closed socket, this function is a no-op, and returns the + /// same value as would be returned by native_handle() + native_handle_type release_native_handle() noexcept; + +private: + enum opt_enum { + opt_ReuseAddr, ///< `SOL_SOCKET`, `SO_REUSEADDR` + opt_Linger, ///< `SOL_SOCKET`, `SO_LINGER` + opt_NoDelay, ///< `IPPROTO_TCP`, `TCP_NODELAY` (disable the Nagle algorithm) + }; + + template class Option; + +public: + using reuse_address = Option; + using no_delay = Option; + + // linger struct defined by POSIX sys/socket.h. + struct linger_opt; + using linger = Option; + +protected: + Service::Descriptor m_desc; + +private: + StreamProtocol m_protocol; + +protected: + Service::OwnersOperPtr m_read_oper; // Read or accept + Service::OwnersOperPtr m_write_oper; // Write or connect + + SocketBase(Service&); + + const StreamProtocol& get_protocol() const noexcept; + std::error_code do_assign(const StreamProtocol&, native_handle_type, std::error_code&); + void do_close() noexcept; + + void get_option(opt_enum, void* value_data, std::size_t& value_size, std::error_code&) const; + void set_option(opt_enum, const void* value_data, std::size_t value_size, std::error_code&); + void map_option(opt_enum, int& level, int& option_name) const; + + friend class Acceptor; +}; + + +template class SocketBase::Option { +public: + Option(T value = T()); + T value() const; + +private: + T m_value; + + void get(const SocketBase&, std::error_code&); + void set(SocketBase&, std::error_code&) const; + + friend class SocketBase; +}; + +struct SocketBase::linger_opt { + linger_opt(bool enable, int timeout_seconds = 0) + { + m_linger.l_onoff = enable ? 1 : 0; + m_linger.l_linger = timeout_seconds; + } + + ::linger m_linger; + + operator ::linger() const { return m_linger; } + + bool enabled() const { return m_linger.l_onoff != 0; } + int timeout() const { return m_linger.l_linger; } +}; + + +/// Switching between synchronous and asynchronous operations is allowed, but +/// only in a nonoverlapping fashion. That is, a synchronous operation is not +/// allowed to run concurrently with an asynchronous one on the same +/// socket. Note that an asynchronous operation is considered to be running +/// until its completion handler starts executing. +class Socket : public SocketBase { +public: + Socket(Service&); + + /// \brief Create a socket with an already-connected native socket handle. + /// + /// This constructor is shorthand for creating the socket with the + /// one-argument constructor, and then calling the two-argument assign() + /// with the specified protocol and native handle. + Socket(Service&, const StreamProtocol&, native_handle_type); + + ~Socket() noexcept; + + void connect(const Endpoint&); + std::error_code connect(const Endpoint&, std::error_code&); + + /// @{ \brief Perform a synchronous read operation. + /// + /// read() will not return until the specified buffer is full, or an error + /// occurs. Reaching the end of input before the buffer is filled, is + /// considered an error, and will cause the operation to fail with + /// MiscExtErrors::end_of_input. + /// + /// read_until() will not return until the specified buffer contains the + /// specified delimiter, or an error occurs. If the buffer is filled before + /// the delimiter is found, the operation fails with + /// MiscExtErrors::delim_not_found. Otherwise, if the end of input is + /// reached before the delimiter is found, the operation fails with + /// MiscExtErrors::end_of_input. If the operation succeeds, the last byte + /// placed in the buffer is the delimiter. + /// + /// The versions that take a ReadAheadBuffer argument will read through that + /// buffer. This allows for fewer larger reads on the underlying + /// socket. Since unconsumed data may be left in the read-ahead buffer after + /// a read operation returns, it is important that the same read-ahead + /// buffer is passed to the next read operation. + /// + /// The versions of read() and read_until() that do not take an + /// `std::error_code&` argument will throw std::system_error on failure. + /// + /// The versions that do take an `std::error_code&` argument will set \a ec + /// to `std::error_code()` on success, and to something else on failure. On + /// failure they will return the number of bytes placed in the specified + /// buffer before the error occured. + /// + /// \return The number of bytes places in the specified buffer upon return. + std::size_t read(char* buffer, std::size_t size); + std::size_t read(char* buffer, std::size_t size, std::error_code& ec); + std::size_t read(char* buffer, std::size_t size, ReadAheadBuffer&); + std::size_t read(char* buffer, std::size_t size, ReadAheadBuffer&, std::error_code& ec); + std::size_t read_until(char* buffer, std::size_t size, char delim, ReadAheadBuffer&); + std::size_t read_until(char* buffer, std::size_t size, char delim, ReadAheadBuffer&, + std::error_code& ec); + /// @} + + /// @{ \brief Perform a synchronous write operation. + /// + /// write() will not return until all the specified bytes have been written + /// to the socket, or an error occurs. + /// + /// The versions of write() that does not take an `std::error_code&` + /// argument will throw std::system_error on failure. When it succeeds, it + /// always returns \a size. + /// + /// The versions that does take an `std::error_code&` argument will set \a + /// ec to `std::error_code()` on success, and to something else on + /// failure. On success it returns \a size. On faulure it returns the number + /// of bytes written before the failure occured. + std::size_t write(const char* data, std::size_t size); + std::size_t write(const char* data, std::size_t size, std::error_code& ec); + /// @} + + /// @{ \brief Read at least one byte from this socket. + /// + /// If \a size is zero, both versions of read_some() will return zero + /// without blocking. Read errors may or may not be detected in this case. + /// + /// Otherwise, if \a size is greater than zero, and at least one byte is + /// immediately available, that is, without blocking, then both versions + /// will read at least one byte (but generally as many immediately available + /// bytes as will fit into the specified buffer), and return without + /// blocking. + /// + /// Otherwise, both versions will block the calling thread until at least one + /// byte becomes available, or an error occurs. + /// + /// In this context, it counts as an error, if the end of input is reached + /// before at least one byte becomes available (see + /// MiscExtErrors::end_of_input). + /// + /// If no error occurs, both versions will return the number of bytes placed + /// in the specified buffer, which is generally as many as are immediately + /// available at the time when the first byte becomes available, although + /// never more than \a size. + /// + /// If no error occurs, the three-argument version will set \a ec to + /// indicate success. + /// + /// If an error occurs, the two-argument version will throw + /// `std::system_error`, while the three-argument version will set \a ec to + /// indicate the error, and return zero. + /// + /// As long as \a size is greater than zero, the two argument version will + /// always return a value that is greater than zero, while the three + /// argument version will return a value greater than zero when, and only + /// when \a ec is set to indicate success (no error, and no end of input). + std::size_t read_some(char* buffer, std::size_t size); + std::size_t read_some(char* buffer, std::size_t size, std::error_code& ec); + /// @} + + /// @{ \brief Write at least one byte to this socket. + /// + /// If \a size is zero, both versions of write_some() will return zero + /// without blocking. Write errors may or may not be detected in this case. + /// + /// Otherwise, if \a size is greater than zero, and at least one byte can be + /// written immediately, that is, without blocking, then both versions will + /// write at least one byte (but generally as many as can be written + /// immediately), and return without blocking. + /// + /// Otherwise, both versions will block the calling thread until at least one + /// byte can be written, or an error occurs. + /// + /// If no error occurs, both versions will return the number of bytes + /// written, which is generally as many as can be written immediately at the + /// time when the first byte can be written. + /// + /// If no error occurs, the three-argument version will set \a ec to + /// indicate success. + /// + /// If an error occurs, the two-argument version will throw + /// `std::system_error`, while the three-argument version will set \a ec to + /// indicate the error, and return zero. + /// + /// As long as \a size is greater than zero, the two argument version will + /// always return a value that is greater than zero, while the three + /// argument version will return a value greater than zero when, and only + /// when \a ec is set to indicate success. + std::size_t write_some(const char* data, std::size_t size); + std::size_t write_some(const char* data, std::size_t size, std::error_code&); + /// @} + + /// \brief Perform an asynchronous connect operation. + /// + /// Initiate an asynchronous connect operation. The completion handler is + /// called when the operation completes. The operation completes when the + /// connection is established, or an error occurs. + /// + /// The completion handler is always executed by the event loop thread, + /// i.e., by a thread that is executing Service::run(). Conversely, the + /// completion handler is guaranteed to not be called while no thread is + /// executing Service::run(). The execution of the completion handler is + /// always deferred to the event loop, meaning that it never happens as a + /// synchronous side effect of the execution of async_connect(), even when + /// async_connect() is executed by the event loop thread. The completion + /// handler is guaranteed to be called eventually, as long as there is time + /// enough for the operation to complete or fail, and a thread is executing + /// Service::run() for long enough. + /// + /// The operation can be canceled by calling cancel(), and will be + /// automatically canceled if the socket is closed. If the operation is + /// canceled, it will fail with `error::operation_aborted`. The operation + /// remains cancelable up until the point in time where the completion + /// handler starts to execute. This means that if cancel() is called before + /// the completion handler starts to execute, then the completion handler is + /// guaranteed to have `error::operation_aborted` passed to it. This is true + /// regardless of whether cancel() is called explicitly or implicitly, such + /// as when the socket is destroyed. + /// + /// If the socket is not already open, it will be opened as part of the + /// connect operation as if by calling `open(ep.protocol())`. If the opening + /// operation succeeds, but the connect operation fails, the socket will be + /// left in the opened state. + /// + /// The specified handler will be executed by an expression on the form + /// `handler(ec)` where `ec` is the error code. If the the handler object is + /// movable, it will never be copied. Otherwise, it will be copied as + /// necessary. + /// + /// It is an error to start a new connect operation (synchronous or + /// asynchronous) while an asynchronous connect operation is in progress. An + /// asynchronous connect operation is considered complete as soon as the + /// completion handler starts to execute. + /// + /// \param ep The remote endpoint of the connection to be established. + template void async_connect(const Endpoint& ep, H handler); + + /// @{ \brief Perform an asynchronous read operation. + /// + /// Initiate an asynchronous buffered read operation on the associated + /// socket. The completion handler will be called when the operation + /// completes, or an error occurs. + /// + /// async_read() will continue reading until the specified buffer is full, + /// or an error occurs. If the end of input is reached before the buffer is + /// filled, the operation fails with MiscExtErrors::end_of_input. + /// + /// async_read_until() will continue reading until the specified buffer + /// contains the specified delimiter, or an error occurs. If the buffer is + /// filled before a delimiter is found, the operation fails with + /// MiscExtErrors::delim_not_found. Otherwise, if the end of input is + /// reached before a delimiter is found, the operation fails with + /// MiscExtErrors::end_of_input. Otherwise, if the operation succeeds, the + /// last byte placed in the buffer is the delimiter. + /// + /// The versions that take a ReadAheadBuffer argument will read through that + /// buffer. This allows for fewer larger reads on the underlying + /// socket. Since unconsumed data may be left in the read-ahead buffer after + /// a read operation completes, it is important that the same read-ahead + /// buffer is passed to the next read operation. + /// + /// The completion handler is always executed by the event loop thread, + /// i.e., by a thread that is executing Service::run(). Conversely, the + /// completion handler is guaranteed to not be called while no thread is + /// executing Service::run(). The execution of the completion handler is + /// always deferred to the event loop, meaning that it never happens as a + /// synchronous side effect of the execution of async_read() or + /// async_read_until(), even when async_read() or async_read_until() is + /// executed by the event loop thread. The completion handler is guaranteed + /// to be called eventually, as long as there is time enough for the + /// operation to complete or fail, and a thread is executing Service::run() + /// for long enough. + /// + /// The operation can be canceled by calling cancel() on the associated + /// socket, and will be automatically canceled if the associated socket is + /// closed. If the operation is canceled, it will fail with + /// `error::operation_aborted`. The operation remains cancelable up until + /// the point in time where the completion handler starts to execute. This + /// means that if cancel() is called before the completion handler starts to + /// execute, then the completion handler is guaranteed to have + /// `error::operation_aborted` passed to it. This is true regardless of + /// whether cancel() is called explicitly or implicitly, such as when the + /// socket is destroyed. + /// + /// The specified handler will be executed by an expression on the form + /// `handler(ec, n)` where `ec` is the error code, and `n` is the number of + /// bytes placed in the buffer (of type `std::size_t`). `n` is guaranteed to + /// be less than, or equal to \a size. If the the handler object is movable, + /// it will never be copied. Otherwise, it will be copied as necessary. + /// + /// It is an error to start a read operation before the associated socket is + /// connected. + /// + /// It is an error to start a new read operation (synchronous or + /// asynchronous) while an asynchronous read operation is in progress. An + /// asynchronous read operation is considered complete as soon as the + /// completion handler starts executing. This means that a new read + /// operation can be started from the completion handler of another + /// asynchronous buffered read operation. + template void async_read(char* buffer, std::size_t size, H handler); + template void async_read(char* buffer, std::size_t size, ReadAheadBuffer&, H handler); + template void async_read_until(char* buffer, std::size_t size, char delim, + ReadAheadBuffer&, H handler); + /// @} + + /// \brief Perform an asynchronous write operation. + /// + /// Initiate an asynchronous write operation. The completion handler is + /// called when the operation completes. The operation completes when all + /// the specified bytes have been written to the socket, or an error occurs. + /// + /// The completion handler is always executed by the event loop thread, + /// i.e., by a thread that is executing Service::run(). Conversely, the + /// completion handler is guaranteed to not be called while no thread is + /// executing Service::run(). The execution of the completion handler is + /// always deferred to the event loop, meaning that it never happens as a + /// synchronous side effect of the execution of async_write(), even when + /// async_write() is executed by the event loop thread. The completion + /// handler is guaranteed to be called eventually, as long as there is time + /// enough for the operation to complete or fail, and a thread is executing + /// Service::run() for long enough. + /// + /// The operation can be canceled by calling cancel(), and will be + /// automatically canceled if the socket is closed. If the operation is + /// canceled, it will fail with `error::operation_aborted`. The operation + /// remains cancelable up until the point in time where the completion + /// handler starts to execute. This means that if cancel() is called before + /// the completion handler starts to execute, then the completion handler is + /// guaranteed to have `error::operation_aborted` passed to it. This is true + /// regardless of whether cancel() is called explicitly or implicitly, such + /// as when the socket is destroyed. + /// + /// The specified handler will be executed by an expression on the form + /// `handler(ec, n)` where `ec` is the error code, and `n` is the number of + /// bytes written (of type `std::size_t`). If the the handler object is + /// movable, it will never be copied. Otherwise, it will be copied as + /// necessary. + /// + /// It is an error to start an asynchronous write operation before the + /// socket is connected. + /// + /// It is an error to start a new write operation (synchronous or + /// asynchronous) while an asynchronous write operation is in progress. An + /// asynchronous write operation is considered complete as soon as the + /// completion handler starts to execute. This means that a new write + /// operation can be started from the completion handler of another + /// asynchronous write operation. + template void async_write(const char* data, std::size_t size, H handler); + + template void async_read_some(char* buffer, std::size_t size, H handler); + template void async_write_some(const char* data, std::size_t size, H handler); + + enum shutdown_type { +#ifdef _WIN32 + /// Shutdown the receiving side of the socket. + shutdown_receive = SD_RECEIVE, + + /// Shutdown the sending side of the socket. + shutdown_send = SD_SEND, + + /// Shutdown both sending and receiving side of the socket. + shutdown_both = SD_BOTH +#else + shutdown_receive = SHUT_RD, + shutdown_send = SHUT_WR, + shutdown_both = SHUT_RDWR +#endif + }; + + /// @{ \brief Shut down the connected sockets sending and/or receiving + /// side. + /// + /// It is an error to call this function when the socket is not both open + /// and connected. + void shutdown(shutdown_type); + std::error_code shutdown(shutdown_type, std::error_code&); + /// @} + + /// @{ \brief Initialize socket with an already-connected native socket + /// handle. + /// + /// The specified native handle must refer to a socket that is already fully + /// open and connected. + /// + /// If the assignment operation succeeds, this socket object has taken + /// ownership of the specified native handle, and the handle will be closed + /// when the socket object is destroyed, (or when close() is called). If the + /// operation fails, the caller still owns the specified native handle. + /// + /// It is an error to call connect() or async_connect() on a socket object + /// that is initialized this way (unless it is first closed). + /// + /// It is an error to call this function on a socket object that is already + /// open. + void assign(const StreamProtocol&, native_handle_type); + std::error_code assign(const StreamProtocol&, native_handle_type, std::error_code&); + /// @} + + /// Returns a reference to this socket, as this socket is the lowest layer + /// of a stream. + Socket& lowest_layer() noexcept; + +private: + using Want = Service::Want; + using StreamOps = Service::BasicStreamOps; + + class ConnectOperBase; + template class ConnectOper; + + using LendersConnectOperPtr = std::unique_ptr; + + // `ec` untouched on success, but no immediate completion + bool initiate_async_connect(const Endpoint&, std::error_code& ec); + // `ec` untouched on success + std::error_code finalize_async_connect(std::error_code& ec) noexcept; + + // See Service::BasicStreamOps for details on these these 6 functions. + void do_init_read_async(std::error_code&, Want&) noexcept; + void do_init_write_async(std::error_code&, Want&) noexcept; + std::size_t do_read_some_sync(char* buffer, std::size_t size, + std::error_code&) noexcept; + std::size_t do_write_some_sync(const char* data, std::size_t size, + std::error_code&) noexcept; + std::size_t do_read_some_async(char* buffer, std::size_t size, + std::error_code&, Want&) noexcept; + std::size_t do_write_some_async(const char* data, std::size_t size, + std::error_code&, Want&) noexcept; + + friend class Service::BasicStreamOps; + friend class Service::BasicStreamOps; + friend class ReadAheadBuffer; + friend class ssl::Stream; +}; + + +/// Switching between synchronous and asynchronous operations is allowed, but +/// only in a nonoverlapping fashion. That is, a synchronous operation is not +/// allowed to run concurrently with an asynchronous one on the same +/// acceptor. Note that an asynchronous operation is considered to be running +/// until its completion handler starts executing. +class Acceptor : public SocketBase { +public: + Acceptor(Service&); + ~Acceptor() noexcept; + + static constexpr int max_connections = SOMAXCONN; + + void listen(int backlog = max_connections); + std::error_code listen(int backlog, std::error_code&); + + void accept(Socket&); + void accept(Socket&, Endpoint&); + std::error_code accept(Socket&, std::error_code&); + std::error_code accept(Socket&, Endpoint&, std::error_code&); + + /// @{ \brief Perform an asynchronous accept operation. + /// + /// Initiate an asynchronous accept operation. The completion handler will + /// be called when the operation completes. The operation completes when the + /// connection is accepted, or an error occurs. If the operation succeeds, + /// the specified local socket will have become connected to a remote + /// socket. + /// + /// The completion handler is always executed by the event loop thread, + /// i.e., by a thread that is executing Service::run(). Conversely, the + /// completion handler is guaranteed to not be called while no thread is + /// executing Service::run(). The execution of the completion handler is + /// always deferred to the event loop, meaning that it never happens as a + /// synchronous side effect of the execution of async_accept(), even when + /// async_accept() is executed by the event loop thread. The completion + /// handler is guaranteed to be called eventually, as long as there is time + /// enough for the operation to complete or fail, and a thread is executing + /// Service::run() for long enough. + /// + /// The operation can be canceled by calling cancel(), and will be + /// automatically canceled if the acceptor is closed. If the operation is + /// canceled, it will fail with `error::operation_aborted`. The operation + /// remains cancelable up until the point in time where the completion + /// handler starts to execute. This means that if cancel() is called before + /// the completion handler starts to execute, then the completion handler is + /// guaranteed to have `error::operation_aborted` passed to it. This is true + /// regardless of whether cancel() is called explicitly or implicitly, such + /// as when the acceptor is destroyed. + /// + /// The specified handler will be executed by an expression on the form + /// `handler(ec)` where `ec` is the error code. If the the handler object is + /// movable, it will never be copied. Otherwise, it will be copied as + /// necessary. + /// + /// It is an error to start a new accept operation (synchronous or + /// asynchronous) while an asynchronous accept operation is in progress. An + /// asynchronous accept operation is considered complete as soon as the + /// completion handler starts executing. This means that a new accept + /// operation can be started from the completion handler. + /// + /// \param sock This is the local socket, that upon successful completion + /// will have become connected to the remote socket. It must be in the + /// closed state (Socket::is_open()) when async_accept() is called. + /// + /// \param ep Upon completion, the remote peer endpoint will have been + /// assigned to this variable. + template void async_accept(Socket& sock, H handler); + template void async_accept(Socket& sock, Endpoint& ep, H handler); + /// @} + +private: + using Want = Service::Want; + + class AcceptOperBase; + template class AcceptOper; + + using LendersAcceptOperPtr = std::unique_ptr; + + std::error_code accept(Socket&, Endpoint*, std::error_code&); + Want do_accept_async(Socket&, Endpoint*, std::error_code&) noexcept; + + template void async_accept(Socket&, Endpoint*, H); +}; + + +/// \brief A timer object supporting asynchronous wait operations. +class DeadlineTimer { +public: + DeadlineTimer(Service&); + ~DeadlineTimer() noexcept; + + /// Thread-safe. + Service& get_service() noexcept; + + /// \brief Perform an asynchronous wait operation. + /// + /// Initiate an asynchronous wait operation. The completion handler becomes + /// ready to execute when the expiration time is reached, or an error occurs + /// (cancellation counts as an error here). The expiration time is the time + /// of initiation plus the specified delay. The error code passed to the + /// complition handler will **never** indicate success, unless the + /// expiration time was reached. + /// + /// The completion handler is always executed by the event loop thread, + /// i.e., by a thread that is executing Service::run(). Conversely, the + /// completion handler is guaranteed to not be called while no thread is + /// executing Service::run(). The execution of the completion handler is + /// always deferred to the event loop, meaning that it never happens as a + /// synchronous side effect of the execution of async_wait(), even when + /// async_wait() is executed by the event loop thread. The completion + /// handler is guaranteed to be called eventually, as long as there is time + /// enough for the operation to complete or fail, and a thread is executing + /// Service::run() for long enough. + /// + /// The operation can be canceled by calling cancel(), and will be + /// automatically canceled if the timer is destroyed. If the operation is + /// canceled, it will fail with `error::operation_aborted`. The operation + /// remains cancelable up until the point in time where the completion + /// handler starts to execute. This means that if cancel() is called before + /// the completion handler starts to execute, then the completion handler is + /// guaranteed to have `error::operation_aborted` passed to it. This is true + /// regardless of whether cancel() is called explicitly or implicitly, such + /// as when the timer is destroyed. + /// + /// The specified handler will be executed by an expression on the form + /// `handler(ec)` where `ec` is the error code. If the the handler object is + /// movable, it will never be copied. Otherwise, it will be copied as + /// necessary. + /// + /// It is an error to start a new asynchronous wait operation while an + /// another one is in progress. An asynchronous wait operation is in + /// progress until its completion handler starts executing. + template + void async_wait(std::chrono::duration delay, H handler); + + /// \brief Cancel an asynchronous wait operation. + /// + /// If an asynchronous wait operation, that is associated with this deadline + /// timer, is in progress, cause it to fail with + /// `error::operation_aborted`. An asynchronous wait operation is in + /// progress until its completion handler starts executing. + /// + /// Completion handlers of canceled operations will become immediately ready + /// to execute, but will never be executed directly as part of the execution + /// of cancel(). + /// + /// Cancellation happens automatically when the timer object is destroyed. + void cancel() noexcept; + +private: + template class WaitOper; + + using clock = Service::clock; + + Service::Impl& m_service_impl; + Service::OwnersOperPtr m_wait_oper; + + void initiate_oper(Service::LendersWaitOperPtr); +}; + + +/// \brief Register a function whose invocation can be triggered repeatedly. +/// +/// While the function is always executed by the event loop thread, the +/// triggering of its execution can be done by any thread, and the triggering +/// operation is guaranteed to never throw. +/// +/// The function is guaranteed to not be called after the Trigger object is +/// destroyed. It is safe, though, to destroy the Trigger object during the +/// execution of the function. +/// +/// Note that even though the trigger() function is thread-safe, the Trigger +/// object, as a whole, is not. In particular, construction and destruction must +/// not be considered thread-safe. +/// +/// ### Relation to post() +/// +/// For a particular execution of trigger() and a particular invocation of +/// Service::post(), if the execution of trigger() ends before the execution of +/// Service::post() begins, then it is guaranteed that the function associated +/// with the trigger gets to execute at least once after the execution of +/// trigger() begins, and before the post handler gets to execute. +class Trigger { +public: + template Trigger(Service&, F func); + ~Trigger() noexcept; + + Trigger() noexcept = default; + Trigger(Trigger&&) noexcept = default; + Trigger& operator=(Trigger&&) noexcept = default; + + /// \brief Trigger another invocation of the associated function. + /// + /// An invocation of trigger() puts the Trigger object into the triggered + /// state. It remains in the triggered state until shortly before the + /// function starts to execute. While the Trigger object is in the triggered + /// state, trigger() has no effect. This means that the number of executions + /// of the function will generally be less that the number of times + /// trigger() is invoked(). + /// + /// A particular invocation of trigger() ensures that there will be at least + /// one invocation of the associated function whose execution begins after + /// the beginning of the execution of trigger(), so long as the event loop + /// thread does not exit prematurely from run(). + /// + /// If trigger() is invoked from the event loop thread, the next execution + /// of the associated function will not begin until after trigger returns(), + /// effectively preventing reentrancy for the associated function. + /// + /// If trigger() is invoked from another thread, the associated function may + /// start to execute before trigger() returns. + /// + /// Note that the associated function can retrigger itself, i.e., if the + /// associated function calls trigger(), then that will lead to another + /// invocation of the associated function, but not until the first + /// invocation ends (no reentrance). + /// + /// This function is thread-safe. + void trigger() noexcept; + +private: + template class ExecOper; + + util::bind_ptr m_exec_oper; +}; + + +class ReadAheadBuffer { +public: + ReadAheadBuffer(); + + /// Discard any buffered data. + void clear() noexcept; + +private: + using Want = Service::Want; + + char* m_begin = nullptr; + char* m_end = nullptr; + static constexpr std::size_t s_size = 1024; + const std::unique_ptr m_buffer; + + bool empty() const noexcept; + bool read(char*& begin, char* end, int delim, std::error_code&) noexcept; + template void refill_sync(S& stream, std::error_code&) noexcept; + template bool refill_async(S& stream, std::error_code&, Want&) noexcept; + + template friend class Service::BasicStreamOps; +}; + + +enum class ResolveErrors { + /// Host not found (authoritative). + host_not_found = 1, + + /// Host not found (non-authoritative). + host_not_found_try_again, + + /// The query is valid but does not have associated address data. + no_data, + + /// A non-recoverable error occurred. + no_recovery, + + /// The service is not supported for the given socket type. + service_not_found, + + /// The socket type is not supported. + socket_type_not_supported +}; + +class ResolveErrorCategory : public std::error_category { +public: + const char* name() const noexcept override final; + std::string message(int) const override final; +}; + +/// The error category associated with ResolveErrors. The name of this category is +/// `realm.util.network.resolve`. +extern ResolveErrorCategory resolve_error_category; + +inline std::error_code make_error_code(ResolveErrors err) +{ + return std::error_code(int(err), resolve_error_category); +} + +} // namespace network +} // namespace util +} // namespace realm + +namespace std { + +template<> class is_error_code_enum { +public: + static const bool value = true; +}; + +} // namespace std + +namespace realm { +namespace util { +namespace network { + + + + + +// Implementation + +// ---------------- StreamProtocol ---------------- + +inline StreamProtocol StreamProtocol::ip_v4() +{ + StreamProtocol prot; + prot.m_family = AF_INET; + return prot; +} + +inline StreamProtocol StreamProtocol::ip_v6() +{ + StreamProtocol prot; + prot.m_family = AF_INET6; + return prot; +} + +inline bool StreamProtocol::is_ip_v4() const +{ + return m_family == AF_INET; +} + +inline bool StreamProtocol::is_ip_v6() const +{ + return m_family == AF_INET6; +} + +inline int StreamProtocol::family() const +{ + return m_family; +} + +inline int StreamProtocol::protocol() const +{ + return m_protocol; +} + +inline StreamProtocol::StreamProtocol() : + m_family{AF_UNSPEC}, // Allow both IPv4 and IPv6 + m_socktype{SOCK_STREAM}, // Or SOCK_DGRAM for UDP + m_protocol{0} // Any protocol +{ +} + +// ---------------- Address ---------------- + +inline bool Address::is_ip_v4() const +{ + return !m_is_ip_v6; +} + +inline bool Address::is_ip_v6() const +{ + return m_is_ip_v6; +} + +template +inline std::basic_ostream& operator<<(std::basic_ostream& out, const Address& addr) +{ + // FIXME: Not taking `addr.m_ip_v6_scope_id` into account. What does ASIO + // do? + union buffer_union { + char ip_v4[INET_ADDRSTRLEN]; + char ip_v6[INET6_ADDRSTRLEN]; + }; + char buffer[sizeof (buffer_union)]; + int af = addr.m_is_ip_v6 ? AF_INET6 : AF_INET; +#ifdef _WIN32 + void* src = const_cast(reinterpret_cast(&addr.m_union)); +#else + const void* src = &addr.m_union; +#endif + const char* ret = ::inet_ntop(af, src, buffer, sizeof buffer); + if (ret == 0) { + std::error_code ec = make_basic_system_error_code(errno); + throw std::system_error(ec); + } + out << ret; + return out; +} + +inline Address::Address() +{ + m_union.m_ip_v4 = ip_v4_type(); +} + +inline Address make_address(const char* c_str) +{ + std::error_code ec; + Address addr = make_address(c_str, ec); + if (ec) + throw std::system_error(ec); + return addr; +} + +inline Address make_address(const std::string& str) +{ + std::error_code ec; + Address addr = make_address(str, ec); + if (ec) + throw std::system_error(ec); + return addr; +} + +inline Address make_address(const std::string& str, std::error_code& ec) noexcept +{ + return make_address(str.c_str(), ec); +} + +// ---------------- Endpoint ---------------- + +inline StreamProtocol Endpoint::protocol() const +{ + return m_protocol; +} + +inline Address Endpoint::address() const +{ + Address addr; + if (m_protocol.is_ip_v4()) { + addr.m_union.m_ip_v4 = m_sockaddr_union.m_ip_v4.sin_addr; + } + else { + addr.m_union.m_ip_v6 = m_sockaddr_union.m_ip_v6.sin6_addr; + addr.m_ip_v6_scope_id = m_sockaddr_union.m_ip_v6.sin6_scope_id; + addr.m_is_ip_v6 = true; + } + return addr; +} + +inline Endpoint::port_type Endpoint::port() const +{ + return ntohs(m_protocol.is_ip_v4() ? m_sockaddr_union.m_ip_v4.sin_port : + m_sockaddr_union.m_ip_v6.sin6_port); +} + +inline Endpoint::data_type* Endpoint::data() +{ + return &m_sockaddr_union.m_base; +} + +inline const Endpoint::data_type* Endpoint::data() const +{ + return &m_sockaddr_union.m_base; +} + +inline Endpoint::Endpoint() : + Endpoint{StreamProtocol::ip_v4(), 0} +{ +} + +inline Endpoint::Endpoint(const StreamProtocol& protocol, port_type port) : + m_protocol{protocol} +{ + int family = m_protocol.family(); + if (family == AF_INET) { + m_sockaddr_union.m_ip_v4 = sockaddr_ip_v4_type(); // Clear + m_sockaddr_union.m_ip_v4.sin_family = AF_INET; + m_sockaddr_union.m_ip_v4.sin_port = htons(port); + m_sockaddr_union.m_ip_v4.sin_addr.s_addr = INADDR_ANY; + } + else if (family == AF_INET6) { + m_sockaddr_union.m_ip_v6 = sockaddr_ip_v6_type(); // Clear + m_sockaddr_union.m_ip_v6.sin6_family = AF_INET6; + m_sockaddr_union.m_ip_v6.sin6_port = htons(port); + } + else { + m_sockaddr_union.m_ip_v4 = sockaddr_ip_v4_type(); // Clear + m_sockaddr_union.m_ip_v4.sin_family = AF_UNSPEC; + m_sockaddr_union.m_ip_v4.sin_port = htons(port); + m_sockaddr_union.m_ip_v4.sin_addr.s_addr = INADDR_ANY; + } +} + +inline Endpoint::Endpoint(const Address& addr, port_type port) +{ + if (addr.m_is_ip_v6) { + m_protocol = StreamProtocol::ip_v6(); + m_sockaddr_union.m_ip_v6.sin6_family = AF_INET6; + m_sockaddr_union.m_ip_v6.sin6_port = htons(port); + m_sockaddr_union.m_ip_v6.sin6_flowinfo = 0; + m_sockaddr_union.m_ip_v6.sin6_addr = addr.m_union.m_ip_v6; + m_sockaddr_union.m_ip_v6.sin6_scope_id = addr.m_ip_v6_scope_id; + } + else { + m_protocol = StreamProtocol::ip_v4(); + m_sockaddr_union.m_ip_v4.sin_family = AF_INET; + m_sockaddr_union.m_ip_v4.sin_port = htons(port); + m_sockaddr_union.m_ip_v4.sin_addr = addr.m_union.m_ip_v4; + } +} + +inline Endpoint::List::iterator Endpoint::List::begin() const noexcept +{ + return m_endpoints.data(); +} + +inline Endpoint::List::iterator Endpoint::List::end() const noexcept +{ + return m_endpoints.data() + m_endpoints.size(); +} + +inline std::size_t Endpoint::List::size() const noexcept +{ + return m_endpoints.size(); +} + +inline bool Endpoint::List::empty() const noexcept +{ + return m_endpoints.size() == 0; +} + +// ---------------- Service::OperQueue ---------------- + +template inline bool Service::OperQueue::empty() const noexcept +{ + return !m_back; +} + +template inline void Service::OperQueue::push_back(LendersOperPtr op) noexcept +{ + REALM_ASSERT(!op->m_next); + if (m_back) { + op->m_next = m_back->m_next; + m_back->m_next = op.get(); + } + else { + op->m_next = op.get(); + } + m_back = op.release(); +} + +template template +inline void Service::OperQueue::push_back(OperQueue& q) noexcept +{ + if (!q.m_back) + return; + if (m_back) + std::swap(m_back->m_next, q.m_back->m_next); + m_back = q.m_back; + q.m_back = nullptr; +} + +template inline auto Service::OperQueue::pop_front() noexcept -> LendersOperPtr +{ + Oper* op = nullptr; + if (m_back) { + op = static_cast(m_back->m_next); + if (op != m_back) { + m_back->m_next = op->m_next; + } + else { + m_back = nullptr; + } + op->m_next = nullptr; + } + return LendersOperPtr(op); +} + +template inline void Service::OperQueue::clear() noexcept +{ + if (m_back) { + LendersOperPtr op(m_back); + while (op->m_next != m_back) + op.reset(static_cast(op->m_next)); + m_back = nullptr; + } +} + +template inline Service::OperQueue::OperQueue(OperQueue&& q) noexcept : + m_back{q.m_back} +{ + q.m_back = nullptr; +} + +template inline Service::OperQueue::~OperQueue() noexcept +{ + clear(); +} + +// ---------------- Service::Descriptor ---------------- + +inline Service::Descriptor::Descriptor(Impl& s) noexcept : + service_impl{s} +{ +} + +inline Service::Descriptor::~Descriptor() noexcept +{ + if (is_open()) + close(); +} + +inline void Service::Descriptor::assign(native_handle_type fd, bool in_blocking_mode) noexcept +{ + REALM_ASSERT(!is_open()); + m_fd = fd; + m_in_blocking_mode = in_blocking_mode; +#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE + m_read_ready = false; + m_write_ready = false; + m_imminent_end_of_input = false; + m_is_registered = false; +#endif +} + +inline void Service::Descriptor::close() noexcept +{ + REALM_ASSERT(is_open()); +#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE + if (m_is_registered) + deregister_for_async(); + m_is_registered = false; +#endif + do_close(); +} + +inline auto Service::Descriptor::release() noexcept -> native_handle_type +{ + REALM_ASSERT(is_open()); +#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE + if (m_is_registered) + deregister_for_async(); + m_is_registered = false; +#endif + return do_release(); +} + +inline bool Service::Descriptor::is_open() const noexcept +{ + return (m_fd != -1); +} + +inline auto Service::Descriptor::native_handle() const noexcept -> native_handle_type +{ + return m_fd; +} + +inline bool Service::Descriptor::in_blocking_mode() const noexcept +{ + return m_in_blocking_mode; +} + +template +inline void Service::Descriptor::initiate_oper(std::unique_ptr op, + Args&&... args) +{ + Service::Want want = op->initiate(std::forward(args)...); // Throws + add_initiated_oper(std::move(op), want); // Throws +} + +inline void Service::Descriptor::ensure_blocking_mode() +{ + // Assuming that descriptors are either used mostly in blocking mode, or + // mostly in nonblocking mode. + if (REALM_UNLIKELY(!m_in_blocking_mode)) { + bool value = false; + set_nonblock_flag(value); // Throws + m_in_blocking_mode = true; + } +} + +inline void Service::Descriptor::ensure_nonblocking_mode() +{ + // Assuming that descriptors are either used mostly in blocking mode, or + // mostly in nonblocking mode. + if (REALM_UNLIKELY(m_in_blocking_mode)) { + bool value = true; + set_nonblock_flag(value); // Throws + m_in_blocking_mode = false; + } +} + +inline bool Service::Descriptor::assume_read_would_block() const noexcept +{ +#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE + return !m_in_blocking_mode && !m_read_ready; +#else + return false; +#endif +} + +inline bool Service::Descriptor::assume_write_would_block() const noexcept +{ +#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE + return !m_in_blocking_mode && !m_write_ready; +#else + return false; +#endif +} + +inline void Service::Descriptor::set_read_ready(bool value) noexcept +{ +#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE + m_read_ready = value; +#else + // No-op + static_cast(value); +#endif +} + +inline void Service::Descriptor::set_write_ready(bool value) noexcept +{ +#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE + m_write_ready = value; +#else + // No-op + static_cast(value); +#endif +} + +// ---------------- Service ---------------- + +class Service::AsyncOper { +public: + bool in_use() const noexcept; + bool is_complete() const noexcept; + bool is_canceled() const noexcept; + void cancel() noexcept; + /// Every object of type \ref AsyncOper must be destroyed either by a call + /// to this function or to recycle(). This function recycles the operation + /// object (commits suicide), even if it throws. + virtual void recycle_and_execute() = 0; + /// Every object of type \ref AsyncOper must be destroyed either by a call + /// to recycle_and_execute() or to this function. This function destroys the + /// object (commits suicide). + virtual void recycle() noexcept = 0; + /// Must be called when the owner dies, and the object is in use (not an + /// instance of UnusedOper). + virtual void orphan() noexcept = 0; +protected: + AsyncOper(std::size_t size, bool in_use) noexcept; + virtual ~AsyncOper() noexcept {} + void set_is_complete(bool value) noexcept; + template + void do_recycle_and_execute(bool orphaned, H& handler, Args&&...); + void do_recycle(bool orphaned) noexcept; +private: + std::size_t m_size; // Allocated number of bytes + bool m_in_use = false; + // Set to true when the operation completes successfully or fails. If the + // operation is canceled before this happens, it will never be set to + // true. Always false when not in use + bool m_complete = false; + // Set to true when the operation is canceled. Always false when not in use. + bool m_canceled = false; + AsyncOper* m_next = nullptr; // Always null when not in use + template + void do_recycle_and_execute_helper(bool orphaned, bool& was_recycled, H handler, Args...); + friend class Service; +}; + +class Service::ResolveOperBase : public AsyncOper { +public: + ResolveOperBase(std::size_t size, Resolver& resolver, Resolver::Query query) noexcept : + AsyncOper{size, true}, + m_resolver{&resolver}, + m_query{std::move(query)} + { + } + void complete() noexcept + { + set_is_complete(true); + } + void recycle() noexcept override final + { + bool orphaned = !m_resolver; + REALM_ASSERT(orphaned); + // Note: do_recycle() commits suicide. + do_recycle(orphaned); + } + void orphan() noexcept override final + { + m_resolver = nullptr; + } +protected: + Resolver* m_resolver; + Resolver::Query m_query; + Endpoint::List m_endpoints; + std::error_code m_error_code; + friend class Service; +}; + +class Service::WaitOperBase : public AsyncOper { +public: + WaitOperBase(std::size_t size, DeadlineTimer& timer, + clock::time_point expiration_time) noexcept : + AsyncOper{size, true}, // Second argument is `in_use` + m_timer{&timer}, + m_expiration_time{expiration_time} + { + } + void complete() noexcept + { + set_is_complete(true); + } + void recycle() noexcept override final + { + bool orphaned = !m_timer; + REALM_ASSERT(orphaned); + // Note: do_recycle() commits suicide. + do_recycle(orphaned); + } + void orphan() noexcept override final + { + m_timer = nullptr; + } +protected: + DeadlineTimer* m_timer; + clock::time_point m_expiration_time; + friend class Service; +}; + +class Service::TriggerExecOperBase : public AsyncOper, public AtomicRefCountBase { +public: + TriggerExecOperBase(Impl& service) noexcept : + AsyncOper{0, false}, // First arg is `size` (unused), second arg is `in_use` + m_service{&service} + { + } + void recycle() noexcept override final + { + REALM_ASSERT(in_use()); + REALM_ASSERT(!m_service); + // Note: Potential suicide when `self` goes out of scope + util::bind_ptr self{this, bind_ptr_base::adopt_tag{}}; + } + void orphan() noexcept override final + { + REALM_ASSERT(m_service); + m_service = nullptr; + } + void trigger() noexcept + { + REALM_ASSERT(m_service); + Service::trigger_exec(*m_service, *this); + } +protected: + Impl* m_service; +}; + +class Service::PostOperBase : public AsyncOper { +public: + PostOperBase(std::size_t size, Impl& service) noexcept : + AsyncOper{size, true}, // Second argument is `in_use` + m_service{service} + { + } + void recycle() noexcept override final + { + // Service::recycle_post_oper() destroys this operation object + Service::recycle_post_oper(m_service, this); + } + void orphan() noexcept override final + { + REALM_ASSERT(false); // Never called + } +protected: + Impl& m_service; +}; + +template class Service::PostOper : public PostOperBase { +public: + PostOper(std::size_t size, Impl& service, H handler) : + PostOperBase{size, service}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + // Recycle the operation object before the handler is exceuted, such + // that the memory is available for a new post operation that might be + // initiated during the execution of the handler. + bool was_recycled = false; + try { + H handler = std::move(m_handler); // Throws + // Service::recycle_post_oper() destroys this operation object + Service::recycle_post_oper(m_service, this); + was_recycled = true; + handler(); // Throws + } + catch (...) { + if (!was_recycled) { + // Service::recycle_post_oper() destroys this operation object + Service::recycle_post_oper(m_service, this); + } + throw; + } + } +private: + H m_handler; +}; + +class Service::IoOper : public AsyncOper { +public: + IoOper(std::size_t size) noexcept : + AsyncOper{size, true} // Second argument is `in_use` + { + } + virtual Descriptor& descriptor() noexcept = 0; + /// Advance this operation and figure out out whether it needs to read from, + /// or write to the underlying descriptor to advance further. This function + /// must return Want::read if the operation needs to read, or Want::write if + /// the operation needs to write to advance further. If the operation + /// completes (due to success or failure), this function must return + /// Want::nothing. + virtual Want advance() noexcept = 0; +}; + +class Service::UnusedOper : public AsyncOper { +public: + UnusedOper(std::size_t size) noexcept : + AsyncOper{size, false} // Second argument is `in_use` + { + } + void recycle_and_execute() override final + { + // Must never be called + REALM_ASSERT(false); + } + void recycle() noexcept override final + { + // Must never be called + REALM_ASSERT(false); + } + void orphan() noexcept override final + { + // Must never be called + REALM_ASSERT(false); + } +}; + +// `S` must be a stream class with the following member functions: +// +// Socket& lowest_layer() noexcept; +// +// void do_init_read_async(std::error_code& ec, Want& want) noexcept; +// void do_init_write_async(std::error_code& ec, Want& want) noexcept; +// +// std::size_t do_read_some_sync(char* buffer, std::size_t size, +// std::error_code& ec) noexcept; +// std::size_t do_write_some_sync(const char* data, std::size_t size, +// std::error_code& ec) noexcept; +// std::size_t do_read_some_async(char* buffer, std::size_t size, +// std::error_code& ec, Want& want) noexcept; +// std::size_t do_write_some_async(const char* data, std::size_t size, +// std::error_code& ec, Want& want) noexcept; +// +// If an error occurs during any of these 6 functions, the `ec` argument must be +// set accordingly. Otherwise the `ec` argument must be set to +// `std::error_code()`. +// +// The do_init_*_async() functions must update the `want` argument to indicate +// how the operation must be initiated: +// +// Want::read Wait for read readiness, then call do_*_some_async(). +// Want::write Wait for write readiness, then call do_*_some_async(). +// Want::nothing Call do_*_some_async() immediately without waiting for +// read or write readiness. +// +// If end-of-input occurs while reading, do_read_some_*() must fail, set `ec` to +// MiscExtErrors::end_of_input, and return zero. +// +// If an error occurs during reading or writing, do_*_some_sync() must set `ec` +// accordingly (to something other than `std::system_error()`) and return +// zero. Otherwise they must set `ec` to `std::system_error()` and return the +// number of bytes read or written, which **must** be at least 1. If the +// underlying socket is in nonblocking mode, and no bytes could be immediately +// read or written, these functions must fail with +// `error::resource_unavailable_try_again`. +// +// If an error occurs during reading or writing, do_*_some_async() must set `ec` +// accordingly (to something other than `std::system_error()`), `want` to +// `Want::nothing`, and return zero. Otherwise they must set `ec` to +// `std::system_error()` and return the number of bytes read or written, which +// must be zero if no bytes could be immediately read or written. Note, in this +// case it is not an error if the underlying socket is in nonblocking mode, and +// no bytes could be immediately read or written. When these functions succeed, +// but return zero because no bytes could be immediately read or written, they +// must set `want` to something other than `Want::nothing`. +// +// If no error occurs, do_*_some_async() must set `want` to indicate how the +// operation should proceed if additional data needs to be read or written, or +// if no bytes were transferred: +// +// Want::read Wait for read readiness, then call do_*_some_async() again. +// Want::write Wait for write readiness, then call do_*_some_async() again. +// Want::nothing Call do_*_some_async() again without waiting for read or +// write readiness. +// +// NOTE: If, for example, do_read_some_async() sets `want` to `Want::write`, it +// means that the stream needs to write data to the underlying TCP socket before +// it is able to deliver any additional data to the caller. While such a +// situation will never occur on a raw TCP socket, it can occur on an SSL stream +// (Secure Socket Layer). +// +// When do_*_some_async() returns `n`, at least one of the following conditions +// must be true: +// +// n > 0 Bytes were transferred. +// ec != std::error_code() An error occured. +// want != Want::nothing Wait for read/write readiness. +// +// This is of critical importance, as it is the only way we can avoid falling +// into a busy loop of repeated invocations of do_*_some_async(). +// +// NOTE: do_*_some_async() are allowed to set `want` to `Want::read` or +// `Want::write`, even when they succesfully transfer a nonzero number of bytes. +template class Service::BasicStreamOps { +public: + class StreamOper; + class ReadOperBase; + class WriteOperBase; + class BufferedReadOperBase; + template class ReadOper; + template class WriteOper; + template class BufferedReadOper; + + using LendersReadOperPtr = std::unique_ptr; + using LendersWriteOperPtr = std::unique_ptr; + using LendersBufferedReadOperPtr = std::unique_ptr; + + // Synchronous read + static std::size_t read(S& stream, char* buffer, std::size_t size, + std::error_code& ec) + { + REALM_ASSERT(!stream.lowest_layer().m_read_oper || + !stream.lowest_layer().m_read_oper->in_use()); + stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws + char* begin = buffer; + char* end = buffer + size; + char* curr = begin; + for (;;) { + if (curr == end) { + ec = std::error_code(); // Success + break; + } + char* buffer_2 = curr; + std::size_t size_2 = std::size_t(end - curr); + std::size_t n = stream.do_read_some_sync(buffer_2, size_2, ec); + if (REALM_UNLIKELY(ec)) + break; + REALM_ASSERT(n > 0); + REALM_ASSERT(n <= size_2); + curr += n; + } + std::size_t n = std::size_t(curr - begin); + return n; + } + + // Synchronous write + static std::size_t write(S& stream, const char* data, std::size_t size, + std::error_code& ec) + { + REALM_ASSERT(!stream.lowest_layer().m_write_oper || + !stream.lowest_layer().m_write_oper->in_use()); + stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws + const char* begin = data; + const char* end = data + size; + const char* curr = begin; + for (;;) { + if (curr == end) { + ec = std::error_code(); // Success + break; + } + const char* data_2 = curr; + std::size_t size_2 = std::size_t(end - curr); + std::size_t n = stream.do_write_some_sync(data_2, size_2, ec); + if (REALM_UNLIKELY(ec)) + break; + REALM_ASSERT(n > 0); + REALM_ASSERT(n <= size_2); + curr += n; + } + std::size_t n = std::size_t(curr - begin); + return n; + } + + // Synchronous read + static std::size_t buffered_read(S& stream, char* buffer, std::size_t size, int delim, + ReadAheadBuffer& rab, std::error_code& ec) + { + REALM_ASSERT(!stream.lowest_layer().m_read_oper || + !stream.lowest_layer().m_read_oper->in_use()); + stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws + char* begin = buffer; + char* end = buffer + size; + char* curr = begin; + for (;;) { + bool complete = rab.read(curr, end, delim, ec); + if (complete) + break; + + rab.refill_sync(stream, ec); + if (REALM_UNLIKELY(ec)) + break; + } + std::size_t n = (curr - begin); + return n; + } + + // Synchronous read + static std::size_t read_some(S& stream, char* buffer, std::size_t size, + std::error_code& ec) + { + REALM_ASSERT(!stream.lowest_layer().m_read_oper || + !stream.lowest_layer().m_read_oper->in_use()); + stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws + return stream.do_read_some_sync(buffer, size, ec); + } + + // Synchronous write + static std::size_t write_some(S& stream, const char* data, std::size_t size, + std::error_code& ec) + { + REALM_ASSERT(!stream.lowest_layer().m_write_oper || + !stream.lowest_layer().m_write_oper->in_use()); + stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws + return stream.do_write_some_sync(data, size, ec); + } + + template + static void async_read(S& stream, char* buffer, std::size_t size, bool is_read_some, H handler) + { + char* begin = buffer; + char* end = buffer + size; + LendersReadOperPtr op = + Service::alloc>(stream.lowest_layer().m_read_oper, stream, is_read_some, + begin, end, std::move(handler)); // Throws + stream.lowest_layer().m_desc.initiate_oper(std::move(op)); // Throws + } + + template + static void async_write(S& stream, const char* data, std::size_t size, bool is_write_some, + H handler) + { + const char* begin = data; + const char* end = data + size; + LendersWriteOperPtr op = + Service::alloc>(stream.lowest_layer().m_write_oper, stream, is_write_some, + begin, end, std::move(handler)); // Throws + stream.lowest_layer().m_desc.initiate_oper(std::move(op)); // Throws + } + + template + static void async_buffered_read(S& stream, char* buffer, std::size_t size, int delim, + ReadAheadBuffer& rab, H handler) + { + char* begin = buffer; + char* end = buffer + size; + LendersBufferedReadOperPtr op = + Service::alloc>(stream.lowest_layer().m_read_oper, stream, + begin, end, delim, rab, + std::move(handler)); // Throws + stream.lowest_layer().m_desc.initiate_oper(std::move(op)); // Throws + } +}; + +template class Service::BasicStreamOps::StreamOper : public IoOper { +public: + StreamOper(std::size_t size, S& stream) noexcept : + IoOper{size}, + m_stream{&stream} + { + } + void recycle() noexcept override final + { + bool orphaned = !m_stream; + REALM_ASSERT(orphaned); + // Note: do_recycle() commits suicide. + do_recycle(orphaned); + } + void orphan() noexcept override final + { + m_stream = nullptr; + } + Descriptor& descriptor() noexcept override final + { + return m_stream->lowest_layer().m_desc; + } +protected: + S* m_stream; + std::error_code m_error_code; +}; + +template class Service::BasicStreamOps::ReadOperBase : public StreamOper { +public: + ReadOperBase(std::size_t size, S& stream, bool is_read_some, char* begin, char* end) noexcept : + StreamOper{size, stream}, + m_is_read_some{is_read_some}, + m_begin{begin}, + m_end{end} + { + } + Want initiate() + { + auto& s = *this; + REALM_ASSERT(this == s.m_stream->lowest_layer().m_read_oper.get()); + REALM_ASSERT(!s.is_complete()); + REALM_ASSERT(s.m_curr <= s.m_end); + Want want = Want::nothing; + if (REALM_UNLIKELY(s.m_curr == s.m_end)) { + s.set_is_complete(true); // Success + } + else { + s.m_stream->lowest_layer().m_desc.ensure_nonblocking_mode(); // Throws + s.m_stream->do_init_read_async(s.m_error_code, want); + if (want == Want::nothing) { + if (REALM_UNLIKELY(s.m_error_code)) { + s.set_is_complete(true); // Failure + } + else { + want = advance(); + } + } + } + return want; + } + Want advance() noexcept override final + { + auto& s = *this; + REALM_ASSERT(!s.is_complete()); + REALM_ASSERT(!s.is_canceled()); + REALM_ASSERT(!s.m_error_code); + REALM_ASSERT(s.m_curr < s.m_end); + REALM_ASSERT(!s.m_is_read_some || s.m_curr == m_begin); + for (;;) { + // Read into callers buffer + char* buffer = s.m_curr; + std::size_t size = std::size_t(s.m_end - s.m_curr); + Want want = Want::nothing; + std::size_t n = s.m_stream->do_read_some_async(buffer, size, s.m_error_code, want); + REALM_ASSERT(n > 0 || s.m_error_code || want != Want::nothing); // No busy loop, please + bool got_nothing = (n == 0); + if (got_nothing) { + if (REALM_UNLIKELY(s.m_error_code)) { + s.set_is_complete(true); // Failure + return Want::nothing; + } + // Got nothing, but want something + return want; + } + REALM_ASSERT(!s.m_error_code); + // Check for completion + REALM_ASSERT(n <= size); + s.m_curr += n; + if (s.m_is_read_some || s.m_curr == s.m_end) { + s.set_is_complete(true); // Success + return Want::nothing; + } + if (want != Want::nothing) + return want; + REALM_ASSERT(n < size); + } + } +protected: + const bool m_is_read_some; + char* const m_begin; // May be dangling after cancellation + char* const m_end; // May be dangling after cancellation + char* m_curr = m_begin; // May be dangling after cancellation +}; + +template class Service::BasicStreamOps::WriteOperBase : public StreamOper { +public: + WriteOperBase(std::size_t size, S& stream, bool is_write_some, + const char* begin, const char* end) noexcept : + StreamOper{size, stream}, + m_is_write_some{is_write_some}, + m_begin{begin}, + m_end{end} + { + } + Want initiate() + { + auto& s = *this; + REALM_ASSERT(this == s.m_stream->lowest_layer().m_write_oper.get()); + REALM_ASSERT(!s.is_complete()); + REALM_ASSERT(s.m_curr <= s.m_end); + Want want = Want::nothing; + if (REALM_UNLIKELY(s.m_curr == s.m_end)) { + s.set_is_complete(true); // Success + } + else { + s.m_stream->lowest_layer().m_desc.ensure_nonblocking_mode(); // Throws + s.m_stream->do_init_write_async(s.m_error_code, want); + if (want == Want::nothing) { + if (REALM_UNLIKELY(s.m_error_code)) { + s.set_is_complete(true); // Failure + } + else { + want = advance(); + } + } + } + return want; + } + Want advance() noexcept override final + { + auto& s = *this; + REALM_ASSERT(!s.is_complete()); + REALM_ASSERT(!s.is_canceled()); + REALM_ASSERT(!s.m_error_code); + REALM_ASSERT(s.m_curr < s.m_end); + REALM_ASSERT(!s.m_is_write_some || s.m_curr == s.m_begin); + for (;;) { + // Write from callers buffer + const char* data = s.m_curr; + std::size_t size = std::size_t(s.m_end - s.m_curr); + Want want = Want::nothing; + std::size_t n = s.m_stream->do_write_some_async(data, size, s.m_error_code, want); + REALM_ASSERT(n > 0 || s.m_error_code || want != Want::nothing); // No busy loop, please + bool wrote_nothing = (n == 0); + if (wrote_nothing) { + if (REALM_UNLIKELY(s.m_error_code)) { + s.set_is_complete(true); // Failure + return Want::nothing; + } + // Wrote nothing, but want something written + return want; + } + REALM_ASSERT(!s.m_error_code); + // Check for completion + REALM_ASSERT(n <= size); + s.m_curr += n; + if (s.m_is_write_some || s.m_curr == s.m_end) { + s.set_is_complete(true); // Success + return Want::nothing; + } + if (want != Want::nothing) + return want; + REALM_ASSERT(n < size); + } + } +protected: + const bool m_is_write_some; + const char* const m_begin; // May be dangling after cancellation + const char* const m_end; // May be dangling after cancellation + const char* m_curr = m_begin; // May be dangling after cancellation +}; + +template class Service::BasicStreamOps::BufferedReadOperBase : public StreamOper { +public: + BufferedReadOperBase(std::size_t size, S& stream, char* begin, char* end, int delim, + ReadAheadBuffer& rab) noexcept : + StreamOper{size, stream}, + m_read_ahead_buffer{rab}, + m_begin{begin}, + m_end{end}, + m_delim{delim} + { + } + Want initiate() + { + auto& s = *this; + REALM_ASSERT(this == s.m_stream->lowest_layer().m_read_oper.get()); + REALM_ASSERT(!s.is_complete()); + Want want = Want::nothing; + bool complete = s.m_read_ahead_buffer.read(s.m_curr, s.m_end, s.m_delim, s.m_error_code); + if (complete) { + s.set_is_complete(true); // Success or failure + } + else { + s.m_stream->lowest_layer().m_desc.ensure_nonblocking_mode(); // Throws + s.m_stream->do_init_read_async(s.m_error_code, want); + if (want == Want::nothing) { + if (REALM_UNLIKELY(s.m_error_code)) { + s.set_is_complete(true); // Failure + } + else { + want = advance(); + } + } + } + return want; + } + Want advance() noexcept override final + { + auto& s = *this; + REALM_ASSERT(!s.is_complete()); + REALM_ASSERT(!s.is_canceled()); + REALM_ASSERT(!s.m_error_code); + REALM_ASSERT(s.m_read_ahead_buffer.empty()); + REALM_ASSERT(s.m_curr < s.m_end); + for (;;) { + // Fill read-ahead buffer from stream (is empty now) + Want want = Want::nothing; + bool nonempty = s.m_read_ahead_buffer.refill_async(*s.m_stream, s.m_error_code, want); + REALM_ASSERT(nonempty || s.m_error_code || + want != Want::nothing); // No busy loop, please + bool got_nothing = !nonempty; + if (got_nothing) { + if (REALM_UNLIKELY(s.m_error_code)) { + s.set_is_complete(true); // Failure + return Want::nothing; + } + // Got nothing, but want something + return want; + } + // Transfer buffered data to callers buffer + bool complete = + s.m_read_ahead_buffer.read(s.m_curr, s.m_end, s.m_delim, s.m_error_code); + if (complete) { + s.set_is_complete(true); // Success or failure (delim_not_found) + return Want::nothing; + } + if (want != Want::nothing) + return want; + } + } +protected: + ReadAheadBuffer& m_read_ahead_buffer; // May be dangling after cancellation + char* const m_begin; // May be dangling after cancellation + char* const m_end; // May be dangling after cancellation + char* m_curr = m_begin; // May be dangling after cancellation + const int m_delim; +}; + +template template +class Service::BasicStreamOps::ReadOper : public ReadOperBase { +public: + ReadOper(std::size_t size, S& stream, bool is_read_some, char* begin, char* end, H handler) : + ReadOperBase{size, stream, is_read_some, begin, end}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + auto& s = *this; + REALM_ASSERT(s.is_complete() || s.is_canceled()); + REALM_ASSERT(s.is_complete() == (s.m_error_code || s.m_curr == s.m_end || + (s.m_is_read_some && s.m_curr != s.m_begin))); + REALM_ASSERT(s.m_curr >= s.m_begin); + bool orphaned = !s.m_stream; + std::error_code ec = s.m_error_code; + if (s.is_canceled()) + ec = error::operation_aborted; + std::size_t num_bytes_transferred = std::size_t(s.m_curr - s.m_begin); + // Note: do_recycle_and_execute() commits suicide. + s.template do_recycle_and_execute(orphaned, s.m_handler, ec, + num_bytes_transferred); // Throws + } +private: + H m_handler; +}; + +template template +class Service::BasicStreamOps::WriteOper : public WriteOperBase { +public: + WriteOper(std::size_t size, S& stream, bool is_write_some, + const char* begin, const char* end, H handler) : + WriteOperBase{size, stream, is_write_some, begin, end}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + auto& s = *this; + REALM_ASSERT(s.is_complete() || s.is_canceled()); + REALM_ASSERT(s.is_complete() == (s.m_error_code || s.m_curr == s.m_end || + (s.m_is_write_some && s.m_curr != s.m_begin))); + REALM_ASSERT(s.m_curr >= s.m_begin); + bool orphaned = !s.m_stream; + std::error_code ec = s.m_error_code; + if (s.is_canceled()) + ec = error::operation_aborted; + std::size_t num_bytes_transferred = std::size_t(s.m_curr - s.m_begin); + // Note: do_recycle_and_execute() commits suicide. + s.template do_recycle_and_execute(orphaned, s.m_handler, ec, + num_bytes_transferred); // Throws + } +private: + H m_handler; +}; + +template template +class Service::BasicStreamOps::BufferedReadOper : public BufferedReadOperBase { +public: + BufferedReadOper(std::size_t size, S& stream, char* begin, char* end, int delim, + ReadAheadBuffer& rab, H handler) : + BufferedReadOperBase{size, stream, begin, end, delim, rab}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + auto& s = *this; + REALM_ASSERT(s.is_complete() || (s.is_canceled() && !s.m_error_code)); + REALM_ASSERT(s.is_canceled() || s.m_error_code || + (s.m_delim != std::char_traits::eof() ? + s.m_curr > s.m_begin && s.m_curr[-1] == + std::char_traits::to_char_type(s.m_delim) : + s.m_curr == s.m_end)); + REALM_ASSERT(s.m_curr >= s.m_begin); + bool orphaned = !s.m_stream; + std::error_code ec = s.m_error_code; + if (s.is_canceled()) + ec = error::operation_aborted; + std::size_t num_bytes_transferred = std::size_t(s.m_curr - s.m_begin); + // Note: do_recycle_and_execute() commits suicide. + s.template do_recycle_and_execute(orphaned, s.m_handler, ec, + num_bytes_transferred); // Throws + } +private: + H m_handler; +}; + +template inline void Service::post(H handler) +{ + do_post(&Service::post_oper_constr, sizeof (PostOper), &handler); +} + +inline void Service::OwnersOperDeleter::operator()(AsyncOper* op) const noexcept +{ + if (op->in_use()) { + op->orphan(); + } + else { + void* addr = op; + op->~AsyncOper(); + delete[] static_cast(addr); + } +} + +inline void Service::LendersOperDeleter::operator()(AsyncOper* op) const noexcept +{ + op->recycle(); // Suicide +} + +template std::unique_ptr +Service::alloc(OwnersOperPtr& owners_ptr, Args&&... args) +{ + void* addr = owners_ptr.get(); + std::size_t size; + if (REALM_LIKELY(addr)) { + REALM_ASSERT(!owners_ptr->in_use()); + size = owners_ptr->m_size; + // We can use static dispatch in the destructor call here, since an + // object, that is not in use, is always an instance of UnusedOper. + REALM_ASSERT(dynamic_cast(owners_ptr.get())); + static_cast(owners_ptr.get())->UnusedOper::~UnusedOper(); + if (REALM_UNLIKELY(size < sizeof (Oper))) { + owners_ptr.release(); + delete[] static_cast(addr); + goto no_object; + } + } + else { + no_object: + addr = new char[sizeof (Oper)]; // Throws + size = sizeof (Oper); + owners_ptr.reset(static_cast(addr)); + } + std::unique_ptr lenders_ptr; + try { + lenders_ptr.reset(new (addr) Oper(size, std::forward(args)...)); // Throws + } + catch (...) { + new (addr) UnusedOper(size); // Does not throw + throw; + } + return lenders_ptr; +} + +template inline Service::PostOperBase* +Service::post_oper_constr(void* addr, std::size_t size, Impl& service, void* cookie) +{ + H& handler = *static_cast(cookie); + return new (addr) PostOper(size, service, std::move(handler)); // Throws +} + +inline bool Service::AsyncOper::in_use() const noexcept +{ + return m_in_use; +} + +inline bool Service::AsyncOper::is_complete() const noexcept +{ + return m_complete; +} + +inline void Service::AsyncOper::cancel() noexcept +{ + REALM_ASSERT(m_in_use); + REALM_ASSERT(!m_canceled); + m_canceled = true; +} + +inline Service::AsyncOper::AsyncOper(std::size_t size, bool is_in_use) noexcept : + m_size{size}, + m_in_use{is_in_use} +{ +} + +inline bool Service::AsyncOper::is_canceled() const noexcept +{ + return m_canceled; +} + +inline void Service::AsyncOper::set_is_complete(bool value) noexcept +{ + REALM_ASSERT(!m_complete); + REALM_ASSERT(!value || m_in_use); + m_complete = value; +} + +template +inline void Service::AsyncOper::do_recycle_and_execute(bool orphaned, H& handler, Args&&... args) +{ + // Recycle the operation object before the handler is exceuted, such that + // the memory is available for a new post operation that might be initiated + // during the execution of the handler. + bool was_recycled = false; + try { + // We need to copy or move all arguments to be passed to the handler, + // such that there is no risk of references to the recycled operation + // object being passed to the handler (the passed arguments may be + // references to members of the recycled operation object). The easiest + // way to achive this, is by forwarding the reference arguments (passed + // to this function) to a helper function whose arguments have + // nonreference type (`Args...` rather than `Args&&...`). + // + // Note that the copying and moving of arguments may throw, and it is + // important that the operation is still recycled even if that + // happens. For that reason, copying and moving of arguments must not + // happen until we are in a scope (this scope) that catches and deals + // correctly with such exceptions. + do_recycle_and_execute_helper(orphaned, was_recycled, std::move(handler), + std::forward(args)...); // Throws + } + catch (...) { + if (!was_recycled) + do_recycle(orphaned); + throw; + } +} + +template +inline void Service::AsyncOper::do_recycle_and_execute_helper(bool orphaned, bool& was_recycled, + H handler, Args... args) +{ + do_recycle(orphaned); + was_recycled = true; + handler(std::move(args)...); // Throws +} + +inline void Service::AsyncOper::do_recycle(bool orphaned) noexcept +{ + REALM_ASSERT(in_use()); + void* addr = this; + std::size_t size = m_size; + this->~AsyncOper(); // Suicide + if (orphaned) { + delete[] static_cast(addr); + } + else { + new (addr) UnusedOper(size); + } +} + +// ---------------- Resolver ---------------- + +template class Resolver::ResolveOper : public Service::ResolveOperBase { +public: + ResolveOper(std::size_t size, Resolver& r, Query q, H handler) : + ResolveOperBase{size, r, std::move(q)}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + REALM_ASSERT(is_complete() || (is_canceled() && !m_error_code)); + REALM_ASSERT(is_canceled() || m_error_code || !m_endpoints.empty()); + bool orphaned = !m_resolver; + std::error_code ec = m_error_code; + if (is_canceled()) + ec = error::operation_aborted; + // Note: do_recycle_and_execute() commits suicide. + do_recycle_and_execute(orphaned, m_handler, ec, std::move(m_endpoints)); // Throws + } +private: + H m_handler; +}; + +inline Resolver::Resolver(Service& service) : + m_service_impl{*service.m_impl} +{ +} + +inline Resolver::~Resolver() noexcept +{ + cancel(); +} + +inline Endpoint::List Resolver::resolve(const Query& q) +{ + std::error_code ec; + Endpoint::List list = resolve(q, ec); + if (REALM_UNLIKELY(ec)) + throw std::system_error(ec); + return list; +} + +template void Resolver::async_resolve(Query query, H handler) +{ + Service::LendersResolveOperPtr op = + Service::alloc>(m_resolve_oper, *this, + std::move(query), + std::move(handler)); // Throws + initiate_oper(std::move(op)); // Throws +} + +inline Resolver::Query::Query(std::string service_port, int init_flags) : + m_flags{init_flags}, + m_service{service_port} +{ +} + +inline Resolver::Query::Query(const StreamProtocol& prot, std::string service_port, + int init_flags) : + m_flags{init_flags}, + m_protocol{prot}, + m_service{service_port} +{ +} + +inline Resolver::Query::Query(std::string host_name, std::string service_port, int init_flags) : + m_flags{init_flags}, + m_host{host_name}, + m_service{service_port} +{ +} + +inline Resolver::Query::Query(const StreamProtocol& prot, std::string host_name, + std::string service_port, int init_flags) : + m_flags{init_flags}, + m_protocol{prot}, + m_host{host_name}, + m_service{service_port} +{ +} + +inline Resolver::Query::~Query() noexcept +{ +} + +inline int Resolver::Query::flags() const +{ + return m_flags; +} + +inline StreamProtocol Resolver::Query::protocol() const +{ + return m_protocol; +} + +inline std::string Resolver::Query::host() const +{ + return m_host; +} + +inline std::string Resolver::Query::service() const +{ + return m_service; +} + +// ---------------- SocketBase ---------------- + +inline SocketBase::SocketBase(Service& service) : + m_desc{*service.m_impl} +{ +} + +inline SocketBase::~SocketBase() noexcept +{ + close(); +} + +inline bool SocketBase::is_open() const noexcept +{ + return m_desc.is_open(); +} + +inline auto SocketBase::native_handle() const noexcept -> native_handle_type +{ + return m_desc.native_handle(); +} + +inline void SocketBase::open(const StreamProtocol& prot) +{ + std::error_code ec; + if (open(prot, ec)) + throw std::system_error(ec); +} + +inline void SocketBase::close() noexcept +{ + if (!is_open()) + return; + cancel(); + m_desc.close(); +} + +template +inline void SocketBase::get_option(O& opt) const +{ + std::error_code ec; + if (get_option(opt, ec)) + throw std::system_error(ec); +} + +template +inline std::error_code SocketBase::get_option(O& opt, std::error_code& ec) const +{ + opt.get(*this, ec); + return ec; +} + +template +inline void SocketBase::set_option(const O& opt) +{ + std::error_code ec; + if (set_option(opt, ec)) + throw std::system_error(ec); +} + +template +inline std::error_code SocketBase::set_option(const O& opt, std::error_code& ec) +{ + opt.set(*this, ec); + return ec; +} + +inline void SocketBase::bind(const Endpoint& ep) +{ + std::error_code ec; + if (bind(ep, ec)) + throw std::system_error(ec); +} + +inline Endpoint SocketBase::local_endpoint() const +{ + std::error_code ec; + Endpoint ep = local_endpoint(ec); + if (ec) + throw std::system_error(ec); + return ep; +} + +inline auto SocketBase::release_native_handle() noexcept -> native_handle_type +{ + if (is_open()) { + cancel(); + return m_desc.release(); + } + return m_desc.native_handle(); +} + +inline const StreamProtocol& SocketBase::get_protocol() const noexcept +{ + return m_protocol; +} + +template +inline SocketBase::Option::Option(T init_value) : + m_value{init_value} +{ +} + +template +inline T SocketBase::Option::value() const +{ + return m_value; +} + +template +inline void SocketBase::Option::get(const SocketBase& sock, std::error_code& ec) +{ + union { + U value; + char strut[sizeof (U) + 1]; + }; + std::size_t value_size = sizeof strut; + sock.get_option(opt_enum(opt), &value, value_size, ec); + if (!ec) { + REALM_ASSERT(value_size == sizeof value); + m_value = T(value); + } +} + +template +inline void SocketBase::Option::set(SocketBase& sock, std::error_code& ec) const +{ + U value_to_set = U(m_value); + sock.set_option(opt_enum(opt), &value_to_set, sizeof value_to_set, ec); +} + +// ---------------- Socket ---------------- + +class Socket::ConnectOperBase : public Service::IoOper { +public: + ConnectOperBase(std::size_t size, Socket& sock) noexcept : + IoOper{size}, + m_socket{&sock} + { + } + Want initiate(const Endpoint& ep) + { + REALM_ASSERT(this == m_socket->m_write_oper.get()); + if (m_socket->initiate_async_connect(ep, m_error_code)) { // Throws + set_is_complete(true); // Failure, or immediate completion + return Want::nothing; + } + return Want::write; + } + Want advance() noexcept override final + { + REALM_ASSERT(!is_complete()); + REALM_ASSERT(!is_canceled()); + REALM_ASSERT(!m_error_code); + m_socket->finalize_async_connect(m_error_code); + set_is_complete(true); + return Want::nothing; + } + void recycle() noexcept override final + { + bool orphaned = !m_socket; + REALM_ASSERT(orphaned); + // Note: do_recycle() commits suicide. + do_recycle(orphaned); + } + void orphan() noexcept override final + { + m_socket = nullptr; + } + Service::Descriptor& descriptor() noexcept override final + { + return m_socket->m_desc; + } +protected: + Socket* m_socket; + std::error_code m_error_code; +}; + +template class Socket::ConnectOper : public ConnectOperBase { +public: + ConnectOper(std::size_t size, Socket& sock, H handler) : + ConnectOperBase{size, sock}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + REALM_ASSERT(is_complete() || (is_canceled() && !m_error_code)); + bool orphaned = !m_socket; + std::error_code ec = m_error_code; + if (is_canceled()) + ec = error::operation_aborted; + // Note: do_recycle_and_execute() commits suicide. + do_recycle_and_execute(orphaned, m_handler, ec); // Throws + } +private: + H m_handler; +}; + +inline Socket::Socket(Service& service) : + SocketBase{service} +{ +} + +inline Socket::Socket(Service& service, const StreamProtocol& prot, + native_handle_type native_socket) : + SocketBase{service} +{ + assign(prot, native_socket); // Throws +} + +inline Socket::~Socket() noexcept +{ +} + +inline void Socket::connect(const Endpoint& ep) +{ + std::error_code ec; + if (connect(ep, ec)) // Throws + throw std::system_error(ec); +} + +inline std::size_t Socket::read(char* buffer, std::size_t size) +{ + std::error_code ec; + read(buffer, size, ec); // Throws + if (ec) + throw std::system_error(ec); + return size; +} + +inline std::size_t Socket::read(char* buffer, std::size_t size, std::error_code& ec) +{ + return StreamOps::read(*this, buffer, size, ec); // Throws +} + +inline std::size_t Socket::read(char* buffer, std::size_t size, ReadAheadBuffer& rab) +{ + std::error_code ec; + read(buffer, size, rab, ec); // Throws + if (ec) + throw std::system_error(ec); + return size; +} + +inline std::size_t Socket::read(char* buffer, std::size_t size, ReadAheadBuffer& rab, + std::error_code& ec) +{ + int delim = std::char_traits::eof(); + return StreamOps::buffered_read(*this, buffer, size, delim, rab, ec); // Throws +} + +inline std::size_t Socket::read_until(char* buffer, std::size_t size, char delim, + ReadAheadBuffer& rab) +{ + std::error_code ec; + std::size_t n = read_until(buffer, size, delim, rab, ec); // Throws + if (ec) + throw std::system_error(ec); + return n; +} + +inline std::size_t Socket::read_until(char* buffer, std::size_t size, char delim, + ReadAheadBuffer& rab, std::error_code& ec) +{ + int delim_2 = std::char_traits::to_int_type(delim); + return StreamOps::buffered_read(*this, buffer, size, delim_2, rab, ec); // Throws +} + +inline std::size_t Socket::write(const char* data, std::size_t size) +{ + std::error_code ec; + write(data, size, ec); // Throws + if (ec) + throw std::system_error(ec); + return size; +} + +inline std::size_t Socket::write(const char* data, std::size_t size, std::error_code& ec) +{ + return StreamOps::write(*this, data, size, ec); // Throws +} + +inline std::size_t Socket::read_some(char* buffer, std::size_t size) +{ + std::error_code ec; + std::size_t n = read_some(buffer, size, ec); // Throws + if (ec) + throw std::system_error(ec); + return n; +} + +inline std::size_t Socket::read_some(char* buffer, std::size_t size, std::error_code& ec) +{ + return StreamOps::read_some(*this, buffer, size, ec); // Throws +} + +inline std::size_t Socket::write_some(const char* data, std::size_t size) +{ + std::error_code ec; + std::size_t n = write_some(data, size, ec); // Throws + if (ec) + throw std::system_error(ec); + return n; +} + +inline std::size_t Socket::write_some(const char* data, std::size_t size, std::error_code& ec) +{ + return StreamOps::write_some(*this, data, size, ec); // Throws +} + +template inline void Socket::async_connect(const Endpoint& ep, H handler) +{ + LendersConnectOperPtr op = + Service::alloc>(m_write_oper, *this, std::move(handler)); // Throws + m_desc.initiate_oper(std::move(op), ep); // Throws +} + +template inline void Socket::async_read(char* buffer, std::size_t size, H handler) +{ + bool is_read_some = false; + StreamOps::async_read(*this, buffer, size, is_read_some, std::move(handler)); // Throws +} + +template +inline void Socket::async_read(char* buffer, std::size_t size, ReadAheadBuffer& rab, H handler) +{ + int delim = std::char_traits::eof(); + StreamOps::async_buffered_read(*this, buffer, size, delim, rab, std::move(handler)); // Throws +} + +template +inline void Socket::async_read_until(char* buffer, std::size_t size, char delim, + ReadAheadBuffer& rab, H handler) +{ + int delim_2 = std::char_traits::to_int_type(delim); + StreamOps::async_buffered_read(*this, buffer, size, delim_2, rab, std::move(handler)); // Throws +} + +template inline void Socket::async_write(const char* data, std::size_t size, H handler) +{ + bool is_write_some = false; + StreamOps::async_write(*this, data, size, is_write_some, std::move(handler)); // Throws +} + +template inline void Socket::async_read_some(char* buffer, std::size_t size, H handler) +{ + bool is_read_some = true; + StreamOps::async_read(*this, buffer, size, is_read_some, std::move(handler)); // Throws +} + +template +inline void Socket::async_write_some(const char* data, std::size_t size, H handler) +{ + bool is_write_some = true; + StreamOps::async_write(*this, data, size, is_write_some, std::move(handler)); // Throws +} + +inline void Socket::shutdown(shutdown_type what) +{ + std::error_code ec; + if (shutdown(what, ec)) // Throws + throw std::system_error(ec); +} + +inline void Socket::assign(const StreamProtocol& prot, native_handle_type native_socket) +{ + std::error_code ec; + if (assign(prot, native_socket, ec)) // Throws + throw std::system_error(ec); +} + +inline std::error_code Socket::assign(const StreamProtocol& prot, + native_handle_type native_socket, std::error_code& ec) +{ + return do_assign(prot, native_socket, ec); // Throws +} + +inline Socket& Socket::lowest_layer() noexcept +{ + return *this; +} + +inline void Socket::do_init_read_async(std::error_code&, Want& want) noexcept +{ + want = Want::read; // Wait for read readiness before proceeding +} + +inline void Socket::do_init_write_async(std::error_code&, Want& want) noexcept +{ + want = Want::write; // Wait for write readiness before proceeding +} + +inline std::size_t Socket::do_read_some_sync(char* buffer, std::size_t size, + std::error_code& ec) noexcept +{ + return m_desc.read_some(buffer, size, ec); +} + +inline std::size_t Socket::do_write_some_sync(const char* data, std::size_t size, + std::error_code& ec) noexcept +{ + return m_desc.write_some(data, size, ec); +} + +inline std::size_t Socket::do_read_some_async(char* buffer, std::size_t size, + std::error_code& ec, Want& want) noexcept +{ + std::error_code ec_2; + std::size_t n = m_desc.read_some(buffer, size, ec_2); + bool success = (!ec_2 || ec_2 == error::resource_unavailable_try_again); + if (REALM_UNLIKELY(!success)) { + ec = ec_2; + want = Want::nothing; // Failure + return 0; + } + ec = std::error_code(); + want = Want::read; // Success + return n; +} + +inline std::size_t Socket::do_write_some_async(const char* data, std::size_t size, + std::error_code& ec, Want& want) noexcept +{ + std::error_code ec_2; + std::size_t n = m_desc.write_some(data, size, ec_2); + bool success = (!ec_2 || ec_2 == error::resource_unavailable_try_again); + if (REALM_UNLIKELY(!success)) { + ec = ec_2; + want = Want::nothing; // Failure + return 0; + } + ec = std::error_code(); + want = Want::write; // Success + return n; +} + +// ---------------- Acceptor ---------------- + +class Acceptor::AcceptOperBase : public Service::IoOper { +public: + AcceptOperBase(std::size_t size, Acceptor& a, Socket& s, Endpoint* e) : + IoOper{size}, + m_acceptor{&a}, + m_socket{s}, + m_endpoint{e} + { + } + Want initiate() + { + REALM_ASSERT(this == m_acceptor->m_read_oper.get()); + REALM_ASSERT(!is_complete()); + m_acceptor->m_desc.ensure_nonblocking_mode(); // Throws + return Want::read; + } + Want advance() noexcept override final + { + REALM_ASSERT(!is_complete()); + REALM_ASSERT(!is_canceled()); + REALM_ASSERT(!m_error_code); + REALM_ASSERT(!m_socket.is_open()); + Want want = m_acceptor->do_accept_async(m_socket, m_endpoint, m_error_code); + if (want == Want::nothing) + set_is_complete(true); // Success or failure + return want; + } + void recycle() noexcept override final + { + bool orphaned = !m_acceptor; + REALM_ASSERT(orphaned); + // Note: do_recycle() commits suicide. + do_recycle(orphaned); + } + void orphan() noexcept override final + { + m_acceptor = nullptr; + } + Service::Descriptor& descriptor() noexcept override final + { + return m_acceptor->m_desc; + } +protected: + Acceptor* m_acceptor; + Socket& m_socket; // May be dangling after cancellation + Endpoint* const m_endpoint; // May be dangling after cancellation + std::error_code m_error_code; +}; + +template class Acceptor::AcceptOper : public AcceptOperBase { +public: + AcceptOper(std::size_t size, Acceptor& a, Socket& s, Endpoint* e, H handler) : + AcceptOperBase{size, a, s, e}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + REALM_ASSERT(is_complete() || (is_canceled() && !m_error_code)); + REALM_ASSERT(is_canceled() || m_error_code || m_socket.is_open()); + bool orphaned = !m_acceptor; + std::error_code ec = m_error_code; + if (is_canceled()) + ec = error::operation_aborted; + // Note: do_recycle_and_execute() commits suicide. + do_recycle_and_execute(orphaned, m_handler, ec); // Throws + } +private: + H m_handler; +}; + +inline Acceptor::Acceptor(Service& service) : + SocketBase{service} +{ +} + +inline Acceptor::~Acceptor() noexcept +{ +} + +inline void Acceptor::listen(int backlog) +{ + std::error_code ec; + if (listen(backlog, ec)) // Throws + throw std::system_error(ec); +} + +inline void Acceptor::accept(Socket& sock) +{ + std::error_code ec; + if (accept(sock, ec)) // Throws + throw std::system_error(ec); +} + +inline void Acceptor::accept(Socket& sock, Endpoint& ep) +{ + std::error_code ec; + if (accept(sock, ep, ec)) // Throws + throw std::system_error(ec); +} + +inline std::error_code Acceptor::accept(Socket& sock, std::error_code& ec) +{ + Endpoint* ep = nullptr; + return accept(sock, ep, ec); // Throws +} + +inline std::error_code Acceptor::accept(Socket& sock, Endpoint& ep, std::error_code& ec) +{ + return accept(sock, &ep, ec); // Throws +} + +template inline void Acceptor::async_accept(Socket& sock, H handler) +{ + Endpoint* ep = nullptr; + async_accept(sock, ep, std::move(handler)); // Throws +} + +template inline void Acceptor::async_accept(Socket& sock, Endpoint& ep, H handler) +{ + async_accept(sock, &ep, std::move(handler)); // Throws +} + +inline std::error_code Acceptor::accept(Socket& socket, Endpoint* ep, std::error_code& ec) +{ + REALM_ASSERT(!m_read_oper || !m_read_oper->in_use()); + if (REALM_UNLIKELY(socket.is_open())) + throw util::runtime_error("Socket is already open"); + m_desc.ensure_blocking_mode(); // Throws + m_desc.accept(socket.m_desc, m_protocol, ep, ec); + return ec; +} + +inline Acceptor::Want Acceptor::do_accept_async(Socket& socket, Endpoint* ep, + std::error_code& ec) noexcept +{ + std::error_code ec_2; + m_desc.accept(socket.m_desc, m_protocol, ep, ec_2); + if (ec_2 == error::resource_unavailable_try_again) + return Want::read; + ec = ec_2; + return Want::nothing; +} + +template inline void Acceptor::async_accept(Socket& sock, Endpoint* ep, H handler) +{ + if (REALM_UNLIKELY(sock.is_open())) + throw util::runtime_error("Socket is already open"); + LendersAcceptOperPtr op = Service::alloc>(m_read_oper, *this, sock, ep, + std::move(handler)); // Throws + m_desc.initiate_oper(std::move(op)); // Throws +} + +// ---------------- DeadlineTimer ---------------- + +template +class DeadlineTimer::WaitOper : public Service::WaitOperBase { +public: + WaitOper(std::size_t size, DeadlineTimer& timer, clock::time_point expiration_time, + H handler) : + Service::WaitOperBase{size, timer, expiration_time}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + bool orphaned = !m_timer; + std::error_code ec; + if (is_canceled()) + ec = error::operation_aborted; + // Note: do_recycle_and_execute() commits suicide. + do_recycle_and_execute(orphaned, m_handler, ec); // Throws + } +private: + H m_handler; +}; + +inline DeadlineTimer::DeadlineTimer(Service& service) : + m_service_impl{*service.m_impl} +{ +} + +inline DeadlineTimer::~DeadlineTimer() noexcept +{ + cancel(); +} + +template +inline void DeadlineTimer::async_wait(std::chrono::duration delay, H handler) +{ + clock::time_point now = clock::now(); + // FIXME: This method of detecting overflow does not work. Comparison + // between distinct duration types is not overflow safe. Overflow easily + // happens in the implied conversion of arguments to the common duration + // type (std::common_type<>). + auto max_add = clock::time_point::max() - now; + if (delay > max_add) + throw util::overflow_error("Expiration time overflow"); + clock::time_point expiration_time = now + delay; + Service::LendersWaitOperPtr op = + Service::alloc>(m_wait_oper, *this, expiration_time, + std::move(handler)); // Throws + initiate_oper(std::move(op)); // Throws +} + +// ---------------- Trigger ---------------- + +template +class Trigger::ExecOper : public Service::TriggerExecOperBase { +public: + ExecOper(Service::Impl& service_impl, H handler) : + Service::TriggerExecOperBase{service_impl}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + REALM_ASSERT(in_use()); + // Note: Potential suicide when `self` goes out of scope + util::bind_ptr self{this, bind_ptr_base::adopt_tag{}}; + if (m_service) { + Service::reset_trigger_exec(*m_service, *this); + m_handler(); // Throws + } + } +private: + H m_handler; +}; + +template inline Trigger::Trigger(Service& service, H handler) : + m_exec_oper{new ExecOper{*service.m_impl, std::move(handler)}} // Throws +{ +} + +inline Trigger::~Trigger() noexcept +{ + if (m_exec_oper) + m_exec_oper->orphan(); +} + +inline void Trigger::trigger() noexcept +{ + REALM_ASSERT(m_exec_oper); + m_exec_oper->trigger(); +} + +// ---------------- ReadAheadBuffer ---------------- + +inline ReadAheadBuffer::ReadAheadBuffer() : + m_buffer{new char[s_size]} // Throws +{ +} + +inline void ReadAheadBuffer::clear() noexcept +{ + m_begin = nullptr; + m_end = nullptr; +} + +inline bool ReadAheadBuffer::empty() const noexcept +{ + return (m_begin == m_end); +} + +template inline void ReadAheadBuffer::refill_sync(S& stream, std::error_code& ec) noexcept +{ + char* buffer = m_buffer.get(); + std::size_t size = s_size; + static_assert(noexcept(stream.do_read_some_sync(buffer, size, ec)), ""); + std::size_t n = stream.do_read_some_sync(buffer, size, ec); + if (REALM_UNLIKELY(n == 0)) + return; + REALM_ASSERT(!ec); + REALM_ASSERT(n <= size); + m_begin = m_buffer.get(); + m_end = m_begin + n; +} + +template +inline bool ReadAheadBuffer::refill_async(S& stream, std::error_code& ec, Want& want) noexcept +{ + char* buffer = m_buffer.get(); + std::size_t size = s_size; + static_assert(noexcept(stream.do_read_some_async(buffer, size, ec, want)), ""); + std::size_t n = stream.do_read_some_async(buffer, size, ec, want); + if (n == 0) + return false; + REALM_ASSERT(!ec); + REALM_ASSERT(n <= size); + m_begin = m_buffer.get(); + m_end = m_begin + n; + return true; +} + +} // namespace network +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_NETWORK_HPP diff --git a/Pods/Realm/include/core/realm/util/network_ssl.hpp b/Pods/Realm/include/core/realm/util/network_ssl.hpp new file mode 100644 index 0000000000..3284bf8483 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/network_ssl.hpp @@ -0,0 +1,1378 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_UTIL_NETWORK_SSL_HPP +#define REALM_UTIL_NETWORK_SSL_HPP + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#if REALM_HAVE_OPENSSL +# include +# include +#elif REALM_HAVE_SECURE_TRANSPORT +# include +# include +# include + +#define REALM_HAVE_KEYCHAIN_APIS (TARGET_OS_MAC && !TARGET_OS_IPHONE) + +#endif + +// FIXME: Add necessary support for customizing the SSL server and client +// configurations. + +// FIXME: Currently, the synchronous SSL operations (handshake, read, write, +// shutdown) do not automatically retry if the underlying SSL function returns +// with SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. This normally never +// happens, but it can happen according to the man pages, but in the case of +// SSL_write(), only when a renegotiation has to take place. It is likely that +// the solution is to to wrap the SSL calls inside a loop, such that they keep +// retrying until they succeed, however, such a simple scheme will fail if the +// synchronous operations were to be used with an underlying TCP socket in +// nonblocking mode. Currently, the underlying TCP socket is always in blocking +// mode when performing synchronous operations, but that may continue to be the +// case in teh future. + + +namespace realm { +namespace util { +namespace network { +namespace ssl { + +enum class Errors { + certificate_rejected = 1, +}; + +class ErrorCategory : public std::error_category { +public: + const char* name() const noexcept override final; + std::string message(int) const override final; + bool equivalent(const std::error_code&, int) const noexcept override final; +}; + +/// The error category associated with \ref Errors. The name of this category is +/// `realm.util.network.ssl`. +extern ErrorCategory error_category; + +inline std::error_code make_error_code(Errors err) +{ + return std::error_code(int(err), error_category); +} + +inline std::error_condition make_error_condition(Errors err) +{ + return std::error_condition(int(err), error_category); +} + +} // namespace ssl +} // namespace network +} // namespace util +} // namespace realm + +namespace std { + +template<> class is_error_condition_enum { +public: + static const bool value = true; +}; + +} // namespace std + +namespace realm { +namespace util { +namespace network { + +class OpensslErrorCategory : public std::error_category { +public: + const char* name() const noexcept override final; + std::string message(int) const override final; +}; + +/// The error category associated with error codes produced by the third-party +/// library, OpenSSL. The name of this category is `openssl`. +extern OpensslErrorCategory openssl_error_category; + +class SecureTransportErrorCategory : public std::error_category { +public: + const char* name() const noexcept override final; + std::string message(int) const override final; +}; + +/// The error category associated with error codes produced by Apple's +/// SecureTransport library. The name of this category is `securetransport`. +extern SecureTransportErrorCategory secure_transport_error_category; + + +namespace ssl { + +class ProtocolNotSupported; + + +/// `VerifyMode::none` corresponds to OpenSSL's `SSL_VERIFY_NONE`, and +/// `VerifyMode::peer` to `SSL_VERIFY_PEER`. +enum class VerifyMode { none, peer }; + + +class Context { +public: + Context(); + ~Context() noexcept; + + /// File must be in PEM format. Corresponds to OpenSSL's + /// `SSL_CTX_use_certificate_chain_file()`. + void use_certificate_chain_file(const std::string& path); + + /// File must be in PEM format. Corresponds to OpenSSL's + /// `SSL_CTX_use_PrivateKey_file()`. + void use_private_key_file(const std::string& path); + + /// Calling use_default_verify() will make a client use the device + /// default certificates for server verification. For OpenSSL, + /// use_default_verify() corresponds to + /// SSL_CTX_set_default_verify_paths(SSL_CTX*); + void use_default_verify(); + + /// The verify file is a PEM file containing trust certificates that the + /// client will use to verify the server certificate. If use_verify_file() + /// is not called, the default device trust store will be used. + /// use_verify_file() corresponds roughly to OpenSSL's + /// SSL_CTX_load_verify_locations(). + void use_verify_file(const std::string& path); + +private: + void ssl_init(); + void ssl_destroy() noexcept; + void ssl_use_certificate_chain_file(const std::string& path, std::error_code&); + void ssl_use_private_key_file(const std::string& path, std::error_code&); + void ssl_use_default_verify(std::error_code&); + void ssl_use_verify_file(const std::string& path, std::error_code&); + +#if REALM_HAVE_OPENSSL + SSL_CTX* m_ssl_ctx = nullptr; + +#elif REALM_HAVE_SECURE_TRANSPORT + +#if REALM_HAVE_KEYCHAIN_APIS + std::error_code open_temporary_keychain_if_needed(); + std::error_code update_identity_if_needed(); + + util::CFPtr m_keychain; + std::string m_keychain_path; + + util::CFPtr m_certificate; + util::CFPtr m_private_key; + util::CFPtr m_identity; + + util::CFPtr m_certificate_chain; + +#else + using SecKeychainRef = std::nullptr_t; + +#endif // REALM_HAVE_KEYCHAIN_APIS + static util::CFPtr load_pem_file(const std::string& path, SecKeychainRef, std::error_code&); + + util::CFPtr m_trust_anchors; + util::CFPtr m_pinned_certificate; + +#endif + + friend class Stream; +}; + + +/// Switching between synchronous and asynchronous operations is allowed, but +/// only in a nonoverlapping fashion. That is, a synchronous operation is not +/// allowed to run concurrently with an asynchronous one on the same +/// stream. Note that an asynchronous operation is considered to be running +/// until its completion handler starts executing. +class Stream { +public: + using port_type = util::network::Endpoint::port_type; + using SSLVerifyCallback = bool(const std::string& server_address, + port_type server_port, + const char* pem_data, + size_t pem_size, + int preverify_ok, + int depth); + + enum HandshakeType { client, server }; + + util::Logger* logger = nullptr; + + Stream(Socket&, Context&, HandshakeType); + ~Stream() noexcept; + + /// \brief set_logger() set a logger for the stream class. If + /// set_logger() is not called, no logging will take place by + /// the Stream class. + void set_logger(util::Logger*); + + /// \brief Set the certificate verification mode for this SSL stream. + /// + /// Corresponds to OpenSSL's `SSL_set_verify()` with null passed as + /// `verify_callback`. + /// + /// Clients should always set it to `VerifyMode::peer`, such that the client + /// verifies the servers certificate. Servers should only set it to + /// `VerifyMode::peer` if they want to request a certificate from the + /// client. When testing with self-signed certificates, it is necessary to + /// set it to `VerifyMode::none` for clients too. + /// + /// It is an error if this function is called after the handshake operation + /// is initiated. + /// + /// The default verify mode is `VerifyMode::none`. + void set_verify_mode(VerifyMode); + + /// \brief Check the certificate against a host_name. + /// + /// set_check_host() includes a host name check in the + /// certificate verification. It is typically used by clients + /// to secure that the received certificate has a common name + /// or subject alternative name that matches \param host_name. + /// + /// set_check_host() is only useful if verify_mode is + /// set to VerifyMode::peer. + void set_check_host(std::string host_name); + const std::string& get_host_name(); + + /// get_server_port() and set_server_port() are getter and setter for + /// the server port. They are only used by the verify callback function + /// below. + port_type get_server_port(); + void set_server_port(port_type server_port); + + /// If use_verify_callback() is called, the SSL certificate chain of + /// the server is presented to callback, one certificate at a time. + /// The SSL connection is accepted if and only if callback returns true + /// for all certificates. + /// The signature of \param callback is + /// + /// bool(const std::string& server_address, + /// port_type server_port, + /// const char* pem_data, + /// size_t pem_size, + /// int preverify_ok, + /// int depth); + // + /// server address and server_port is the address and port of the server + /// that a SSL connection is being established to. + /// pem_data is the certificate of length pem_size in + /// the PEM format. preverify_ok is OpenSSL's preverification of the + /// certificate. preverify_ok is either 0, or 1. If preverify_ok is 1, + /// OpenSSL has accepted the certificate and it will generally be safe + /// to trust that certificate. depth represents the position of the + /// certificate in the certificate chain sent by the server. depth = 0 + /// represents the actual server certificate that should contain the + /// host name(server address) of the server. The highest depth is the + /// root certificate. + /// The callback function will receive the certificates starting from + /// the root certificate and moving down the chain until it reaches the + /// server's own certificate with a host name. The depth of the last + /// certificate is 0. The depth of the first certificate is chain + /// length - 1. + /// + /// The return value of the callback function decides whether the + /// client accepts the certificate. If the return value is false, the + /// processing of the certificate chain is interrupted and the SSL + /// connection is rejected. If the return value is true, the verification + /// process continues. If the callback function returns true for all + /// presented certificates including the depth == 0 certificate, the + /// SSL connection is accepted. + /// + /// A recommended way of using the callback function is to return true + /// if preverify_ok = 1 and depth > 0, + /// always check the host name if depth = 0, + /// and use an independent verification step if preverify_ok = 0. + /// + /// Another possible way of using the callback is to collect all the + /// certificates until depth = 0, and present the entire chain for + /// independent verification. + void use_verify_callback(const std::function& callback); + +#ifdef REALM_INCLUDE_CERTS + /// use_included_certificates() loads a set of certificates that are + /// included in the header file src/realm/noinst/root_certs.hpp. By using + /// the included certificates, the client can verify a server in the case + /// where the relevant certificate cannot be found, or is absent, in the + /// system trust store. This function is only implemented for OpenSSL. + void use_included_certificates(); +#endif + + /// @{ + /// + /// Read and write operations behave the same way as they do on \ref + /// network::Socket, except that after cancellation of asynchronous + /// operations (`lowest_layer().cancel()`), the stream may be left in a bad + /// state (see below). + /// + /// The handshake operation must complete successfully before any read, + /// write, or shutdown operations are performed. + /// + /// The shutdown operation sends the shutdown alert to the peer, and + /// returns/completes as soon as the alert message has been written to the + /// underlying socket. It is an error if the shutdown operation is initiated + /// while there are read or write operations in progress. No read or write + /// operations are allowed to be initiated after the shutdown operation has + /// been initiated. When the shutdown operation has completed, it is safe to + /// close the underlying socket (`lowest_layer().close()`). + /// + /// If a write operation is executing while, or is initiated after a close + /// notify alert is received from the remote peer, the write operation will + /// fail with error::broken_pipe. + /// + /// Callback functions for async read and write operations must take two + /// arguments, an std::error_code(), and an integer of a type std::size_t + /// indicating the number of transferred bytes (other types are allowed as + /// long as implicit conversion can take place). + /// + /// Callback functions for async handshake and shutdown operations must take + /// a single argument of type std::error_code() (other types are allowed as + /// long as implicit conversion can take place). + /// + /// Resumption of stream operation after cancellation of asynchronous + /// operations is not supported (does not work). Since the shutdown + /// operation involves network communication, that operation is also not + /// allowed after cancellation. The only thing that is allowed, is to + /// destroy the stream object. Other stream objects are not affected. + + void handshake(); + std::error_code handshake(std::error_code&); + + std::size_t read(char* buffer, std::size_t size); + std::size_t read(char* buffer, std::size_t size, std::error_code& ec); + std::size_t read(char* buffer, std::size_t size, ReadAheadBuffer&); + std::size_t read(char* buffer, std::size_t size, ReadAheadBuffer&, std::error_code& ec); + std::size_t read_until(char* buffer, std::size_t size, char delim, ReadAheadBuffer&); + std::size_t read_until(char* buffer, std::size_t size, char delim, ReadAheadBuffer&, + std::error_code& ec); + + std::size_t write(const char* data, std::size_t size); + std::size_t write(const char* data, std::size_t size, std::error_code& ec); + + std::size_t read_some(char* buffer, std::size_t size); + std::size_t read_some(char* buffer, std::size_t size, std::error_code&); + + std::size_t write_some(const char* data, std::size_t size); + std::size_t write_some(const char* data, std::size_t size, std::error_code&); + + void shutdown(); + std::error_code shutdown(std::error_code&); + + template void async_handshake(H handler); + + template void async_read(char* buffer, std::size_t size, H handler); + template void async_read(char* buffer, std::size_t size, ReadAheadBuffer&, H handler); + template void async_read_until(char* buffer, std::size_t size, char delim, + ReadAheadBuffer&, H handler); + + template void async_write(const char* data, std::size_t size, H handler); + + template void async_read_some(char* buffer, std::size_t size, H handler); + + template void async_write_some(const char* data, std::size_t size, H handler); + + template void async_shutdown(H handler); + + /// @} + + /// Returns a reference to the underlying socket. + Socket& lowest_layer() noexcept; + +private: + using Want = Service::Want; + using StreamOps = Service::BasicStreamOps; + + class HandshakeOperBase; + template class HandshakeOper; + class ShutdownOperBase; + template class ShutdownOper; + + using LendersHandshakeOperPtr = std::unique_ptr; + using LendersShutdownOperPtr = std::unique_ptr; + + Socket& m_tcp_socket; + Context& m_ssl_context; + const HandshakeType m_handshake_type; + + // The host name that the certificate should be checked against. + // The host name is called server address in the certificate verify + // callback function. + std::string m_host_name; + + // The port of the server which is used in the certificate verify + // callback function. + port_type m_server_port; + + // The callback for certificate verification and an + // opaque argument that will be supplied to the callback. + const std::function* m_ssl_verify_callback = nullptr; + + bool m_valid_certificate_in_chain = false; + + + // See Service::BasicStreamOps for details on these these 6 functions. + void do_init_read_async(std::error_code&, Want&) noexcept; + void do_init_write_async(std::error_code&, Want&) noexcept; + std::size_t do_read_some_sync(char* buffer, std::size_t size, + std::error_code&) noexcept; + std::size_t do_write_some_sync(const char* data, std::size_t size, + std::error_code&) noexcept; + std::size_t do_read_some_async(char* buffer, std::size_t size, + std::error_code&, Want&) noexcept; + std::size_t do_write_some_async(const char* data, std::size_t size, + std::error_code&, Want&) noexcept; + + // The meaning of the arguments and return values of ssl_read() and + // ssl_write() are identical to do_read_some_async() and + // do_write_some_async() respectively, except that when the return value is + // nonzero, `want` is always `Want::nothing`, meaning that after bytes have + // been transferred, ssl_read() and ssl_write() must be called again to + // figure out whether it is necessary to wait for read or write readiness. + // + // The first invocation of ssl_shutdown() must send the shutdown alert to + // the peer. In blocking mode it must wait until the alert has been sent. In + // nonblocking mode, it must keep setting `want` to something other than + // `Want::nothing` until the alert has been sent. When the shutdown alert + // has been sent, it is safe to shut down the sending side of the underlying + // socket. On failure, ssl_shutdown() must set `ec` to something different + // than `std::error_code()` and return false. On success, it must set `ec` + // to `std::error_code()`, and return true if a shutdown alert from the peer + // has already been received, otherwise it must return false. When it sets + // `want` to something other than `Want::nothing`, it must set `ec` to + // `std::error_code()` and return false. + // + // The second invocation of ssl_shutdown() (after the first invocation + // completed) must wait for reception on the peers shutdown alert. + // + // Note: The semantics around the second invocation of shutdown is currently + // unused by the higher level API, because of a requirement of compatibility + // with Apple's Secure Transport API. + void ssl_init(); + void ssl_destroy() noexcept; + void ssl_set_verify_mode(VerifyMode, std::error_code&); + void ssl_set_check_host(std::string, std::error_code&); + void ssl_use_verify_callback(const std::function&, std::error_code&); + void ssl_use_included_certificates(std::error_code&); + + void ssl_handshake(std::error_code&, Want& want) noexcept; + bool ssl_shutdown(std::error_code& ec, Want& want) noexcept; + std::size_t ssl_read(char* buffer, std::size_t size, + std::error_code&, Want& want) noexcept; + std::size_t ssl_write(const char* data, std::size_t size, + std::error_code&, Want& want) noexcept; + +#if REALM_HAVE_OPENSSL + class BioMethod; + static BioMethod s_bio_method; + SSL* m_ssl = nullptr; + std::error_code m_bio_error_code; + + int m_ssl_index = -1; + + template + std::size_t ssl_perform(Oper oper, std::error_code& ec, Want& want) noexcept; + + int do_ssl_accept() noexcept; + int do_ssl_connect() noexcept; + int do_ssl_shutdown() noexcept; + int do_ssl_read(char* buffer, std::size_t size) noexcept; + int do_ssl_write(const char* data, std::size_t size) noexcept; + + static int bio_write(BIO*, const char*, int) noexcept; + static int bio_read(BIO*, char*, int) noexcept; + static int bio_puts(BIO*, const char*) noexcept; + static long bio_ctrl(BIO*, int, long, void*) noexcept; + static int bio_create(BIO*) noexcept; + static int bio_destroy(BIO*) noexcept; + + // verify_callback_using_hostname is used as an argument to OpenSSL's SSL_set_verify function. + // verify_callback_using_hostname verifies that the certificate is valid and contains + // m_host_name as a Common Name or Subject Alternative Name. + static int verify_callback_using_hostname(int preverify_ok, X509_STORE_CTX *ctx) noexcept; + + // verify_callback_using_delegate() is also used as an argument to OpenSSL's set_verify_function. + // verify_callback_using_delegate() calls out to the user supplied verify callback. + static int verify_callback_using_delegate(int preverify_ok, X509_STORE_CTX *ctx) noexcept; + + // verify_callback_using_root_certs is used by OpenSSL to handle certificate verification + // using the included root certifictes. + static int verify_callback_using_root_certs(int preverify_ok, X509_STORE_CTX *ctx); +#elif REALM_HAVE_SECURE_TRANSPORT + util::CFPtr m_ssl; + VerifyMode m_verify_mode = VerifyMode::none; + + enum class BlockingOperation { + read, + write, + }; + util::Optional m_last_operation; + + // Details of the underlying I/O error that lead to errSecIO being returned + // from a SecureTransport function. + std::error_code m_last_error; + + // The number of bytes accepted by SSWrite() but not yet confirmed to be + // written to the underlying socket. + std::size_t m_num_partially_written_bytes = 0; + + template + std::size_t ssl_perform(Oper oper, std::error_code& ec, Want& want) noexcept; + + std::pair do_ssl_handshake() noexcept; + std::pair do_ssl_shutdown() noexcept; + std::pair do_ssl_read(char* buffer, std::size_t size) noexcept; + std::pair do_ssl_write(const char* data, std::size_t size) noexcept; + + static OSStatus tcp_read(SSLConnectionRef, void*, std::size_t* length) noexcept; + static OSStatus tcp_write(SSLConnectionRef, const void*, std::size_t* length) noexcept; + + OSStatus tcp_read(void*, std::size_t* length) noexcept; + OSStatus tcp_write(const void*, std::size_t* length) noexcept; + + OSStatus verify_peer() noexcept; +#endif + + friend class Service::BasicStreamOps; + friend class network::ReadAheadBuffer; +}; + + +// Implementation + +class ProtocolNotSupported : public std::exception { +public: + const char* what() const noexcept override final; +}; + +inline Context::Context() +{ + ssl_init(); // Throws +} + +inline Context::~Context() noexcept +{ + ssl_destroy(); +} + +inline void Context::use_certificate_chain_file(const std::string& path) +{ + std::error_code ec; + ssl_use_certificate_chain_file(path, ec); // Throws + if (ec) + throw std::system_error(ec); +} + +inline void Context::use_private_key_file(const std::string& path) +{ + std::error_code ec; + ssl_use_private_key_file(path, ec); // Throws + if (ec) + throw std::system_error(ec); +} + +inline void Context::use_default_verify() +{ + std::error_code ec; + ssl_use_default_verify(ec); + if (ec) + throw std::system_error(ec); +} + +inline void Context::use_verify_file(const std::string& path) +{ + std::error_code ec; + ssl_use_verify_file(path, ec); + if (ec) { + throw std::system_error(ec); + } +} + +class Stream::HandshakeOperBase : public Service::IoOper { +public: + HandshakeOperBase(std::size_t size, Stream& stream) : + IoOper{size}, + m_stream{&stream} + { + } + Want initiate() + { + REALM_ASSERT(this == m_stream->m_tcp_socket.m_read_oper.get()); + REALM_ASSERT(!is_complete()); + m_stream->m_tcp_socket.m_desc.ensure_nonblocking_mode(); // Throws + return advance(); + } + Want advance() noexcept override final + { + REALM_ASSERT(!is_complete()); + REALM_ASSERT(!is_canceled()); + REALM_ASSERT(!m_error_code); + Want want = Want::nothing; + m_stream->ssl_handshake(m_error_code, want); + set_is_complete(want == Want::nothing); + return want; + } + void recycle() noexcept override final + { + bool orphaned = !m_stream; + REALM_ASSERT(orphaned); + // Note: do_recycle() commits suicide. + do_recycle(orphaned); + } + void orphan() noexcept override final + { + m_stream = nullptr; + } + Service::Descriptor& descriptor() noexcept override final + { + return m_stream->lowest_layer().m_desc; + } +protected: + Stream* m_stream; + std::error_code m_error_code; +}; + +template class Stream::HandshakeOper : public HandshakeOperBase { +public: + HandshakeOper(std::size_t size, Stream& stream, H handler) : + HandshakeOperBase{size, stream}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + REALM_ASSERT(is_complete() || is_canceled()); + bool orphaned = !m_stream; + std::error_code ec = m_error_code; + if (is_canceled()) + ec = error::operation_aborted; + // Note: do_recycle_and_execute() commits suicide. + do_recycle_and_execute(orphaned, m_handler, ec); // Throws + } +private: + H m_handler; +}; + +class Stream::ShutdownOperBase : public Service::IoOper { +public: + ShutdownOperBase(std::size_t size, Stream& stream) : + IoOper{size}, + m_stream{&stream} + { + } + Want initiate() + { + REALM_ASSERT(this == m_stream->m_tcp_socket.m_write_oper.get()); + REALM_ASSERT(!is_complete()); + m_stream->m_tcp_socket.m_desc.ensure_nonblocking_mode(); // Throws + return advance(); + } + Want advance() noexcept override final + { + REALM_ASSERT(!is_complete()); + REALM_ASSERT(!is_canceled()); + REALM_ASSERT(!m_error_code); + Want want = Want::nothing; + m_stream->ssl_shutdown(m_error_code, want); + if (want == Want::nothing) + set_is_complete(true); + return want; + } + void recycle() noexcept override final + { + bool orphaned = !m_stream; + REALM_ASSERT(orphaned); + // Note: do_recycle() commits suicide. + do_recycle(orphaned); + } + void orphan() noexcept override final + { + m_stream = nullptr; + } + Service::Descriptor& descriptor() noexcept override final + { + return m_stream->lowest_layer().m_desc; + } +protected: + Stream* m_stream; + std::error_code m_error_code; +}; + +template class Stream::ShutdownOper : public ShutdownOperBase { +public: + ShutdownOper(std::size_t size, Stream& stream, H handler) : + ShutdownOperBase{size, stream}, + m_handler{std::move(handler)} + { + } + void recycle_and_execute() override final + { + REALM_ASSERT(is_complete() || is_canceled()); + bool orphaned = !m_stream; + std::error_code ec = m_error_code; + if (is_canceled()) + ec = error::operation_aborted; + // Note: do_recycle_and_execute() commits suicide. + do_recycle_and_execute(orphaned, m_handler, ec); // Throws + } +private: + H m_handler; +}; + +inline Stream::Stream(Socket& socket, Context& context, HandshakeType type) : + m_tcp_socket{socket}, + m_ssl_context{context}, + m_handshake_type{type} +{ + ssl_init(); // Throws +} + +inline Stream::~Stream() noexcept +{ + m_tcp_socket.cancel(); + ssl_destroy(); +} + +inline void Stream::set_logger(util::Logger* logger) +{ + this->logger = logger; +} + +inline void Stream::set_verify_mode(VerifyMode mode) +{ + std::error_code ec; + ssl_set_verify_mode(mode, ec); // Throws + if (ec) + throw std::system_error(ec); +} + +inline void Stream::set_check_host(std::string host_name) +{ + m_host_name = host_name; + std::error_code ec; + ssl_set_check_host(host_name, ec); + if (ec) + throw std::system_error(ec); +} + +inline const std::string& Stream::get_host_name() +{ + return m_host_name; +} + +inline Stream::port_type Stream::get_server_port() +{ + return m_server_port; +} + +inline void Stream::set_server_port(port_type server_port) +{ + m_server_port = server_port; +} + +inline void Stream::use_verify_callback(const std::function& callback) +{ + std::error_code ec; + ssl_use_verify_callback(callback, ec); // Throws + if (ec) + throw std::system_error(ec); +} + +#ifdef REALM_INCLUDE_CERTS +inline void Stream::use_included_certificates() +{ + std::error_code ec; + ssl_use_included_certificates(ec); // Throws + if (ec) + throw std::system_error(ec); +} +#endif + +inline void Stream::handshake() +{ + std::error_code ec; + if (handshake(ec)) // Throws + throw std::system_error(ec); +} + +inline std::size_t Stream::read(char* buffer, std::size_t size) +{ + std::error_code ec; + read(buffer, size, ec); // Throws + if (ec) + throw std::system_error(ec); + return size; +} + +inline std::size_t Stream::read(char* buffer, std::size_t size, std::error_code& ec) +{ + return StreamOps::read(*this, buffer, size, ec); // Throws +} + +inline std::size_t Stream::read(char* buffer, std::size_t size, ReadAheadBuffer& rab) +{ + std::error_code ec; + read(buffer, size, rab, ec); // Throws + if (ec) + throw std::system_error(ec); + return size; +} + +inline std::size_t Stream::read(char* buffer, std::size_t size, ReadAheadBuffer& rab, + std::error_code& ec) +{ + int delim = std::char_traits::eof(); + return StreamOps::buffered_read(*this, buffer, size, delim, rab, ec); // Throws +} + +inline std::size_t Stream::read_until(char* buffer, std::size_t size, char delim, + ReadAheadBuffer& rab) +{ + std::error_code ec; + std::size_t n = read_until(buffer, size, delim, rab, ec); // Throws + if (ec) + throw std::system_error(ec); + return n; +} + +inline std::size_t Stream::read_until(char* buffer, std::size_t size, char delim, + ReadAheadBuffer& rab, std::error_code& ec) +{ + int delim_2 = std::char_traits::to_int_type(delim); + return StreamOps::buffered_read(*this, buffer, size, delim_2, rab, ec); // Throws +} + +inline std::size_t Stream::write(const char* data, std::size_t size) +{ + std::error_code ec; + write(data, size, ec); // Throws + if (ec) + throw std::system_error(ec); + return size; +} + +inline std::size_t Stream::write(const char* data, std::size_t size, std::error_code& ec) +{ + return StreamOps::write(*this, data, size, ec); // Throws +} + +inline std::size_t Stream::read_some(char* buffer, std::size_t size) +{ + std::error_code ec; + std::size_t n = read_some(buffer, size, ec); // Throws + if (ec) + throw std::system_error(ec); + return n; +} + +inline std::size_t Stream::read_some(char* buffer, std::size_t size, std::error_code& ec) +{ + return StreamOps::read_some(*this, buffer, size, ec); // Throws +} + +inline std::size_t Stream::write_some(const char* data, std::size_t size) +{ + std::error_code ec; + std::size_t n = write_some(data, size, ec); // Throws + if (ec) + throw std::system_error(ec); + return n; +} + +inline std::size_t Stream::write_some(const char* data, std::size_t size, std::error_code& ec) +{ + return StreamOps::write_some(*this, data, size, ec); // Throws +} + +inline void Stream::shutdown() +{ + std::error_code ec; + if (shutdown(ec)) // Throws + throw std::system_error(ec); +} + +template inline void Stream::async_handshake(H handler) +{ + LendersHandshakeOperPtr op = + Service::alloc>(m_tcp_socket.m_read_oper, *this, + std::move(handler)); // Throws + m_tcp_socket.m_desc.initiate_oper(std::move(op)); // Throws +} + +template inline void Stream::async_read(char* buffer, std::size_t size, H handler) +{ + bool is_read_some = false; + StreamOps::async_read(*this, buffer, size, is_read_some, std::move(handler)); // Throws +} + +template +inline void Stream::async_read(char* buffer, std::size_t size, ReadAheadBuffer& rab, H handler) +{ + int delim = std::char_traits::eof(); + StreamOps::async_buffered_read(*this, buffer, size, delim, rab, std::move(handler)); // Throws +} + +template +inline void Stream::async_read_until(char* buffer, std::size_t size, char delim, + ReadAheadBuffer& rab, H handler) +{ + int delim_2 = std::char_traits::to_int_type(delim); + StreamOps::async_buffered_read(*this, buffer, size, delim_2, rab, std::move(handler)); // Throws +} + +template inline void Stream::async_write(const char* data, std::size_t size, H handler) +{ + bool is_write_some = false; + StreamOps::async_write(*this, data, size, is_write_some, std::move(handler)); // Throws +} + +template inline void Stream::async_read_some(char* buffer, std::size_t size, H handler) +{ + bool is_read_some = true; + StreamOps::async_read(*this, buffer, size, is_read_some, std::move(handler)); // Throws +} + +template inline void Stream::async_write_some(const char* data, std::size_t size, H handler) +{ + bool is_write_some = true; + StreamOps::async_write(*this, data, size, is_write_some, std::move(handler)); // Throws +} + +template inline void Stream::async_shutdown(H handler) +{ + LendersShutdownOperPtr op = + Service::alloc>(m_tcp_socket.m_write_oper, *this, + std::move(handler)); // Throws + m_tcp_socket.m_desc.initiate_oper(std::move(op)); // Throws +} + +inline void Stream::do_init_read_async(std::error_code&, Want& want) noexcept +{ + want = Want::nothing; // Proceed immediately unless there is an error +} + +inline void Stream::do_init_write_async(std::error_code&, Want& want) noexcept +{ + want = Want::nothing; // Proceed immediately unless there is an error +} + +inline std::size_t Stream::do_read_some_sync(char* buffer, std::size_t size, + std::error_code& ec) noexcept +{ + Want want = Want::nothing; + std::size_t n = do_read_some_async(buffer, size, ec, want); + if (n == 0 && want != Want::nothing) + ec = error::resource_unavailable_try_again; + return n; +} + +inline std::size_t Stream::do_write_some_sync(const char* data, std::size_t size, + std::error_code& ec) noexcept +{ + Want want = Want::nothing; + std::size_t n = do_write_some_async(data, size, ec, want); + if (n == 0 && want != Want::nothing) + ec = error::resource_unavailable_try_again; + return n; +} + +inline std::size_t Stream::do_read_some_async(char* buffer, std::size_t size, + std::error_code& ec, Want& want) noexcept +{ + return ssl_read(buffer, size, ec, want); +} + +inline std::size_t Stream::do_write_some_async(const char* data, std::size_t size, + std::error_code& ec, Want& want) noexcept +{ + return ssl_write(data, size, ec, want); +} + +inline Socket& Stream::lowest_layer() noexcept +{ + return m_tcp_socket; +} + + +#if REALM_HAVE_OPENSSL + +inline void Stream::ssl_handshake(std::error_code& ec, Want& want) noexcept +{ + auto perform = [this]() noexcept { + switch (m_handshake_type) { + case client: + return do_ssl_connect(); + case server: + return do_ssl_accept(); + } + REALM_ASSERT(false); + return 0; + }; + std::size_t n = ssl_perform(std::move(perform), ec, want); + REALM_ASSERT(n == 0 || n == 1); + if (want == Want::nothing && n == 0 && !ec) { + // End of input on TCP socket + ec = MiscExtErrors::premature_end_of_input; + } +} + +inline std::size_t Stream::ssl_read(char* buffer, std::size_t size, + std::error_code& ec, Want& want) noexcept +{ + auto perform = [this, buffer, size]() noexcept { + return do_ssl_read(buffer, size); + }; + std::size_t n = ssl_perform(std::move(perform), ec, want); + if (want == Want::nothing && n == 0 && !ec) { + // End of input on TCP socket + if (SSL_get_shutdown(m_ssl) & SSL_RECEIVED_SHUTDOWN) { + ec = MiscExtErrors::end_of_input; + } + else { + ec = MiscExtErrors::premature_end_of_input; + } + } + return n; +} + +inline std::size_t Stream::ssl_write(const char* data, std::size_t size, + std::error_code& ec, Want& want) noexcept +{ + // While OpenSSL is able to continue writing after we have received the + // close notify alert fro the remote peer, Apple's Secure Transport API is + // not, so to achieve common behaviour, we make sure that any such attempt + // will result in an `error::broken_pipe` error. + if ((SSL_get_shutdown(m_ssl) & SSL_RECEIVED_SHUTDOWN) != 0) { + ec = error::broken_pipe; + want = Want::nothing; + return 0; + } + auto perform = [this, data, size]() noexcept { + return do_ssl_write(data, size); + }; + std::size_t n = ssl_perform(std::move(perform), ec, want); + if (want == Want::nothing && n == 0 && !ec) { + // End of input on TCP socket + ec = MiscExtErrors::premature_end_of_input; + } + return n; +} + +inline bool Stream::ssl_shutdown(std::error_code& ec, Want& want) noexcept +{ + auto perform = [this]() noexcept { + return do_ssl_shutdown(); + }; + std::size_t n = ssl_perform(std::move(perform), ec, want); + REALM_ASSERT(n == 0 || n == 1); + if (want == Want::nothing && n == 0 && !ec) { + // The first invocation of SSL_shutdown() does not signal completion + // until the shutdown alert has been sent to the peer, or an error + // occurred (does not wait for acknowledgment). + // + // The second invocation (after a completed first invocation) does not + // signal completion until the peers shutdown alert has been received, + // or an error occurred. + // + // It is believed that: + // + // If this is the first time SSL_shutdown() is called, and + // `SSL_get_shutdown() & SSL_SENT_SHUTDOWN` evaluates to nonzero, then a + // zero return value means "partial success" (shutdown alert was sent, + // but the peers shutdown alert was not yet received), and 1 means "full + // success" (peers shutdown alert has already been received). + // + // If this is the first time SSL_shutdown() is called, and + // `SSL_get_shutdown() & SSL_SENT_SHUTDOWN` valuates to zero, then a + // zero return value means "premature end of input", and 1 is supposedly + // not a possibility. + // + // If this is the second time SSL_shutdown() is called (after the first + // call has returned zero), then a zero return value means "premature + // end of input", and 1 means "full success" (peers shutdown alert has + // now been received). + if ((SSL_get_shutdown(m_ssl) & SSL_SENT_SHUTDOWN) == 0) + ec = MiscExtErrors::premature_end_of_input; + } + return (n > 0); +} + +// Provides a homogeneous, and mostly quirks-free interface across the OpenSSL +// operations (handshake, read, write, shutdown). +// +// First of all, if the operation remains incomplete (neither successfully +// completed, nor failed), ssl_perform() will set `ec` to `std::system_error()`, +// `want` to something other than `Want::nothing`, and return zero. Note that +// read and write operations are partial in the sense that they do not need to +// read or write everything before completing successfully. They only need to +// read or write at least one byte to complete successfully. +// +// Such a situation will normally only happen when the underlying TCP socket is +// in nonblocking mode, and the read/write requirements of the operation could +// not be immediately accommodated. However, as is noted in the SSL_write() man +// page, it can also happen in blocking mode (at least while writing). +// +// If an error occurred, ssl_perform() will set `ec` to something other than +// `std::system_error()`, `want` to `Want::nothing`, and return 0. +// +// If no error occurred, and the operation completed (`!ec && want == +// Want::nothing`), then the return value indicates the outcome of the +// operation. +// +// In general, a nonzero value means "full" success, and a zero value means +// "partial" success, however, a zero result can also generally mean "premature +// end of input" / "unclean protocol termination". +// +// Assuming there is no premature end of input, then for reads and writes, the +// returned value is the number of transferred bytes. Zero for read on end of +// input. Never zero for write. For handshake it is always 1. For shutdown it is +// 1 if the peer shutdown alert was already received, otherwise it is zero. +// +// ssl_read() should use `SSL_get_shutdown() & SSL_RECEIVED_SHUTDOWN` to +// distinguish between the two possible meanings of zero. +// +// ssl_shutdown() should use `SSL_get_shutdown() & SSL_SENT_SHUTDOWN` to +// distinguish between the two possible meanings of zero. +template +std::size_t Stream::ssl_perform(Oper oper, std::error_code& ec, Want& want) noexcept +{ + ERR_clear_error(); + m_bio_error_code = std::error_code(); // Success + int ret = oper(); + int ssl_error = SSL_get_error(m_ssl, ret); + int sys_error = int(ERR_get_error()); + + // Guaranteed by the documentation of SSL_get_error() + REALM_ASSERT((ret > 0) == (ssl_error == SSL_ERROR_NONE)); + + REALM_ASSERT(!m_bio_error_code || ssl_error == SSL_ERROR_SYSCALL); + + // Judging from various comments in the man pages, and from experience with + // the API, it seems that, + // + // ret=0, ssl_error=SSL_ERROR_SYSCALL, sys_error=0 + // + // is supposed to be an indicator of "premature end of input" / "unclean + // protocol termination", while + // + // ret=0, ssl_error=SSL_ERROR_ZERO_RETURN + // + // is supposed to be an indicator of the following success conditions: + // + // - Mature end of input / clean protocol termination. + // + // - Successful transmission of the shutdown alert, but no prior reception + // of shutdown alert from peer. + // + // Unfortunately, as is also remarked in various places in the man pages, + // those two success conditions may actually result in `ret=0, + // ssl_error=SSL_ERROR_SYSCALL, sys_error=0` too, and it seems that they + // almost always do. + // + // This means that we cannot properly discriminate between these conditions + // in ssl_perform(), and will have to defer to the caller to interpret the + // situation. Since thay cannot be properly told apart, we report all + // `ret=0, ssl_error=SSL_ERROR_SYSCALL, sys_error=0` and `ret=0, + // ssl_error=SSL_ERROR_ZERO_RETURN` cases as the latter. + switch (ssl_error) { + case SSL_ERROR_NONE: + ec = std::error_code(); // Success + want = Want::nothing; + return std::size_t(ret); // ret > 0 + case SSL_ERROR_ZERO_RETURN: + ec = std::error_code(); // Success + want = Want::nothing; + return 0; + case SSL_ERROR_WANT_READ: + ec = std::error_code(); // Success + want = Want::read; + return 0; + case SSL_ERROR_WANT_WRITE: + ec = std::error_code(); // Success + want = Want::write; + return 0; + case SSL_ERROR_SYSCALL: + if (REALM_UNLIKELY(sys_error != 0)) { + ec = make_basic_system_error_code(sys_error); + } + else if (REALM_UNLIKELY(m_bio_error_code)) { + ec = m_bio_error_code; + } + else if (ret == 0) { + // ret = 0, ssl_eror = SSL_ERROR_SYSCALL, sys_error = 0 + // + // See remarks above! + ec = std::error_code(); // Success + } + else { + // ret = -1, ssl_eror = SSL_ERROR_SYSCALL, sys_error = 0 + // + // This situation arises in OpenSSL version >= 1.1. + // It has been observed in the SSL_connect call if the + // other endpoint terminates the connection during + // SSL_connect. The OpenSSL documentation states + // that ret = -1 implies an underlying BIO error and + // that errno should be consulted. However, + // errno = 0(Undefined error) in the observed case. + // At the moment. we will report + // MiscExtErrors::premature_end_of_input. + // If we see this error case occurring in other situations in + // the future, we will have to update this case. + ec = MiscExtErrors::premature_end_of_input; + } + want = Want::nothing; + return 0; + case SSL_ERROR_SSL: + ec = std::error_code(sys_error, openssl_error_category); + want = Want::nothing; + return 0; + default: + break; + } + // We are not supposed to ever get here + REALM_ASSERT(false); + return 0; +} + +inline int Stream::do_ssl_accept() noexcept +{ + int ret = SSL_accept(m_ssl); + return ret; +} + +inline int Stream::do_ssl_connect() noexcept +{ + int ret = SSL_connect(m_ssl); + return ret; +} + +inline int Stream::do_ssl_read(char* buffer, std::size_t size) noexcept +{ + int size_2 = int(size); + if (size > unsigned(std::numeric_limits::max())) + size_2 = std::size_t(std::numeric_limits::max()); + int ret = SSL_read(m_ssl, buffer, size_2); + return ret; +} + +inline int Stream::do_ssl_write(const char* data, std::size_t size) noexcept +{ + int size_2 = int(size); + if (size > unsigned(std::numeric_limits::max())) + size_2 = std::size_t(std::numeric_limits::max()); + int ret = SSL_write(m_ssl, data, size_2); + return ret; +} + +inline int Stream::do_ssl_shutdown() noexcept +{ + int ret = SSL_shutdown(m_ssl); + return ret; +} + +#elif REALM_HAVE_SECURE_TRANSPORT + +// Provides a homogeneous, and mostly quirks-free interface across the SecureTransport +// operations (handshake, read, write, shutdown). +// +// First of all, if the operation remains incomplete (neither successfully +// completed, nor failed), ssl_perform() will set `ec` to `std::system_error()`, +// `want` to something other than `Want::nothing`, and return zero. +// +// If an error occurred, ssl_perform() will set `ec` to something other than +// `std::system_error()`, `want` to `Want::nothing`, and return 0. +// +// If no error occurred, and the operation completed (`!ec && want == +// Want::nothing`), then the return value indicates the outcome of the +// operation. +// +// In general, a nonzero value means "full" success, and a zero value means +// "partial" success, however, a zero result can also generally mean "premature +// end of input" / "unclean protocol termination". +// +// Assuming there is no premature end of input, then for reads and writes, the +// returned value is the number of transferred bytes. Zero for read on end of +// input. Never zero for write. For handshake it is always 1. For shutdown it is +// 1 if the peer shutdown alert was already received, otherwise it is zero. +template +std::size_t Stream::ssl_perform(Oper oper, std::error_code& ec, Want& want) noexcept +{ + OSStatus result; + std::size_t n; + std::tie(result, n) = oper(); + + if (result == noErr) { + ec = std::error_code(); + want = Want::nothing; + return n; + } + + if (result == errSSLWouldBlock) { + REALM_ASSERT(m_last_operation); + ec = std::error_code(); + want = m_last_operation == BlockingOperation::read ? Want::read : Want::write; + m_last_operation = {}; + return n; + } + + if (result == errSSLClosedGraceful) { + ec = MiscExtErrors::end_of_input; + want = Want::nothing; + return n; + } + + if (result == errSSLClosedAbort || result == errSSLClosedNoNotify) { + ec = MiscExtErrors::premature_end_of_input; + want = Want::nothing; + return n; + } + + if (result == errSecIO) { + // A generic I/O error means something went wrong at a lower level. Use the error + // code we smuggled out of our lower-level functions to provide a more specific error. + REALM_ASSERT(m_last_error); + ec = m_last_error; + want = Want::nothing; + return n; + } + + ec = std::error_code(result, secure_transport_error_category); + want = Want::nothing; + return 0; +} +#endif // REALM_HAVE_OPENSSL / REALM_HAVE_SECURE_TRANSPORT + +} // namespace ssl +} // namespace network +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_NETWORK_SSL_HPP diff --git a/Pods/Realm/include/core/realm/util/optional.hpp b/Pods/Realm/include/core/realm/util/optional.hpp new file mode 100644 index 0000000000..07cada1080 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/optional.hpp @@ -0,0 +1,722 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#pragma once +#ifndef REALM_UTIL_OPTIONAL_HPP +#define REALM_UTIL_OPTIONAL_HPP + +#include +#include + +#include // std::logic_error +#include // std::less + +namespace realm { +namespace util { + +template +class Optional; + +// some() should be the equivalent of the proposed C++17 `make_optional`. +template +Optional some(Args&&...); +template +struct Some; + +// Note: Should conform with the future std::nullopt_t and std::in_place_t. +struct None { + constexpr explicit None(int) + { + } +}; +static constexpr None none{0}; +struct InPlace { + constexpr InPlace() + { + } +}; +static constexpr InPlace in_place; + +// Note: Should conform with the future std::bad_optional_access. +struct BadOptionalAccess : ExceptionWithBacktrace { + using ExceptionWithBacktrace::ExceptionWithBacktrace; +}; + +} // namespace util + +namespace _impl { + +template ::value> +struct OptionalStorage; + +template +struct TypeIsAssignableToOptional { + // Constraints from [optional.object.assign.18] + static const bool value = (std::is_same::type, T>::value && + std::is_constructible::value && std::is_assignable::value); +}; + +} // namespace _impl + +namespace util { + +// Note: Should conform with the future std::optional. +template +class Optional : private _impl::OptionalStorage { +public: + using value_type = T; + + constexpr Optional(); + constexpr Optional(None); + Optional(Optional&& other); + Optional(const Optional& other); + + constexpr Optional(T&& value); + constexpr Optional(const T& value); + + template + constexpr Optional(InPlace tag, Args&&...); + // FIXME: std::optional specifies an std::initializer_list constructor overload as well. + + Optional& operator=(None); + Optional& operator=(Optional&& other); + Optional& operator=(const Optional& other); + + template ::value>::type> + Optional& operator=(U&& value); + + explicit constexpr operator bool() const; + constexpr const T& value() const; // Throws + T& value(); // Throws, FIXME: Can be constexpr with C++14 + constexpr const T& operator*() const; // Throws + T& operator*(); // Throws, FIXME: Can be constexpr with C++14 + constexpr const T* operator->() const; // Throws + T* operator->(); // Throws, FIXME: Can be constexpr with C++14 + + template + constexpr T value_or(U&& value) const &; + + template + T value_or(U&& value) &&; + + void swap(Optional& other); // FIXME: Add noexcept() clause + + template + void emplace(Args&&...); + // FIXME: std::optional specifies an std::initializer_list overload for `emplace` as well. +private: + using Storage = _impl::OptionalStorage; + using Storage::m_engaged; + using Storage::m_value; + + constexpr bool is_engaged() const + { + return m_engaged; + } + void set_engaged(bool b) + { + m_engaged = b; + } + void clear(); +}; + +/// An Optional is functionally equivalent to a bool. +/// Note: C++17 does not (yet) specify this specialization, but it is convenient +/// as a "safer bool", especially in the presence of `fmap`. +/// Disabled for compliance with std::optional. +// template <> +// class Optional { +// public: +// Optional() {} +// Optional(None) {} +// Optional(Optional&&) = default; +// Optional(const Optional&) = default; +// explicit operator bool() const { return m_engaged; } +// private: +// bool m_engaged = false; +// friend struct Some; +// }; + +/// An Optional is a non-owning nullable pointer that throws on dereference. +// FIXME: Visual Studio 2015's constexpr support isn't sufficient to allow Optional to compile +// in constexpr contexts. +template +class Optional { +public: + using value_type = T&; + using target_type = typename std::decay::type; + + constexpr Optional() + { + } + constexpr Optional(None) + { + } // FIXME: Was a delegating constructor, but not fully supported in VS2015 + Optional(const Optional& other) = default; + template + Optional(const Optional& other) + : m_ptr(other.m_ptr) + { + } + template + Optional(std::reference_wrapper ref) + : m_ptr(&ref.get()) + { + } + + constexpr Optional(T& init_value) + : m_ptr(&init_value) + { + } + Optional(T&& value) = delete; // Catches accidental references to rvalue temporaries. + + Optional& operator=(None) + { + m_ptr = nullptr; + return *this; + } + Optional& operator=(const Optional& other) + { + m_ptr = other.m_ptr; + return *this; + } + + template + Optional& operator=(std::reference_wrapper ref) + { + m_ptr = &ref.get(); + return *this; + } + + explicit constexpr operator bool() const + { + return m_ptr; + } + constexpr const target_type& value() const; // Throws + target_type& value(); // Throws + constexpr const target_type& operator*() const + { + return value(); + } + target_type& operator*() + { + return value(); + } + constexpr const target_type* operator->() const + { + return &value(); + } + target_type* operator->() + { + return &value(); + } + + void swap(Optional other); // FIXME: Add noexcept() clause +private: + T* m_ptr = nullptr; + + template + friend class Optional; +}; + + +template +struct RemoveOptional { + using type = T; +}; +template +struct RemoveOptional> { + using type = typename RemoveOptional::type; // Remove recursively +}; + + +/// Implementation: + +template +struct Some { + template + static Optional some(Args&&... args) + { + return Optional{std::forward(args)...}; + } +}; + +/// Disabled for compliance with std::optional. +// template <> +// struct Some { +// static Optional some() +// { +// Optional opt; +// opt.m_engaged = true; +// return opt; +// } +// }; + +template +Optional some(Args&&... args) +{ + return Some::some(std::forward(args)...); +} + + +template +constexpr Optional::Optional() + : Storage(none) +{ +} + +template +constexpr Optional::Optional(None) + : Storage(none) +{ +} + +template +Optional::Optional(Optional&& other) + : Storage(none) +{ + if (other.m_engaged) { + new (&m_value) T(std::move(other.m_value)); + m_engaged = true; + } +} + +template +Optional::Optional(const Optional& other) + : Storage(none) +{ + if (other.m_engaged) { + new (&m_value) T(other.m_value); + m_engaged = true; + } +} + +template +constexpr Optional::Optional(T&& r_value) + : Storage(std::move(r_value)) +{ +} + +template +constexpr Optional::Optional(const T& l_value) + : Storage(l_value) +{ +} + +template +template +constexpr Optional::Optional(InPlace, Args&&... args) + : Storage(std::forward(args)...) +{ +} + +template +void Optional::clear() +{ + if (m_engaged) { + m_value.~T(); + m_engaged = false; + } +} + +template +Optional& Optional::operator=(None) +{ + clear(); + return *this; +} + +template +Optional& Optional::operator=(Optional&& other) +{ + if (m_engaged) { + if (other.m_engaged) { + m_value = std::move(other.m_value); + } + else { + clear(); + } + } + else { + if (other.m_engaged) { + new (&m_value) T(std::move(other.m_value)); + m_engaged = true; + } + } + return *this; +} + +template +Optional& Optional::operator=(const Optional& other) +{ + if (m_engaged) { + if (other.m_engaged) { + m_value = other.m_value; + } + else { + clear(); + } + } + else { + if (other.m_engaged) { + new (&m_value) T(other.m_value); + m_engaged = true; + } + } + return *this; +} + +template +template +Optional& Optional::operator=(U&& r_value) +{ + if (m_engaged) { + m_value = std::forward(r_value); + } + else { + new (&m_value) T(std::forward(r_value)); + m_engaged = true; + } + return *this; +} + +template +constexpr Optional::operator bool() const +{ + return m_engaged; +} + +template +constexpr const T& Optional::value() const +{ + return m_engaged ? m_value : (throw BadOptionalAccess{"bad optional access"}, m_value); +} + +template +T& Optional::value() +{ + if (!m_engaged) { + throw BadOptionalAccess{"bad optional access"}; + } + return m_value; +} + +template +constexpr const typename Optional::target_type& Optional::value() const +{ + return m_ptr ? *m_ptr : (throw BadOptionalAccess{"bad optional access"}, *m_ptr); +} + +template +typename Optional::target_type& Optional::value() +{ + if (!m_ptr) { + throw BadOptionalAccess{"bad optional access"}; + } + return *m_ptr; +} + +template +constexpr const T& Optional::operator*() const +{ + // Note: This differs from std::optional, which doesn't throw. + return value(); +} + +template +T& Optional::operator*() +{ + // Note: This differs from std::optional, which doesn't throw. + return value(); +} + +template +constexpr const T* Optional::operator->() const +{ + // Note: This differs from std::optional, which doesn't throw. + return &value(); +} + +template +T* Optional::operator->() +{ + // Note: This differs from std::optional, which doesn't throw. + return &value(); +} + +template +template +constexpr T Optional::value_or(U&& otherwise) const & +{ + return m_engaged ? T{m_value} : T{std::forward(otherwise)}; +} + +template +template +T Optional::value_or(U&& otherwise) && +{ + if (is_engaged()) { + return T(std::move(m_value)); + } + else { + return T(std::forward(otherwise)); + } +} + +template +void Optional::swap(Optional& other) +{ + // FIXME: This might be optimizable. + Optional tmp = std::move(other); + other = std::move(*this); + *this = std::move(tmp); +} + +template +template +void Optional::emplace(Args&&... args) +{ + clear(); + new (&m_value) T(std::forward(args)...); + m_engaged = true; +} + + +template +constexpr Optional::type> make_optional(T&& value) +{ + using Type = typename std::decay::type; + return some(std::forward(value)); +} + +template +bool operator==(const Optional& lhs, const Optional& rhs) +{ + if (!lhs && !rhs) { + return true; + } + if (lhs && rhs) { + return *lhs == *rhs; + } + return false; +} + +template +bool operator!=(const Optional& lhs, const Optional& rhs) +{ + return !(lhs == rhs); +} + +template +bool operator<(const Optional& lhs, const Optional& rhs) +{ + if (!rhs) { + return false; + } + if (!lhs) { + return true; + } + return std::less{}(*lhs, *rhs); +} + +template +bool operator>(const util::Optional& lhs, const util::Optional& rhs) +{ + if (!lhs) { + return false; + } + if (!rhs) { + return true; + } + return std::greater{}(*lhs, *rhs); +} + +template +bool operator==(const Optional& lhs, None) +{ + return !bool(lhs); +} + +template +bool operator!=(const Optional& lhs, None) +{ + return bool(lhs); +} + +template +bool operator<(const Optional& lhs, None) +{ + static_cast(lhs); + return false; +} + +template +bool operator==(None, const Optional& rhs) +{ + return !bool(rhs); +} + +template +bool operator!=(None, const Optional& rhs) +{ + return bool(rhs); +} + +template +bool operator<(None, const Optional& rhs) +{ + return bool(rhs); +} + +template +bool operator==(const Optional& lhs, const U& rhs) +{ + return lhs ? *lhs == rhs : false; +} + +template +bool operator<(const Optional& lhs, const T& rhs) +{ + return lhs ? std::less{}(*lhs, rhs) : true; +} + +template +bool operator==(const T& lhs, const Optional& rhs) +{ + return rhs ? lhs == *rhs : false; +} + +template +bool operator<(const T& lhs, const Optional& rhs) +{ + return rhs ? std::less{}(lhs, *rhs) : false; +} + +template +auto operator>>(Optional lhs, F&& rhs) -> decltype(fmap(lhs, std::forward(rhs))) +{ + return fmap(lhs, std::forward(rhs)); +} + +template +OS& operator<<(OS& os, const Optional& rhs) +{ + if (rhs) { + os << "some(" << *rhs << ")"; + } + else { + os << "none"; + } + return os; +} + +template +T unwrap(T&& value) +{ + return value; +} + +template +T unwrap(util::Optional&& value) +{ + return *value; +} + +template +T unwrap(const util::Optional& value) +{ + return *value; +} + +template +T unwrap(util::Optional& value) +{ + return *value; +} + +} // namespace util + +namespace _impl { + +// T is trivially destructible. +template +struct OptionalStorage { + union { + T m_value; + char m_null_state; + }; + bool m_engaged = false; + + constexpr OptionalStorage(realm::util::None) + : m_null_state() + { + } + constexpr OptionalStorage(T&& value) + : m_value(std::move(value)) + , m_engaged(true) + { + } + + template + constexpr OptionalStorage(Args&&... args) + : m_value(args...) + , m_engaged(true) + { + } +}; + +// T is not trivially destructible. +template +struct OptionalStorage { + union { + T m_value; + char m_null_state; + }; + bool m_engaged = false; + + constexpr OptionalStorage(realm::util::None) + : m_null_state() + { + } + constexpr OptionalStorage(T&& value) + : m_value(std::move(value)) + , m_engaged(true) + { + } + + template + constexpr OptionalStorage(Args&&... args) + : m_value(args...) + , m_engaged(true) + { + } + + ~OptionalStorage() + { + if (m_engaged) + m_value.~T(); + } +}; + +} // namespace _impl + +using util::none; + +} // namespace realm + +#endif // REALM_UTIL_OPTIONAL_HPP diff --git a/Pods/Realm/include/core/realm/util/overload.hpp b/Pods/Realm/include/core/realm/util/overload.hpp new file mode 100644 index 0000000000..49188ae132 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/overload.hpp @@ -0,0 +1,70 @@ +/************************************************************************* + * + * Copyright 2017 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_OVERLOAD_HPP +#define REALM_UTIL_OVERLOAD_HPP + +#include + +namespace realm { + +namespace _impl { + +template +struct Overloaded; + +} // namespace _impl + + +namespace util { + +// Declare an overload set using lambdas or other function objects. +// A minimal version of C++ Library Evolution Working Group proposal P0051R2. + +template +_impl::Overloaded overload(Fns&&... f) +{ + return _impl::Overloaded(std::forward(f)...); +} + +} // namespace util + + +namespace _impl { + +template +struct Overloaded : Fn, Overloaded { + template + Overloaded(U&& fn, Rest&&... rest) : Fn(std::forward(fn)), Overloaded(std::forward(rest)...) { } + + using Fn::operator(); + using Overloaded::operator(); +}; + +template +struct Overloaded : Fn { + template + Overloaded(U&& fn) : Fn(std::forward(fn)) { } + + using Fn::operator(); +}; + +} // namespace _impl +} // namespace realm + +#endif // REALM_UTIL_OVERLOAD_HPP diff --git a/Pods/Realm/include/core/realm/util/parent_dir.hpp b/Pods/Realm/include/core/realm/util/parent_dir.hpp new file mode 100644 index 0000000000..0e74e22756 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/parent_dir.hpp @@ -0,0 +1,37 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_UTIL_PARENT_DIR_HPP +#define REALM_UTIL_PARENT_DIR_HPP + +#include + +namespace realm { +namespace util { + +/// Same effect as std::filesystem::path::parent_path(). +/// +/// FIXME: This function ought to be moved to in the +/// realm-core repository. +std::string parent_dir(const std::string& path); + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_PARENT_DIR_HPP diff --git a/Pods/Realm/include/core/realm/util/priority_queue.hpp b/Pods/Realm/include/core/realm/util/priority_queue.hpp new file mode 100644 index 0000000000..a2a28c89d6 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/priority_queue.hpp @@ -0,0 +1,304 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + + +#pragma once +#ifndef REALM_UTIL_PRIORITY_QUEUE_HPP +#define REALM_UTIL_PRIORITY_QUEUE_HPP + +#include +#include +#include + +namespace realm { +namespace util { + + +/// PriorityQueue corresponds exactly to `std::priority_queue`, but has the extra feature +/// of allowing iteration and erasure of elements in the queue. +/// +/// PriorityQueue only allows const access to its elements, because non-const access +/// would open up the risk of changing the ordering of the elements. +/// +/// Note: As opposed to `std::priority_queue`, this does not store elements in a heap +/// internally. Instead, elements are stored in sorted order. Users of this class are +/// allowed to operate on this assumption. +template , class Compare = std::less> +class PriorityQueue : private Compare { +public: + using container_type = Container; + using value_type = typename Container::value_type; + using size_type = typename Container::size_type; + using reference = typename Container::reference; + using const_reference = typename Container::const_reference; + using const_reverse_iterator = typename Container::const_reverse_iterator; + using const_iterator = typename Container::const_iterator; + + //@{ + /// Construct a PriorityQueue, optionally providing a comparator object. + PriorityQueue(const Compare& comparator, const Container& cont); + + explicit PriorityQueue(const Compare& comparator = Compare{}, Container&& cont = Container{}); + + template + PriorityQueue(InputIt first, InputIt last, const Compare& comparator, const Container& cont); + + template + PriorityQueue(InputIt first, InputIt last, const Compare& comparator = Compare{}, Container&& cont = Container{}); + //@} + // Skipping Allocator-specific template constructors. + + PriorityQueue(const PriorityQueue&) = default; + PriorityQueue(PriorityQueue&&) = default; + PriorityQueue& operator=(const PriorityQueue&) = default; + PriorityQueue& operator=(PriorityQueue&&) = default; + + bool empty() const; + size_type size() const; + + //@{ + /// Push an element to the priority queue. + /// + /// If insertion to the underlying `Container` invalidates + /// iterators and references, any iterators and references into this + /// priority queue are also invalidated. By default, this is the case. + void push(const T& value); + void push(T&& value); + //@} + + /// Pop the largest element from the priority queue. + /// + /// If `pop_back` on the underlying `Container` invalidates + /// iterators and references, any iterators and reference into this + /// priority queue are also invalidated. By default, this is *NOT* the case. + /// + /// Calling `pop()` on an empty priority queue is undefined. + void pop(); + + /// Return a reference to the largest element of the priority queue. + /// + /// Calling `top()` on an empty priority queue is undefined. + const_reference top() const; + + /// Pop the top of the queue and return it by moving it out of the queue. + /// + /// Note: This method does not exist in `std::priority_queue`. + /// + /// Calling `pop_top()` on an empty priorty queue is undefined. + value_type pop_top(); + + // FIXME: emplace() deliberately omitted for simplicity. + + /// Swap the contents of this priority queue with the contents of \a other. + void swap(PriorityQueue& other); + + // Not in std::priority_queue: + + /// Return an iterator to the beginning of the queue (smallest element first). + const_iterator begin() const; + + /// Return an iterator to the end of the queue (largest element last); + const_iterator end() const; + + /// Return a reverse iterator into the priority queue (largest element first). + const_reverse_iterator rbegin() const; + + /// Return a reverse iterator representing the end of the priority queue (smallest element last). + const_reverse_iterator rend() const; + + /// Erase element pointed to by \a it. + /// + /// Note: This function differs from `std::priority_queue` by returning the erased + /// element using move semantics. + /// + /// Calling `erase()` with a beyond-end iterator (such as what is returned by `end()`) + /// is undefined. + value_type erase(const_iterator it); + + /// Remove all elements from the priority queue. + void clear(); + + /// Calls `reserve()` on the underlying `Container`. + void reserve(size_type); + +private: + Container m_queue; + + const Compare& compare() const; + Compare& compare(); +}; + + +/// Implementation + +template +PriorityQueue::PriorityQueue(const Compare& comparator, const Container& cont) + : Compare(comparator) + , m_queue(cont) +{ +} + +template +PriorityQueue::PriorityQueue(const Compare& comparator, Container&& cont) + : Compare(comparator) + , m_queue(std::move(cont)) +{ +} + +template +template +PriorityQueue::PriorityQueue(InputIt first, InputIt last, const Compare& comparator, + const Container& cont) + : Compare(comparator) + , m_queue(cont) +{ + for (auto it = first; it != last; ++it) { + push(*it); + } +} + +template +template +PriorityQueue::PriorityQueue(InputIt first, InputIt last, const Compare& comparator, + Container&& cont) + : Compare(comparator) + , m_queue(std::move(cont)) +{ + for (auto it = first; it != last; ++it) { + push(*it); + } +} + +template +typename PriorityQueue::size_type PriorityQueue::size() const +{ + return m_queue.size(); +} + +template +bool PriorityQueue::empty() const +{ + return m_queue.empty(); +} + +template +void PriorityQueue::push(const T& element) +{ + auto it = std::lower_bound(m_queue.begin(), m_queue.end(), element, compare()); + m_queue.insert(it, element); +} + +template +void PriorityQueue::push(T&& element) +{ + auto it = std::lower_bound(m_queue.begin(), m_queue.end(), element, compare()); + m_queue.insert(it, std::move(element)); +} + +template +void PriorityQueue::pop() +{ + m_queue.pop_back(); +} + +template +typename PriorityQueue::const_reference PriorityQueue::top() const +{ + return m_queue.back(); +} + +template +typename PriorityQueue::value_type PriorityQueue::pop_top() +{ + value_type value = std::move(m_queue.back()); + m_queue.pop_back(); + return value; +} + +template +Compare& PriorityQueue::compare() +{ + return *this; +} + +template +const Compare& PriorityQueue::compare() const +{ + return *this; +} + +template +typename PriorityQueue::const_iterator PriorityQueue::begin() const +{ + return m_queue.begin(); +} + +template +typename PriorityQueue::const_iterator PriorityQueue::end() const +{ + return m_queue.end(); +} + +template +typename PriorityQueue::const_reverse_iterator +PriorityQueue::rbegin() const +{ + return m_queue.rbegin(); +} + +template +typename PriorityQueue::const_reverse_iterator +PriorityQueue::rend() const +{ + return m_queue.rend(); +} + +template +typename PriorityQueue::value_type +PriorityQueue::erase(const_iterator it) +{ + // Convert to non-const iterator: + auto non_const_iterator = m_queue.begin() + (it - m_queue.begin()); + value_type value = std::move(*non_const_iterator); + m_queue.erase(non_const_iterator); + return value; +} + +template +void PriorityQueue::clear() +{ + m_queue.clear(); +} + +template +void PriorityQueue::reserve(size_type sz) +{ + m_queue.reserve(sz); +} + +template +void PriorityQueue::swap(PriorityQueue& other) +{ + using std::swap; + swap(m_queue, other.m_queue); + swap(compare(), other.compare()); +} +} +} + +#endif // REALM_UTIL_PRIORITY_QUEUE_HPP diff --git a/Pods/Realm/include/core/realm/util/random.hpp b/Pods/Realm/include/core/realm/util/random.hpp new file mode 100644 index 0000000000..d0c7fe9339 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/random.hpp @@ -0,0 +1,137 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_RANDOM_HPP +#define REALM_UTIL_RANDOM_HPP + +#include +#include +#include +#include +#include +#include + +namespace realm { +namespace util { + +/// Perform a nondeterministc seeding of the specified pseudo random number +/// generator. +/// +/// \tparam Engine A type that satisfies UniformRandomBitGenerator as defined by +/// the C++ standard. +/// +/// \tparam state_size The number of words of type Engine::result_type that make +/// up the engine state. +/// +/// Thread-safe. +/// +/// FIXME: Move this to core repo, as it is generally useful. +template +void seed_prng_nondeterministically(Engine&); + +template +std::string generate_random_lower_case_string(Engine& engine, size_t size); + + +// Implementation + +} // namespace util + +namespace _impl { + +void get_extra_seed_entropy(unsigned int& extra_entropy_1, unsigned int& extra_entropy_2, + unsigned int& extra_entropy_3); + +} // namespace _impl + +namespace util { + +template void seed_prng_nondeterministically(Engine& engine) +{ + // This implementation was informed and inspired by + // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0205r0.html. + // + // The number of bits of entropy needed is `state_size * + // std::numeric_limits::digits` (assuming that + // the engine uses all available bits in each word). + // + // Each invocation of `std::random_device::operator()` gives us + // `std::numeric_limits::digits` bits (assuming maximum + // entropy). Note that `std::random_device::result_type` must be `unsigned + // int`, `std::random_device::min()` must return zero, and + // `std::random_device::max()` must return `std::numeric_limits::max()`. + // + // Ideally, we could have used `std::random_device::entropy()` as the actual + // number of bits of entropy produced per invocation of + // `std::random_device::operator()`, however, it is incorrectly implemented + // on many platform. Also, it is supposed to return zero when + // `std::random_device` is just a PRNG, but that would leave us with no way + // to continue. + // + // When the actual entropy from `std::random_device` is less than maximum, + // the seeding will be less than optimal. For example, if the actual entropy + // is only half of the maximum, then the seeding will only produce half the + // entrpy that it ought to, but that will generally still be a good seeding. + // + // For the (assumed) rare cases where `std::random_device` is a PRGN that is + // not nondeterministically seeded, we include a bit of extra entropy taken + // from such places as the current time and the ID of the executing process + // (when available). + + constexpr long seed_bits_needed = state_size * + long(std::numeric_limits::digits); + constexpr int seed_bits_per_device_invocation = + std::numeric_limits::digits; + constexpr size_t seed_words_needed = + size_t((seed_bits_needed + (seed_bits_per_device_invocation - 1)) / + seed_bits_per_device_invocation); // Rounding up + constexpr int num_extra = 3; + std::array seed_values; + std::random_device rnddev; + std::generate(seed_values.begin(), seed_values.end()-num_extra, std::ref(rnddev)); + + unsigned int extra_entropy[3]; + _impl::get_extra_seed_entropy(extra_entropy[0], extra_entropy[1], extra_entropy[2]); + static_assert(num_extra == sizeof extra_entropy / sizeof extra_entropy[0], "Mismatch"); + std::copy(extra_entropy, extra_entropy+num_extra, seed_values.end()-num_extra); + + std::seed_seq seed_seq(seed_values.begin(), seed_values.end()); + engine.seed(seed_seq); +} + +template +std::string generate_random_lower_case_string(Engine& engine, size_t size) +{ + std::uniform_int_distribution dist(0, 25); + std::string str; + str.reserve(size); + for (size_t i = 0; i < size; ++i) { + short val = dist(engine); + char c = 'a' + char(val); + str.push_back(c); + } + return str; +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_RANDOM_HPP diff --git a/Pods/Realm/include/core/realm/util/resource_limits.hpp b/Pods/Realm/include/core/realm/util/resource_limits.hpp new file mode 100644 index 0000000000..858624aa5a --- /dev/null +++ b/Pods/Realm/include/core/realm/util/resource_limits.hpp @@ -0,0 +1,83 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_UTIL_RESOURCE_LIMITS_HPP +#define REALM_UTIL_RESOURCE_LIMITS_HPP + +namespace realm { +namespace util { + + +enum class Resource { + /// The maximum size, in bytes, of the core file produced when the memory + /// image of this process is dumped. If the memory image is larger than the + /// limit, the core file will not be created. Same as `RLIMIT_CORE` of + /// POSIX. + core_dump_size, + + /// The maximum CPU time, in seconds, available to this process. If the + /// limit is exceeded, the process will be killed. Same as `RLIMIT_CPU` of + /// POSIX. + cpu_time, + + /// The maximum size, in bytes, of the data segment of this process. If the + /// limit is exceede, std::malloc() will fail with `errno` equal to + /// `ENOMEM`. Same as `RLIMIT_DATA` of POSIX. + data_segment_size, + + /// The maximum size, in bytes, of a file that is modified by this + /// process. If the limit is exceede, the process will be killed. Same as + /// `RLIMIT_FSIZE` of POSIX. + file_size, + + /// One plus the maximum file descriptor value that can be opened by this + /// process. Same as `RLIMIT_NOFILE` of POSIX. + num_open_files, + + /// The maximum size, in bytes, of the stack of the main thread of this + /// process. If the limit is exceede, the process is killed. Same as + /// `RLIMIT_STACK` of POSIX. + stack_size, + + /// The maximum size, in bytes, of the process's virtual memory (address + /// space). If the limit is exceeded due to heap allocation, std::malloc() + /// will fail with `errno` equal to `ENOMEM`. If the limit is exceeded due + /// to explicit memory mapping, mmap() will fail with `errno` equal to + /// `ENOMEM`. If the limit is exceeded due to stack expansion, the process + /// will be killed. Same as `RLIMIT_AS` of POSIX. + virtual_memory_size +}; + + +bool system_has_rlimit(Resource) noexcept; + + +//@{ +/// Get or set resouce limits. A negative value means 'unlimited', both when +/// getting and when setting. +long get_hard_rlimit(Resource); +long get_soft_rlimit(Resource); +void set_soft_rlimit(Resource, long value); +//@} + + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_RESOURCE_LIMITS_HPP diff --git a/Pods/Realm/include/core/realm/util/safe_int_ops.hpp b/Pods/Realm/include/core/realm/util/safe_int_ops.hpp new file mode 100644 index 0000000000..15030add4d --- /dev/null +++ b/Pods/Realm/include/core/realm/util/safe_int_ops.hpp @@ -0,0 +1,623 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_SAFE_INT_OPS_HPP +#define REALM_UTIL_SAFE_INT_OPS_HPP + +#ifdef _WIN32 +#undef max // collides with numeric_limits::max called later in this header file +#undef min // collides with numeric_limits::min called later in this header file +#endif + +#include + +#include +#include +#include + +namespace realm { +namespace util { + + +/// Perform integral or floating-point promotion on the argument. This +/// is useful for example when printing a number of arbitrary numeric +/// type to 'stdout', since it will convert values of character-like +/// types to regular integer types, which will then be printed as +/// numbers rather characters. +template +typename Promote::type promote(T value) noexcept; + + +/// This function allows you to test for a negative value in any +/// numeric type, even when the type is unsigned. Normally, when the +/// type is unsigned, such a test will produce a compiler warning. +template +bool is_negative(T value) noexcept; + + +/// Cast the specified value to the specified unsigned type reducing +/// the value (or in case of negative values, the two's complement +/// representation) modulo `2**N` where `N` is the number of value +/// bits (or digits) in the unsigned target type. This is usefull in +/// cases where the target type may be `bool`, but need not be `bool`. +template +To cast_to_unsigned(From) noexcept; + + +//@{ + +/// Compare two integers of the same, or of different type, and +/// produce the expected result according to the natural +/// interpretation of the operation. +/// +/// Note that in general a standard comparison between a signed and an +/// unsigned integer type is unsafe, and it often generates a compiler +/// warning. An example is a 'less than' comparison between a negative +/// value of type 'int' and a small positive value of type +/// 'unsigned'. In this case the negative value will be converted to +/// 'unsigned' producing a large positive value which, in turn, will +/// lead to the counter intuitive result of 'false'. +/// +/// Please note that these operation incur absolutely no overhead when +/// the two types have the same signedness. +/// +/// These functions check at compile time that both types have valid +/// specializations of std::numeric_limits<> and that both are indeed +/// integers. +/// +/// These functions make absolutely no assumptions about the platform +/// except that it complies with at least C++03. + +template +inline bool int_equal_to(A, B) noexcept; +template +inline bool int_not_equal_to(A, B) noexcept; +template +inline bool int_less_than(A, B) noexcept; +template +inline bool int_less_than_or_equal(A, B) noexcept; +template +inline bool int_greater_than(A, B) noexcept; +template +inline bool int_greater_than_or_equal(A, B) noexcept; + +//@} + + +//@{ + +/// Check for overflow in integer variable `lval` while adding integer +/// `rval` to it, or while subtracting integer `rval` from it. Returns +/// true on positive or negative overflow. +/// +/// Both `lval` and `rval` must be of an integer type for which a +/// specialization of std::numeric_limits<> exists. The two types need +/// not be the same, in particular, one can be signed and the other +/// one can be unsigned. +/// +/// These functions are especially well suited for cases where \a rval +/// is a compile-time constant. +/// +/// These functions check at compile time that both types have valid +/// specializations of std::numeric_limits<> and that both are indeed +/// integers. +/// +/// These functions make absolutely no assumptions about the platform +/// except that it complies with at least C++03. + +template +inline bool int_add_with_overflow_detect(L& lval, R rval) noexcept; + +template +inline bool int_subtract_with_overflow_detect(L& lval, R rval) noexcept; + +//@} + + +/// Check for positive overflow when multiplying two positive integers +/// of the same, or of different type. Returns true on overflow. +/// +/// \param lval Must not be negative. Both signed and unsigned types +/// can be used. +/// +/// \param rval Must be stricly greater than zero. Both signed and +/// unsigned types can be used. +/// +/// This function is especially well suited for cases where \a rval is +/// a compile-time constant. +/// +/// This function checks at compile time that both types have valid +/// specializations of std::numeric_limits<> and that both are indeed +/// integers. +/// +/// This function makes absolutely no assumptions about the platform +/// except that it complies with at least C++03. +template +inline bool int_multiply_with_overflow_detect(L& lval, R rval) noexcept; + + +/// Checks for positive overflow when performing a bitwise shift to +/// the left on a non-negative value of arbitrary integer +/// type. Returns true on overflow. +/// +/// \param lval Must not be negative. Both signed and unsigned types +/// can be used. +/// +/// \param i Must be non-negative and such that L(1)>>i has a +/// value that is defined by the C++03 standard. In particular, the +/// value of i must not exceed the number of bits of storage type T as +/// shifting by this amount is not defined by the standard. +/// +/// This function makes absolutely no assumptions about the platform +/// except that it complies with at least C++03. +template +inline bool int_shift_left_with_overflow_detect(T& lval, int i) noexcept; + + +//@{ + +/// Check for overflow when casting an integer value from one type to +/// another. While the first function is a mere check, the second one +/// also carries out the cast, but only when there is no +/// overflow. Both return true on overflow. +/// +/// These functions check at compile time that both types have valid +/// specializations of std::numeric_limits<> and that both are indeed +/// integers. +/// +/// These functions make absolutely no assumptions about the platform +/// except that it complies with at least C++03. + +template +bool int_cast_has_overflow(From from) noexcept; + +template +bool int_cast_with_overflow_detect(From from, To& to) noexcept; + +//@} + + +/// Convert negative values from two's complement representation to the +/// platforms native representation. +/// +/// If `To` is an unsigned type, this function does nothing beyond casting the +/// specified value to `To`. Otherwise, `To` is a signed type, and negative +/// values will be converted from two's complement representation in unsigned +/// `From` to the platforms native representation in `To`. +/// +/// For signed `To` the result is well-defined if, and only if the value with +/// the specified two's complement representation is representable in the +/// specified signed type. While this is generally the case when using +/// corresponding signed/unsigned type pairs, it is not guaranteed by the +/// standard. However, if you know that the signed type has at least as many +/// value bits as the unsigned type, then the result is always +/// well-defined. Note that a 'value bit' in this context is the same as a +/// 'digit' from the point of view of `std::numeric_limits`. +/// +/// On platforms that use two's complement representation of negative values, +/// this function is expected to be completely optimized away. This has been +/// observed to be true with both GCC 4.8 and Clang 3.2. +/// +/// Note that the **opposite** direction (from the platforms native +/// representation to two's complement) is trivially handled by casting the +/// signed value to a value of a sufficiently wide unsigned integer type. An +/// unsigned type will be sufficiently wide if it has at least one more value +/// bit than the signed type. +/// +/// Interestingly, the C++ language offers no direct way of doing what this +/// function does, yet, this function is implemented in a way that makes no +/// assumption about the underlying platform except what is guaranteed by C++11. +/// +/// \tparam From The unsigned type used to store the two's complement +/// representation. +/// +/// \tparam To A signed or unsigned integer type. +template +To from_twos_compl(From twos_compl) noexcept; + + +// Implementation: + +template +inline typename Promote::type promote(T value) noexcept +{ + typedef typename Promote::type promoted_type; + promoted_type value_2 = promoted_type(value); + return value_2; +} + +} // namespace util + +namespace _impl { + +template +struct IsNegative { + static bool test(T value) noexcept + { + return value < 0; + } +}; +template +struct IsNegative { + static bool test(T) noexcept + { + return false; + } +}; + +template +struct CastToUnsigned { + template + static To cast(From value) noexcept + { + return To(value); + } +}; +template <> +struct CastToUnsigned { + template + static bool cast(From value) noexcept + { + return bool(unsigned(value) & 1); + } +}; + +template +struct SafeIntBinopsImpl { +}; + +// (unsigned, unsigned) (all size combinations) +// +// This implementation utilizes the fact that overflow in unsigned +// arithmetic is guaranteed to be handled by reduction modulo 2**N +// where N is the number of bits in the unsigned type. The purpose of +// the bitwise 'and' with lim_l::max() is to make a cast to bool +// behave the same way as casts to other unsigned integer types. +// Finally, this implementation uses the fact that if modular addition +// overflows, then the result must be a value that is less than both +// operands. Also, if modular subtraction overflows, then the result +// must be a value that is greater than the first operand. +template +struct SafeIntBinopsImpl { + typedef std::numeric_limits lim_l; + typedef std::numeric_limits lim_r; + static const int needed_bits_l = lim_l::digits; + static const int needed_bits_r = lim_r::digits; + static const int needed_bits = needed_bits_l >= needed_bits_r ? needed_bits_l : needed_bits_r; + typedef typename util::FastestUnsigned::type common_unsigned; + static bool equal(L l, R r) noexcept + { + return common_unsigned(l) == common_unsigned(r); + } + static bool less(L l, R r) noexcept + { + return common_unsigned(l) < common_unsigned(r); + } + static bool add(L& lval, R rval) noexcept + { + L lval_2 = util::cast_to_unsigned(lval + rval); + bool overflow = common_unsigned(lval_2) < common_unsigned(rval); + if (REALM_UNLIKELY(overflow)) + return true; + lval = lval_2; + return false; + } + static bool sub(L& lval, R rval) noexcept + { + common_unsigned lval_2 = common_unsigned(lval) - common_unsigned(rval); + bool overflow = lval_2 > common_unsigned(lval); + if (REALM_UNLIKELY(overflow)) + return true; + lval = util::cast_to_unsigned(lval_2); + return false; + } +}; + +// (unsigned, signed) (all size combinations) +template +struct SafeIntBinopsImpl { + typedef std::numeric_limits lim_l; + typedef std::numeric_limits lim_r; + static const int needed_bits_l = lim_l::digits; + static const int needed_bits_r = lim_r::digits + 1; + static const int needed_bits = needed_bits_l >= needed_bits_r ? needed_bits_l : needed_bits_r; + typedef typename util::FastestUnsigned::type common_unsigned; + typedef std::numeric_limits lim_cu; + static bool equal(L l, R r) noexcept + { + return (lim_l::digits > lim_r::digits) ? r >= 0 && l == util::cast_to_unsigned(r) : R(l) == r; + } + static bool less(L l, R r) noexcept + { + return (lim_l::digits > lim_r::digits) ? r >= 0 && l < util::cast_to_unsigned(r) : R(l) < r; + } + static bool add(L& lval, R rval) noexcept + { + common_unsigned lval_2 = lval + common_unsigned(rval); + bool overflow; + if (lim_l::digits < lim_cu::digits) { + overflow = common_unsigned(lval_2) > common_unsigned(lim_l::max()); + } + else { + overflow = (lval_2 < common_unsigned(lval)) == (rval >= 0); + } + if (REALM_UNLIKELY(overflow)) + return true; + lval = util::cast_to_unsigned(lval_2); + return false; + } + static bool sub(L& lval, R rval) noexcept + { + common_unsigned lval_2 = lval - common_unsigned(rval); + bool overflow; + if (lim_l::digits < lim_cu::digits) { + overflow = common_unsigned(lval_2) > common_unsigned(lim_l::max()); + } + else { + overflow = (common_unsigned(lval_2) > common_unsigned(lval)) == (rval >= 0); + } + if (REALM_UNLIKELY(overflow)) + return true; + lval = util::cast_to_unsigned(lval_2); + return false; + } +}; + +// (signed, unsigned) (all size combinations) +template +struct SafeIntBinopsImpl { + typedef std::numeric_limits lim_l; + typedef std::numeric_limits lim_r; + static const int needed_bits_l = lim_l::digits + 1; + static const int needed_bits_r = lim_r::digits; + static const int needed_bits = needed_bits_l >= needed_bits_r ? needed_bits_l : needed_bits_r; + typedef typename util::FastestUnsigned::type common_unsigned; + static bool equal(L l, R r) noexcept + { + return (lim_l::digits < lim_r::digits) ? l >= 0 && util::cast_to_unsigned(l) == r : l == L(r); + } + static bool less(L l, R r) noexcept + { + return (lim_l::digits < lim_r::digits) ? l < 0 || util::cast_to_unsigned(l) < r : l < L(r); + } + static bool add(L& lval, R rval) noexcept + { + common_unsigned max_add = common_unsigned(lim_l::max()) - common_unsigned(lval); + bool overflow = common_unsigned(rval) > max_add; + if (REALM_UNLIKELY(overflow)) + return true; + lval = util::from_twos_compl(common_unsigned(lval) + rval); + return false; + } + static bool sub(L& lval, R rval) noexcept + { + common_unsigned max_sub = common_unsigned(lval) - common_unsigned(lim_l::min()); + bool overflow = common_unsigned(rval) > max_sub; + if (REALM_UNLIKELY(overflow)) + return true; + lval = util::from_twos_compl(common_unsigned(lval) - rval); + return false; + } +}; + +// (signed, signed) (all size combinations) +template +struct SafeIntBinopsImpl { + typedef std::numeric_limits lim_l; + static bool equal(L l, R r) noexcept + { + return l == r; + } + static bool less(L l, R r) noexcept + { + return l < r; + } + static bool add(L& lval, R rval) noexcept + { + // Note that both subtractions below occur in a signed type + // that is at least as wide as both of the two types. Note + // also that any signed type guarantees that there is no + // overflow when subtracting two negative values or two + // non-negative value. See C99 (adopted as subset of C++11) + // section 6.2.6.2 "Integer types" paragraph 2. + if (rval < 0) { + if (REALM_UNLIKELY(lval < lim_l::min() - rval)) + return true; + } + else { + if (REALM_UNLIKELY(lval > lim_l::max() - rval)) + return true; + } + // The following statement has exactly the same effect as + // `lval += rval`. + lval = L(lval + rval); + return false; + } + static bool sub(L& lval, R rval) noexcept + { + // Note that both subtractions below occur in a signed type + // that is at least as wide as both of the two types. Note + // also that there can be no overflow when adding a negative + // value to a non-negative value, or when adding a + // non-negative value to a negative one. + if (rval < 0) { + if (REALM_UNLIKELY(lval > lim_l::max() + rval)) + return true; + } + else { + if (REALM_UNLIKELY(lval < lim_l::min() + rval)) + return true; + } + // The following statement has exactly the same effect as + // `lval += rval`. + lval = L(lval - rval); + return false; + } +}; + +template +struct SafeIntBinops : SafeIntBinopsImpl::is_signed, std::numeric_limits::is_signed> { + typedef std::numeric_limits lim_l; + typedef std::numeric_limits lim_r; + static_assert(lim_l::is_specialized && lim_r::is_specialized, + "std::numeric_limits<> must be specialized for both types"); + static_assert(lim_l::is_integer && lim_r::is_integer, "Both types must be integers"); +}; + +} // namespace _impl + +namespace util { + +template +inline bool is_negative(T value) noexcept +{ + return _impl::IsNegative::is_signed>::test(value); +} + +template +inline To cast_to_unsigned(From value) noexcept +{ + return _impl::CastToUnsigned::cast(value); +} + +template +inline bool int_equal_to(A a, B b) noexcept +{ + return _impl::SafeIntBinops::equal(a, b); +} + +template +inline bool int_not_equal_to(A a, B b) noexcept +{ + return !_impl::SafeIntBinops::equal(a, b); +} + +template +inline bool int_less_than(A a, B b) noexcept +{ + return _impl::SafeIntBinops::less(a, b); +} + +template +inline bool int_less_than_or_equal(A a, B b) noexcept +{ + return !_impl::SafeIntBinops::less(b, a); // Not greater than +} + +template +inline bool int_greater_than(A a, B b) noexcept +{ + return _impl::SafeIntBinops::less(b, a); +} + +template +inline bool int_greater_than_or_equal(A a, B b) noexcept +{ + return !_impl::SafeIntBinops::less(a, b); // Not less than +} + +template +inline bool int_add_with_overflow_detect(L& lval, R rval) noexcept +{ + return _impl::SafeIntBinops::add(lval, rval); +} + +template +inline bool int_subtract_with_overflow_detect(L& lval, R rval) noexcept +{ + return _impl::SafeIntBinops::sub(lval, rval); +} + +template +inline bool int_multiply_with_overflow_detect(L& lval, R rval) noexcept +{ + // FIXME: Check if the following optimizes better (if it works at all): + // L lval_2 = L(lval * rval); + // bool overflow = rval != 0 && (lval_2 / rval) != lval; + typedef std::numeric_limits lim_l; + typedef std::numeric_limits lim_r; + static_assert(lim_l::is_specialized && lim_r::is_specialized, + "std::numeric_limits<> must be specialized for both types"); + static_assert(lim_l::is_integer && lim_r::is_integer, "Both types must be integers"); + REALM_ASSERT(int_greater_than_or_equal(lval, 0)); + REALM_ASSERT(int_greater_than(rval, 0)); + if (int_less_than(lim_l::max() / rval, lval)) + return true; + lval = L(lval * rval); + return false; +} + +template +inline bool int_shift_left_with_overflow_detect(T& lval, int i) noexcept +{ + typedef std::numeric_limits lim; + static_assert(lim::is_specialized, "std::numeric_limits<> must be specialized for T"); + static_assert(lim::is_integer, "T must be an integer type"); + REALM_ASSERT(int_greater_than_or_equal(lval, 0)); + if ((lim::max() >> i) < lval) + return true; + lval <<= i; + return false; +} + +template +inline bool int_cast_has_overflow(From from) noexcept +{ + typedef std::numeric_limits lim_to; + return int_less_than(from, lim_to::min()) || int_less_than(lim_to::max(), from); +} + +template +inline bool int_cast_with_overflow_detect(From from, To& to) noexcept +{ + if (REALM_LIKELY(!int_cast_has_overflow(from))) { + to = To(from); + return false; + } + return true; +} + +template +inline To from_twos_compl(From twos_compl) noexcept +{ + typedef std::numeric_limits lim_f; + typedef std::numeric_limits lim_t; + static_assert(lim_f::is_specialized && lim_t::is_specialized, + "std::numeric_limits<> must be specialized for both types"); + static_assert(lim_f::is_integer && lim_t::is_integer, "Both types must be integers"); + static_assert(!lim_f::is_signed, "`From` must be unsigned"); + To native; + int sign_bit_pos = lim_f::digits - 1; + From sign_bit = From(1) << sign_bit_pos; + bool non_negative = !lim_t::is_signed || (twos_compl & sign_bit) == 0; + if (non_negative) { + // Non-negative value + native = To(twos_compl); + } + else { + // Negative value + native = To(-1 - To(From(-1) - twos_compl)); + } + return native; +} + + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_SAFE_INT_OPS_HPP diff --git a/Pods/Realm/include/core/realm/util/scope_exit.hpp b/Pods/Realm/include/core/realm/util/scope_exit.hpp new file mode 100644 index 0000000000..5410d1957c --- /dev/null +++ b/Pods/Realm/include/core/realm/util/scope_exit.hpp @@ -0,0 +1,72 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_SCOPE_EXIT_HPP +#define REALM_UTIL_SCOPE_EXIT_HPP + +#include +#include + +#include + +namespace realm { +namespace util { + +template +class ScopeExit { +public: + explicit ScopeExit(const H& handler) noexcept(std::is_nothrow_copy_constructible::value) + : m_handler(handler) + { + } + + explicit ScopeExit(H&& handler) noexcept(std::is_nothrow_move_constructible::value) + : m_handler(std::move(handler)) + { + } + + ScopeExit(ScopeExit&& se) noexcept(std::is_nothrow_move_constructible::value) + : m_handler(std::move(se.m_handler)) + { + se.m_handler = none; + } + + ~ScopeExit() noexcept + { + if (m_handler) + (*m_handler)(); + } + + static_assert(noexcept(std::declval()()), "Handler must be nothrow executable"); + static_assert(std::is_nothrow_destructible::value, "Handler must be nothrow destructible"); + +private: + util::Optional m_handler; +}; + +template +ScopeExit::type> make_scope_exit(H&& handler) noexcept( + noexcept(ScopeExit::type>(std::forward(handler)))) +{ + return ScopeExit::type>(std::forward(handler)); +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_SCOPE_EXIT_HPP diff --git a/Pods/Realm/include/core/realm/util/serializer.hpp b/Pods/Realm/include/core/realm/util/serializer.hpp new file mode 100644 index 0000000000..ff8f41ba7b --- /dev/null +++ b/Pods/Realm/include/core/realm/util/serializer.hpp @@ -0,0 +1,91 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_SERIALIZER_HPP +#define REALM_UTIL_SERIALIZER_HPP + +#include +#include + +#include +#include +#include + +namespace realm { + +class BinaryData; +struct null; +struct RowIndex; +class StringData; +class Timestamp; +class LinkMap; + +namespace util { +namespace serializer { + + +// Definitions +template +std::string print_value(T value); + +template +std::string print_value(Optional value); + +const static std::string value_separator = "."; + +// Specializations declared here to be defined in the cpp file +template <> std::string print_value<>(BinaryData); +template <> std::string print_value<>(bool); +template <> std::string print_value<>(realm::null); +template <> std::string print_value<>(StringData); +template <> std::string print_value<>(realm::Timestamp); +template <> std::string print_value<>(realm::RowIndex); + +// General implementation for most types +template +std::string print_value(T value) +{ + std::stringstream ss; + ss << value; + return ss.str(); +} + +template +std::string print_value(Optional value) +{ + if (bool(value)) { + return print_value(*value); + } else { + return "NULL"; + } +} + +struct SerialisationState +{ + std::string describe_column(ConstTableRef table, size_t col_ndx); + std::string describe_columns(const LinkMap& link_map, size_t target_col_ndx); + std::string get_column_name(ConstTableRef table, size_t col_ndx); + std::string get_variable_name(ConstTableRef table); + std::vector subquery_prefix_list; +}; + +} // namespace serializer +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_SERIALIZER_HPP diff --git a/Pods/Realm/include/core/realm/util/shared_ptr.hpp b/Pods/Realm/include/core/realm/util/shared_ptr.hpp new file mode 100644 index 0000000000..f89b24fdc1 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/shared_ptr.hpp @@ -0,0 +1,130 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_SHARED_PTR_HPP +#define REALM_SHARED_PTR_HPP + +#include // size_t + +namespace realm { +namespace util { + +template +class SharedPtr { +public: + SharedPtr(T* p) + { + init(p); + } + + SharedPtr() + { + init(0); + } + + ~SharedPtr() + { + decref(); + } + + SharedPtr(const SharedPtr& o) + : m_ptr(o.m_ptr) + , m_count(o.m_count) + { + incref(); + } + + SharedPtr& operator=(const SharedPtr& o) + { + if (m_ptr == o.m_ptr) + return *this; + decref(); + m_ptr = o.m_ptr; + m_count = o.m_count; + incref(); + return *this; + } + + T* operator->() const + { + return m_ptr; + } + + T& operator*() const + { + return *m_ptr; + } + + T* get() const + { + return m_ptr; + } + + bool operator==(const SharedPtr& o) const + { + return m_ptr == o.m_ptr; + } + + bool operator!=(const SharedPtr& o) const + { + return m_ptr != o.m_ptr; + } + + bool operator<(const SharedPtr& o) const + { + return m_ptr < o.m_ptr; + } + + size_t ref_count() const + { + return *m_count; + } + +private: + void init(T* p) + { + m_ptr = p; + try { + m_count = new size_t(1); + } + catch (...) { + delete p; + throw; + } + } + + void decref() + { + if (--(*m_count) == 0) { + delete m_ptr; + delete m_count; + } + } + + void incref() + { + ++(*m_count); + } + + T* m_ptr; + size_t* m_count; +}; +} +} + +#endif diff --git a/Pods/Realm/include/core/realm/util/signal_blocker.hpp b/Pods/Realm/include/core/realm/util/signal_blocker.hpp new file mode 100644 index 0000000000..bb1489b06c --- /dev/null +++ b/Pods/Realm/include/core/realm/util/signal_blocker.hpp @@ -0,0 +1,79 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_SIGNAL_BLOCKER_HPP +#define REALM_UTIL_SIGNAL_BLOCKER_HPP + +#include + +#include + + +namespace realm { +namespace util { + +/// \brief Block all signals from being delivered to the instantiating thread. +/// +/// On platforms that support POSIX signals, the constructor will set the signal +/// mask such that all signals are blocked from being delivered to the calling +/// thread, and the destructor will restore the signal mask to its original +/// value. +/// +/// This scheme assumes that it is always the same thread that constructs and +/// destroys a particular instance of SignalBlocker, and that, for a particular +/// thread, two SignalBlocker objects never overlap in time, and the signal mask +/// is never modified by other means while a SignalBlocker object exists. +class SignalBlocker { +public: + SignalBlocker() noexcept; + ~SignalBlocker() noexcept; + +private: +#ifndef _WIN32 + ::sigset_t m_orig_mask; +#endif +}; + + + +// Implementation + +inline SignalBlocker::SignalBlocker() noexcept +{ +#ifndef _WIN32 + ::sigset_t mask; + sigfillset(&mask); + int ret = ::pthread_sigmask(SIG_BLOCK, &mask, &m_orig_mask); + REALM_ASSERT(ret == 0); +#endif +} + +inline SignalBlocker::~SignalBlocker() noexcept +{ +#ifndef _WIN32 + int ret = ::pthread_sigmask(SIG_SETMASK, &m_orig_mask, nullptr); + REALM_ASSERT(ret == 0); +#endif +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_SIGNAL_BLOCKER_HPP diff --git a/Pods/Realm/include/core/realm/util/string_buffer.hpp b/Pods/Realm/include/core/realm/util/string_buffer.hpp new file mode 100644 index 0000000000..9d85043f92 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/string_buffer.hpp @@ -0,0 +1,169 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_STRING_BUFFER_HPP +#define REALM_UTIL_STRING_BUFFER_HPP + +#include +#include +#include + +#include +#include + +namespace realm { +namespace util { + + +// FIXME: Check whether this class provides anything that a C++03 +// std::string does not already provide. In particular, can a C++03 +// std::string be used as a contiguous mutable buffer? +class StringBuffer { +public: + StringBuffer() noexcept; + + std::string str() const; + + /// Returns the current size of the string in this buffer. This + /// size does not include the terminating zero. + size_t size() const noexcept; + + /// Gives read and write access to the bytes of this buffer. The + /// caller may read and write from *c_str() up to, but not + /// including, *(c_str()+size()). + char* data() noexcept; + + /// Gives read access to the bytes of this buffer. The caller may + /// read from *c_str() up to, but not including, + /// *(c_str()+size()). + const char* data() const noexcept; + + /// Guarantees that the returned string is zero terminated, that + /// is, *(c_str()+size()) is zero. The caller may read from + /// *c_str() up to and including *(c_str()+size()). + const char* c_str() const noexcept; + + void append(const std::string&); + + void append(const char* append_data, size_t append_size); + + /// Append a zero-terminated string to this buffer. + void append_c_str(const char* c_string); + + /// The specified size is understood as not including the + /// terminating zero. If the specified size is less than the + /// current size, then the string is truncated accordingly. If the + /// specified size is greater than the current size, then the + /// extra characters will have undefined values, however, there + /// will be a terminating zero at *(c_str()+size()), and the + /// original terminating zero will also be left in place such that + /// from the point of view of c_str(), the size of the string is + /// unchanged. + void resize(size_t new_size); + + /// The specified minimum capacity is understood as not including + /// the terminating zero. This operation does not change the size + /// of the string in the buffer as returned by size(). If the + /// specified capacity is less than the current capacity, this + /// operation has no effect. + void reserve(size_t min_capacity); + + /// Set size to zero. The capacity remains unchanged. + void clear() noexcept; + +private: + util::Buffer m_buffer; + size_t m_size; // Excluding the terminating zero + void reallocate(size_t min_capacity); +}; + + +// Implementation: + +inline StringBuffer::StringBuffer() noexcept + : m_size(0) +{ +} + +inline std::string StringBuffer::str() const +{ + return std::string(m_buffer.data(), m_size); +} + +inline size_t StringBuffer::size() const noexcept +{ + return m_size; +} + +inline char* StringBuffer::data() noexcept +{ + return m_buffer.data(); +} + +inline const char* StringBuffer::data() const noexcept +{ + return m_buffer.data(); +} + +inline const char* StringBuffer::c_str() const noexcept +{ + static const char zero = 0; + const char* d = data(); + return d ? d : &zero; +} + +inline void StringBuffer::append(const std::string& s) +{ + return append(s.data(), s.size()); +} + +inline void StringBuffer::append_c_str(const char* c_string) +{ + append(c_string, std::strlen(c_string)); +} + +inline void StringBuffer::reserve(size_t min_capacity) +{ + size_t capacity = m_buffer.size(); + if (capacity == 0 || capacity - 1 < min_capacity) + reallocate(min_capacity); +} + +inline void StringBuffer::resize(size_t new_size) +{ + reserve(new_size); + // Note that even reserve(0) will attempt to allocate a + // buffer, so we can safely write the truncating zero at this + // time. + m_size = new_size; + m_buffer[new_size] = 0; +} + +inline void StringBuffer::clear() noexcept +{ + if (m_buffer.size() == 0) + return; + m_size = 0; + m_buffer[0] = 0; +} + + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_STRING_BUFFER_HPP diff --git a/Pods/Realm/include/core/realm/util/system_process.hpp b/Pods/Realm/include/core/realm/util/system_process.hpp new file mode 100644 index 0000000000..53792ed32f --- /dev/null +++ b/Pods/Realm/include/core/realm/util/system_process.hpp @@ -0,0 +1,198 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_UTIL_SYSTEM_PROCESS_HPP +#define REALM_UTIL_SYSTEM_PROCESS_HPP + +#include +#include +#include +#include + +#include + + +namespace realm { +namespace util { +namespace sys_proc { + +using Environment = std::map; + +/// This function is safe to call only when the caller can be sure that there +/// are no threads that modify the environment concurrently. +/// +/// When possible, call this function from the main thread before any other +/// threads are created, such as early in `main()`. +Environment copy_local_environment(); + + +struct ExitInfo { + /// If nonzero, the process was killed by a signal. The value is the + /// signal number. + int killed_by_signal = 0; + + /// Zero if the process was killed by a signal, otherwise this is the value + /// returned by the `main()` function, or passed to `exit()`. + /// + /// On a POSIX system, if an error occurs during ::execve(), that is, after + /// ::fork(), an exit status of 127 will be used (aligned with + /// ::posix_spawn()). + int status = 0; + + /// Returns true if, and only if both `killed_by_signal` and `status` are + /// zero. + explicit operator bool() const noexcept; +}; + + +struct SpawnConfig { + /// When set to true, the child process will be able to use a + /// ParentDeathGuard to detect the destruction of the SystemProcess object + /// in the parent process, even when this happens implicitly due to abrupt + /// termination of the parent process. + bool parent_death_guard = false; + + /// If a logger is specified here, the child process will be able to + /// instantiate a ParentLogger object, and messages logged through that + /// ParentLogger object will be transported to the parent process and + /// submitted to the logger pointed to by `logger`. The specified logger is + /// guaranteed to only be accessed while ChildHandle::join() is executing, + /// and only by the thread that executes ChildHandle::join(). See + /// ParentLogger for further details. + Logger* logger = nullptr; +}; + + +class ChildHandle { +public: + /// Wait for the child process to exit. + /// + /// If a logger was passed to spawn() (SpawnConfig::logger), then this + /// function will also transport log messages from the child to the parent + /// process while waiting for the child process to exit. See ParentLogger + /// for details. + ExitInfo join(); + + ChildHandle(ChildHandle&&) noexcept; + ~ChildHandle() noexcept; + +private: + class Impl; + std::unique_ptr m_impl; + + ChildHandle(Impl*) noexcept; + + friend ChildHandle spawn(const std::string&, const std::vector&, + const Environment&, const SpawnConfig&); +}; + + +/// Returns true if, and only if the spawn() functions work on this platform. If +/// this function returns false, the spawn() functions will throw. +bool is_spawn_supported() noexcept; + + +//@{ +/// Spawn a child process. +ChildHandle spawn(const std::string& path, const std::vector& args = {}, + const Environment& = {}); +ChildHandle spawn(const std::string& path, const std::vector& args, + const Environment&, const SpawnConfig&); +//@} + + +/// Force a child process to terminate immediately if the parent process is +/// terminated, or if the parent process destroys the ChildHandle object +/// representing the child process. +/// +/// If a child process instantiates an object of this type, and keeps it alive, +/// and the child process was spawned with support for detection of parent +/// termination (SpawnConfig::parent_death_guard), then the child process will +/// be killed shortly after the parent destroys its ChildHandle object, even +/// when this happens implicitly due to abrupt termination of the parent +/// process. +/// +/// If a child process instantiates an object of this type, that object must be +/// instantiated by the main thread, and before any other thread is spawned in +/// the child process. +/// +/// In order for the guard to have the intended effect, it must be instantiated +/// immediately in the child process, and be kept alive for as long as the child +/// process is running. +class ParentDeathGuard { +public: + ParentDeathGuard(); + ~ParentDeathGuard() noexcept; + +private: + std::thread m_thread; + int m_stop_pipe_write = -1; +}; + + +/// A logger that can transport log messages from the child to the parent +/// process. +/// +/// If the parent process specifies a logger when spawning a child process +/// (SpawnConfig::logger), then that child process can instantiate a +/// ParentLogger object, and messages logged through it will be transported to +/// the parent process. While the parent process is executing +/// ChildHandle::join(), those messages will be written to the logger specified +/// by the parent process. +/// +/// If a child process instantiates an object of this type, that object must be +/// instantiated by the main thread, and before any other thread is spawned in +/// the child process. +/// +/// At most one ParentLogger object may be instantiated per child process. +/// +/// This logger is **not** thread-safe. +class ParentLogger : public RootLogger { +public: + ParentLogger(); + ~ParentLogger() noexcept; + +protected: + void do_log(Level, std::string) override final; + +private: + int m_pipe_write = -1; +}; + + + + +// Implementation + +inline ExitInfo::operator bool() const noexcept +{ + return (killed_by_signal == 0 && status == 0); +} + +inline ChildHandle spawn(const std::string& path, const std::vector& args, + const Environment& env) +{ + return spawn(path, args, env, SpawnConfig{}); // Throws +} + +} // namespace sys_proc +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_SYSTEM_PROCESS_HPP diff --git a/Pods/Realm/include/core/realm/util/terminate.hpp b/Pods/Realm/include/core/realm/util/terminate.hpp new file mode 100644 index 0000000000..4e6034e8fc --- /dev/null +++ b/Pods/Realm/include/core/realm/util/terminate.hpp @@ -0,0 +1,59 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_TERMINATE_HPP +#define REALM_UTIL_TERMINATE_HPP + +#include + +#include +#include +#include + +#define REALM_TERMINATE(msg) realm::util::terminate((msg), __FILE__, __LINE__) + +namespace realm { +namespace util { + +REALM_NORETURN void terminate(const char* message, const char* file, long line, + std::initializer_list&& = {}) noexcept; +REALM_NORETURN void terminate_with_info(const char* message, const char* file, long line, + const char* interesting_names, + std::initializer_list&& = {}) noexcept; + +// LCOV_EXCL_START +template +REALM_NORETURN void terminate(const char* message, const char* file, long line, Ts... infos) noexcept +{ + static_assert(sizeof...(infos) == 2 || sizeof...(infos) == 4 || sizeof...(infos) == 6, + "Called realm::util::terminate() with wrong number of arguments"); + terminate(message, file, line, {Printable(infos)...}); +} + +template +REALM_NORETURN void terminate_with_info(const char* assert_message, int line, const char* file, + const char* interesting_names, Args&&... interesting_values) noexcept +{ + terminate_with_info(assert_message, file, line, interesting_names, {Printable(interesting_values)...}); +} +// LCOV_EXCL_STOP + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_TERMINATE_HPP diff --git a/Pods/Realm/include/core/realm/util/thread.hpp b/Pods/Realm/include/core/realm/util/thread.hpp new file mode 100644 index 0000000000..8ca5e38486 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/thread.hpp @@ -0,0 +1,759 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_THREAD_HPP +#define REALM_UTIL_THREAD_HPP + +#include + +#ifdef _WIN32 +#include +#include // for windows non-interprocess condvars we use std::condition_variable +#include +#include // _getpid() +#else +#include +#endif + +// Use below line to enable a thread bug detection tool. Note: Will make program execution slower. +// #include <../test/pthread_test.hpp> + +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace realm { +namespace util { + + +/// A separate thread of execution. +/// +/// This class is a C++03 compatible reproduction of a subset of std::thread +/// from C++11 (when discounting Thread::start(), Thread::set_name(), and +/// Thread::get_name()). +class Thread { +public: + Thread(); + ~Thread() noexcept; + + template + explicit Thread(F func); + + // Disable copying. It is an error to copy this Thread class. + Thread(const Thread&) = delete; + Thread& operator=(const Thread&) = delete; + + Thread(Thread&&); + + /// This method is an extension of the API provided by + /// std::thread. This method exists because proper move semantics + /// is unavailable in C++03. If move semantics had been available, + /// calling `start(func)` would have been equivalent to `*this = + /// Thread(func)`. Please see std::thread::operator=() for + /// details. + template + void start(F func); + + bool joinable() noexcept; + + void join(); + + // If supported by the platform, set the name of the calling thread (mainly + // for debugging purposes). The name will be silently clamped to whatever + // limit the platform places on these names. Linux places a limit of 15 + // characters for these names. + static void set_name(const std::string&); + + // If supported by the platform, this function assigns the name of the + // calling thread to \a name, and returns true, otherwise it does nothing + // and returns false. + static bool get_name(std::string& name); + +private: + +#ifdef _WIN32 + std::thread m_std_thread; +#else + pthread_t m_id; +#endif + bool m_joinable; + typedef void* (*entry_func_type)(void*); + + void start(entry_func_type, void* arg); + + template + static void* entry_point(void*) noexcept; + + REALM_NORETURN static void create_failed(int); + REALM_NORETURN static void join_failed(int); +}; + + +/// Low-level mutual exclusion device. +class Mutex { +public: + Mutex(); + ~Mutex() noexcept; + + struct process_shared_tag { + }; + /// Initialize this mutex for use across multiple processes. When + /// constructed this way, the instance may be placed in memory + /// shared by multiple processes, as well as in a memory mapped + /// file. Such a mutex remains valid even after the constructing + /// process terminates. Deleting the instance (freeing the memory + /// or deleting the file) without first calling the destructor is + /// legal and will not cause any system resources to be leaked. + Mutex(process_shared_tag); + + // Disable copying. + Mutex(const Mutex&) = delete; + Mutex& operator=(const Mutex&) = delete; + + friend class LockGuard; + friend class UniqueLock; + friend class InterprocessCondVar; + + void lock() noexcept; + bool try_lock() noexcept; + void unlock() noexcept; + +protected: +#ifdef _WIN32 + // Used for non-process-shared mutex. We only know at runtime whether or not to use it, depending on if we call + // Mutex::Mutex(process_shared_tag) + CRITICAL_SECTION m_critical_section; +#else + pthread_mutex_t m_impl = PTHREAD_MUTEX_INITIALIZER; +#endif + + struct no_init_tag { + }; + Mutex(no_init_tag) + { + } + + void init_as_regular(); + void init_as_process_shared(bool robust_if_available); + + REALM_NORETURN static void init_failed(int); + REALM_NORETURN static void attr_init_failed(int); + REALM_NORETURN static void destroy_failed(int) noexcept; + REALM_NORETURN static void lock_failed(int) noexcept; + +private: + friend class CondVar; + friend class RobustMutex; +}; + + +/// A simple mutex ownership wrapper. +class LockGuard { +public: + LockGuard(Mutex&) noexcept; + ~LockGuard() noexcept; + +private: + Mutex& m_mutex; + friend class CondVar; +}; + + +/// See UniqueLock. +struct defer_lock_tag { +}; + +/// A general-purpose mutex ownership wrapper supporting deferred +/// locking as well as repeated unlocking and relocking. +class UniqueLock { +public: + UniqueLock(Mutex&) noexcept; + UniqueLock(Mutex&, defer_lock_tag) noexcept; + ~UniqueLock() noexcept; + + void lock() noexcept; + void unlock() noexcept; + bool holds_lock() noexcept; + +private: + Mutex* m_mutex; + bool m_is_locked; +}; + + +/// A robust version of a process-shared mutex. +/// +/// A robust mutex is one that detects whether a thread (or process) +/// has died while holding a lock on the mutex. +/// +/// When the present platform does not offer support for robust +/// mutexes, this mutex class behaves as a regular process-shared +/// mutex, which means that if a thread dies while holding a lock, any +/// future attempt at locking will block indefinitely. +class RobustMutex : private Mutex { +public: + RobustMutex(); + ~RobustMutex() noexcept; + + static bool is_robust_on_this_platform() noexcept; + + class NotRecoverable; + + /// \param recover_func If the present platform does not support + /// robust mutexes, this function is never called. Otherwise it is + /// called if, and only if a thread has died while holding a + /// lock. The purpose of the function is to reestablish a + /// consistent shared state. If it fails to do this by throwing an + /// exception, the mutex enters the 'unrecoverable' state where + /// any future attempt at locking it will fail and cause + /// NotRecoverable to be thrown. This function is advised to throw + /// NotRecoverable when it fails, but it may throw any exception. + /// + /// \throw NotRecoverable If thrown by the specified recover + /// function, or if the mutex has entered the 'unrecoverable' + /// state due to a different thread throwing from its recover + /// function. + template + void lock(Func recover_func); + + template + bool try_lock(Func recover_func); + + void unlock() noexcept; + + /// Low-level locking of robust mutex. + /// + /// If the present platform does not support robust mutexes, this + /// function always returns true. Otherwise it returns false if, + /// and only if a thread has died while holding a lock. + /// + /// \note Most application should never call this function + /// directly. It is called automatically when using the ordinary + /// lock() function. + /// + /// \throw NotRecoverable If this mutex has entered the "not + /// recoverable" state. It enters this state if + /// mark_as_consistent() is not called between a call to + /// robust_lock() that returns false and the corresponding call to + /// unlock(). + bool low_level_lock(); + + /// Low-level try-lock of robust mutex + /// + /// If the present platform does not support robust mutexes, this + /// function always returns 0 or 1. Otherwise it returns -1 if, + /// and only if a thread has died while holding a lock. + /// + /// Returns 1 if the lock is succesfully obtained. + /// Returns 0 if the lock is held by somebody else (not obtained) + /// Returns -1 if a thread has died while holding a lock. + /// + /// \note Most application should never call this function + /// directly. It is called automatically when using the ordinary + /// lock() function. + /// + /// \throw NotRecoverable If this mutex has entered the "not + /// recoverable" state. It enters this state if + /// mark_as_consistent() is not called between a call to + /// robust_lock() that returns false and the corresponding call to + /// unlock(). + int try_low_level_lock(); + + /// Pull this mutex out of the 'inconsistent' state. + /// + /// Must be called only after low_level_lock() has returned false. + /// + /// \note Most application should never call this function + /// directly. It is called automatically when using the ordinary + /// lock() function. + void mark_as_consistent() noexcept; + + /// Attempt to check if this mutex is a valid object. + /// + /// This attempts to trylock() the mutex, and if that fails returns false if + /// the return value indicates that the low-level mutex is invalid (which is + /// distinct from 'inconsistent'). Although pthread_mutex_trylock() may + /// return EINVAL if the argument is not an initialized mutex object, merely + /// attempting to check if an arbitrary blob of memory is a mutex object may + /// involve undefined behavior, so it is only safe to assume that this + /// function will run correctly when it is known that the mutex object is + /// valid. + bool is_valid() noexcept; + + friend class CondVar; +}; + +class RobustMutex::NotRecoverable : public std::exception { +public: + const char* what() const noexcept override + { + return "Failed to recover consistent state of shared memory"; + } +}; + + +/// A simple robust mutex ownership wrapper. +class RobustLockGuard { +public: + /// \param m the mutex to guard + /// \param func See RobustMutex::lock(). + template + RobustLockGuard(RobustMutex& m, TFunc func); + ~RobustLockGuard() noexcept; + +private: + RobustMutex& m_mutex; + friend class CondVar; +}; + + +/// Condition variable for use in synchronization monitors. +class CondVar { +public: + CondVar(); + ~CondVar() noexcept; + + struct process_shared_tag { + }; + + /// Initialize this condition variable for use across multiple + /// processes. When constructed this way, the instance may be + /// placed in memory shared by multimple processes, as well as in + /// a memory mapped file. Such a condition variable remains valid + /// even after the constructing process terminates. Deleting the + /// instance (freeing the memory or deleting the file) without + /// first calling the destructor is legal and will not cause any + /// system resources to be leaked. + CondVar(process_shared_tag); + + /// Wait for another thread to call notify() or notify_all(). + void wait(LockGuard& l) noexcept; + template + void wait(RobustMutex& m, Func recover_func, const struct timespec* tp = nullptr); + + /// If any threads are wating for this condition, wake up at least + /// one. + void notify() noexcept; + + /// Wake up every thread that is currently wating on this + /// condition. + void notify_all() noexcept; + +private: +#ifdef _WIN32 + CONDITION_VARIABLE m_condvar = CONDITION_VARIABLE_INIT; +#else + pthread_cond_t m_impl; +#endif + + REALM_NORETURN static void init_failed(int); + REALM_NORETURN static void attr_init_failed(int); + REALM_NORETURN static void destroy_failed(int) noexcept; + void handle_wait_error(int error); +}; + + +// Implementation: + +inline Thread::Thread() + : m_joinable(false) +{ +} + +template +inline Thread::Thread(F func) + : m_joinable(true) +{ + std::unique_ptr func2(new F(func)); // Throws + start(&Thread::entry_point, func2.get()); // Throws + func2.release(); +} + +inline Thread::Thread(Thread&& thread) +{ +#ifndef _WIN32 + m_id = thread.m_id; + m_joinable = thread.m_joinable; + thread.m_joinable = false; +#endif +} + +template +inline void Thread::start(F func) +{ + if (m_joinable) + std::terminate(); + std::unique_ptr func2(new F(func)); // Throws + start(&Thread::entry_point, func2.get()); // Throws + func2.release(); + m_joinable = true; +} + +inline Thread::~Thread() noexcept +{ + if (m_joinable) + REALM_TERMINATE("Destruction of joinable thread"); +} + +inline bool Thread::joinable() noexcept +{ + return m_joinable; +} + +inline void Thread::start(entry_func_type entry_func, void* arg) +{ +#ifdef _WIN32 + m_std_thread = std::thread(entry_func, arg); +#else + const pthread_attr_t* attr = nullptr; // Use default thread attributes + int r = pthread_create(&m_id, attr, entry_func, arg); + if (REALM_UNLIKELY(r != 0)) + create_failed(r); // Throws +#endif +} + +template +inline void* Thread::entry_point(void* cookie) noexcept +{ + std::unique_ptr func(static_cast(cookie)); + try { + (*func)(); + } + catch (...) { + std::terminate(); + } + return 0; +} + + +inline Mutex::Mutex() +{ + init_as_regular(); +} + +inline Mutex::Mutex(process_shared_tag) +{ + bool robust_if_available = false; + init_as_process_shared(robust_if_available); +} + +inline Mutex::~Mutex() noexcept +{ +#ifndef _WIN32 + int r = pthread_mutex_destroy(&m_impl); + if (REALM_UNLIKELY(r != 0)) + destroy_failed(r); +#else + DeleteCriticalSection(&m_critical_section); +#endif +} + +inline void Mutex::init_as_regular() +{ +#ifndef _WIN32 + int r = pthread_mutex_init(&m_impl, 0); + if (REALM_UNLIKELY(r != 0)) + init_failed(r); +#else + InitializeCriticalSection(&m_critical_section); +#endif +} + +inline void Mutex::lock() noexcept +{ +#ifdef _WIN32 + EnterCriticalSection(&m_critical_section); +#else + int r = pthread_mutex_lock(&m_impl); + if (REALM_LIKELY(r == 0)) + return; + lock_failed(r); +#endif +} + +inline bool Mutex::try_lock() noexcept +{ +#ifdef _WIN32 + return TryEnterCriticalSection(&m_critical_section); +#else + int r = pthread_mutex_trylock(&m_impl); + if (r == EBUSY) { + return false; + } + else if (r == 0) { + return true; + } + lock_failed(r); +#endif +} + +inline void Mutex::unlock() noexcept +{ +#ifdef _WIN32 + LeaveCriticalSection(&m_critical_section); +#else + int r = pthread_mutex_unlock(&m_impl); + REALM_ASSERT(r == 0); +#endif +} + + +inline LockGuard::LockGuard(Mutex& m) noexcept + : m_mutex(m) +{ + m_mutex.lock(); +} + +inline LockGuard::~LockGuard() noexcept +{ + m_mutex.unlock(); +} + + +inline UniqueLock::UniqueLock(Mutex& m) noexcept + : m_mutex(&m) +{ + m_mutex->lock(); + m_is_locked = true; +} + +inline UniqueLock::UniqueLock(Mutex& m, defer_lock_tag) noexcept + : m_mutex(&m) +{ + m_is_locked = false; +} + +inline UniqueLock::~UniqueLock() noexcept +{ + if (m_is_locked) + m_mutex->unlock(); +} + +inline bool UniqueLock::holds_lock() noexcept +{ + return m_is_locked; +} + +inline void UniqueLock::lock() noexcept +{ + m_mutex->lock(); + m_is_locked = true; +} + +inline void UniqueLock::unlock() noexcept +{ + m_mutex->unlock(); + m_is_locked = false; +} + +template +inline RobustLockGuard::RobustLockGuard(RobustMutex& m, TFunc func) + : m_mutex(m) +{ + m_mutex.lock(func); +} + +inline RobustLockGuard::~RobustLockGuard() noexcept +{ + m_mutex.unlock(); +} + + +inline RobustMutex::RobustMutex() + : Mutex(no_init_tag()) +{ + bool robust_if_available = true; + init_as_process_shared(robust_if_available); +} + +inline RobustMutex::~RobustMutex() noexcept +{ +} + +template +inline void RobustMutex::lock(Func recover_func) +{ + bool no_thread_has_died = low_level_lock(); // Throws + if (REALM_LIKELY(no_thread_has_died)) + return; + try { + recover_func(); // Throws + mark_as_consistent(); + // If we get this far, the protected memory has been + // brought back into a consistent state, and the mutex has + // been notified about this. This means that we can safely + // enter the applications critical section. + } + catch (...) { + // Unlocking without first calling mark_as_consistent() + // means that the mutex enters the "not recoverable" + // state, which will cause all future attempts at locking + // to fail. + unlock(); + throw; + } +} + +template +inline bool RobustMutex::try_lock(Func recover_func) +{ + int lock_result = try_low_level_lock(); // Throws + if (lock_result == 0) return false; + bool no_thread_has_died = lock_result == 1; + if (REALM_LIKELY(no_thread_has_died)) + return true; + try { + recover_func(); // Throws + mark_as_consistent(); + // If we get this far, the protected memory has been + // brought back into a consistent state, and the mutex has + // been notified aboit this. This means that we can safely + // enter the applications critical section. + } + catch (...) { + // Unlocking without first calling mark_as_consistent() + // means that the mutex enters the "not recoverable" + // state, which will cause all future attempts at locking + // to fail. + unlock(); + throw; + } + return true; +} + +inline void RobustMutex::unlock() noexcept +{ + Mutex::unlock(); +} + + +inline CondVar::CondVar() +{ +#ifndef _WIN32 + int r = pthread_cond_init(&m_impl, 0); + if (REALM_UNLIKELY(r != 0)) + init_failed(r); +#endif +} + +inline CondVar::~CondVar() noexcept +{ +#ifndef _WIN32 + int r = pthread_cond_destroy(&m_impl); + if (REALM_UNLIKELY(r != 0)) + destroy_failed(r); +#endif +} + +inline void CondVar::wait(LockGuard& l) noexcept +{ +#ifdef _WIN32 + SleepConditionVariableCS(&m_condvar, &l.m_mutex.m_critical_section, INFINITE); +#else + int r = pthread_cond_wait(&m_impl, &l.m_mutex.m_impl); + if (REALM_UNLIKELY(r != 0)) + REALM_TERMINATE("pthread_cond_wait() failed"); +#endif +} + +template +inline void CondVar::wait(RobustMutex& m, Func recover_func, const struct timespec* tp) +{ + int r; + + if (!tp) { +#ifdef _WIN32 + if (!SleepConditionVariableCS(&m_condvar, &m.m_critical_section, INFINITE)) + r = GetLastError(); + else + r = 0; +#else + r = pthread_cond_wait(&m_impl, &m.m_impl); +#endif + } + else { +#ifdef _WIN32 + if (!SleepConditionVariableCS(&m_condvar, &m.m_critical_section, tp->tv_sec / 1000)) { + r = GetLastError(); + if (r == ERROR_TIMEOUT) + return; + } else { + r = 0 + } +#else + r = pthread_cond_timedwait(&m_impl, &m.m_impl, tp); + if (r == ETIMEDOUT) + return; +#endif + } + + if (REALM_LIKELY(r == 0)) + return; + + handle_wait_error(r); + + try { + recover_func(); // Throws + m.mark_as_consistent(); + // If we get this far, the protected memory has been + // brought back into a consistent state, and the mutex has + // been notified aboit this. This means that we can safely + // enter the applications critical section. + } + catch (...) { + // Unlocking without first calling mark_as_consistent() + // means that the mutex enters the "not recoverable" + // state, which will cause all future attempts at locking + // to fail. + m.unlock(); + throw; + } +} + +inline void CondVar::notify() noexcept +{ +#ifdef _WIN32 + WakeConditionVariable(&m_condvar); +#else + int r = pthread_cond_signal(&m_impl); + REALM_ASSERT(r == 0); +#endif +} + +inline void CondVar::notify_all() noexcept +{ +#ifdef _WIN32 + WakeAllConditionVariable(&m_condvar); +#else + int r = pthread_cond_broadcast(&m_impl); + REALM_ASSERT(r == 0); +#endif +} + + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_THREAD_HPP diff --git a/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp b/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp new file mode 100644 index 0000000000..b779e5a5e6 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp @@ -0,0 +1,334 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2015] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ +#ifndef REALM_UTIL_THREAD_EXEC_GUARD_HPP +#define REALM_UTIL_THREAD_EXEC_GUARD_HPP + +#include +#include +#include + +#include +#include + + +namespace realm { +namespace util { + +/// Execute a `R::run()` using a managed thread. +/// +/// \tparam R The type of the runnable object. This type must satisfy the +/// requirements of the Runnable concept. See ThreadExecGuardWithParent. +template class ThreadExecGuard { +public: + explicit ThreadExecGuard(R& runnable); + + ThreadExecGuard(ThreadExecGuard&&) = default; + + /// If start() or start_with_signals_blocked() was successfully executed, + /// and stop_and_rethrow() has not been called, call `R::stop()`, and then + /// wait for the thread to terminate (join). + ~ThreadExecGuard() noexcept = default; + + // @{ + /// Launch a thread and make it execute `R::run()` of the associated + /// "runnable" object. + /// + /// At most one of these functions are allowed to be called on a particular + /// guard object, and it must only be called once. + void start(); + void start(const std::string& thread_name); + void start_with_signals_blocked(); + void start_with_signals_blocked(const std::string& thread_name); + // @} + + /// If start() or start_with_signals_blocked() was successfully executed, + /// call `R::stop()`, wait for the thread to terminate (join), and then, if + /// an exception was thrown by `R::run()`, rethrow it. + void stop_and_rethrow(); + +private: + struct State { + R& runnable; + util::Thread thread; + std::exception_ptr exception; + State(R&) noexcept; + ~State() noexcept; + void start(const std::string* thread_name); + void stop_and_rethrow(); + }; + + std::unique_ptr m_state; +}; + + +/// Execute a `R::run()` using a managed thread. +/// +/// \tparam R The type of the runnable object. This type must satisfy the +/// requirements of the Runnable concept. See below. +/// +/// \tparam P The type of the object representing the parent thread. This type +/// must satisfy the requirements of the Stoppable concept. See below. +/// +/// A type satisfies the requirements of the *Stoppable* concept, if +/// - it has a nonthrowing member function named `stop()`, and +/// - `stop()` is thread-safe, and +/// - `stop()` is idempotent (can be called multiple times). +/// +/// A type satisfies the requirements of the *Runnable* concept, if +/// - it satisfies the requirements of the Stoppable concept, and +/// - it has a member function named `run()`, and +/// - `run()` will stop executing within a reasonable amount of time after +/// `stop()` has been called. +/// +template class ThreadExecGuardWithParent { +public: + explicit ThreadExecGuardWithParent(R& runnable, P& parent); + + ThreadExecGuardWithParent(ThreadExecGuardWithParent&&) = default; + + /// If start() or start_with_signals_blocked() was successfully executed, + /// and stop_and_rethrow() has not been called, call `R::stop()`, and then + /// wait for the thread to terminate (join). + ~ThreadExecGuardWithParent() noexcept = default; + + // @{ + /// Launch a thread and make it execute `R::run()` of the associated + /// "runnable" object. + /// + /// If `R::run()` throws, call `P::stop()` on the specified parent. + /// + /// At most one of these functions are allowed to be called on a particular + /// guard object, and it must only be called once. + void start(); + void start(const std::string& thread_name); + void start_with_signals_blocked(); + void start_with_signals_blocked(const std::string& thread_name); + // @} + + /// If start() or start_with_signals_blocked() was successfully executed, + /// call `R::stop()`, wait for the thread to terminate (join), and then, if + /// an exception was thrown by `R::run()`, rethrow it. + void stop_and_rethrow(); + +private: + struct State { + R& runnable; + P& parent; + util::Thread thread; + std::exception_ptr exception; + State(R&, P&) noexcept; + ~State() noexcept; + void start(const std::string* thread_name); + void stop_and_rethrow(); + }; + + std::unique_ptr m_state; +}; + + +template ThreadExecGuard make_thread_exec_guard(R& runnable); + +template +ThreadExecGuardWithParent make_thread_exec_guard(R& runnable, P& parent); + + + + +// Implementation + +template inline ThreadExecGuard::ThreadExecGuard(R& runnable) : + m_state{std::make_unique(runnable)} // Throws +{ +} + +template inline void ThreadExecGuard::start() +{ + const std::string* thread_name = nullptr; + m_state->start(thread_name); // Throws +} + +template inline void ThreadExecGuard::start(const std::string& thread_name) +{ + m_state->start(&thread_name); // Throws +} + +template inline void ThreadExecGuard::start_with_signals_blocked() +{ + SignalBlocker sb; + const std::string* thread_name = nullptr; + m_state->start(thread_name); // Throws +} + +template +inline void ThreadExecGuard::start_with_signals_blocked(const std::string& thread_name) +{ + SignalBlocker sb; + m_state->start(&thread_name); // Throws +} + +template inline void ThreadExecGuard::stop_and_rethrow() +{ + m_state->stop_and_rethrow(); // Throws +} + +template inline ThreadExecGuard::State::State(R& r) noexcept : + runnable{r} +{ +} + +template inline ThreadExecGuard::State::~State() noexcept +{ + if (thread.joinable()) { + runnable.stop(); + thread.join(); + } +} + +template inline void ThreadExecGuard::State::start(const std::string* thread_name) +{ + bool set_thread_name = false; + std::string thread_name_2; + if (thread_name) { + set_thread_name = true; + thread_name_2 = *thread_name; // Throws (copy) + } + auto run = [this, set_thread_name, thread_name=std::move(thread_name_2)]() noexcept { + try { + if (set_thread_name) + util::Thread::set_name(thread_name); // Throws + runnable.run(); // Throws + } + catch (...) { + exception = std::current_exception(); + } + }; + thread.start(std::move(run)); // Throws +} + +template inline void ThreadExecGuard::State::stop_and_rethrow() +{ + if (thread.joinable()) { + runnable.stop(); + thread.join(); + if (exception) + std::rethrow_exception(exception); // Throws + } +} + +template +inline ThreadExecGuardWithParent::ThreadExecGuardWithParent(R& runnable, P& parent) : + m_state{std::make_unique(runnable, parent)} // Throws +{ +} + +template inline void ThreadExecGuardWithParent::start() +{ + const std::string* thread_name = nullptr; + m_state->start(thread_name); // Throws +} + +template +inline void ThreadExecGuardWithParent::start(const std::string& thread_name) +{ + m_state->start(&thread_name); // Throws +} + +template inline void ThreadExecGuardWithParent::start_with_signals_blocked() +{ + SignalBlocker sb; + const std::string* thread_name = nullptr; + m_state->start(thread_name); // Throws +} + +template +inline void ThreadExecGuardWithParent::start_with_signals_blocked(const std::string& thread_name) +{ + SignalBlocker sb; + m_state->start(&thread_name); // Throws +} + +template inline void ThreadExecGuardWithParent::stop_and_rethrow() +{ + m_state->stop_and_rethrow(); // Throws +} + +template +inline ThreadExecGuardWithParent::State::State(R& r, P& p) noexcept : + runnable{r}, + parent{p} +{ +} + +template inline ThreadExecGuardWithParent::State::~State() noexcept +{ + if (thread.joinable()) { + runnable.stop(); + thread.join(); + } +} + +template +inline void ThreadExecGuardWithParent::State::start(const std::string* thread_name) +{ + bool set_thread_name = false; + std::string thread_name_2; + if (thread_name) { + set_thread_name = true; + thread_name_2 = *thread_name; // Throws (copy) + } + auto run = [this, set_thread_name, thread_name=std::move(thread_name_2)]() noexcept { + try { + if (set_thread_name) + util::Thread::set_name(thread_name); // Throws + runnable.run(); // Throws + } + catch (...) { + exception = std::current_exception(); + parent.stop(); + } + }; + thread.start(std::move(run)); // Throws +} + +template inline void ThreadExecGuardWithParent::State::stop_and_rethrow() +{ + if (thread.joinable()) { + runnable.stop(); + thread.join(); + if (exception) + std::rethrow_exception(exception); // Throws + } +} + +template inline ThreadExecGuard make_thread_exec_guard(R& runnable) +{ + return ThreadExecGuard{runnable}; // Throws +} + +template +inline ThreadExecGuardWithParent make_thread_exec_guard(R& runnable, P& parent) +{ + return ThreadExecGuardWithParent{runnable, parent}; // Throws +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_THREAD_EXEC_GUARD_HPP diff --git a/Pods/Realm/include/core/realm/util/time.hpp b/Pods/Realm/include/core/realm/util/time.hpp new file mode 100644 index 0000000000..3a3d8455c5 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/time.hpp @@ -0,0 +1,88 @@ +/************************************************************************* + * + * REALM CONFIDENTIAL + * __________________ + * + * [2011] - [2016] Realm Inc + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of Realm Incorporated and its suppliers, + * if any. The intellectual and technical concepts contained + * herein are proprietary to Realm Incorporated + * and its suppliers and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from Realm Incorporated. + * + **************************************************************************/ + +#ifndef REALM_UTIL_TIME_HPP +#define REALM_UTIL_TIME_HPP + +#include +#include +#include +#include +#include +#include + + +namespace realm { +namespace util { + +/// Thread safe version of std::localtime(). Uses localtime_r() on POSIX. +std::tm localtime(std::time_t); + +/// Thread safe version of std::gmtime(). Uses gmtime_r() on POSIX. +std::tm gmtime(std::time_t); + +/// Similar to std::put_time() from . See std::put_time() for +/// information about the format string. This function is provided because +/// std::put_time() is unavailable in GCC 4. This function is thread safe. +/// +/// The default format is ISO 8601 date and time. +template +void put_time(std::basic_ostream&, const std::tm&, const C* format = "%FT%T%z"); + +/// @{ These functions combine localtime() or gmtime() with put_time() and +/// std::ostringstream. For detals on the format string, see +/// std::put_time(). These function are thread safe. +std::string format_local_time(std::time_t, const char* format = "%FT%T%z"); +std::string format_utc_time(std::time_t, const char* format = "%FT%T%z"); +/// @} + + + + +// Implementation + +template +inline void put_time(std::basic_ostream& out, const std::tm& tm, const C* format) +{ + const auto& facet = std::use_facet>(out.getloc()); // Throws + facet.put(std::ostreambuf_iterator(out), out, ' ', &tm, + format, format + T::length(format)); // Throws +} + +inline std::string format_local_time(std::time_t time, const char* format) +{ + std::tm tm = util::localtime(time); + std::ostringstream out; + util::put_time(out, tm, format); // Throws + return out.str(); // Throws +} + +inline std::string format_utc_time(std::time_t time, const char* format) +{ + std::tm tm = util::gmtime(time); + std::ostringstream out; + util::put_time(out, tm, format); // Throws + return out.str(); // Throws +} + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_TIME_HPP diff --git a/Pods/Realm/include/core/realm/util/to_string.hpp b/Pods/Realm/include/core/realm/util/to_string.hpp new file mode 100644 index 0000000000..c3fac65090 --- /dev/null +++ b/Pods/Realm/include/core/realm/util/to_string.hpp @@ -0,0 +1,126 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_TO_STRING_HPP +#define REALM_UTIL_TO_STRING_HPP + +#include +#include + +namespace realm { +namespace util { + +class Printable { +public: + Printable(bool value) + : m_type(Type::Bool) + , m_uint(value) + { + } + Printable(unsigned char value) + : m_type(Type::Uint) + , m_uint(value) + { + } + Printable(unsigned int value) + : m_type(Type::Uint) + , m_uint(value) + { + } + Printable(unsigned long value) + : m_type(Type::Uint) + , m_uint(value) + { + } + Printable(unsigned long long value) + : m_type(Type::Uint) + , m_uint(value) + { + } + Printable(char value) + : m_type(Type::Int) + , m_int(value) + { + } + Printable(int value) + : m_type(Type::Int) + , m_int(value) + { + } + Printable(long value) + : m_type(Type::Int) + , m_int(value) + { + } + Printable(long long value) + : m_type(Type::Int) + , m_int(value) + { + } + Printable(const char* value) + : m_type(Type::String) + , m_string(value) + { + } + Printable(std::string const& value) + : m_type(Type::String) + , m_string(value.c_str()) + { + } + + + void print(std::ostream& out, bool quote) const; + std::string str() const; + + static void print_all(std::ostream& out, const std::initializer_list& values, bool quote); + +private: + enum class Type { + Bool, + Int, + Uint, + String, + } m_type; + + union { + uintmax_t m_uint; + intmax_t m_int; + const char* m_string; + }; +}; + + +template +std::string to_string(const T& v) +{ + return Printable(v).str(); +} + +std::string format(const char* fmt, std::initializer_list); + +template +std::string format(const char* fmt, Args&&... args) +{ + return format(fmt, {Printable(args)...}); +} + + +} // namespace util +} // namespace realm + +#endif // REALM_UTIL_TO_STRING_HPP diff --git a/Pods/Realm/include/core/realm/util/type_list.hpp b/Pods/Realm/include/core/realm/util/type_list.hpp new file mode 100644 index 0000000000..da847c751c --- /dev/null +++ b/Pods/Realm/include/core/realm/util/type_list.hpp @@ -0,0 +1,244 @@ +/************************************************************************* + * + * Copyright 2016 Realm Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + **************************************************************************/ + +#ifndef REALM_UTIL_TYPE_LIST_HPP +#define REALM_UTIL_TYPE_LIST_HPP + +namespace realm { +namespace util { + + +/// The 'cons' operator for building lists of types. +/// +/// \tparam H The head of the list, that is, the first type in the +/// list. +/// +/// \tparam T The tail of the list, that is, the list of types +/// following the head. It is 'void' if nothing follows the head, +/// otherwise it matches TypeCons. +/// +/// Note that 'void' is interpreted as a zero-length list. +template +struct TypeCons { + typedef H head; + typedef T tail; +}; + + +/// Append a type the the end of a type list. The resulting type list +/// is available as TypeAppend::type. +/// +/// \tparam List A list of types constructed using TypeCons<>. Note +/// that 'void' is interpreted as a zero-length list. +/// +/// \tparam T The new type to be appended. +template +struct TypeAppend { + typedef TypeCons::type> type; +}; +/// Base case for empty type list. +template +struct TypeAppend { + typedef TypeCons type; +}; + + +/// Get an element from the specified list of types. The result is +/// available as TypeAt::type. +/// +/// \tparam List A list of types constructed using TypeCons<>. Note +/// that 'void' is interpreted as a zero-length list. +/// +/// \tparam i The index of the list element to get. +template +struct TypeAt { + typedef typename TypeAt::type type; +}; +/// Base case for empty type list. +template +struct TypeAt { + typedef typename List::head type; +}; + + +/// Count the number of elements in the specified list of types. The +/// result is available as TypeCount::value. +/// +/// \tparam List The list of types, constructed using TypeCons<>. Note +/// that 'void' is interpreted as a zero-length list. +template +struct TypeCount { + static const int value = 1 + TypeCount::value; +}; +/// Base case for empty type list. +template <> +struct TypeCount { + static const int value = 0; +}; + + +/// Find the first type in the specified list that satisfies the +/// specified predicate. +/// +/// \tparam List The list of types, constructed using TypeCons<>. Note +/// that 'void' is interpreted as a zero-length list. +/// +/// \tparam Pred Must be such that `Pred::%value` is true if, and +/// only if the predicate is satisfied for `T`. +template class Pred> +struct FindType { +private: + typedef typename List::head type_1; + typedef typename FindType::type type_2; + +public: + typedef typename std::conditional::value, type_1, type_2>::type type; +}; +/// Base case for empty type list. +template