code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
// Created by eric_horacek on 10/8/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI) && !os(macOS)
import SwiftUI
// MARK: - EpoxySwiftUIUIHostingController
/// A `UIHostingController` that hosts SwiftUI views within an Epoxy container, e.g. an Epoxy
/// `CollectionView`.
///
/// Exposed internally to allow consumers to reason about these view controllers, e.g. to opt
/// collection view cells out of automated view controller impression tracking.
///
/// - SeeAlso: `EpoxySwiftUIHostingView`
@available(iOS 13.0, tvOS 13.0, *)
open class EpoxySwiftUIHostingController<Content: View>: UIHostingController<Content> {
// MARK: Lifecycle
/// Creates a `UIHostingController` that optionally ignores the `safeAreaInsets` when laying out
/// its contained `RootView`.
convenience init(rootView: Content, ignoreSafeArea: Bool) {
self.init(rootView: rootView)
// We unfortunately need to call a private API to disable the safe area. We can also accomplish
// this by dynamically subclassing this view controller's view at runtime and overriding its
// `safeAreaInsets` property and returning `.zero`. An implementation of that logic is
// available in this file in the `2d28b3181cca50b89618b54836f7a9b6e36ea78e` commit if this API
// no longer functions in future SwiftUI versions.
_disableSafeArea = ignoreSafeArea
}
// MARK: Open
open override func viewDidLoad() {
super.viewDidLoad()
// A `UIHostingController` has a system background color by default as it's typically used in
// full-screen use cases. Since we're using this view controller to place SwiftUI views within
// other view controllers we default the background color to clear so we can see the views
// below, e.g. to draw highlight states in a `CollectionView`.
view.backgroundColor = .clear
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/EpoxySwiftUIHostingController.swift
|
Swift
|
unknown
| 1,875
|
// Created by eric_horacek on 9/16/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
#if canImport(Combine) && canImport(SwiftUI) && !os(macOS)
import Combine
import SwiftUI
// MARK: - SwiftUIHostingViewReuseBehavior
/// The reuse behavior of an `EpoxySwiftUIHostingView`.
enum SwiftUIHostingViewReuseBehavior: Hashable {
/// Instances of a `EpoxySwiftUIHostingView` with `RootView`s of same type can be reused within
/// the Epoxy container.
///
/// This is the default reuse behavior.
case reusable
/// Instances of a `EpoxySwiftUIHostingView` with `RootView`s of same type can only reused within
/// the Epoxy container when they have identical `reuseID`s.
case unique(reuseID: AnyHashable)
}
// MARK: - CallbackContextEpoxyModeled
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension CallbackContextEpoxyModeled
where
Self: WillDisplayProviding & DidEndDisplayingProviding,
CallbackContext: ViewProviding & AnimatedProviding
{
/// Updates the appearance state of a `EpoxySwiftUIHostingView` in coordination with the
/// `willDisplay` and `didEndDisplaying` callbacks of this `EpoxyableModel`.
///
/// - Note: You should only need to call then from the implementation of a concrete
/// `EpoxyableModel` convenience vendor method, e.g. `SwiftUI.View.itemModel(…)`.
func linkDisplayLifecycle<RootView: View>() -> Self
where
CallbackContext.View == EpoxySwiftUIHostingView<RootView>
{
willDisplay { context in
context.view.handleWillDisplay(animated: context.animated)
}
.didEndDisplaying { context in
context.view.handleDidEndDisplaying(animated: context.animated)
}
}
}
// MARK: - EpoxySwiftUIHostingView
/// A `UIView` that hosts a SwiftUI view within an Epoxy container, e.g. an Epoxy `CollectionView`.
///
/// Wraps an `EpoxySwiftUIHostingController` and adds it as a child view controller to the next
/// ancestor view controller in the hierarchy.
///
/// There's a private API that accomplishes this same behavior without needing a `UIViewController`:
/// `_UIHostingView`, but we can't safely use it as 1) the behavior may change out from under us, 2)
/// the API is private and 3) the `_UIHostingView` doesn't not accept setting a new `View` instance.
///
/// - SeeAlso: `EpoxySwiftUIHostingController`
@available(iOS 13.0, tvOS 13.0, *)
final class EpoxySwiftUIHostingView<RootView: View>: UIView, EpoxyableView {
// MARK: Lifecycle
init(style: Style) {
// Ignore the safe area to ensure the view isn't laid out incorrectly when being sized while
// overlapping the safe area.
epoxyContent = EpoxyHostingContent(rootView: style.initialContent.rootView)
viewController = EpoxySwiftUIHostingController(
rootView: .init(content: epoxyContent, environment: epoxyEnvironment),
ignoreSafeArea: true)
dataID = style.initialContent.dataID ?? DefaultDataID.noneProvided as AnyHashable
super.init(frame: .zero)
epoxyEnvironment.intrinsicContentSizeInvalidator = .init(invalidate: { [weak self] in
self?.viewController.view.invalidateIntrinsicContentSize()
// Inform the enclosing collection view that the size has changed, if we're contained in one,
// allowing the cell to resize.
//
// On iOS 16+, we could call `invalidateIntrinsicContentSize()` on the enclosing collection
// view cell instead, but that currently causes visual artifacts with `MagazineLayout`. The
// better long term fix is likely to switch to `UIHostingConfiguration` on iOS 16+ anyways.
if let enclosingCollectionView = self?.superview?.superview?.superview as? UICollectionView {
enclosingCollectionView.collectionViewLayout.invalidateLayout()
}
})
layoutMargins = .zero
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
struct Style: Hashable {
init(reuseBehavior: SwiftUIHostingViewReuseBehavior, initialContent: Content) {
self.reuseBehavior = reuseBehavior
self.initialContent = initialContent
}
var reuseBehavior: SwiftUIHostingViewReuseBehavior
var initialContent: Content
static func == (lhs: Style, rhs: Style) -> Bool {
lhs.reuseBehavior == rhs.reuseBehavior
}
func hash(into hasher: inout Hasher) {
hasher.combine(reuseBehavior)
}
}
struct Content: Equatable {
init(rootView: RootView, dataID: AnyHashable?) {
self.rootView = rootView
self.dataID = dataID
}
var rootView: RootView
var dataID: AnyHashable?
static func == (_: Content, _: Content) -> Bool {
// The content should never be equal since we need the `rootView` to be updated on every
// content change.
false
}
}
override func didMoveToWindow() {
super.didMoveToWindow()
// We'll only be able to discover a valid parent `viewController` once we're added to a window,
// so we do so here in addition to the `handleWillDisplay(…)` method.
if window != nil {
addViewControllerIfNeeded()
}
}
func setContent(_ content: Content, animated _: Bool) {
// This triggers a change in the observed `EpoxyHostingContent` object and allows the
// propagation of the SwiftUI transaction, instead of just replacing the `rootView`.
epoxyContent.rootView = content.rootView
dataID = content.dataID ?? DefaultDataID.noneProvided as AnyHashable
// The view controller must be added to the view controller hierarchy to measure its content.
if window != nil {
addViewControllerIfNeeded()
}
// As of iOS 15.2, `UIHostingController` now renders updated content asynchronously, and as such
// this view will get sized incorrectly with the previous content when reused unless we invoke
// this semi-private API. We couldn't find any other method to get the view to resize
// synchronously after updating `rootView`, but hopefully this will become a internal API soon so
// we can remove this call.
viewController._render(seconds: 0)
// This is required to ensure that views with new content are properly resized.
viewController.view.invalidateIntrinsicContentSize()
}
override func layoutMarginsDidChange() {
super.layoutMarginsDidChange()
let margins = layoutMargins
switch effectiveUserInterfaceLayoutDirection {
case .rightToLeft:
epoxyEnvironment.layoutMargins = .init(
top: margins.top,
leading: margins.right,
bottom: margins.bottom,
trailing: margins.left)
case .leftToRight:
fallthrough
@unknown default:
epoxyEnvironment.layoutMargins = .init(
top: margins.top,
leading: margins.left,
bottom: margins.bottom,
trailing: margins.right)
}
// Allow the layout margins update to fully propagate through to the SwiftUI View before
// invalidating the layout.
DispatchQueue.main.async {
self.viewController.view.invalidateIntrinsicContentSize()
}
}
func handleWillDisplay(animated: Bool) {
guard state != .appeared, window != nil else { return }
transition(to: .appearing(animated: animated))
transition(to: .appeared)
}
func handleDidEndDisplaying(animated: Bool) {
guard state != .disappeared else { return }
transition(to: .disappearing(animated: animated))
transition(to: .disappeared)
}
// MARK: Private
private let viewController: EpoxySwiftUIHostingController<EpoxyHostingWrapper<RootView>>
private let epoxyContent: EpoxyHostingContent<RootView>
private let epoxyEnvironment = EpoxyHostingEnvironment()
private var dataID: AnyHashable
private var state: AppearanceState = .disappeared
/// Updates the appearance state of the `viewController`.
private func transition(to state: AppearanceState) {
guard state != self.state else { return }
// See "Handling View-Related Notifications" section for the state machine diagram.
// https://developer.apple.com/documentation/uikit/uiviewcontroller
switch (to: state, from: self.state) {
case (to: .appearing(let animated), from: .disappeared):
viewController.beginAppearanceTransition(true, animated: animated)
addViewControllerIfNeeded()
case (to: .disappearing(let animated), from: .appeared):
viewController.beginAppearanceTransition(false, animated: animated)
case (to: .disappeared, from: .disappearing):
removeViewControllerIfNeeded()
case (to: .appeared, from: .appearing):
viewController.endAppearanceTransition()
case (to: .disappeared, from: .appeared):
viewController.beginAppearanceTransition(false, animated: true)
removeViewControllerIfNeeded()
case (to: .appeared, from: .disappearing(let animated)):
viewController.beginAppearanceTransition(true, animated: animated)
viewController.endAppearanceTransition()
case (to: .disappeared, from: .appearing(let animated)):
viewController.beginAppearanceTransition(false, animated: animated)
removeViewControllerIfNeeded()
case (to: .appeared, from: .disappeared):
viewController.beginAppearanceTransition(true, animated: false)
addViewControllerIfNeeded()
viewController.endAppearanceTransition()
case (to: .appearing(let animated), from: .appeared):
viewController.beginAppearanceTransition(false, animated: animated)
viewController.beginAppearanceTransition(true, animated: animated)
case (to: .appearing(let animated), from: .disappearing):
viewController.beginAppearanceTransition(true, animated: animated)
case (to: .disappearing(let animated), from: .disappeared):
viewController.beginAppearanceTransition(true, animated: animated)
addViewControllerIfNeeded()
viewController.beginAppearanceTransition(false, animated: animated)
case (to: .disappearing(let animated), from: .appearing):
viewController.beginAppearanceTransition(false, animated: animated)
case (to: .appearing, from: .appearing),
(to: .appeared, from: .appeared),
(to: .disappearing, from: .disappearing),
(to: .disappeared, from: .disappeared):
// This should never happen since we guard on identical states.
EpoxyLogger.shared.assertionFailure("Impossible state change from \(self.state) to \(state)")
}
self.state = state
}
private func addViewControllerIfNeeded() {
// This isn't great, and means that we're going to add this view controller as a child view
// controller of a view controller somewhere else in the hierarchy, which the author of that
// view controller may not be expecting. However there's not really a better pathway forward
// here without requiring a view controller instance to be passed all the way through, which is
// both burdensome and error-prone.
guard let nextViewController = superview?.next(UIViewController.self) else {
EpoxyLogger.shared.assertionFailure(
"""
Unable to add a UIHostingController view, could not locate a UIViewController in the \
responder chain for view with ID \(dataID) of type \(RootView.self).
""")
return
}
guard viewController.parent !== nextViewController else { return }
// If in a different parent, we need to first remove from it before we add.
if viewController.parent != nil {
removeViewControllerIfNeeded()
}
addViewController(to: nextViewController)
state = .appeared
}
private func addViewController(to parent: UIViewController) {
viewController.willMove(toParent: parent)
parent.addChild(viewController)
addSubview(viewController.view)
// Get the view controller's view to be sized correctly so that we don't have to wait for
// autolayout to perform a pass to do so.
viewController.view.frame = bounds
viewController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
viewController.view.leadingAnchor.constraint(equalTo: leadingAnchor),
viewController.view.topAnchor.constraint(equalTo: topAnchor),
viewController.view.trailingAnchor.constraint(equalTo: trailingAnchor),
viewController.view.bottomAnchor.constraint(equalTo: bottomAnchor),
])
viewController.didMove(toParent: parent)
}
private func removeViewControllerIfNeeded() {
guard viewController.parent != nil else { return }
viewController.willMove(toParent: nil)
viewController.view.removeFromSuperview()
viewController.removeFromParent()
viewController.didMove(toParent: nil)
}
}
// MARK: - AppearanceState
/// The appearance state of a `EpoxySwiftUIHostingController` contained within a
/// `EpoxySwiftUIHostingView`.
private enum AppearanceState: Equatable {
case appearing(animated: Bool)
case appeared
case disappearing(animated: Bool)
case disappeared
}
// MARK: - UIResponder
extension UIResponder {
/// Recursively traverses the responder chain upwards from this responder to its next responder
/// until the a responder of the given type is located, else returns `nil`.
@nonobjc
fileprivate func next<ResponderType>(_ type: ResponderType.Type) -> ResponderType? {
self as? ResponderType ?? next?.next(type)
}
}
// MARK: - EpoxyHostingContent
/// The object that is used to communicate changes in the root view to the
/// `EpoxySwiftUIHostingController`.
@available(iOS 13.0, tvOS 13.0, *)
final class EpoxyHostingContent<RootView: View>: ObservableObject {
// MARK: Lifecycle
init(rootView: RootView) {
_rootView = .init(wrappedValue: rootView)
}
// MARK: Internal
@Published var rootView: RootView
}
// MARK: - EpoxyHostingEnvironment
/// The object that is used to communicate values to SwiftUI views within an
/// `EpoxySwiftUIHostingController`, e.g. layout margins.
@available(iOS 13.0, tvOS 13.0, *)
final class EpoxyHostingEnvironment: ObservableObject {
@Published var layoutMargins = EdgeInsets()
@Published var intrinsicContentSizeInvalidator = EpoxyIntrinsicContentSizeInvalidator(invalidate: { })
}
// MARK: - EpoxyHostingWrapper
/// The wrapper view that is used to communicate values to SwiftUI views within an
/// `EpoxySwiftUIHostingController`, e.g. layout margins.
@available(iOS 13.0, tvOS 13.0, *)
struct EpoxyHostingWrapper<Content: View>: View {
@ObservedObject var content: EpoxyHostingContent<Content>
@ObservedObject var environment: EpoxyHostingEnvironment
var body: some View {
content.rootView
.environment(\.epoxyLayoutMargins, environment.layoutMargins)
.environment(\.epoxyIntrinsicContentSizeInvalidator, environment.intrinsicContentSizeInvalidator)
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/EpoxySwiftUIHostingView.swift
|
Swift
|
unknown
| 14,749
|
// Created by matthew_cheok on 11/19/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
// MARK: - EpoxyIntrinsicContentSizeInvalidator
/// Allows the SwiftUI view contained in an Epoxy model to request the invalidation of
/// the container's intrinsic content size.
///
/// ```
/// @Environment(\.epoxyIntrinsicContentSizeInvalidator) var invalidateIntrinsicContentSize
///
/// var body: some View {
/// ...
/// .onChange(of: size) {
/// invalidateIntrinsicContentSize()
/// }
/// }
/// ```
struct EpoxyIntrinsicContentSizeInvalidator {
let invalidate: () -> Void
func callAsFunction() {
invalidate()
}
}
// MARK: - EnvironmentValues
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension EnvironmentValues {
/// A means of invalidating the intrinsic content size of the parent `EpoxySwiftUIHostingView`.
var epoxyIntrinsicContentSizeInvalidator: EpoxyIntrinsicContentSizeInvalidator {
get { self[EpoxyIntrinsicContentSizeInvalidatorKey.self] }
set { self[EpoxyIntrinsicContentSizeInvalidatorKey.self] = newValue }
}
}
// MARK: - EpoxyIntrinsicContentSizeInvalidatorKey
private struct EpoxyIntrinsicContentSizeInvalidatorKey: EnvironmentKey {
static let defaultValue = EpoxyIntrinsicContentSizeInvalidator(invalidate: { })
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/EpoxySwiftUIIntrinsicContentSizeInvalidator.swift
|
Swift
|
unknown
| 1,325
|
// Created by eric_horacek on 10/8/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
// MARK: - View
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension View {
/// Applies the layout margins from the parent `EpoxySwiftUIHostingView` to this `View`, if there
/// are any.
///
/// Can be used to have a background in SwiftUI underlap the safe area within a bar installer, for
/// example.
///
/// These margins are propagated via the `EnvironmentValues.epoxyLayoutMargins`.
func epoxyLayoutMargins() -> some View {
modifier(EpoxyLayoutMarginsPadding())
}
}
// MARK: - EnvironmentValues
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension EnvironmentValues {
/// The layout margins of the parent `EpoxySwiftUIHostingView`, else zero if there is none.
var epoxyLayoutMargins: EdgeInsets {
get { self[EpoxyLayoutMarginsKey.self] }
set { self[EpoxyLayoutMarginsKey.self] = newValue }
}
}
// MARK: - EpoxyLayoutMarginsKey
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
private struct EpoxyLayoutMarginsKey: EnvironmentKey {
static let defaultValue = EdgeInsets()
}
// MARK: - EpoxyLayoutMarginsPadding
/// A view modifier that applies the layout margins from an enclosing `EpoxySwiftUIHostingView` to
/// the modified `View`.
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
private struct EpoxyLayoutMarginsPadding: ViewModifier {
@Environment(\.epoxyLayoutMargins) var epoxyLayoutMargins
func body(content: Content) -> some View {
content.padding(epoxyLayoutMargins)
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/EpoxySwiftUILayoutMargins.swift
|
Swift
|
unknown
| 1,589
|
// Created by eric_horacek on 9/13/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
// MARK: - StyledView
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension StyledView where Self: ContentConfigurableView & BehaviorsConfigurableView {
/// Returns a SwiftUI `View` representing this `EpoxyableView`.
///
/// To perform additional configuration of the `EpoxyableView` instance, call `configure` on the
/// returned SwiftUI `View`:
/// ```
/// MyView.swiftUIView(…)
/// .configure { context in
/// context.view.doSomething()
/// }
/// ```
///
/// To configure the sizing behavior of the `EpoxyableView` instance, call `sizing` on the
/// returned SwiftUI `View`:
/// ```
/// MyView.swiftUIView(…).sizing(.intrinsicSize)
/// ```
static func swiftUIView(
content: Content,
style: Style,
behaviors: Behaviors? = nil)
-> SwiftUIView<Self, (content: Content, style: Style)>
{
SwiftUIView(storage: (content: content, style: style)) {
let view = Self(style: style)
view.setContent(content, animated: false)
return view
}
.configure { context in
// We need to create a new view instance when the style changes.
if context.oldStorage.style != style {
context.view = Self(style: style)
context.view.setContent(content, animated: context.animated)
}
// Otherwise, if the just the content changes, we need to update it.
else if context.oldStorage.content != content {
context.view.setContent(content, animated: context.animated)
context.container.invalidateIntrinsicContentSize()
}
context.view.setBehaviors(behaviors)
}
}
}
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension StyledView
where
Self: ContentConfigurableView & BehaviorsConfigurableView,
Style == Never
{
/// Returns a SwiftUI `View` representing this `EpoxyableView`.
///
/// To perform additional configuration of the `EpoxyableView` instance, call `configure` on the
/// returned SwiftUI `View`:
/// ```
/// MyView.swiftUIView(…)
/// .configure { context in
/// context.view.doSomething()
/// }
/// ```
///
/// To configure the sizing behavior of the `EpoxyableView` instance, call `sizing` on the
/// returned SwiftUI `View`:
/// ```
/// MyView.swiftUIView(…).sizing(.intrinsicSize)
/// ```
static func swiftUIView(
content: Content,
behaviors: Behaviors? = nil)
-> SwiftUIView<Self, Content>
{
SwiftUIView(storage: content) {
let view = Self()
view.setContent(content, animated: false)
return view
}
.configure { context in
// We need to update the content of the existing view when the content is updated.
if context.oldStorage != content {
context.view.setContent(content, animated: context.animated)
context.container.invalidateIntrinsicContentSize()
}
context.view.setBehaviors(behaviors)
}
}
}
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension StyledView
where
Self: ContentConfigurableView & BehaviorsConfigurableView,
Content == Never
{
/// Returns a SwiftUI `View` representing this `EpoxyableView`.
///
/// To perform additional configuration of the `EpoxyableView` instance, call `configure` on the
/// returned SwiftUI `View`:
/// ```
/// MyView.swiftUIView(…)
/// .configure { context in
/// context.view.doSomething()
/// }
/// ```
///
/// To configure the sizing behavior of the `EpoxyableView` instance, call `sizing` on the
/// returned SwiftUI `View`:
/// ```
/// MyView.swiftUIView(…).sizing(.intrinsicSize)
/// ```
/// The sizing defaults to `.automatic`.
static func swiftUIView(
style: Style,
behaviors: Behaviors? = nil)
-> SwiftUIView<Self, Style>
{
SwiftUIView(storage: style) {
Self(style: style)
}
.configure { context in
// We need to create a new view instance when the style changes.
if context.oldStorage != style {
context.view = Self(style: style)
}
context.view.setBehaviors(behaviors)
}
}
}
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension StyledView
where
Self: ContentConfigurableView & BehaviorsConfigurableView,
Content == Never,
Style == Never
{
/// Returns a SwiftUI `View` representing this `EpoxyableView`.
///
/// To perform additional configuration of the `EpoxyableView` instance, call `configure` on the
/// returned SwiftUI `View`:
/// ```
/// MyView.swiftUIView(…)
/// .configure { context in
/// context.view.doSomething()
/// }
/// ```
///
/// To configure the sizing behavior of the `EpoxyableView` instance, call `sizing` on the
/// returned SwiftUI `View`:
/// ```
/// MyView.swiftUIView(…).sizing(.intrinsicSize)
/// ```
/// The sizing defaults to `.automatic`.
static func swiftUIView(behaviors: Behaviors? = nil) -> SwiftUIView<Self, Void> {
SwiftUIView {
Self()
}
.configure { context in
context.view.setBehaviors(behaviors)
}
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/EpoxyableView+SwiftUIView.swift
|
Swift
|
unknown
| 5,161
|
// Created by eric_horacek on 6/22/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
// MARK: - MeasuringViewRepresentable
/// A `UIViewRepresentable` that uses a `SwiftUIMeasurementContainer` wrapping its represented
/// `UIView` to report its size that fits a proposed size to SwiftUI.
///
/// Supports iOS 13-15 using the private `_overrideSizeThatFits(…)` method and iOS 16+ using the
/// `sizeThatFits(…)` method.
///
/// - SeeAlso: ``SwiftUIMeasurementContainer``
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
protocol MeasuringViewRepresentable: ViewRepresentableType
where
RepresentableViewType == SwiftUIMeasurementContainer<Content>
{
/// The `UIView` content that's being measured by the enclosing `SwiftUIMeasurementContainer`.
associatedtype Content: ViewType
/// The sizing strategy of the represented view.
///
/// To configure the sizing behavior of the `View` instance, call `sizing` on this `View`, e.g.:
/// ```
/// myView.sizing(.intrinsicSize)
/// ```
var sizing: SwiftUIMeasurementContainerStrategy { get set }
}
// MARK: Extensions
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension MeasuringViewRepresentable {
/// Returns a copy of this view with its sizing strategy updated to the given `sizing` value.
func sizing(_ strategy: SwiftUIMeasurementContainerStrategy) -> Self {
var copy = self
copy.sizing = strategy
return copy
}
}
// MARK: Defaults
#if os(iOS) || os(tvOS)
@available(iOS 13.0, tvOS 13.0, *)
extension MeasuringViewRepresentable {
func _overrideSizeThatFits(
_ size: inout CGSize,
in proposedSize: _ProposedSize,
uiView: UIViewType)
{
uiView.strategy = sizing
// Note: this method is not double-called on iOS 16, so we don't need to do anything to prevent
// extra work here.
let children = Mirror(reflecting: proposedSize).children
// Creates a `CGSize` by replacing `nil`s with `UIView.noIntrinsicMetric`
uiView.proposedSize = .init(
width: children.first { $0.label == "width" }?.value as? CGFloat ?? ViewType.noIntrinsicMetric,
height: children.first { $0.label == "height" }?.value as? CGFloat ?? ViewType.noIntrinsicMetric)
size = uiView.measuredFittingSize
}
#if swift(>=5.7) // Proxy check for being built with the iOS 15 SDK
@available(iOS 16.0, tvOS 16.0, macOS 13.0, *)
func sizeThatFits(
_ proposal: ProposedViewSize,
uiView: UIViewType,
context _: Context)
-> CGSize?
{
uiView.strategy = sizing
// Creates a size by replacing `nil`s with `UIView.noIntrinsicMetric`
uiView.proposedSize = .init(
width: proposal.width ?? ViewType.noIntrinsicMetric,
height: proposal.height ?? ViewType.noIntrinsicMetric)
return uiView.measuredFittingSize
}
#endif
}
#elseif os(macOS)
@available(macOS 10.15, *)
extension MeasuringViewRepresentable {
func _overrideSizeThatFits(
_ size: inout CGSize,
in proposedSize: _ProposedSize,
nsView: NSViewType)
{
nsView.strategy = sizing
let children = Mirror(reflecting: proposedSize).children
// Creates a `CGSize` by replacing `nil`s with `UIView.noIntrinsicMetric`
nsView.proposedSize = .init(
width: children.first { $0.label == "width" }?.value as? CGFloat ?? ViewType.noIntrinsicMetric,
height: children.first { $0.label == "height" }?.value as? CGFloat ?? ViewType.noIntrinsicMetric)
size = nsView.measuredFittingSize
}
// Proxy check for being built with the macOS 13 SDK.
#if swift(>=5.7.1)
@available(macOS 13.0, *)
func sizeThatFits(
_ proposal: ProposedViewSize,
nsView: NSViewType,
context _: Context)
-> CGSize?
{
nsView.strategy = sizing
// Creates a size by replacing `nil`s with `UIView.noIntrinsicMetric`
nsView.proposedSize = .init(
width: proposal.width ?? ViewType.noIntrinsicMetric,
height: proposal.height ?? ViewType.noIntrinsicMetric)
return nsView.measuredFittingSize
}
#endif
}
#endif
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/LayoutUtilities/MeasuringViewRepresentable.swift
|
Swift
|
unknown
| 4,037
|
// Created by Bryn Bodayle on 1/24/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
// MARK: - SwiftUIMeasurementContainer
/// A view that has an `intrinsicContentSize` of the `uiView`'s `systemLayoutSizeFitting(…)` and
/// supports double layout pass sizing and content size category changes.
///
/// This container view uses an injected proposed width to measure the view and return its ideal
/// height through the `SwiftUISizingContext` binding.
///
/// - SeeAlso: ``MeasuringViewRepresentable``
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
final class SwiftUIMeasurementContainer<Content: ViewType>: ViewType {
// MARK: Lifecycle
init(content: Content, strategy: SwiftUIMeasurementContainerStrategy) {
self.content = content
self.strategy = strategy
// On iOS 15 and below, passing zero can result in a constraint failure the first time a view
// is displayed, but the system gracefully recovers afterwards. On iOS 16, it's fine to pass
// zero.
let initialSize: CGSize
if #available(iOS 16, tvOS 16, macOS 13, *) {
initialSize = .zero
} else {
initialSize = .init(width: 375, height: 150)
}
super.init(frame: .init(origin: .zero, size: initialSize))
addSubview(content)
setUpConstraints()
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
/// The most recently measured fitting size of the `uiView` that fits within the current
/// `proposedSize`.
///
/// Contains `proposedSize`/`bounds.size` fallbacks for dimensions with no intrinsic size, as
/// compared to `intrinsicContentSize` which has `UIView.noIntrinsicMetric` fields in the case of
/// no intrinsic size.
var measuredFittingSize: CGSize {
_measuredFittingSize ?? measureView()
}
/// The `UIView` content that's being measured by this container.
var content: Content {
didSet {
guard content !== oldValue else { return }
oldValue.removeFromSuperview()
addSubview(content)
// Invalidate the strategy since it's derived from this view.
_resolvedStrategy = nil
// Re-configure the constraints since they depend on the resolved strategy.
setUpConstraints()
// Finally, we need to re-measure the view.
_measuredFittingSize = nil
}
}
/// The proposed size at the time of the latest measurement.
///
/// Has a side-effect of updating the `measuredIntrinsicContentSize` if it's changed.
var proposedSize = CGSize.noIntrinsicMetric {
didSet {
guard oldValue != proposedSize else { return }
// The proposed size is only used by the measurement, so just re-measure.
_measuredFittingSize = nil
}
}
/// The measurement strategy of this container.
///
/// Has a side-effect of updating the `measuredIntrinsicContentSize` if it's changed.
var strategy: SwiftUIMeasurementContainerStrategy {
didSet {
guard oldValue != strategy else { return }
// Invalidate the resolved strategy since it's derived from this strategy.
_resolvedStrategy = nil
// Then, re-measure the view.
_measuredFittingSize = nil
}
}
override var intrinsicContentSize: CGSize {
_intrinsicContentSize
}
#if os(macOS)
override func layout() {
super.layout()
// We need to re-measure the view whenever the size of the bounds changes, as the previous size
// may now be incorrect.
if latestMeasurementBoundsSize != nil, bounds.size != latestMeasurementBoundsSize {
// This will trigger SwiftUI to re-measure the view.
super.invalidateIntrinsicContentSize()
}
}
#else
override func layoutSubviews() {
super.layoutSubviews()
// We need to re-measure the view whenever the size of the bounds changes, as the previous size
// may now be incorrect.
if latestMeasurementBoundsSize != nil, bounds.size != latestMeasurementBoundsSize {
// This will trigger SwiftUI to re-measure the view.
super.invalidateIntrinsicContentSize()
}
}
#endif
override func invalidateIntrinsicContentSize() {
super.invalidateIntrinsicContentSize()
// Invalidate the resolved strategy in case it changes with the re-measurement as it relies on
// the intrinsic size.
_resolvedStrategy = nil
_measuredFittingSize = nil
}
// MARK: Private
/// The most recently measured intrinsic content size of the `uiView`, else `noIntrinsicMetric` if
/// it has not yet been measured.
///
/// Contains `UIView.noIntrinsicMetric` fallbacks for dimensions with no intrinsic size,
/// as compared to `measuredFittingSize` which has `proposedSize`/`bounds.size` fallbacks.
private var _intrinsicContentSize = CGSize.noIntrinsicMetric
/// The bounds size at the time of the latest measurement.
private var latestMeasurementBoundsSize: CGSize?
/// The most recently updated set of constraints constraining `uiView` to `self`.
private var uiViewConstraints = [NSLayoutConstraint.Attribute: NSLayoutConstraint]()
/// The cached `resolvedStrategy` to prevent unnecessary re-measurements.
private var _resolvedStrategy: ResolvedSwiftUIMeasurementContainerStrategy?
/// The cached `measuredFittingSize` to prevent unnecessary re-measurements.
private var _measuredFittingSize: CGSize?
/// The resolved measurement strategy.
private var resolvedStrategy: ResolvedSwiftUIMeasurementContainerStrategy {
if let resolvedStrategy = _resolvedStrategy {
return resolvedStrategy
}
let resolved: ResolvedSwiftUIMeasurementContainerStrategy
switch strategy {
case .automatic:
// Perform an intrinsic size measurement pass, which gives us valid values for
// `UILabel.preferredMaxLayoutWidth`.
let intrinsicSize = content.systemLayoutFittingIntrinsicSize()
// If the view has a intrinsic width and contains a double layout pass subview, give it the
// proposed width to allow the label content to gracefully wrap to multiple lines.
if intrinsicSize.width > 0, content.containsDoubleLayoutPassSubviews() {
resolved = .intrinsicHeightProposedWidth
} else {
let zero = CGFloat(0)
switch (width: intrinsicSize.width, height: intrinsicSize.height) {
case (width: ...zero, height: ...zero):
resolved = .proposed
case (width: ...zero, height: zero.nextUp...):
resolved = .intrinsicHeightProposedWidth
case (width: zero.nextUp..., height: ...zero):
resolved = .intrinsicWidthProposedHeight
default:
resolved = .intrinsic(intrinsicSize)
}
}
case .proposed:
resolved = .proposed
case .intrinsicHeightProposedWidth:
resolved = .intrinsicHeightProposedWidth
case .intrinsicWidthProposedHeight:
resolved = .intrinsicWidthProposedHeight
case .intrinsic:
resolved = .intrinsic(content.systemLayoutFittingIntrinsicSize())
}
_resolvedStrategy = resolved
return resolved
}
private func setUpConstraints() {
content.translatesAutoresizingMaskIntoConstraints = false
let leading = content.leadingAnchor.constraint(equalTo: leadingAnchor)
let top = content.topAnchor.constraint(equalTo: topAnchor)
let trailing = content.trailingAnchor.constraint(equalTo: trailingAnchor)
let bottom = content.bottomAnchor.constraint(equalTo: bottomAnchor)
let newConstraints: [NSLayoutConstraint.Attribute: NSLayoutConstraint] = [
.leading: leading, .top: top, .trailing: trailing, .bottom: bottom,
]
// Start with the lowest priority constraints so we aren't measuring the view too early, the
// priorities will be updated later on.
prioritizeConstraints(newConstraints, strategy: .intrinsic(.zero))
NSLayoutConstraint.deactivate(Array(uiViewConstraints.values))
uiViewConstraints = newConstraints
NSLayoutConstraint.activate(Array(uiViewConstraints.values))
}
/// Prioritizes the given constraints based on the provided resolved strategy.
private func prioritizeConstraints(
_ constraints: [NSLayoutConstraint.Attribute: NSLayoutConstraint],
strategy: ResolvedSwiftUIMeasurementContainerStrategy)
{
// Give a required constraint in the dimensions that are fixed to the bounds, otherwise almost
// required.
switch strategy {
case .proposed:
constraints[.trailing]?.priority = .required
constraints[.bottom]?.priority = .required
case .intrinsicHeightProposedWidth:
constraints[.trailing]?.priority = .required
constraints[.bottom]?.priority = .almostRequired
case .intrinsicWidthProposedHeight:
constraints[.trailing]?.priority = .almostRequired
constraints[.bottom]?.priority = .required
case .intrinsic:
constraints[.trailing]?.priority = .almostRequired
constraints[.bottom]?.priority = .almostRequired
}
#if os(macOS)
// On macOS, views default to having required constraints setting their height / width
// equal to their intrinsic content size. These have to be disabled in favor of the constraints
// we create here.
content.isVerticalContentSizeConstraintActive = false
content.isHorizontalContentSizeConstraintActive = false
#endif
}
/// Measures the `uiView`, storing the resulting size in `measuredIntrinsicContentSize`.
private func measureView() -> CGSize {
latestMeasurementBoundsSize = bounds.size
prioritizeConstraints(uiViewConstraints, strategy: resolvedStrategy)
var measuredSize: CGSize
let proposedSizeElseBounds = proposedSize.replacingNoIntrinsicMetric(with: bounds.size)
switch resolvedStrategy {
case .proposed:
measuredSize = .noIntrinsicMetric
case .intrinsicHeightProposedWidth:
measuredSize = content.systemLayoutFittingIntrinsicHeightFixedWidth(proposedSizeElseBounds.width)
measuredSize.width = ViewType.noIntrinsicMetric
case .intrinsicWidthProposedHeight:
measuredSize = content.systemLayoutFittingIntrinsicWidthFixedHeight(proposedSizeElseBounds.height)
measuredSize.height = ViewType.noIntrinsicMetric
case .intrinsic(let size):
measuredSize = size
// If the measured size exceeds an available width or height, set the measured size to
// `noIntrinsicMetric` to ensure that the component can be compressed, otherwise it will
// overflow beyond the proposed size.
// - If the previous intrinsic content size is the same as the new proposed size, we don't
// do this as SwiftUI sometimes "proposes" the same intrinsic size back to the component and
// we don't want that scenario to prevent size changes when there is actually more space
// available.
if
proposedSize.width != ViewType.noIntrinsicMetric,
measuredSize.width > proposedSizeElseBounds.width,
_intrinsicContentSize.width != proposedSize.width
{
measuredSize.width = ViewType.noIntrinsicMetric
}
if
proposedSize.height != ViewType.noIntrinsicMetric,
measuredSize.height > proposedSizeElseBounds.height,
_intrinsicContentSize.height != proposedSize.height
{
measuredSize.height = ViewType.noIntrinsicMetric
}
}
_intrinsicContentSize = measuredSize
let measuredFittingSize = measuredSize.replacingNoIntrinsicMetric(with: proposedSizeElseBounds)
_measuredFittingSize = measuredFittingSize
return measuredFittingSize
}
}
// MARK: - SwiftUIMeasurementContainerStrategy
/// The measurement strategy of a `SwiftUIMeasurementContainer`.
enum SwiftUIMeasurementContainerStrategy {
/// The container makes a best effort to correctly choose the measurement strategy of the view.
///
/// The best effort is based on a number of heuristics:
/// - The `uiView` will be given its intrinsic width and/or height when measurement in that
/// dimension produces a positive value, while zero/negative values will result in that
/// dimension receiving the available space proposed by the parent.
/// - If the view contains `UILabel` subviews that require a double layout pass as determined by
/// a `preferredMaxLayoutWidth` that's greater than zero after a layout, then the view will
/// default to `intrinsicHeightProposedWidth` to allow the labels to wrap.
///
/// If you would like to opt out of automatic sizing for performance or to override the default
/// behavior, choose another strategy.
case automatic
/// The `uiView` is sized to fill the area proposed by its parent.
///
/// Typically used for views that should expand greedily in both axes, e.g. a background view.
case proposed
/// The `uiView` is sized with its intrinsic height and expands horizontally to fill the width
/// proposed by its parent.
///
/// Typically used for views that have a height that's a function of their width, e.g. a row with
/// text that can wrap to multiple lines.
case intrinsicHeightProposedWidth
/// The `uiView` is sized with its intrinsic width and expands vertically to fill the height
/// proposed by its parent.
///
/// Typically used for views that are free to grow vertically but have a fixed width, e.g. a view
/// in a horizontal carousel.
case intrinsicWidthProposedHeight
/// The `uiView` is sized to its intrinsic width and height.
///
/// Typically used for components with a specific intrinsic size in both axes, e.g. controls or
/// inputs.
case intrinsic
}
// MARK: - ResolvedSwiftUIMeasurementContainerStrategy
/// The resolved measurement strategy of a `SwiftUIMeasurementContainer`, matching the cases of the
/// `SwiftUIMeasurementContainerStrategy` without the automatic case.
private enum ResolvedSwiftUIMeasurementContainerStrategy {
case proposed, intrinsicHeightProposedWidth, intrinsicWidthProposedHeight, intrinsic(CGSize)
}
// MARK: - UILayoutPriority
extension LayoutPriorityType {
/// An "almost required" constraint, useful for creating near-required constraints that don't
/// error when unable to be satisfied.
@nonobjc
fileprivate static var almostRequired: LayoutPriorityType { .init(rawValue: required.rawValue - 1) }
}
// MARK: - UIView
extension ViewType {
/// The `systemLayoutSizeFitting(…)` of this view with a compressed size and fitting priorities.
@nonobjc
fileprivate func systemLayoutFittingIntrinsicSize() -> CGSize {
#if os(macOS)
intrinsicContentSize
#else
systemLayoutSizeFitting(
UIView.layoutFittingCompressedSize,
withHorizontalFittingPriority: .fittingSizeLevel,
verticalFittingPriority: .fittingSizeLevel)
#endif
}
/// The `systemLayoutSizeFitting(…)` of this view with a compressed height with a fitting size
/// priority and with the given fixed width and fitting priority.
@nonobjc
fileprivate func systemLayoutFittingIntrinsicHeightFixedWidth(
_ width: CGFloat,
priority: LayoutPriorityType = .almostRequired)
-> CGSize
{
#if os(macOS)
return CGSize(width: width, height: intrinsicContentSize.height)
#else
let targetSize = CGSize(width: width, height: UIView.layoutFittingCompressedSize.height)
return systemLayoutSizeFitting(
targetSize,
withHorizontalFittingPriority: priority,
verticalFittingPriority: .fittingSizeLevel)
#endif
}
/// The `systemLayoutSizeFitting(…)` of this view with a compressed width with a fitting size
/// priority and with the given fixed height and fitting priority.
@nonobjc
fileprivate func systemLayoutFittingIntrinsicWidthFixedHeight(
_ height: CGFloat,
priority: LayoutPriorityType = .almostRequired)
-> CGSize
{
#if os(macOS)
return CGSize(width: intrinsicContentSize.width, height: height)
#else
let targetSize = CGSize(width: UIView.layoutFittingCompressedSize.width, height: height)
return systemLayoutSizeFitting(
targetSize,
withHorizontalFittingPriority: .fittingSizeLevel,
verticalFittingPriority: priority)
#endif
}
/// Whether this view or any of its subviews has a subview that has a double layout pass `UILabel`
/// as determined by a non-zero `preferredMaxLayoutWidth`, which implies that it should get a
/// `intrinsicHeightProposedWidth` sizing strategy to allow the label to wrap and grow.
@nonobjc
fileprivate func containsDoubleLayoutPassSubviews() -> Bool {
#if os(macOS)
return false
#else
var contains = false
if let label = self as? UILabel, label.preferredMaxLayoutWidth > 0 {
contains = true
}
for subview in subviews {
contains = contains || subview.containsDoubleLayoutPassSubviews()
}
return contains
#endif
}
}
// MARK: - CGSize
extension CGSize {
/// A `CGSize` with `noIntrinsicMetric` for both its width and height.
fileprivate static var noIntrinsicMetric: CGSize {
.init(width: ViewType.noIntrinsicMetric, height: ViewType.noIntrinsicMetric)
}
/// Returns a `CGSize` with its width and/or height replaced with the corresponding field of the
/// provided `fallback` size if they are `UIView.noIntrinsicMetric`.
fileprivate func replacingNoIntrinsicMetric(with fallback: CGSize) -> CGSize {
.init(
width: width == ViewType.noIntrinsicMetric ? fallback.width : width,
height: height == ViewType.noIntrinsicMetric ? fallback.height : height)
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/LayoutUtilities/SwiftUIMeasurementContainer.swift
|
Swift
|
unknown
| 17,490
|
// Created by eric_horacek on 9/8/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
// MARK: - SwiftUIView
/// A `UIViewRepresentable` SwiftUI `View` that wraps its `Content` `UIView` within a
/// `SwiftUIMeasurementContainer`, used to size a UIKit view correctly within a SwiftUI view
/// hierarchy.
///
/// Includes an optional generic `Storage` value, which can be used to compare old and new values
/// across state changes to prevent redundant view updates.
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
struct SwiftUIView<Content: ViewType, Storage>: MeasuringViewRepresentable,
UIViewConfiguringSwiftUIView
{
// MARK: Lifecycle
/// Creates a SwiftUI representation of the content view with the given storage and the provided
/// `makeContent` closure to construct the content whenever `makeUIView(…)` is invoked.
init(storage: Storage, makeContent: @escaping () -> Content) {
self.storage = storage
self.makeContent = makeContent
}
/// Creates a SwiftUI representation of the content view with the provided `makeContent` closure
/// to construct it whenever `makeUIView(…)` is invoked.
init(makeContent: @escaping () -> Content) where Storage == Void {
storage = ()
self.makeContent = makeContent
}
// MARK: Internal
var configurations: [Configuration] = []
var sizing: SwiftUIMeasurementContainerStrategy = .automatic
// MARK: Private
/// The current stored value, with the previous value provided to the configuration closure as
/// the `oldStorage`.
private var storage: Storage
/// A closure that's invoked to construct the represented content view.
private var makeContent: () -> Content
}
// MARK: UIViewRepresentable
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension SwiftUIView {
func makeCoordinator() -> Coordinator {
Coordinator(storage: storage)
}
#if os(macOS)
func makeNSView(context _: Context) -> SwiftUIMeasurementContainer<Content> {
SwiftUIMeasurementContainer(content: makeContent(), strategy: sizing)
}
func updateNSView(_ uiView: SwiftUIMeasurementContainer<Content>, context: Context) {
let oldStorage = context.coordinator.storage
context.coordinator.storage = storage
let configurationContext = ConfigurationContext(
oldStorage: oldStorage,
viewRepresentableContext: context,
container: uiView)
for configuration in configurations {
configuration(configurationContext)
}
}
#else
func makeUIView(context _: Context) -> SwiftUIMeasurementContainer<Content> {
SwiftUIMeasurementContainer(content: makeContent(), strategy: sizing)
}
func updateUIView(_ uiView: SwiftUIMeasurementContainer<Content>, context: Context) {
let oldStorage = context.coordinator.storage
context.coordinator.storage = storage
let configurationContext = ConfigurationContext(
oldStorage: oldStorage,
viewRepresentableContext: context,
container: uiView)
for configuration in configurations {
configuration(configurationContext)
}
}
#endif
}
// MARK: SwiftUIView.ConfigurationContext
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension SwiftUIView {
/// The configuration context that's available to configure the `Content` view whenever the
/// `updateUIView()` method is invoked via a configuration closure.
struct ConfigurationContext: ViewProviding {
/// The previous value for the `Storage` of this `SwiftUIView`, which can be used to store
/// values across state changes to prevent redundant view updates.
var oldStorage: Storage
/// The `UIViewRepresentable.Context`, with information about the transaction and environment.
var viewRepresentableContext: Context
/// The backing measurement container that contains the `Content`.
var container: SwiftUIMeasurementContainer<Content>
/// The `UIView` content that's being configured.
///
/// Setting this to a new value updates the backing measurement container's `content`.
var view: Content {
get { container.content }
nonmutating set { container.content = newValue }
}
/// A convenience accessor indicating whether this content update should be animated.
var animated: Bool {
viewRepresentableContext.transaction.animation != nil
}
}
}
// MARK: SwiftUIView.Coordinator
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension SwiftUIView {
/// A coordinator that stores the `storage` associated with this view, enabling the old storage
/// value to be accessed during the `updateUIView(…)`.
final class Coordinator {
// MARK: Lifecycle
fileprivate init(storage: Storage) {
self.storage = storage
}
// MARK: Internal
fileprivate(set) var storage: Storage
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/SwiftUIView.swift
|
Swift
|
unknown
| 4,827
|
// Created by eric_horacek on 3/3/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
// MARK: - ViewTypeProtocol + swiftUIView
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension ViewTypeProtocol {
/// Returns a SwiftUI `View` representing this `UIView`, constructed with the given `makeView`
/// closure and sized with the given sizing configuration.
///
/// To perform additional configuration of the `UIView` instance, call `configure` on the
/// returned SwiftUI `View`:
/// ```
/// MyUIView.swiftUIView(…)
/// .configure { context in
/// context.view.doSomething()
/// }
/// ```
///
/// To configure the sizing behavior of the `UIView` instance, call `sizing` on the returned
/// SwiftUI `View`:
/// ```
/// MyView.swiftUIView(…).sizing(.intrinsicSize)
/// ```
/// The sizing defaults to `.automatic`.
static func swiftUIView(makeView: @escaping () -> Self) -> SwiftUIView<Self, Void> {
SwiftUIView(makeContent: makeView)
}
}
// MARK: - ViewTypeProtocol
/// A protocol that all `UIView`s conform to, enabling extensions that have a `Self` reference.
protocol ViewTypeProtocol: ViewType { }
// MARK: - ViewType + ViewTypeProtocol
extension ViewType: ViewTypeProtocol { }
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/UIView+SwiftUIView.swift
|
Swift
|
unknown
| 1,296
|
// Created by eric_horacek on 3/4/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
// MARK: - UIViewConfiguringSwiftUIView
/// A protocol describing a SwiftUI `View` that can configure its `UIView` content via an array of
/// `configuration` closures.
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
protocol UIViewConfiguringSwiftUIView: View {
/// The context available to this configuration, which provides the `UIView` instance at a minimum
/// but can include additional context as needed.
associatedtype ConfigurationContext: ViewProviding
/// A closure that is invoked to configure the represented content view.
typealias Configuration = (ConfigurationContext) -> Void
/// A mutable array of configuration closures that should each be invoked with the
/// `ConfigurationContext` whenever `updateUIView` is called in a `UIViewRepresentable`.
var configurations: [Configuration] { get set }
}
// MARK: Extensions
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension UIViewConfiguringSwiftUIView {
/// Returns a copy of this view updated to have the given closure applied to its represented view
/// whenever it is updated via the `updateUIView(…)` method.
func configure(_ configure: @escaping Configuration) -> Self {
var copy = self
copy.configurations.append(configure)
return copy
}
/// Returns a copy of this view updated to have the given closures applied to its represented view
/// whenever it is updated via the `updateUIView(…)` method.
func configurations(_ configurations: [Configuration]) -> Self {
var copy = self
copy.configurations.append(contentsOf: configurations)
return copy
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/SwiftUI/UIViewConfiguringSwiftUIView.swift
|
Swift
|
unknown
| 1,731
|
// Created by Tyler Hedrick on 5/26/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - BehaviorsConfigurableView
/// A view that can be configured with a `Behaviors` instance that contains the view's non-
/// `Equatable` properties that can be updated on view instances after initialization, e.g. callback
/// closures or delegates.
///
/// Since it is not possible to establish the equality of two `Behaviors` instances, `Behaviors`
/// will be set more often than `ContentConfigurableView.Content`, needing to be updated every time
/// the view's corresponding `EpoxyModeled` instance is updated. As such, setting behaviors should
/// be as lightweight as possible.
///
/// Properties of `Behaviors` should be mutually exclusive with the properties in the
/// `StyledView.Style` and `ContentConfigurableView.Content`.
///
/// - SeeAlso: `ContentConfigurableView`
/// - SeeAlso: `StyledView`
/// - SeeAlso: `EpoxyableView`
protocol BehaviorsConfigurableView: ViewType {
/// The non-`Equatable` properties that can be changed over of the lifecycle this View's
/// instances, e.g. callback closures or delegates.
///
/// Defaults to `Never` for views that do not have `Behaviors`.
associatedtype Behaviors = Never
/// Updates the behaviors of this view to those in the given `behaviors`, else resets the
/// behaviors if `nil`.
///
/// Behaviors are optional as they must be "resettable" in order for Epoxy to reset the behaviors
/// on your view when no behaviors are provided.
func setBehaviors(_ behaviors: Self.Behaviors?)
}
// MARK: Defaults
extension BehaviorsConfigurableView where Behaviors == Never {
func setBehaviors(_ behaviors: Never?) {
switch behaviors {
case nil:
break
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Views/BehaviorsConfigurableView.swift
|
Swift
|
unknown
| 1,760
|
// Created by Laura Skelton on 5/30/17.
// Copyright © 2017 Airbnb. All rights reserved.
// MARK: - ContentConfigurableView
/// A view that can be configured with a `Content` instance that contains the view's `Equatable`
/// properties that can be updated on existing view instances, e.g. text `String`s or image `URL`s.
///
/// For performance, it is generally expected that `Content` is only set when it is not equal to the
/// previous `Content` instance that has been set on a view instance. As a further optimization,
/// this view can guard updates on the equality of each property of the `Content` against the
/// current property value when set.
///
/// Properties of `Content` should be mutually exclusive with the properties of the
/// `StyledView.Style` and `BehaviorsConfigurableView.Behaviors`.
///
/// - SeeAlso: `BehaviorsConfigurableView`
/// - SeeAlso: `StyledView`
/// - SeeAlso: `EpoxyableView`
protocol ContentConfigurableView: ViewType {
/// The `Equatable` properties that can be updated on instances of this view, e.g. text `String`s
/// or image `URL`s.
///
/// Defaults to `Never` for views that do not have `Content`.
associatedtype Content: Equatable = Never
/// Updates the content of this view to the properties of the given `content`, optionally
/// animating the updates.
func setContent(_ content: Self.Content, animated: Bool)
}
// MARK: Defaults
extension ContentConfigurableView where Content == Never {
func setContent(_: Never, animated _: Bool) { }
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Views/ContentConfigurableView.swift
|
Swift
|
unknown
| 1,516
|
// Created by eric_horacek on 1/13/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
/// A `UIView` that can be declaratively configured via a concrete `EpoxyableModel` instance.
typealias EpoxyableView = BehaviorsConfigurableView & ContentConfigurableView & StyledView
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Views/EpoxyableView.swift
|
Swift
|
unknown
| 279
|
// Created by Laura Skelton on 4/14/16.
// Copyright © 2016 Airbnb. All rights reserved.
// MARK: - StyledView
/// A view that can be initialized with a `Style` instance that contains the view's invariant
/// configuration parameters, e.g. the `UIButton.ButtonType` of a `UIButton`.
///
/// A `Style` is expected to be invariant over the lifecycle of the view; it should not possible to
/// change the `Style` of a view after it is created. All variant properties of the view should
/// either be included in the `ContentConfigurableView.Content` if they are `Equatable` (e.g. a
/// title `String`) or the `BehaviorsConfigurableView.Behaviors` if they are not (e.g. a callback
/// closure).
///
/// A `Style` is `Hashable` to allow views of the same type with equal `Style`s to be reused by
/// establishing whether their invariant `Style` instances are equal.
///
/// Properties of `Style` should be mutually exclusive with the properties of the
/// `ContentConfigurableView.Content` and `BehaviorsConfigurableView.Behaviors`.
///
/// - SeeAlso: `ContentConfigurableView`
/// - SeeAlso: `BehaviorsConfigurableView`
/// - SeeAlso: `EpoxyableView`
protocol StyledView: ViewType {
/// The style type of this view, passed into its initializer to configure the resulting instance.
///
/// Defaults to `Never` for views that do not have a `Style`.
associatedtype Style: Hashable = Never
/// Creates an instance of this view configured with the given `Style` instance.
init(style: Style)
}
// MARK: Defaults
extension StyledView where Style == Never {
init(style: Never) {
// An empty switch is required to silence the "'self.init' isn't called on all paths before
// returning from initializer" error.
switch style { }
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Views/StyledView.swift
|
Swift
|
unknown
| 1,755
|
// Created by Cal Stephens on 6/26/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
#if canImport(UIKit)
import UIKit
/// The platform's main view type.
/// Either `UIView` on iOS/tvOS or `NSView` on macOS.
typealias ViewType = UIView
/// The platform's SwiftUI view representable type.
/// Either `UIViewRepresentable` on iOS/tvOS or `NSViewRepresentable` on macOS.
@available(iOS 13.0, tvOS 13.0, *)
typealias ViewRepresentableType = UIViewRepresentable
/// The platform's layout constraint priority type.
/// Either `UILayoutPriority` on iOS/tvOS or `NSLayoutConstraint.Priority` on macOS.
typealias LayoutPriorityType = UILayoutPriority
@available(iOS 13.0, tvOS 13.0, *)
extension ViewRepresentableType {
/// The platform's view type for `ViewRepresentableType`.
/// Either `UIViewType` on iOS/tvOS or `NSViewType` on macOS.
typealias RepresentableViewType = UIViewType
}
#elseif canImport(AppKit)
import AppKit
/// The platform's main view type.
/// Either `UIView` on iOS/tvOS, or `NSView` on macOS.
typealias ViewType = NSView
/// The platform's SwiftUI view representable type.
/// Either `UIViewRepresentable` on iOS/tvOS, or `NSViewRepresentable` on macOS.
@available(macOS 10.15, *)
typealias ViewRepresentableType = NSViewRepresentable
/// The platform's layout constraint priority type.
/// Either `UILayoutPriority` on iOS/tvOS, or `NSLayoutConstraint.Priority` on macOS.
typealias LayoutPriorityType = NSLayoutConstraint.Priority
@available(macOS 10.15, *)
extension ViewRepresentableType {
/// The platform's view type for `ViewRepresentableType`.
/// Either `UIViewType` on iOS/tvOS or `NSViewType` on macOS.
typealias RepresentableViewType = NSViewType
}
#endif
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Views/ViewType.swift
|
Swift
|
unknown
| 1,757
|
//
// LRUCache.swift
// LRUCache
//
// Version 1.0.2
//
// Created by Nick Lockwood on 05/08/2021.
// Copyright © 2021 Nick Lockwood. All rights reserved.
//
// Distributed under the permissive MIT license
// Get the latest version from here:
//
// https://github.com/nicklockwood/LRUCache
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
#if canImport(UIKit)
import UIKit
/// Notification that cache should be cleared
let LRUCacheMemoryWarningNotification: NSNotification.Name =
UIApplication.didReceiveMemoryWarningNotification
#else
/// Notification that cache should be cleared
let LRUCacheMemoryWarningNotification: NSNotification.Name =
.init("LRUCacheMemoryWarningNotification")
#endif
// MARK: - LRUCache
final class LRUCache<Key: Hashable, Value> {
// MARK: Lifecycle
/// Initialize the cache with the specified `totalCostLimit` and `countLimit`
init(
totalCostLimit: Int = .max,
countLimit: Int = .max,
notificationCenter: NotificationCenter = .default)
{
self.totalCostLimit = totalCostLimit
self.countLimit = countLimit
self.notificationCenter = notificationCenter
token = notificationCenter.addObserver(
forName: LRUCacheMemoryWarningNotification,
object: nil,
queue: nil)
{ [weak self] _ in
self?.removeAllValues()
}
}
deinit {
if let token {
notificationCenter.removeObserver(token)
}
}
// MARK: Internal
/// The current total cost of values in the cache
private(set) var totalCost = 0
/// The maximum total cost permitted
var totalCostLimit: Int {
didSet { clean() }
}
/// The maximum number of values permitted
var countLimit: Int {
didSet { clean() }
}
// MARK: Private
private var values: [Key: Container] = [:]
private unowned(unsafe) var head: Container?
private unowned(unsafe) var tail: Container?
private let lock: NSLock = .init()
private var token: AnyObject?
private let notificationCenter: NotificationCenter
}
extension LRUCache {
/// The number of values currently stored in the cache
var count: Int {
values.count
}
/// Is the cache empty?
var isEmpty: Bool {
values.isEmpty
}
/// Returns all values in the cache from oldest to newest
var allValues: [Value] {
lock.lock()
defer { lock.unlock() }
var values = [Value]()
var next = head
while let container = next {
values.append(container.value)
next = container.next
}
return values
}
/// Insert a value into the cache with optional `cost`
func setValue(_ value: Value?, forKey key: Key, cost: Int = 0) {
guard let value else {
removeValue(forKey: key)
return
}
lock.lock()
if let container = values[key] {
container.value = value
totalCost -= container.cost
container.cost = cost
remove(container)
append(container)
} else {
let container = Container(
value: value,
cost: cost,
key: key)
values[key] = container
append(container)
}
totalCost += cost
lock.unlock()
clean()
}
/// Remove a value from the cache and return it
@discardableResult
func removeValue(forKey key: Key) -> Value? {
lock.lock()
defer { lock.unlock() }
guard let container = values.removeValue(forKey: key) else {
return nil
}
remove(container)
totalCost -= container.cost
return container.value
}
/// Fetch a value from the cache
func value(forKey key: Key) -> Value? {
lock.lock()
defer { lock.unlock() }
if let container = values[key] {
remove(container)
append(container)
return container.value
}
return nil
}
/// Remove all values from the cache
func removeAllValues() {
lock.lock()
values.removeAll()
head = nil
tail = nil
lock.unlock()
}
}
extension LRUCache {
// MARK: Fileprivate
fileprivate final class Container {
// MARK: Lifecycle
init(value: Value, cost: Int, key: Key) {
self.value = value
self.cost = cost
self.key = key
}
// MARK: Internal
var value: Value
var cost: Int
let key: Key
unowned(unsafe) var prev: Container?
unowned(unsafe) var next: Container?
}
// MARK: Private
// Remove container from list (must be called inside lock)
private func remove(_ container: Container) {
if head === container {
head = container.next
}
if tail === container {
tail = container.prev
}
container.next?.prev = container.prev
container.prev?.next = container.next
container.next = nil
}
// Append container to list (must be called inside lock)
private func append(_ container: Container) {
assert(container.next == nil)
if head == nil {
head = container
}
container.prev = tail
tail?.next = container
tail = container
}
// Remove expired values (must be called outside lock)
private func clean() {
lock.lock()
defer { lock.unlock() }
while
totalCost > totalCostLimit || count > countLimit,
let container = head
{
remove(container)
values.removeValue(forKey: container.key)
totalCost -= container.cost
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/LRUCache/LRUCache.swift
|
Swift
|
unknown
| 6,312
|
//
// Archive+BackingConfiguration.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
struct BackingConfiguration {
let file: FILEPointer
let endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord
let zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?
#if swift(>=5.0)
let memoryFile: MemoryFile?
init(
file: FILEPointer,
endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord,
zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory? = nil,
memoryFile: MemoryFile? = nil)
{
self.file = file
self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
self.zip64EndOfCentralDirectory = zip64EndOfCentralDirectory
self.memoryFile = memoryFile
}
#else
init(
file: FILEPointer,
endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord,
zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?)
{
self.file = file
self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
self.zip64EndOfCentralDirectory = zip64EndOfCentralDirectory
}
#endif
}
static func makeBackingConfiguration(for url: URL, mode: AccessMode)
-> BackingConfiguration?
{
let fileManager = FileManager()
switch mode {
case .read:
let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
guard
let archiveFile = fopen(fileSystemRepresentation, "rb"),
let (eocdRecord, zip64EOCD) = Archive.scanForEndOfCentralDirectoryRecord(in: archiveFile)
else {
return nil
}
return BackingConfiguration(
file: archiveFile,
endOfCentralDirectoryRecord: eocdRecord,
zip64EndOfCentralDirectory: zip64EOCD)
case .create:
let endOfCentralDirectoryRecord = EndOfCentralDirectoryRecord(
numberOfDisk: 0,
numberOfDiskStart: 0,
totalNumberOfEntriesOnDisk: 0,
totalNumberOfEntriesInCentralDirectory: 0,
sizeOfCentralDirectory: 0,
offsetToStartOfCentralDirectory: 0,
zipFileCommentLength: 0,
zipFileCommentData: Data())
do {
try endOfCentralDirectoryRecord.data.write(to: url, options: .withoutOverwriting)
} catch { return nil }
fallthrough
case .update:
let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
guard
let archiveFile = fopen(fileSystemRepresentation, "rb+"),
let (eocdRecord, zip64EOCD) = Archive.scanForEndOfCentralDirectoryRecord(in: archiveFile)
else {
return nil
}
fseeko(archiveFile, 0, SEEK_SET)
return BackingConfiguration(
file: archiveFile,
endOfCentralDirectoryRecord: eocdRecord,
zip64EndOfCentralDirectory: zip64EOCD)
}
}
#if swift(>=5.0)
static func makeBackingConfiguration(for data: Data, mode: AccessMode)
-> BackingConfiguration?
{
let posixMode: String
switch mode {
case .read: posixMode = "rb"
case .create: posixMode = "wb+"
case .update: posixMode = "rb+"
}
let memoryFile = MemoryFile(data: data)
guard let archiveFile = memoryFile.open(mode: posixMode) else { return nil }
switch mode {
case .read:
guard let (eocdRecord, zip64EOCD) = Archive.scanForEndOfCentralDirectoryRecord(in: archiveFile) else {
return nil
}
return BackingConfiguration(
file: archiveFile,
endOfCentralDirectoryRecord: eocdRecord,
zip64EndOfCentralDirectory: zip64EOCD,
memoryFile: memoryFile)
case .create:
let endOfCentralDirectoryRecord = EndOfCentralDirectoryRecord(
numberOfDisk: 0,
numberOfDiskStart: 0,
totalNumberOfEntriesOnDisk: 0,
totalNumberOfEntriesInCentralDirectory: 0,
sizeOfCentralDirectory: 0,
offsetToStartOfCentralDirectory: 0,
zipFileCommentLength: 0,
zipFileCommentData: Data())
_ = endOfCentralDirectoryRecord.data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
fwrite(buffer.baseAddress, buffer.count, 1, archiveFile) // Errors handled during read
}
fallthrough
case .update:
guard let (eocdRecord, zip64EOCD) = Archive.scanForEndOfCentralDirectoryRecord(in: archiveFile) else {
return nil
}
fseeko(archiveFile, 0, SEEK_SET)
return BackingConfiguration(
file: archiveFile,
endOfCentralDirectoryRecord: eocdRecord,
zip64EndOfCentralDirectory: zip64EOCD,
memoryFile: memoryFile)
}
}
#endif
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive+BackingConfiguration.swift
|
Swift
|
unknown
| 4,839
|
//
// Archive+Helpers.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
// MARK: - Reading
func readUncompressed(
entry: Entry,
bufferSize: Int,
skipCRC32: Bool,
progress: Progress? = nil,
with consumer: Consumer)
throws -> CRC32
{
let size = entry.centralDirectoryStructure.effectiveUncompressedSize
guard size <= .max else { throw ArchiveError.invalidEntrySize }
return try Data.consumePart(
of: Int64(size),
chunkSize: bufferSize,
skipCRC32: skipCRC32,
provider: { _, chunkSize -> Data in
try Data.readChunk(of: chunkSize, from: self.archiveFile)
},
consumer: { data in
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
try consumer(data)
progress?.completedUnitCount += Int64(data.count)
})
}
func readCompressed(
entry: Entry,
bufferSize: Int,
skipCRC32: Bool,
progress: Progress? = nil,
with consumer: Consumer)
throws -> CRC32
{
let size = entry.centralDirectoryStructure.effectiveCompressedSize
guard size <= .max else { throw ArchiveError.invalidEntrySize }
return try Data.decompress(
size: Int64(size),
bufferSize: bufferSize,
skipCRC32: skipCRC32,
provider: { _, chunkSize -> Data in
try Data.readChunk(of: chunkSize, from: self.archiveFile)
},
consumer: { data in
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
try consumer(data)
progress?.completedUnitCount += Int64(data.count)
})
}
// MARK: - Writing
func writeEntry(
uncompressedSize: Int64,
type: Entry.EntryType,
compressionMethod: CompressionMethod,
bufferSize: Int,
progress: Progress? = nil,
provider: Provider) throws -> (sizeWritten: Int64, crc32: CRC32)
{
var checksum = CRC32(0)
var sizeWritten = Int64(0)
switch type {
case .file:
switch compressionMethod {
case .none:
(sizeWritten, checksum) = try writeUncompressed(
size: uncompressedSize,
bufferSize: bufferSize,
progress: progress,
provider: provider)
case .deflate:
(sizeWritten, checksum) = try writeCompressed(
size: uncompressedSize,
bufferSize: bufferSize,
progress: progress,
provider: provider)
}
case .directory:
_ = try provider(0, 0)
if let progress { progress.completedUnitCount = progress.totalUnitCount }
case .symlink:
let (linkSizeWritten, linkChecksum) = try writeSymbolicLink(
size: Int(uncompressedSize),
provider: provider)
(sizeWritten, checksum) = (Int64(linkSizeWritten), linkChecksum)
if let progress { progress.completedUnitCount = progress.totalUnitCount }
}
return (sizeWritten, checksum)
}
func writeLocalFileHeader(
path: String,
compressionMethod: CompressionMethod,
size: (uncompressed: UInt64, compressed: UInt64),
checksum: CRC32,
modificationDateTime: (UInt16, UInt16))
throws -> LocalFileHeader
{
// We always set Bit 11 in generalPurposeBitFlag, which indicates an UTF-8 encoded path.
guard let fileNameData = path.data(using: .utf8) else { throw ArchiveError.invalidEntryPath }
var uncompressedSizeOfLFH = UInt32(0)
var compressedSizeOfLFH = UInt32(0)
var extraFieldLength = UInt16(0)
var zip64ExtendedInformation: Entry.ZIP64ExtendedInformation?
var versionNeededToExtract = Version.v20.rawValue
// ZIP64 Extended Information in the Local header MUST include BOTH original and compressed file size fields.
if size.uncompressed >= maxUncompressedSize || size.compressed >= maxCompressedSize {
uncompressedSizeOfLFH = .max
compressedSizeOfLFH = .max
extraFieldLength = UInt16(20) // 2 + 2 + 8 + 8
versionNeededToExtract = Version.v45.rawValue
zip64ExtendedInformation = Entry.ZIP64ExtendedInformation(
dataSize: extraFieldLength - 4,
uncompressedSize: size.uncompressed,
compressedSize: size.compressed,
relativeOffsetOfLocalHeader: 0,
diskNumberStart: 0)
} else {
uncompressedSizeOfLFH = UInt32(size.uncompressed)
compressedSizeOfLFH = UInt32(size.compressed)
}
let localFileHeader = LocalFileHeader(
versionNeededToExtract: versionNeededToExtract,
generalPurposeBitFlag: UInt16(2048),
compressionMethod: compressionMethod.rawValue,
lastModFileTime: modificationDateTime.1,
lastModFileDate: modificationDateTime.0,
crc32: checksum,
compressedSize: compressedSizeOfLFH,
uncompressedSize: uncompressedSizeOfLFH,
fileNameLength: UInt16(fileNameData.count),
extraFieldLength: extraFieldLength,
fileNameData: fileNameData,
extraFieldData: zip64ExtendedInformation?.data ?? Data())
_ = try Data.write(chunk: localFileHeader.data, to: archiveFile)
return localFileHeader
}
func writeCentralDirectoryStructure(
localFileHeader: LocalFileHeader,
relativeOffset: UInt64,
externalFileAttributes: UInt32)
throws -> CentralDirectoryStructure
{
var extraUncompressedSize: UInt64?
var extraCompressedSize: UInt64?
var extraOffset: UInt64?
var relativeOffsetOfCD = UInt32(0)
var extraFieldLength = UInt16(0)
var zip64ExtendedInformation: Entry.ZIP64ExtendedInformation?
if localFileHeader.uncompressedSize == .max || localFileHeader.compressedSize == .max {
let zip64Field = Entry.ZIP64ExtendedInformation
.scanForZIP64Field(in: localFileHeader.extraFieldData, fields: [.uncompressedSize, .compressedSize])
extraUncompressedSize = zip64Field?.uncompressedSize
extraCompressedSize = zip64Field?.compressedSize
}
if relativeOffset >= maxOffsetOfLocalFileHeader {
extraOffset = relativeOffset
relativeOffsetOfCD = .max
} else {
relativeOffsetOfCD = UInt32(relativeOffset)
}
extraFieldLength = [extraUncompressedSize, extraCompressedSize, extraOffset]
.compactMap { $0 }
.reduce(UInt16(0)) { $0 + UInt16(MemoryLayout.size(ofValue: $1)) }
if extraFieldLength > 0 {
// Size of extra fields, shouldn't include the leading 4 bytes
zip64ExtendedInformation = Entry.ZIP64ExtendedInformation(
dataSize: extraFieldLength,
uncompressedSize: extraUncompressedSize ?? 0,
compressedSize: extraCompressedSize ?? 0,
relativeOffsetOfLocalHeader: extraOffset ?? 0,
diskNumberStart: 0)
extraFieldLength += Entry.ZIP64ExtendedInformation.headerSize
}
let centralDirectory = CentralDirectoryStructure(
localFileHeader: localFileHeader,
fileAttributes: externalFileAttributes,
relativeOffset: relativeOffsetOfCD,
extraField: (
extraFieldLength,
zip64ExtendedInformation?.data ?? Data()))
_ = try Data.write(chunk: centralDirectory.data, to: archiveFile)
return centralDirectory
}
func writeEndOfCentralDirectory(
centralDirectoryStructure: CentralDirectoryStructure,
startOfCentralDirectory: UInt64,
startOfEndOfCentralDirectory: UInt64,
operation: ModifyOperation)
throws -> EndOfCentralDirectoryStructure
{
var record = endOfCentralDirectoryRecord
let sizeOfCD = sizeOfCentralDirectory
let numberOfTotalEntries = totalNumberOfEntriesInCentralDirectory
let countChange = operation.rawValue
var dataLength = centralDirectoryStructure.extraFieldLength
dataLength += centralDirectoryStructure.fileNameLength
dataLength += centralDirectoryStructure.fileCommentLength
let cdDataLengthChange = countChange * (Int(dataLength) + CentralDirectoryStructure.size)
let (updatedSizeOfCD, updatedNumberOfEntries): (UInt64, UInt64) = try {
switch operation {
case .add:
guard .max - sizeOfCD >= cdDataLengthChange else {
throw ArchiveError.invalidCentralDirectorySize
}
guard .max - numberOfTotalEntries >= countChange else {
throw ArchiveError.invalidCentralDirectoryEntryCount
}
return (sizeOfCD + UInt64(cdDataLengthChange), numberOfTotalEntries + UInt64(countChange))
case .remove:
return (sizeOfCD - UInt64(-cdDataLengthChange), numberOfTotalEntries - UInt64(-countChange))
}
}()
let sizeOfCDForEOCD = updatedSizeOfCD >= maxSizeOfCentralDirectory
? UInt32.max
: UInt32(updatedSizeOfCD)
let numberOfTotalEntriesForEOCD = updatedNumberOfEntries >= maxTotalNumberOfEntries
? UInt16.max
: UInt16(updatedNumberOfEntries)
let offsetOfCDForEOCD = startOfCentralDirectory >= maxOffsetOfCentralDirectory
? UInt32.max
: UInt32(startOfCentralDirectory)
// ZIP64 End of Central Directory
var zip64EOCD: ZIP64EndOfCentralDirectory?
if numberOfTotalEntriesForEOCD == .max || offsetOfCDForEOCD == .max || sizeOfCDForEOCD == .max {
zip64EOCD = try writeZIP64EOCD(
totalNumberOfEntries: updatedNumberOfEntries,
sizeOfCentralDirectory: updatedSizeOfCD,
offsetOfCentralDirectory: startOfCentralDirectory,
offsetOfEndOfCentralDirectory: startOfEndOfCentralDirectory)
}
record = EndOfCentralDirectoryRecord(
record: record,
numberOfEntriesOnDisk: numberOfTotalEntriesForEOCD,
numberOfEntriesInCentralDirectory: numberOfTotalEntriesForEOCD,
updatedSizeOfCentralDirectory: sizeOfCDForEOCD,
startOfCentralDirectory: offsetOfCDForEOCD)
_ = try Data.write(chunk: record.data, to: archiveFile)
return (record, zip64EOCD)
}
func writeUncompressed(
size: Int64,
bufferSize: Int,
progress: Progress? = nil,
provider: Provider) throws -> (sizeWritten: Int64, checksum: CRC32)
{
var position: Int64 = 0
var sizeWritten: Int64 = 0
var checksum = CRC32(0)
while position < size {
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
let readSize = (size - position) >= bufferSize ? bufferSize : Int(size - position)
let entryChunk = try provider(position, readSize)
checksum = entryChunk.crc32(checksum: checksum)
sizeWritten += Int64(try Data.write(chunk: entryChunk, to: archiveFile))
position += Int64(bufferSize)
progress?.completedUnitCount = sizeWritten
}
return (sizeWritten, checksum)
}
func writeCompressed(
size: Int64,
bufferSize: Int,
progress: Progress? = nil,
provider: Provider) throws -> (sizeWritten: Int64, checksum: CRC32)
{
var sizeWritten: Int64 = 0
let consumer: Consumer = { data in sizeWritten += Int64(try Data.write(chunk: data, to: self.archiveFile)) }
let checksum = try Data.compress(
size: size,
bufferSize: bufferSize,
provider: { position, size -> Data in
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
let data = try provider(position, size)
progress?.completedUnitCount += Int64(data.count)
return data
},
consumer: consumer)
return (sizeWritten, checksum)
}
func writeSymbolicLink(size: Int, provider: Provider) throws -> (sizeWritten: Int, checksum: CRC32) {
// The reported size of a symlink is the number of characters in the path it points to.
let linkData = try provider(0, size)
let checksum = linkData.crc32(checksum: 0)
let sizeWritten = try Data.write(chunk: linkData, to: archiveFile)
return (sizeWritten, checksum)
}
func writeZIP64EOCD(
totalNumberOfEntries: UInt64,
sizeOfCentralDirectory: UInt64,
offsetOfCentralDirectory: UInt64,
offsetOfEndOfCentralDirectory: UInt64)
throws -> ZIP64EndOfCentralDirectory
{
var zip64EOCD: ZIP64EndOfCentralDirectory = zip64EndOfCentralDirectory ?? {
// Shouldn't include the leading 12 bytes: (size - 12 = 44)
let record = ZIP64EndOfCentralDirectoryRecord(
sizeOfZIP64EndOfCentralDirectoryRecord: UInt64(44),
versionMadeBy: UInt16(789),
versionNeededToExtract: Version.v45.rawValue,
numberOfDisk: 0,
numberOfDiskStart: 0,
totalNumberOfEntriesOnDisk: 0,
totalNumberOfEntriesInCentralDirectory: 0,
sizeOfCentralDirectory: 0,
offsetToStartOfCentralDirectory: 0,
zip64ExtensibleDataSector: Data())
let locator = ZIP64EndOfCentralDirectoryLocator(
numberOfDiskWithZIP64EOCDRecordStart: 0,
relativeOffsetOfZIP64EOCDRecord: 0,
totalNumberOfDisk: 1)
return ZIP64EndOfCentralDirectory(record: record, locator: locator)
}()
let updatedRecord = ZIP64EndOfCentralDirectoryRecord(
record: zip64EOCD.record,
numberOfEntriesOnDisk: totalNumberOfEntries,
numberOfEntriesInCD: totalNumberOfEntries,
sizeOfCentralDirectory: sizeOfCentralDirectory,
offsetToStartOfCD: offsetOfCentralDirectory)
let updatedLocator = ZIP64EndOfCentralDirectoryLocator(
locator: zip64EOCD.locator,
offsetOfZIP64EOCDRecord: offsetOfEndOfCentralDirectory)
zip64EOCD = ZIP64EndOfCentralDirectory(record: updatedRecord, locator: updatedLocator)
_ = try Data.write(chunk: zip64EOCD.data, to: archiveFile)
return zip64EOCD
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive+Helpers.swift
|
Swift
|
unknown
| 13,520
|
//
// Archive+MemoryFile.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
var isMemoryArchive: Bool { url.scheme == memoryURLScheme }
}
#if swift(>=5.0)
extension Archive {
/// Returns a `Data` object containing a representation of the receiver.
var data: Data? { memoryFile?.data }
}
class MemoryFile {
// MARK: Lifecycle
init(data: Data = Data()) {
self.data = data
}
// MARK: Internal
private(set) var data: Data
func open(mode: String) -> FILEPointer? {
let cookie = Unmanaged.passRetained(self)
let writable = mode.count > 0 && (mode.first! != "r" || mode.last! == "+")
let append = mode.count > 0 && mode.first! == "a"
#if os(macOS) || canImport(UIKit) || os(Android)
let result = writable
? funopen(cookie.toOpaque(), readStub, writeStub, seekStub, closeStub)
: funopen(cookie.toOpaque(), readStub, nil, seekStub, closeStub)
#else
let stubs = cookie_io_functions_t(read: readStub, write: writeStub, seek: seekStub, close: closeStub)
let result = fopencookie(cookie.toOpaque(), mode, stubs)
#endif
if append {
fseeko(result, 0, SEEK_END)
}
return result
}
// MARK: Private
private var offset = 0
}
extension MemoryFile {
fileprivate func readData(buffer: UnsafeMutableRawBufferPointer) -> Int {
let size = min(buffer.count, data.count - offset)
let start = data.startIndex
data.copyBytes(to: buffer.bindMemory(to: UInt8.self), from: start + offset..<start + offset + size)
offset += size
return size
}
fileprivate func writeData(buffer: UnsafeRawBufferPointer) -> Int {
let start = data.startIndex
if offset < data.count, offset + buffer.count > data.count {
data.removeSubrange(start + offset..<start + data.count)
} else if offset > data.count {
data.append(Data(count: offset - data.count))
}
if offset == data.count {
data.append(buffer.bindMemory(to: UInt8.self))
} else {
let start = data.startIndex // May have changed in earlier mutation
data.replaceSubrange(start + offset..<start + offset + buffer.count, with: buffer.bindMemory(to: UInt8.self))
}
offset += buffer.count
return buffer.count
}
fileprivate func seek(offset: Int, whence: Int32) -> Int {
var result = -1
if whence == SEEK_SET {
result = offset
} else if whence == SEEK_CUR {
result = self.offset + offset
} else if whence == SEEK_END {
result = data.count + offset
}
self.offset = result
return self.offset
}
}
private func fileFromCookie(cookie: UnsafeRawPointer) -> MemoryFile {
Unmanaged<MemoryFile>.fromOpaque(cookie).takeUnretainedValue()
}
private func closeStub(_ cookie: UnsafeMutableRawPointer?) -> Int32 {
if let cookie {
Unmanaged<MemoryFile>.fromOpaque(cookie).release()
}
return 0
}
#if os(macOS) || canImport(UIKit) || os(Android)
private func readStub(
_ cookie: UnsafeMutableRawPointer?,
_ bytePtr: UnsafeMutablePointer<Int8>?,
_ count: Int32)
-> Int32
{
guard let cookie, let bytePtr else { return 0 }
return Int32(fileFromCookie(cookie: cookie).readData(
buffer: UnsafeMutableRawBufferPointer(start: bytePtr, count: Int(count))))
}
private func writeStub(
_ cookie: UnsafeMutableRawPointer?,
_ bytePtr: UnsafePointer<Int8>?,
_ count: Int32)
-> Int32
{
guard let cookie, let bytePtr else { return 0 }
return Int32(fileFromCookie(cookie: cookie).writeData(
buffer: UnsafeRawBufferPointer(start: bytePtr, count: Int(count))))
}
private func seekStub(
_ cookie: UnsafeMutableRawPointer?,
_ offset: fpos_t,
_ whence: Int32)
-> fpos_t
{
guard let cookie else { return 0 }
return fpos_t(fileFromCookie(cookie: cookie).seek(offset: Int(offset), whence: whence))
}
#else
private func readStub(
_ cookie: UnsafeMutableRawPointer?,
_ bytePtr: UnsafeMutablePointer<Int8>?,
_ count: Int)
-> Int
{
guard let cookie, let bytePtr else { return 0 }
return fileFromCookie(cookie: cookie).readData(
buffer: UnsafeMutableRawBufferPointer(start: bytePtr, count: count))
}
private func writeStub(
_ cookie: UnsafeMutableRawPointer?,
_ bytePtr: UnsafePointer<Int8>?,
_ count: Int)
-> Int
{
guard let cookie, let bytePtr else { return 0 }
return fileFromCookie(cookie: cookie).writeData(
buffer: UnsafeRawBufferPointer(start: bytePtr, count: count))
}
private func seekStub(
_ cookie: UnsafeMutableRawPointer?,
_ offset: UnsafeMutablePointer<Int>?,
_ whence: Int32)
-> Int32
{
guard let cookie, let offset else { return 0 }
let result = fileFromCookie(cookie: cookie).seek(offset: Int(offset.pointee), whence: whence)
if result >= 0 {
offset.pointee = result
return 0
} else {
return -1
}
}
#endif
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive+MemoryFile.swift
|
Swift
|
unknown
| 5,023
|
//
// Archive+Progress.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
/// The number of the work units that have to be performed when
/// removing `entry` from the receiver.
///
/// - Parameter entry: The entry that will be removed.
/// - Returns: The number of the work units.
func totalUnitCountForRemoving(_ entry: Entry) -> Int64 {
Int64(offsetToStartOfCentralDirectory - entry.localSize)
}
func makeProgressForRemoving(_ entry: Entry) -> Progress {
Progress(totalUnitCount: totalUnitCountForRemoving(entry))
}
/// The number of the work units that have to be performed when
/// reading `entry` from the receiver.
///
/// - Parameter entry: The entry that will be read.
/// - Returns: The number of the work units.
func totalUnitCountForReading(_ entry: Entry) -> Int64 {
switch entry.type {
case .file, .symlink:
return Int64(entry.uncompressedSize)
case .directory:
return defaultDirectoryUnitCount
}
}
func makeProgressForReading(_ entry: Entry) -> Progress {
Progress(totalUnitCount: totalUnitCountForReading(entry))
}
/// The number of the work units that have to be performed when
/// adding the file at `url` to the receiver.
/// - Parameter entry: The entry that will be removed.
/// - Returns: The number of the work units.
func totalUnitCountForAddingItem(at url: URL) -> Int64 {
var count = Int64(0)
do {
let type = try FileManager.typeForItem(at: url)
switch type {
case .file, .symlink:
count = Int64(try FileManager.fileSizeForItem(at: url))
case .directory:
count = defaultDirectoryUnitCount
}
} catch { count = -1 }
return count
}
func makeProgressForAddingItem(at url: URL) -> Progress {
Progress(totalUnitCount: totalUnitCountForAddingItem(at: url))
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive+Progress.swift
|
Swift
|
unknown
| 2,107
|
//
// Archive+Reading.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
/// Read a ZIP `Entry` from the receiver and write it to `url`.
///
/// - Parameters:
/// - entry: The ZIP `Entry` to read.
/// - url: The destination file URL.
/// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed).
/// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance.
/// - progress: A progress object that can be used to track or cancel the extract operation.
/// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`.
/// - Throws: An error if the destination file cannot be written or the entry contains malformed content.
func extract(
_ entry: Entry,
to url: URL,
bufferSize: Int = defaultReadChunkSize,
skipCRC32: Bool = false,
progress: Progress? = nil)
throws -> CRC32
{
guard bufferSize > 0 else {
throw ArchiveError.invalidBufferSize
}
let fileManager = FileManager()
var checksum = CRC32(0)
switch entry.type {
case .file:
guard !fileManager.itemExists(at: url) else {
throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path])
}
try fileManager.createParentDirectoryStructure(for: url)
let destinationRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
guard let destinationFile: FILEPointer = fopen(destinationRepresentation, "wb+") else {
throw CocoaError(.fileNoSuchFile)
}
defer { fclose(destinationFile) }
let consumer = { _ = try Data.write(chunk: $0, to: destinationFile) }
checksum = try extract(
entry,
bufferSize: bufferSize,
skipCRC32: skipCRC32,
progress: progress,
consumer: consumer)
case .directory:
let consumer = { (_: Data) in
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
}
checksum = try extract(
entry,
bufferSize: bufferSize,
skipCRC32: skipCRC32,
progress: progress,
consumer: consumer)
case .symlink:
guard !fileManager.itemExists(at: url) else {
throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path])
}
let consumer = { (data: Data) in
guard let linkPath = String(data: data, encoding: .utf8) else { throw ArchiveError.invalidEntryPath }
try fileManager.createParentDirectoryStructure(for: url)
try fileManager.createSymbolicLink(atPath: url.path, withDestinationPath: linkPath)
}
checksum = try extract(
entry,
bufferSize: bufferSize,
skipCRC32: skipCRC32,
progress: progress,
consumer: consumer)
}
let attributes = FileManager.attributes(from: entry)
try fileManager.setAttributes(attributes, ofItemAtPath: url.path)
return checksum
}
/// Read a ZIP `Entry` from the receiver and forward its contents to a `Consumer` closure.
///
/// - Parameters:
/// - entry: The ZIP `Entry` to read.
/// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed).
/// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance.
/// - progress: A progress object that can be used to track or cancel the extract operation.
/// - consumer: A closure that consumes contents of `Entry` as `Data` chunks.
/// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`..
/// - Throws: An error if the destination file cannot be written or the entry contains malformed content.
func extract(
_ entry: Entry,
bufferSize: Int = defaultReadChunkSize,
skipCRC32: Bool = false,
progress: Progress? = nil,
consumer: Consumer)
throws -> CRC32
{
guard bufferSize > 0 else {
throw ArchiveError.invalidBufferSize
}
var checksum = CRC32(0)
let localFileHeader = entry.localFileHeader
guard entry.dataOffset <= .max else { throw ArchiveError.invalidLocalHeaderDataOffset }
fseeko(archiveFile, off_t(entry.dataOffset), SEEK_SET)
progress?.totalUnitCount = totalUnitCountForReading(entry)
switch entry.type {
case .file:
guard let compressionMethod = CompressionMethod(rawValue: localFileHeader.compressionMethod) else {
throw ArchiveError.invalidCompressionMethod
}
switch compressionMethod {
case .none: checksum = try readUncompressed(
entry: entry,
bufferSize: bufferSize,
skipCRC32: skipCRC32,
progress: progress,
with: consumer)
case .deflate: checksum = try readCompressed(
entry: entry,
bufferSize: bufferSize,
skipCRC32: skipCRC32,
progress: progress,
with: consumer)
}
case .directory:
try consumer(Data())
progress?.completedUnitCount = totalUnitCountForReading(entry)
case .symlink:
let localFileHeader = entry.localFileHeader
let size = Int(localFileHeader.compressedSize)
let data = try Data.readChunk(of: size, from: archiveFile)
checksum = data.crc32(checksum: 0)
try consumer(data)
progress?.completedUnitCount = totalUnitCountForReading(entry)
}
return checksum
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive+Reading.swift
|
Swift
|
unknown
| 5,674
|
//
// Archive+ReadingDeprecated.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
@available(
*,
deprecated,
message: "Please use `Int` for `bufferSize`.")
func extract(
_ entry: Entry,
to url: URL,
bufferSize: UInt32,
skipCRC32: Bool = false,
progress: Progress? = nil)
throws -> CRC32
{
try extract(entry, to: url, bufferSize: Int(bufferSize), skipCRC32: skipCRC32, progress: progress)
}
@available(
*,
deprecated,
message: "Please use `Int` for `bufferSize`.")
func extract(
_ entry: Entry,
bufferSize: UInt32,
skipCRC32: Bool = false,
progress: Progress? = nil,
consumer: Consumer)
throws -> CRC32
{
try extract(
entry,
bufferSize: Int(bufferSize),
skipCRC32: skipCRC32,
progress: progress,
consumer: consumer)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive+ReadingDeprecated.swift
|
Swift
|
unknown
| 1,112
|
//
// Archive+Writing.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
enum ModifyOperation: Int {
case remove = -1
case add = 1
}
typealias EndOfCentralDirectoryStructure = (EndOfCentralDirectoryRecord, ZIP64EndOfCentralDirectory?)
/// Write files, directories or symlinks to the receiver.
///
/// - Parameters:
/// - path: The path that is used to identify an `Entry` within the `Archive` file.
/// - baseURL: The base URL of the resource to add.
/// The `baseURL` combined with `path` must form a fully qualified file URL.
/// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Entry`.
/// By default, no compression will be applied.
/// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed).
/// - progress: A progress object that can be used to track or cancel the add operation.
/// - Throws: An error if the source file cannot be read or the receiver is not writable.
func addEntry(
with path: String,
relativeTo baseURL: URL,
compressionMethod: CompressionMethod = .none,
bufferSize: Int = defaultWriteChunkSize,
progress: Progress? = nil)
throws
{
let fileURL = baseURL.appendingPathComponent(path)
try addEntry(
with: path,
fileURL: fileURL,
compressionMethod: compressionMethod,
bufferSize: bufferSize,
progress: progress)
}
/// Write files, directories or symlinks to the receiver.
///
/// - Parameters:
/// - path: The path that is used to identify an `Entry` within the `Archive` file.
/// - fileURL: An absolute file URL referring to the resource to add.
/// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Entry`.
/// By default, no compression will be applied.
/// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed).
/// - progress: A progress object that can be used to track or cancel the add operation.
/// - Throws: An error if the source file cannot be read or the receiver is not writable.
func addEntry(
with path: String,
fileURL: URL,
compressionMethod: CompressionMethod = .none,
bufferSize: Int = defaultWriteChunkSize,
progress: Progress? = nil)
throws
{
let fileManager = FileManager()
guard fileManager.itemExists(at: fileURL) else {
throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: fileURL.path])
}
let type = try FileManager.typeForItem(at: fileURL)
// symlinks do not need to be readable
guard type == .symlink || fileManager.isReadableFile(atPath: fileURL.path) else {
throw CocoaError(.fileReadNoPermission, userInfo: [NSFilePathErrorKey: url.path])
}
let modDate = try FileManager.fileModificationDateTimeForItem(at: fileURL)
let uncompressedSize = type == .directory ? 0 : try FileManager.fileSizeForItem(at: fileURL)
let permissions = try FileManager.permissionsForItem(at: fileURL)
var provider: Provider
switch type {
case .file:
let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: fileURL.path)
guard let entryFile: FILEPointer = fopen(entryFileSystemRepresentation, "rb") else {
throw CocoaError(.fileNoSuchFile)
}
defer { fclose(entryFile) }
provider = { _, _ in try Data.readChunk(of: bufferSize, from: entryFile) }
try addEntry(
with: path,
type: type,
uncompressedSize: uncompressedSize,
modificationDate: modDate,
permissions: permissions,
compressionMethod: compressionMethod,
bufferSize: bufferSize,
progress: progress,
provider: provider)
case .directory:
provider = { _, _ in Data() }
try addEntry(
with: path.hasSuffix("/") ? path : path + "/",
type: type,
uncompressedSize: uncompressedSize,
modificationDate: modDate,
permissions: permissions,
compressionMethod: compressionMethod,
bufferSize: bufferSize,
progress: progress,
provider: provider)
case .symlink:
provider = { _, _ -> Data in
let linkDestination = try fileManager.destinationOfSymbolicLink(atPath: fileURL.path)
let linkFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: linkDestination)
let linkLength = Int(strlen(linkFileSystemRepresentation))
let linkBuffer = UnsafeBufferPointer(start: linkFileSystemRepresentation, count: linkLength)
return Data(buffer: linkBuffer)
}
try addEntry(
with: path,
type: type,
uncompressedSize: uncompressedSize,
modificationDate: modDate,
permissions: permissions,
compressionMethod: compressionMethod,
bufferSize: bufferSize,
progress: progress,
provider: provider)
}
}
/// Write files, directories or symlinks to the receiver.
///
/// - Parameters:
/// - path: The path that is used to identify an `Entry` within the `Archive` file.
/// - type: Indicates the `Entry.EntryType` of the added content.
/// - uncompressedSize: The uncompressed size of the data that is going to be added with `provider`.
/// - modificationDate: A `Date` describing the file modification date of the `Entry`.
/// Default is the current `Date`.
/// - permissions: POSIX file permissions for the `Entry`.
/// Default is `0`o`644` for files and symlinks and `0`o`755` for directories.
/// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Entry`.
/// By default, no compression will be applied.
/// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed).
/// - progress: A progress object that can be used to track or cancel the add operation.
/// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk.
/// - Throws: An error if the source data is invalid or the receiver is not writable.
func addEntry(
with path: String,
type: Entry.EntryType,
uncompressedSize: Int64,
modificationDate: Date = Date(),
permissions: UInt16? = nil,
compressionMethod: CompressionMethod = .none,
bufferSize: Int = defaultWriteChunkSize,
progress: Progress? = nil,
provider: Provider)
throws
{
guard accessMode != .read else { throw ArchiveError.unwritableArchive }
// Directories and symlinks cannot be compressed
let compressionMethod = type == .file ? compressionMethod : .none
progress?.totalUnitCount = type == .directory ? defaultDirectoryUnitCount : uncompressedSize
let (eocdRecord, zip64EOCD) = (endOfCentralDirectoryRecord, zip64EndOfCentralDirectory)
guard offsetToStartOfCentralDirectory <= .max else { throw ArchiveError.invalidCentralDirectoryOffset }
var startOfCD = Int64(offsetToStartOfCentralDirectory)
fseeko(archiveFile, off_t(startOfCD), SEEK_SET)
let existingSize = sizeOfCentralDirectory
let existingData = try Data.readChunk(of: Int(existingSize), from: archiveFile)
fseeko(archiveFile, off_t(startOfCD), SEEK_SET)
let fileHeaderStart = Int64(ftello(archiveFile))
let modDateTime = modificationDate.fileModificationDateTime
defer { fflush(self.archiveFile) }
do {
// Local File Header
var localFileHeader = try writeLocalFileHeader(
path: path,
compressionMethod: compressionMethod,
size: (UInt64(uncompressedSize), 0),
checksum: 0,
modificationDateTime: modDateTime)
// File Data
let (written, checksum) = try writeEntry(
uncompressedSize: uncompressedSize,
type: type,
compressionMethod: compressionMethod,
bufferSize: bufferSize,
progress: progress,
provider: provider)
startOfCD = Int64(ftello(archiveFile))
// Write the local file header a second time. Now with compressedSize (if applicable) and a valid checksum.
fseeko(archiveFile, off_t(fileHeaderStart), SEEK_SET)
localFileHeader = try writeLocalFileHeader(
path: path,
compressionMethod: compressionMethod,
size: (UInt64(uncompressedSize), UInt64(written)),
checksum: checksum,
modificationDateTime: modDateTime)
// Central Directory
fseeko(archiveFile, off_t(startOfCD), SEEK_SET)
_ = try Data.writeLargeChunk(existingData, size: existingSize, bufferSize: bufferSize, to: archiveFile)
let permissions = permissions ?? (type == .directory ? defaultDirectoryPermissions : defaultFilePermissions)
let externalAttributes = FileManager.externalFileAttributesForEntry(of: type, permissions: permissions)
let centralDir = try writeCentralDirectoryStructure(
localFileHeader: localFileHeader,
relativeOffset: UInt64(fileHeaderStart),
externalFileAttributes: externalAttributes)
// End of Central Directory Record (including ZIP64 End of Central Directory Record/Locator)
let startOfEOCD = UInt64(ftello(archiveFile))
let eocd = try writeEndOfCentralDirectory(
centralDirectoryStructure: centralDir,
startOfCentralDirectory: UInt64(startOfCD),
startOfEndOfCentralDirectory: startOfEOCD,
operation: .add)
(endOfCentralDirectoryRecord, zip64EndOfCentralDirectory) = eocd
} catch ArchiveError.cancelledOperation {
try rollback(UInt64(fileHeaderStart), (existingData, existingSize), bufferSize, eocdRecord, zip64EOCD)
throw ArchiveError.cancelledOperation
}
}
/// Remove a ZIP `Entry` from the receiver.
///
/// - Parameters:
/// - entry: The `Entry` to remove.
/// - bufferSize: The maximum size for the read and write buffers used during removal.
/// - progress: A progress object that can be used to track or cancel the remove operation.
/// - Throws: An error if the `Entry` is malformed or the receiver is not writable.
func remove(_ entry: Entry, bufferSize: Int = defaultReadChunkSize, progress: Progress? = nil) throws {
guard accessMode != .read else { throw ArchiveError.unwritableArchive }
let (tempArchive, tempDir) = try makeTempArchive()
defer { tempDir.map { try? FileManager().removeItem(at: $0) } }
progress?.totalUnitCount = totalUnitCountForRemoving(entry)
var centralDirectoryData = Data()
var offset: UInt64 = 0
for currentEntry in self {
let cds = currentEntry.centralDirectoryStructure
if currentEntry != entry {
let entryStart = cds.effectiveRelativeOffsetOfLocalHeader
fseeko(archiveFile, off_t(entryStart), SEEK_SET)
let provider: Provider = { _, chunkSize -> Data in
try Data.readChunk(of: chunkSize, from: self.archiveFile)
}
let consumer: Consumer = {
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
_ = try Data.write(chunk: $0, to: tempArchive.archiveFile)
progress?.completedUnitCount += Int64($0.count)
}
guard currentEntry.localSize <= .max else { throw ArchiveError.invalidLocalHeaderSize }
_ = try Data.consumePart(
of: Int64(currentEntry.localSize),
chunkSize: bufferSize,
provider: provider,
consumer: consumer)
let updatedCentralDirectory = updateOffsetInCentralDirectory(
centralDirectoryStructure: cds,
updatedOffset: entryStart - offset)
centralDirectoryData.append(updatedCentralDirectory.data)
} else { offset = currentEntry.localSize }
}
let startOfCentralDirectory = UInt64(ftello(tempArchive.archiveFile))
_ = try Data.write(chunk: centralDirectoryData, to: tempArchive.archiveFile)
let startOfEndOfCentralDirectory = UInt64(ftello(tempArchive.archiveFile))
tempArchive.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
tempArchive.zip64EndOfCentralDirectory = zip64EndOfCentralDirectory
let ecodStructure = try
tempArchive.writeEndOfCentralDirectory(
centralDirectoryStructure: entry.centralDirectoryStructure,
startOfCentralDirectory: startOfCentralDirectory,
startOfEndOfCentralDirectory: startOfEndOfCentralDirectory,
operation: .remove)
(tempArchive.endOfCentralDirectoryRecord, tempArchive.zip64EndOfCentralDirectory) = ecodStructure
(endOfCentralDirectoryRecord, zip64EndOfCentralDirectory) = ecodStructure
fflush(tempArchive.archiveFile)
try replaceCurrentArchive(with: tempArchive)
}
func replaceCurrentArchive(with archive: Archive) throws {
fclose(archiveFile)
if isMemoryArchive {
#if swift(>=5.0)
guard
let data = archive.data,
let config = Archive.makeBackingConfiguration(for: data, mode: .update)
else {
throw ArchiveError.unwritableArchive
}
archiveFile = config.file
memoryFile = config.memoryFile
endOfCentralDirectoryRecord = config.endOfCentralDirectoryRecord
zip64EndOfCentralDirectory = config.zip64EndOfCentralDirectory
#endif
} else {
let fileManager = FileManager()
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
do {
_ = try fileManager.replaceItemAt(url, withItemAt: archive.url)
} catch {
_ = try fileManager.removeItem(at: url)
_ = try fileManager.moveItem(at: archive.url, to: url)
}
#else
_ = try fileManager.removeItem(at: url)
_ = try fileManager.moveItem(at: archive.url, to: url)
#endif
let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
guard let file = fopen(fileSystemRepresentation, "rb+") else { throw ArchiveError.unreadableArchive }
archiveFile = file
}
}
}
// MARK: - Private
extension Archive {
private func updateOffsetInCentralDirectory(
centralDirectoryStructure: CentralDirectoryStructure,
updatedOffset: UInt64)
-> CentralDirectoryStructure
{
let zip64ExtendedInformation = Entry.ZIP64ExtendedInformation(
zip64ExtendedInformation: centralDirectoryStructure.zip64ExtendedInformation, offset: updatedOffset)
let offsetInCD = updatedOffset < maxOffsetOfLocalFileHeader ? UInt32(updatedOffset) : UInt32.max
return CentralDirectoryStructure(
centralDirectoryStructure: centralDirectoryStructure,
zip64ExtendedInformation: zip64ExtendedInformation,
relativeOffset: offsetInCD)
}
private func rollback(
_ localFileHeaderStart: UInt64,
_ existingCentralDirectory: (data: Data, size: UInt64),
_ bufferSize: Int,
_ endOfCentralDirRecord: EndOfCentralDirectoryRecord,
_ zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?)
throws
{
fflush(archiveFile)
ftruncate(fileno(archiveFile), off_t(localFileHeaderStart))
fseeko(archiveFile, off_t(localFileHeaderStart), SEEK_SET)
_ = try Data.writeLargeChunk(
existingCentralDirectory.data,
size: existingCentralDirectory.size,
bufferSize: bufferSize,
to: archiveFile)
_ = try Data.write(chunk: existingCentralDirectory.data, to: archiveFile)
if let zip64EOCD = zip64EndOfCentralDirectory {
_ = try Data.write(chunk: zip64EOCD.data, to: archiveFile)
}
_ = try Data.write(chunk: endOfCentralDirRecord.data, to: archiveFile)
}
private func makeTempArchive() throws -> (Archive, URL?) {
var archive: Archive
var url: URL?
if isMemoryArchive {
#if swift(>=5.0)
guard
let tempArchive = Archive(
data: Data(),
accessMode: .create,
preferredEncoding: preferredEncoding)
else {
throw ArchiveError.unwritableArchive
}
archive = tempArchive
#else
fatalError("Memory archives are unsupported.")
#endif
} else {
let manager = FileManager()
let tempDir = URL.temporaryReplacementDirectoryURL(for: self)
let uniqueString = ProcessInfo.processInfo.globallyUniqueString
let tempArchiveURL = tempDir.appendingPathComponent(uniqueString)
try manager.createParentDirectoryStructure(for: tempArchiveURL)
guard let tempArchive = Archive(url: tempArchiveURL, accessMode: .create) else {
throw ArchiveError.unwritableArchive
}
archive = tempArchive
url = tempDir
}
return (archive, url)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive+Writing.swift
|
Swift
|
unknown
| 16,780
|
//
// Archive+WritingDeprecated.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
@available(
*,
deprecated,
message: "Please use `Int` for `bufferSize`.")
func addEntry(
with path: String,
relativeTo baseURL: URL,
compressionMethod: CompressionMethod = .none,
bufferSize: UInt32,
progress: Progress? = nil)
throws
{
try addEntry(
with: path,
relativeTo: baseURL,
compressionMethod: compressionMethod,
bufferSize: Int(bufferSize),
progress: progress)
}
@available(
*,
deprecated,
message: "Please use `Int` for `bufferSize`.")
func addEntry(
with path: String,
fileURL: URL,
compressionMethod: CompressionMethod = .none,
bufferSize: UInt32,
progress: Progress? = nil)
throws
{
try addEntry(
with: path,
fileURL: fileURL,
compressionMethod: compressionMethod,
bufferSize: Int(bufferSize),
progress: progress)
}
@available(
*,
deprecated,
message: "Please use `Int64` for `uncompressedSize` and provider `position`. `Int` for `bufferSize`.")
func addEntry(
with path: String,
type: Entry.EntryType,
uncompressedSize: UInt32,
modificationDate: Date = Date(),
permissions: UInt16? = nil,
compressionMethod: CompressionMethod = .none,
bufferSize: Int = defaultWriteChunkSize,
progress: Progress? = nil,
provider: (_ position: Int, _ size: Int) throws -> Data)
throws
{
let newProvider: Provider = { try provider(Int($0), $1) }
try addEntry(
with: path,
type: type,
uncompressedSize: Int64(uncompressedSize),
modificationDate: modificationDate,
permissions: permissions,
compressionMethod: compressionMethod,
bufferSize: bufferSize,
progress: progress,
provider: newProvider)
}
@available(
*,
deprecated,
message: "Please use `Int` for `bufferSize`.")
func remove(_ entry: Entry, bufferSize: UInt32, progress: Progress? = nil) throws {
try remove(entry, bufferSize: Int(bufferSize), progress: progress)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive+WritingDeprecated.swift
|
Swift
|
unknown
| 2,370
|
//
// Archive+ZIP64.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
let zip64EOCDRecordStructSignature = 0x06064b50
let zip64EOCDLocatorStructSignature = 0x07064b50
// MARK: - ExtraFieldHeaderID
enum ExtraFieldHeaderID: UInt16 {
case zip64ExtendedInformation = 0x0001
}
extension Archive {
struct ZIP64EndOfCentralDirectory {
let record: ZIP64EndOfCentralDirectoryRecord
let locator: ZIP64EndOfCentralDirectoryLocator
}
struct ZIP64EndOfCentralDirectoryRecord: DataSerializable {
let zip64EOCDRecordSignature = UInt32(zip64EOCDRecordStructSignature)
let sizeOfZIP64EndOfCentralDirectoryRecord: UInt64
let versionMadeBy: UInt16
let versionNeededToExtract: UInt16
let numberOfDisk: UInt32
let numberOfDiskStart: UInt32
let totalNumberOfEntriesOnDisk: UInt64
let totalNumberOfEntriesInCentralDirectory: UInt64
let sizeOfCentralDirectory: UInt64
let offsetToStartOfCentralDirectory: UInt64
let zip64ExtensibleDataSector: Data
static let size = 56
}
struct ZIP64EndOfCentralDirectoryLocator: DataSerializable {
let zip64EOCDLocatorSignature = UInt32(zip64EOCDLocatorStructSignature)
let numberOfDiskWithZIP64EOCDRecordStart: UInt32
let relativeOffsetOfZIP64EOCDRecord: UInt64
let totalNumberOfDisk: UInt32
static let size = 20
}
}
extension Archive.ZIP64EndOfCentralDirectoryRecord {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider _: (Int) throws -> Data) {
guard data.count == Archive.ZIP64EndOfCentralDirectoryRecord.size else { return nil }
guard data.scanValue(start: 0) == zip64EOCDRecordSignature else { return nil }
sizeOfZIP64EndOfCentralDirectoryRecord = data.scanValue(start: 4)
versionMadeBy = data.scanValue(start: 12)
versionNeededToExtract = data.scanValue(start: 14)
// Version Needed to Extract: 4.5 - File uses ZIP64 format extensions
guard versionNeededToExtract >= Archive.Version.v45.rawValue else { return nil }
numberOfDisk = data.scanValue(start: 16)
numberOfDiskStart = data.scanValue(start: 20)
totalNumberOfEntriesOnDisk = data.scanValue(start: 24)
totalNumberOfEntriesInCentralDirectory = data.scanValue(start: 32)
sizeOfCentralDirectory = data.scanValue(start: 40)
offsetToStartOfCentralDirectory = data.scanValue(start: 48)
zip64ExtensibleDataSector = Data()
}
init(
record: Archive.ZIP64EndOfCentralDirectoryRecord,
numberOfEntriesOnDisk: UInt64,
numberOfEntriesInCD: UInt64,
sizeOfCentralDirectory: UInt64,
offsetToStartOfCD: UInt64)
{
sizeOfZIP64EndOfCentralDirectoryRecord = record.sizeOfZIP64EndOfCentralDirectoryRecord
versionMadeBy = record.versionMadeBy
versionNeededToExtract = record.versionNeededToExtract
numberOfDisk = record.numberOfDisk
numberOfDiskStart = record.numberOfDiskStart
totalNumberOfEntriesOnDisk = numberOfEntriesOnDisk
totalNumberOfEntriesInCentralDirectory = numberOfEntriesInCD
self.sizeOfCentralDirectory = sizeOfCentralDirectory
offsetToStartOfCentralDirectory = offsetToStartOfCD
zip64ExtensibleDataSector = record.zip64ExtensibleDataSector
}
// MARK: Internal
var data: Data {
var zip64EOCDRecordSignature = zip64EOCDRecordSignature
var sizeOfZIP64EOCDRecord = sizeOfZIP64EndOfCentralDirectoryRecord
var versionMadeBy = versionMadeBy
var versionNeededToExtract = versionNeededToExtract
var numberOfDisk = numberOfDisk
var numberOfDiskStart = numberOfDiskStart
var totalNumberOfEntriesOnDisk = totalNumberOfEntriesOnDisk
var totalNumberOfEntriesInCD = totalNumberOfEntriesInCentralDirectory
var sizeOfCD = sizeOfCentralDirectory
var offsetToStartOfCD = offsetToStartOfCentralDirectory
var data = Data()
withUnsafePointer(to: &zip64EOCDRecordSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &sizeOfZIP64EOCDRecord) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &versionMadeBy) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &versionNeededToExtract) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDiskStart) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesOnDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesInCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &sizeOfCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &offsetToStartOfCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
data.append(zip64ExtensibleDataSector)
return data
}
}
extension Archive.ZIP64EndOfCentralDirectoryLocator {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider _: (Int) throws -> Data) {
guard data.count == Archive.ZIP64EndOfCentralDirectoryLocator.size else { return nil }
guard data.scanValue(start: 0) == zip64EOCDLocatorSignature else { return nil }
numberOfDiskWithZIP64EOCDRecordStart = data.scanValue(start: 4)
relativeOffsetOfZIP64EOCDRecord = data.scanValue(start: 8)
totalNumberOfDisk = data.scanValue(start: 16)
}
init(locator: Archive.ZIP64EndOfCentralDirectoryLocator, offsetOfZIP64EOCDRecord: UInt64) {
numberOfDiskWithZIP64EOCDRecordStart = locator.numberOfDiskWithZIP64EOCDRecordStart
relativeOffsetOfZIP64EOCDRecord = offsetOfZIP64EOCDRecord
totalNumberOfDisk = locator.totalNumberOfDisk
}
// MARK: Internal
var data: Data {
var zip64EOCDLocatorSignature = zip64EOCDLocatorSignature
var numberOfDiskWithZIP64EOCD = numberOfDiskWithZIP64EOCDRecordStart
var offsetOfZIP64EOCDRecord = relativeOffsetOfZIP64EOCDRecord
var totalNumberOfDisk = totalNumberOfDisk
var data = Data()
withUnsafePointer(to: &zip64EOCDLocatorSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDiskWithZIP64EOCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &offsetOfZIP64EOCDRecord) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
return data
}
}
extension Archive.ZIP64EndOfCentralDirectory {
var data: Data { record.data + locator.data }
}
/// Properties that represent the maximum value of each field
var maxUInt32 = UInt32.max
var maxUInt16 = UInt16.max
var maxCompressedSize: UInt32 { maxUInt32 }
var maxUncompressedSize: UInt32 { maxUInt32 }
var maxOffsetOfLocalFileHeader: UInt32 { maxUInt32 }
var maxOffsetOfCentralDirectory: UInt32 { maxUInt32 }
var maxSizeOfCentralDirectory: UInt32 { maxUInt32 }
var maxTotalNumberOfEntries: UInt16 { maxUInt16 }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive+ZIP64.swift
|
Swift
|
unknown
| 7,211
|
//
// Archive.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
/// The default chunk size when reading entry data from an archive.
let defaultReadChunkSize = Int(16 * 1024)
/// The default chunk size when writing entry data to an archive.
let defaultWriteChunkSize = defaultReadChunkSize
/// The default permissions for newly added entries.
let defaultFilePermissions = UInt16(0o644)
/// The default permissions for newly added directories.
let defaultDirectoryPermissions = UInt16(0o755)
let defaultPOSIXBufferSize = defaultReadChunkSize
let defaultDirectoryUnitCount = Int64(1)
let minEndOfCentralDirectoryOffset = Int64(22)
let endOfCentralDirectoryStructSignature = 0x06054b50
let localFileHeaderStructSignature = 0x04034b50
let dataDescriptorStructSignature = 0x08074b50
let centralDirectoryStructSignature = 0x02014b50
let memoryURLScheme = "memory"
// MARK: - Archive
/// A sequence of uncompressed or compressed ZIP entries.
///
/// You use an `Archive` to create, read or update ZIP files.
/// To read an existing ZIP file, you have to pass in an existing file `URL` and `AccessMode.read`:
///
/// var archiveURL = URL(fileURLWithPath: "/path/file.zip")
/// var archive = Archive(url: archiveURL, accessMode: .read)
///
/// An `Archive` is a sequence of entries. You can
/// iterate over an archive using a `for`-`in` loop to get access to individual `Entry` objects:
///
/// for entry in archive {
/// print(entry.path)
/// }
///
/// Each `Entry` in an `Archive` is represented by its `path`. You can
/// use `path` to retrieve the corresponding `Entry` from an `Archive` via subscripting:
///
/// let entry = archive['/path/file.txt']
///
/// To create a new `Archive`, pass in a non-existing file URL and `AccessMode.create`. To modify an
/// existing `Archive` use `AccessMode.update`:
///
/// var archiveURL = URL(fileURLWithPath: "/path/file.zip")
/// var archive = Archive(url: archiveURL, accessMode: .update)
/// try archive?.addEntry("test.txt", relativeTo: baseURL, compressionMethod: .deflate)
final class Archive: Sequence {
// MARK: Lifecycle
/// Initializes a new ZIP `Archive`.
///
/// You can use this initalizer to create new archive files or to read and update existing ones.
/// The `mode` parameter indicates the intended usage of the archive: `.read`, `.create` or `.update`.
/// - Parameters:
/// - url: File URL to the receivers backing file.
/// - mode: Access mode of the receiver.
/// - preferredEncoding: Encoding for entry paths. Overrides the encoding specified in the archive.
/// This encoding is only used when _decoding_ paths from the receiver.
/// Paths of entries added with `addEntry` are always UTF-8 encoded.
/// - Returns: An archive initialized with a backing file at the passed in file URL and the given access mode
/// or `nil` if the following criteria are not met:
/// - Note:
/// - The file URL _must_ point to an existing file for `AccessMode.read`.
/// - The file URL _must_ point to a non-existing file for `AccessMode.create`.
/// - The file URL _must_ point to an existing file for `AccessMode.update`.
init?(url: URL, accessMode mode: AccessMode, preferredEncoding: String.Encoding? = nil) {
self.url = url
accessMode = mode
self.preferredEncoding = preferredEncoding
guard let config = Archive.makeBackingConfiguration(for: url, mode: mode) else {
return nil
}
archiveFile = config.file
endOfCentralDirectoryRecord = config.endOfCentralDirectoryRecord
zip64EndOfCentralDirectory = config.zip64EndOfCentralDirectory
setvbuf(archiveFile, nil, _IOFBF, Int(defaultPOSIXBufferSize))
}
deinit {
fclose(self.archiveFile)
}
// MARK: Internal
typealias LocalFileHeader = Entry.LocalFileHeader
typealias DataDescriptor = Entry.DefaultDataDescriptor
typealias ZIP64DataDescriptor = Entry.ZIP64DataDescriptor
typealias CentralDirectoryStructure = Entry.CentralDirectoryStructure
/// An error that occurs during reading, creating or updating a ZIP file.
enum ArchiveError: Error {
/// Thrown when an archive file is either damaged or inaccessible.
case unreadableArchive
/// Thrown when an archive is either opened with AccessMode.read or the destination file is unwritable.
case unwritableArchive
/// Thrown when the path of an `Entry` cannot be stored in an archive.
case invalidEntryPath
/// Thrown when an `Entry` can't be stored in the archive with the proposed compression method.
case invalidCompressionMethod
/// Thrown when the stored checksum of an `Entry` doesn't match the checksum during reading.
case invalidCRC32
/// Thrown when an extract, add or remove operation was canceled.
case cancelledOperation
/// Thrown when an extract operation was called with zero or negative `bufferSize` parameter.
case invalidBufferSize
/// Thrown when uncompressedSize/compressedSize exceeds `Int64.max` (Imposed by file API).
case invalidEntrySize
/// Thrown when the offset of local header data exceeds `Int64.max` (Imposed by file API).
case invalidLocalHeaderDataOffset
/// Thrown when the size of local header exceeds `Int64.max` (Imposed by file API).
case invalidLocalHeaderSize
/// Thrown when the offset of central directory exceeds `Int64.max` (Imposed by file API).
case invalidCentralDirectoryOffset
/// Thrown when the size of central directory exceeds `UInt64.max` (Imposed by ZIP specification).
case invalidCentralDirectorySize
/// Thrown when number of entries in central directory exceeds `UInt64.max` (Imposed by ZIP specification).
case invalidCentralDirectoryEntryCount
/// Thrown when an archive does not contain the required End of Central Directory Record.
case missingEndOfCentralDirectoryRecord
}
/// The access mode for an `Archive`.
enum AccessMode: UInt {
/// Indicates that a newly instantiated `Archive` should create its backing file.
case create
/// Indicates that a newly instantiated `Archive` should read from an existing backing file.
case read
/// Indicates that a newly instantiated `Archive` should update an existing backing file.
case update
}
/// The version of an `Archive`
enum Version: UInt16 {
/// The minimum version for deflate compressed archives
case v20 = 20
/// The minimum version for archives making use of ZIP64 extensions
case v45 = 45
}
struct EndOfCentralDirectoryRecord: DataSerializable {
let endOfCentralDirectorySignature = UInt32(endOfCentralDirectoryStructSignature)
let numberOfDisk: UInt16
let numberOfDiskStart: UInt16
let totalNumberOfEntriesOnDisk: UInt16
let totalNumberOfEntriesInCentralDirectory: UInt16
let sizeOfCentralDirectory: UInt32
let offsetToStartOfCentralDirectory: UInt32
let zipFileCommentLength: UInt16
let zipFileCommentData: Data
static let size = 22
}
/// URL of an Archive's backing file.
let url: URL
/// Access mode for an archive file.
let accessMode: AccessMode
var archiveFile: FILEPointer
var endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord
var zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?
var preferredEncoding: String.Encoding?
var totalNumberOfEntriesInCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.totalNumberOfEntriesInCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.totalNumberOfEntriesInCentralDirectory)
}
var sizeOfCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.sizeOfCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.sizeOfCentralDirectory)
}
var offsetToStartOfCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.offsetToStartOfCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.offsetToStartOfCentralDirectory)
}
#if swift(>=5.0)
var memoryFile: MemoryFile?
/// Initializes a new in-memory ZIP `Archive`.
///
/// You can use this initalizer to create new in-memory archive files or to read and update existing ones.
///
/// - Parameters:
/// - data: `Data` object used as backing for in-memory archives.
/// - mode: Access mode of the receiver.
/// - preferredEncoding: Encoding for entry paths. Overrides the encoding specified in the archive.
/// This encoding is only used when _decoding_ paths from the receiver.
/// Paths of entries added with `addEntry` are always UTF-8 encoded.
/// - Returns: An in-memory archive initialized with passed in backing data.
/// - Note:
/// - The backing `data` _must_ contain a valid ZIP archive for `AccessMode.read` and `AccessMode.update`.
/// - The backing `data` _must_ be empty (or omitted) for `AccessMode.create`.
init?(data: Data = Data(), accessMode mode: AccessMode, preferredEncoding: String.Encoding? = nil) {
guard
let url = URL(string: "\(memoryURLScheme)://"),
let config = Archive.makeBackingConfiguration(for: data, mode: mode)
else {
return nil
}
self.url = url
accessMode = mode
self.preferredEncoding = preferredEncoding
archiveFile = config.file
memoryFile = config.memoryFile
endOfCentralDirectoryRecord = config.endOfCentralDirectoryRecord
zip64EndOfCentralDirectory = config.zip64EndOfCentralDirectory
}
#endif
// MARK: - Helpers
static func scanForEndOfCentralDirectoryRecord(in file: FILEPointer)
-> EndOfCentralDirectoryStructure?
{
var eocdOffset: UInt64 = 0
var index = minEndOfCentralDirectoryOffset
fseeko(file, 0, SEEK_END)
let archiveLength = Int64(ftello(file))
while eocdOffset == 0, index <= archiveLength {
fseeko(file, off_t(archiveLength - index), SEEK_SET)
var potentialDirectoryEndTag = UInt32()
fread(&potentialDirectoryEndTag, 1, MemoryLayout<UInt32>.size, file)
if potentialDirectoryEndTag == UInt32(endOfCentralDirectoryStructSignature) {
eocdOffset = UInt64(archiveLength - index)
guard let eocd: EndOfCentralDirectoryRecord = Data.readStruct(from: file, at: eocdOffset) else {
return nil
}
let zip64EOCD = scanForZIP64EndOfCentralDirectory(in: file, eocdOffset: eocdOffset)
return (eocd, zip64EOCD)
}
index += 1
}
return nil
}
func makeIterator() -> AnyIterator<Entry> {
let totalNumberOfEntriesInCD = totalNumberOfEntriesInCentralDirectory
var directoryIndex = offsetToStartOfCentralDirectory
var index = 0
return AnyIterator {
guard index < totalNumberOfEntriesInCD else { return nil }
guard
let centralDirStruct: CentralDirectoryStructure = Data.readStruct(
from: self.archiveFile,
at: directoryIndex)
else {
return nil
}
let offset = UInt64(centralDirStruct.effectiveRelativeOffsetOfLocalHeader)
guard
let localFileHeader: LocalFileHeader = Data.readStruct(
from: self.archiveFile,
at: offset)
else { return nil }
var dataDescriptor: DataDescriptor?
var zip64DataDescriptor: ZIP64DataDescriptor?
if centralDirStruct.usesDataDescriptor {
let additionalSize = UInt64(localFileHeader.fileNameLength) + UInt64(localFileHeader.extraFieldLength)
let isCompressed = centralDirStruct.compressionMethod != CompressionMethod.none.rawValue
let dataSize = isCompressed
? centralDirStruct.effectiveCompressedSize
: centralDirStruct.effectiveUncompressedSize
let descriptorPosition = offset + UInt64(LocalFileHeader.size) + additionalSize + dataSize
if centralDirStruct.isZIP64 {
zip64DataDescriptor = Data.readStruct(from: self.archiveFile, at: descriptorPosition)
} else {
dataDescriptor = Data.readStruct(from: self.archiveFile, at: descriptorPosition)
}
}
defer {
directoryIndex += UInt64(CentralDirectoryStructure.size)
directoryIndex += UInt64(centralDirStruct.fileNameLength)
directoryIndex += UInt64(centralDirStruct.extraFieldLength)
directoryIndex += UInt64(centralDirStruct.fileCommentLength)
index += 1
}
return Entry(
centralDirectoryStructure: centralDirStruct,
localFileHeader: localFileHeader,
dataDescriptor: dataDescriptor,
zip64DataDescriptor: zip64DataDescriptor)
}
}
/// Retrieve the ZIP `Entry` with the given `path` from the receiver.
///
/// - Note: The ZIP file format specification does not enforce unique paths for entries.
/// Therefore an archive can contain multiple entries with the same path. This method
/// always returns the first `Entry` with the given `path`.
///
/// - Parameter path: A relative file path identifying the corresponding `Entry`.
/// - Returns: An `Entry` with the given `path`. Otherwise, `nil`.
subscript(path: String) -> Entry? {
if let encoding = preferredEncoding {
return first { $0.path(using: encoding) == path }
}
return first { $0.path == path }
}
// MARK: Private
private static func scanForZIP64EndOfCentralDirectory(in file: FILEPointer, eocdOffset: UInt64)
-> ZIP64EndOfCentralDirectory?
{
guard UInt64(ZIP64EndOfCentralDirectoryLocator.size) < eocdOffset else {
return nil
}
let locatorOffset = eocdOffset - UInt64(ZIP64EndOfCentralDirectoryLocator.size)
guard UInt64(ZIP64EndOfCentralDirectoryRecord.size) < locatorOffset else {
return nil
}
let recordOffset = locatorOffset - UInt64(ZIP64EndOfCentralDirectoryRecord.size)
guard
let locator: ZIP64EndOfCentralDirectoryLocator = Data.readStruct(from: file, at: locatorOffset),
let record: ZIP64EndOfCentralDirectoryRecord = Data.readStruct(from: file, at: recordOffset)
else {
return nil
}
return ZIP64EndOfCentralDirectory(record: record, locator: locator)
}
}
extension Archive.EndOfCentralDirectoryRecord {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider provider: (Int) throws -> Data) {
guard data.count == Archive.EndOfCentralDirectoryRecord.size else { return nil }
guard data.scanValue(start: 0) == endOfCentralDirectorySignature else { return nil }
numberOfDisk = data.scanValue(start: 4)
numberOfDiskStart = data.scanValue(start: 6)
totalNumberOfEntriesOnDisk = data.scanValue(start: 8)
totalNumberOfEntriesInCentralDirectory = data.scanValue(start: 10)
sizeOfCentralDirectory = data.scanValue(start: 12)
offsetToStartOfCentralDirectory = data.scanValue(start: 16)
zipFileCommentLength = data.scanValue(start: 20)
guard let commentData = try? provider(Int(zipFileCommentLength)) else { return nil }
guard commentData.count == Int(zipFileCommentLength) else { return nil }
zipFileCommentData = commentData
}
init(
record: Archive.EndOfCentralDirectoryRecord,
numberOfEntriesOnDisk: UInt16,
numberOfEntriesInCentralDirectory: UInt16,
updatedSizeOfCentralDirectory: UInt32,
startOfCentralDirectory: UInt32)
{
numberOfDisk = record.numberOfDisk
numberOfDiskStart = record.numberOfDiskStart
totalNumberOfEntriesOnDisk = numberOfEntriesOnDisk
totalNumberOfEntriesInCentralDirectory = numberOfEntriesInCentralDirectory
sizeOfCentralDirectory = updatedSizeOfCentralDirectory
offsetToStartOfCentralDirectory = startOfCentralDirectory
zipFileCommentLength = record.zipFileCommentLength
zipFileCommentData = record.zipFileCommentData
}
// MARK: Internal
var data: Data {
var endOfCDSignature = endOfCentralDirectorySignature
var numberOfDisk = numberOfDisk
var numberOfDiskStart = numberOfDiskStart
var totalNumberOfEntriesOnDisk = totalNumberOfEntriesOnDisk
var totalNumberOfEntriesInCD = totalNumberOfEntriesInCentralDirectory
var sizeOfCentralDirectory = sizeOfCentralDirectory
var offsetToStartOfCD = offsetToStartOfCentralDirectory
var zipFileCommentLength = zipFileCommentLength
var data = Data()
withUnsafePointer(to: &endOfCDSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDiskStart) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesOnDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesInCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &sizeOfCentralDirectory) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &offsetToStartOfCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &zipFileCommentLength) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
data.append(zipFileCommentData)
return data
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Archive.swift
|
Swift
|
unknown
| 17,293
|
//
// Data+Compression.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
#if canImport(zlib)
import zlib
#endif
// MARK: - CompressionMethod
/// The compression method of an `Entry` in a ZIP `Archive`.
enum CompressionMethod: UInt16 {
/// Indicates that an `Entry` has no compression applied to its contents.
case none = 0
/// Indicates that contents of an `Entry` have been compressed with a zlib compatible Deflate algorithm.
case deflate = 8
}
/// An unsigned 32-Bit Integer representing a checksum.
typealias CRC32 = UInt32
/// A custom handler that consumes a `Data` object containing partial entry data.
/// - Parameters:
/// - data: A chunk of `Data` to consume.
/// - Throws: Can throw to indicate errors during data consumption.
typealias Consumer = (_ data: Data) throws -> Void
/// A custom handler that receives a position and a size that can be used to provide data from an arbitrary source.
/// - Parameters:
/// - position: The current read position.
/// - size: The size of the chunk to provide.
/// - Returns: A chunk of `Data`.
/// - Throws: Can throw to indicate errors in the data source.
typealias Provider = (_ position: Int64, _ size: Int) throws -> Data
extension Data {
enum CompressionError: Error {
case invalidStream
case corruptedData
}
/// Compress the output of `provider` and pass it to `consumer`.
/// - Parameters:
/// - size: The uncompressed size of the data to be compressed.
/// - bufferSize: The maximum size of the compression buffer.
/// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk.
/// - consumer: A closure that processes the result of the compress operation.
/// - Returns: The checksum of the processed content.
static func compress(size: Int64, bufferSize: Int, provider: Provider, consumer: Consumer) throws -> CRC32 {
#if os(macOS) || canImport(UIKit)
return try process(
operation: COMPRESSION_STREAM_ENCODE,
size: size,
bufferSize: bufferSize,
provider: provider,
consumer: consumer)
#else
return try encode(size: size, bufferSize: bufferSize, provider: provider, consumer: consumer)
#endif
}
/// Decompress the output of `provider` and pass it to `consumer`.
/// - Parameters:
/// - size: The compressed size of the data to be decompressed.
/// - bufferSize: The maximum size of the decompression buffer.
/// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance.
/// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk.
/// - consumer: A closure that processes the result of the decompress operation.
/// - Returns: The checksum of the processed content.
static func decompress(
size: Int64,
bufferSize: Int,
skipCRC32: Bool,
provider: Provider,
consumer: Consumer)
throws -> CRC32
{
#if os(macOS) || canImport(UIKit)
return try process(
operation: COMPRESSION_STREAM_DECODE,
size: size,
bufferSize: bufferSize,
skipCRC32: skipCRC32,
provider: provider,
consumer: consumer)
#else
return try decode(bufferSize: bufferSize, skipCRC32: skipCRC32, provider: provider, consumer: consumer)
#endif
}
/// Calculate the `CRC32` checksum of the receiver.
///
/// - Parameter checksum: The starting seed.
/// - Returns: The checksum calculated from the bytes of the receiver and the starting seed.
func crc32(checksum: CRC32) -> CRC32 {
#if canImport(zlib)
return withUnsafeBytes { bufferPointer in
let length = UInt32(count)
return CRC32(zlib.crc32(UInt(checksum), bufferPointer.bindMemory(to: UInt8.self).baseAddress, length))
}
#else
return builtInCRC32(checksum: checksum)
#endif
}
}
// MARK: - Apple Platforms
#if os(macOS) || canImport(UIKit)
import Compression
extension Data {
static func process(
operation: compression_stream_operation,
size: Int64,
bufferSize: Int,
skipCRC32: Bool = false,
provider: Provider,
consumer: Consumer)
throws -> CRC32
{
var crc32 = CRC32(0)
let destPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
defer { destPointer.deallocate() }
let streamPointer = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
defer { streamPointer.deallocate() }
var stream = streamPointer.pointee
var status = compression_stream_init(&stream, operation, COMPRESSION_ZLIB)
guard status != COMPRESSION_STATUS_ERROR else { throw CompressionError.invalidStream }
defer { compression_stream_destroy(&stream) }
stream.src_size = 0
stream.dst_ptr = destPointer
stream.dst_size = bufferSize
var position: Int64 = 0
var sourceData: Data?
repeat {
let isExhausted = stream.src_size == 0
if isExhausted {
do {
sourceData = try provider(position, Int(Swift.min(size - position, Int64(bufferSize))))
position += Int64(stream.prepare(for: sourceData))
} catch { throw error }
}
if let sourceData {
sourceData.withUnsafeBytes { rawBufferPointer in
if let baseAddress = rawBufferPointer.baseAddress {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.src_ptr = pointer.advanced(by: sourceData.count - stream.src_size)
let flags = sourceData.count < bufferSize ? Int32(COMPRESSION_STREAM_FINALIZE.rawValue) : 0
status = compression_stream_process(&stream, flags)
}
}
if
operation == COMPRESSION_STREAM_ENCODE,
isExhausted, skipCRC32 == false { crc32 = sourceData.crc32(checksum: crc32) }
}
switch status {
case COMPRESSION_STATUS_OK, COMPRESSION_STATUS_END:
let outputData = Data(bytesNoCopy: destPointer, count: bufferSize - stream.dst_size, deallocator: .none)
try consumer(outputData)
if operation == COMPRESSION_STREAM_DECODE, !skipCRC32 { crc32 = outputData.crc32(checksum: crc32) }
stream.dst_ptr = destPointer
stream.dst_size = bufferSize
default: throw CompressionError.corruptedData
}
} while status == COMPRESSION_STATUS_OK
return crc32
}
}
extension compression_stream {
fileprivate mutating func prepare(for sourceData: Data?) -> Int {
guard let sourceData else { return 0 }
src_size = sourceData.count
return sourceData.count
}
}
// MARK: - Linux
#else
import CZlib
extension Data {
static func encode(size: Int64, bufferSize: Int, provider: Provider, consumer: Consumer) throws -> CRC32 {
var stream = z_stream()
let streamSize = Int32(MemoryLayout<z_stream>.size)
var result = deflateInit2_(
&stream,
Z_DEFAULT_COMPRESSION,
Z_DEFLATED,
-MAX_WBITS,
9,
Z_DEFAULT_STRATEGY,
ZLIB_VERSION,
streamSize)
defer { deflateEnd(&stream) }
guard result == Z_OK else { throw CompressionError.invalidStream }
var flush = Z_NO_FLUSH
var position: Int64 = 0
var zipCRC32 = CRC32(0)
repeat {
let readSize = Int(Swift.min(size - position, Int64(bufferSize)))
var inputChunk = try provider(position, readSize)
zipCRC32 = inputChunk.crc32(checksum: zipCRC32)
stream.avail_in = UInt32(inputChunk.count)
try inputChunk.withUnsafeMutableBytes { rawBufferPointer in
if let baseAddress = rawBufferPointer.baseAddress {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.next_in = pointer
flush = position + Int64(bufferSize) >= size ? Z_FINISH : Z_NO_FLUSH
} else if rawBufferPointer.count > 0 {
throw CompressionError.corruptedData
} else {
stream.next_in = nil
flush = Z_FINISH
}
var outputChunk = Data(count: bufferSize)
repeat {
stream.avail_out = UInt32(bufferSize)
try outputChunk.withUnsafeMutableBytes { rawBufferPointer in
guard let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 else {
throw CompressionError.corruptedData
}
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.next_out = pointer
result = deflate(&stream, flush)
}
guard result >= Z_OK else { throw CompressionError.corruptedData }
outputChunk.count = bufferSize - Int(stream.avail_out)
try consumer(outputChunk)
} while stream.avail_out == 0
}
position += Int64(readSize)
} while flush != Z_FINISH
return zipCRC32
}
static func decode(bufferSize: Int, skipCRC32: Bool, provider: Provider, consumer: Consumer) throws -> CRC32 {
var stream = z_stream()
let streamSize = Int32(MemoryLayout<z_stream>.size)
var result = inflateInit2_(&stream, -MAX_WBITS, ZLIB_VERSION, streamSize)
defer { inflateEnd(&stream) }
guard result == Z_OK else { throw CompressionError.invalidStream }
var unzipCRC32 = CRC32(0)
var position: Int64 = 0
repeat {
stream.avail_in = UInt32(bufferSize)
var chunk = try provider(position, bufferSize)
position += Int64(chunk.count)
try chunk.withUnsafeMutableBytes { rawBufferPointer in
if let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.next_in = pointer
repeat {
var outputData = Data(count: bufferSize)
stream.avail_out = UInt32(bufferSize)
try outputData.withUnsafeMutableBytes { rawBufferPointer in
if let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.next_out = pointer
} else {
throw CompressionError.corruptedData
}
result = inflate(&stream, Z_NO_FLUSH)
guard
result != Z_NEED_DICT,
result != Z_DATA_ERROR,
result != Z_MEM_ERROR
else {
throw CompressionError.corruptedData
}
}
let remainingLength = UInt32(bufferSize) - stream.avail_out
outputData.count = Int(remainingLength)
try consumer(outputData)
if !skipCRC32 { unzipCRC32 = outputData.crc32(checksum: unzipCRC32) }
} while stream.avail_out == 0
}
}
} while result != Z_STREAM_END
return unzipCRC32
}
}
#endif
/// The lookup table used to calculate `CRC32` checksums when using the built-in
/// CRC32 implementation.
private let crcTable: [CRC32] = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832,
0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a,
0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab,
0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4,
0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074,
0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525,
0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76,
0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6,
0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7,
0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7,
0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330,
0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
]
extension Data {
/// Lookup table-based CRC32 implenetation that is used
/// if `zlib` isn't available.
/// - Parameter checksum: Running checksum or `0` for the initial run.
/// - Returns: The calculated checksum of the receiver.
func builtInCRC32(checksum: CRC32) -> CRC32 {
// The typecast is necessary on 32-bit platforms because of
// https://bugs.swift.org/browse/SR-1774
let mask = 0xffffffff as CRC32
var result = checksum ^ mask
#if swift(>=5.0)
crcTable.withUnsafeBufferPointer { crcTablePointer in
self.withUnsafeBytes { bufferPointer in
var bufferIndex = 0
while bufferIndex < self.count {
let byte = bufferPointer[bufferIndex]
let index = Int((result ^ CRC32(byte)) & 0xff)
result = (result >> 8) ^ crcTablePointer[index]
bufferIndex += 1
}
}
}
#else
withUnsafeBytes { bytes in
let bins = stride(from: 0, to: self.count, by: 256)
for bin in bins {
for binIndex in 0..<256 {
let byteIndex = bin + binIndex
guard byteIndex < self.count else { break }
let byte = bytes[byteIndex]
let index = Int((result ^ CRC32(byte)) & 0xff)
result = (result >> 8) ^ crcTable[index]
}
}
}
#endif
return result ^ mask
}
}
#if !swift(>=5.0)
// Since Swift 5.0, `Data.withUnsafeBytes()` passes an `UnsafeRawBufferPointer` instead of an `UnsafePointer<UInt8>`
// into `body`.
// We provide a compatible method for targets that use Swift 4.x so that we can use the new version
// across all language versions.
extension Data {
func withUnsafeBytes<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T {
let count = count
return try withUnsafeBytes { (pointer: UnsafePointer<UInt8>) throws -> T in
try body(UnsafeRawBufferPointer(start: pointer, count: count))
}
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#else
mutating func withUnsafeMutableBytes<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T {
let count = count
guard count > 0 else {
return try body(UnsafeMutableRawBufferPointer(start: nil, count: count))
}
return try withUnsafeMutableBytes { (pointer: UnsafeMutablePointer<UInt8>) throws -> T in
try body(UnsafeMutableRawBufferPointer(start: pointer, count: count))
}
}
#endif
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Data+Compression.swift
|
Swift
|
unknown
| 16,623
|
//
// Data+CompressionDeprecated.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Data {
@available(*, deprecated, message: "Please use `Int64` for `size` and provider `position`.")
static func compress(
size: Int,
bufferSize: Int,
provider: (_ position: Int, _ size: Int) throws -> Data,
consumer: Consumer)
throws -> CRC32
{
let newProvider: Provider = { try provider(Int($0), $1) }
return try compress(size: Int64(size), bufferSize: bufferSize, provider: newProvider, consumer: consumer)
}
@available(*, deprecated, message: "Please use `Int64` for `size` and provider `position`.")
static func decompress(
size: Int,
bufferSize: Int,
skipCRC32: Bool,
provider: (_ position: Int, _ size: Int) throws -> Data,
consumer: Consumer)
throws -> CRC32
{
let newProvider: Provider = { try provider(Int($0), $1) }
return try decompress(
size: Int64(size),
bufferSize: bufferSize,
skipCRC32: skipCRC32,
provider: newProvider,
consumer: consumer)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Data+CompressionDeprecated.swift
|
Swift
|
unknown
| 1,307
|
//
// Data+Serialization.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
#if os(Android)
typealias FILEPointer = OpaquePointer
#else
typealias FILEPointer = UnsafeMutablePointer<FILE>
#endif
// MARK: - DataSerializable
protocol DataSerializable {
static var size: Int { get }
init?(data: Data, additionalDataProvider: (Int) throws -> Data)
var data: Data { get }
}
extension Data {
enum DataError: Error {
case unreadableFile
case unwritableFile
}
static func readStruct<T>(from file: FILEPointer, at offset: UInt64)
-> T? where T: DataSerializable
{
guard offset <= .max else { return nil }
fseeko(file, off_t(offset), SEEK_SET)
guard let data = try? readChunk(of: T.size, from: file) else {
return nil
}
let structure = T(data: data, additionalDataProvider: { additionalDataSize -> Data in
try self.readChunk(of: additionalDataSize, from: file)
})
return structure
}
static func consumePart(
of size: Int64,
chunkSize: Int,
skipCRC32: Bool = false,
provider: Provider,
consumer: Consumer)
throws -> CRC32
{
var checksum = CRC32(0)
guard size > 0 else {
try consumer(Data())
return checksum
}
let readInOneChunk = (size < chunkSize)
var chunkSize = readInOneChunk ? Int(size) : chunkSize
var bytesRead: Int64 = 0
while bytesRead < size {
let remainingSize = size - bytesRead
chunkSize = remainingSize < chunkSize ? Int(remainingSize) : chunkSize
let data = try provider(bytesRead, chunkSize)
try consumer(data)
if !skipCRC32 {
checksum = data.crc32(checksum: checksum)
}
bytesRead += Int64(chunkSize)
}
return checksum
}
static func readChunk(of size: Int, from file: FILEPointer) throws -> Data {
let alignment = MemoryLayout<UInt>.alignment
#if swift(>=4.1)
let bytes = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: alignment)
#else
let bytes = UnsafeMutableRawPointer.allocate(bytes: size, alignedTo: alignment)
#endif
let bytesRead = fread(bytes, 1, size, file)
let error = ferror(file)
if error > 0 {
throw DataError.unreadableFile
}
#if swift(>=4.1)
return Data(bytesNoCopy: bytes, count: bytesRead, deallocator: .custom { buf, _ in buf.deallocate() })
#else
let deallocator = Deallocator.custom { buf, _ in buf.deallocate(bytes: size, alignedTo: 1) }
return Data(bytesNoCopy: bytes, count: bytesRead, deallocator: deallocator)
#endif
}
static func write(chunk: Data, to file: FILEPointer) throws -> Int {
var sizeWritten = 0
chunk.withUnsafeBytes { rawBufferPointer in
if let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
sizeWritten = fwrite(pointer, 1, chunk.count, file)
}
}
let error = ferror(file)
if error > 0 {
throw DataError.unwritableFile
}
return sizeWritten
}
static func writeLargeChunk(
_ chunk: Data,
size: UInt64,
bufferSize: Int,
to file: FILEPointer)
throws -> UInt64
{
var sizeWritten: UInt64 = 0
chunk.withUnsafeBytes { rawBufferPointer in
if let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
while sizeWritten < size {
let remainingSize = size - sizeWritten
let chunkSize = Swift.min(Int(remainingSize), bufferSize)
let curPointer = pointer.advanced(by: Int(sizeWritten))
fwrite(curPointer, 1, chunkSize, file)
sizeWritten += UInt64(chunkSize)
}
}
}
let error = ferror(file)
if error > 0 {
throw DataError.unwritableFile
}
return sizeWritten
}
func scanValue<T>(start: Int) -> T {
let subdata = subdata(in: start..<start + MemoryLayout<T>.size)
#if swift(>=5.0)
return subdata.withUnsafeBytes { $0.load(as: T.self) }
#else
return subdata.withUnsafeBytes { $0.pointee }
#endif
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Data+Serialization.swift
|
Swift
|
unknown
| 4,371
|
//
// Entry+Serialization.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Entry.LocalFileHeader {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider provider: (Int) throws -> Data) {
guard data.count == Entry.LocalFileHeader.size else { return nil }
guard data.scanValue(start: 0) == localFileHeaderSignature else { return nil }
versionNeededToExtract = data.scanValue(start: 4)
generalPurposeBitFlag = data.scanValue(start: 6)
compressionMethod = data.scanValue(start: 8)
lastModFileTime = data.scanValue(start: 10)
lastModFileDate = data.scanValue(start: 12)
crc32 = data.scanValue(start: 14)
compressedSize = data.scanValue(start: 18)
uncompressedSize = data.scanValue(start: 22)
fileNameLength = data.scanValue(start: 26)
extraFieldLength = data.scanValue(start: 28)
let additionalDataLength = Int(fileNameLength) + Int(extraFieldLength)
guard let additionalData = try? provider(additionalDataLength) else { return nil }
guard additionalData.count == additionalDataLength else { return nil }
var subRangeStart = 0
var subRangeEnd = Int(fileNameLength)
fileNameData = additionalData.subdata(in: subRangeStart..<subRangeEnd)
subRangeStart += Int(fileNameLength)
subRangeEnd = subRangeStart + Int(extraFieldLength)
extraFieldData = additionalData.subdata(in: subRangeStart..<subRangeEnd)
if
let zip64ExtendedInformation = Entry.ZIP64ExtendedInformation.scanForZIP64Field(
in: extraFieldData,
fields: validFields)
{
extraFields = [zip64ExtendedInformation]
}
}
// MARK: Internal
var data: Data {
var localFileHeaderSignature = localFileHeaderSignature
var versionNeededToExtract = versionNeededToExtract
var generalPurposeBitFlag = generalPurposeBitFlag
var compressionMethod = compressionMethod
var lastModFileTime = lastModFileTime
var lastModFileDate = lastModFileDate
var crc32 = crc32
var compressedSize = compressedSize
var uncompressedSize = uncompressedSize
var fileNameLength = fileNameLength
var extraFieldLength = extraFieldLength
var data = Data()
withUnsafePointer(to: &localFileHeaderSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &versionNeededToExtract) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &generalPurposeBitFlag) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &compressionMethod) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &lastModFileTime) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &lastModFileDate) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &crc32) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &compressedSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &uncompressedSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &fileNameLength) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &extraFieldLength) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
data.append(fileNameData)
data.append(extraFieldData)
return data
}
}
extension Entry.CentralDirectoryStructure {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider provider: (Int) throws -> Data) {
guard data.count == Entry.CentralDirectoryStructure.size else { return nil }
guard data.scanValue(start: 0) == centralDirectorySignature else { return nil }
versionMadeBy = data.scanValue(start: 4)
versionNeededToExtract = data.scanValue(start: 6)
generalPurposeBitFlag = data.scanValue(start: 8)
compressionMethod = data.scanValue(start: 10)
lastModFileTime = data.scanValue(start: 12)
lastModFileDate = data.scanValue(start: 14)
crc32 = data.scanValue(start: 16)
compressedSize = data.scanValue(start: 20)
uncompressedSize = data.scanValue(start: 24)
fileNameLength = data.scanValue(start: 28)
extraFieldLength = data.scanValue(start: 30)
fileCommentLength = data.scanValue(start: 32)
diskNumberStart = data.scanValue(start: 34)
internalFileAttributes = data.scanValue(start: 36)
externalFileAttributes = data.scanValue(start: 38)
relativeOffsetOfLocalHeader = data.scanValue(start: 42)
let additionalDataLength = Int(fileNameLength) + Int(extraFieldLength) + Int(fileCommentLength)
guard let additionalData = try? provider(additionalDataLength) else { return nil }
guard additionalData.count == additionalDataLength else { return nil }
var subRangeStart = 0
var subRangeEnd = Int(fileNameLength)
fileNameData = additionalData.subdata(in: subRangeStart..<subRangeEnd)
subRangeStart += Int(fileNameLength)
subRangeEnd = subRangeStart + Int(extraFieldLength)
extraFieldData = additionalData.subdata(in: subRangeStart..<subRangeEnd)
subRangeStart += Int(extraFieldLength)
subRangeEnd = subRangeStart + Int(fileCommentLength)
fileCommentData = additionalData.subdata(in: subRangeStart..<subRangeEnd)
if
let zip64ExtendedInformation = Entry.ZIP64ExtendedInformation.scanForZIP64Field(
in: extraFieldData,
fields: validFields)
{
extraFields = [zip64ExtendedInformation]
}
}
// MARK: Internal
var data: Data {
var centralDirectorySignature = centralDirectorySignature
var versionMadeBy = versionMadeBy
var versionNeededToExtract = versionNeededToExtract
var generalPurposeBitFlag = generalPurposeBitFlag
var compressionMethod = compressionMethod
var lastModFileTime = lastModFileTime
var lastModFileDate = lastModFileDate
var crc32 = crc32
var compressedSize = compressedSize
var uncompressedSize = uncompressedSize
var fileNameLength = fileNameLength
var extraFieldLength = extraFieldLength
var fileCommentLength = fileCommentLength
var diskNumberStart = diskNumberStart
var internalFileAttributes = internalFileAttributes
var externalFileAttributes = externalFileAttributes
var relativeOffsetOfLocalHeader = relativeOffsetOfLocalHeader
var data = Data()
withUnsafePointer(to: ¢ralDirectorySignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &versionMadeBy) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &versionNeededToExtract) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &generalPurposeBitFlag) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &compressionMethod) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &lastModFileTime) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &lastModFileDate) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &crc32) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &compressedSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &uncompressedSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &fileNameLength) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &extraFieldLength) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &fileCommentLength) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &diskNumberStart) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &internalFileAttributes) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &externalFileAttributes) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &relativeOffsetOfLocalHeader) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
data.append(fileNameData)
data.append(extraFieldData)
data.append(fileCommentData)
return data
}
}
extension Entry.DataDescriptor {
init?(data: Data, additionalDataProvider _: (Int) throws -> Data) {
guard data.count == Self.size else { return nil }
let signature: UInt32 = data.scanValue(start: 0)
// The DataDescriptor signature is not mandatory so we have to re-arrange the input data if it is missing.
var readOffset = 0
if signature == dataDescriptorSignature { readOffset = 4 }
crc32 = data.scanValue(start: readOffset)
readOffset += MemoryLayout<UInt32>.size
compressedSize = data.scanValue(start: readOffset)
readOffset += Self.memoryLengthOfSize
uncompressedSize = data.scanValue(start: readOffset)
// Our add(_ entry:) methods always maintain compressed & uncompressed
// sizes and so we don't need a data descriptor for newly added entries.
// Data descriptors of already existing entries are manually preserved
// when copying those entries to the tempArchive during remove(_ entry:).
self.data = Data()
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Entry+Serialization.swift
|
Swift
|
unknown
| 9,448
|
//
// Entry+ZIP64.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
// MARK: - ExtensibleDataField
protocol ExtensibleDataField {
var headerID: UInt16 { get }
var dataSize: UInt16 { get }
}
extension Entry {
enum EntryError: Error {
case invalidDataError
}
struct ZIP64ExtendedInformation: ExtensibleDataField {
let headerID: UInt16 = ExtraFieldHeaderID.zip64ExtendedInformation.rawValue
let dataSize: UInt16
static let headerSize: UInt16 = 4
let uncompressedSize: UInt64
let compressedSize: UInt64
let relativeOffsetOfLocalHeader: UInt64
let diskNumberStart: UInt32
}
var zip64ExtendedInformation: ZIP64ExtendedInformation? {
centralDirectoryStructure.zip64ExtendedInformation
}
}
typealias Field = Entry.ZIP64ExtendedInformation.Field
extension Entry.LocalFileHeader {
var validFields: [Field] {
var fields: [Field] = []
if uncompressedSize == .max { fields.append(.uncompressedSize) }
if compressedSize == .max { fields.append(.compressedSize) }
return fields
}
}
extension Entry.CentralDirectoryStructure {
var validFields: [Field] {
var fields: [Field] = []
if uncompressedSize == .max { fields.append(.uncompressedSize) }
if compressedSize == .max { fields.append(.compressedSize) }
if relativeOffsetOfLocalHeader == .max { fields.append(.relativeOffsetOfLocalHeader) }
if diskNumberStart == .max { fields.append(.diskNumberStart) }
return fields
}
var zip64ExtendedInformation: Entry.ZIP64ExtendedInformation? {
extraFields?.compactMap { $0 as? Entry.ZIP64ExtendedInformation }.first
}
}
extension Entry.ZIP64ExtendedInformation {
// MARK: Lifecycle
init?(data: Data, fields: [Field]) {
let headerLength = 4
guard fields.reduce(0, { $0 + $1.size }) + headerLength == data.count else { return nil }
var readOffset = headerLength
func value<T>(of field: Field) throws -> T where T: BinaryInteger {
if fields.contains(field) {
defer {
readOffset += MemoryLayout<T>.size
}
guard readOffset + field.size <= data.count else {
throw Entry.EntryError.invalidDataError
}
return data.scanValue(start: readOffset)
} else {
return 0
}
}
do {
dataSize = data.scanValue(start: 2)
uncompressedSize = try value(of: .uncompressedSize)
compressedSize = try value(of: .compressedSize)
relativeOffsetOfLocalHeader = try value(of: .relativeOffsetOfLocalHeader)
diskNumberStart = try value(of: .diskNumberStart)
} catch {
return nil
}
}
init?(zip64ExtendedInformation: Entry.ZIP64ExtendedInformation?, offset: UInt64) {
// Only used when removing entry, if no ZIP64 extended information exists,
// then this information will not be newly added either
guard let existingInfo = zip64ExtendedInformation else { return nil }
relativeOffsetOfLocalHeader = offset >= maxOffsetOfLocalFileHeader ? offset : 0
uncompressedSize = existingInfo.uncompressedSize
compressedSize = existingInfo.compressedSize
diskNumberStart = existingInfo.diskNumberStart
let tempDataSize = [relativeOffsetOfLocalHeader, uncompressedSize, compressedSize]
.filter { $0 != 0 }
.reduce(UInt16(0)) { $0 + UInt16(MemoryLayout.size(ofValue: $1)) }
dataSize = tempDataSize + (diskNumberStart > 0 ? UInt16(MemoryLayout.size(ofValue: diskNumberStart)) : 0)
if dataSize == 0 { return nil }
}
// MARK: Internal
enum Field {
case uncompressedSize
case compressedSize
case relativeOffsetOfLocalHeader
case diskNumberStart
var size: Int {
switch self {
case .uncompressedSize, .compressedSize, .relativeOffsetOfLocalHeader:
return 8
case .diskNumberStart:
return 4
}
}
}
var data: Data {
var headerID = headerID
var dataSize = dataSize
var uncompressedSize = uncompressedSize
var compressedSize = compressedSize
var relativeOffsetOfLFH = relativeOffsetOfLocalHeader
var diskNumberStart = diskNumberStart
var data = Data()
withUnsafePointer(to: &headerID) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &dataSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
if uncompressedSize != 0 || compressedSize != 0 {
withUnsafePointer(to: &uncompressedSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &compressedSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
}
if relativeOffsetOfLocalHeader != 0 {
withUnsafePointer(to: &relativeOffsetOfLFH) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
}
if diskNumberStart != 0 {
withUnsafePointer(to: &diskNumberStart) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
}
return data
}
static func scanForZIP64Field(in data: Data, fields: [Field]) -> Entry.ZIP64ExtendedInformation? {
guard data.isEmpty == false else { return nil }
var offset = 0
var headerID: UInt16
var dataSize: UInt16
let extraFieldLength = data.count
let headerSize = Int(Entry.ZIP64ExtendedInformation.headerSize)
while offset < extraFieldLength - headerSize {
headerID = data.scanValue(start: offset)
dataSize = data.scanValue(start: offset + 2)
let nextOffset = offset + headerSize + Int(dataSize)
guard nextOffset <= extraFieldLength else { return nil }
if headerID == ExtraFieldHeaderID.zip64ExtendedInformation.rawValue {
return Entry.ZIP64ExtendedInformation(data: data.subdata(in: offset..<nextOffset), fields: fields)
}
offset = nextOffset
}
return nil
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Entry+ZIP64.swift
|
Swift
|
unknown
| 5,966
|
//
// Entry.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import CoreFoundation
import Foundation
// MARK: - Entry
/// A value that represents a file, a directory or a symbolic link within a ZIP `Archive`.
///
/// You can retrieve instances of `Entry` from an `Archive` via subscripting or iteration.
/// Entries are identified by their `path`.
struct Entry: Equatable {
// MARK: Lifecycle
init?(
centralDirectoryStructure: CentralDirectoryStructure,
localFileHeader: LocalFileHeader,
dataDescriptor: DefaultDataDescriptor? = nil,
zip64DataDescriptor: ZIP64DataDescriptor? = nil)
{
// We currently don't support encrypted archives
guard !centralDirectoryStructure.isEncrypted else { return nil }
self.centralDirectoryStructure = centralDirectoryStructure
self.localFileHeader = localFileHeader
self.dataDescriptor = dataDescriptor
self.zip64DataDescriptor = zip64DataDescriptor
}
// MARK: Internal
/// The type of an `Entry` in a ZIP `Archive`.
enum EntryType: Int {
/// Indicates a regular file.
case file
/// Indicates a directory.
case directory
/// Indicates a symbolic link.
case symlink
init(mode: mode_t) {
switch mode & S_IFMT {
case S_IFDIR:
self = .directory
case S_IFLNK:
self = .symlink
default:
self = .file
}
}
}
enum OSType: UInt {
case msdos = 0
case unix = 3
case osx = 19
case unused = 20
}
struct LocalFileHeader: DataSerializable {
let localFileHeaderSignature = UInt32(localFileHeaderStructSignature)
let versionNeededToExtract: UInt16
let generalPurposeBitFlag: UInt16
let compressionMethod: UInt16
let lastModFileTime: UInt16
let lastModFileDate: UInt16
let crc32: UInt32
let compressedSize: UInt32
let uncompressedSize: UInt32
let fileNameLength: UInt16
let extraFieldLength: UInt16
static let size = 30
let fileNameData: Data
let extraFieldData: Data
var extraFields: [ExtensibleDataField]?
}
struct DataDescriptor<T: BinaryInteger>: DataSerializable {
let data: Data
let dataDescriptorSignature = UInt32(dataDescriptorStructSignature)
let crc32: UInt32
// For normal archives, the compressed and uncompressed sizes are 4 bytes each.
// For ZIP64 format archives, the compressed and uncompressed sizes are 8 bytes each.
let compressedSize: T
let uncompressedSize: T
static var memoryLengthOfSize: Int { MemoryLayout<T>.size }
static var size: Int { memoryLengthOfSize * 2 + 8 }
}
typealias DefaultDataDescriptor = DataDescriptor<UInt32>
typealias ZIP64DataDescriptor = DataDescriptor<UInt64>
struct CentralDirectoryStructure: DataSerializable {
static let size = 46
let centralDirectorySignature = UInt32(centralDirectoryStructSignature)
let versionMadeBy: UInt16
let versionNeededToExtract: UInt16
let generalPurposeBitFlag: UInt16
let compressionMethod: UInt16
let lastModFileTime: UInt16
let lastModFileDate: UInt16
let crc32: UInt32
let compressedSize: UInt32
let uncompressedSize: UInt32
let fileNameLength: UInt16
let extraFieldLength: UInt16
let fileCommentLength: UInt16
let diskNumberStart: UInt16
let internalFileAttributes: UInt16
let externalFileAttributes: UInt32
let relativeOffsetOfLocalHeader: UInt32
let fileNameData: Data
let extraFieldData: Data
let fileCommentData: Data
var extraFields: [ExtensibleDataField]?
var usesDataDescriptor: Bool { (generalPurposeBitFlag & (1 << 3)) != 0 }
var usesUTF8PathEncoding: Bool { (generalPurposeBitFlag & (1 << 11)) != 0 }
var isEncrypted: Bool { (generalPurposeBitFlag & (1 << 0)) != 0 }
var isZIP64: Bool {
// If ZIP64 extended information is existing, try to treat cd as ZIP64 format
// even if the version needed to extract is lower than 4.5
UInt8(truncatingIfNeeded: versionNeededToExtract) >= 45 || zip64ExtendedInformation != nil
}
}
let centralDirectoryStructure: CentralDirectoryStructure
let localFileHeader: LocalFileHeader
let dataDescriptor: DefaultDataDescriptor?
let zip64DataDescriptor: ZIP64DataDescriptor?
/// The `path` of the receiver within a ZIP `Archive`.
var path: String {
let dosLatinUS = 0x400
let dosLatinUSEncoding = CFStringEncoding(dosLatinUS)
let dosLatinUSStringEncoding = CFStringConvertEncodingToNSStringEncoding(dosLatinUSEncoding)
let codepage437 = String.Encoding(rawValue: dosLatinUSStringEncoding)
let encoding = centralDirectoryStructure.usesUTF8PathEncoding ? .utf8 : codepage437
return self.path(using: encoding)
}
/// The file attributes of the receiver as key/value pairs.
///
/// Contains the modification date and file permissions.
var fileAttributes: [FileAttributeKey: Any] {
FileManager.attributes(from: self)
}
/// The `CRC32` checksum of the receiver.
///
/// - Note: Always returns `0` for entries of type `EntryType.directory`.
var checksum: CRC32 {
if centralDirectoryStructure.usesDataDescriptor {
return zip64DataDescriptor?.crc32 ?? dataDescriptor?.crc32 ?? 0
}
return centralDirectoryStructure.crc32
}
/// The `EntryType` of the receiver.
var type: EntryType {
// OS Type is stored in the upper byte of versionMadeBy
let osTypeRaw = centralDirectoryStructure.versionMadeBy >> 8
let osType = OSType(rawValue: UInt(osTypeRaw)) ?? .unused
var isDirectory = path.hasSuffix("/")
switch osType {
case .unix, .osx:
let mode = mode_t(centralDirectoryStructure.externalFileAttributes >> 16) & S_IFMT
switch mode {
case S_IFREG:
return .file
case S_IFDIR:
return .directory
case S_IFLNK:
return .symlink
default:
return isDirectory ? .directory : .file
}
case .msdos:
isDirectory = isDirectory || ((centralDirectoryStructure.externalFileAttributes >> 4) == 0x01)
fallthrough // For all other OSes we can only guess based on the directory suffix char
default: return isDirectory ? .directory : .file
}
}
/// Indicates whether or not the receiver is compressed.
var isCompressed: Bool {
localFileHeader.compressionMethod != CompressionMethod.none.rawValue
}
/// The size of the receiver's compressed data.
var compressedSize: UInt64 {
if centralDirectoryStructure.isZIP64 {
return zip64DataDescriptor?.compressedSize ?? centralDirectoryStructure.effectiveCompressedSize
}
return UInt64(dataDescriptor?.compressedSize ?? centralDirectoryStructure.compressedSize)
}
/// The size of the receiver's uncompressed data.
var uncompressedSize: UInt64 {
if centralDirectoryStructure.isZIP64 {
return zip64DataDescriptor?.uncompressedSize ?? centralDirectoryStructure.effectiveUncompressedSize
}
return UInt64(dataDescriptor?.uncompressedSize ?? centralDirectoryStructure.uncompressedSize)
}
/// The combined size of the local header, the data and the optional data descriptor.
var localSize: UInt64 {
let localFileHeader = localFileHeader
var extraDataLength = Int(localFileHeader.fileNameLength)
extraDataLength += Int(localFileHeader.extraFieldLength)
var size = UInt64(LocalFileHeader.size + extraDataLength)
size += isCompressed ? compressedSize : uncompressedSize
if centralDirectoryStructure.isZIP64 {
size += zip64DataDescriptor != nil ? UInt64(ZIP64DataDescriptor.size) : 0
} else {
size += dataDescriptor != nil ? UInt64(DefaultDataDescriptor.size) : 0
}
return size
}
var dataOffset: UInt64 {
var dataOffset = centralDirectoryStructure.effectiveRelativeOffsetOfLocalHeader
dataOffset += UInt64(LocalFileHeader.size)
dataOffset += UInt64(localFileHeader.fileNameLength)
dataOffset += UInt64(localFileHeader.extraFieldLength)
return dataOffset
}
static func == (lhs: Entry, rhs: Entry) -> Bool {
lhs.path == rhs.path
&& lhs.localFileHeader.crc32 == rhs.localFileHeader.crc32
&& lhs.centralDirectoryStructure.effectiveRelativeOffsetOfLocalHeader
== rhs.centralDirectoryStructure.effectiveRelativeOffsetOfLocalHeader
}
/// Returns the `path` of the receiver within a ZIP `Archive` using a given encoding.
///
/// - Parameters:
/// - encoding: `String.Encoding`
func path(using encoding: String.Encoding) -> String {
String(data: centralDirectoryStructure.fileNameData, encoding: encoding) ?? ""
}
}
extension Entry.CentralDirectoryStructure {
init(
localFileHeader: Entry.LocalFileHeader,
fileAttributes: UInt32,
relativeOffset: UInt32,
extraField: (length: UInt16, data: Data))
{
versionMadeBy = UInt16(789)
versionNeededToExtract = localFileHeader.versionNeededToExtract
generalPurposeBitFlag = localFileHeader.generalPurposeBitFlag
compressionMethod = localFileHeader.compressionMethod
lastModFileTime = localFileHeader.lastModFileTime
lastModFileDate = localFileHeader.lastModFileDate
crc32 = localFileHeader.crc32
compressedSize = localFileHeader.compressedSize
uncompressedSize = localFileHeader.uncompressedSize
fileNameLength = localFileHeader.fileNameLength
extraFieldLength = extraField.length
fileCommentLength = UInt16(0)
diskNumberStart = UInt16(0)
internalFileAttributes = UInt16(0)
externalFileAttributes = fileAttributes
relativeOffsetOfLocalHeader = relativeOffset
fileNameData = localFileHeader.fileNameData
extraFieldData = extraField.data
fileCommentData = Data()
if
let zip64ExtendedInformation = Entry.ZIP64ExtendedInformation.scanForZIP64Field(
in: extraFieldData,
fields: validFields)
{
extraFields = [zip64ExtendedInformation]
}
}
init(
centralDirectoryStructure: Entry.CentralDirectoryStructure,
zip64ExtendedInformation: Entry.ZIP64ExtendedInformation?,
relativeOffset: UInt32)
{
if let existingInfo = zip64ExtendedInformation {
extraFieldData = existingInfo.data
versionNeededToExtract = max(
centralDirectoryStructure.versionNeededToExtract,
Archive.Version.v45.rawValue)
} else {
extraFieldData = centralDirectoryStructure.extraFieldData
let existingVersion = centralDirectoryStructure.versionNeededToExtract
versionNeededToExtract = existingVersion < Archive.Version.v45.rawValue
? centralDirectoryStructure.versionNeededToExtract
: Archive.Version.v20.rawValue
}
extraFieldLength = UInt16(extraFieldData.count)
relativeOffsetOfLocalHeader = relativeOffset
versionMadeBy = centralDirectoryStructure.versionMadeBy
generalPurposeBitFlag = centralDirectoryStructure.generalPurposeBitFlag
compressionMethod = centralDirectoryStructure.compressionMethod
lastModFileTime = centralDirectoryStructure.lastModFileTime
lastModFileDate = centralDirectoryStructure.lastModFileDate
crc32 = centralDirectoryStructure.crc32
compressedSize = centralDirectoryStructure.compressedSize
uncompressedSize = centralDirectoryStructure.uncompressedSize
fileNameLength = centralDirectoryStructure.fileNameLength
fileCommentLength = centralDirectoryStructure.fileCommentLength
diskNumberStart = centralDirectoryStructure.diskNumberStart
internalFileAttributes = centralDirectoryStructure.internalFileAttributes
externalFileAttributes = centralDirectoryStructure.externalFileAttributes
fileNameData = centralDirectoryStructure.fileNameData
fileCommentData = centralDirectoryStructure.fileCommentData
if
let zip64ExtendedInformation = Entry.ZIP64ExtendedInformation.scanForZIP64Field(
in: extraFieldData,
fields: validFields)
{
extraFields = [zip64ExtendedInformation]
}
}
}
extension Entry.CentralDirectoryStructure {
var effectiveCompressedSize: UInt64 {
if isZIP64, let compressedSize = zip64ExtendedInformation?.compressedSize, compressedSize > 0 {
return compressedSize
}
return UInt64(compressedSize)
}
var effectiveUncompressedSize: UInt64 {
if isZIP64, let uncompressedSize = zip64ExtendedInformation?.uncompressedSize, uncompressedSize > 0 {
return uncompressedSize
}
return UInt64(uncompressedSize)
}
var effectiveRelativeOffsetOfLocalHeader: UInt64 {
if isZIP64, let offset = zip64ExtendedInformation?.relativeOffsetOfLocalHeader, offset > 0 {
return offset
}
return UInt64(relativeOffsetOfLocalHeader)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/Entry.swift
|
Swift
|
unknown
| 12,804
|
//
// FileManager+ZIP.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension FileManager {
typealias CentralDirectoryStructure = Entry.CentralDirectoryStructure
class func attributes(from entry: Entry) -> [FileAttributeKey: Any] {
let centralDirectoryStructure = entry.centralDirectoryStructure
let entryType = entry.type
let fileTime = centralDirectoryStructure.lastModFileTime
let fileDate = centralDirectoryStructure.lastModFileDate
let defaultPermissions = entryType == .directory ? defaultDirectoryPermissions : defaultFilePermissions
var attributes = [.posixPermissions: defaultPermissions] as [FileAttributeKey: Any]
// Certain keys are not yet supported in swift-corelibs
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
attributes[.modificationDate] = Date(dateTime: (fileDate, fileTime))
#endif
let versionMadeBy = centralDirectoryStructure.versionMadeBy
guard let osType = Entry.OSType(rawValue: UInt(versionMadeBy >> 8)) else { return attributes }
let externalFileAttributes = centralDirectoryStructure.externalFileAttributes
let permissions = permissions(for: externalFileAttributes, osType: osType, entryType: entryType)
attributes[.posixPermissions] = NSNumber(value: permissions)
return attributes
}
class func permissions(
for externalFileAttributes: UInt32,
osType: Entry.OSType,
entryType: Entry.EntryType)
-> UInt16
{
switch osType {
case .unix, .osx:
let permissions = mode_t(externalFileAttributes >> 16) & ~S_IFMT
let defaultPermissions = entryType == .directory ? defaultDirectoryPermissions : defaultFilePermissions
return permissions == 0 ? defaultPermissions : UInt16(permissions)
default:
return entryType == .directory ? defaultDirectoryPermissions : defaultFilePermissions
}
}
class func externalFileAttributesForEntry(of type: Entry.EntryType, permissions: UInt16) -> UInt32 {
var typeInt: UInt16
switch type {
case .file:
typeInt = UInt16(S_IFREG)
case .directory:
typeInt = UInt16(S_IFDIR)
case .symlink:
typeInt = UInt16(S_IFLNK)
}
var externalFileAttributes = UInt32(typeInt | UInt16(permissions))
externalFileAttributes = (externalFileAttributes << 16)
return externalFileAttributes
}
class func permissionsForItem(at URL: URL) throws -> UInt16 {
let fileManager = FileManager()
let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: URL.path)
var fileStat = stat()
lstat(entryFileSystemRepresentation, &fileStat)
let permissions = fileStat.st_mode
return UInt16(permissions)
}
class func fileModificationDateTimeForItem(at url: URL) throws -> Date {
let fileManager = FileManager()
guard fileManager.itemExists(at: url) else {
throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: url.path])
}
let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
var fileStat = stat()
lstat(entryFileSystemRepresentation, &fileStat)
#if os(macOS) || canImport(UIKit)
let modTimeSpec = fileStat.st_mtimespec
#else
let modTimeSpec = fileStat.st_mtim
#endif
let timeStamp = TimeInterval(modTimeSpec.tv_sec) + TimeInterval(modTimeSpec.tv_nsec) / 1000000000.0
let modDate = Date(timeIntervalSince1970: timeStamp)
return modDate
}
class func fileSizeForItem(at url: URL) throws -> Int64 {
let fileManager = FileManager()
guard fileManager.itemExists(at: url) else {
throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: url.path])
}
let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
var fileStat = stat()
lstat(entryFileSystemRepresentation, &fileStat)
guard fileStat.st_size >= 0 else {
throw CocoaError(.fileReadTooLarge, userInfo: [NSFilePathErrorKey: url.path])
}
// `st_size` is a signed int value
return Int64(fileStat.st_size)
}
class func typeForItem(at url: URL) throws -> Entry.EntryType {
let fileManager = FileManager()
guard url.isFileURL, fileManager.itemExists(at: url) else {
throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: url.path])
}
let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
var fileStat = stat()
lstat(entryFileSystemRepresentation, &fileStat)
return Entry.EntryType(mode: mode_t(fileStat.st_mode))
}
/// Zips the file or directory contents at the specified source URL to the destination URL.
///
/// If the item at the source URL is a directory, the directory itself will be
/// represented within the ZIP `Archive`. Calling this method with a directory URL
/// `file:///path/directory/` will create an archive with a `directory/` entry at the root level.
/// You can override this behavior by passing `false` for `shouldKeepParent`. In that case, the contents
/// of the source directory will be placed at the root of the archive.
/// - Parameters:
/// - sourceURL: The file URL pointing to an existing file or directory.
/// - destinationURL: The file URL that identifies the destination of the zip operation.
/// - shouldKeepParent: Indicates that the directory name of a source item should be used as root element
/// within the archive. Default is `true`.
/// - compressionMethod: Indicates the `CompressionMethod` that should be applied.
/// By default, `zipItem` will create uncompressed archives.
/// - progress: A progress object that can be used to track or cancel the zip operation.
/// - Throws: Throws an error if the source item does not exist or the destination URL is not writable.
func zipItem(
at sourceURL: URL,
to destinationURL: URL,
shouldKeepParent: Bool = true,
compressionMethod: CompressionMethod = .none,
progress: Progress? = nil)
throws
{
let fileManager = FileManager()
guard fileManager.itemExists(at: sourceURL) else {
throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: sourceURL.path])
}
guard !fileManager.itemExists(at: destinationURL) else {
throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: destinationURL.path])
}
guard let archive = Archive(url: destinationURL, accessMode: .create) else {
throw Archive.ArchiveError.unwritableArchive
}
let isDirectory = try FileManager.typeForItem(at: sourceURL) == .directory
if isDirectory {
let subPaths = try subpathsOfDirectory(atPath: sourceURL.path)
var totalUnitCount = Int64(0)
if let progress {
totalUnitCount = subPaths.reduce(Int64(0)) {
let itemURL = sourceURL.appendingPathComponent($1)
let itemSize = archive.totalUnitCountForAddingItem(at: itemURL)
return $0 + itemSize
}
progress.totalUnitCount = totalUnitCount
}
// If the caller wants to keep the parent directory, we use the lastPathComponent of the source URL
// as common base for all entries (similar to macOS' Archive Utility.app)
let directoryPrefix = sourceURL.lastPathComponent
for entryPath in subPaths {
let finalEntryPath = shouldKeepParent ? directoryPrefix + "/" + entryPath : entryPath
let finalBaseURL = shouldKeepParent ? sourceURL.deletingLastPathComponent() : sourceURL
if let progress {
let itemURL = sourceURL.appendingPathComponent(entryPath)
let entryProgress = archive.makeProgressForAddingItem(at: itemURL)
progress.addChild(entryProgress, withPendingUnitCount: entryProgress.totalUnitCount)
try archive.addEntry(
with: finalEntryPath,
relativeTo: finalBaseURL,
compressionMethod: compressionMethod,
progress: entryProgress)
} else {
try archive.addEntry(
with: finalEntryPath,
relativeTo: finalBaseURL,
compressionMethod: compressionMethod)
}
}
} else {
progress?.totalUnitCount = archive.totalUnitCountForAddingItem(at: sourceURL)
let baseURL = sourceURL.deletingLastPathComponent()
try archive.addEntry(
with: sourceURL.lastPathComponent,
relativeTo: baseURL,
compressionMethod: compressionMethod,
progress: progress)
}
}
/// Unzips the contents at the specified source URL to the destination URL.
///
/// - Parameters:
/// - sourceURL: The file URL pointing to an existing ZIP file.
/// - destinationURL: The file URL that identifies the destination directory of the unzip operation.
/// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance.
/// - progress: A progress object that can be used to track or cancel the unzip operation.
/// - preferredEncoding: Encoding for entry paths. Overrides the encoding specified in the archive.
/// - Throws: Throws an error if the source item does not exist or the destination URL is not writable.
func unzipItem(
at sourceURL: URL,
to destinationURL: URL,
skipCRC32: Bool = false,
progress: Progress? = nil,
preferredEncoding: String.Encoding? = nil)
throws
{
let fileManager = FileManager()
guard fileManager.itemExists(at: sourceURL) else {
throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: sourceURL.path])
}
guard let archive = Archive(url: sourceURL, accessMode: .read, preferredEncoding: preferredEncoding) else {
throw Archive.ArchiveError.unreadableArchive
}
// Defer extraction of symlinks until all files & directories have been created.
// This is necessary because we can't create links to files that haven't been created yet.
let sortedEntries = archive.sorted { left, right -> Bool in
switch (left.type, right.type) {
case (.directory, .file): return true
case (.directory, .symlink): return true
case (.file, .symlink): return true
default: return false
}
}
var totalUnitCount = Int64(0)
if let progress {
totalUnitCount = sortedEntries.reduce(0) { $0 + archive.totalUnitCountForReading($1) }
progress.totalUnitCount = totalUnitCount
}
for entry in sortedEntries {
let path = preferredEncoding == nil ? entry.path : entry.path(using: preferredEncoding!)
let entryURL = destinationURL.appendingPathComponent(path)
guard entryURL.isContained(in: destinationURL) else {
throw CocoaError(
.fileReadInvalidFileName,
userInfo: [NSFilePathErrorKey: entryURL.path])
}
let crc32: CRC32
if let progress {
let entryProgress = archive.makeProgressForReading(entry)
progress.addChild(entryProgress, withPendingUnitCount: entryProgress.totalUnitCount)
crc32 = try archive.extract(entry, to: entryURL, skipCRC32: skipCRC32, progress: entryProgress)
} else {
crc32 = try archive.extract(entry, to: entryURL, skipCRC32: skipCRC32)
}
func verifyChecksumIfNecessary() throws {
if skipCRC32 == false, crc32 != entry.checksum {
throw Archive.ArchiveError.invalidCRC32
}
}
try verifyChecksumIfNecessary()
}
}
// MARK: - Helpers
func itemExists(at url: URL) -> Bool {
// Use `URL.checkResourceIsReachable()` instead of `FileManager.fileExists()` here
// because we don't want implicit symlink resolution.
// As per documentation, `FileManager.fileExists()` traverses symlinks and therefore a broken symlink
// would throw a `.fileReadNoSuchFile` false positive error.
// For ZIP files it may be intended to archive "broken" symlinks because they might be
// resolvable again when extracting the archive to a different destination.
(try? url.checkResourceIsReachable()) == true
}
func createParentDirectoryStructure(for url: URL) throws {
let parentDirectoryURL = url.deletingLastPathComponent()
try createDirectory(at: parentDirectoryURL, withIntermediateDirectories: true, attributes: nil)
}
}
extension Date {
// MARK: Lifecycle
init(dateTime: (UInt16, UInt16)) {
var msdosDateTime = Int(dateTime.0)
msdosDateTime <<= 16
msdosDateTime |= Int(dateTime.1)
var unixTime = tm()
unixTime.tm_sec = Int32((msdosDateTime & 31) * 2)
unixTime.tm_min = Int32((msdosDateTime >> 5) & 63)
unixTime.tm_hour = Int32((Int(dateTime.1) >> 11) & 31)
unixTime.tm_mday = Int32((msdosDateTime >> 16) & 31)
unixTime.tm_mon = Int32((msdosDateTime >> 21) & 15)
unixTime.tm_mon -= 1 // UNIX time struct month entries are zero based.
unixTime.tm_year = Int32(1980 + (msdosDateTime >> 25))
unixTime.tm_year -= 1900 // UNIX time structs count in "years since 1900".
let time = timegm(&unixTime)
self = Date(timeIntervalSince1970: TimeInterval(time))
}
// MARK: Internal
var fileModificationDateTime: (UInt16, UInt16) {
(self.fileModificationDate, self.fileModificationTime)
}
var fileModificationDate: UInt16 {
var time = time_t(timeIntervalSince1970)
guard let unixTime = gmtime(&time) else {
return 0
}
var year = unixTime.pointee.tm_year + 1900 // UNIX time structs count in "years since 1900".
// ZIP uses the MSDOS date format which has a valid range of 1980 - 2099.
year = year >= 1980 ? year : 1980
year = year <= 2099 ? year : 2099
let month = unixTime.pointee.tm_mon + 1 // UNIX time struct month entries are zero based.
let day = unixTime.pointee.tm_mday
return UInt16(day + (month * 32) + ((year - 1980) * 512))
}
var fileModificationTime: UInt16 {
var time = time_t(timeIntervalSince1970)
guard let unixTime = gmtime(&time) else {
return 0
}
let hour = unixTime.pointee.tm_hour
let minute = unixTime.pointee.tm_min
let second = unixTime.pointee.tm_sec
return UInt16((second / 2) + (minute * 32) + (hour * 2048))
}
}
#if swift(>=4.2)
#else
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#else
// The swift-corelibs-foundation version of NSError.swift was missing a convenience method to create
// error objects from error codes. (https://github.com/apple/swift-corelibs-foundation/pull/1420)
// We have to provide an implementation for non-Darwin platforms using Swift versions < 4.2.
extension CocoaError {
static func error(_ code: CocoaError.Code, userInfo: [AnyHashable: Any]? = nil, url: URL? = nil) -> Error {
var info: [String: Any] = userInfo as? [String: Any] ?? [:]
if let url {
info[NSURLErrorKey] = url
}
return NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: info)
}
}
#endif
#endif
extension URL {
func isContained(in parentDirectoryURL: URL) -> Bool {
// Ensure this URL is contained in the passed in URL
let parentDirectoryURL = URL(fileURLWithPath: parentDirectoryURL.path, isDirectory: true).standardized
return standardized.absoluteString.hasPrefix(parentDirectoryURL.absoluteString)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/FileManager+ZIP.swift
|
Swift
|
unknown
| 15,410
|
//
// URL+ZIP.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension URL {
static func temporaryReplacementDirectoryURL(for archive: Archive) -> URL {
#if swift(>=5.0) || os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
if
archive.url.isFileURL,
let tempDir = try? FileManager().url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: archive.url,
create: true)
{
return tempDir
}
#endif
return URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(
ProcessInfo.processInfo.globallyUniqueString)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/ZipFoundation/URL+ZIP.swift
|
Swift
|
unknown
| 867
|
//
// LayerContainer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/22/19.
//
import QuartzCore
// MARK: - CompositionLayer
/// The base class for a child layer of CompositionContainer
class CompositionLayer: CALayer, KeypathSearchable {
// MARK: Lifecycle
init(layer: LayerModel, size: CGSize) {
transformNode = LayerTransformNode(transform: layer.transform)
if let masks = layer.masks?.filter({ $0.mode != .none }), !masks.isEmpty {
maskLayer = MaskContainerLayer(masks: masks)
} else {
maskLayer = nil
}
matteType = layer.matte
inFrame = layer.inFrame.cgFloat
outFrame = layer.outFrame.cgFloat
timeStretch = layer.timeStretch.cgFloat
startFrame = layer.startTime.cgFloat
keypathName = layer.name
childKeypaths = [transformNode.transformProperties]
super.init()
anchorPoint = .zero
actions = [
"opacity" : NSNull(),
"transform" : NSNull(),
"bounds" : NSNull(),
"anchorPoint" : NSNull(),
"sublayerTransform" : NSNull(),
]
contentsLayer.anchorPoint = .zero
contentsLayer.bounds = CGRect(origin: .zero, size: size)
contentsLayer.actions = [
"opacity" : NSNull(),
"transform" : NSNull(),
"bounds" : NSNull(),
"anchorPoint" : NSNull(),
"sublayerTransform" : NSNull(),
"hidden" : NSNull(),
]
compositingFilter = layer.blendMode.filterName
addSublayer(contentsLayer)
if let maskLayer {
contentsLayer.mask = maskLayer
}
name = layer.name
}
override init(layer: Any) {
/// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
guard let layer = layer as? CompositionLayer else {
fatalError("Wrong Layer Class")
}
transformNode = layer.transformNode
matteType = layer.matteType
inFrame = layer.inFrame
outFrame = layer.outFrame
timeStretch = layer.timeStretch
startFrame = layer.startFrame
keypathName = layer.keypathName
childKeypaths = [transformNode.transformProperties]
maskLayer = nil
super.init(layer: layer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
weak var layerDelegate: CompositionLayerDelegate?
let transformNode: LayerTransformNode
let contentsLayer = CALayer()
let maskLayer: MaskContainerLayer?
let matteType: MatteType?
let inFrame: CGFloat
let outFrame: CGFloat
let startFrame: CGFloat
let timeStretch: CGFloat
// MARK: Keypath Searchable
let keypathName: String
final var childKeypaths: [KeypathSearchable]
var renderScale: CGFloat = 1 {
didSet {
updateRenderScale()
}
}
var matteLayer: CompositionLayer? {
didSet {
if let matte = matteLayer {
if let type = matteType, type == .invert {
mask = InvertedMatteLayer(inputMatte: matte)
} else {
mask = matte
}
} else {
mask = nil
}
}
}
var keypathProperties: [String: AnyNodeProperty] {
[:]
}
var keypathLayer: CALayer? {
contentsLayer
}
final func displayWithFrame(frame: CGFloat, forceUpdates: Bool) {
transformNode.updateTree(frame, forceUpdates: forceUpdates)
let layerVisible = frame.isInRangeOrEqual(inFrame, outFrame)
/// Only update contents if current time is within the layers time bounds.
if layerVisible {
displayContentsWithFrame(frame: frame, forceUpdates: forceUpdates)
maskLayer?.updateWithFrame(frame: frame, forceUpdates: forceUpdates)
}
contentsLayer.transform = transformNode.globalTransform
contentsLayer.opacity = transformNode.opacity
contentsLayer.isHidden = !layerVisible
layerDelegate?.frameUpdated(frame: frame)
}
func displayContentsWithFrame(frame _: CGFloat, forceUpdates _: Bool) {
/// To be overridden by subclass
}
func updateRenderScale() {
contentsScale = renderScale
}
}
// MARK: - CompositionLayerDelegate
protocol CompositionLayerDelegate: AnyObject {
func frameUpdated(frame: CGFloat)
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/CompLayers/CompositionLayer.swift
|
Swift
|
unknown
| 4,137
|
//
// ImageCompositionLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import QuartzCore
final class ImageCompositionLayer: CompositionLayer {
// MARK: Lifecycle
init(imageLayer: ImageLayerModel, size: CGSize) {
imageReferenceID = imageLayer.referenceID
super.init(layer: imageLayer, size: size)
contentsLayer.masksToBounds = true
contentsLayer.contentsGravity = CALayerContentsGravity.resize
}
override init(layer: Any) {
/// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
guard let layer = layer as? ImageCompositionLayer else {
fatalError("init(layer:) Wrong Layer Class")
}
imageReferenceID = layer.imageReferenceID
image = nil
super.init(layer: layer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
let imageReferenceID: String
var image: CGImage? = nil {
didSet {
if let image {
contentsLayer.contents = image
} else {
contentsLayer.contents = nil
}
}
}
var imageContentsGravity: CALayerContentsGravity = .resize {
didSet {
contentsLayer.contentsGravity = imageContentsGravity
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/CompLayers/ImageCompositionLayer.swift
|
Swift
|
unknown
| 1,305
|
//
// MaskContainerLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import QuartzCore
extension MaskMode {
var usableMode: MaskMode {
switch self {
case .add:
return .add
case .subtract:
return .subtract
case .intersect:
return .intersect
case .lighten:
return .add
case .darken:
return .darken
case .difference:
return .intersect
case .none:
return .none
}
}
}
// MARK: - MaskContainerLayer
final class MaskContainerLayer: CALayer {
// MARK: Lifecycle
init(masks: [Mask]) {
super.init()
anchorPoint = .zero
var containerLayer = CALayer()
var firstObject = true
for mask in masks {
let maskLayer = MaskLayer(mask: mask)
maskLayers.append(maskLayer)
if mask.mode.usableMode == .none {
continue
} else if mask.mode.usableMode == .add || firstObject {
firstObject = false
containerLayer.addSublayer(maskLayer)
} else {
containerLayer.mask = maskLayer
let newContainer = CALayer()
newContainer.addSublayer(containerLayer)
containerLayer = newContainer
}
}
addSublayer(containerLayer)
}
override init(layer: Any) {
/// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
guard let layer = layer as? MaskContainerLayer else {
fatalError("init(layer:) Wrong Layer Class")
}
super.init(layer: layer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
func updateWithFrame(frame: CGFloat, forceUpdates: Bool) {
for maskLayer in maskLayers {
maskLayer.updateWithFrame(frame: frame, forceUpdates: forceUpdates)
}
}
// MARK: Fileprivate
fileprivate var maskLayers: [MaskLayer] = []
}
extension CGRect {
static var veryLargeRect: CGRect {
CGRect(
x: -10_000_000,
y: -10_000_000,
width: 20_000_000,
height: 20_000_000)
}
}
// MARK: - MaskLayer
private class MaskLayer: CALayer {
// MARK: Lifecycle
init(mask: Mask) {
properties = MaskNodeProperties(mask: mask)
super.init()
addSublayer(maskLayer)
anchorPoint = .zero
maskLayer.fillColor = mask.mode == .add
? .rgb(1, 0, 0)
: .rgb(0, 1, 0)
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
actions = [
"opacity" : NSNull(),
]
}
override init(layer: Any) {
properties = nil
super.init(layer: layer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
let properties: MaskNodeProperties?
let maskLayer = CAShapeLayer()
func updateWithFrame(frame: CGFloat, forceUpdates: Bool) {
guard let properties else { return }
if properties.opacity.needsUpdate(frame: frame) || forceUpdates {
properties.opacity.update(frame: frame)
opacity = Float(properties.opacity.value.cgFloatValue)
}
if properties.shape.needsUpdate(frame: frame) || forceUpdates {
properties.shape.update(frame: frame)
properties.expansion.update(frame: frame)
let shapePath = properties.shape.value.cgPath()
var path = shapePath
if
properties.mode.usableMode == .subtract && !properties.inverted ||
(properties.mode.usableMode == .add && properties.inverted)
{
/// Add a bounds rect to invert the mask
let newPath = CGMutablePath()
newPath.addRect(CGRect.veryLargeRect)
newPath.addPath(shapePath)
path = newPath
}
maskLayer.path = path
}
}
}
// MARK: - MaskNodeProperties
private class MaskNodeProperties: NodePropertyMap {
// MARK: Lifecycle
init(mask: Mask) {
mode = mask.mode
inverted = mask.inverted
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: mask.opacity.keyframes))
shape = NodeProperty(provider: KeyframeInterpolator(keyframes: mask.shape.keyframes))
expansion = NodeProperty(provider: KeyframeInterpolator(keyframes: mask.expansion.keyframes))
propertyMap = [
PropertyName.opacity.rawValue : opacity,
"Shape" : shape,
"Expansion" : expansion,
]
properties = Array(propertyMap.values)
}
// MARK: Internal
var propertyMap: [String: AnyNodeProperty]
var properties: [AnyNodeProperty]
let mode: MaskMode
let inverted: Bool
let opacity: NodeProperty<LottieVector1D>
let shape: NodeProperty<BezierPath>
let expansion: NodeProperty<LottieVector1D>
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/CompLayers/MaskContainerLayer.swift
|
Swift
|
unknown
| 4,616
|
//
// NullCompositionLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import Foundation
final class NullCompositionLayer: CompositionLayer {
init(layer: LayerModel) {
super.init(layer: layer, size: .zero)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(layer: Any) {
/// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
guard let layer = layer as? NullCompositionLayer else {
fatalError("init(layer:) Wrong Layer Class")
}
super.init(layer: layer)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/CompLayers/NullCompositionLayer.swift
|
Swift
|
unknown
| 667
|
//
// PreCompositionLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import QuartzCore
final class PreCompositionLayer: CompositionLayer {
// MARK: Lifecycle
init(
precomp: PreCompLayerModel,
asset: PrecompAsset,
layerImageProvider: LayerImageProvider,
layerTextProvider: LayerTextProvider,
textProvider: AnimationKeypathTextProvider,
fontProvider: AnimationFontProvider,
assetLibrary: AssetLibrary?,
frameRate: CGFloat,
rootAnimationLayer: MainThreadAnimationLayer?)
{
animationLayers = []
if let keyframes = precomp.timeRemapping?.keyframes {
remappingNode = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframes))
} else {
remappingNode = nil
}
self.frameRate = frameRate
super.init(layer: precomp, size: CGSize(width: precomp.width, height: precomp.height))
bounds = CGRect(origin: .zero, size: CGSize(width: precomp.width, height: precomp.height))
contentsLayer.masksToBounds = true
contentsLayer.bounds = bounds
let layers = asset.layers.initializeCompositionLayers(
assetLibrary: assetLibrary,
layerImageProvider: layerImageProvider,
layerTextProvider: layerTextProvider,
textProvider: textProvider,
fontProvider: fontProvider,
frameRate: frameRate,
rootAnimationLayer: rootAnimationLayer)
var imageLayers = [ImageCompositionLayer]()
var textLayers = [TextCompositionLayer]()
var mattedLayer: CompositionLayer? = nil
for layer in layers.reversed() {
layer.bounds = bounds
animationLayers.append(layer)
if let imageLayer = layer as? ImageCompositionLayer {
imageLayers.append(imageLayer)
}
if let textLayer = layer as? TextCompositionLayer {
textLayers.append(textLayer)
}
if let matte = mattedLayer {
/// The previous layer requires this layer to be its matte
matte.matteLayer = layer
mattedLayer = nil
continue
}
if
let matte = layer.matteType,
matte == .add || matte == .invert
{
/// We have a layer that requires a matte.
mattedLayer = layer
}
contentsLayer.addSublayer(layer)
}
childKeypaths.append(contentsOf: layers)
layerImageProvider.addImageLayers(imageLayers)
layerTextProvider.addTextLayers(textLayers)
}
override init(layer: Any) {
/// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
guard let layer = layer as? PreCompositionLayer else {
fatalError("init(layer:) Wrong Layer Class")
}
frameRate = layer.frameRate
remappingNode = nil
animationLayers = []
super.init(layer: layer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
let frameRate: CGFloat
let remappingNode: NodeProperty<LottieVector1D>?
override var keypathProperties: [String: AnyNodeProperty] {
guard let remappingNode else {
return super.keypathProperties
}
return ["Time Remap" : remappingNode]
}
override func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) {
let localFrame: CGFloat
if let remappingNode {
remappingNode.update(frame: frame)
localFrame = remappingNode.value.cgFloatValue * frameRate
} else {
localFrame = (frame - startFrame) / timeStretch
}
for animationLayer in animationLayers {
animationLayer.displayWithFrame(frame: localFrame, forceUpdates: forceUpdates)
}
}
override func updateRenderScale() {
super.updateRenderScale()
for animationLayer in animationLayers {
animationLayer.renderScale = renderScale
}
}
// MARK: Fileprivate
fileprivate var animationLayers: [CompositionLayer]
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/CompLayers/PreCompositionLayer.swift
|
Swift
|
unknown
| 3,881
|
//
// ShapeLayerContainer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/22/19.
//
import CoreGraphics
import Foundation
/// A CompositionLayer responsible for initializing and rendering shapes
final class ShapeCompositionLayer: CompositionLayer {
// MARK: Lifecycle
init(shapeLayer: ShapeLayerModel) {
let results = shapeLayer.items.initializeNodeTree()
let renderContainer = ShapeContainerLayer()
self.renderContainer = renderContainer
rootNode = results.rootNode
super.init(layer: shapeLayer, size: .zero)
contentsLayer.addSublayer(renderContainer)
for container in results.renderContainers {
renderContainer.insertRenderLayer(container)
}
rootNode?.updateTree(0, forceUpdates: true)
childKeypaths.append(contentsOf: results.childrenNodes)
}
override init(layer: Any) {
guard let layer = layer as? ShapeCompositionLayer else {
fatalError("init(layer:) wrong class.")
}
rootNode = nil
renderContainer = nil
super.init(layer: layer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
let rootNode: AnimatorNode?
let renderContainer: ShapeContainerLayer?
override func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) {
rootNode?.updateTree(frame, forceUpdates: forceUpdates)
renderContainer?.markRenderUpdates(forFrame: frame)
}
override func updateRenderScale() {
super.updateRenderScale()
renderContainer?.renderScale = renderScale
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/CompLayers/ShapeCompositionLayer.swift
|
Swift
|
unknown
| 1,556
|
//
// SolidCompositionLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import QuartzCore
final class SolidCompositionLayer: CompositionLayer {
// MARK: Lifecycle
init(solid: SolidLayerModel) {
let components = solid.colorHex.hexColorComponents()
colorProperty =
NodeProperty(provider: SingleValueProvider(LottieColor(
r: Double(components.red),
g: Double(components.green),
b: Double(components.blue),
a: 1)))
super.init(layer: solid, size: .zero)
solidShape.path = CGPath(rect: CGRect(x: 0, y: 0, width: solid.width, height: solid.height), transform: nil)
contentsLayer.addSublayer(solidShape)
}
override init(layer: Any) {
/// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
guard let layer = layer as? SolidCompositionLayer else {
fatalError("init(layer:) Wrong Layer Class")
}
colorProperty = layer.colorProperty
super.init(layer: layer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
let colorProperty: NodeProperty<LottieColor>?
let solidShape = CAShapeLayer()
override var keypathProperties: [String: AnyNodeProperty] {
guard let colorProperty else { return super.keypathProperties }
return [PropertyName.color.rawValue : colorProperty]
}
override func displayContentsWithFrame(frame: CGFloat, forceUpdates _: Bool) {
guard let colorProperty else { return }
colorProperty.update(frame: frame)
solidShape.fillColor = colorProperty.value.cgColorValue
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/CompLayers/SolidCompositionLayer.swift
|
Swift
|
unknown
| 1,680
|
//
// TextCompositionLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
/// Needed for NSMutableParagraphStyle...
#if os(OSX)
import AppKit
#else
import UIKit
#endif
extension TextJustification {
var textAlignment: NSTextAlignment {
switch self {
case .left:
return .left
case .right:
return .right
case .center:
return .center
}
}
var caTextAlignement: CATextLayerAlignmentMode {
switch self {
case .left:
return .left
case .right:
return .right
case .center:
return .center
}
}
}
// MARK: - TextCompositionLayer
final class TextCompositionLayer: CompositionLayer {
// MARK: Lifecycle
init(
textLayer: TextLayerModel,
textProvider: AnimationKeypathTextProvider,
fontProvider: AnimationFontProvider,
rootAnimationLayer: MainThreadAnimationLayer?)
{
var rootNode: TextAnimatorNode?
for animator in textLayer.animators {
rootNode = TextAnimatorNode(parentNode: rootNode, textAnimator: animator)
}
self.rootNode = rootNode
textDocument = KeyframeInterpolator(keyframes: textLayer.text.keyframes)
self.textProvider = textProvider
self.fontProvider = fontProvider
self.rootAnimationLayer = rootAnimationLayer
super.init(layer: textLayer, size: .zero)
contentsLayer.addSublayer(self.textLayer)
self.textLayer.masksToBounds = false
self.textLayer.isGeometryFlipped = true
if let rootNode {
childKeypaths.append(rootNode)
}
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(layer: Any) {
/// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
guard let layer = layer as? TextCompositionLayer else {
fatalError("init(layer:) Wrong Layer Class")
}
rootNode = nil
textDocument = nil
textProvider = DefaultTextProvider()
fontProvider = DefaultFontProvider()
super.init(layer: layer)
}
// MARK: Internal
let rootNode: TextAnimatorNode?
let textDocument: KeyframeInterpolator<TextDocument>?
let textLayer = CoreTextRenderLayer()
var textProvider: AnimationKeypathTextProvider
var fontProvider: AnimationFontProvider
weak var rootAnimationLayer: MainThreadAnimationLayer?
lazy var fullAnimationKeypath: AnimationKeypath = // Individual layers don't know their full keypaths, so we have to delegate
// to the `MainThreadAnimationLayer` to search the layer hierarchy and find
// the full keypath (which includes this layer's parent layers)
rootAnimationLayer?.keypath(for: self)
// If that failed for some reason, just use the last path component (which we do have here)
?? AnimationKeypath(keypath: keypathName)
override func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) {
guard let textDocument else { return }
textLayer.contentsScale = renderScale
let documentUpdate = textDocument.hasUpdate(frame: frame)
let animatorUpdate = rootNode?.updateContents(frame, forceLocalUpdate: forceUpdates) ?? false
guard documentUpdate == true || animatorUpdate == true else { return }
rootNode?.rebuildOutputs(frame: frame)
// Get Text Attributes
let text = textDocument.value(frame: frame) as! TextDocument
// Prior to Lottie 4.3.0 the Main Thread rendering engine always just used `LegacyAnimationTextProvider`
// and called it with the `keypathName` (only the last path component of the full keypath).
// Starting in Lottie 4.3.0 we use `AnimationKeypathTextProvider` instead if implemented.
let textString: String
if let keypathTextValue = textProvider.text(for: fullAnimationKeypath, sourceText: text.text) {
textString = keypathTextValue
} else if let legacyTextProvider = textProvider as? LegacyAnimationTextProvider {
textString = legacyTextProvider.textFor(keypathName: keypathName, sourceText: text.text)
} else {
textString = text.text
}
let strokeColor = rootNode?.textOutputNode.strokeColor ?? text.strokeColorData?.cgColorValue
let strokeWidth = rootNode?.textOutputNode.strokeWidth ?? CGFloat(text.strokeWidth ?? 0)
let tracking = (CGFloat(text.fontSize) * (rootNode?.textOutputNode.tracking ?? CGFloat(text.tracking))) / 1000.0
let matrix = rootNode?.textOutputNode.xform ?? CATransform3DIdentity
let ctFont = fontProvider.fontFor(family: text.fontFamily, size: CGFloat(text.fontSize))
// Set all of the text layer options
textLayer.text = textString
textLayer.font = ctFont
textLayer.alignment = text.justification.textAlignment
textLayer.lineHeight = CGFloat(text.lineHeight)
textLayer.tracking = tracking
if let fillColor = rootNode?.textOutputNode.fillColor {
textLayer.fillColor = fillColor
} else if let fillColor = text.fillColorData?.cgColorValue {
textLayer.fillColor = fillColor
} else {
textLayer.fillColor = nil
}
textLayer.preferredSize = text.textFrameSize?.sizeValue
textLayer.strokeOnTop = text.strokeOverFill ?? false
textLayer.strokeWidth = strokeWidth
textLayer.strokeColor = strokeColor
textLayer.sizeToFit()
textLayer.opacity = Float(rootNode?.textOutputNode.opacity ?? 1)
textLayer.transform = CATransform3DIdentity
textLayer.position = text.textFramePosition?.pointValue ?? CGPoint.zero
textLayer.transform = matrix
}
override func updateRenderScale() {
super.updateRenderScale()
textLayer.contentsScale = renderScale
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/CompLayers/TextCompositionLayer.swift
|
Swift
|
unknown
| 5,614
|
//
// MainThreadAnimationLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/24/19.
//
import QuartzCore
// MARK: - MainThreadAnimationLayer
/// The base `CALayer` for the Main Thread rendering engine
///
/// This layer holds a single composition container and allows for animation of
/// the currentFrame property.
final class MainThreadAnimationLayer: CALayer, RootAnimationLayer {
// MARK: Lifecycle
init(
animation: LottieAnimation,
imageProvider: AnimationImageProvider,
textProvider: AnimationKeypathTextProvider,
fontProvider: AnimationFontProvider,
maskAnimationToBounds: Bool,
logger: LottieLogger)
{
layerImageProvider = LayerImageProvider(imageProvider: imageProvider, assets: animation.assetLibrary?.imageAssets)
layerTextProvider = LayerTextProvider(textProvider: textProvider)
layerFontProvider = LayerFontProvider(fontProvider: fontProvider)
animationLayers = []
self.logger = logger
super.init()
masksToBounds = maskAnimationToBounds
bounds = animation.bounds
let layers = animation.layers.initializeCompositionLayers(
assetLibrary: animation.assetLibrary,
layerImageProvider: layerImageProvider,
layerTextProvider: layerTextProvider,
textProvider: textProvider,
fontProvider: fontProvider,
frameRate: CGFloat(animation.framerate),
rootAnimationLayer: self)
var imageLayers = [ImageCompositionLayer]()
var textLayers = [TextCompositionLayer]()
var mattedLayer: CompositionLayer? = nil
for layer in layers.reversed() {
layer.bounds = bounds
animationLayers.append(layer)
if let imageLayer = layer as? ImageCompositionLayer {
imageLayers.append(imageLayer)
}
if let textLayer = layer as? TextCompositionLayer {
textLayers.append(textLayer)
}
if let matte = mattedLayer {
/// The previous layer requires this layer to be its matte
matte.matteLayer = layer
mattedLayer = nil
continue
}
if
let matte = layer.matteType,
matte == .add || matte == .invert
{
/// We have a layer that requires a matte.
mattedLayer = layer
}
addSublayer(layer)
}
layerImageProvider.addImageLayers(imageLayers)
layerImageProvider.reloadImages()
layerTextProvider.addTextLayers(textLayers)
layerTextProvider.reloadTexts()
layerFontProvider.addTextLayers(textLayers)
layerFontProvider.reloadTexts()
setNeedsDisplay()
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
animationLayers = []
layerImageProvider = LayerImageProvider(imageProvider: BlankImageProvider(), assets: nil)
layerTextProvider = LayerTextProvider(textProvider: DefaultTextProvider())
layerFontProvider = LayerFontProvider(fontProvider: DefaultFontProvider())
logger = typedLayer.logger
super.init(layer: layer)
currentFrame = typedLayer.currentFrame
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Public
public var respectAnimationFrameRate = false
// MARK: CALayer Animations
override public class func needsDisplay(forKey key: String) -> Bool {
if key == "currentFrame" {
return true
}
return super.needsDisplay(forKey: key)
}
override public func action(forKey event: String) -> CAAction? {
if event == "currentFrame" {
let animation = CABasicAnimation(keyPath: event)
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.fromValue = presentation()?.currentFrame
return animation
}
return super.action(forKey: event)
}
public override func display() {
guard Thread.isMainThread else { return }
var newFrame: CGFloat
if
let animationKeys = animationKeys(),
!animationKeys.isEmpty
{
newFrame = presentation()?.currentFrame ?? currentFrame
} else {
// We ignore the presentation's frame if there's no animation in the layer.
newFrame = currentFrame
}
if respectAnimationFrameRate {
newFrame = floor(newFrame)
}
for animationLayer in animationLayers {
animationLayer.displayWithFrame(frame: newFrame, forceUpdates: forceDisplayUpdateOnEachFrame)
}
}
// MARK: Internal
/// The animatable Current Frame Property
@NSManaged var currentFrame: CGFloat
/// The parent `LottieAnimationLayer` that manages this layer
weak var lottieAnimationLayer: LottieAnimationLayer?
/// Whether or not to use `forceDisplayUpdate()` when rendering each individual frame.
/// - The main thread rendering engine implements optimizations to decrease the amount
/// of properties that have to be re-rendered on each frame. There are some cases
/// where this can result in bugs / incorrect behavior, so we allow it to be disabled.
/// - Forcing a full render on every frame will decrease performance, and is not recommended
/// except as a workaround to a bug in the main thread rendering engine.
var forceDisplayUpdateOnEachFrame = false
var animationLayers: ContiguousArray<CompositionLayer>
var primaryAnimationKey: AnimationKey {
.managed
}
var isAnimationPlaying: Bool? {
nil // this state is managed by `LottieAnimationView`
}
var _animationLayers: [CALayer] {
Array(animationLayers)
}
var imageProvider: AnimationImageProvider {
get {
layerImageProvider.imageProvider
}
set {
layerImageProvider.imageProvider = newValue
}
}
var renderScale: CGFloat = 1 {
didSet {
for animationLayer in animationLayers {
animationLayer.renderScale = renderScale
}
}
}
var textProvider: AnimationKeypathTextProvider {
get { layerTextProvider.textProvider }
set { layerTextProvider.textProvider = newValue }
}
var fontProvider: AnimationFontProvider {
get { layerFontProvider.fontProvider }
set { layerFontProvider.fontProvider = newValue }
}
func reloadImages() {
layerImageProvider.reloadImages()
}
func removeAnimations() {
// no-op, since the primary animation is managed by the `LottieAnimationView`.
}
/// Forces the view to update its drawing.
func forceDisplayUpdate() {
for animationLayer in animationLayers {
animationLayer.displayWithFrame(frame: currentFrame, forceUpdates: true)
}
}
func logHierarchyKeypaths() {
logger.info("Lottie: Logging Animation Keypaths")
for keypath in allHierarchyKeypaths() {
logger.info(keypath)
}
}
func allHierarchyKeypaths() -> [String] {
animationLayers.flatMap { $0.allKeypaths() }
}
func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) {
for layer in animationLayers {
if let foundProperties = layer.nodeProperties(for: keypath) {
for property in foundProperties {
property.setProvider(provider: valueProvider)
}
layer.displayWithFrame(frame: presentation()?.currentFrame ?? currentFrame, forceUpdates: true)
}
}
}
func getValue(for keypath: AnimationKeypath, atFrame: CGFloat?) -> Any? {
for layer in animationLayers {
if
let foundProperties = layer.nodeProperties(for: keypath),
let first = foundProperties.first
{
return first.valueProvider.value(frame: atFrame ?? currentFrame)
}
}
return nil
}
func getOriginalValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any? {
for layer in animationLayers {
if
let foundProperties = layer.nodeProperties(for: keypath),
let first = foundProperties.first
{
return first.originalValueProvider.value(frame: atFrame ?? currentFrame)
}
}
return nil
}
func layer(for keypath: AnimationKeypath) -> CALayer? {
for layer in animationLayers {
if let foundLayer = layer.layer(for: keypath) {
return foundLayer
}
}
return nil
}
func keypath(for layerToFind: CALayer) -> AnimationKeypath? {
for layer in animationLayers {
if let foundKeypath = layer.keypath(for: layerToFind) {
return foundKeypath
}
}
return nil
}
func animatorNodes(for keypath: AnimationKeypath) -> [AnimatorNode]? {
var results = [AnimatorNode]()
for layer in animationLayers {
if let nodes = layer.animatorNodes(for: keypath) {
results.append(contentsOf: nodes)
}
}
if results.count == 0 {
return nil
}
return results
}
// MARK: Fileprivate
fileprivate let layerImageProvider: LayerImageProvider
fileprivate let layerTextProvider: LayerTextProvider
fileprivate let layerFontProvider: LayerFontProvider
fileprivate let logger: LottieLogger
}
// MARK: - BlankImageProvider
private class BlankImageProvider: AnimationImageProvider {
func imageForAsset(asset _: ImageAsset) -> CGImage? {
nil
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/MainThreadAnimationLayer.swift
|
Swift
|
unknown
| 9,294
|
// Created by Jianjun Wu on 2022/5/12.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - CachedImageProvider
private final class CachedImageProvider: AnimationImageProvider {
// MARK: Lifecycle
/// Initializes an image provider with an image provider
///
/// - Parameter imageProvider: The provider to load image from asset
///
public init(imageProvider: AnimationImageProvider) {
self.imageProvider = imageProvider
}
// MARK: Public
public func imageForAsset(asset: ImageAsset) -> CGImage? {
if let image = imageCache.value(forKey: asset.id) {
return image
}
if let image = imageProvider.imageForAsset(asset: asset) {
imageCache.setValue(image, forKey: asset.id)
return image
}
return nil
}
// MARK: Internal
func contentsGravity(for asset: ImageAsset) -> CALayerContentsGravity {
imageProvider.contentsGravity(for: asset)
}
// MARK: Private
/// The underlying storage of this cache.
/// - We use the `LRUCache` library instead of `NSCache`, because `NSCache`
/// clears all cached values when the app is backgrounded instead of
/// only when the app receives a memory warning notification.
private var imageCache = LRUCache<String, CGImage>()
private let imageProvider: AnimationImageProvider
}
extension AnimationImageProvider {
/// Create a cache enabled image provider which will reuse the asset image with the same asset id
/// It wraps the current provider as image loader, and uses `NSCache` to cache the images for resue.
/// The cache will be reset when the `animation` is reset.
var cachedImageProvider: AnimationImageProvider {
guard cacheEligible else { return self }
return CachedImageProvider(imageProvider: self)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/Utility/CachedImageProvider.swift
|
Swift
|
unknown
| 1,790
|
//
// CompositionLayersInitializer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import CoreGraphics
import Foundation
extension [LayerModel] {
func initializeCompositionLayers(
assetLibrary: AssetLibrary?,
layerImageProvider: LayerImageProvider,
layerTextProvider: LayerTextProvider,
textProvider: AnimationKeypathTextProvider,
fontProvider: AnimationFontProvider,
frameRate: CGFloat,
rootAnimationLayer: MainThreadAnimationLayer?)
-> [CompositionLayer]
{
var compositionLayers = [CompositionLayer]()
var layerMap = [Int : CompositionLayer]()
/// Organize the assets into a dictionary of [ID : ImageAsset]
var childLayers = [LayerModel]()
for layer in self {
if layer.hidden == true {
let genericLayer = NullCompositionLayer(layer: layer)
compositionLayers.append(genericLayer)
layerMap[layer.index] = genericLayer
} else if let shapeLayer = layer as? ShapeLayerModel {
let shapeContainer = ShapeCompositionLayer(shapeLayer: shapeLayer)
compositionLayers.append(shapeContainer)
layerMap[layer.index] = shapeContainer
} else if let solidLayer = layer as? SolidLayerModel {
let solidContainer = SolidCompositionLayer(solid: solidLayer)
compositionLayers.append(solidContainer)
layerMap[layer.index] = solidContainer
} else if
let precompLayer = layer as? PreCompLayerModel,
let assetLibrary,
let precompAsset = assetLibrary.precompAssets[precompLayer.referenceID]
{
let precompContainer = PreCompositionLayer(
precomp: precompLayer,
asset: precompAsset,
layerImageProvider: layerImageProvider,
layerTextProvider: layerTextProvider,
textProvider: textProvider,
fontProvider: fontProvider,
assetLibrary: assetLibrary,
frameRate: frameRate,
rootAnimationLayer: rootAnimationLayer)
compositionLayers.append(precompContainer)
layerMap[layer.index] = precompContainer
} else if
let imageLayer = layer as? ImageLayerModel,
let assetLibrary,
let imageAsset = assetLibrary.imageAssets[imageLayer.referenceID]
{
let imageContainer = ImageCompositionLayer(
imageLayer: imageLayer,
size: CGSize(width: imageAsset.width, height: imageAsset.height))
compositionLayers.append(imageContainer)
layerMap[layer.index] = imageContainer
} else if let textLayer = layer as? TextLayerModel {
let textContainer = TextCompositionLayer(
textLayer: textLayer,
textProvider: textProvider,
fontProvider: fontProvider,
rootAnimationLayer: rootAnimationLayer)
compositionLayers.append(textContainer)
layerMap[layer.index] = textContainer
} else {
let genericLayer = NullCompositionLayer(layer: layer)
compositionLayers.append(genericLayer)
layerMap[layer.index] = genericLayer
}
if layer.parent != nil {
childLayers.append(layer)
}
}
/// Now link children with their parents
for layerModel in childLayers {
if let parentID = layerModel.parent {
let childLayer = layerMap[layerModel.index]
let parentLayer = layerMap[parentID]
childLayer?.transformNode.parentNode = parentLayer?.transformNode
}
}
return compositionLayers
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/Utility/CompositionLayersInitializer.swift
|
Swift
|
unknown
| 3,488
|
//
// TextLayer.swift
// Pods
//
// Created by Brandon Withrow on 8/3/20.
//
import CoreGraphics
import CoreText
import Foundation
import QuartzCore
/// Needed for NSMutableParagraphStyle...
#if os(OSX)
import AppKit
#else
import UIKit
#endif
// MARK: - CoreTextRenderLayer
/// A CALayer subclass that renders text content using CoreText
final class CoreTextRenderLayer: CALayer {
// MARK: Public
public var text: String? {
didSet {
needsContentUpdate = true
setNeedsLayout()
setNeedsDisplay()
}
}
public var font: CTFont? {
didSet {
needsContentUpdate = true
setNeedsLayout()
setNeedsDisplay()
}
}
public var alignment: NSTextAlignment = .left {
didSet {
needsContentUpdate = true
setNeedsLayout()
setNeedsDisplay()
}
}
public var lineHeight: CGFloat = 0 {
didSet {
needsContentUpdate = true
setNeedsLayout()
setNeedsDisplay()
}
}
public var tracking: CGFloat = 0 {
didSet {
needsContentUpdate = true
setNeedsLayout()
setNeedsDisplay()
}
}
public var fillColor: CGColor? {
didSet {
needsContentUpdate = true
setNeedsLayout()
setNeedsDisplay()
}
}
public var strokeColor: CGColor? {
didSet {
needsContentUpdate = true
setNeedsLayout()
setNeedsDisplay()
}
}
public var strokeWidth: CGFloat = 0 {
didSet {
needsContentUpdate = true
setNeedsLayout()
setNeedsDisplay()
}
}
public var strokeOnTop = false {
didSet {
setNeedsLayout()
setNeedsDisplay()
}
}
public var preferredSize: CGSize? {
didSet {
needsContentUpdate = true
setNeedsLayout()
setNeedsDisplay()
}
}
public func sizeToFit() {
updateTextContent()
bounds = drawingRect
anchorPoint = drawingAnchor
setNeedsLayout()
setNeedsDisplay()
}
// MARK: Internal
override func action(forKey _: String) -> CAAction? {
nil
}
override func draw(in ctx: CGContext) {
guard let attributedString else { return }
updateTextContent()
guard fillFrameSetter != nil || strokeFrameSetter != nil else { return }
ctx.textMatrix = .identity
ctx.setAllowsAntialiasing(true)
ctx.setAllowsFontSubpixelPositioning(true)
ctx.setAllowsFontSubpixelQuantization(true)
ctx.setShouldAntialias(true)
ctx.setShouldSubpixelPositionFonts(true)
ctx.setShouldSubpixelQuantizeFonts(true)
if contentsAreFlipped() {
ctx.translateBy(x: 0, y: drawingRect.height)
ctx.scaleBy(x: 1.0, y: -1.0)
}
let drawingPath = CGPath(rect: drawingRect, transform: nil)
let fillFrame: CTFrame?
if let setter = fillFrameSetter {
fillFrame = CTFramesetterCreateFrame(setter, CFRangeMake(0, attributedString.length), drawingPath, nil)
} else {
fillFrame = nil
}
let strokeFrame: CTFrame?
if let setter = strokeFrameSetter {
strokeFrame = CTFramesetterCreateFrame(setter, CFRangeMake(0, attributedString.length), drawingPath, nil)
} else {
strokeFrame = nil
}
// This fixes a vertical padding issue that arises when drawing some fonts.
// For some reason some fonts, such as Helvetica draw with and ascender that is greater than the one reported by CTFontGetAscender.
// I suspect this is actually an issue with the Attributed string, but cannot reproduce.
if let fillFrame {
ctx.adjustWithLineOrigins(in: fillFrame, with: font)
} else if let strokeFrame {
ctx.adjustWithLineOrigins(in: strokeFrame, with: font)
}
if !strokeOnTop, let strokeFrame {
CTFrameDraw(strokeFrame, ctx)
}
if let fillFrame {
CTFrameDraw(fillFrame, ctx)
}
if strokeOnTop, let strokeFrame {
CTFrameDraw(strokeFrame, ctx)
}
}
// MARK: Private
private var drawingRect: CGRect = .zero
private var drawingAnchor: CGPoint = .zero
private var fillFrameSetter: CTFramesetter?
private var attributedString: NSAttributedString?
private var strokeFrameSetter: CTFramesetter?
private var needsContentUpdate = false
// Draws Debug colors for the font alignment.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
private func drawDebug(_ ctx: CGContext) {
if let font {
let ascent = CTFontGetAscent(font)
let descent = CTFontGetDescent(font)
let capHeight = CTFontGetCapHeight(font)
let leading = CTFontGetLeading(font)
// Ascent Red
ctx.setFillColor(CGColor(srgbRed: 1, green: 0, blue: 0, alpha: 0.5))
ctx.fill(CGRect(x: 0, y: 0, width: drawingRect.width, height: ascent))
// Descent Blue
ctx.setFillColor(CGColor(srgbRed: 0, green: 0, blue: 1, alpha: 0.5))
ctx.fill(CGRect(x: 0, y: ascent, width: drawingRect.width, height: descent))
// Leading Yellow
ctx.setFillColor(CGColor(srgbRed: 1, green: 1, blue: 0, alpha: 0.5))
ctx.fill(CGRect(x: 0, y: ascent + descent, width: drawingRect.width, height: leading))
// Cap height Green
ctx.setFillColor(CGColor(srgbRed: 0, green: 1, blue: 0, alpha: 0.5))
ctx.fill(CGRect(x: 0, y: ascent - capHeight, width: drawingRect.width, height: capHeight))
if drawingRect.height - ascent + descent + leading > 0 {
// Remainder
ctx.setFillColor(CGColor(srgbRed: 0, green: 1, blue: 1, alpha: 0.5))
ctx
.fill(CGRect(
x: 0,
y: ascent + descent + leading,
width: drawingRect.width,
height: drawingRect.height - ascent + descent + leading))
}
}
}
private func updateTextContent() {
guard needsContentUpdate else { return }
needsContentUpdate = false
guard let font, let text, text.count > 0, fillColor != nil || strokeColor != nil else {
drawingRect = .zero
drawingAnchor = .zero
attributedString = nil
fillFrameSetter = nil
strokeFrameSetter = nil
return
}
// Get Font properties
let ascent = CTFontGetAscent(font)
let descent = CTFontGetDescent(font)
let capHeight = CTFontGetCapHeight(font)
let leading = CTFontGetLeading(font)
let minLineHeight = -(ascent + descent + leading)
// Calculate line spacing
let lineSpacing = max(CGFloat(minLineHeight) + lineHeight, CGFloat(minLineHeight))
// Build Attributes
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = 1
paragraphStyle.maximumLineHeight = ascent + descent + leading
paragraphStyle.alignment = alignment
paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
var attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.ligature: 0,
NSAttributedString.Key.font: font,
NSAttributedString.Key.kern: tracking,
NSAttributedString.Key.paragraphStyle: paragraphStyle,
]
if let fillColor {
attributes[NSAttributedString.Key.foregroundColor] = fillColor
}
let attrString = NSAttributedString(string: text, attributes: attributes)
attributedString = attrString
if fillColor != nil {
let setter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)
fillFrameSetter = setter
} else {
fillFrameSetter = nil
}
if let strokeColor {
attributes[NSAttributedString.Key.foregroundColor] = nil
attributes[NSAttributedString.Key.strokeWidth] = strokeWidth
attributes[NSAttributedString.Key.strokeColor] = strokeColor
let strokeAttributedString = NSAttributedString(string: text, attributes: attributes)
strokeFrameSetter = CTFramesetterCreateWithAttributedString(strokeAttributedString as CFAttributedString)
} else {
strokeFrameSetter = nil
strokeWidth = 0
}
guard let setter = fillFrameSetter ?? strokeFrameSetter else {
return
}
// Calculate drawing size and anchor offset
let textAnchor: CGPoint
if let preferredSize {
drawingRect = CGRect(origin: .zero, size: preferredSize)
drawingRect.size.height += (ascent - capHeight)
drawingRect.size.height += descent
textAnchor = CGPoint(x: 0, y: ascent - capHeight)
} else {
let size = CTFramesetterSuggestFrameSizeWithConstraints(
setter,
CFRange(location: 0, length: attrString.length),
nil,
CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
nil)
switch alignment {
case .left:
textAnchor = CGPoint(x: 0, y: ascent)
case .right:
textAnchor = CGPoint(x: size.width, y: ascent)
case .center:
textAnchor = CGPoint(x: size.width * 0.5, y: ascent)
default:
textAnchor = .zero
}
drawingRect = CGRect(
x: 0,
y: 0,
width: ceil(size.width),
height: ceil(size.height))
}
// Now Calculate Anchor
drawingAnchor = CGPoint(
x: textAnchor.x.remap(fromLow: 0, fromHigh: drawingRect.size.width, toLow: 0, toHigh: 1),
y: textAnchor.y.remap(fromLow: 0, fromHigh: drawingRect.size.height, toLow: 0, toHigh: 1))
if fillFrameSetter != nil, strokeFrameSetter != nil {
drawingRect.size.width += strokeWidth
drawingRect.size.height += strokeWidth
}
}
}
extension CGContext {
fileprivate func adjustWithLineOrigins(in frame: CTFrame, with font: CTFont?) {
guard let font else { return }
let count = CFArrayGetCount(CTFrameGetLines(frame))
guard count > 0 else { return }
var o = [CGPoint](repeating: .zero, count: 1)
CTFrameGetLineOrigins(frame, CFRange(location: count - 1, length: 1), &o)
let diff = CTFontGetDescent(font) - o[0].y
if diff > 0 {
translateBy(x: 0, y: diff)
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/Utility/CoreTextRenderLayer.swift
|
Swift
|
unknown
| 9,834
|
//
// InvertedMatteLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/28/19.
//
import QuartzCore
/// A layer that inverses the alpha output of its input layer.
///
/// WARNING: This is experimental and probably not very performant.
final class InvertedMatteLayer: CALayer, CompositionLayerDelegate {
// MARK: Lifecycle
init(inputMatte: CompositionLayer) {
self.inputMatte = inputMatte
super.init()
inputMatte.layerDelegate = self
anchorPoint = .zero
bounds = inputMatte.bounds
setNeedsDisplay()
}
override init(layer: Any) {
guard let layer = layer as? InvertedMatteLayer else {
fatalError("init(layer:) wrong class.")
}
inputMatte = nil
super.init(layer: layer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
let inputMatte: CompositionLayer?
func frameUpdated(frame _: CGFloat) {
setNeedsDisplay()
displayIfNeeded()
}
override func draw(in ctx: CGContext) {
guard let inputMatte else { return }
ctx.setFillColor(.rgb(0, 0, 0))
ctx.fill(bounds)
ctx.setBlendMode(.destinationOut)
inputMatte.render(in: ctx)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/Utility/InvertedMatteLayer.swift
|
Swift
|
unknown
| 1,207
|
//
// LayerFontProvider.swift
// Lottie
//
// Created by Brandon Withrow on 8/5/20.
// Copyright © 2020 YurtvilleProds. All rights reserved.
//
/// Connects a LottieFontProvider to a group of text layers
final class LayerFontProvider {
// MARK: Lifecycle
init(fontProvider: AnimationFontProvider) {
self.fontProvider = fontProvider
textLayers = []
reloadTexts()
}
// MARK: Internal
private(set) var textLayers: [TextCompositionLayer]
var fontProvider: AnimationFontProvider {
didSet {
reloadTexts()
}
}
func addTextLayers(_ layers: [TextCompositionLayer]) {
textLayers += layers
}
func reloadTexts() {
for textLayer in textLayers {
textLayer.fontProvider = fontProvider
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/Utility/LayerFontProvider.swift
|
Swift
|
unknown
| 755
|
//
// LayerImageProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
/// Connects a LottieImageProvider to a group of image layers
final class LayerImageProvider {
// MARK: Lifecycle
init(imageProvider: AnimationImageProvider, assets: [String: ImageAsset]?) {
self.imageProvider = imageProvider
imageLayers = [ImageCompositionLayer]()
if let assets {
imageAssets = assets
} else {
imageAssets = [:]
}
reloadImages()
}
// MARK: Internal
private(set) var imageLayers: [ImageCompositionLayer]
let imageAssets: [String: ImageAsset]
var imageProvider: AnimationImageProvider {
didSet {
reloadImages()
}
}
func addImageLayers(_ layers: [ImageCompositionLayer]) {
for layer in layers {
if imageAssets[layer.imageReferenceID] != nil {
/// Found a linking asset in our asset library. Add layer
imageLayers.append(layer)
}
}
}
func reloadImages() {
for imageLayer in imageLayers {
if let asset = imageAssets[imageLayer.imageReferenceID] {
imageLayer.image = imageProvider.imageForAsset(asset: asset)
imageLayer.imageContentsGravity = imageProvider.contentsGravity(for: asset)
}
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/Utility/LayerImageProvider.swift
|
Swift
|
unknown
| 1,257
|
//
// LayerTextProvider.swift
// lottie-ios-iOS
//
// Created by Alexandr Goncharov on 07/06/2019.
//
/// Connects a LottieTextProvider to a group of text layers
final class LayerTextProvider {
// MARK: Lifecycle
init(textProvider: AnimationKeypathTextProvider) {
self.textProvider = textProvider
textLayers = []
reloadTexts()
}
// MARK: Internal
private(set) var textLayers: [TextCompositionLayer]
var textProvider: AnimationKeypathTextProvider {
didSet {
reloadTexts()
}
}
func addTextLayers(_ layers: [TextCompositionLayer]) {
textLayers += layers
}
func reloadTexts() {
for textLayer in textLayers {
textLayer.textProvider = textProvider
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/Utility/LayerTextProvider.swift
|
Swift
|
unknown
| 725
|
//
// LayerTransformPropertyMap.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
import QuartzCore
// MARK: - LayerTransformProperties
final class LayerTransformProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(transform: Transform) {
anchor = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.anchorPoint.keyframes))
scale = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.scale.keyframes))
rotationX = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.rotationX.keyframes))
rotationY = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.rotationY.keyframes))
rotationZ = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.rotationZ.keyframes))
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.opacity.keyframes))
var propertyMap: [String: AnyNodeProperty] = [
"Anchor Point" : anchor,
PropertyName.scale.rawValue : scale,
PropertyName.rotation.rawValue: rotationZ,
"Rotation X" : rotationX,
"Rotation Y" : rotationY,
"Rotation Z" : rotationZ,
PropertyName.opacity.rawValue : opacity,
]
if
let positionKeyframesX = transform.positionX?.keyframes,
let positionKeyframesY = transform.positionY?.keyframes
{
let xPosition: NodeProperty<LottieVector1D> = NodeProperty(provider: KeyframeInterpolator(keyframes: positionKeyframesX))
let yPosition: NodeProperty<LottieVector1D> = NodeProperty(provider: KeyframeInterpolator(keyframes: positionKeyframesY))
propertyMap["X Position"] = xPosition
propertyMap["Y Position"] = yPosition
positionX = xPosition
positionY = yPosition
position = nil
} else if let positionKeyframes = transform.position?.keyframes {
let position: NodeProperty<LottieVector3D> = NodeProperty(provider: KeyframeInterpolator(keyframes: positionKeyframes))
propertyMap[PropertyName.position.rawValue] = position
self.position = position
positionX = nil
positionY = nil
} else {
position = nil
positionY = nil
positionX = nil
}
keypathProperties = propertyMap
properties = Array(propertyMap.values)
}
// MARK: Internal
let keypathProperties: [String: AnyNodeProperty]
var keypathName = "Transform"
let properties: [AnyNodeProperty]
let anchor: NodeProperty<LottieVector3D>
let scale: NodeProperty<LottieVector3D>
let rotationX: NodeProperty<LottieVector1D>
let rotationY: NodeProperty<LottieVector1D>
let rotationZ: NodeProperty<LottieVector1D>
let position: NodeProperty<LottieVector3D>?
let positionX: NodeProperty<LottieVector1D>?
let positionY: NodeProperty<LottieVector1D>?
let opacity: NodeProperty<LottieVector1D>
var childKeypaths: [KeypathSearchable] {
[]
}
}
// MARK: - LayerTransformNode
class LayerTransformNode: AnimatorNode {
// MARK: Lifecycle
init(transform: Transform) {
transformProperties = LayerTransformProperties(transform: transform)
}
// MARK: Internal
let outputNode: NodeOutput = PassThroughOutputNode(parent: nil)
let transformProperties: LayerTransformProperties
var parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var isEnabled = true
var opacity: Float = 1
var localTransform: CATransform3D = CATransform3DIdentity
var globalTransform: CATransform3D = CATransform3DIdentity
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
transformProperties
}
func shouldRebuildOutputs(frame _: CGFloat) -> Bool {
hasLocalUpdates || hasUpstreamUpdates
}
func rebuildOutputs(frame _: CGFloat) {
opacity = Float(transformProperties.opacity.value.cgFloatValue) * 0.01
let position: CGPoint
if let point = transformProperties.position?.value.pointValue {
position = point
} else if
let xPos = transformProperties.positionX?.value.cgFloatValue,
let yPos = transformProperties.positionY?.value.cgFloatValue
{
position = CGPoint(x: xPos, y: yPos)
} else {
position = .zero
}
localTransform = CATransform3D.makeTransform(
anchor: transformProperties.anchor.value.pointValue,
position: position,
scale: transformProperties.scale.value.sizeValue,
rotationX: transformProperties.rotationX.value.cgFloatValue,
rotationY: transformProperties.rotationY.value.cgFloatValue,
rotationZ: transformProperties.rotationZ.value.cgFloatValue,
skew: nil,
skewAxis: nil)
if let parentNode = parentNode as? LayerTransformNode {
globalTransform = CATransform3DConcat(localTransform, parentNode.globalTransform)
} else {
globalTransform = localTransform
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/LayerContainers/Utility/LayerTransformNode.swift
|
Swift
|
unknown
| 4,879
|
//
// ItemsExtension.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/18/19.
//
// MARK: - NodeTree
final class NodeTree {
var rootNode: AnimatorNode? = nil
var transform: ShapeTransform? = nil
var renderContainers: [ShapeContainerLayer] = []
var paths: [PathOutputNode] = []
var childrenNodes: [AnimatorNode] = []
}
extension [ShapeItem] {
func initializeNodeTree() -> NodeTree {
let nodeTree = NodeTree()
for item in self {
guard item.hidden == false, item.type != .unknown else { continue }
if let fill = item as? Fill {
let node = FillNode(parentNode: nodeTree.rootNode, fill: fill)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
} else if let stroke = item as? Stroke {
let node = StrokeNode(parentNode: nodeTree.rootNode, stroke: stroke)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
} else if let gradientFill = item as? GradientFill {
let node = GradientFillNode(parentNode: nodeTree.rootNode, gradientFill: gradientFill)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
} else if let gradientStroke = item as? GradientStroke {
let node = GradientStrokeNode(parentNode: nodeTree.rootNode, gradientStroke: gradientStroke)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
} else if let ellipse = item as? Ellipse {
let node = EllipseNode(parentNode: nodeTree.rootNode, ellipse: ellipse)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
} else if let rect = item as? Rectangle {
let node = RectangleNode(parentNode: nodeTree.rootNode, rectangle: rect)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
} else if let star = item as? Star {
switch star.starType {
case .none:
continue
case .polygon:
let node = PolygonNode(parentNode: nodeTree.rootNode, star: star)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
case .star:
let node = StarNode(parentNode: nodeTree.rootNode, star: star)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
}
} else if let shape = item as? Shape {
let node = ShapeNode(parentNode: nodeTree.rootNode, shape: shape)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
} else if let trim = item as? Trim {
let node = TrimPathNode(parentNode: nodeTree.rootNode, trim: trim, upstreamPaths: nodeTree.paths)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
} else if let roundedCorners = item as? RoundedCorners {
let node = RoundedCornersNode(
parentNode: nodeTree.rootNode,
roundedCorners: roundedCorners,
upstreamPaths: nodeTree.paths)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
} else if let xform = item as? ShapeTransform {
nodeTree.transform = xform
continue
} else if let group = item as? Group {
let tree = group.items.initializeNodeTree()
let node = GroupNode(name: group.name, parentNode: nodeTree.rootNode, tree: tree)
nodeTree.rootNode = node
nodeTree.childrenNodes.append(node)
/// Now add all child paths to current tree
nodeTree.paths.append(contentsOf: tree.paths)
nodeTree.renderContainers.append(node.container)
} else if item is Repeater {
LottieLogger.shared.warn("""
The Main Thread rendering engine doesn't currently support repeaters.
To play an animation with repeaters, you can use the Core Animation rendering engine instead.
""")
}
if let pathNode = nodeTree.rootNode as? PathNode {
//// Add path container to the node tree
nodeTree.paths.append(pathNode.pathOutput)
}
if let renderNode = nodeTree.rootNode as? RenderNode {
nodeTree.renderContainers.append(ShapeRenderLayer(renderer: renderNode.renderer))
}
}
return nodeTree
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Extensions/ItemsExtension.swift
|
Swift
|
unknown
| 4,179
|
//
// NodeProperty.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import CoreGraphics
import Foundation
/// A node property that holds a reference to a T ValueProvider and a T ValueContainer.
class NodeProperty<T>: AnyNodeProperty {
// MARK: Lifecycle
init(provider: AnyValueProvider) {
valueProvider = provider
originalValueProvider = valueProvider
typedContainer = ValueContainer<T>(provider.value(frame: 0) as! T)
typedContainer.setNeedsUpdate()
}
// MARK: Internal
var valueProvider: AnyValueProvider
var originalValueProvider: AnyValueProvider
var valueType: Any.Type { T.self }
var value: T {
typedContainer.outputValue
}
var valueContainer: AnyValueContainer {
typedContainer
}
func needsUpdate(frame: CGFloat) -> Bool {
valueContainer.needsUpdate || valueProvider.hasUpdate(frame: frame)
}
func setProvider(provider: AnyValueProvider) {
guard provider.valueType == valueType else { return }
valueProvider = provider
valueContainer.setNeedsUpdate()
}
func update(frame: CGFloat) {
typedContainer.setValue(valueProvider.value(frame: frame), forFrame: frame)
}
// MARK: Fileprivate
fileprivate var typedContainer: ValueContainer<T>
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/NodeProperties/NodeProperty.swift
|
Swift
|
unknown
| 1,261
|
//
// AnyNodeProperty.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import CoreGraphics
import Foundation
// MARK: - AnyNodeProperty
/// A property of a node. The node property holds a provider and a container
protocol AnyNodeProperty {
/// Returns true if the property needs to recompute its stored value
func needsUpdate(frame: CGFloat) -> Bool
/// Updates the property for the frame
func update(frame: CGFloat)
/// The stored value container for the property
var valueContainer: AnyValueContainer { get }
/// The value provider for the property
var valueProvider: AnyValueProvider { get }
/// The original value provider for the property
var originalValueProvider: AnyValueProvider { get }
/// The Type of the value provider
var valueType: Any.Type { get }
/// Sets the value provider for the property.
func setProvider(provider: AnyValueProvider)
}
extension AnyNodeProperty {
/// Returns the most recently computed value for the keypath, returns nil if property wasn't found
func getValueOfType<T>() -> T? {
valueContainer.value as? T
}
/// Returns the most recently computed value for the keypath, returns nil if property wasn't found
func getValue() -> Any? {
valueContainer.value
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/NodeProperties/Protocols/AnyNodeProperty.swift
|
Swift
|
unknown
| 1,281
|
//
// AnyValueContainer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import CoreGraphics
import Foundation
/// The container for the value of a property.
protocol AnyValueContainer: AnyObject {
/// The stored value of the container
var value: Any { get }
/// Notifies the provider that it should update its container
func setNeedsUpdate()
/// When true the container needs to have its value updated by its provider
var needsUpdate: Bool { get }
/// The frame time of the last provided update
var lastUpdateFrame: CGFloat { get }
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/NodeProperties/Protocols/AnyValueContainer.swift
|
Swift
|
unknown
| 582
|
//
// KeypathSettable.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
import QuartzCore
/// Protocol that provides keypath search functionality. Returns all node properties associated with a keypath.
protocol KeypathSearchable {
/// The name of the Keypath
var keypathName: String { get }
/// A list of properties belonging to the keypath.
var keypathProperties: [String: AnyNodeProperty] { get }
/// Children Keypaths
var childKeypaths: [KeypathSearchable] { get }
var keypathLayer: CALayer? { get }
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/NodeProperties/Protocols/KeypathSearchable.swift
|
Swift
|
unknown
| 547
|
//
// NodePropertyMap.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/21/19.
//
import QuartzCore
// MARK: - NodePropertyMap
protocol NodePropertyMap {
var properties: [AnyNodeProperty] { get }
}
extension NodePropertyMap {
var childKeypaths: [KeypathSearchable] {
[]
}
var keypathLayer: CALayer? {
nil
}
/// Checks if the node's local contents need to be rebuilt.
func needsLocalUpdate(frame: CGFloat) -> Bool {
for property in properties {
if property.needsUpdate(frame: frame) {
return true
}
}
return false
}
/// Rebuilds only the local nodes that have an update for the frame
func updateNodeProperties(frame: CGFloat) {
for property in properties {
property.update(frame: frame)
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/NodeProperties/Protocols/NodePropertyMap.swift
|
Swift
|
unknown
| 790
|
//
// ValueContainer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import CoreGraphics
import Foundation
/// A container for a node value that is Typed to T.
class ValueContainer<T>: AnyValueContainer {
// MARK: Lifecycle
init(_ value: T) {
outputValue = value
}
// MARK: Internal
private(set) var lastUpdateFrame = CGFloat.infinity
fileprivate(set) var needsUpdate = true
var value: Any {
outputValue as Any
}
var outputValue: T {
didSet {
needsUpdate = false
}
}
func setValue(_ value: Any, forFrame: CGFloat) {
if let typedValue = value as? T {
needsUpdate = false
lastUpdateFrame = forFrame
outputValue = typedValue
}
}
func setNeedsUpdate() {
needsUpdate = true
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/NodeProperties/ValueContainer.swift
|
Swift
|
unknown
| 789
|
//
// KeyframeGroupInterpolator.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/22/19.
//
import CoreGraphics
import Foundation
/// A value provider that produces an array of values from an array of Keyframe Interpolators
final class GroupInterpolator<ValueType>: ValueProvider where ValueType: Interpolatable {
// MARK: Lifecycle
/// Initialize with an array of array of keyframes.
init(keyframeGroups: ContiguousArray<ContiguousArray<Keyframe<ValueType>>>) {
keyframeInterpolators = ContiguousArray(keyframeGroups.map { KeyframeInterpolator(keyframes: $0) })
}
// MARK: Internal
let keyframeInterpolators: ContiguousArray<KeyframeInterpolator<ValueType>>
var valueType: Any.Type {
[ValueType].self
}
var storage: ValueProviderStorage<[ValueType]> {
.closure { frame in
self.keyframeInterpolators.map { $0.value(frame: frame) as! ValueType }
}
}
func hasUpdate(frame: CGFloat) -> Bool {
let updated = keyframeInterpolators.first(where: { $0.hasUpdate(frame: frame) })
return updated != nil
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/NodeProperties/ValueProviders/GroupInterpolator.swift
|
Swift
|
unknown
| 1,073
|
//
// SingleValueProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import Foundation
import QuartzCore
/// Returns a value for every frame.
final class SingleValueProvider<ValueType: AnyInterpolatable>: ValueProvider {
// MARK: Lifecycle
init(_ value: ValueType) {
self.value = value
}
// MARK: Internal
var value: ValueType {
didSet {
hasUpdate = true
}
}
var storage: ValueProviderStorage<ValueType> {
.singleValue(value)
}
var valueType: Any.Type {
ValueType.self
}
func hasUpdate(frame _: CGFloat) -> Bool {
hasUpdate
}
// MARK: Private
private var hasUpdate = true
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/NodeProperties/ValueProviders/SingleValueProvider.swift
|
Swift
|
unknown
| 673
|
// Created by Lan Xu on 2024/6/7.
// Copyright © 2024 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - DropShadowNode
final class DropShadowNode: LayerEffectNode {
// MARK: Lifecycle
init(model: DropShadowModel) {
properties = DropShadowNodeProperties(model: model)
}
// MARK: Internal
var properties: DropShadowNodeProperties
var propertyMap: any NodePropertyMap {
properties
}
func applyEffect(to layer: CALayer) {
if let opacity = properties.opacity?.value.cgFloatValue {
// Lottie animation files express opacity as a numerical percentage value
// (e.g. 0%, 50%, 100%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.0, 0.5, 1.0).
layer.shadowOpacity = Float(opacity / 100)
}
if
let angleDegrees = properties.angle?.value.cgFloatValue,
let distance = properties.distance?.value.cgFloatValue
{
// Lottie animation files express rotation in degrees
// (e.g. 90º, 180º, 360º) so we convert to radians to get the
// values expected by Core Animation (e.g. π/2, π, 2π)
let angleRadians = (angleDegrees * .pi) / 180
// Lottie animation files express the `shadowOffset` as (angle, distance) pair,
// which we convert to the expected x / y offset values:
let offsetX = distance * cos(angleRadians)
let offsetY = distance * sin(angleRadians)
layer.shadowOffset = .init(width: offsetX, height: offsetY)
}
layer.shadowColor = properties.color?.value.cgColorValue
layer.shadowRadius = properties.radius?.value.cgFloatValue ?? 0
}
}
// MARK: - DropShadowNodeProperties
final class DropShadowNodeProperties: NodePropertyMap {
// MARK: Lifecycle
init(model: DropShadowModel) {
if let opacityKeyframes = model._opacity?.keyframes {
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: opacityKeyframes))
propertyMap[PropertyName.opacity.rawValue] = opacity
} else {
opacity = nil
}
if let radiusKeyframes = model._radius?.keyframes {
radius = NodeProperty(provider: KeyframeInterpolator(keyframes: radiusKeyframes))
propertyMap["Radius"] = radius
} else {
radius = nil
}
if let colorKeyFrames = model._color?.keyframes {
color = NodeProperty(provider: KeyframeInterpolator(keyframes: colorKeyFrames))
propertyMap[PropertyName.color.rawValue] = color
} else {
color = nil
}
if let angleKeyFrames = model._angle?.keyframes {
angle = NodeProperty(provider: KeyframeInterpolator(keyframes: angleKeyFrames))
propertyMap["Angle"] = angle
} else {
angle = nil
}
if let distanceKeyFrame = model._distance?.keyframes {
distance = NodeProperty(provider: KeyframeInterpolator(keyframes: distanceKeyFrame))
propertyMap["Distance"] = distance
} else {
distance = nil
}
properties = Array(propertyMap.values)
}
// MARK: Internal
var propertyMap: [String: AnyNodeProperty] = [:]
var properties: [AnyNodeProperty]
let opacity: NodeProperty<LottieVector1D>?
let radius: NodeProperty<LottieVector1D>?
let color: NodeProperty<LottieColor>?
let angle: NodeProperty<LottieVector1D>?
let distance: NodeProperty<LottieVector1D>?
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/LayerEffectNodes/DropShadowNode.swift
|
Swift
|
unknown
| 3,302
|
// Created by Lan Xu on 2024/6/8.
// Copyright © 2024 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - LayerEffectNode
protocol LayerEffectNode {
func applyEffect(to layer: CALayer)
var propertyMap: NodePropertyMap { get }
}
extension LayerEffectNode {
func updateWithFrame(layer: CALayer, frame: CGFloat) {
for property in propertyMap.properties {
if property.needsUpdate(frame: frame) {
property.update(frame: frame)
}
}
applyEffect(to: layer)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/LayerEffectNodes/LayerEffectNode.swift
|
Swift
|
unknown
| 510
|
//
// RoundedCornersNode.swift
// Lottie
//
// Created by Duolingo on 10/31/22.
//
import Foundation
import QuartzCore
// MARK: - RoundedCornersProperties
final class RoundedCornersProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(roundedCorners: RoundedCorners) {
keypathName = roundedCorners.name
radius = NodeProperty(provider: KeyframeInterpolator(keyframes: roundedCorners.radius.keyframes))
keypathProperties = ["Radius" : radius]
properties = Array(keypathProperties.values)
}
// MARK: Internal
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
let keypathName: String
let radius: NodeProperty<LottieVector1D>
}
// MARK: - RoundedCornersNode
final class RoundedCornersNode: AnimatorNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, roundedCorners: RoundedCorners, upstreamPaths: [PathOutputNode]) {
outputNode = PassThroughOutputNode(parent: parentNode?.outputNode)
self.parentNode = parentNode
properties = RoundedCornersProperties(roundedCorners: roundedCorners)
self.upstreamPaths = upstreamPaths
}
// MARK: Internal
let properties: RoundedCornersProperties
let parentNode: AnimatorNode?
let outputNode: NodeOutput
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var isEnabled = true
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
func forceUpstreamOutputUpdates() -> Bool {
hasLocalUpdates || hasUpstreamUpdates
}
func rebuildOutputs(frame: CGFloat) {
for pathContainer in upstreamPaths {
let pathObjects = pathContainer.removePaths(updateFrame: frame)
for path in pathObjects {
let cornerRadius = properties.radius.value.cgFloatValue
if cornerRadius != 0 {
pathContainer.appendPath(
path.roundCorners(radius: cornerRadius),
updateFrame: frame)
} else {
pathContainer.appendPath(path, updateFrame: frame)
}
}
}
}
// MARK: Fileprivate
fileprivate let upstreamPaths: [PathOutputNode]
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/ModifierNodes/RoundedCornersNode.swift
|
Swift
|
unknown
| 2,171
|
//
// TrimPathNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/23/19.
//
import Foundation
import QuartzCore
// MARK: - TrimPathProperties
final class TrimPathProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(trim: Trim) {
keypathName = trim.name
start = NodeProperty(provider: KeyframeInterpolator(keyframes: trim.start.keyframes))
end = NodeProperty(provider: KeyframeInterpolator(keyframes: trim.end.keyframes))
offset = NodeProperty(provider: KeyframeInterpolator(keyframes: trim.offset.keyframes))
type = trim.trimType
keypathProperties = [
"Start" : start,
"End" : end,
"Offset" : offset,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
let keypathName: String
let start: NodeProperty<LottieVector1D>
let end: NodeProperty<LottieVector1D>
let offset: NodeProperty<LottieVector1D>
let type: TrimType
}
// MARK: - TrimPathNode
final class TrimPathNode: AnimatorNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, trim: Trim, upstreamPaths: [PathOutputNode]) {
outputNode = PassThroughOutputNode(parent: parentNode?.outputNode)
self.parentNode = parentNode
properties = TrimPathProperties(trim: trim)
self.upstreamPaths = upstreamPaths
}
// MARK: Internal
let properties: TrimPathProperties
let parentNode: AnimatorNode?
let outputNode: NodeOutput
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var isEnabled = true
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
func forceUpstreamOutputUpdates() -> Bool {
hasLocalUpdates || hasUpstreamUpdates
}
func rebuildOutputs(frame: CGFloat) {
/// Make sure there is a trim.
let startValue = properties.start.value.cgFloatValue * 0.01
let endValue = properties.end.value.cgFloatValue * 0.01
let start = min(startValue, endValue)
let end = max(startValue, endValue)
let offset = properties.offset.value.cgFloatValue.truncatingRemainder(dividingBy: 360) / 360
/// No need to trim, it's a full path
if start == 0, end == 1 {
return
}
/// All paths are empty.
if start == end {
for pathContainer in upstreamPaths {
pathContainer.removePaths(updateFrame: frame)
}
return
}
if properties.type == .simultaneously {
/// Just trim each path
for pathContainer in upstreamPaths {
let pathObjects = pathContainer.removePaths(updateFrame: frame)
for path in pathObjects {
// We are treating each compount path as an individual path. Its subpaths are treated as a whole.
pathContainer.appendPath(
path.trim(fromPosition: start, toPosition: end, offset: offset, trimSimultaneously: false),
updateFrame: frame)
}
}
return
}
/// Individual path trimming.
/// Brace yourself for the below code.
/// Normalize lengths with offset.
var startPosition = (start + offset).truncatingRemainder(dividingBy: 1)
var endPosition = (end + offset).truncatingRemainder(dividingBy: 1)
if startPosition < 0 {
startPosition = 1 + startPosition
}
if endPosition < 0 {
endPosition = 1 + endPosition
}
if startPosition == 1 {
startPosition = 0
}
if endPosition == 0 {
endPosition = 1
}
/// First get the total length of all paths.
var totalLength: CGFloat = 0
for upstreamPath in upstreamPaths {
totalLength = totalLength + upstreamPath.totalLength
}
/// Now determine the start and end cut lengths
let startLength = startPosition * totalLength
let endLength = endPosition * totalLength
var pathStart: CGFloat = 0
/// Now loop through all path containers
for pathContainer in upstreamPaths {
let pathEnd = pathStart + pathContainer.totalLength
if
!startLength.isInRange(pathStart, pathEnd) &&
endLength.isInRange(pathStart, pathEnd)
{
// pathStart|=======E----------------------|pathEnd
// Cut path components, removing after end.
let pathCutLength = endLength - pathStart
let subpaths = pathContainer.removePaths(updateFrame: frame)
var subpathStart: CGFloat = 0
for path in subpaths {
let subpathEnd = subpathStart + path.length
if pathCutLength < subpathEnd {
/// This is the subpath that needs to be cut.
let cutLength = pathCutLength - subpathStart
let newPath = path.trim(fromPosition: 0, toPosition: cutLength / path.length, offset: 0, trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
break
} else {
/// Add to container and move on
pathContainer.appendPath(path, updateFrame: frame)
}
if pathCutLength == subpathEnd {
/// Right on the end. The next subpath is not included. Break.
break
}
subpathStart = subpathEnd
}
} else if
!endLength.isInRange(pathStart, pathEnd) &&
startLength.isInRange(pathStart, pathEnd)
{
// pathStart|-------S======================|pathEnd
//
// Cut path components, removing before beginning.
let pathCutLength = startLength - pathStart
// Clear paths from container
let subpaths = pathContainer.removePaths(updateFrame: frame)
var subpathStart: CGFloat = 0
for path in subpaths {
let subpathEnd = subpathStart + path.length
if subpathStart < pathCutLength, pathCutLength < subpathEnd {
/// This is the subpath that needs to be cut.
let cutLength = pathCutLength - subpathStart
let newPath = path.trim(fromPosition: cutLength / path.length, toPosition: 1, offset: 0, trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
} else if pathCutLength <= subpathStart {
pathContainer.appendPath(path, updateFrame: frame)
}
subpathStart = subpathEnd
}
} else if
endLength.isInRange(pathStart, pathEnd) &&
startLength.isInRange(pathStart, pathEnd)
{
// pathStart|-------S============E---------|endLength
// pathStart|=====E----------------S=======|endLength
// trim from path beginning to endLength.
// Cut path components, removing before beginnings.
let startCutLength = startLength - pathStart
let endCutLength = endLength - pathStart
// Clear paths from container
let subpaths = pathContainer.removePaths(updateFrame: frame)
var subpathStart: CGFloat = 0
for path in subpaths {
let subpathEnd = subpathStart + path.length
if
!startCutLength.isInRange(subpathStart, subpathEnd),
!endCutLength.isInRange(subpathStart, subpathEnd)
{
// The whole path is included. Add
// S|==============================|E
pathContainer.appendPath(path, updateFrame: frame)
} else if
startCutLength.isInRange(subpathStart, subpathEnd),
!endCutLength.isInRange(subpathStart, subpathEnd)
{
/// The start of the path needs to be trimmed
// |-------S======================|E
let cutLength = startCutLength - subpathStart
let newPath = path.trim(fromPosition: cutLength / path.length, toPosition: 1, offset: 0, trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
} else if
!startCutLength.isInRange(subpathStart, subpathEnd),
endCutLength.isInRange(subpathStart, subpathEnd)
{
// S|=======E----------------------|
let cutLength = endCutLength - subpathStart
let newPath = path.trim(fromPosition: 0, toPosition: cutLength / path.length, offset: 0, trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
break
} else if
startCutLength.isInRange(subpathStart, subpathEnd),
endCutLength.isInRange(subpathStart, subpathEnd)
{
// |-------S============E---------|
let cutFromLength = startCutLength - subpathStart
let cutToLength = endCutLength - subpathStart
let newPath = path.trim(
fromPosition: cutFromLength / path.length,
toPosition: cutToLength / path.length,
offset: 0,
trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
break
}
subpathStart = subpathEnd
}
} else if
(endLength <= pathStart && pathEnd <= startLength) ||
(startLength <= pathStart && endLength <= pathStart) ||
(pathEnd <= startLength && pathEnd <= endLength)
{
/// The Path needs to be cleared
pathContainer.removePaths(updateFrame: frame)
}
pathStart = pathEnd
}
}
// MARK: Fileprivate
fileprivate let upstreamPaths: [PathOutputNode]
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/ModifierNodes/TrimPathNode.swift
|
Swift
|
unknown
| 9,437
|
//
// TransformNodeOutput.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import QuartzCore
class GroupOutputNode: NodeOutput {
// MARK: Lifecycle
init(parent: NodeOutput?, rootNode: NodeOutput?) {
self.parent = parent
self.rootNode = rootNode
}
// MARK: Internal
let parent: NodeOutput?
let rootNode: NodeOutput?
var isEnabled = true
private(set) var outputPath: CGPath? = nil
private(set) var transform: CATransform3D = CATransform3DIdentity
func setTransform(_ xform: CATransform3D, forFrame _: CGFloat) {
transform = xform
outputPath = nil
}
func hasOutputUpdates(_ forFrame: CGFloat) -> Bool {
guard isEnabled else {
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
outputPath = parent?.outputPath
return upstreamUpdates
}
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
if upstreamUpdates {
outputPath = nil
}
let rootUpdates = rootNode?.hasOutputUpdates(forFrame) ?? false
if rootUpdates {
outputPath = nil
}
var localUpdates = false
if outputPath == nil {
localUpdates = true
let newPath = CGMutablePath()
if let parentNode = parent, let parentPath = parentNode.outputPath {
/// First add parent path.
newPath.addPath(parentPath)
}
var xform = CATransform3DGetAffineTransform(transform)
if
let rootNode,
let rootPath = rootNode.outputPath,
let xformedPath = rootPath.copy(using: &xform)
{
/// Now add root path. Note root path is transformed.
newPath.addPath(xformedPath)
}
outputPath = newPath
}
return upstreamUpdates || localUpdates
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/OutputNodes/GroupOutputNode.swift
|
Swift
|
unknown
| 1,753
|
//
// PassThroughOutputNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import CoreGraphics
class PassThroughOutputNode: NodeOutput {
// MARK: Lifecycle
init(parent: NodeOutput?) {
self.parent = parent
}
// MARK: Internal
let parent: NodeOutput?
var hasUpdate = false
var isEnabled = true
var outputPath: CGPath? {
if let parent {
return parent.outputPath
}
return nil
}
func hasOutputUpdates(_ forFrame: CGFloat) -> Bool {
/// Changes to this node do not affect downstream nodes.
let parentUpdate = parent?.hasOutputUpdates(forFrame) ?? false
/// Changes to upstream nodes do, however, affect this nodes state.
hasUpdate = hasUpdate || parentUpdate
return parentUpdate
}
func hasRenderUpdates(_ forFrame: CGFloat) -> Bool {
/// Return true if there are upstream updates or if this node has updates
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
hasUpdate = hasUpdate || upstreamUpdates
return hasUpdate
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/OutputNodes/PassThroughOutputNode.swift
|
Swift
|
unknown
| 1,050
|
//
// PathNodeOutput.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import CoreGraphics
/// A node that has an output of a BezierPath
class PathOutputNode: NodeOutput {
// MARK: Lifecycle
init(parent: NodeOutput?) {
self.parent = parent
}
// MARK: Internal
let parent: NodeOutput?
fileprivate(set) var outputPath: CGPath? = nil
var lastUpdateFrame: CGFloat? = nil
var lastPathBuildFrame: CGFloat? = nil
var isEnabled = true
fileprivate(set) var totalLength: CGFloat = 0
fileprivate(set) var pathObjects: [CompoundBezierPath] = []
func hasOutputUpdates(_ forFrame: CGFloat) -> Bool {
guard isEnabled else {
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
outputPath = parent?.outputPath
return upstreamUpdates
}
/// Ask if parent was updated
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
/// If parent was updated and the path hasn't been built for this frame, clear the path.
if upstreamUpdates && lastPathBuildFrame != forFrame {
outputPath = nil
}
if outputPath == nil {
/// If the path is clear, build the new path.
lastPathBuildFrame = forFrame
let newPath = CGMutablePath()
if let parentNode = parent, let parentPath = parentNode.outputPath {
newPath.addPath(parentPath)
}
for path in pathObjects {
for subPath in path.paths {
newPath.addPath(subPath.cgPath())
}
}
outputPath = newPath
}
/// Return true if there were upstream updates or if this node was updated.
return upstreamUpdates || (lastUpdateFrame == forFrame)
}
@discardableResult
func removePaths(updateFrame: CGFloat?) -> [CompoundBezierPath] {
lastUpdateFrame = updateFrame
let returnPaths = pathObjects
outputPath = nil
totalLength = 0
pathObjects = []
return returnPaths
}
func setPath(_ path: BezierPath, updateFrame: CGFloat) {
lastUpdateFrame = updateFrame
outputPath = nil
totalLength = path.length
pathObjects = [CompoundBezierPath(path: path)]
}
func appendPath(_ path: CompoundBezierPath, updateFrame: CGFloat) {
lastUpdateFrame = updateFrame
outputPath = nil
totalLength = totalLength + path.length
pathObjects.append(path)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/OutputNodes/PathOutputNode.swift
|
Swift
|
unknown
| 2,337
|
//
// FillRenderer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import QuartzCore
extension FillRule {
var cgFillRule: CGPathFillRule {
switch self {
case .evenOdd:
return .evenOdd
default:
return .winding
}
}
var caFillRule: CAShapeLayerFillRule {
switch self {
case .evenOdd:
return CAShapeLayerFillRule.evenOdd
default:
return CAShapeLayerFillRule.nonZero
}
}
}
// MARK: - FillRenderer
/// A rendered for a Path Fill
final class FillRenderer: PassThroughOutputNode, Renderable {
var shouldRenderInContext = false
var color: CGColor? {
didSet {
hasUpdate = true
}
}
var opacity: CGFloat = 0 {
didSet {
hasUpdate = true
}
}
var fillRule: FillRule = .none {
didSet {
hasUpdate = true
}
}
func render(_: CGContext) {
// do nothing
}
func setupSublayers(layer _: CAShapeLayer) {
// do nothing
}
func updateShapeLayer(layer: CAShapeLayer) {
layer.fillColor = color
layer.opacity = Float(opacity)
layer.fillRule = fillRule.caFillRule
hasUpdate = false
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/OutputNodes/Renderables/FillRenderer.swift
|
Swift
|
unknown
| 1,148
|
//
// GradientFillRenderer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import QuartzCore
// MARK: - GradientFillLayer
private final class GradientFillLayer: CALayer {
var start: CGPoint = .zero {
didSet {
setNeedsDisplay()
}
}
var numberOfColors = 0 {
didSet {
setNeedsDisplay()
}
}
var colors: [CGFloat] = [] {
didSet {
setNeedsDisplay()
}
}
var end: CGPoint = .zero {
didSet {
setNeedsDisplay()
}
}
var type: GradientType = .none {
didSet {
setNeedsDisplay()
}
}
override func draw(in ctx: CGContext) {
var alphaColors = [CGColor]()
var alphaLocations = [CGFloat]()
var gradientColors = [CGColor]()
var colorLocations = [CGFloat]()
let maskColorSpace = CGColorSpaceCreateDeviceGray()
for i in 0..<numberOfColors {
let ix = i * 4
if colors.count > ix {
let color = CGColor.rgb(colors[ix + 1], colors[ix + 2], colors[ix + 3])
gradientColors.append(color)
colorLocations.append(colors[ix])
}
}
var drawMask = false
for i in stride(from: numberOfColors * 4, to: colors.endIndex, by: 2) {
let alpha = colors[i + 1]
if alpha < 1 {
drawMask = true
}
alphaLocations.append(colors[i])
alphaColors.append(.gray(alpha))
}
/// First draw a mask is necessary.
if drawMask {
guard
let maskGradient = CGGradient(
colorsSpace: maskColorSpace,
colors: alphaColors as CFArray,
locations: alphaLocations),
let maskContext = CGContext(
data: nil,
width: ctx.width,
height: ctx.height,
bitsPerComponent: 8,
bytesPerRow: ctx.width,
space: maskColorSpace,
bitmapInfo: 0)
else { return }
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: CGFloat(maskContext.height))
maskContext.concatenate(flipVertical)
maskContext.concatenate(ctx.ctm)
if type == .linear {
maskContext.drawLinearGradient(
maskGradient,
start: start,
end: end,
options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
} else {
maskContext.drawRadialGradient(
maskGradient,
startCenter: start,
startRadius: 0,
endCenter: start,
endRadius: start.distanceTo(end),
options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
}
/// Clips the gradient
if let alphaMask = maskContext.makeImage() {
ctx.clip(to: ctx.boundingBoxOfClipPath, mask: alphaMask)
}
}
/// Now draw the gradient
guard
let gradient = CGGradient(
colorsSpace: LottieConfiguration.shared.colorSpace,
colors: gradientColors as CFArray,
locations: colorLocations)
else { return }
if type == .linear {
ctx.drawLinearGradient(gradient, start: start, end: end, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
} else {
ctx.drawRadialGradient(
gradient,
startCenter: start,
startRadius: 0,
endCenter: start,
endRadius: start.distanceTo(end),
options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
}
}
}
// MARK: - GradientFillRenderer
/// A rendered for a Path Fill
final class GradientFillRenderer: PassThroughOutputNode, Renderable {
// MARK: Lifecycle
override init(parent: NodeOutput?) {
super.init(parent: parent)
maskLayer.fillColor = .rgb(1, 1, 1)
gradientLayer.mask = maskLayer
maskLayer.actions = [
"startPoint" : NSNull(),
"endPoint" : NSNull(),
"opacity" : NSNull(),
"locations" : NSNull(),
"colors" : NSNull(),
"bounds" : NSNull(),
"anchorPoint" : NSNull(),
"isRadial" : NSNull(),
"path" : NSNull(),
]
gradientLayer.actions = maskLayer.actions
}
// MARK: Internal
var shouldRenderInContext = false
var start: CGPoint = .zero {
didSet {
hasUpdate = true
}
}
var numberOfColors = 0 {
didSet {
hasUpdate = true
}
}
var colors: [CGFloat] = [] {
didSet {
hasUpdate = true
}
}
var end: CGPoint = .zero {
didSet {
hasUpdate = true
}
}
var opacity: CGFloat = 0 {
didSet {
hasUpdate = true
}
}
var type: GradientType = .none {
didSet {
hasUpdate = true
}
}
var fillRule: CAShapeLayerFillRule {
get { maskLayer.fillRule }
set { maskLayer.fillRule = newValue }
}
func render(_: CGContext) {
// do nothing
}
func setupSublayers(layer: CAShapeLayer) {
layer.addSublayer(gradientLayer)
layer.fillColor = nil
}
func updateShapeLayer(layer: CAShapeLayer) {
hasUpdate = false
guard let path = layer.path else {
return
}
let frame = path.boundingBox
let anchor = CGPoint(
x: -frame.origin.x / frame.size.width,
y: -frame.origin.y / frame.size.height)
maskLayer.path = path
maskLayer.bounds = path.boundingBox
maskLayer.anchorPoint = anchor
gradientLayer.bounds = maskLayer.bounds
gradientLayer.anchorPoint = anchor
// setup gradient properties
gradientLayer.start = start
gradientLayer.end = end
gradientLayer.numberOfColors = numberOfColors
gradientLayer.colors = colors
gradientLayer.opacity = Float(opacity)
gradientLayer.type = type
}
// MARK: Private
private let gradientLayer = GradientFillLayer()
private let maskLayer = CAShapeLayer()
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientFillRenderer.swift
|
Swift
|
unknown
| 5,631
|
//
// GradientStrokeRenderer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import QuartzCore
// MARK: - Renderer
final class GradientStrokeRenderer: PassThroughOutputNode, Renderable {
// MARK: Lifecycle
override init(parent: NodeOutput?) {
strokeRender = StrokeRenderer(parent: nil)
gradientRender = LegacyGradientFillRenderer(parent: nil)
strokeRender.color = .rgb(1, 1, 1)
super.init(parent: parent)
}
// MARK: Internal
var shouldRenderInContext = true
let strokeRender: StrokeRenderer
let gradientRender: LegacyGradientFillRenderer
override func hasOutputUpdates(_ forFrame: CGFloat) -> Bool {
let updates = super.hasOutputUpdates(forFrame)
return updates || strokeRender.hasUpdate || gradientRender.hasUpdate
}
func updateShapeLayer(layer _: CAShapeLayer) {
/// Not Applicable
}
func setupSublayers(layer _: CAShapeLayer) {
/// Not Applicable
}
func render(_ inContext: CGContext) {
guard inContext.path != nil, inContext.path!.isEmpty == false else {
return
}
strokeRender.hasUpdate = false
hasUpdate = false
gradientRender.hasUpdate = false
strokeRender.setupForStroke(inContext)
inContext.replacePathWithStrokedPath()
/// Now draw the gradient.
gradientRender.render(inContext)
}
func renderBoundsFor(_ boundingBox: CGRect) -> CGRect {
strokeRender.renderBoundsFor(boundingBox)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientStrokeRenderer.swift
|
Swift
|
unknown
| 1,447
|
//
// LegacyGradientFillRenderer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import QuartzCore
/// A rendered for a Path Fill
final class LegacyGradientFillRenderer: PassThroughOutputNode, Renderable {
var shouldRenderInContext = true
var start: CGPoint = .zero {
didSet {
hasUpdate = true
}
}
var numberOfColors = 0 {
didSet {
hasUpdate = true
}
}
var colors: [CGFloat] = [] {
didSet {
hasUpdate = true
}
}
var end: CGPoint = .zero {
didSet {
hasUpdate = true
}
}
var opacity: CGFloat = 0 {
didSet {
hasUpdate = true
}
}
var type: GradientType = .none {
didSet {
hasUpdate = true
}
}
func updateShapeLayer(layer _: CAShapeLayer) {
// Not applicable
}
func setupSublayers(layer _: CAShapeLayer) {
// Not applicable
}
func render(_ inContext: CGContext) {
guard inContext.path != nil, inContext.path!.isEmpty == false else {
return
}
hasUpdate = false
var alphaColors = [CGColor]()
var alphaLocations = [CGFloat]()
var gradientColors = [CGColor]()
var colorLocations = [CGFloat]()
let maskColorSpace = CGColorSpaceCreateDeviceGray()
for i in 0..<numberOfColors {
let ix = i * 4
if colors.count > ix {
let color = CGColor.rgb(colors[ix + 1], colors[ix + 2], colors[ix + 3])
gradientColors.append(color)
colorLocations.append(colors[ix])
}
}
var drawMask = false
for i in stride(from: numberOfColors * 4, to: colors.endIndex, by: 2) {
let alpha = colors[i + 1]
if alpha < 1 {
drawMask = true
}
alphaLocations.append(colors[i])
alphaColors.append(.gray(alpha))
}
inContext.setAlpha(opacity)
inContext.clip()
/// First draw a mask is necessary.
if drawMask {
guard
let maskGradient = CGGradient(
colorsSpace: maskColorSpace,
colors: alphaColors as CFArray,
locations: alphaLocations),
let maskContext = CGContext(
data: nil,
width: inContext.width,
height: inContext.height,
bitsPerComponent: 8,
bytesPerRow: inContext.width,
space: maskColorSpace,
bitmapInfo: 0)
else { return }
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: CGFloat(maskContext.height))
maskContext.concatenate(flipVertical)
maskContext.concatenate(inContext.ctm)
if type == .linear {
maskContext.drawLinearGradient(
maskGradient,
start: start,
end: end,
options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
} else {
maskContext.drawRadialGradient(
maskGradient,
startCenter: start,
startRadius: 0,
endCenter: start,
endRadius: start.distanceTo(end),
options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
}
/// Clips the gradient
if let alphaMask = maskContext.makeImage() {
inContext.clip(to: inContext.boundingBoxOfClipPath, mask: alphaMask)
}
}
/// Now draw the gradient
guard
let gradient = CGGradient(
colorsSpace: LottieConfiguration.shared.colorSpace,
colors: gradientColors as CFArray,
locations: colorLocations)
else { return }
if type == .linear {
inContext.drawLinearGradient(gradient, start: start, end: end, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
} else {
inContext.drawRadialGradient(
gradient,
startCenter: start,
startRadius: 0,
endCenter: start,
endRadius: start.distanceTo(end),
options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/OutputNodes/Renderables/LegacyGradientFillRenderer.swift
|
Swift
|
unknown
| 3,850
|
//
// StrokeRenderer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import QuartzCore
extension LineJoin {
var cgLineJoin: CGLineJoin {
switch self {
case .bevel:
return .bevel
case .none:
return .miter
case .miter:
return .miter
case .round:
return .round
}
}
var caLineJoin: CAShapeLayerLineJoin {
switch self {
case .none:
return CAShapeLayerLineJoin.miter
case .miter:
return CAShapeLayerLineJoin.miter
case .round:
return CAShapeLayerLineJoin.round
case .bevel:
return CAShapeLayerLineJoin.bevel
}
}
}
extension LineCap {
var cgLineCap: CGLineCap {
switch self {
case .none:
return .butt
case .butt:
return .butt
case .round:
return .round
case .square:
return .square
}
}
var caLineCap: CAShapeLayerLineCap {
switch self {
case .none:
return CAShapeLayerLineCap.butt
case .butt:
return CAShapeLayerLineCap.butt
case .round:
return CAShapeLayerLineCap.round
case .square:
return CAShapeLayerLineCap.square
}
}
}
// MARK: - StrokeRenderer
/// A rendered that renders a stroke on a path.
final class StrokeRenderer: PassThroughOutputNode, Renderable {
var shouldRenderInContext = false
var color: CGColor? {
didSet {
hasUpdate = true
}
}
var opacity: CGFloat = 0 {
didSet {
hasUpdate = true
}
}
var width: CGFloat = 0 {
didSet {
hasUpdate = true
}
}
var miterLimit: CGFloat = 0 {
didSet {
hasUpdate = true
}
}
var lineCap: LineCap = .none {
didSet {
hasUpdate = true
}
}
var lineJoin: LineJoin = .none {
didSet {
hasUpdate = true
}
}
var dashPhase: CGFloat? {
didSet {
hasUpdate = true
}
}
var dashLengths: [CGFloat]? {
didSet {
hasUpdate = true
}
}
func setupSublayers(layer _: CAShapeLayer) {
// empty
}
func renderBoundsFor(_ boundingBox: CGRect) -> CGRect {
boundingBox.insetBy(dx: -width, dy: -width)
}
func setupForStroke(_ inContext: CGContext) {
inContext.setLineWidth(width)
inContext.setMiterLimit(miterLimit)
inContext.setLineCap(lineCap.cgLineCap)
inContext.setLineJoin(lineJoin.cgLineJoin)
if let dashPhase, let lengths = dashLengths {
inContext.setLineDash(phase: dashPhase, lengths: lengths)
} else {
inContext.setLineDash(phase: 0, lengths: [])
}
}
func render(_ inContext: CGContext) {
guard inContext.path != nil, inContext.path!.isEmpty == false else {
return
}
guard let color else { return }
hasUpdate = false
setupForStroke(inContext)
inContext.setAlpha(opacity)
inContext.setStrokeColor(color)
inContext.strokePath()
}
func updateShapeLayer(layer: CAShapeLayer) {
layer.strokeColor = color
layer.opacity = Float(opacity)
layer.lineWidth = width
layer.lineJoin = lineJoin.caLineJoin
layer.lineCap = lineCap.caLineCap
layer.lineDashPhase = dashPhase ?? 0
layer.fillColor = nil
if let dashPattern = dashLengths {
layer.lineDashPattern = dashPattern.map { NSNumber(value: Double($0)) }
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/OutputNodes/Renderables/StrokeRenderer.swift
|
Swift
|
unknown
| 3,263
|
//
// EllipseNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/17/19.
//
import Foundation
import QuartzCore
// MARK: - EllipseNodeProperties
final class EllipseNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(ellipse: Ellipse) {
keypathName = ellipse.name
direction = ellipse.direction
position = NodeProperty(provider: KeyframeInterpolator(keyframes: ellipse.position.keyframes))
size = NodeProperty(provider: KeyframeInterpolator(keyframes: ellipse.size.keyframes))
keypathProperties = [
PropertyName.position.rawValue : position,
"Size" : size,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
let direction: PathDirection
let position: NodeProperty<LottieVector3D>
let size: NodeProperty<LottieVector3D>
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
}
// MARK: - EllipseNode
final class EllipseNode: AnimatorNode, PathNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, ellipse: Ellipse) {
pathOutput = PathOutputNode(parent: parentNode?.outputNode)
properties = EllipseNodeProperties(ellipse: ellipse)
self.parentNode = parentNode
}
// MARK: Internal
static let ControlPointConstant: CGFloat = 0.55228
let pathOutput: PathOutputNode
let properties: EllipseNodeProperties
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
var isEnabled = true {
didSet {
pathOutput.isEnabled = isEnabled
}
}
func rebuildOutputs(frame: CGFloat) {
pathOutput.setPath(
.ellipse(
size: properties.size.value.sizeValue,
center: properties.position.value.pointValue,
direction: properties.direction),
updateFrame: frame)
}
}
extension BezierPath {
/// Constructs a `BezierPath` in the shape of an ellipse
static func ellipse(
size: CGSize,
center: CGPoint,
direction: PathDirection)
-> BezierPath
{
// Unfortunately we HAVE to manually build out the ellipse.
// Every Apple method constructs an ellipse from the 3 o-clock position
// After effects constructs from the Noon position.
// After effects does clockwise, but also has a flag for reversed.
var half = size * 0.5
if direction == .counterClockwise {
half.width = half.width * -1
}
let q1 = CGPoint(x: center.x, y: center.y - half.height)
let q2 = CGPoint(x: center.x + half.width, y: center.y)
let q3 = CGPoint(x: center.x, y: center.y + half.height)
let q4 = CGPoint(x: center.x - half.width, y: center.y)
let cp = half * EllipseNode.ControlPointConstant
var path = BezierPath(startPoint: CurveVertex(
point: q1,
inTangentRelative: CGPoint(x: -cp.width, y: 0),
outTangentRelative: CGPoint(x: cp.width, y: 0)))
path.addVertex(CurveVertex(
point: q2,
inTangentRelative: CGPoint(x: 0, y: -cp.height),
outTangentRelative: CGPoint(x: 0, y: cp.height)))
path.addVertex(CurveVertex(
point: q3,
inTangentRelative: CGPoint(x: cp.width, y: 0),
outTangentRelative: CGPoint(x: -cp.width, y: 0)))
path.addVertex(CurveVertex(
point: q4,
inTangentRelative: CGPoint(x: 0, y: cp.height),
outTangentRelative: CGPoint(x: 0, y: -cp.height)))
path.addVertex(CurveVertex(
point: q1,
inTangentRelative: CGPoint(x: -cp.width, y: 0),
outTangentRelative: CGPoint(x: cp.width, y: 0)))
path.close()
return path
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/PathNodes/EllipseNode.swift
|
Swift
|
unknown
| 3,717
|
//
// PolygonNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/21/19.
//
import Foundation
import QuartzCore
// MARK: - PolygonNodeProperties
final class PolygonNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(star: Star) {
keypathName = star.name
direction = star.direction
position = NodeProperty(provider: KeyframeInterpolator(keyframes: star.position.keyframes))
outerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRadius.keyframes))
outerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRoundness.keyframes))
rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: star.rotation.keyframes))
points = NodeProperty(provider: KeyframeInterpolator(keyframes: star.points.keyframes))
keypathProperties = [
PropertyName.position.rawValue : position,
"Outer Radius" : outerRadius,
"Outer Roundedness" : outerRoundedness,
PropertyName.rotation.rawValue : rotation,
"Points" : points,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
var childKeypaths: [KeypathSearchable] = []
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
let direction: PathDirection
let position: NodeProperty<LottieVector3D>
let outerRadius: NodeProperty<LottieVector1D>
let outerRoundedness: NodeProperty<LottieVector1D>
let rotation: NodeProperty<LottieVector1D>
let points: NodeProperty<LottieVector1D>
}
// MARK: - PolygonNode
final class PolygonNode: AnimatorNode, PathNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, star: Star) {
pathOutput = PathOutputNode(parent: parentNode?.outputNode)
properties = PolygonNodeProperties(star: star)
self.parentNode = parentNode
}
// MARK: Internal
/// Magic number needed for constructing path.
static let PolygonConstant: CGFloat = 0.25
let properties: PolygonNodeProperties
let pathOutput: PathOutputNode
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
var isEnabled = true {
didSet {
pathOutput.isEnabled = isEnabled
}
}
func rebuildOutputs(frame: CGFloat) {
let path = BezierPath.polygon(
position: properties.position.value.pointValue,
numberOfPoints: properties.points.value.cgFloatValue,
outerRadius: properties.outerRadius.value.cgFloatValue,
outerRoundedness: properties.outerRoundedness.value.cgFloatValue,
rotation: properties.rotation.value.cgFloatValue,
direction: properties.direction)
pathOutput.setPath(path, updateFrame: frame)
}
}
extension BezierPath {
/// Creates a `BezierPath` in the shape of a polygon
static func polygon(
position: CGPoint,
numberOfPoints: CGFloat,
outerRadius: CGFloat,
outerRoundedness inputOuterRoundedness: CGFloat,
rotation: CGFloat,
direction: PathDirection)
-> BezierPath
{
var currentAngle = (rotation - 90).toRadians()
let anglePerPoint = ((2 * CGFloat.pi) / numberOfPoints)
let outerRoundedness = inputOuterRoundedness * 0.01
var point = CGPoint(
x: outerRadius * cos(currentAngle),
y: outerRadius * sin(currentAngle))
var vertices = [CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero)]
var previousPoint = point
currentAngle += anglePerPoint;
for _ in 0..<Int(ceil(numberOfPoints)) {
previousPoint = point
point = CGPoint(
x: outerRadius * cos(currentAngle),
y: outerRadius * sin(currentAngle))
if outerRoundedness != 0 {
let cp1Theta = (atan2(previousPoint.y, previousPoint.x) - CGFloat.pi / 2)
let cp1Dx = cos(cp1Theta);
let cp1Dy = sin(cp1Theta);
let cp2Theta = (atan2(point.y, point.x) - CGFloat.pi / 2)
let cp2Dx = cos(cp2Theta)
let cp2Dy = sin(cp2Theta)
let cp1 = CGPoint(
x: outerRadius * outerRoundedness * PolygonNode.PolygonConstant * cp1Dx,
y: outerRadius * outerRoundedness * PolygonNode.PolygonConstant * cp1Dy)
let cp2 = CGPoint(
x: outerRadius * outerRoundedness * PolygonNode.PolygonConstant * cp2Dx,
y: outerRadius * outerRoundedness * PolygonNode.PolygonConstant * cp2Dy)
let previousVertex = vertices[vertices.endIndex - 1]
vertices[vertices.endIndex - 1] = CurveVertex(
previousVertex.inTangent,
previousVertex.point,
previousVertex.point - cp1)
vertices.append(CurveVertex(point: point + position, inTangentRelative: cp2, outTangentRelative: .zero))
} else {
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
}
currentAngle += anglePerPoint;
}
let reverse = direction == .counterClockwise
if reverse {
vertices = vertices.reversed()
}
var path = BezierPath()
for vertex in vertices {
path.addVertex(reverse ? vertex.reversed() : vertex)
}
path.close()
return path
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/PathNodes/PolygonNode.swift
|
Swift
|
unknown
| 5,306
|
//
// RectNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/21/19.
//
import CoreGraphics
import Foundation
// MARK: - RectNodeProperties
final class RectNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(rectangle: Rectangle) {
keypathName = rectangle.name
direction = rectangle.direction
position = NodeProperty(provider: KeyframeInterpolator(keyframes: rectangle.position.keyframes))
size = NodeProperty(provider: KeyframeInterpolator(keyframes: rectangle.size.keyframes))
cornerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: rectangle.cornerRadius.keyframes))
keypathProperties = [
PropertyName.position.rawValue : position,
"Size" : size,
"Roundness" : cornerRadius,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
let direction: PathDirection
let position: NodeProperty<LottieVector3D>
let size: NodeProperty<LottieVector3D>
let cornerRadius: NodeProperty<LottieVector1D>
}
// MARK: - RectangleNode
final class RectangleNode: AnimatorNode, PathNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, rectangle: Rectangle) {
properties = RectNodeProperties(rectangle: rectangle)
pathOutput = PathOutputNode(parent: parentNode?.outputNode)
self.parentNode = parentNode
}
// MARK: Internal
let properties: RectNodeProperties
let pathOutput: PathOutputNode
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
var isEnabled = true {
didSet {
pathOutput.isEnabled = isEnabled
}
}
func rebuildOutputs(frame: CGFloat) {
pathOutput.setPath(
.rectangle(
position: properties.position.value.pointValue,
size: properties.size.value.sizeValue,
cornerRadius: properties.cornerRadius.value.cgFloatValue,
direction: properties.direction),
updateFrame: frame)
}
}
// MARK: - BezierPath + rectangle
extension BezierPath {
/// Constructs a `BezierPath` in the shape of a rectangle, optionally with rounded corners
static func rectangle(
position: CGPoint,
size inputSize: CGSize,
cornerRadius: CGFloat,
direction: PathDirection)
-> BezierPath
{
let size = inputSize * 0.5
let radius = min(min(cornerRadius, size.width) , size.height)
var bezierPath = BezierPath()
let points: [CurveVertex]
if radius <= 0 {
/// No Corners
points = [
/// Lead In
CurveVertex(
point: CGPoint(x: size.width, y: -size.height),
inTangentRelative: .zero,
outTangentRelative: .zero)
.translated(position),
/// Corner 1
CurveVertex(
point: CGPoint(x: size.width, y: size.height),
inTangentRelative: .zero,
outTangentRelative: .zero)
.translated(position),
/// Corner 2
CurveVertex(
point: CGPoint(x: -size.width, y: size.height),
inTangentRelative: .zero,
outTangentRelative: .zero)
.translated(position),
/// Corner 3
CurveVertex(
point: CGPoint(x: -size.width, y: -size.height),
inTangentRelative: .zero,
outTangentRelative: .zero)
.translated(position),
/// Corner 4
CurveVertex(
point: CGPoint(x: size.width, y: -size.height),
inTangentRelative: .zero,
outTangentRelative: .zero)
.translated(position),
]
} else {
let controlPoint = radius * EllipseNode.ControlPointConstant
points = [
/// Lead In
CurveVertex(
CGPoint(x: radius, y: 0),
CGPoint(x: radius, y: 0),
CGPoint(x: radius, y: 0))
.translated(CGPoint(x: -radius, y: radius))
.translated(CGPoint(x: size.width, y: -size.height))
.translated(position),
/// Corner 1
CurveVertex(
CGPoint(x: radius, y: 0), // In tangent
CGPoint(x: radius, y: 0), // Point
CGPoint(x: radius, y: controlPoint))
.translated(CGPoint(x: -radius, y: -radius))
.translated(CGPoint(x: size.width, y: size.height))
.translated(position),
CurveVertex(
CGPoint(x: controlPoint, y: radius), // In tangent
CGPoint(x: 0, y: radius), // Point
CGPoint(x: 0, y: radius)) // Out Tangent
.translated(CGPoint(x: -radius, y: -radius))
.translated(CGPoint(x: size.width, y: size.height))
.translated(position),
/// Corner 2
CurveVertex(
CGPoint(x: 0, y: radius), // In tangent
CGPoint(x: 0, y: radius), // Point
CGPoint(x: -controlPoint, y: radius)) // Out tangent
.translated(CGPoint(x: radius, y: -radius))
.translated(CGPoint(x: -size.width, y: size.height))
.translated(position),
CurveVertex(
CGPoint(x: -radius, y: controlPoint), // In tangent
CGPoint(x: -radius, y: 0), // Point
CGPoint(x: -radius, y: 0)) // Out tangent
.translated(CGPoint(x: radius, y: -radius))
.translated(CGPoint(x: -size.width, y: size.height))
.translated(position),
/// Corner 3
CurveVertex(
CGPoint(x: -radius, y: 0), // In tangent
CGPoint(x: -radius, y: 0), // Point
CGPoint(x: -radius, y: -controlPoint)) // Out tangent
.translated(CGPoint(x: radius, y: radius))
.translated(CGPoint(x: -size.width, y: -size.height))
.translated(position),
CurveVertex(
CGPoint(x: -controlPoint, y: -radius), // In tangent
CGPoint(x: 0, y: -radius), // Point
CGPoint(x: 0, y: -radius)) // Out tangent
.translated(CGPoint(x: radius, y: radius))
.translated(CGPoint(x: -size.width, y: -size.height))
.translated(position),
/// Corner 4
CurveVertex(
CGPoint(x: 0, y: -radius), // In tangent
CGPoint(x: 0, y: -radius), // Point
CGPoint(x: controlPoint, y: -radius)) // Out tangent
.translated(CGPoint(x: -radius, y: radius))
.translated(CGPoint(x: size.width, y: -size.height))
.translated(position),
CurveVertex(
CGPoint(x: radius, y: -controlPoint), // In tangent
CGPoint(x: radius, y: 0), // Point
CGPoint(x: radius, y: 0)) // Out tangent
.translated(CGPoint(x: -radius, y: radius))
.translated(CGPoint(x: size.width, y: -size.height))
.translated(position),
]
}
let reversed = direction == .counterClockwise
let pathPoints = reversed ? points.reversed() : points
for point in pathPoints {
bezierPath.addVertex(reversed ? point.reversed() : point)
}
bezierPath.close()
return bezierPath
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/PathNodes/RectNode.swift
|
Swift
|
unknown
| 7,159
|
//
// PathNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/16/19.
//
import CoreGraphics
import Foundation
// MARK: - ShapeNodeProperties
final class ShapeNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(shape: Shape) {
keypathName = shape.name
path = NodeProperty(provider: KeyframeInterpolator(keyframes: shape.path.keyframes))
keypathProperties = [
"Path" : path,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
let path: NodeProperty<BezierPath>
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
}
// MARK: - ShapeNode
final class ShapeNode: AnimatorNode, PathNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, shape: Shape) {
pathOutput = PathOutputNode(parent: parentNode?.outputNode)
properties = ShapeNodeProperties(shape: shape)
self.parentNode = parentNode
}
// MARK: Internal
let properties: ShapeNodeProperties
let pathOutput: PathOutputNode
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
var isEnabled = true {
didSet {
pathOutput.isEnabled = isEnabled
}
}
func rebuildOutputs(frame: CGFloat) {
pathOutput.setPath(properties.path.value, updateFrame: frame)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/PathNodes/ShapeNode.swift
|
Swift
|
unknown
| 1,504
|
//
// StarNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/21/19.
//
import Foundation
import QuartzCore
// MARK: - StarNodeProperties
final class StarNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(star: Star) {
keypathName = star.name
direction = star.direction
position = NodeProperty(provider: KeyframeInterpolator(keyframes: star.position.keyframes))
outerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRadius.keyframes))
outerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRoundness.keyframes))
if let innerRadiusKeyframes = star.innerRadius?.keyframes {
innerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: innerRadiusKeyframes))
} else {
innerRadius = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
}
if let innderRoundedness = star.innerRoundness?.keyframes {
innerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: innderRoundedness))
} else {
innerRoundedness = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
}
rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: star.rotation.keyframes))
points = NodeProperty(provider: KeyframeInterpolator(keyframes: star.points.keyframes))
keypathProperties = [
PropertyName.position.rawValue : position,
"Outer Radius" : outerRadius,
"Outer Roundedness" : outerRoundedness,
"Inner Radius" : innerRadius,
"Inner Roundedness" : innerRoundedness,
PropertyName.rotation.rawValue : rotation,
"Points" : points,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
let direction: PathDirection
let position: NodeProperty<LottieVector3D>
let outerRadius: NodeProperty<LottieVector1D>
let outerRoundedness: NodeProperty<LottieVector1D>
let innerRadius: NodeProperty<LottieVector1D>
let innerRoundedness: NodeProperty<LottieVector1D>
let rotation: NodeProperty<LottieVector1D>
let points: NodeProperty<LottieVector1D>
}
// MARK: - StarNode
final class StarNode: AnimatorNode, PathNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, star: Star) {
pathOutput = PathOutputNode(parent: parentNode?.outputNode)
properties = StarNodeProperties(star: star)
self.parentNode = parentNode
}
// MARK: Internal
/// Magic number needed for building path data
static let PolystarConstant: CGFloat = 0.47829
let properties: StarNodeProperties
let pathOutput: PathOutputNode
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
var isEnabled = true {
didSet {
pathOutput.isEnabled = isEnabled
}
}
func rebuildOutputs(frame: CGFloat) {
let path = BezierPath.star(
position: properties.position.value.pointValue,
outerRadius: properties.outerRadius.value.cgFloatValue,
innerRadius: properties.innerRadius.value.cgFloatValue,
outerRoundedness: properties.outerRoundedness.value.cgFloatValue,
innerRoundedness: properties.innerRoundedness.value.cgFloatValue,
numberOfPoints: properties.points.value.cgFloatValue,
rotation: properties.rotation.value.cgFloatValue,
direction: properties.direction)
pathOutput.setPath(path, updateFrame: frame)
}
}
extension BezierPath {
/// Constructs a `BezierPath` in the shape of a star
static func star(
position: CGPoint,
outerRadius: CGFloat,
innerRadius: CGFloat,
outerRoundedness inoutOuterRoundedness: CGFloat,
innerRoundedness inputInnerRoundedness: CGFloat,
numberOfPoints: CGFloat,
rotation: CGFloat,
direction: PathDirection)
-> BezierPath
{
var currentAngle = (rotation - 90).toRadians()
let anglePerPoint = (2 * CGFloat.pi) / numberOfPoints
let halfAnglePerPoint = anglePerPoint / 2.0
let partialPointAmount = numberOfPoints - floor(numberOfPoints)
let outerRoundedness = inoutOuterRoundedness * 0.01
let innerRoundedness = inputInnerRoundedness * 0.01
var point: CGPoint = .zero
var partialPointRadius: CGFloat = 0
if partialPointAmount != 0 {
currentAngle += halfAnglePerPoint * (1 - partialPointAmount)
partialPointRadius = innerRadius + partialPointAmount * (outerRadius - innerRadius)
point.x = (partialPointRadius * cos(currentAngle))
point.y = (partialPointRadius * sin(currentAngle))
currentAngle += anglePerPoint * partialPointAmount / 2
} else {
point.x = (outerRadius * cos(currentAngle))
point.y = (outerRadius * sin(currentAngle))
currentAngle += halfAnglePerPoint
}
var vertices = [CurveVertex]()
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
var previousPoint = point
var longSegment = false
let numPoints = Int(ceil(numberOfPoints) * 2)
for i in 0..<numPoints {
var radius = longSegment ? outerRadius : innerRadius
var dTheta = halfAnglePerPoint
if partialPointRadius != 0, i == numPoints - 2 {
dTheta = anglePerPoint * partialPointAmount / 2
}
if partialPointRadius != 0, i == numPoints - 1 {
radius = partialPointRadius
}
previousPoint = point
point.x = (radius * cos(currentAngle))
point.y = (radius * sin(currentAngle))
if innerRoundedness == 0, outerRoundedness == 0 {
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
} else {
let cp1Theta = (atan2(previousPoint.y, previousPoint.x) - CGFloat.pi / 2)
let cp1Dx = cos(cp1Theta)
let cp1Dy = sin(cp1Theta)
let cp2Theta = (atan2(point.y, point.x) - CGFloat.pi / 2)
let cp2Dx = cos(cp2Theta)
let cp2Dy = sin(cp2Theta)
let cp1Roundedness = longSegment ? innerRoundedness : outerRoundedness
let cp2Roundedness = longSegment ? outerRoundedness : innerRoundedness
let cp1Radius = longSegment ? innerRadius : outerRadius
let cp2Radius = longSegment ? outerRadius : innerRadius
var cp1 = CGPoint(
x: cp1Radius * cp1Roundedness * StarNode.PolystarConstant * cp1Dx,
y: cp1Radius * cp1Roundedness * StarNode.PolystarConstant * cp1Dy)
var cp2 = CGPoint(
x: cp2Radius * cp2Roundedness * StarNode.PolystarConstant * cp2Dx,
y: cp2Radius * cp2Roundedness * StarNode.PolystarConstant * cp2Dy)
if partialPointAmount != 0 {
if i == 0 {
cp1 = cp1 * partialPointAmount
} else if i == numPoints - 1 {
cp2 = cp2 * partialPointAmount
}
}
let previousVertex = vertices[vertices.endIndex - 1]
vertices[vertices.endIndex - 1] = CurveVertex(
previousVertex.inTangent,
previousVertex.point,
previousVertex.point - cp1)
vertices.append(CurveVertex(point: point + position, inTangentRelative: cp2, outTangentRelative: .zero))
}
currentAngle += dTheta
longSegment = !longSegment
}
let reverse = direction == .counterClockwise
if reverse {
vertices = vertices.reversed()
}
var path = BezierPath()
for vertex in vertices {
path.addVertex(reverse ? vertex.reversed() : vertex)
}
path.close()
return path
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/PathNodes/StarNode.swift
|
Swift
|
unknown
| 7,696
|
//
// GroupNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/18/19.
//
import QuartzCore
// MARK: - GroupNodeProperties
final class GroupNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(transform: ShapeTransform?) {
if let transform {
anchor = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.anchor.keyframes))
position = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.position.keyframes))
scale = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.scale.keyframes))
rotationX = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.rotationX.keyframes))
rotationY = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.rotationY.keyframes))
rotationZ = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.rotationZ.keyframes))
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.opacity.keyframes))
skew = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.skew.keyframes))
skewAxis = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.skewAxis.keyframes))
} else {
/// Transform node missing. Default to empty transform.
anchor = NodeProperty(provider: SingleValueProvider(LottieVector3D(x: CGFloat(0), y: CGFloat(0), z: CGFloat(0))))
position = NodeProperty(provider: SingleValueProvider(LottieVector3D(x: CGFloat(0), y: CGFloat(0), z: CGFloat(0))))
scale = NodeProperty(provider: SingleValueProvider(LottieVector3D(x: CGFloat(100), y: CGFloat(100), z: CGFloat(100))))
rotationX = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
rotationY = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
rotationZ = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
opacity = NodeProperty(provider: SingleValueProvider(LottieVector1D(100)))
skew = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
skewAxis = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
}
keypathProperties = [
"Anchor Point" : anchor,
PropertyName.position.rawValue : position,
PropertyName.scale.rawValue : scale,
PropertyName.rotation.rawValue : rotationZ,
"Rotation X" : rotationX,
"Rotation Y" : rotationY,
"Rotation Z" : rotationZ,
PropertyName.opacity.rawValue : opacity,
"Skew" : skew,
"Skew Axis" : skewAxis,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName = "Transform"
var childKeypaths: [KeypathSearchable] = []
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
let anchor: NodeProperty<LottieVector3D>
let position: NodeProperty<LottieVector3D>
let scale: NodeProperty<LottieVector3D>
let rotationX: NodeProperty<LottieVector1D>
let rotationY: NodeProperty<LottieVector1D>
let rotationZ: NodeProperty<LottieVector1D>
let opacity: NodeProperty<LottieVector1D>
let skew: NodeProperty<LottieVector1D>
let skewAxis: NodeProperty<LottieVector1D>
var caTransform: CATransform3D {
CATransform3D.makeTransform(
anchor: anchor.value.pointValue,
position: position.value.pointValue,
scale: scale.value.sizeValue,
rotationX: rotationX.value.cgFloatValue,
rotationY: rotationY.value.cgFloatValue,
rotationZ: rotationZ.value.cgFloatValue,
skew: skew.value.cgFloatValue,
skewAxis: skewAxis.value.cgFloatValue)
}
}
// MARK: - GroupNode
final class GroupNode: AnimatorNode {
// MARK: Lifecycle
// MARK: Initializer
init(name: String, parentNode: AnimatorNode?, tree: NodeTree) {
self.parentNode = parentNode
keypathName = name
rootNode = tree.rootNode
properties = GroupNodeProperties(transform: tree.transform)
groupOutput = GroupOutputNode(parent: parentNode?.outputNode, rootNode: rootNode?.outputNode)
var childKeypaths: [KeypathSearchable] = tree.childrenNodes
childKeypaths.append(properties)
self.childKeypaths = childKeypaths
for childContainer in tree.renderContainers {
container.insertRenderLayer(childContainer)
}
}
// MARK: Internal
// MARK: Properties
let groupOutput: GroupOutputNode
let properties: GroupNodeProperties
let rootNode: AnimatorNode?
var container = ShapeContainerLayer()
// MARK: Keypath Searchable
let keypathName: String
let childKeypaths: [KeypathSearchable]
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var keypathLayer: CALayer? {
container
}
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
var outputNode: NodeOutput {
groupOutput
}
var isEnabled = true {
didSet {
container.isHidden = !isEnabled
}
}
func performAdditionalLocalUpdates(frame: CGFloat, forceLocalUpdate: Bool) -> Bool {
rootNode?.updateContents(frame, forceLocalUpdate: forceLocalUpdate) ?? false
}
func performAdditionalOutputUpdates(_ frame: CGFloat, forceOutputUpdate: Bool) {
rootNode?.updateOutputs(frame, forceOutputUpdate: forceOutputUpdate)
}
func rebuildOutputs(frame: CGFloat) {
container.opacity = Float(properties.opacity.value.cgFloatValue) * 0.01
container.transform = properties.caTransform
groupOutput.setTransform(container.transform, forFrame: frame)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/RenderContainers/GroupNode.swift
|
Swift
|
unknown
| 5,562
|
//
// FillNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/17/19.
//
import CoreGraphics
import Foundation
// MARK: - FillNodeProperties
final class FillNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(fill: Fill) {
keypathName = fill.name
color = NodeProperty(provider: KeyframeInterpolator(keyframes: fill.color.keyframes))
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: fill.opacity.keyframes))
type = fill.fillRule
keypathProperties = [
PropertyName.opacity.rawValue : opacity,
PropertyName.color.rawValue : color,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
let opacity: NodeProperty<LottieVector1D>
let color: NodeProperty<LottieColor>
let type: FillRule
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
}
// MARK: - FillNode
final class FillNode: AnimatorNode, RenderNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, fill: Fill) {
fillRender = FillRenderer(parent: parentNode?.outputNode)
fillProperties = FillNodeProperties(fill: fill)
self.parentNode = parentNode
}
// MARK: Internal
let fillRender: FillRenderer
let fillProperties: FillNodeProperties
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var renderer: NodeOutput & Renderable {
fillRender
}
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
fillProperties
}
var isEnabled = true {
didSet {
fillRender.isEnabled = isEnabled
}
}
func localUpdatesPermeateDownstream() -> Bool {
false
}
func rebuildOutputs(frame _: CGFloat) {
fillRender.color = fillProperties.color.value.cgColorValue
fillRender.opacity = fillProperties.opacity.value.cgFloatValue * 0.01
fillRender.fillRule = fillProperties.type
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/RenderNodes/FillNode.swift
|
Swift
|
unknown
| 2,013
|
//
// GradientFillNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/22/19.
//
import Foundation
import QuartzCore
// MARK: - GradientFillProperties
final class GradientFillProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(gradientfill: GradientFill) {
keypathName = gradientfill.name
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.opacity.keyframes))
startPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.startPoint.keyframes))
endPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.endPoint.keyframes))
colors = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.colors.keyframes))
gradientType = gradientfill.gradientType
numberOfColors = gradientfill.numberOfColors
fillRule = gradientfill.fillRule
keypathProperties = [
PropertyName.opacity.rawValue : opacity,
"Start Point" : startPoint,
"End Point" : endPoint,
PropertyName.gradientColors.rawValue : colors,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
let opacity: NodeProperty<LottieVector1D>
let startPoint: NodeProperty<LottieVector3D>
let endPoint: NodeProperty<LottieVector3D>
let colors: NodeProperty<[Double]>
let gradientType: GradientType
let numberOfColors: Int
let fillRule: FillRule
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
}
// MARK: - GradientFillNode
final class GradientFillNode: AnimatorNode, RenderNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, gradientFill: GradientFill) {
fillRender = GradientFillRenderer(parent: parentNode?.outputNode)
fillProperties = GradientFillProperties(gradientfill: gradientFill)
self.parentNode = parentNode
}
// MARK: Internal
let fillRender: GradientFillRenderer
let fillProperties: GradientFillProperties
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var renderer: NodeOutput & Renderable {
fillRender
}
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
fillProperties
}
var isEnabled = true {
didSet {
fillRender.isEnabled = isEnabled
}
}
func localUpdatesPermeateDownstream() -> Bool {
false
}
func rebuildOutputs(frame _: CGFloat) {
fillRender.start = fillProperties.startPoint.value.pointValue
fillRender.end = fillProperties.endPoint.value.pointValue
fillRender.opacity = fillProperties.opacity.value.cgFloatValue * 0.01
fillRender.colors = fillProperties.colors.value.map { CGFloat($0) }
fillRender.type = fillProperties.gradientType
fillRender.numberOfColors = fillProperties.numberOfColors
fillRender.fillRule = fillProperties.fillRule.caFillRule
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/RenderNodes/GradientFillNode.swift
|
Swift
|
unknown
| 2,951
|
//
// GradientStrokeNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/23/19.
//
import CoreGraphics
import Foundation
// MARK: - GradientStrokeProperties
final class GradientStrokeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(gradientStroke: GradientStroke) {
keypathName = gradientStroke.name
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.opacity.keyframes))
startPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.startPoint.keyframes))
endPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.endPoint.keyframes))
colors = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.colors.keyframes))
gradientType = gradientStroke.gradientType
numberOfColors = gradientStroke.numberOfColors
width = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.width.keyframes))
miterLimit = CGFloat(gradientStroke.miterLimit)
lineCap = gradientStroke.lineCap
lineJoin = gradientStroke.lineJoin
if let dashes = gradientStroke.dashPattern {
var dashPatterns = ContiguousArray<ContiguousArray<Keyframe<LottieVector1D>>>()
var dashPhase = ContiguousArray<Keyframe<LottieVector1D>>()
for dash in dashes {
if dash.type == .offset {
dashPhase = dash.value.keyframes
} else {
dashPatterns.append(dash.value.keyframes)
}
}
dashPattern = NodeProperty(provider: GroupInterpolator(keyframeGroups: dashPatterns))
self.dashPhase = NodeProperty(provider: KeyframeInterpolator(keyframes: dashPhase))
} else {
dashPattern = NodeProperty(provider: SingleValueProvider([LottieVector1D]()))
dashPhase = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
}
keypathProperties = [
PropertyName.opacity.rawValue : opacity,
"Start Point" : startPoint,
"End Point" : endPoint,
PropertyName.gradientColors.rawValue : colors,
PropertyName.strokeWidth.rawValue : width,
"Dashes" : dashPattern,
"Dash Phase" : dashPhase,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
let opacity: NodeProperty<LottieVector1D>
let startPoint: NodeProperty<LottieVector3D>
let endPoint: NodeProperty<LottieVector3D>
let colors: NodeProperty<[Double]>
let width: NodeProperty<LottieVector1D>
let dashPattern: NodeProperty<[LottieVector1D]>
let dashPhase: NodeProperty<LottieVector1D>
let lineCap: LineCap
let lineJoin: LineJoin
let miterLimit: CGFloat
let gradientType: GradientType
let numberOfColors: Int
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
}
// MARK: - GradientStrokeNode
final class GradientStrokeNode: AnimatorNode, RenderNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, gradientStroke: GradientStroke) {
strokeRender = GradientStrokeRenderer(parent: parentNode?.outputNode)
strokeProperties = GradientStrokeProperties(gradientStroke: gradientStroke)
self.parentNode = parentNode
}
// MARK: Internal
let strokeRender: GradientStrokeRenderer
let strokeProperties: GradientStrokeProperties
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var renderer: NodeOutput & Renderable {
strokeRender
}
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
strokeProperties
}
var isEnabled = true {
didSet {
strokeRender.isEnabled = isEnabled
}
}
func localUpdatesPermeateDownstream() -> Bool {
false
}
func rebuildOutputs(frame _: CGFloat) {
/// Update gradient properties
strokeRender.gradientRender.start = strokeProperties.startPoint.value.pointValue
strokeRender.gradientRender.end = strokeProperties.endPoint.value.pointValue
strokeRender.gradientRender.opacity = strokeProperties.opacity.value.cgFloatValue
strokeRender.gradientRender.colors = strokeProperties.colors.value.map { CGFloat($0) }
strokeRender.gradientRender.type = strokeProperties.gradientType
strokeRender.gradientRender.numberOfColors = strokeProperties.numberOfColors
/// Now update stroke properties
strokeRender.strokeRender.opacity = strokeProperties.opacity.value.cgFloatValue
strokeRender.strokeRender.width = strokeProperties.width.value.cgFloatValue
strokeRender.strokeRender.miterLimit = strokeProperties.miterLimit
strokeRender.strokeRender.lineCap = strokeProperties.lineCap
strokeRender.strokeRender.lineJoin = strokeProperties.lineJoin
/// Get dash lengths
let dashLengths = strokeProperties.dashPattern.value.map { $0.cgFloatValue }
if dashLengths.count > 0, dashLengths.isSupportedLayerDashPattern {
strokeRender.strokeRender.dashPhase = strokeProperties.dashPhase.value.cgFloatValue
strokeRender.strokeRender.dashLengths = dashLengths
} else {
strokeRender.strokeRender.dashLengths = nil
strokeRender.strokeRender.dashPhase = nil
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/RenderNodes/GradientStrokeNode.swift
|
Swift
|
unknown
| 5,190
|
//
// StrokeNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/22/19.
//
import Foundation
import QuartzCore
// MARK: - StrokeNodeProperties
final class StrokeNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(stroke: Stroke) {
keypathName = stroke.name
color = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.color.keyframes))
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.opacity.keyframes))
width = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.width.keyframes))
miterLimit = CGFloat(stroke.miterLimit)
lineCap = stroke.lineCap
lineJoin = stroke.lineJoin
if let dashes = stroke.dashPattern {
let (dashPatterns, dashPhase) = dashes.shapeLayerConfiguration
dashPattern = NodeProperty(provider: GroupInterpolator(keyframeGroups: dashPatterns))
if dashPhase.count == 0 {
self.dashPhase = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
} else {
self.dashPhase = NodeProperty(provider: KeyframeInterpolator(keyframes: dashPhase))
}
} else {
dashPattern = NodeProperty(provider: SingleValueProvider([LottieVector1D]()))
dashPhase = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
}
keypathProperties = [
PropertyName.opacity.rawValue : opacity,
PropertyName.color.rawValue : color,
PropertyName.strokeWidth.rawValue : width,
"Dashes" : dashPattern,
"Dash Phase" : dashPhase,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
let keypathName: String
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
let opacity: NodeProperty<LottieVector1D>
let color: NodeProperty<LottieColor>
let width: NodeProperty<LottieVector1D>
let dashPattern: NodeProperty<[LottieVector1D]>
let dashPhase: NodeProperty<LottieVector1D>
let lineCap: LineCap
let lineJoin: LineJoin
let miterLimit: CGFloat
}
// MARK: - StrokeNode
/// Node that manages stroking a path
final class StrokeNode: AnimatorNode, RenderNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, stroke: Stroke) {
strokeRender = StrokeRenderer(parent: parentNode?.outputNode)
strokeProperties = StrokeNodeProperties(stroke: stroke)
self.parentNode = parentNode
}
// MARK: Internal
let strokeRender: StrokeRenderer
let strokeProperties: StrokeNodeProperties
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var renderer: NodeOutput & Renderable {
strokeRender
}
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
strokeProperties
}
var isEnabled = true {
didSet {
strokeRender.isEnabled = isEnabled
}
}
func localUpdatesPermeateDownstream() -> Bool {
false
}
func rebuildOutputs(frame _: CGFloat) {
strokeRender.color = strokeProperties.color.value.cgColorValue
strokeRender.opacity = strokeProperties.opacity.value.cgFloatValue * 0.01
strokeRender.width = strokeProperties.width.value.cgFloatValue
strokeRender.miterLimit = strokeProperties.miterLimit
strokeRender.lineCap = strokeProperties.lineCap
strokeRender.lineJoin = strokeProperties.lineJoin
/// Get dash lengths
let dashLengths = strokeProperties.dashPattern.value.map { $0.cgFloatValue }
if dashLengths.count > 0, dashLengths.isSupportedLayerDashPattern {
strokeRender.dashPhase = strokeProperties.dashPhase.value.cgFloatValue
strokeRender.dashLengths = dashLengths
} else {
strokeRender.dashLengths = nil
strokeRender.dashPhase = nil
}
}
}
// MARK: - [DashElement] + shapeLayerConfiguration
extension [DashElement] {
typealias ShapeLayerConfiguration = (
dashPatterns: ContiguousArray<ContiguousArray<Keyframe<LottieVector1D>>>,
dashPhase: ContiguousArray<Keyframe<LottieVector1D>>)
/// Converts the `[DashElement]` data model into `lineDashPattern` and `lineDashPhase`
/// representations usable in a `CAShapeLayer`
var shapeLayerConfiguration: ShapeLayerConfiguration {
var dashPatterns = ContiguousArray<ContiguousArray<Keyframe<LottieVector1D>>>()
var dashPhase = ContiguousArray<Keyframe<LottieVector1D>>()
for dash in self {
if dash.type == .offset {
dashPhase = dash.value.keyframes
} else {
dashPatterns.append(dash.value.keyframes)
}
}
dashPatterns = ContiguousArray(dashPatterns.map { pattern in
ContiguousArray(pattern.map { keyframe -> Keyframe<LottieVector1D> in
// The recommended way to create a stroke of round dots, in theory,
// is to use a value of 0 followed by the stroke width, but for
// some reason Core Animation incorrectly (?) renders these as pills
// instead of circles. As a workaround, for parity with Lottie on other
// platforms, we can change `0`s to `0.01`: https://stackoverflow.com/a/38036486
if keyframe.value.cgFloatValue == 0 {
return keyframe.withValue(LottieVector1D(0.01))
} else {
return keyframe
}
})
})
return (dashPatterns, dashPhase)
}
}
extension [CGFloat] {
// If all of the items in the dash pattern are zeros, then we shouldn't attempt to render it.
// This causes Core Animation to have extremely poor performance for some reason, even though
// it doesn't affect the appearance of the animation.
// - We check for `== 0.01` instead of `== 0` because `dashPattern.shapeLayerConfiguration`
// converts all `0` values to `0.01` to work around a different Core Animation rendering issue.
var isSupportedLayerDashPattern: Bool {
!allSatisfy { $0 == 0.01 }
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/RenderNodes/StrokeNode.swift
|
Swift
|
unknown
| 5,854
|
//
// TextAnimatorNode.swift
// lottie-ios-iOS
//
// Created by Brandon Withrow on 2/19/19.
//
import QuartzCore
// MARK: - TextAnimatorNodeProperties
final class TextAnimatorNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(textAnimator: TextAnimator) {
keypathName = textAnimator.name
var properties = [String : AnyNodeProperty]()
if let keyframeGroup = textAnimator.anchor {
anchor = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Anchor"] = anchor
} else {
anchor = nil
}
if let keyframeGroup = textAnimator.position {
position = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties[PropertyName.position.rawValue] = position
} else {
position = nil
}
if let keyframeGroup = textAnimator.scale {
scale = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties[PropertyName.scale.rawValue] = scale
} else {
scale = nil
}
if let keyframeGroup = textAnimator.skew {
skew = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Skew"] = skew
} else {
skew = nil
}
if let keyframeGroup = textAnimator.skewAxis {
skewAxis = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Skew Axis"] = skewAxis
} else {
skewAxis = nil
}
if let keyframeGroup = textAnimator.rotationX {
rotationX = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Rotation X"] = rotationX
} else {
rotationX = nil
}
if let keyframeGroup = textAnimator.rotationY {
rotationY = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Rotation Y"] = rotationY
} else {
rotationY = nil
}
if let keyframeGroup = textAnimator.rotationZ {
rotationZ = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Rotation Z"] = rotationZ
properties[PropertyName.rotation.rawValue] = rotationZ
} else {
rotationZ = nil
}
if let keyframeGroup = textAnimator.opacity {
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties[PropertyName.opacity.rawValue] = opacity
} else {
opacity = nil
}
if let keyframeGroup = textAnimator.strokeColor {
strokeColor = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Stroke Color"] = strokeColor
} else {
strokeColor = nil
}
if let keyframeGroup = textAnimator.fillColor {
fillColor = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Fill Color"] = fillColor
} else {
fillColor = nil
}
if let keyframeGroup = textAnimator.strokeWidth {
strokeWidth = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties[PropertyName.strokeWidth.rawValue] = strokeWidth
} else {
strokeWidth = nil
}
if let keyframeGroup = textAnimator.tracking {
tracking = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Tracking"] = tracking
} else {
tracking = nil
}
keypathProperties = properties
self.properties = Array(keypathProperties.values)
}
// MARK: Internal
let keypathName: String
let anchor: NodeProperty<LottieVector3D>?
let position: NodeProperty<LottieVector3D>?
let scale: NodeProperty<LottieVector3D>?
let skew: NodeProperty<LottieVector1D>?
let skewAxis: NodeProperty<LottieVector1D>?
let rotationX: NodeProperty<LottieVector1D>?
let rotationY: NodeProperty<LottieVector1D>?
let rotationZ: NodeProperty<LottieVector1D>?
let opacity: NodeProperty<LottieVector1D>?
let strokeColor: NodeProperty<LottieColor>?
let fillColor: NodeProperty<LottieColor>?
let strokeWidth: NodeProperty<LottieVector1D>?
let tracking: NodeProperty<LottieVector1D>?
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
var caTransform: CATransform3D {
CATransform3D.makeTransform(
anchor: anchor?.value.pointValue ?? .zero,
position: position?.value.pointValue ?? .zero,
scale: scale?.value.sizeValue ?? CGSize(width: 100, height: 100),
rotationX: rotationX?.value.cgFloatValue ?? 0,
rotationY: rotationY?.value.cgFloatValue ?? 0,
rotationZ: rotationZ?.value.cgFloatValue ?? 0,
skew: skew?.value.cgFloatValue,
skewAxis: skewAxis?.value.cgFloatValue)
}
}
// MARK: - TextOutputNode
final class TextOutputNode: NodeOutput {
// MARK: Lifecycle
init(parent: TextOutputNode?) {
parentTextNode = parent
}
// MARK: Internal
var parentTextNode: TextOutputNode?
var isEnabled = true
var outputPath: CGPath?
var parent: NodeOutput? {
parentTextNode
}
var xform: CATransform3D {
get {
_xform ?? parentTextNode?.xform ?? CATransform3DIdentity
}
set {
_xform = newValue
}
}
var opacity: CGFloat {
get {
_opacity ?? parentTextNode?.opacity ?? 1
}
set {
_opacity = newValue
}
}
var strokeColor: CGColor? {
get {
_strokeColor ?? parentTextNode?.strokeColor
}
set {
_strokeColor = newValue
}
}
var fillColor: CGColor? {
get {
_fillColor ?? parentTextNode?.fillColor
}
set {
_fillColor = newValue
}
}
var tracking: CGFloat {
get {
_tracking ?? parentTextNode?.tracking ?? 0
}
set {
_tracking = newValue
}
}
var strokeWidth: CGFloat {
get {
_strokeWidth ?? parentTextNode?.strokeWidth ?? 0
}
set {
_strokeWidth = newValue
}
}
func hasOutputUpdates(_: CGFloat) -> Bool {
// TODO Fix This
true
}
// MARK: Fileprivate
fileprivate var _xform: CATransform3D?
fileprivate var _opacity: CGFloat?
fileprivate var _strokeColor: CGColor?
fileprivate var _fillColor: CGColor?
fileprivate var _tracking: CGFloat?
fileprivate var _strokeWidth: CGFloat?
}
// MARK: - TextAnimatorNode
class TextAnimatorNode: AnimatorNode {
// MARK: Lifecycle
init(parentNode: TextAnimatorNode?, textAnimator: TextAnimator) {
textOutputNode = TextOutputNode(parent: parentNode?.textOutputNode)
textAnimatorProperties = TextAnimatorNodeProperties(textAnimator: textAnimator)
self.parentNode = parentNode
}
// MARK: Internal
let textOutputNode: TextOutputNode
let textAnimatorProperties: TextAnimatorNodeProperties
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var isEnabled = true
var outputNode: NodeOutput {
textOutputNode
}
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
textAnimatorProperties
}
func localUpdatesPermeateDownstream() -> Bool {
true
}
func rebuildOutputs(frame _: CGFloat) {
textOutputNode.xform = textAnimatorProperties.caTransform
textOutputNode.opacity = (textAnimatorProperties.opacity?.value.cgFloatValue ?? 100) * 0.01
textOutputNode.strokeColor = textAnimatorProperties.strokeColor?.value.cgColorValue
textOutputNode.fillColor = textAnimatorProperties.fillColor?.value.cgColorValue
textOutputNode.tracking = textAnimatorProperties.tracking?.value.cgFloatValue ?? 1
textOutputNode.strokeWidth = textAnimatorProperties.strokeWidth?.value.cgFloatValue ?? 0
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Nodes/Text/TextAnimatorNode.swift
|
Swift
|
unknown
| 7,791
|
//
// AnimatorNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/15/19.
//
import QuartzCore
// MARK: - NodeOutput
/// Defines the basic outputs of an animator node.
///
protocol NodeOutput {
/// The parent node.
var parent: NodeOutput? { get }
/// Returns true if there are any updates upstream. OutputPath must be built before returning.
func hasOutputUpdates(_ forFrame: CGFloat) -> Bool
var outputPath: CGPath? { get }
var isEnabled: Bool { get set }
}
// MARK: - AnimatorNode
/// The Animator Node is the base node in the render system tree.
///
/// It defines a single node that has an output path and option input node.
/// At animation time the root animation node is asked to update its contents for
/// the current frame.
/// The node reaches up its chain of nodes until the first node that does not need
/// updating is found. Then each node updates its contents down the render pipeline.
/// Each node adds its local path to its input path and passes it forward.
///
/// An animator node holds a group of interpolators. These interpolators determine
/// if the node needs an update for the current frame.
///
protocol AnimatorNode: AnyObject, KeypathSearchable {
/// The available properties of the Node.
///
/// These properties are automatically updated each frame.
/// These properties are also settable and gettable through the dynamic
/// property system.
///
var propertyMap: NodePropertyMap & KeypathSearchable { get }
/// The upstream input node
var parentNode: AnimatorNode? { get }
/// The output of the node.
var outputNode: NodeOutput { get }
/// Update the outputs of the node. Called if local contents were update or if outputsNeedUpdate returns true.
func rebuildOutputs(frame: CGFloat)
/// Setters for marking current node state.
var isEnabled: Bool { get set }
var hasLocalUpdates: Bool { get set }
var hasUpstreamUpdates: Bool { get set }
var lastUpdateFrame: CGFloat? { get set }
// MARK: Optional
/// Marks if updates to this node affect nodes downstream.
func localUpdatesPermeateDownstream() -> Bool
func forceUpstreamOutputUpdates() -> Bool
/// Called at the end of this nodes update cycle. Always called. Optional.
func performAdditionalLocalUpdates(frame: CGFloat, forceLocalUpdate: Bool) -> Bool
func performAdditionalOutputUpdates(_ frame: CGFloat, forceOutputUpdate: Bool)
/// The default simply returns `hasLocalUpdates`
func shouldRebuildOutputs(frame: CGFloat) -> Bool
}
/// Basic Node Logic
extension AnimatorNode {
func shouldRebuildOutputs(frame _: CGFloat) -> Bool {
hasLocalUpdates
}
func localUpdatesPermeateDownstream() -> Bool {
/// Optional override
true
}
func forceUpstreamOutputUpdates() -> Bool {
/// Optional
false
}
func performAdditionalLocalUpdates(frame _: CGFloat, forceLocalUpdate: Bool) -> Bool {
/// Optional
forceLocalUpdate
}
func performAdditionalOutputUpdates(_: CGFloat, forceOutputUpdate _: Bool) {
/// Optional
}
@discardableResult
func updateOutputs(_ frame: CGFloat, forceOutputUpdate: Bool) -> Bool {
guard isEnabled else {
// Disabled node, pass through.
lastUpdateFrame = frame
return parentNode?.updateOutputs(frame, forceOutputUpdate: forceOutputUpdate) ?? false
}
if forceOutputUpdate == false && lastUpdateFrame != nil && lastUpdateFrame! == frame {
/// This node has already updated for this frame. Go ahead and return the results.
return hasUpstreamUpdates || hasLocalUpdates
}
/// Ask if this node should force output updates upstream.
let forceUpstreamUpdates = forceOutputUpdate || forceUpstreamOutputUpdates()
/// Perform upstream output updates. Optionally mark upstream updates if any.
hasUpstreamUpdates = (
parentNode?
.updateOutputs(frame, forceOutputUpdate: forceUpstreamUpdates) ?? false || hasUpstreamUpdates)
/// Perform additional local output updates
performAdditionalOutputUpdates(frame, forceOutputUpdate: forceUpstreamUpdates)
/// If there are local updates, or if updates have been force, rebuild outputs
if forceUpstreamUpdates || shouldRebuildOutputs(frame: frame) {
lastUpdateFrame = frame
rebuildOutputs(frame: frame)
}
return hasUpstreamUpdates || hasLocalUpdates
}
/// Rebuilds the content of this node, and upstream nodes if necessary.
@discardableResult
func updateContents(_ frame: CGFloat, forceLocalUpdate: Bool) -> Bool {
guard isEnabled else {
// Disabled node, pass through.
return parentNode?.updateContents(frame, forceLocalUpdate: forceLocalUpdate) ?? false
}
if forceLocalUpdate == false && lastUpdateFrame != nil && lastUpdateFrame! == frame {
/// This node has already updated for this frame. Go ahead and return the results.
return localUpdatesPermeateDownstream() ? hasUpstreamUpdates || hasLocalUpdates : hasUpstreamUpdates
}
/// Are there local updates? If so mark the node.
hasLocalUpdates = forceLocalUpdate ? forceLocalUpdate : propertyMap.needsLocalUpdate(frame: frame)
/// Were there upstream updates? If so mark the node
hasUpstreamUpdates = parentNode?.updateContents(frame, forceLocalUpdate: forceLocalUpdate) ?? false
/// Perform property updates if necessary.
if hasLocalUpdates {
/// Rebuild local properties
propertyMap.updateNodeProperties(frame: frame)
}
/// Ask the node to perform any other updates it might have.
hasUpstreamUpdates = performAdditionalLocalUpdates(frame: frame, forceLocalUpdate: forceLocalUpdate) || hasUpstreamUpdates
/// If the node can update nodes downstream, notify them, otherwise pass on any upstream updates downstream.
return localUpdatesPermeateDownstream() ? hasUpstreamUpdates || hasLocalUpdates : hasUpstreamUpdates
}
func updateTree(_ frame: CGFloat, forceUpdates: Bool = false) {
updateContents(frame, forceLocalUpdate: forceUpdates)
updateOutputs(frame, forceOutputUpdate: forceUpdates)
}
}
extension AnimatorNode {
/// Default implementation for Keypath searchable.
/// Forward all calls to the propertyMap.
var keypathName: String {
propertyMap.keypathName
}
var keypathProperties: [String: AnyNodeProperty] {
propertyMap.keypathProperties
}
var childKeypaths: [KeypathSearchable] {
propertyMap.childKeypaths
}
var keypathLayer: CALayer? {
nil
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Protocols/AnimatorNode.swift
|
Swift
|
unknown
| 6,476
|
//
// PathNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/17/19.
//
// MARK: - PathNode
protocol PathNode {
var pathOutput: PathOutputNode { get }
}
extension PathNode where Self: AnimatorNode {
var outputNode: NodeOutput {
pathOutput
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Protocols/PathNode.swift
|
Swift
|
unknown
| 274
|
//
// RenderNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/17/19.
//
import QuartzCore
// MARK: - RenderNode
/// A protocol that defines a node that holds render instructions
protocol RenderNode {
var renderer: Renderable & NodeOutput { get }
}
// MARK: - Renderable
/// A protocol that defines anything with render instructions
protocol Renderable {
/// The last frame in which this node was updated.
var hasUpdate: Bool { get }
func hasRenderUpdates(_ forFrame: CGFloat) -> Bool
/// Determines if the renderer requires a custom context for drawing.
/// If yes the shape layer will perform a custom drawing pass.
/// If no the shape layer will be a standard CAShapeLayer
var shouldRenderInContext: Bool { get }
/// Passes in the CAShapeLayer to update
func updateShapeLayer(layer: CAShapeLayer)
/// Asks the renderer what the renderable bounds is for the given box.
func renderBoundsFor(_ boundingBox: CGRect) -> CGRect
/// Opportunity for renderers to inject sublayers
func setupSublayers(layer: CAShapeLayer)
/// Renders the shape in a custom context
func render(_ inContext: CGContext)
}
extension RenderNode where Self: AnimatorNode {
var outputNode: NodeOutput {
renderer
}
}
extension Renderable {
func renderBoundsFor(_ boundingBox: CGRect) -> CGRect {
/// Optional
boundingBox
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/Protocols/RenderNode.swift
|
Swift
|
unknown
| 1,381
|
//
// ShapeContainerLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import QuartzCore
/// The base layer that holds Shapes and Shape Renderers
class ShapeContainerLayer: CALayer {
// MARK: Lifecycle
override init() {
super.init()
actions = [
"position" : NSNull(),
"bounds" : NSNull(),
"anchorPoint" : NSNull(),
"transform" : NSNull(),
"opacity" : NSNull(),
"hidden" : NSNull(),
]
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(layer: Any) {
guard let layer = layer as? ShapeContainerLayer else {
fatalError("init(layer:) wrong class.")
}
super.init(layer: layer)
}
// MARK: Internal
private(set) var renderLayers: [ShapeContainerLayer] = []
var renderScale: CGFloat = 1 {
didSet {
updateRenderScale()
}
}
func insertRenderLayer(_ layer: ShapeContainerLayer) {
renderLayers.append(layer)
insertSublayer(layer, at: 0)
}
func markRenderUpdates(forFrame: CGFloat) {
if hasRenderUpdate(forFrame: forFrame) {
rebuildContents(forFrame: forFrame)
}
guard isHidden == false else { return }
for renderLayer in renderLayers {
renderLayer.markRenderUpdates(forFrame: forFrame)
}
}
func hasRenderUpdate(forFrame _: CGFloat) -> Bool {
false
}
func rebuildContents(forFrame _: CGFloat) {
/// Override
}
func updateRenderScale() {
contentsScale = renderScale
for renderLayer in renderLayers {
renderLayer.renderScale = renderScale
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/RenderLayers/ShapeContainerLayer.swift
|
Swift
|
unknown
| 1,618
|
//
// RenderLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/18/19.
//
import QuartzCore
/// The layer responsible for rendering shape objects
final class ShapeRenderLayer: ShapeContainerLayer {
// MARK: Lifecycle
init(renderer: Renderable & NodeOutput) {
self.renderer = renderer
super.init()
anchorPoint = .zero
actions = [
"position" : NSNull(),
"bounds" : NSNull(),
"anchorPoint" : NSNull(),
"path" : NSNull(),
"transform" : NSNull(),
"opacity" : NSNull(),
"hidden" : NSNull(),
]
shapeLayer.actions = [
"position" : NSNull(),
"bounds" : NSNull(),
"anchorPoint" : NSNull(),
"path" : NSNull(),
"fillColor" : NSNull(),
"strokeColor" : NSNull(),
"lineWidth" : NSNull(),
"miterLimit" : NSNull(),
"lineDashPhase" : NSNull(),
"opacity": NSNull(),
"hidden" : NSNull(),
]
addSublayer(shapeLayer)
renderer.setupSublayers(layer: shapeLayer)
}
override init(layer: Any) {
guard let layer = layer as? ShapeRenderLayer else {
fatalError("init(layer:) wrong class.")
}
renderer = layer.renderer
super.init(layer: layer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
fileprivate(set) var renderer: Renderable & NodeOutput
let shapeLayer = CAShapeLayer()
override func hasRenderUpdate(forFrame: CGFloat) -> Bool {
isHidden = !renderer.isEnabled
guard isHidden == false else { return false }
return renderer.hasRenderUpdates(forFrame)
}
override func rebuildContents(forFrame _: CGFloat) {
if renderer.shouldRenderInContext {
if let newPath = renderer.outputPath {
bounds = renderer.renderBoundsFor(newPath.boundingBox)
} else {
bounds = .zero
}
position = bounds.origin
setNeedsDisplay()
} else {
shapeLayer.path = renderer.outputPath
renderer.updateShapeLayer(layer: shapeLayer)
}
}
override func draw(in ctx: CGContext) {
if let path = renderer.outputPath {
if !path.isEmpty {
ctx.addPath(path)
}
}
renderer.render(ctx)
}
override func updateRenderScale() {
super.updateRenderScale()
shapeLayer.contentsScale = renderScale
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/MainThread/NodeRenderSystem/RenderLayers/ShapeRenderLayer.swift
|
Swift
|
unknown
| 2,341
|
//
// Asset.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
// MARK: - Asset
public class Asset: Codable, DictionaryInitializable {
// MARK: Lifecycle
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Asset.CodingKeys.self)
if let id = try? container.decode(String.self, forKey: .id) {
self.id = id
} else {
id = String(try container.decode(Int.self, forKey: .id))
}
}
required init(dictionary: [String: Any]) throws {
if let id = dictionary[CodingKeys.id.rawValue] as? String {
self.id = id
} else if let id = dictionary[CodingKeys.id.rawValue] as? Int {
self.id = String(id)
} else {
throw InitializableError.invalidInput()
}
}
// MARK: Public
/// The ID of the asset
public let id: String
// MARK: Private
private enum CodingKeys: String, CodingKey {
case id
}
}
// MARK: Sendable
/// Since `Asset` isn't `final`, we have to use `@unchecked Sendable` instead of `Sendable.`
/// All `Asset` subclasses are immutable `Sendable` values.
// swiftlint:disable:next no_unchecked_sendable
extension Asset: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Assets/Asset.swift
|
Swift
|
unknown
| 1,199
|
//
// AssetLibrary.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
final class AssetLibrary: Codable, AnyInitializable, Sendable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var containerForKeys = container
var decodedAssets = [String : Asset]()
var imageAssets = [String : ImageAsset]()
var precompAssets = [String : PrecompAsset]()
while
!container.isAtEnd,
let keyContainer = try? containerForKeys.nestedContainer(keyedBy: PrecompAsset.CodingKeys.self)
{
if
keyContainer.contains(.layers),
let precompAsset = try? container.decode(PrecompAsset.self)
{
decodedAssets[precompAsset.id] = precompAsset
precompAssets[precompAsset.id] = precompAsset
} else if let imageAsset = try? container.decode(ImageAsset.self) {
decodedAssets[imageAsset.id] = imageAsset
imageAssets[imageAsset.id] = imageAsset
}
}
assets = decodedAssets
self.precompAssets = precompAssets
self.imageAssets = imageAssets
}
init(value: Any) throws {
guard let dictionaries = value as? [[String: Any]] else {
throw InitializableError.invalidInput()
}
var decodedAssets = [String : Asset]()
var imageAssets = [String : ImageAsset]()
var precompAssets = [String : PrecompAsset]()
for dictionary in dictionaries {
if dictionary[PrecompAsset.CodingKeys.layers.rawValue] != nil {
let asset = try PrecompAsset(dictionary: dictionary)
decodedAssets[asset.id] = asset
precompAssets[asset.id] = asset
} else if let asset = try? ImageAsset(dictionary: dictionary) {
decodedAssets[asset.id] = asset
imageAssets[asset.id] = asset
}
}
assets = decodedAssets
self.precompAssets = precompAssets
self.imageAssets = imageAssets
}
// MARK: Internal
/// The Assets
let assets: [String: Asset]
let imageAssets: [String: ImageAsset]
let precompAssets: [String: PrecompAsset]
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(contentsOf: Array(assets.values))
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Assets/AssetLibrary.swift
|
Swift
|
unknown
| 2,233
|
//
// ImageAsset.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
import CoreGraphics
import Foundation
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
// MARK: - ImageAsset
public final class ImageAsset: Asset {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ImageAsset.CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
directory = try container.decode(String.self, forKey: .directory)
width = try container.decode(Double.self, forKey: .width)
height = try container.decode(Double.self, forKey: .height)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
name = try dictionary.value(for: CodingKeys.name)
directory = try dictionary.value(for: CodingKeys.directory)
width = try dictionary.value(for: CodingKeys.width)
height = try dictionary.value(for: CodingKeys.height)
try super.init(dictionary: dictionary)
}
// MARK: Public
/// Image name
public let name: String
/// Image Directory
public let directory: String
/// Image Size
public let width: Double
public let height: Double
override public func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(directory, forKey: .directory)
try container.encode(width, forKey: .width)
try container.encode(height, forKey: .height)
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case name = "p"
case directory = "u"
case width = "w"
case height = "h"
}
}
extension Data {
// MARK: Lifecycle
/// Initializes `Data` from an `ImageAsset`.
///
/// Returns nil when the input is not recognized as valid Data URL.
/// - parameter imageAsset: The image asset that contains Data URL.
init?(imageAsset: ImageAsset) {
self.init(dataString: imageAsset.name)
}
/// Initializes `Data` from a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) String.
///
/// Returns nil when the input is not recognized as valid Data URL.
/// - parameter dataString: The data string to parse.
/// - parameter options: Options for the string parsing. Default value is `[]`.
init?(dataString: String, options: DataURLReadOptions = []) {
let trimmedDataString = dataString.trimmingCharacters(in: .whitespacesAndNewlines)
guard
dataString.hasPrefix("data:"),
let url = URL(string: trimmedDataString)
else {
return nil
}
// The code below is needed because Data(contentsOf:) floods logs
// with messages since url doesn't have a host. This only fixes flooding logs
// when data inside Data URL is base64 encoded.
if
let base64Range = trimmedDataString.range(of: ";base64,"),
!options.contains(DataURLReadOptions.legacy)
{
let encodedString = String(trimmedDataString[base64Range.upperBound...])
self.init(base64Encoded: encodedString)
} else {
try? self.init(contentsOf: url)
}
}
// MARK: Internal
struct DataURLReadOptions: OptionSet {
let rawValue: Int
/// Will read Data URL using Data(contentsOf:)
static let legacy = DataURLReadOptions(rawValue: 1 << 0)
}
}
extension ImageAsset {
/// A `CGImage` loaded from this asset if represented using a Base 64 encoding
var base64Image: CGImage? {
guard let data = Data(imageAsset: self) else { return nil }
#if canImport(UIKit)
return UIImage(data: data)?.cgImage
#elseif canImport(AppKit)
return NSImage(data: data)?.lottie_CGImage
#endif
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Assets/ImageAsset.swift
|
Swift
|
unknown
| 3,777
|
//
// PrecompAsset.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
final class PrecompAsset: Asset {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PrecompAsset.CodingKeys.self)
layers = try container.decode([LayerModel].self, ofFamily: LayerType.self, forKey: .layers)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let layerDictionaries: [[String: Any]] = try dictionary.value(for: CodingKeys.layers)
layers = try [LayerModel].fromDictionaries(layerDictionaries)
try super.init(dictionary: dictionary)
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case layers
}
/// Layers of the precomp
let layers: [LayerModel]
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(layers, forKey: .layers)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Assets/PrecompAsset.swift
|
Swift
|
unknown
| 1,013
|
//
// DictionaryInitializable.swift
// Lottie
//
// Created by Marcelo Fabri on 5/5/22.
//
// MARK: - InitializableError
enum InitializableError: Error {
case invalidInput(file: StaticString = #file, line: UInt = #line)
}
// MARK: - DictionaryInitializable
protocol DictionaryInitializable {
init(dictionary: [String: Any]) throws
}
// MARK: - AnyInitializable
protocol AnyInitializable {
init(value: Any) throws
}
extension Dictionary {
@_disfavoredOverload
func value<T, KeyType: RawRepresentable>(
for key: KeyType,
file: StaticString = #file,
line: UInt = #line)
throws -> T where KeyType.RawValue == Key
{
guard let value = self[key.rawValue] as? T else {
throw InitializableError.invalidInput(file: file, line: line)
}
return value
}
func value<T: AnyInitializable, KeyType: RawRepresentable>(
for key: KeyType,
file: StaticString = #file,
line: UInt = #line)
throws -> T where KeyType.RawValue == Key
{
if let value = self[key.rawValue] as? T {
return value
}
if let value = self[key.rawValue] {
return try T(value: value)
}
throw InitializableError.invalidInput(file: file, line: line)
}
}
// MARK: - AnyInitializable + AnyInitializable
extension [Double]: AnyInitializable {
init(value: Any) throws {
guard let array = value as? [Double] else {
throw InitializableError.invalidInput()
}
self = array
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/DictionaryInitializable.swift
|
Swift
|
unknown
| 1,460
|
//
// DotLottieAnimation.swift
// Pods
//
// Created by Evandro Harrison Hoffmann on 28/06/2021.
//
import Foundation
// MARK: - DotLottieAnimation
struct DotLottieAnimation: Codable {
/// Id of Animation
var id: String
/// Loop enabled
var loop: Bool? = false
/// Animation Playback Speed
var speed: Double? = 1
/// 1 or -1
var direction: Int? = 1
/// mode - "bounce" | "normal"
var mode: DotLottieAnimationMode? = .normal
/// Loop mode for animation
var loopMode: LottieLoopMode {
switch mode {
case .bounce:
return .autoReverse
case .normal, nil:
return (loop ?? false) ? .loop : .playOnce
}
}
/// Animation speed
var animationSpeed: Double {
(speed ?? 1) * Double(direction ?? 1)
}
/// Loads `LottieAnimation` from `animationUrl`
/// - Returns: Deserialized `LottieAnimation`. Optional.
func animation(url: URL) throws -> LottieAnimation {
let animationUrl = url.appendingPathComponent("\(id).json")
let data = try Data(contentsOf: animationUrl)
return try LottieAnimation.from(data: data)
}
}
// MARK: - DotLottieAnimationMode
enum DotLottieAnimationMode: String, Codable {
case normal
case bounce
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/DotLottie/DotLottieAnimation.swift
|
Swift
|
unknown
| 1,205
|
//
// DotLottieImageProvider.swift
// Lottie
//
// Created by Evandro Hoffmann on 20/10/22.
//
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
// MARK: - DotLottieImageProvider
/// An image provider that loads the images from a DotLottieFile into memory
class DotLottieImageProvider: AnimationImageProvider {
// MARK: Lifecycle
/// Initializes an image provider with a specific filepath.
///
/// - Parameter filepath: The absolute filepath containing the images.
///
convenience init?(filepath: String) {
self.init(filepath: URL(fileURLWithPath: filepath))
}
init?(filepath: URL) {
guard filepath.urls.count > 0 else { return nil }
self.filepath = filepath
loadImages()
}
// MARK: Internal
let filepath: URL
func imageForAsset(asset: ImageAsset) -> CGImage? {
if let base64Image = asset.base64Image {
return base64Image
}
return images[asset.name]
}
// MARK: Private
/// This is intentionally a Dictionary instead of an NSCache. Files from a decompressed dotLottie zip archive
/// are only valid are deleted after being read into memory. If we used an NSCache then the OS could evict
/// the cache entries when under memory pressure, and we would have no way to reload them later.
/// - Ideally we would have a way to remove image data when under memory pressure, but this would require
/// re-decompressing the dotLottie file when requesting an image that has been loaded but then removed.
private var images = [String: CGImage]()
private func loadImages() {
for url in filepath.urls {
#if canImport(UIKit)
if
let data = try? Data(contentsOf: url),
let image = UIImage(data: data)?.cgImage
{
images[url.lastPathComponent] = image
}
#elseif canImport(AppKit)
if
let data = try? Data(contentsOf: url),
let image = NSImage(data: data)?.lottie_CGImage
{
images[url.lastPathComponent] = image
}
#endif
}
}
}
// MARK: Hashable
extension DotLottieImageProvider: Hashable {
static func ==(_ lhs: DotLottieImageProvider, _ rhs: DotLottieImageProvider) -> Bool {
lhs.filepath == rhs.filepath
}
func hash(into hasher: inout Hasher) {
hasher.combine(filepath)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/DotLottie/DotLottieImageProvider.swift
|
Swift
|
unknown
| 2,315
|
//
// DotLottieManifest.swift
// Lottie
//
// Created by Evandro Harrison Hoffmann on 27/06/2020.
//
import Foundation
/// Manifest model for .lottie File
struct DotLottieManifest: Codable {
var animations: [DotLottieAnimation]
var version: String?
var author: String?
var generator: String?
/// Decodes data to Manifest model
/// - Parameter data: Data to decode
/// - Throws: Error
/// - Returns: .lottie Manifest model
static func decode(from data: Data) throws -> DotLottieManifest {
try JSONDecoder().decode(DotLottieManifest.self, from: data)
}
/// Loads manifest from given URL
/// - Parameter path: URL path to Manifest
/// - Returns: Manifest Model
static func load(from url: URL) throws -> DotLottieManifest {
let data = try Data(contentsOf: url)
return try decode(from: data)
}
/// Encodes to data
/// - Parameter encoder: JSONEncoder
/// - Throws: Error
/// - Returns: encoded Data
func encode(with encoder: JSONEncoder = JSONEncoder()) throws -> Data {
try encoder.encode(self)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/DotLottie/DotLottieManifest.swift
|
Swift
|
unknown
| 1,060
|
//
// DotLottieUtils.swift
// Lottie
//
// Created by Evandro Harrison Hoffmann on 27/06/2020.
//
import Foundation
// MARK: - DotLottieUtils
enum DotLottieUtils {
static let dotLottieExtension = "lottie"
static let jsonExtension = "json"
/// Temp folder to app directory
static var tempDirectoryURL: URL {
if #available(iOS 10.0, macOS 10.12, *) {
return FileManager.default.temporaryDirectory
}
return URL(fileURLWithPath: NSTemporaryDirectory())
}
}
extension URL {
/// Checks if url is a lottie file
var isDotLottie: Bool {
pathExtension == DotLottieUtils.dotLottieExtension
}
/// Checks if url is a json file
var isJsonFile: Bool {
pathExtension == DotLottieUtils.jsonExtension
}
var urls: [URL] {
FileManager.default.urls(for: self) ?? []
}
}
extension FileManager {
/// Lists urls for all files in a directory
/// - Parameters:
/// - url: URL of directory to search
/// - skipsHiddenFiles: If should or not show hidden files
/// - Returns: Returns urls of all files matching criteria in the directory
func urls(for url: URL, skipsHiddenFiles: Bool = true) -> [URL]? {
try? contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [])
}
}
// MARK: - DotLottieError
public enum DotLottieError: Error {
/// URL response has no data.
case noDataLoaded
/// Asset with this name was not found in the provided bundle.
case assetNotFound(name: String, bundle: Bundle?)
/// Animation loading from asset is not supported on macOS 10.10.
case loadingFromAssetNotSupported
@available(*, deprecated, message: "Unused")
case invalidFileFormat
@available(*, deprecated, message: "Unused")
case invalidData
@available(*, deprecated, message: "Unused")
case animationNotAvailable
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/DotLottie/DotLottieUtils.swift
|
Swift
|
unknown
| 1,836
|
import Foundation
#if canImport(UIKit)
import UIKit
#endif
extension Bundle {
func getAnimationData(_ name: String, subdirectory: String? = nil) throws -> Data {
// Check for files in the bundle at the given path
let name = name.removingJSONSuffix()
if let url = url(forResource: name, withExtension: "json", subdirectory: subdirectory) {
return try Data(contentsOf: url)
}
// Check for data assets
let assetKey = subdirectory != nil ? "\(subdirectory ?? "")/\(name)" : name
return try Data(assetName: assetKey, in: self)
}
func dotLottieData(_ name: String, subdirectory: String? = nil) throws -> Data {
// Check for files in the bundle at the given path
let name = name.removingDotLottieSuffix()
if let url = url(forResource: name, withExtension: "lottie", subdirectory: subdirectory) {
return try Data(contentsOf: url)
}
let assetKey = subdirectory != nil ? "\(subdirectory ?? "")/\(name)" : name
return try Data(assetName: assetKey, in: self)
}
}
extension String {
fileprivate func removingJSONSuffix() -> String {
// Allow filenames to be passed with a ".json" extension (but not other extensions)
// to keep the behavior from Lottie 2.x - instead of failing to load the animation
guard hasSuffix(".json") else {
return self
}
return (self as NSString).deletingPathExtension
}
fileprivate func removingDotLottieSuffix() -> String {
// Allow filenames to be passed with a ".lottie" extension (but not other extensions)
// to keep the behavior from Lottie 2.x - instead of failing to load the file
guard hasSuffix(".lottie") else {
return self
}
return (self as NSString).deletingPathExtension
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Extensions/Bundle.swift
|
Swift
|
unknown
| 1,742
|
// From: https://medium.com/@kewindannerfjordremeczki/swift-4-0-decodable-heterogeneous-collections-ecc0e6b468cf
// MARK: - ClassFamily
/// To support a new class family, create an enum that conforms to this protocol and contains the different types.
protocol ClassFamily: Decodable {
/// The discriminator key.
static var discriminator: Discriminator { get }
/// The "unknown" fallback case if the type discriminator could not be parsed successfully.
static var unknown: Self { get }
/// Returns the class type of the object corresponding to the value.
func getType() -> AnyObject.Type
}
// MARK: - Discriminator
/// Discriminator key enum used to retrieve discriminator fields in JSON payloads.
enum Discriminator: String, CodingKey {
case type = "ty"
}
extension KeyedDecodingContainer {
/// Decode a heterogeneous list of objects for a given family.
/// - Parameters:
/// - heterogeneousType: The decodable type of the list.
/// - family: The ClassFamily enum for the type family.
/// - key: The CodingKey to look up the list in the current container.
/// - Returns: The resulting list of heterogeneousType elements.
func decode<T: Decodable, U: ClassFamily>(_: [T].Type, ofFamily family: U.Type, forKey key: K) throws -> [T] {
var container = try nestedUnkeyedContainer(forKey: key)
var list = [T]()
var tmpContainer = container
while !container.isAtEnd {
let typeContainer = try container.nestedContainer(keyedBy: Discriminator.self)
let family: U = (try? typeContainer.decodeIfPresent(U.self, forKey: U.discriminator)) ?? .unknown
if let type = family.getType() as? T.Type {
list.append(try tmpContainer.decode(type))
}
}
return list
}
/// Decode a heterogeneous list of objects for a given family if the given key is present.
/// - Parameters:
/// - heterogeneousType: The decodable type of the list.
/// - family: The ClassFamily enum for the type family.
/// - key: The CodingKey to look up the list in the current container.
/// - Returns: The resulting list of heterogeneousType elements.
func decodeIfPresent<T: Decodable, U: ClassFamily>(_: [T].Type, ofFamily family: U.Type, forKey key: K) throws -> [T]? {
var container: UnkeyedDecodingContainer
do {
container = try nestedUnkeyedContainer(forKey: key)
} catch {
return nil
}
var list = [T]()
var tmpContainer = container
while !container.isAtEnd {
let typeContainer = try container.nestedContainer(keyedBy: Discriminator.self)
let family: U = (try? typeContainer.decodeIfPresent(U.self, forKey: U.discriminator)) ?? .unknown
if let type = family.getType() as? T.Type {
list.append(try tmpContainer.decode(type))
}
}
return list
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Extensions/KeyedDecodingContainerExtensions.swift
|
Swift
|
unknown
| 2,815
|
//
// Keyframe.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/7/19.
//
// MARK: - KeyframeData
/// A generic class used to parse and remap keyframe json.
///
/// Keyframe json has a couple of different variations and formats depending on the
/// type of keyframea and also the version of the JSON. By parsing the raw data
/// we can reconfigure it into a constant format.
final class KeyframeData<T> {
// MARK: Lifecycle
init(
startValue: T?,
endValue: T?,
time: AnimationFrameTime?,
hold: Int?,
inTangent: LottieVector2D?,
outTangent: LottieVector2D?,
spatialInTangent: LottieVector3D?,
spatialOutTangent: LottieVector3D?)
{
self.startValue = startValue
self.endValue = endValue
self.time = time
self.hold = hold
self.inTangent = inTangent
self.outTangent = outTangent
self.spatialInTangent = spatialInTangent
self.spatialOutTangent = spatialOutTangent
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case startValue = "s"
case endValue = "e"
case time = "t"
case hold = "h"
case inTangent = "i"
case outTangent = "o"
case spatialInTangent = "ti"
case spatialOutTangent = "to"
}
/// The start value of the keyframe
let startValue: T?
/// The End value of the keyframe. Note: Newer versions animation json do not have this field.
let endValue: T?
/// The time in frames of the keyframe.
let time: AnimationFrameTime?
/// A hold keyframe freezes interpolation until the next keyframe that is not a hold.
let hold: Int?
/// The in tangent for the time interpolation curve.
let inTangent: LottieVector2D?
/// The out tangent for the time interpolation curve.
let outTangent: LottieVector2D?
/// The spacial in tangent of the vector.
let spatialInTangent: LottieVector3D?
/// The spacial out tangent of the vector.
let spatialOutTangent: LottieVector3D?
var isHold: Bool {
if let hold {
return hold > 0
}
return false
}
}
// MARK: Encodable
extension KeyframeData: Encodable where T: Encodable { }
// MARK: Decodable
extension KeyframeData: Decodable where T: Decodable { }
// MARK: DictionaryInitializable
extension KeyframeData: DictionaryInitializable where T: AnyInitializable {
convenience init(dictionary: [String: Any]) throws {
let startValue = try? dictionary[CodingKeys.startValue.rawValue].flatMap(T.init)
let endValue = try? dictionary[CodingKeys.endValue.rawValue].flatMap(T.init)
let time: AnimationFrameTime? = try? dictionary.value(for: CodingKeys.time)
let hold: Int? = try? dictionary.value(for: CodingKeys.hold)
let inTangent: LottieVector2D? = try? dictionary.value(for: CodingKeys.inTangent)
let outTangent: LottieVector2D? = try? dictionary.value(for: CodingKeys.outTangent)
let spatialInTangent: LottieVector3D? = try? dictionary.value(for: CodingKeys.spatialInTangent)
let spatialOutTangent: LottieVector3D? = try? dictionary.value(for: CodingKeys.spatialOutTangent)
self.init(
startValue: startValue,
endValue: endValue,
time: time,
hold: hold,
inTangent: inTangent,
outTangent: outTangent,
spatialInTangent: spatialInTangent,
spatialOutTangent: spatialOutTangent)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Keyframes/KeyframeData.swift
|
Swift
|
unknown
| 3,284
|