repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kingloveyy/SwiftBlog
SwiftBlog/SwiftBlog/Classes/BusinessModel/StatusesData.swift
1
1275
// // StatusesData.swift // SwiftBlog // // Created by King on 15/3/19. // Copyright (c) 2015年 king. All rights reserved. // import UIKit /// 微博数据列表模型 class StatusesData: NSObject { /// 微博记录数组 var statuses: [Status]? /// 微博总数 var total_number: Int = 0 /// 未读数辆 var has_unread: Int = 0 } /// 微博模型 class Status: NSObject, DictModelProtocol { /// 微博创建时间 var created_at: String? /// 微博ID var id: Int = 0 /// 微博信息内容 var text: String? /// 微博来源 var source: String? /// 转发数 var reposts_count: Int = 0 /// 评论数 var comments_count: Int = 0 /// 表态数 var attitudes_count: Int = 0 /// 配图数组 var pic_urls: [StatusPictureURL]? /// 用户信息 var user: UserInfo? /// 转发微博 var retweeted_status: Status? static func customeClassMapping() -> [String : String]? { return ["pic_urls": "\(StatusPictureURL.self)", "user": "\(UserInfo.self)", "retweeted_status": "\(Status.self)"] } } /// 微博配图模型 class StatusPictureURL: NSObject { /// 缩略图 URL var thumbnail_pic: String? }
mit
760a81811beef3b9303360a68451cede
19.089286
61
0.559111
3.338279
false
false
false
false
DevaLee/LYCSwiftDemo
LYCSwiftDemo/Classes/Base/LYCTabbarViewController.swift
1
2533
// // LYCTabbarViewController.swift // LYCSwiftDemo // // Created by yuchen.li on 2017/6/7. // Copyright © 2017年 zsc. All rights reserved. // import UIKit class LYCTabbarViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - 初始化方法 func setup() { UITabBar.appearance().tintColor = UIColor.white let mainVC = LYCSharedViewController().mainViewController() mainVC.tabBarItem = createTabbarItem(titleString: "首页", imageName: "live-n", selectImageName: "live-p") addChildVC(childVC: mainVC) // let ranking-p let rankingVC = LYCSharedViewController().rankViewController() rankingVC.tabBarItem = createTabbarItem(titleString: "排行", imageName: "ranking-n", selectImageName: "ranking-p") addChildVC(childVC: rankingVC) let discorverVC = LYCSharedViewController().discorverViewController() discorverVC.tabBarItem = createTabbarItem(titleString: "发现", imageName: "found-n", selectImageName: "found-p") addChildVC(childVC: discorverVC) let meVC = LYCSharedViewController().meViewController() meVC.tabBarItem = createTabbarItem(titleString: "我", imageName: "mine-n", selectImageName: "mine-p") addChildVC(childVC: meVC) self.selectedIndex = 0 } // 创建Item func createTabbarItem(titleString : String ,imageName : String, selectImageName : String) -> (UITabBarItem) { let preimage = UIImage(named : imageName)?.withRenderingMode(.alwaysOriginal) let selectImage = UIImage(named : selectImageName)?.withRenderingMode(.alwaysOriginal) let barItem = UITabBarItem.init(title: titleString, image: preimage, selectedImage: selectImage) barItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.init(r: 191, g: 138, b: 82)], for: .selected) barItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.black], for: .normal) return barItem; } // 添加 子控制器 func addChildVC(childVC : UIViewController){ let nav = LYCNavigationViewController.init(rootViewController: childVC) self.addChildViewController(nav) } }
mit
eb5c166dcb97749269e939e42384ceca
37.307692
126
0.675502
4.834951
false
false
false
false
a7ex/SwiftDTO
SwiftDTO/Payload/Dictionary+Keypath.swift
1
3148
// // Dictionary+Keypath.swift // ParseTester // // Created by Alex Apprime on 20.05.17. // Copyright © 2017 apprime. All rights reserved. // import Foundation extension Dictionary where Key == String { func value(forKeyPath keyPath: String) -> Any? { guard !keyPath.isEmpty else { return nil } let keys = keyPath.components(separatedBy: ".") guard let firstKey = keys.first, let val = self[firstKey] else { return nil } if keys.count > 1 { if let arr = val as? [Any], let index = Int(keys[1]), index > -1, index < arr.count { if keys.count > 2 { let newKey = keys.suffix(from: 2).joined(separator: ".") return (arr[index] as? [String: Any])?.value(forKeyPath: newKey) } else { return arr[index] } } else if let dict = val as? [String: Any] { let newKey = keys.suffix(from: 1).joined(separator: ".") return dict.value(forKeyPath: newKey) } else { return nil } } return val } func arrayValue(forKeyPath keyPath: String) -> [Any]? { guard !keyPath.isEmpty else { return nil } let keys = keyPath.components(separatedBy: ".") guard let firstKey = keys.first, let val = self[firstKey] else { return nil } if keys.count > 1 { if let arr = val as? [Any], let index = Int(keys[1]), index > -1, index < arr.count { if keys.count > 2 { let newKey = keys.suffix(from: 2).joined(separator: ".") return (arr[index] as? [String: Any])?.arrayValue(forKeyPath: newKey) } else { return forceArray(for: arr[index]) } } else if let dict = val as? [String: Any] { let newKey = keys.suffix(from: 1).joined(separator: ".") return dict.arrayValue(forKeyPath: newKey) } else { return nil } } return forceArray(for: val) } private func forceArray(for obj: Any?) -> [Any]? { guard let obj = obj else { return nil } guard let arrObj = obj as? [Any] else { return [obj] } return arrObj } } extension Dictionary where Key == String, Value == Any { mutating func setValue(_ value: Any, forKeyPath keyPath: String) { guard !keyPath.isEmpty else { return } let keys = keyPath.components(separatedBy: ".") if keys.count > 1 { var subdict: [String: Any] if let val = self[keys.first!] as? [String: Any] { subdict = val } else { subdict = [String: Any]() } let newKey = keys.suffix(from: 1).joined(separator: ".") subdict.setValue(value, forKeyPath: newKey) self[keys.first!] = subdict } else { self[keys.first!] = value } } }
apache-2.0
1cec8fcca5e7247dabd1116b1df9f68b
35.172414
89
0.499206
4.370833
false
false
false
false
fe9lix/Protium
iOS/Protium/src/gifsearch/GifSearchUI.swift
1
4717
import UIKit import RxSwift import RxCocoa final class GifSearchUI: InteractableUI<GifSearchInteractor> { @IBOutlet weak var searchTextField: UITextField! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout! @IBOutlet weak var loadingView: GiphyBadge! let disposeBag = DisposeBag() fileprivate let cellImageTapped = PublishSubject<GifPM>() // MARK: - Lifecycle class func create(interactorFactory: @escaping (GifSearchUI) -> GifSearchInteractor) -> GifSearchUI { return create( storyboard: UIStoryboard(name: "GifSearch", bundle: Bundle(for: GifSearchUI.self)), interactorFactory: downcast(interactorFactory) ) as! GifSearchUI } override func viewDidLoad() { title = "GifSearch.Title".localized super.viewDidLoad() } // MARK: - Bindings override func bindInteractor(interactor: GifSearchInteractor) { collectionView.register(GifCell.self) // Update presentation models for cells. interactor.gifList .map { $0.value?.items ?? [] } .drive(collectionView.rx.items(cellIdentifier: GifCell.reuseIdentifier, cellType: GifCell.self)) { index, model, cell in cell.model = model // Closure registered for demo purposes only: // Shows how an event occuring in a nested view component can be bubbled up. // If the cell support multiple different events, it might make more sense to // use the delegation pattern here instead of closures. cell.imageTapped = { [unowned self] gifPM in self.cellImageTapped.onNext(gifPM) } } .addDisposableTo(disposeBag) // Error handling. interactor.gifList .filter { $0.isError } .drive(onNext: { result in log(result.error) // Errors could be displayed here. In this example, just log. }) .addDisposableTo(disposeBag) // Dismiss Keyboard when list is scrolled. collectionView.rx.contentOffset .subscribe { _ in if self.searchTextField.isFirstResponder { _ = self.searchTextField.resignFirstResponder() } } .addDisposableTo(disposeBag) // Toggle loading state: Increase bottom inset to make room for loading badge. interactor.isLoading .drive(onNext: { loading in self.collectionView.contentInset = UIEdgeInsets( top: 0, left: 0, bottom: loading ? 72 : 0, right: 0 )} ) .addDisposableTo(disposeBag) interactor.isLoading .drive(self.loadingView.rx.visible) .addDisposableTo(disposeBag) } // MARK: - Layout override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionViewFlowLayout.itemSize = CGSize(width: (collectionView.bounds.width * 0.5).rounded(.down), height: 100.0) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) collectionViewFlowLayout.invalidateLayout() } } extension GifSearchUI { // Note that this Struct contains *reference* types as properties, // therefore copy-semantics are different than for pure value types. // The struct here should merely be regarded as convenience container for UI actions // that are passed as "parameter object" to the Interactor. struct Actions { let search: Driver<String> let loadNextPage: Observable<Void> let cellSelected: Driver<GifPM> var cellImageTapped: Driver<GifPM> } // Extensions only support computed properties. Since this struct is created each time it is accessed, // make sure to reference existing Rx streams here. var actions: Actions { return Actions( search: searchTextField.rx.text.orEmpty.asDriver(), loadNextPage: collectionView.rx.contentOffset .flatMap { _ in self.collectionView.isNearBottomEdge(edgeOffset: 20.0) ? Observable.just(()) : Observable.empty() }, cellSelected: collectionView.rx.modelSelected(GifPM.self).asDriver(), cellImageTapped: cellImageTapped.asDriver(onErrorJustReturn: GifPM.empty()) ) } }
mit
18fd27f5c6181ce082048d1803833a15
38.638655
132
0.623066
5.323928
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ColorModel/Model/DeviceNColorModel.swift
1
162048
// // DeviceNColorModel.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @frozen public struct Device2ColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 2 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double) { self.component_0 = component_0 self.component_1 = component_1 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension Device2ColorModel { @inlinable @inline(__always) public func normalized() -> Device2ColorModel { return self } @inlinable @inline(__always) public func denormalized() -> Device2ColorModel { return self } } extension Device2ColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> Device2ColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) return Device2ColorModel(component_0, component_1) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device2ColorModel, _ transform: (Double, Double) -> Double) -> Device2ColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) return Device2ColorModel(component_0, component_1) } } @frozen public struct Device3ColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 3 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension Device3ColorModel { @inlinable @inline(__always) public func normalized() -> Device3ColorModel { return self } @inlinable @inline(__always) public func denormalized() -> Device3ColorModel { return self } } extension Device3ColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> Device3ColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) return Device3ColorModel(component_0, component_1, component_2) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device3ColorModel, _ transform: (Double, Double) -> Double) -> Device3ColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) return Device3ColorModel(component_0, component_1, component_2) } } @frozen public struct Device4ColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 4 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension Device4ColorModel { @inlinable @inline(__always) public func normalized() -> Device4ColorModel { return self } @inlinable @inline(__always) public func denormalized() -> Device4ColorModel { return self } } extension Device4ColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> Device4ColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) return Device4ColorModel(component_0, component_1, component_2, component_3) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device4ColorModel, _ transform: (Double, Double) -> Double) -> Device4ColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) return Device4ColorModel(component_0, component_1, component_2, component_3) } } @frozen public struct Device5ColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 5 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension Device5ColorModel { @inlinable @inline(__always) public func normalized() -> Device5ColorModel { return self } @inlinable @inline(__always) public func denormalized() -> Device5ColorModel { return self } } extension Device5ColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> Device5ColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) return Device5ColorModel( component_0, component_1, component_2, component_3, component_4 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device5ColorModel, _ transform: (Double, Double) -> Double) -> Device5ColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) return Device5ColorModel( component_0, component_1, component_2, component_3, component_4 ) } } @frozen public struct Device6ColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 6 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension Device6ColorModel { @inlinable @inline(__always) public func normalized() -> Device6ColorModel { return self } @inlinable @inline(__always) public func denormalized() -> Device6ColorModel { return self } } extension Device6ColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> Device6ColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) return Device6ColorModel( component_0, component_1, component_2, component_3, component_4, component_5 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device6ColorModel, _ transform: (Double, Double) -> Double) -> Device6ColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) return Device6ColorModel( component_0, component_1, component_2, component_3, component_4, component_5 ) } } @frozen public struct Device7ColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 7 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double public var component_6: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double, _ component_6: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension Device7ColorModel { @inlinable @inline(__always) public func normalized() -> Device7ColorModel { return self } @inlinable @inline(__always) public func denormalized() -> Device7ColorModel { return self } } extension Device7ColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> Device7ColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) return Device7ColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device7ColorModel, _ transform: (Double, Double) -> Double) -> Device7ColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) return Device7ColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6 ) } } @frozen public struct Device8ColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 8 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double public var component_6: Double public var component_7: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double, _ component_6: Double, _ component_7: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension Device8ColorModel { @inlinable @inline(__always) public func normalized() -> Device8ColorModel { return self } @inlinable @inline(__always) public func denormalized() -> Device8ColorModel { return self } } extension Device8ColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> Device8ColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) return Device8ColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device8ColorModel, _ transform: (Double, Double) -> Double) -> Device8ColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) return Device8ColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7 ) } } @frozen public struct Device9ColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 9 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double public var component_6: Double public var component_7: Double public var component_8: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double, _ component_6: Double, _ component_7: Double, _ component_8: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension Device9ColorModel { @inlinable @inline(__always) public func normalized() -> Device9ColorModel { return self } @inlinable @inline(__always) public func denormalized() -> Device9ColorModel { return self } } extension Device9ColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> Device9ColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) return Device9ColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device9ColorModel, _ transform: (Double, Double) -> Double) -> Device9ColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) return Device9ColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8 ) } } @frozen public struct DeviceAColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 10 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double public var component_6: Double public var component_7: Double public var component_8: Double public var component_9: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double, _ component_6: Double, _ component_7: Double, _ component_8: Double, _ component_9: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension DeviceAColorModel { @inlinable @inline(__always) public func normalized() -> DeviceAColorModel { return self } @inlinable @inline(__always) public func denormalized() -> DeviceAColorModel { return self } } extension DeviceAColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> DeviceAColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) return DeviceAColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceAColorModel, _ transform: (Double, Double) -> Double) -> DeviceAColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) return DeviceAColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9 ) } } @frozen public struct DeviceBColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 11 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double public var component_6: Double public var component_7: Double public var component_8: Double public var component_9: Double public var component_10: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double, _ component_6: Double, _ component_7: Double, _ component_8: Double, _ component_9: Double, _ component_10: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension DeviceBColorModel { @inlinable @inline(__always) public func normalized() -> DeviceBColorModel { return self } @inlinable @inline(__always) public func denormalized() -> DeviceBColorModel { return self } } extension DeviceBColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> DeviceBColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) return DeviceBColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceBColorModel, _ transform: (Double, Double) -> Double) -> DeviceBColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) return DeviceBColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10 ) } } @frozen public struct DeviceCColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 12 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double public var component_6: Double public var component_7: Double public var component_8: Double public var component_9: Double public var component_10: Double public var component_11: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 self.component_11 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double, _ component_6: Double, _ component_7: Double, _ component_8: Double, _ component_9: Double, _ component_10: Double, _ component_11: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 self.component_11 = component_11 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension DeviceCColorModel { @inlinable @inline(__always) public func normalized() -> DeviceCColorModel { return self } @inlinable @inline(__always) public func denormalized() -> DeviceCColorModel { return self } } extension DeviceCColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> DeviceCColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) let component_11 = transform(self.component_11) return DeviceCColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) updateAccumulatingResult(&accumulator, component_11) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceCColorModel, _ transform: (Double, Double) -> Double) -> DeviceCColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) let component_11 = transform(self.component_11, other.component_11) return DeviceCColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11 ) } } @frozen public struct DeviceDColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 13 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double public var component_6: Double public var component_7: Double public var component_8: Double public var component_9: Double public var component_10: Double public var component_11: Double public var component_12: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 self.component_11 = 0 self.component_12 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double, _ component_6: Double, _ component_7: Double, _ component_8: Double, _ component_9: Double, _ component_10: Double, _ component_11: Double, _ component_12: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 self.component_11 = component_11 self.component_12 = component_12 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension DeviceDColorModel { @inlinable @inline(__always) public func normalized() -> DeviceDColorModel { return self } @inlinable @inline(__always) public func denormalized() -> DeviceDColorModel { return self } } extension DeviceDColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> DeviceDColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) let component_11 = transform(self.component_11) let component_12 = transform(self.component_12) return DeviceDColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) updateAccumulatingResult(&accumulator, component_11) updateAccumulatingResult(&accumulator, component_12) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceDColorModel, _ transform: (Double, Double) -> Double) -> DeviceDColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) let component_11 = transform(self.component_11, other.component_11) let component_12 = transform(self.component_12, other.component_12) return DeviceDColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12 ) } } @frozen public struct DeviceEColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 14 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double public var component_6: Double public var component_7: Double public var component_8: Double public var component_9: Double public var component_10: Double public var component_11: Double public var component_12: Double public var component_13: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 self.component_11 = 0 self.component_12 = 0 self.component_13 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double, _ component_6: Double, _ component_7: Double, _ component_8: Double, _ component_9: Double, _ component_10: Double, _ component_11: Double, _ component_12: Double, _ component_13: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 self.component_11 = component_11 self.component_12 = component_12 self.component_13 = component_13 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension DeviceEColorModel { @inlinable @inline(__always) public func normalized() -> DeviceEColorModel { return self } @inlinable @inline(__always) public func denormalized() -> DeviceEColorModel { return self } } extension DeviceEColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> DeviceEColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) let component_11 = transform(self.component_11) let component_12 = transform(self.component_12) let component_13 = transform(self.component_13) return DeviceEColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12, component_13 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) updateAccumulatingResult(&accumulator, component_11) updateAccumulatingResult(&accumulator, component_12) updateAccumulatingResult(&accumulator, component_13) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceEColorModel, _ transform: (Double, Double) -> Double) -> DeviceEColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) let component_11 = transform(self.component_11, other.component_11) let component_12 = transform(self.component_12, other.component_12) let component_13 = transform(self.component_13, other.component_13) return DeviceEColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12, component_13 ) } } @frozen public struct DeviceFColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 15 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") return 0...1 } public var component_0: Double public var component_1: Double public var component_2: Double public var component_3: Double public var component_4: Double public var component_5: Double public var component_6: Double public var component_7: Double public var component_8: Double public var component_9: Double public var component_10: Double public var component_11: Double public var component_12: Double public var component_13: Double public var component_14: Double @inlinable @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 self.component_11 = 0 self.component_12 = 0 self.component_13 = 0 self.component_14 = 0 } @inlinable @inline(__always) public init(_ component_0: Double, _ component_1: Double, _ component_2: Double, _ component_3: Double, _ component_4: Double, _ component_5: Double, _ component_6: Double, _ component_7: Double, _ component_8: Double, _ component_9: Double, _ component_10: Double, _ component_11: Double, _ component_12: Double, _ component_13: Double, _ component_14: Double) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 self.component_11 = component_11 self.component_12 = component_12 self.component_13 = component_13 self.component_14 = component_14 } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension DeviceFColorModel { @inlinable @inline(__always) public func normalized() -> DeviceFColorModel { return self } @inlinable @inline(__always) public func denormalized() -> DeviceFColorModel { return self } } extension DeviceFColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> DeviceFColorModel { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) let component_11 = transform(self.component_11) let component_12 = transform(self.component_12) let component_13 = transform(self.component_13) let component_14 = transform(self.component_14) return DeviceFColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12, component_13, component_14 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) updateAccumulatingResult(&accumulator, component_11) updateAccumulatingResult(&accumulator, component_12) updateAccumulatingResult(&accumulator, component_13) updateAccumulatingResult(&accumulator, component_14) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceFColorModel, _ transform: (Double, Double) -> Double) -> DeviceFColorModel { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) let component_11 = transform(self.component_11, other.component_11) let component_12 = transform(self.component_12, other.component_12) let component_13 = transform(self.component_13, other.component_13) let component_14 = transform(self.component_14, other.component_14) return DeviceFColorModel( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12, component_13, component_14 ) } } // MARK: FloatComponents extension Device2ColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 2 } public var component_0: Scalar public var component_1: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar) { self.component_0 = component_0 self.component_1 = component_1 } @inlinable @inline(__always) public init(_ color: Device2ColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: Device2ColorModel { get { return Device2ColorModel(Double(component_0), Double(component_1)) } set { self = FloatComponents(newValue) } } } } extension Device2ColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> Device2ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) return Device2ColorModel.FloatComponents(component_0, component_1) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device2ColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> Device2ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) return Device2ColorModel.FloatComponents(component_0, component_1) } } extension Device3ColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 3 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 } @inlinable @inline(__always) public init(_ color: Device3ColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: Device3ColorModel { get { return Device3ColorModel(Double(component_0), Double(component_1), Double(component_2)) } set { self = FloatComponents(newValue) } } } } extension Device3ColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> Device3ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) return Device3ColorModel.FloatComponents(component_0, component_1, component_2) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device3ColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> Device3ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) return Device3ColorModel.FloatComponents(component_0, component_1, component_2) } } extension Device4ColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 4 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 } @inlinable @inline(__always) public init(_ color: Device4ColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: Device4ColorModel { get { return Device4ColorModel(Double(component_0), Double(component_1), Double(component_2), Double(component_3)) } set { self = FloatComponents(newValue) } } } } extension Device4ColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> Device4ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) return Device4ColorModel.FloatComponents(component_0, component_1, component_2, component_3) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device4ColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> Device4ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) return Device4ColorModel.FloatComponents(component_0, component_1, component_2, component_3) } } extension Device5ColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 5 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 } @inlinable @inline(__always) public init(_ color: Device5ColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: Device5ColorModel { get { return Device5ColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4) ) } set { self = FloatComponents(newValue) } } } } extension Device5ColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> Device5ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) return Device5ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device5ColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> Device5ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) return Device5ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4 ) } } extension Device6ColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 6 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 } @inlinable @inline(__always) public init(_ color: Device6ColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: Device6ColorModel { get { return Device6ColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5) ) } set { self = FloatComponents(newValue) } } } } extension Device6ColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> Device6ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) return Device6ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device6ColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> Device6ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) return Device6ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5 ) } } extension Device7ColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 7 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar public var component_6: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar, _ component_6: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 } @inlinable @inline(__always) public init(_ color: Device7ColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) self.component_6 = Scalar(color.component_6) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) self.component_6 = Scalar(components.component_6) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: Device7ColorModel { get { return Device7ColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5), Double(component_6) ) } set { self = FloatComponents(newValue) } } } } extension Device7ColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> Device7ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) return Device7ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device7ColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> Device7ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) return Device7ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6 ) } } extension Device8ColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 8 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar public var component_6: Scalar public var component_7: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar, _ component_6: Scalar, _ component_7: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 } @inlinable @inline(__always) public init(_ color: Device8ColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) self.component_6 = Scalar(color.component_6) self.component_7 = Scalar(color.component_7) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) self.component_6 = Scalar(components.component_6) self.component_7 = Scalar(components.component_7) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: Device8ColorModel { get { return Device8ColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5), Double(component_6), Double(component_7) ) } set { self = FloatComponents(newValue) } } } } extension Device8ColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> Device8ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) return Device8ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device8ColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> Device8ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) return Device8ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7 ) } } extension Device9ColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 9 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar public var component_6: Scalar public var component_7: Scalar public var component_8: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar, _ component_6: Scalar, _ component_7: Scalar, _ component_8: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 } @inlinable @inline(__always) public init(_ color: Device9ColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) self.component_6 = Scalar(color.component_6) self.component_7 = Scalar(color.component_7) self.component_8 = Scalar(color.component_8) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) self.component_6 = Scalar(components.component_6) self.component_7 = Scalar(components.component_7) self.component_8 = Scalar(components.component_8) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: Device9ColorModel { get { return Device9ColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5), Double(component_6), Double(component_7), Double(component_8) ) } set { self = FloatComponents(newValue) } } } } extension Device9ColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> Device9ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) return Device9ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) return accumulator } @inlinable @inline(__always) public func combined(_ other: Device9ColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> Device9ColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) return Device9ColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8 ) } } extension DeviceAColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 10 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar public var component_6: Scalar public var component_7: Scalar public var component_8: Scalar public var component_9: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar, _ component_6: Scalar, _ component_7: Scalar, _ component_8: Scalar, _ component_9: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 } @inlinable @inline(__always) public init(_ color: DeviceAColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) self.component_6 = Scalar(color.component_6) self.component_7 = Scalar(color.component_7) self.component_8 = Scalar(color.component_8) self.component_9 = Scalar(color.component_9) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) self.component_6 = Scalar(components.component_6) self.component_7 = Scalar(components.component_7) self.component_8 = Scalar(components.component_8) self.component_9 = Scalar(components.component_9) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: DeviceAColorModel { get { return DeviceAColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5), Double(component_6), Double(component_7), Double(component_8), Double(component_9) ) } set { self = FloatComponents(newValue) } } } } extension DeviceAColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> DeviceAColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) return DeviceAColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceAColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> DeviceAColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) return DeviceAColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9 ) } } extension DeviceBColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 11 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar public var component_6: Scalar public var component_7: Scalar public var component_8: Scalar public var component_9: Scalar public var component_10: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar, _ component_6: Scalar, _ component_7: Scalar, _ component_8: Scalar, _ component_9: Scalar, _ component_10: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 } @inlinable @inline(__always) public init(_ color: DeviceBColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) self.component_6 = Scalar(color.component_6) self.component_7 = Scalar(color.component_7) self.component_8 = Scalar(color.component_8) self.component_9 = Scalar(color.component_9) self.component_10 = Scalar(color.component_10) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) self.component_6 = Scalar(components.component_6) self.component_7 = Scalar(components.component_7) self.component_8 = Scalar(components.component_8) self.component_9 = Scalar(components.component_9) self.component_10 = Scalar(components.component_10) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: DeviceBColorModel { get { return DeviceBColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5), Double(component_6), Double(component_7), Double(component_8), Double(component_9), Double(component_10) ) } set { self = FloatComponents(newValue) } } } } extension DeviceBColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> DeviceBColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) return DeviceBColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceBColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> DeviceBColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) return DeviceBColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10 ) } } extension DeviceCColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 12 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar public var component_6: Scalar public var component_7: Scalar public var component_8: Scalar public var component_9: Scalar public var component_10: Scalar public var component_11: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 self.component_11 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar, _ component_6: Scalar, _ component_7: Scalar, _ component_8: Scalar, _ component_9: Scalar, _ component_10: Scalar, _ component_11: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 self.component_11 = component_11 } @inlinable @inline(__always) public init(_ color: DeviceCColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) self.component_6 = Scalar(color.component_6) self.component_7 = Scalar(color.component_7) self.component_8 = Scalar(color.component_8) self.component_9 = Scalar(color.component_9) self.component_10 = Scalar(color.component_10) self.component_11 = Scalar(color.component_11) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) self.component_6 = Scalar(components.component_6) self.component_7 = Scalar(components.component_7) self.component_8 = Scalar(components.component_8) self.component_9 = Scalar(components.component_9) self.component_10 = Scalar(components.component_10) self.component_11 = Scalar(components.component_11) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: DeviceCColorModel { get { return DeviceCColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5), Double(component_6), Double(component_7), Double(component_8), Double(component_9), Double(component_10), Double(component_11) ) } set { self = FloatComponents(newValue) } } } } extension DeviceCColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> DeviceCColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) let component_11 = transform(self.component_11) return DeviceCColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) updateAccumulatingResult(&accumulator, component_11) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceCColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> DeviceCColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) let component_11 = transform(self.component_11, other.component_11) return DeviceCColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11 ) } } extension DeviceDColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 13 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar public var component_6: Scalar public var component_7: Scalar public var component_8: Scalar public var component_9: Scalar public var component_10: Scalar public var component_11: Scalar public var component_12: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 self.component_11 = 0 self.component_12 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar, _ component_6: Scalar, _ component_7: Scalar, _ component_8: Scalar, _ component_9: Scalar, _ component_10: Scalar, _ component_11: Scalar, _ component_12: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 self.component_11 = component_11 self.component_12 = component_12 } @inlinable @inline(__always) public init(_ color: DeviceDColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) self.component_6 = Scalar(color.component_6) self.component_7 = Scalar(color.component_7) self.component_8 = Scalar(color.component_8) self.component_9 = Scalar(color.component_9) self.component_10 = Scalar(color.component_10) self.component_11 = Scalar(color.component_11) self.component_12 = Scalar(color.component_12) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) self.component_6 = Scalar(components.component_6) self.component_7 = Scalar(components.component_7) self.component_8 = Scalar(components.component_8) self.component_9 = Scalar(components.component_9) self.component_10 = Scalar(components.component_10) self.component_11 = Scalar(components.component_11) self.component_12 = Scalar(components.component_12) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: DeviceDColorModel { get { return DeviceDColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5), Double(component_6), Double(component_7), Double(component_8), Double(component_9), Double(component_10), Double(component_11), Double(component_12) ) } set { self = FloatComponents(newValue) } } } } extension DeviceDColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> DeviceDColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) let component_11 = transform(self.component_11) let component_12 = transform(self.component_12) return DeviceDColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) updateAccumulatingResult(&accumulator, component_11) updateAccumulatingResult(&accumulator, component_12) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceDColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> DeviceDColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) let component_11 = transform(self.component_11, other.component_11) let component_12 = transform(self.component_12, other.component_12) return DeviceDColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12 ) } } extension DeviceEColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 14 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar public var component_6: Scalar public var component_7: Scalar public var component_8: Scalar public var component_9: Scalar public var component_10: Scalar public var component_11: Scalar public var component_12: Scalar public var component_13: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 self.component_11 = 0 self.component_12 = 0 self.component_13 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar, _ component_6: Scalar, _ component_7: Scalar, _ component_8: Scalar, _ component_9: Scalar, _ component_10: Scalar, _ component_11: Scalar, _ component_12: Scalar, _ component_13: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 self.component_11 = component_11 self.component_12 = component_12 self.component_13 = component_13 } @inlinable @inline(__always) public init(_ color: DeviceEColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) self.component_6 = Scalar(color.component_6) self.component_7 = Scalar(color.component_7) self.component_8 = Scalar(color.component_8) self.component_9 = Scalar(color.component_9) self.component_10 = Scalar(color.component_10) self.component_11 = Scalar(color.component_11) self.component_12 = Scalar(color.component_12) self.component_13 = Scalar(color.component_13) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) self.component_6 = Scalar(components.component_6) self.component_7 = Scalar(components.component_7) self.component_8 = Scalar(components.component_8) self.component_9 = Scalar(components.component_9) self.component_10 = Scalar(components.component_10) self.component_11 = Scalar(components.component_11) self.component_12 = Scalar(components.component_12) self.component_13 = Scalar(components.component_13) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: DeviceEColorModel { get { return DeviceEColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5), Double(component_6), Double(component_7), Double(component_8), Double(component_9), Double(component_10), Double(component_11), Double(component_12), Double(component_13) ) } set { self = FloatComponents(newValue) } } } } extension DeviceEColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> DeviceEColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) let component_11 = transform(self.component_11) let component_12 = transform(self.component_12) let component_13 = transform(self.component_13) return DeviceEColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12, component_13 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) updateAccumulatingResult(&accumulator, component_11) updateAccumulatingResult(&accumulator, component_12) updateAccumulatingResult(&accumulator, component_13) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceEColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> DeviceEColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) let component_11 = transform(self.component_11, other.component_11) let component_12 = transform(self.component_12, other.component_12) let component_13 = transform(self.component_13, other.component_13) return DeviceEColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12, component_13 ) } } extension DeviceFColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 15 } public var component_0: Scalar public var component_1: Scalar public var component_2: Scalar public var component_3: Scalar public var component_4: Scalar public var component_5: Scalar public var component_6: Scalar public var component_7: Scalar public var component_8: Scalar public var component_9: Scalar public var component_10: Scalar public var component_11: Scalar public var component_12: Scalar public var component_13: Scalar public var component_14: Scalar @inline(__always) public init() { self.component_0 = 0 self.component_1 = 0 self.component_2 = 0 self.component_3 = 0 self.component_4 = 0 self.component_5 = 0 self.component_6 = 0 self.component_7 = 0 self.component_8 = 0 self.component_9 = 0 self.component_10 = 0 self.component_11 = 0 self.component_12 = 0 self.component_13 = 0 self.component_14 = 0 } @inline(__always) public init(_ component_0: Scalar, _ component_1: Scalar, _ component_2: Scalar, _ component_3: Scalar, _ component_4: Scalar, _ component_5: Scalar, _ component_6: Scalar, _ component_7: Scalar, _ component_8: Scalar, _ component_9: Scalar, _ component_10: Scalar, _ component_11: Scalar, _ component_12: Scalar, _ component_13: Scalar, _ component_14: Scalar) { self.component_0 = component_0 self.component_1 = component_1 self.component_2 = component_2 self.component_3 = component_3 self.component_4 = component_4 self.component_5 = component_5 self.component_6 = component_6 self.component_7 = component_7 self.component_8 = component_8 self.component_9 = component_9 self.component_10 = component_10 self.component_11 = component_11 self.component_12 = component_12 self.component_13 = component_13 self.component_14 = component_14 } @inlinable @inline(__always) public init(_ color: DeviceFColorModel) { self.component_0 = Scalar(color.component_0) self.component_1 = Scalar(color.component_1) self.component_2 = Scalar(color.component_2) self.component_3 = Scalar(color.component_3) self.component_4 = Scalar(color.component_4) self.component_5 = Scalar(color.component_5) self.component_6 = Scalar(color.component_6) self.component_7 = Scalar(color.component_7) self.component_8 = Scalar(color.component_8) self.component_9 = Scalar(color.component_9) self.component_10 = Scalar(color.component_10) self.component_11 = Scalar(color.component_11) self.component_12 = Scalar(color.component_12) self.component_13 = Scalar(color.component_13) self.component_14 = Scalar(color.component_14) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.component_0 = Scalar(components.component_0) self.component_1 = Scalar(components.component_1) self.component_2 = Scalar(components.component_2) self.component_3 = Scalar(components.component_3) self.component_4 = Scalar(components.component_4) self.component_5 = Scalar(components.component_5) self.component_6 = Scalar(components.component_6) self.component_7 = Scalar(components.component_7) self.component_8 = Scalar(components.component_8) self.component_9 = Scalar(components.component_9) self.component_10 = Scalar(components.component_10) self.component_11 = Scalar(components.component_11) self.component_12 = Scalar(components.component_12) self.component_13 = Scalar(components.component_13) self.component_14 = Scalar(components.component_14) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: DeviceFColorModel { get { return DeviceFColorModel( Double(component_0), Double(component_1), Double(component_2), Double(component_3), Double(component_4), Double(component_5), Double(component_6), Double(component_7), Double(component_8), Double(component_9), Double(component_10), Double(component_11), Double(component_12), Double(component_13), Double(component_14) ) } set { self = FloatComponents(newValue) } } } } extension DeviceFColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> DeviceFColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0) let component_1 = transform(self.component_1) let component_2 = transform(self.component_2) let component_3 = transform(self.component_3) let component_4 = transform(self.component_4) let component_5 = transform(self.component_5) let component_6 = transform(self.component_6) let component_7 = transform(self.component_7) let component_8 = transform(self.component_8) let component_9 = transform(self.component_9) let component_10 = transform(self.component_10) let component_11 = transform(self.component_11) let component_12 = transform(self.component_12) let component_13 = transform(self.component_13) let component_14 = transform(self.component_14) return DeviceFColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12, component_13, component_14 ) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, component_0) updateAccumulatingResult(&accumulator, component_1) updateAccumulatingResult(&accumulator, component_2) updateAccumulatingResult(&accumulator, component_3) updateAccumulatingResult(&accumulator, component_4) updateAccumulatingResult(&accumulator, component_5) updateAccumulatingResult(&accumulator, component_6) updateAccumulatingResult(&accumulator, component_7) updateAccumulatingResult(&accumulator, component_8) updateAccumulatingResult(&accumulator, component_9) updateAccumulatingResult(&accumulator, component_10) updateAccumulatingResult(&accumulator, component_11) updateAccumulatingResult(&accumulator, component_12) updateAccumulatingResult(&accumulator, component_13) updateAccumulatingResult(&accumulator, component_14) return accumulator } @inlinable @inline(__always) public func combined(_ other: DeviceFColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> DeviceFColorModel.FloatComponents<Scalar> { let component_0 = transform(self.component_0, other.component_0) let component_1 = transform(self.component_1, other.component_1) let component_2 = transform(self.component_2, other.component_2) let component_3 = transform(self.component_3, other.component_3) let component_4 = transform(self.component_4, other.component_4) let component_5 = transform(self.component_5, other.component_5) let component_6 = transform(self.component_6, other.component_6) let component_7 = transform(self.component_7, other.component_7) let component_8 = transform(self.component_8, other.component_8) let component_9 = transform(self.component_9, other.component_9) let component_10 = transform(self.component_10, other.component_10) let component_11 = transform(self.component_11, other.component_11) let component_12 = transform(self.component_12, other.component_12) let component_13 = transform(self.component_13, other.component_13) let component_14 = transform(self.component_14, other.component_14) return DeviceFColorModel.FloatComponents( component_0, component_1, component_2, component_3, component_4, component_5, component_6, component_7, component_8, component_9, component_10, component_11, component_12, component_13, component_14 ) } }
mit
50ad800e99989b50fe1e0218718e764e
37.173852
164
0.621575
4.454193
false
false
false
false
tiembo/google-services
ios/gcm/GcmExampleSwift/AppDelegate.swift
3
8849
// // Copyright (c) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Google @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate { var window: UIWindow? var connectedToGCM = false var subscribedToTopic = false var gcmSenderID: String? var registrationToken: String? var registrationOptions = [String: AnyObject]() let registrationKey = "onRegistrationCompleted" let messageKey = "onMessageReceived" let subscriptionTopic = "/topics/global" // [START register_for_remote_notifications] func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // [START_EXCLUDE] // Configure the Google context: parses the GoogleService-Info.plist, and initializes // the services that have entries in the file var configureError: NSError? GGLContext.sharedInstance().configureWithError(&configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID // [END_EXCLUDE] // Register for remote notifications if #available(iOS 8.0, *) { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { // Fallback let types: UIRemoteNotificationType = [.alert, .badge, .sound] application.registerForRemoteNotifications(matching: types) } // [END register_for_remote_notifications] // [START start_gcm_service] let gcmConfig = GCMConfig.default() gcmConfig?.receiverDelegate = self GCMService.sharedInstance().start(with: gcmConfig) // [END start_gcm_service] return true } func subscribeToTopic() { // If the app has a registration token and is connected to GCM, proceed to subscribe to the // topic if registrationToken != nil && connectedToGCM { GCMPubSub.sharedInstance().subscribe(withToken: self.registrationToken, topic: subscriptionTopic, options: nil, handler: { error -> Void in if let error = error as? NSError { // Treat the "already subscribed" error more gently if error.code == 3001 { print("Already subscribed to \(self.subscriptionTopic)") } else { print("Subscription failed: \(error.localizedDescription)") } } else { self.subscribedToTopic = true NSLog("Subscribed to \(self.subscriptionTopic)") } }) } } // [START connect_gcm_service] func applicationDidBecomeActive( _ application: UIApplication) { // Connect to the GCM server to receive non-APNS notifications GCMService.sharedInstance().connect(handler: { error -> Void in if let error = error as? NSError { print("Could not connect to GCM: \(error.localizedDescription)") } else { self.connectedToGCM = true print("Connected to GCM") // [START_EXCLUDE] self.subscribeToTopic() // [END_EXCLUDE] } }) } // [END connect_gcm_service] // [START disconnect_gcm_service] func applicationDidEnterBackground(_ application: UIApplication) { GCMService.sharedInstance().disconnect() // [START_EXCLUDE] self.connectedToGCM = false // [END_EXCLUDE] } // [END disconnect_gcm_service] // [START receive_apns_token] func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { // [END receive_apns_token] // [START get_gcm_reg_token] // Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol. let instanceIDConfig = GGLInstanceIDConfig.default() instanceIDConfig?.delegate = self // Start the GGLInstanceID shared instance with that config and request a registration // token to enable reception of notifications GGLInstanceID.sharedInstance().start(with: instanceIDConfig) registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken as AnyObject, kGGLInstanceIDAPNSServerTypeSandboxOption:true as AnyObject] GGLInstanceID.sharedInstance().token(withAuthorizedEntity: gcmSenderID, scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) // [END get_gcm_reg_token] } // [START receive_apns_token_error] func application( _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error ) { print("Registration for remote notification failed with error: \(error.localizedDescription)") // [END receive_apns_token_error] let userInfo = ["error": error.localizedDescription] NotificationCenter.default.post( name: Notification.Name(rawValue: registrationKey), object: nil, userInfo: userInfo) } // [START ack_message_reception] func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { print("Notification received: \(userInfo)") // This works only if the app started the GCM service GCMService.sharedInstance().appDidReceiveMessage(userInfo) // Handle the received message // [START_EXCLUDE] NotificationCenter.default.post(name: Notification.Name(rawValue: messageKey), object: nil, userInfo: userInfo) // [END_EXCLUDE] } func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler handler: @escaping (UIBackgroundFetchResult) -> Void) { print("Notification received: \(userInfo)") // This works only if the app started the GCM service GCMService.sharedInstance().appDidReceiveMessage(userInfo) // Handle the received message // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value // [START_EXCLUDE] NotificationCenter.default.post(name: Notification.Name(rawValue: messageKey), object: nil, userInfo: userInfo) handler(UIBackgroundFetchResult.noData) // [END_EXCLUDE] } // [END ack_message_reception] func registrationHandler(_ registrationToken: String?, error: Error?) { if let registrationToken = registrationToken { self.registrationToken = registrationToken print("Registration Token: \(registrationToken)") self.subscribeToTopic() let userInfo = ["registrationToken": registrationToken] NotificationCenter.default.post( name: Notification.Name(rawValue: self.registrationKey), object: nil, userInfo: userInfo) } else if let error = error { print("Registration to GCM failed with error: \(error.localizedDescription)") let userInfo = ["error": error.localizedDescription] NotificationCenter.default.post( name: Notification.Name(rawValue: self.registrationKey), object: nil, userInfo: userInfo) } } // [START on_token_refresh] func onTokenRefresh() { // A rotation of the registration tokens is happening, so the app needs to request a new token. print("The GCM registration token needs to be changed.") GGLInstanceID.sharedInstance().token(withAuthorizedEntity: gcmSenderID, scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) } // [END on_token_refresh] // [START upstream_callbacks] func willSendDataMessage(withID messageID: String!, error: Error!) { if error != nil { // Failed to send the message. } else { // Will send message, you can save the messageID to track the message } } func didSendDataMessage(withID messageID: String!) { // Did successfully send message identified by messageID } // [END upstream_callbacks] func didDeleteMessagesOnServer() { // Some messages sent to this device were deleted on the GCM server before reception, likely // because the TTL expired. The client should notify the app server of this, so that the app // server can resend those messages. } }
apache-2.0
0d5ca79aec30176ec13053934831f2c7
39.967593
103
0.70686
4.897067
false
true
false
false
AlanEnjoy/Live
Live/Live/Classes/Main/Controller/AmuseMenuViewCell.swift
1
1685
// // AmuseMenuViewCell.swift // Live // // Created by Alan's Macbook on 2017/7/26. // Copyright © 2017年 zhushuai. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" class AmuseMenuViewCell: UICollectionViewCell { //MARK:- 数组模型 var groups : [AnchorGroup]? { didSet{ collectionView.reloadData() } } //MARK:- 控件属性 @IBOutlet weak var collectionView: UICollectionView! //MARK:- 从xib中加载 override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) } override func layoutSubviews() { let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let itemW = collectionView.bounds.width / 4 let itemH = collectionView.bounds.height / 2 layout.itemSize = CGSize(width: itemW, height: itemH) } } extension AmuseMenuViewCell : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //1.取出Cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell //2.给cell设置数据 cell.baseGame = groups![indexPath.item] cell.clipsToBounds = true return cell } }
mit
1e3285980c927ec15c2d0d8519ec8852
26.4
127
0.657543
5.18612
false
false
false
false
haijianhuo/TopStore
Pods/CircleMenu/CircleMenuLib/CircleMenu.swift
1
20378
// // CircleMenu.swift // ButtonTest // // Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.com) // // 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 UIKit // MARK: helpers func customize<Type>(_ value: Type, block: (_ object: Type) -> Void) -> Type { block(value) return value } // MARK: Protocol /** * CircleMenuDelegate */ @objc public protocol CircleMenuDelegate { /** Tells the delegate the circle menu is about to draw a button for a particular index. - parameter circleMenu: The circle menu object informing the delegate of this impending event. - parameter button: A circle menu button object that circle menu is going to use when drawing the row. Don't change button.tag - parameter atIndex: An button index. */ @objc optional func circleMenu(_ circleMenu: CircleMenu, willDisplay button: UIButton, atIndex: Int) /** Tells the delegate that a specified index is about to be selected. - parameter circleMenu: A circle menu object informing the delegate about the impending selection. - parameter button: A selected circle menu button. Don't change button.tag - parameter atIndex: Selected button index */ @objc optional func circleMenu(_ circleMenu: CircleMenu, buttonWillSelected button: UIButton, atIndex: Int) /** Tells the delegate that the specified index is now selected. - parameter circleMenu: A circle menu object informing the delegate about the new index selection. - parameter button: A selected circle menu button. Don't change button.tag - parameter atIndex: Selected button index */ @objc optional func circleMenu(_ circleMenu: CircleMenu, buttonDidSelected button: UIButton, atIndex: Int) /** Tells the delegate that the menu was collapsed - the cancel action. - parameter circleMenu: A circle menu object informing the delegate about the new index selection. */ @objc optional func menuCollapsed(_ circleMenu: CircleMenu) } // MARK: CircleMenu /// A Button object with pop ups buttons open class CircleMenu: UIButton { // MARK: properties /// Buttons count @IBInspectable open var buttonsCount: Int = 3 /// Circle animation duration @IBInspectable open var duration: Double = 2 /// Distance between center button and buttons @IBInspectable open var distance: Float = 100 /// Delay between show buttons @IBInspectable open var showDelay: Double = 0 /// Start angle of the circle @IBInspectable open var startAngle: Float = 0 /// End angle of the circle @IBInspectable open var endAngle: Float = 360 // Pop buttons radius, if nil use center button size open var subButtonsRadius: CGFloat? // Show buttons event open var showButtonsEvent: UIControlEvents = UIControlEvents.touchUpInside { didSet { addActions(newEvent: showButtonsEvent, oldEvent: oldValue) } } /// The object that acts as the delegate of the circle menu. @IBOutlet open weak var delegate: AnyObject? // CircleMenuDelegate? var buttons: [UIButton]? weak var platform: UIView? public var customNormalIconView: UIImageView? public var customSelectedIconView: UIImageView? /** Initializes and returns a circle menu object. - parameter frame: A rectangle specifying the initial location and size of the circle menu in its superview’€™s coordinates. - parameter normalIcon: The image to use for the specified normal state. - parameter selectedIcon: The image to use for the specified selected state. - parameter buttonsCount: The number of buttons. - parameter duration: The duration, in seconds, of the animation. - parameter distance: Distance between center button and sub buttons. - returns: A newly created circle menu. */ public init(frame: CGRect, normalIcon: String?, selectedIcon: String?, buttonsCount: Int = 3, duration: Double = 2, distance: Float = 100) { super.init(frame: frame) if let icon = normalIcon { setImage(UIImage(named: icon), for: .normal) } if let icon = selectedIcon { setImage(UIImage(named: icon), for: .selected) } self.buttonsCount = buttonsCount self.duration = duration self.distance = distance commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { addActions(newEvent: showButtonsEvent) customNormalIconView = addCustomImageView(state: .normal) customSelectedIconView = addCustomImageView(state: .selected) customSelectedIconView?.alpha = 0 setImage(UIImage(), for: .normal) setImage(UIImage(), for: .selected) } // MARK: methods /** Hide button - parameter duration: The duration, in seconds, of the animation. - parameter hideDelay: The time to delay, in seconds. */ open func hideButtons(_ duration: Double, hideDelay: Double = 0) { if buttons == nil { return } buttonsAnimationIsShow(isShow: false, duration: duration, hideDelay: hideDelay) tapBounceAnimation(duration: 0.5) tapRotatedAnimation(0.3, isSelected: false) } /** Check is sub buttons showed */ open func buttonsIsShown() -> Bool { guard let buttons = self.buttons else { return false } for button in buttons { if button.alpha == 0 { return false } } return true } open override func removeFromSuperview() { if self.platform?.superview != nil { self.platform?.removeFromSuperview() } super.removeFromSuperview() } // MARK: create fileprivate func createButtons(platform: UIView) -> [UIButton] { var buttons = [UIButton]() let step = getArcStep() for index in 0 ..< buttonsCount { let angle: Float = startAngle + Float(index) * step let distance = Float(bounds.size.height / 2.0) let buttonSize: CGSize if let subButtonsRadius = self.subButtonsRadius { buttonSize = CGSize(width: subButtonsRadius * 2, height: subButtonsRadius * 2) } else { buttonSize = bounds.size } let button = customize(CircleMenuButton(size: buttonSize, platform: platform, distance: distance, angle: angle)) { $0.tag = index $0.addTarget(self, action: #selector(CircleMenu.buttonHandler(_:)), for: UIControlEvents.touchUpInside) $0.alpha = 0 } buttons.append(button) } return buttons } fileprivate func addCustomImageView(state: UIControlState) -> UIImageView? { guard let image = image(for: state) else { return nil } let iconView = customize(UIImageView(image: image)) { $0.translatesAutoresizingMaskIntoConstraints = false $0.contentMode = .center $0.isUserInteractionEnabled = false } addSubview(iconView) // added constraints iconView.addConstraint(NSLayoutConstraint(item: iconView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: bounds.size.height)) iconView.addConstraint(NSLayoutConstraint(item: iconView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: bounds.size.width)) addConstraint(NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: iconView, attribute: .centerX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: iconView, attribute: .centerY, multiplier: 1, constant: 0)) return iconView } fileprivate func createPlatform() -> UIView { let platform = customize(UIView(frame: .zero)) { $0.backgroundColor = .clear $0.translatesAutoresizingMaskIntoConstraints = false } superview?.insertSubview(platform, belowSubview: self) // constraints let sizeConstraints = [NSLayoutAttribute.width, .height].map { NSLayoutConstraint(item: platform, attribute: $0, relatedBy: .equal, toItem: nil, attribute: $0, multiplier: 1, constant: CGFloat(distance * Float(2.0))) } platform.addConstraints(sizeConstraints) let centerConstraints = [NSLayoutAttribute.centerX, .centerY].map { NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: platform, attribute: $0, multiplier: 1, constant: 0) } superview?.addConstraints(centerConstraints) return platform } // MARK: configure fileprivate func addActions(newEvent: UIControlEvents, oldEvent: UIControlEvents? = nil) { if let oldEvent = oldEvent { removeTarget(self, action: #selector(CircleMenu.onTap), for: oldEvent) } addTarget(self, action: #selector(CircleMenu.onTap), for: newEvent) } /** Retrieves the incremental lengths between buttons. If the arc length is 360 degrees or more, the increments will evenly space out in a full circle. If the arc length is less than 360 degrees, the last button will be placed on the endAngle. */ fileprivate func getArcStep() -> Float { var arcLength = endAngle - startAngle var stepCount = buttonsCount if arcLength < 360 { stepCount -= 1 } else if arcLength > 360 { arcLength = 360 } return arcLength / Float(stepCount) } // MARK: actions private var isBounceAnimating: Bool = false @objc func onTap() { guard isBounceAnimating == false else { return } isBounceAnimating = true if buttonsIsShown() == false { let platform = createPlatform() buttons = createButtons(platform: platform) self.platform = platform } let isShow = !buttonsIsShown() let duration = isShow ? 0.5 : 0.2 buttonsAnimationIsShow(isShow: isShow, duration: duration) tapBounceAnimation(duration: 0.5) { [weak self] _ in self?.isBounceAnimating = false } tapRotatedAnimation(0.3, isSelected: isShow) } @objc func buttonHandler(_ sender: CircleMenuButton) { guard let platform = self.platform else { return } delegate?.circleMenu?(self, buttonWillSelected: sender, atIndex: sender.tag) let strokeWidth: CGFloat if let radius = self.subButtonsRadius { strokeWidth = radius * 2 } else { strokeWidth = bounds.size.height } let circle = CircleMenuLoader(radius: CGFloat(distance), strokeWidth: strokeWidth, platform: platform, color: sender.backgroundColor) if let container = sender.container { // rotation animation sender.rotationAnimation(container.angleZ + 360, duration: duration) container.superview?.bringSubview(toFront: container) } let step = getArcStep() circle.fillAnimation(duration, startAngle: -90 + startAngle + step * Float(sender.tag)) { [weak self] in self?.buttons?.forEach { $0.alpha = 0 } } circle.hideAnimation(0.5, delay: duration) { [weak self] in if self?.platform?.superview != nil { self?.platform?.removeFromSuperview() } } hideCenterButton(duration: 0.3) showCenterButton(duration: 0.525, delay: duration) DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: { self.delegate?.circleMenu?(self, buttonDidSelected: sender, atIndex: sender.tag) }) } // MARK: animations fileprivate func buttonsAnimationIsShow(isShow: Bool, duration: Double, hideDelay: Double = 0) { guard let buttons = self.buttons else { return } let step = getArcStep() for index in 0 ..< buttonsCount { guard case let button as CircleMenuButton = buttons[index] else { continue } if isShow == true { delegate?.circleMenu?(self, willDisplay: button, atIndex: index) let angle: Float = startAngle + Float(index) * step button.rotatedZ(angle: angle, animated: false, delay: Double(index) * showDelay) button.showAnimation(distance: distance, duration: duration, delay: Double(index) * showDelay) } else { button.hideAnimation(distance: Float(bounds.size.height / 2.0), duration: duration, delay: hideDelay) } } if isShow == false { // hide buttons and remove self.buttons = nil delegate?.menuCollapsed?(self) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) { if self.platform?.superview != nil { self.platform?.removeFromSuperview() } } } } fileprivate func tapBounceAnimation(duration: TimeInterval, completion: ((Bool)->())? = nil) { transform = CGAffineTransform(scaleX: 0.9, y: 0.9) UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 5, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: completion) } fileprivate func tapRotatedAnimation(_ duration: Float, isSelected: Bool) { let addAnimations: (_ view: UIImageView, _ isShow: Bool) -> Void = { view, isShow in var toAngle: Float = 180.0 var fromAngle: Float = 0 var fromScale = 1.0 var toScale = 0.2 var fromOpacity = 1 var toOpacity = 0 if isShow == true { toAngle = 0 fromAngle = -180 fromScale = 0.2 toScale = 1.0 fromOpacity = 0 toOpacity = 1 } let rotation = customize(CABasicAnimation(keyPath: "transform.rotation")) { $0.duration = TimeInterval(duration) $0.toValue = (toAngle.degrees) $0.fromValue = (fromAngle.degrees) $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } let fade = customize(CABasicAnimation(keyPath: "opacity")) { $0.duration = TimeInterval(duration) $0.fromValue = fromOpacity $0.toValue = toOpacity $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false } let scale = customize(CABasicAnimation(keyPath: "transform.scale")) { $0.duration = TimeInterval(duration) $0.toValue = toScale $0.fromValue = fromScale $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } view.layer.add(rotation, forKey: nil) view.layer.add(fade, forKey: nil) view.layer.add(scale, forKey: nil) } if let customNormalIconView = self.customNormalIconView { addAnimations(customNormalIconView, !isSelected) } if let customSelectedIconView = self.customSelectedIconView { addAnimations(customSelectedIconView, isSelected) } self.isSelected = isSelected alpha = isSelected ? 0.3 : 1 } fileprivate func hideCenterButton(duration: Double, delay: Double = 0) { UIView.animate(withDuration: TimeInterval(duration), delay: TimeInterval(delay), options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) }, completion: nil) } fileprivate func showCenterButton(duration: Float, delay: Double) { UIView.animate(withDuration: TimeInterval(duration), delay: TimeInterval(delay), usingSpringWithDamping: 0.78, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1, y: 1) self.alpha = 1 }, completion: nil) let rotation = customize(CASpringAnimation(keyPath: "transform.rotation")) { $0.duration = TimeInterval(1.5) $0.toValue = 0 $0.fromValue = (Float(-180).degrees) $0.damping = 10 $0.initialVelocity = 0 $0.beginTime = CACurrentMediaTime() + delay } let fade = customize(CABasicAnimation(keyPath: "opacity")) { $0.duration = TimeInterval(0.01) $0.toValue = 0 $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false $0.beginTime = CACurrentMediaTime() + delay } let show = customize(CABasicAnimation(keyPath: "opacity")) { $0.duration = TimeInterval(duration) $0.toValue = 1 $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false $0.beginTime = CACurrentMediaTime() + delay } customNormalIconView?.layer.add(rotation, forKey: nil) customNormalIconView?.layer.add(show, forKey: nil) customSelectedIconView?.layer.add(fade, forKey: nil) } } // MARK: extension internal extension Float { var radians: Float { return self * (Float(180) / Float.pi) } var degrees: Float { return self * Float.pi / 180.0 } } internal extension UIView { var angleZ: Float { return atan2(Float(transform.b), Float(transform.a)).radians } }
mit
c611347db8b2f91081d6528f235b3623
36.799629
136
0.606508
5.116524
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/EditorTextView+Scaling.swift
2
3702
// // EditorTextView+Scaling.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2016-07-10. // // --------------------------------------------------------------------------- // // © 2016-2021 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa extension EditorTextView { // MARK: View Methods /// change scale by pinch gesture override func magnify(with event: NSEvent) { if event.phase.contains(.began) { self.deferredMagnification = 0 self.initialMagnificationScale = self.scale } var scale = self.scale * (1 + event.magnification) // hold a bit at scale 1.0 if (self.initialMagnificationScale > 1.0 && scale < 1.0) || // zoom-out (self.initialMagnificationScale <= 1.0 && scale >= 1.0) // zoom-in { self.deferredMagnification += event.magnification if abs(self.deferredMagnification) > 0.4 { scale = self.scale + self.deferredMagnification / 2 self.deferredMagnification = 0 self.initialMagnificationScale = scale } else { scale = 1.0 } } // sanitize final scale if event.phase.contains(.ended), abs(scale - 1.0) < 0.05 { scale = 1.0 } guard scale != self.scale else { return } let center = self.convert(event.locationInWindow, from: nil) if scale == 1.0 { NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .default) } self.setScale(scale, centeredAt: center) } /// reset scale by two-finger double tap override func smartMagnify(with event: NSEvent) { let scale = (self.scale == 1.0) ? 1.5 : 1.0 let center = self.convert(event.locationInWindow, from: nil) self.setScale(scale, centeredAt: center) } // MARK: Action Messages /// change scale from segmented control button @IBAction func changeTextSize(_ sender: NSSegmentedControl) { switch sender.selectedSegment { case 0: self.smallerFont(sender) case 1: self.biggerFont(sender) default: assertionFailure("Segmented text size button must have 2 segments only.") } } /// scale up @IBAction func biggerFont(_ sender: Any?) { self.setScaleKeepingVisibleArea(self.scale * 1.1) } /// scale down @IBAction func smallerFont(_ sender: Any?) { self.setScaleKeepingVisibleArea(self.scale / 1.1) } /// reset scale and font to default @IBAction func resetFont(_ sender: Any?) { let name = UserDefaults.standard[.fontName] let size = UserDefaults.standard[.fontSize] let font = NSFont(name: name, size: size) ?? NSFont.userFont(ofSize: size) self.font = font self.setScaleKeepingVisibleArea(1.0) } }
apache-2.0
b10019723b2a7c83f395923bc301bfcd
28.608
99
0.568225
4.486061
false
false
false
false
TotalDigital/People-iOS
Pods/p2.OAuth2/SwiftKeychain/Keychain/Keychain.swift
5
5198
// // Keychain.swift // Keychain // // Created by Yanko Dimitrov on 2/6/16. // Copyright © 2016 Yanko Dimitrov. All rights reserved. // import Foundation // MARK: - KeychainServiceType public protocol KeychainServiceType { func insertItemWithAttributes(_ attributes: [String: Any]) throws func removeItemWithAttributes(_ attributes: [String: Any]) throws func fetchItemWithAttributes(_ attributes: [String: Any]) throws -> [String: Any]? } // MARK: - KeychainItemType public protocol KeychainItemType { var accessMode: String {get} var accessGroup: String? {get} var attributes: [String: Any] {get} var data: [String: Any] {get set} var dataToStore: [String: Any] {get} } extension KeychainItemType { public var accessMode: String { return String(kSecAttrAccessibleWhenUnlocked) } public var accessGroup: String? { return nil } } extension KeychainItemType { internal var attributesToSave: [String: Any] { var itemAttributes = attributes let archivedData = NSKeyedArchiver.archivedData(withRootObject: dataToStore) itemAttributes[String(kSecValueData)] = archivedData if let group = accessGroup { itemAttributes[String(kSecAttrAccessGroup)] = group } return itemAttributes } internal func dataFromAttributes(_ attributes: [String: Any]) -> [String: Any]? { guard let valueData = attributes[String(kSecValueData)] as? Data else { return nil } return NSKeyedUnarchiver.unarchiveObject(with: valueData) as? [String: Any] ?? nil } internal var attributesForFetch: [String: Any] { var itemAttributes = attributes itemAttributes[String(kSecReturnData)] = kCFBooleanTrue itemAttributes[String(kSecReturnAttributes)] = kCFBooleanTrue if let group = accessGroup { itemAttributes[String(kSecAttrAccessGroup)] = group } return itemAttributes } } // MARK: - KeychainGenericPasswordType public protocol KeychainGenericPasswordType: KeychainItemType { var serviceName: String {get} var accountName: String {get} } extension KeychainGenericPasswordType { public var serviceName: String { return "swift.keychain.service" } public var attributes: [String: Any] { var attributes = [String: Any]() attributes[String(kSecClass)] = kSecClassGenericPassword attributes[String(kSecAttrAccessible)] = accessMode attributes[String(kSecAttrService)] = serviceName attributes[String(kSecAttrAccount)] = accountName return attributes } } // MARK: - Keychain public struct Keychain: KeychainServiceType { internal func errorForStatusCode(_ statusCode: OSStatus) -> NSError { return NSError(domain: "swift.keychain.error", code: Int(statusCode), userInfo: nil) } // Inserts or updates a keychain item with attributes public func insertItemWithAttributes(_ attributes: [String: Any]) throws { var statusCode = SecItemAdd(attributes as CFDictionary, nil) if statusCode == errSecDuplicateItem { SecItemDelete(attributes as CFDictionary) statusCode = SecItemAdd(attributes as CFDictionary, nil) } if statusCode != errSecSuccess { throw errorForStatusCode(statusCode) } } public func removeItemWithAttributes(_ attributes: [String: Any]) throws { let statusCode = SecItemDelete(attributes as CFDictionary) if statusCode != errSecSuccess { throw errorForStatusCode(statusCode) } } public func fetchItemWithAttributes(_ attributes: [String: Any]) throws -> [String: Any]? { var result: AnyObject? let statusCode = SecItemCopyMatching(attributes as CFDictionary, &result) if statusCode != errSecSuccess { throw errorForStatusCode(statusCode) } if let result = result as? [String: Any] { return result } return nil } } // MARK: - KeychainItemType + Keychain extension KeychainItemType { public func saveInKeychain(_ keychain: KeychainServiceType = Keychain()) throws { try keychain.insertItemWithAttributes(attributesToSave) } public func removeFromKeychain(_ keychain: KeychainServiceType = Keychain()) throws { try keychain.removeItemWithAttributes(attributes) } public mutating func fetchFromKeychain(_ keychain: KeychainServiceType = Keychain()) throws -> Self { if let result = try keychain.fetchItemWithAttributes(attributesForFetch), let itemData = dataFromAttributes(result) { data = itemData } return self } }
apache-2.0
2edd61bbb9ed2e3fc8f509302e3fc6dc
25.78866
105
0.618819
5.630553
false
false
false
false
realDogbert/myScore
myScore/ScoreViewController.swift
1
3689
// // ViewController.swift // myScore // // Created by Frank on 20.07.14. // Copyright (c) 2014 Frank von Eitzen. All rights reserved. // import UIKit class ScoreViewController: UIViewController { @IBOutlet weak var lblHits: UILabel! @IBOutlet weak var lblPutts: UILabel! @IBOutlet weak var lblPenalty: UILabel! @IBOutlet weak var lblHole: UILabel! @IBOutlet weak var lblTotal: UILabel! @IBOutlet weak var lblLength: UILabel! @IBOutlet weak var lblPar: UILabel! @IBOutlet weak var stepperHits: UIStepper! @IBOutlet weak var stepperPutts: UIStepper! @IBOutlet weak var stepperPenalties: UIStepper! @IBOutlet weak var imgAverage: UIImageView! @IBOutlet weak var imgTotalAverage: UIImageView! var hole: Hole! var match: Match! var imgArrowUp = UIImage(named: "Arrow_Up") var imgArrowDown = UIImage(named: "Arrow_Down") var imgArrowSame = UIImage(named: "Arrow_Same") override func viewDidLoad() { super.viewDidLoad() lblHits.text = "\(hole.score.strokes)" lblPutts.text = "\(hole.score.putts)" lblPenalty.text = "\(hole.score.penalties)" stepperHits.value = Double(hole.score.strokes) stepperPutts.value = Double(hole.score.putts) stepperPenalties.value = Double(hole.score.penalties) lblHole.text = "Nr. \(hole.number)" lblPar.text = "Par: \(hole.par)" lblLength.text = "Len: \(hole.length)" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateScore() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateTotalScore() { lblTotal.text = "Ges: \(match.getTotalScore())" } func updateHitsColor() { if hole.score.strokes <= hole.par { lblHits.textColor = UIColor.greenColor() } else { lblHits.textColor = UIColor.blackColor() } } func updateScore() { stepperHits.value = Double(hole.score.strokes) stepperPutts.value = Double(hole.score.putts) stepperPenalties.value = Double(hole.score.penalties) lblHits.text = hole.score.strokes.description lblPutts.text = hole.score.putts.description lblPenalty.text = hole.score.penalties.description //imgAverage.hidden = !(hole.score.strokes > hole.average) switch (hole.score.strokes - hole.average) { case -100...(-1): imgAverage.image = imgArrowUp case 1...100: imgAverage.image = imgArrowDown default: imgAverage.image = imgArrowSame } switch match.getCalculatedAverage() { case -1: imgTotalAverage.image = imgArrowUp case 1: imgTotalAverage.image = imgArrowDown default: imgTotalAverage.image = imgArrowSame } updateHitsColor() updateTotalScore() } @IBAction func updateHits(sender: AnyObject) { hole.score.strokes = Int(stepperHits.value) updateScore() } @IBAction func updatePutts(sender: AnyObject) { hole.score.putts = Int(stepperPutts.value) updateScore() } @IBAction func updatePenalties(sender: AnyObject) { hole.score.penalties = Int(stepperPenalties.value) updateScore() } }
mit
cf5d7d163900c19838489474516b719a
26.529851
66
0.594199
4.3349
false
false
false
false
CandyTrace/CandyTrace
Always Write/Controllers/ChartVC.swift
1
1427
// // ChartVC.swift // Always Write // // Created by Sam Raudabaugh on 3/12/17. // Copyright © 2017 Cornell Tech. All rights reserved. // import UIKit class ChartVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.setBackgroundImage(UIImage(named: "nav-pink"), for: .default) navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Futura-Bold", size: 32)!] title = "PROGRESS REPORT" let profileButton = UIBarButtonItem(image: UIImage(named: "profile-icon"), style: .plain, target: self, action: #selector(profileTapped)) profileButton.tintColor = .black navigationItem.setLeftBarButton(profileButton, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func profileTapped() { let _ = navigationController?.popViewController(animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
90b6d1d89d70c3fcb695d2fd9a076d05
31.409091
145
0.685133
4.817568
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPShopPhotoCell.swift
1
1572
// // KPShopPhotoCell.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/4/18. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit class KPShopPhotoCell: UICollectionViewCell { var shopPhoto: UIImageView! lazy var overlayView: UIView = { let overlay = UIView() overlay.backgroundColor = UIColor.black overlay.alpha = 0.2 return overlay }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.white alpha = 0.4 shopPhoto = UIImageView() shopPhoto.contentMode = .scaleAspectFit shopPhoto.layer.cornerRadius = 2.0 shopPhoto.layer.masksToBounds = true shopPhoto.contentMode = .scaleAspectFill addSubview(shopPhoto) shopPhoto.addConstraints(fromStringArray: ["H:|[$self]|", "V:|[$self]|"]) addSubview(overlayView) overlayView.isUserInteractionEnabled = false overlayView.alpha = 0.0 overlayView.addConstraints(fromStringArray: ["V:|[$self]|", "H:|[$self]|"]) } override var isHighlighted: Bool { didSet { UIView.animate(withDuration: 0.1) { self.overlayView.alpha = self.isHighlighted ? 0.2 : 0 } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
92fb574b3e90537f897ed355e52d8587
26.526316
69
0.554493
5.028846
false
false
false
false
billdonner/sheetcheats9
sc9/TemplateSW.swift
1
2859
// // TemplateSW.swift // // Created by william donner on 9/27/15. // import UIKit //use this to callback into parent view controllers protocol TemplateSWDelegate{ } extension TemplateSWDelegate{ } //even if there is no customization, always wrap and refer to cells distinctly in Interface builder final class TemplateSWCell: UITableViewCell{ } // framework for view controller with or without TableView final class TemplateSWViewController: UIViewController,ModelData { // if supplied, status and async return results can be posted var delegate:TemplateSWDelegate? let CELLID = "TemplateSWTableCellID" let NEXTSCENESEQUEID = "ShowContentSegueID" // if this is a tableview, include this line @IBOutlet weak var tableView: UITableView! // always call cleanup, it removes observers deinit { self.cleanupFontSizeAware(self) } // calling another viewcontroller is almost often done manuall // via performSegueWithIdentifier // there is almost always a need to catch the segue in progress to pass along arguments override func viewDidLoad() { super.viewDidLoad() // respond to content size changes self.setupFontSizeAware(self) // for tables do the normal setup self.tableView.registerClass(TemplateSWCell.self, forCellReuseIdentifier: CELLID) self.tableView.dataSource = self self.tableView.delegate = self } // if you want to let storyboard flows come back here then include this line: @IBAction func unwindToVC(segue: UIStoryboardSegue) {} } extension TemplateSWViewController :SegueHelpers { override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { self.prepForSegue(segue , sender: sender) } } extension TemplateSWViewController : FontSizeAware { func refreshFontSizeAware(vc:TemplateSWViewController) { vc.view.setNeedsDisplay() } } extension TemplateSWViewController:UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return self.recentsCount() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(CELLID, forIndexPath: indexPath) as! TemplateSWCell // Configure the cell... cell.configureCell(self.recentsData(indexPath.row)) return cell } } extension TemplateSWViewController : UITableViewDelegate {// func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.storeStringArgForSeque( self.recentsData(indexPath.item).title ) // the arguments for the next scene need to be stashed and the transition started self.presentAny(self,identifier:NEXTSCENESEQUEID) } }
apache-2.0
491e236d40ee208a9810d6fb900f0998
24.765766
108
0.776845
4.216814
false
false
false
false
EricHein/Swift3.0Practice2016
00.ScratchWork/SpinnersAndAlerts/SpinnersAndAlerts/ViewController.swift
1
2150
// // ViewController.swift // SpinnersAndAlerts // // Created by Eric H on 30/11/2016. // Copyright © 2016 FabledRealm. All rights reserved. // import UIKit class ViewController: UIViewController { var activityIndicatior = UIActivityIndicatorView () override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func alertButtonTapped(_ sender: UIButton) { let alertController = UIAlertController (title: "Test", message: "TestMessage", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (action) in print("Ok button pressed") self.dismiss(animated: true, completion: nil) })) alertController.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: { (action) in print(" No button pressed") self.dismiss(animated: true, completion: nil) })) self.present(alertController, animated: true, completion: nil) } @IBAction func pauseAppTapped(_ sender: Any) { activityIndicatior = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) activityIndicatior.center = self.view.center activityIndicatior.hidesWhenStopped = true activityIndicatior.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray view.addSubview(activityIndicatior) activityIndicatior.startAnimating() //UIApplication.shared.beginIgnoringInteractionEvents() } @IBAction func restoreAppButtonTapped(_ sender: Any) { activityIndicatior.stopAnimating() //UIApplication.shared.endIgnoringInteractionEvents() } }
gpl-3.0
100102fb1ba73e86b7d047119fa595b4
29.267606
133
0.63611
5.468193
false
false
false
false
ludoded/ReceiptBot
ReceiptBot/Scene/Auth/SignIn/SignInInteractor.swift
1
3587
// // SignInInteractor.swift // ReceiptBot // // Created by Haik Ampardjian on 4/8/17. // Copyright (c) 2017 receiptbot. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol SignInInteractorOutput { func presentLogin(response: SignIn.Login.Response) func presentCompleteProfile() func presentRegister(response: SignIn.Google.Response) } class SignInInteractor { var output: (SignInInteractorOutput & PasswordRecoveryInteractorOutput)! var worker: SignInWorker! var extWorker: ExternalLoginWorker! var completeProfileInfo: SignIn.CompleteProfileInfo! // MARK: - Business logic func tryToLogin(request: SignIn.Login.Request) { worker = SignInWorker(email: request.email ?? "", password: request.password ?? "") worker.tryToLogin { [weak self] (wrapper) in DispatchQueue.main.async { self?.passAuthData(data: wrapper) } } } func recoveryPassword(request: PasswordRecoveryModel.Request) { let passwordWorker = PasswordRecoveryWorker(with: request.email) passwordWorker.tryToRecovery { [weak self] (data) in DispatchQueue.main.async { self?.passStatus(data: data) } } } func tryToSignUp(request: SignIn.Google.Request) { let registerWorker = SignUpWorker(email: request.email, password: request.password) registerWorker.tryToSignUp { [weak self] (resp) in switch resp { case .none: DispatchQueue.main.async { self?.passRegister(data: resp) } case .value(let data): if !data.isVerified && !data.userAlreadyCreated || !data.isOrgExist { DispatchQueue.main.async { self?.passCompleteProfile(email: request.email, name: request.name) } } else if !data.isVerified && data.userAlreadyCreated { DispatchQueue.main.async { self?.passRegister(data: .none(message: "User Already Registered, Please Verify your Email Address")) } } else if data.isVerified && data.userAlreadyCreated { self?.tryToExternalSignIn(request: request) } else { DispatchQueue.main.async { self?.passRegister(data: resp) } } } } } func tryToExternalSignIn(request: SignIn.Google.Request) { extWorker = ExternalLoginWorker(email: request.email) extWorker.tryToLogin { [weak self] (resp) in DispatchQueue.main.async { self?.passAuthData(data: resp) } } } /// MARK: passing data func passAuthData(data: RebotValueWrapper<AuthResponse>) { let response = SignIn.Login.Response(data: data) output.presentLogin(response: response) } func passStatus(data: RebotValueWrapper<StatusDetailResponse>) { let response = PasswordRecoveryModel.Response(status: data) output.presentRecoveredPassword(response: response) } func passRegister(data: RebotValueWrapper<SignUpFirstResponse>) { let response = SignIn.Google.Response(data: data) output.presentRegister(response: response) } func passCompleteProfile(email: String, name: String) { completeProfileInfo = SignIn.CompleteProfileInfo(email: email, name: name) output.presentCompleteProfile() } }
lgpl-3.0
d9b926106a7c0245b21709a71da68491
37.569892
150
0.644271
4.546261
false
false
false
false
weirdindiankid/Tinder-Clone
TinderClone/Tabs/ChatViewController.swift
1
8308
// // ChatViewController.swift // TinderClone // // Created by Dharmesh Tarapore on 20/01/2015. // Copyright (c) 2015 Dharmesh Tarapore. All rights reserved. // import UIKit class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var arrayUserIds:NSArray = [] var arrayFriends:NSMutableArray = [] // var users:NSArray = [] var arrayUserFriends:NSMutableArray = [] @IBOutlet weak var chatTable: UITableView! override func viewDidLoad() { super.viewDidLoad() fetchFriends() let barButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: Selector("refresh:")) as UIBarButtonItem self.navigationItem.rightBarButtonItem = barButton } func refresh(button : UIBarButtonItem) { self.arrayFriends.removeAllObjects() self.chatTable.reloadData() fetchFriends() } func fetchFriends() { MBProgressHUD.showHUDAddedTo(self.view, animated:true) var queryForConsideredProfiles = PFQuery(className:"ChatTable") queryForConsideredProfiles.whereKey("userID", equalTo: PFUser.currentUser().objectId) queryForConsideredProfiles.findObjectsInBackgroundWithBlock{ (NSArray objects, NSError error) -> Void in if (error != nil) { NSLog("error " + error.localizedDescription) MBProgressHUD.hideHUDForView(self.view, animated:false) } else { if (objects.count > 0) { var chatTableObject = objects[0] as PFObject self.arrayUserIds = chatTableObject["Friends"] as NSArray var userQuery = PFUser.query() userQuery.findObjectsInBackgroundWithBlock{ (NSArray objects, NSError error) -> Void in if (error != nil) { NSLog("error " + error.localizedDescription) } else { let users = objects for userId in self.arrayUserIds { let user = self.getUserFromUserId(userId as String, arrayUsers: users) self.arrayUserFriends.addObject(user) var query = PFQuery(className: "UserPhoto") query.whereKey("user", equalTo: user) query.findObjectsInBackgroundWithBlock{ (NSArray objects, NSError error) -> Void in if(objects.count != 0) { let object = objects[objects.count - 1] as PFObject let theImage = object["imageData"] as PFFile let imageData:NSData = theImage.getData() let image = UIImage(data: imageData) let dictionary = NSDictionary(objects: [user.username, image], forKeys: ["username", "image"]) self.arrayFriends.addObject(dictionary) self.chatTable.reloadData() } } } } MBProgressHUD.hideHUDForView(self.view, animated:false) } } else { MBProgressHUD.hideHUDForView(self.view, animated:false) } } } } /* for var i = self.arrayUsers.count - 1; i >= 0 ; i-- { let user = self.arrayUsers[i] as PFUser var query = PFQuery(className: "UserPhoto") query.whereKey("user", equalTo: user) query.findObjectsInBackgroundWithBlock{ (NSArray objects, NSError error) -> Void in if(objects.count != 0) { self.removeAllDraggableViews() let object = objects[0] as PFObject let theImage = object["imageData"] as PFFile println(theImage) let imageData:NSData = theImage.getData() let image = UIImage(data: imageData) // var viewDraggable = DraggableView(frame: CGRectMake(20.0, 96.0, 280.0, 280.0), delegate: self) as DraggableView let dateOfBirth = self.calculateAge(user["dobstring"] as String) viewDraggable.setUser(user) println(dateOfBirth) viewDraggable.setProfilePicture(image, andName: user.username + ", \(dateOfBirth)") viewDraggable.backgroundColor = UIColor.blackColor() self.view.addSubview(viewDraggable) } } } */ func getUserFromUserId(userID:String, arrayUsers:NSArray) -> PFUser { var requiredUser = PFUser() for aUser in arrayUsers { if (aUser.objectId == userID) { requiredUser = aUser as PFUser break } } return requiredUser } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table View func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayFriends.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell if ((indexPath.row % 2) == 0) { cell.backgroundColor = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1.0) } else { cell.backgroundColor = UIColor.whiteColor() } cell.selectionStyle = UITableViewCellSelectionStyle.Blue let dictionary = self.arrayFriends.objectAtIndex(indexPath.row) as NSDictionary let username = dictionary.objectForKey("username") as String let image = dictionary.objectForKey("image") as UIImage cell.textLabel!.text = username cell.imageView!.image = image var bgColorView = UIView() // bgColorView.backgroundColor = UIColor(red: 76.0/255.0, green: 161.0/255.0, blue: 255.0/255.0, alpha: 1.0) bgColorView.backgroundColor = UIColor(red: 0.78, green: 0.87, blue: 0.94, alpha: 1.0) bgColorView.layer.masksToBounds = true; cell.selectedBackgroundView = bgColorView; return cell } func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat { return 54.0 } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let messageController = storyboard.instantiateViewControllerWithIdentifier("MessagesViewController") as MessagesViewController let dictionary = self.arrayFriends.objectAtIndex(indexPath.row) as NSDictionary messageController.selectedUser = self.arrayUserFriends.objectAtIndex(indexPath.row) as PFUser messageController.profileImage = dictionary.objectForKey("image") as UIImage self.navigationController!.pushViewController(messageController, animated: true) } }
mit
202f3711018904c191e7ba18dacba4d7
35.599119
154
0.535147
5.80573
false
false
false
false
JadenGeller/Racer
Racer/Racer/Mutex.swift
1
3258
// // Mutex.swift // Racer // // Created by Jaden Geller on 10/20/15. // Copyright © 2015 Jaden Geller. All rights reserved. // public protocol MutexType { /** Acquires the mutex before executing the block and releases the mutex afterwards. For any given mutex, it is guarenteed that no two calls to `acquire` will happen at the same time regardless of what thread the call is made from. - Parameter block: The block to run while the mutex is acquired. - Returns: If the block returns some value, it will be propagated out of the function through this return value. */ func acquire<ReturnValue>(block: () -> ReturnValue) -> ReturnValue } /// A basic `MutexType` that handles locking and unlocking automatically within the closure. public class Mutex: MutexType { private let semaphore = Semaphore(value: 1) /** Acquires the mutex before executing the block and releases the mutex afterwards. - Parameter block: The block to run while the mutex is acquired. - Returns: If the block returns some value, it will be propagated out of the function through this return value. */ public func acquire<ReturnValue>(block: () -> ReturnValue) -> ReturnValue { semaphore.wait() let returnValue = block() semaphore.signal() return returnValue } } /// A `MutexType` that handles doesn't become gridlocked on recursive usage. public class RecursiveMutex: MutexType { private let mutex = Mutex() private var alreadyLocked = ThreadLocal(defaultValue: false) /** Acquires the mutex before executing the block and releases the mutex afterwards. - Parameter block: The block to run while the mutex is acquired. This block is allowed to recurse, or call another fuction that acquires the same mutex. - Returns: If the block returns some value, it will be propagated out of the function through this return value. */ public func acquire<ReturnValue>(block: () -> ReturnValue) -> ReturnValue { if !alreadyLocked.localValue { alreadyLocked.localValue = true defer { alreadyLocked.localValue = false } return mutex.acquire(block) } else { // We already locked on this thread. We don't need to lock again. return block() } } } /// A `MutexType` that combines many individual mutex together such that acquiring the /// `MutexGroup` is equivalent to acquiring each individual mutex. public class MutexGroup: MutexType { private let mutexes: [Mutex] init(mutexes: [Mutex]) { self.mutexes = mutexes } /** Acquires the group of mutexes before executing the block and releases the group afterwards. - Parameter block: The block to run while the mutexes are acquired. - Returns: If the block returns some value, it will be propagated out of the function through this return value. */ public func acquire<ReturnValue>(block: () -> ReturnValue) -> ReturnValue { return mutexes.reduce(block) { nested, mutex in { mutex.acquire(nested) } }() } }
mit
9ed17ab01e4fb40d3217954d186cf637
35.188889
106
0.657353
4.666189
false
false
false
false
alessiobrozzi/firefox-ios
SyncTests/StateTests.swift
2
2832
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared @testable import Sync import XCTest func compareScratchpads(tuple: (lhs: Scratchpad, rhs: Scratchpad)) { // This one is set in the constructor! XCTAssertEqual(tuple.lhs.syncKeyBundle, tuple.rhs.syncKeyBundle) XCTAssertEqual(tuple.lhs.clientName, tuple.rhs.clientName) XCTAssertEqual(tuple.lhs.clientGUID, tuple.rhs.clientGUID) if let lkeys = tuple.lhs.keys { if let rkeys = tuple.rhs.keys { XCTAssertEqual(lkeys.timestamp, rkeys.timestamp) XCTAssertEqual(lkeys.value, rkeys.value) } else { XCTAssertTrue(tuple.rhs.keys != nil) } } else { XCTAssertTrue(tuple.rhs.keys == nil) } XCTAssertTrue(tuple.lhs.global == tuple.rhs.global) XCTAssertEqual(tuple.lhs.localCommands, tuple.rhs.localCommands) XCTAssertEqual(tuple.lhs.engineConfiguration, tuple.rhs.engineConfiguration) } func roundtrip(s: Scratchpad) -> (Scratchpad, rhs: Scratchpad) { let prefs = MockProfilePrefs() s.pickle(prefs) return (s, rhs: Scratchpad.restoreFromPrefs(prefs, syncKeyBundle: s.syncKeyBundle)!) } class StateTests: XCTestCase { func getGlobal() -> Fetched<MetaGlobal> { let g = MetaGlobal(syncID: "abcdefghiklm", storageVersion: 5, engines: ["bookmarks": EngineMeta(version: 1, syncID: "dddddddddddd")], declined: ["tabs"]) return Fetched(value: g, timestamp: Date.now()) } func getEngineConfiguration() -> EngineConfiguration { return EngineConfiguration(enabled: ["bookmarks", "clients"], declined: ["tabs"]) } func baseScratchpad() -> Scratchpad { let syncKeyBundle = KeyBundle.fromKB(Bytes.generateRandomBytes(32)) let keys = Fetched(value: Keys(defaultBundle: syncKeyBundle), timestamp: 1001) let b = Scratchpad(b: syncKeyBundle, persistingTo: MockProfilePrefs()).evolve() b.setKeys(keys) b.localCommands = Set([ .enableEngine(engine: "tabs"), .disableEngine(engine: "passwords"), .resetAllEngines(except: Set<String>(["bookmarks", "clients"])), .resetEngine(engine: "clients")]) return b.build() } func testPickling() { compareScratchpads(tuple: roundtrip(s: baseScratchpad())) compareScratchpads(tuple: roundtrip(s: baseScratchpad().evolve().setGlobal(getGlobal()).build())) compareScratchpads(tuple: roundtrip(s: baseScratchpad().evolve().clearLocalCommands().build())) compareScratchpads(tuple: roundtrip(s: baseScratchpad().evolve().setEngineConfiguration(getEngineConfiguration()).build())) } }
mpl-2.0
3ea2ae0081628264d8163e356d83e1ec
40.647059
161
0.682556
4.523962
false
true
false
false
EvanJq/JQNavigationController
JQNavigationController/Classes/UINavigationBar+Extension.swift
1
2994
// // UINavigationBar+Extension.swift // JQNavigationController // // Created by Evan on 2017/7/6. // Copyright © 2017年 ChenJianqiang. All rights reserved. // import UIKit // MARK: - 自定义NavigationBar背景视图,允许设置NavigationBar透明度,背景色等 public extension UINavigationBar { fileprivate struct AssociatedKeys { static var backgroundView: String = "AssociatedKeysBackgroundView" } /// 自定义背景视图 fileprivate var backgroundView: UIView { get { guard let bgView = objc_getAssociatedObject(self, &AssociatedKeys.backgroundView) as? UIView else { let view = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: 96)) view.backgroundColor = barTintColor // _UIBarBackground is first subView for navigationBar subviews.first?.insertSubview(view, at: 0) subviews.first?.clipsToBounds = true self.backgroundView = view return view } return bgView } set { objc_setAssociatedObject(self, &AssociatedKeys.backgroundView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// 设置背景透明度 public func setBackgroundAlpha(alpha: CGFloat) { backgroundView.alpha = alpha } /// 设置背景色 public func setBackgroundColor(color: UIColor?) { if backgroundView.alpha < 1.0 { setBackgroundImage(UIImage(), for: .default) backgroundView.backgroundColor = color } else { setBackgroundImage(nil, for: .default) barTintColor = color } } /// 设置导航栏在垂直方向上平移多少距离 public func setTranslationY(translationY:CGFloat) { transform = CGAffineTransform.init(translationX: 0, y: translationY) } /// 获取导航栏偏移量 public func getTranslationY() -> CGFloat { return transform.ty } } //=============================================================================== // MARK: - Swizzling会改变全局状态,所以用 DispatchQueue.once 来确保无论多少线程都只会被执行一次 //=============================================================================== extension DispatchQueue { fileprivate static var onceTracker = [String]() //Executes a block of code, associated with a unique token, only once. The code is thread safe and will only execute the code once even in the presence of multithreaded calls. class func once(token: String, block: () -> Void) { // 保证被 objc_sync_enter 和 objc_sync_exit 包裹的代码可以有序同步地执行 objc_sync_enter(self) defer { // 作用域结束后执行defer中的代码 objc_sync_exit(self) } if onceTracker.contains(token) { return } onceTracker.append(token) block() } }
mit
653286a6188fa93a68de81feef8ec25c
30.597701
180
0.592215
4.764298
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Venue
companion-iPad/Venue-companion/Controllers/LeaderboardViewController.swift
1
4310
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit class LeaderboardViewController: UIViewController { @IBOutlet weak var leaderboardTable: UITableView! @IBOutlet weak var welcomeHeight: NSLayoutConstraint! let leaderboard = ApplicationDataManager.sharedInstance.globalLeaderboard var sorted: [String] = [] var userIndex = 0 var deviceNear = false override func viewDidLoad() { super.viewDidLoad() if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.bluetoothManager.leaderboardController = self } welcomeHeight.constant = 115 + 30 // Do any additional setup after loading the view. sorted = Array(leaderboard.keys).sort({self.leaderboard[$0] > self.leaderboard[$1]}) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func determineUserIndex() { guard let currentUser = ApplicationDataManager.sharedInstance.currentUser else { return } var i = 0 for name in sorted { if name == currentUser.name { userIndex = i } i++ } if userIndex < 3 { userIndex = 3 } else if userIndex > sorted.count - 4 { userIndex = sorted.count - 4 } leaderboardTable.reloadData() } } extension LeaderboardViewController: UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { if deviceNear{ return 2 } return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if deviceNear { if section == 0 { return 3 } return 7 } return 10 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRectMake(0, 0, tableView.frame.width, 34)) view.backgroundColor = UIColor(white: 1.0, alpha: 0.4) let label = UILabel(frame: CGRectMake(20, -3, tableView.frame.width-20, 34)) label.textColor = UIColor(red: 123/255, green: 158/255, blue: 46/255, alpha: 1.0) label.font = UIFont.boldSystemFontOfSize(15.0) if section == 0 { label.text = "BRICKLAND'S BEST" } else { label.text = "YOUR COMPETITION" } view.addSubview(label) return view } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier("parkScoreCell") as? ScoreTableViewCell { var index: Int! if indexPath.section == 0 { index = 0 + indexPath.row } else { index = userIndex - 3 + indexPath.row } if let score = leaderboard[sorted[index]] { cell.numberLabel.text = "\(index + 1)" cell.nameLabel.text = sorted[index] cell.scoreLabel.text = "\(score) PTS" } return cell } return UITableViewCell() } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { guard let currentUser = ApplicationDataManager.sharedInstance.currentUser else { cell.backgroundColor = UIColor.whiteColor() return } if let cell = cell as? ScoreTableViewCell { if cell.nameLabel.text == currentUser.name { cell.nameLabel.text = "You" cell.backgroundColor = UIColor(white: 1.0, alpha: 0.8) } else { cell.backgroundColor = UIColor.whiteColor() } } } } extension LeaderboardViewController: UITableViewDelegate { }
epl-1.0
73b1e3a5c523e094819a80376b62d14c
28.520548
125
0.567185
5.339529
false
false
false
false
quire-io/SwiftyChrono
Sources/Refiners/EN/ENPrioritizeSpecificDateRefiner.swift
1
5016
// // ENPrioritizeSpecificDateRefiner.swift // SwiftyChrono // // Created by Jerry Chen on 1/23/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation private let PATTERN = "^\\s*(at|after|before|on|,|-|\\(|\\))?\\s*$" private func isMoreSpecific(previousResult: ParsedResult, currentResult: ParsedResult) -> Bool { var moreSpecific = false if previousResult.start.isCertain(component: .year) { if !currentResult.start.isCertain(component: .year) { moreSpecific = true } else { if previousResult.start.isCertain(component: .month) { if !currentResult.start.isCertain(component: .month) { moreSpecific = true } else { if previousResult.start.isCertain(component: .day) && !currentResult.start.isCertain(component: .day) { moreSpecific = true } } } } } return moreSpecific } private func isAbleToMerge(text: String, previousResult: ParsedResult, currentResult: ParsedResult) -> Bool { let (startIndex, endIndex) = sortTwoNumbers(previousResult.index + previousResult.text.count, currentResult.index) let textBetween = text.substring(from: startIndex, to: endIndex) // Only accepts merge if one of them comes from casual relative date let includesRelativeResult = previousResult.tags[.enRelativeDateFormatParser] ?? false || currentResult.tags[.enRelativeDateFormatParser] ?? false // We assume they refer to the same date if all date fields are implied var referToSameDate = !previousResult.start.isCertain(component: .day) && !previousResult.start.isCertain(component: .month) && !previousResult.start.isCertain(component: .year) // If both years are certain, that determines if they refer to the same date // but with one more specific than the other if previousResult.start.isCertain(component: .year) && currentResult.start.isCertain(component: .year) { referToSameDate = previousResult.start[.year]! == currentResult.start[.year] } // We now test with the next level (month) if they refer to the same date if previousResult.start.isCertain(component: .month) && currentResult.start.isCertain(component: .month) { referToSameDate = previousResult.start[.month]! == currentResult.start[.month] && referToSameDate } return includesRelativeResult && NSRegularExpression.isMatch(forPattern: PATTERN, in: textBetween) && referToSameDate } func mergeResult(text: String, specificResult: ParsedResult, nonSpecificResult: ParsedResult) -> ParsedResult { var specificResult = specificResult let startIndex = min(specificResult.index, nonSpecificResult.index) let endIndex = max( specificResult.index + specificResult.text.count, nonSpecificResult.index + nonSpecificResult.text.count) specificResult.index = startIndex specificResult.text = text.substring(from: startIndex, to: endIndex) for tag in nonSpecificResult.tags.keys { specificResult.tags[tag] = true } specificResult.tags[.enPrioritizeSpecificDateRefiner] = true return specificResult } class ENPrioritizeSpecificDateRefiner: Refiner { override public func refine(text: String, results: [ParsedResult], opt: [OptionType: Int]) -> [ParsedResult] { var results = results let resultsLength = results.count if resultsLength < 2 { return results } var mergedResults = [ParsedResult]() var currentResult: ParsedResult? var previousResult: ParsedResult var i = 1 while i < resultsLength { currentResult = results[i] previousResult = results[i-1] if isMoreSpecific(previousResult: previousResult, currentResult: currentResult!) && isAbleToMerge(text: text, previousResult: previousResult, currentResult: currentResult!) { results[i] = mergeResult(text: text, specificResult: previousResult, nonSpecificResult: currentResult!) currentResult = results[i] i += 1 continue } else if isMoreSpecific(previousResult: currentResult!, currentResult: previousResult) && isAbleToMerge(text: text, previousResult: previousResult, currentResult: currentResult!) { results[i] = mergeResult(text: text, specificResult: currentResult!, nonSpecificResult: previousResult) currentResult = results[i] i += 1 continue } mergedResults.append(previousResult) i += 1 } if let currentResult = currentResult { mergedResults.append(currentResult) } return mergedResults } }
mit
9e9d37efd0594bd1844e0d03651f13bc
36.706767
181
0.645264
4.749053
false
false
false
false
yacir/YBSlantedCollectionViewLayout
Examples/CollectionViewSlantedLayoutDemo/CustomCollectionCell.swift
1
1428
// // CustomCollectionCell.swift // CollectionViewSlantedLayout // // Created by Yassir Barchi on 28/02/2016. // Copyright © 2016-present Yassir Barchi. All rights reserved. // import Foundation import UIKit import CollectionViewSlantedLayout let yOffsetSpeed: CGFloat = 150.0 let xOffsetSpeed: CGFloat = 100.0 class CustomCollectionCell: CollectionViewSlantedCell { @IBOutlet weak var imageView: UIImageView! private var gradient = CAGradientLayer() override func awakeFromNib() { super.awakeFromNib() if let backgroundView = backgroundView { gradient.colors = [UIColor.clear.cgColor, UIColor.black.cgColor] gradient.locations = [0.0, 1.0] gradient.frame = backgroundView.bounds backgroundView.layer.addSublayer(gradient) } } override func layoutSubviews() { super.layoutSubviews() if let backgroundView = backgroundView { gradient.frame = backgroundView.bounds } } var image: UIImage = UIImage() { didSet { imageView.image = image } } var imageHeight: CGFloat { return (imageView?.image?.size.height) ?? 0.0 } var imageWidth: CGFloat { return (imageView?.image?.size.width) ?? 0.0 } func offset(_ offset: CGPoint) { imageView.frame = imageView.bounds.offsetBy(dx: offset.x, dy: offset.y) } }
mit
14265d2ae9be3b43fd6864ea932da52e
23.603448
79
0.644709
4.390769
false
false
false
false
audiokit/AudioKit
Sources/AudioKit/Operations/Generators/Oscillators/fmOscillatorOperation.swift
2
1545
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ extension Operation { /// Classic FM Synthesis audio generation. /// /// - Parameters: /// - baseFrequency: In cycles per second, or Hz, this is the common denominator for the carrier and modulating /// frequencies. (Default: 440, Minimum: 0.0, Maximum: 20000.0) /// - carrierMultiplier: This multiplied by the baseFrequency gives the carrier frequency. /// (Default: 1.0, Minimum: 0.0, Maximum: 1000.0) /// - modulatingMultiplier: This multiplied by the baseFrequency gives the modulating frequency. /// (Default: 1.0, Minimum: 0.0, Maximum: 1000.0) /// - modulationIndex: This multiplied by the modulating frequency gives the modulation amplitude. /// (Default: 1.0, Minimum: 0.0, Maximum: 1000.0) /// - amplitude: Output Amplitude. (Default: 0.5, Minimum: 0.0, Maximum: 10.0) /// public static func fmOscillator( baseFrequency: OperationParameter = 440, carrierMultiplier: OperationParameter = 1.0, modulatingMultiplier: OperationParameter = 1.0, modulationIndex: OperationParameter = 1.0, amplitude: OperationParameter = 0.5 ) -> Operation { return Operation(module: "fm", inputs: baseFrequency, amplitude, carrierMultiplier, modulatingMultiplier, modulationIndex) } }
mit
f57ba511f8827551e00e7b3519bcd88d
52.275862
117
0.620712
4.813084
false
false
false
false
Ramotion/navigation-stack
Source/CollectionView/CollectionStackViewController.swift
1
7548
// // CollectionStackViewController.swift // NavigationStackDemo // // Copyright (c) 26/02/16 Ramotion Inc. (http://ramotion.com) // // 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 UIKit fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // MARK: CollectionStackViewController protocol CollectionStackViewControllerDelegate: class { func controllerDidSelected(index: Int) } class CollectionStackViewController: UICollectionViewController { fileprivate var screens: [UIImage] fileprivate let overlay: Float weak var delegate: CollectionStackViewControllerDelegate? init(images: [UIImage], delegate: CollectionStackViewControllerDelegate?, overlay: Float, scaleRatio: Float, scaleValue: Float, bgColor: UIColor = UIColor.clear, bgView: UIView? = nil, decelerationRate: CGFloat) { screens = images self.delegate = delegate self.overlay = overlay let layout = CollectionViewStackFlowLayout(itemsCount: images.count, overlay: overlay, scaleRatio: scaleRatio, scale: scaleValue) super.init(collectionViewLayout: layout) if let collectionView = self.collectionView { collectionView.backgroundColor = bgColor collectionView.backgroundView = bgView collectionView.decelerationRate = UIScrollView.DecelerationRate(rawValue: decelerationRate) } } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { configureCollectionView() scrolltoIndex(screens.count - 1, animated: false, position: .left) // move to end } override func viewDidAppear(_: Bool) { guard let collectionViewLayout = self.collectionViewLayout as? CollectionViewStackFlowLayout else { fatalError("wrong collection layout") } collectionViewLayout.openAnimating = true scrolltoIndex(0, animated: true, position: .left) // open animation } } // MARK: configure extension CollectionStackViewController { fileprivate func configureCollectionView() { guard let collectionViewLayout = self.collectionViewLayout as? UICollectionViewFlowLayout else { fatalError("wrong collection layout") } collectionViewLayout.scrollDirection = .horizontal collectionView?.showsHorizontalScrollIndicator = false collectionView?.register(CollectionViewStackCell.self, forCellWithReuseIdentifier: String(describing: CollectionViewStackCell.self)) } } // MARK: CollectionViewDataSource extension CollectionStackViewController { override func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int { return screens.count } override func collectionView(_: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let cell = cell as? CollectionViewStackCell { cell.imageView?.image = screens[(indexPath as NSIndexPath).row] } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CollectionViewStackCell.self), for: indexPath) return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let currentCell = collectionView.cellForItem(at: indexPath) else { return } // move cells UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { () -> Void in for cell in self.collectionView!.visibleCells where cell != currentCell { let row = (self.collectionView?.indexPath(for: cell) as NSIndexPath?)?.row let xPosition = row < (indexPath as NSIndexPath).row ? cell.center.x - self.view.bounds.size.width * 2 : cell.center.x + self.view.bounds.size.width * 2 cell.center = CGPoint(x: xPosition, y: cell.center.y) } }, completion: nil) // move to center current cell UIView.animate(withDuration: 0.2, delay: 0.2, options: .curveEaseOut, animations: { () -> Void in let offset = collectionView.contentOffset.x - (self.view.bounds.size.width - collectionView.bounds.size.width * CGFloat(self.overlay)) * CGFloat((indexPath as NSIndexPath).row) currentCell.center = CGPoint(x: (currentCell.center.x + offset), y: currentCell.center.y) }, completion: nil) // scale current cell UIView.animate(withDuration: 0.2, delay: 0.6, options: .curveEaseOut, animations: { () -> Void in let scale = CGAffineTransform(scaleX: 1, y: 1) currentCell.transform = scale currentCell.alpha = 1 }) { (_) -> Void in DispatchQueue.main.async(execute: { () -> Void in self.delegate?.controllerDidSelected(index: (indexPath as NSIndexPath).row) self.dismiss(animated: false, completion: nil) }) } } } // MARK: UICollectionViewDelegateFlowLayout extension CollectionStackViewController: UICollectionViewDelegateFlowLayout { func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt _: IndexPath) -> CGSize { return view.bounds.size } func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, minimumLineSpacingForSectionAt _: NSInteger) -> CGFloat { return -collectionView.bounds.size.width * CGFloat(overlay) } } // MARK: Additional helpers extension CollectionStackViewController { fileprivate func scrolltoIndex(_ index: Int, animated: Bool, position: UICollectionView.ScrollPosition) { let indexPath = IndexPath(item: index, section: 0) collectionView?.scrollToItem(at: indexPath, at: position, animated: animated) } }
mit
8e63afe262471e8a0caac3cf6d55dc94
38.726316
203
0.665474
5.32299
false
false
false
false
brave/browser-ios
Shared/SystemUtils.swift
1
2544
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation /** * System helper methods written in Swift. */ public struct SystemUtils { /** Returns an accurate version of the system uptime even while the device is asleep. http://stackoverflow.com/questions/12488481/getting-ios-system-uptime-that-doesnt-pause-when-asleep - returns: Time interval since last reboot. */ public static func systemUptime() -> TimeInterval { var boottime = timeval() var mib = [CTL_KERN, KERN_BOOTTIME] var size = MemoryLayout<timeval>.stride var now = time_t() time(&now) sysctl(&mib, u_int(mib.count), &boottime, &size, nil, 0) let tv_sec: time_t = withUnsafePointer(to: &boottime.tv_sec) { $0.pointee } return TimeInterval(now - tv_sec) } } extension SystemUtils { // This should be run on first run of the application. // It shouldn't be run from an extension. // Its function is to write a lock file that is only accessible from the application, // and not accessible from extension when the device is locked. Thus, we can tell if an extension is being run // when the device is locked. public static func onFirstRun() { guard let lockFileURL = lockedDeviceURL else { return } let lockFile = lockFileURL.path let fm = FileManager.default if fm.fileExists(atPath: lockFile) { return } let contents = "Device is unlocked".data(using: String.Encoding.utf8) fm.createFile(atPath: lockFile, contents: contents, attributes: [FileAttributeKey(rawValue: FileAttributeKey.protectionKey.rawValue): FileProtectionType.complete]) } private static var lockedDeviceURL: URL? { let directoryURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppInfo.sharedContainerIdentifier) return directoryURL?.appendingPathComponent("security.dummy") } public static func isDeviceLocked() -> Bool { guard let lockFileURL = lockedDeviceURL else { return true } do { _ = try Data(contentsOf: lockFileURL, options: .mappedIfSafe) return false } catch let err as NSError { return err.code == 257 } catch _ { return true } } }
mpl-2.0
8aa3a92f6993a88257b353ebe7a8bc70
35.869565
171
0.650943
4.401384
false
false
false
false
fthomasmorel/FTMainColor
FTMainColor/FTColor.swift
1
1757
// // FTColor.swift // MainColor // // Created by Florent TM on 29/07/2015. // Copyright © 2015 Florent THOMAS MOREL. All rights reserved. // import Foundation import UIKit public struct FTColor { public var red:CGFloat! public var green:CGFloat! public var blue:CGFloat! public func getUIColor() -> UIColor{ return UIColor(red: self.red, green: self.green, blue: self.blue, alpha: CGFloat(1)) } } func getPixelColor(image:UIImage, pos: CGPoint) -> FTColor { let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage)) let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) let pixelInfo: Int = ((Int(image.size.width) * Int(pos.y)) + Int(pos.x)) * 4 let r = CGFloat(data[pixelInfo]) / CGFloat(255.0) let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0) let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0) return FTColor(red: r, green: g, blue: b) } func getDistanceBetweenColor(color1:FTColor, color2:FTColor) -> CGFloat{ let r1 = color1.red let b1 = color1.blue let g1 = color1.green let r2 = color2.red let b2 = color2.blue let g2 = color2.green let sum = (r1 - r2)^2 sum += ((b1 - b2)^2) sum += ((g1 - g2)^2) return CGFloat(sqrt(Double(sum))) } func getAverageColorForColors(colors:[FTColor]) -> FTColor { var color = FTColor(red: 0, green: 0, blue: 0) colors.map { (c) -> Void in color.red = color.red + c.red color.blue = color.blue + c.blue color.green = color.green + c.green } color.red = color.red/CGFloat(colors.count) color.blue = color.blue/CGFloat(colors.count) color.green = color.green/CGFloat(colors.count) return color }
mit
bf5b8cae779c8e780e0538f420cc3854
26.030769
92
0.639522
3.294559
false
false
false
false
luizlopezm/ios-Luis-Trucking
Pods/Eureka/Source/Core/Operators.swift
1
2671
// // Operators.swift // Eureka // // Created by Martin Barreto on 2/24/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation // MARK: Operators infix operator +++{ associativity left precedence 95 } /** Appends a section to a form - parameter left: the form - parameter right: the section to be appended - returns: the updated form */ public func +++(left: Form, right: Section) -> Form { left.append(right) return left } infix operator +++= { associativity left precedence 95 } /** Appends a section to a form without return statement - parameter left: the form - parameter right: the section to be appended */ public func +++=(inout left: Form, right: Section){ left = left +++ right } /** Appends a row to the last section of a form - parameter left: the form - parameter right: the row */ public func +++=(inout left: Form, right: BaseRow){ left +++= Section() <<< right } /** Creates a form with two sections - parameter left: the first section - parameter right: the second section - returns: the created form */ public func +++(left: Section, right: Section) -> Form { let form = Form() form +++ left +++ right return form } /** Creates a form with two sections, each containing one row. - parameter left: The row for the first section - parameter right: The row for the second section - returns: the created form */ public func +++(left: BaseRow, right: BaseRow) -> Form { let form = Section() <<< left +++ Section() <<< right return form } infix operator <<<{ associativity left precedence 100 } /** Appends a row to a section. - parameter left: the section - parameter right: the row to be appended - returns: the section */ public func <<<(left: Section, right: BaseRow) -> Section { left.append(right) return left } /** Creates a section with two rows - parameter left: The first row - parameter right: The second row - returns: the created section */ public func <<<(left: BaseRow, right: BaseRow) -> Section { let section = Section() section <<< left <<< right return section } /** Appends a collection of rows to a section - parameter lhs: the section - parameter rhs: the rows to be appended */ public func +=< C : CollectionType where C.Generator.Element == BaseRow>(inout lhs: Section, rhs: C){ lhs.appendContentsOf(rhs) } /** Appends a collection of section to a form - parameter lhs: the form - parameter rhs: the sections to be appended */ public func +=< C : CollectionType where C.Generator.Element == Section>(inout lhs: Form, rhs: C){ lhs.appendContentsOf(rhs) }
mit
ce2820c17d2b219f6a48e5b4ee608a11
20.532258
101
0.666292
3.967311
false
false
false
false
Elm-Tree-Island/Shower
Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/UIKit/UIButtonSpec.swift
5
1944
import Quick import Nimble import ReactiveSwift import ReactiveCocoa import UIKit import enum Result.NoError class UIButtonSpec: QuickSpec { override func spec() { var button: UIButton! weak var _button: UIButton? beforeEach { button = UIButton(frame: .zero) _button = button } afterEach { button = nil expect(_button).to(beNil()) } it("should accept changes from bindings to its titles under different states") { let firstTitle = "First title" let secondTitle = "Second title" let (pipeSignal, observer) = Signal<String, NoError>.pipe() button.reactive.title <~ SignalProducer(pipeSignal) button.setTitle("", for: .selected) button.setTitle("", for: .highlighted) observer.send(value: firstTitle) expect(button.title(for: UIControlState())) == firstTitle expect(button.title(for: .highlighted)) == "" expect(button.title(for: .selected)) == "" observer.send(value: secondTitle) expect(button.title(for: UIControlState())) == secondTitle expect(button.title(for: .highlighted)) == "" expect(button.title(for: .selected)) == "" } let pressedTest: (UIButton, UIControlEvents) -> Void = { button, event in button.isEnabled = true button.isUserInteractionEnabled = true let pressed = MutableProperty(false) let action = Action<(), Bool, NoError> { _ in SignalProducer(value: true) } pressed <~ SignalProducer(action.values) button.reactive.pressed = CocoaAction(action) expect(pressed.value) == false button.sendActions(for: event) expect(pressed.value) == true } if #available(iOS 9.0, tvOS 9.0, *) { it("should execute the `pressed` action upon receiving a `primaryActionTriggered` action message.") { pressedTest(button, .primaryActionTriggered) } } else { it("should execute the `pressed` action upon receiving a `touchUpInside` action message.") { pressedTest(button, .touchUpInside) } } } }
gpl-3.0
95cdaf065c77c8e2eb5b8909e1be03f2
25.630137
104
0.692387
3.709924
false
false
false
false
alltheflow/copypasta
Carthage/Checkouts/VinceRP/vincerp/Common/Core/Propagator.swift
1
1382
// // Created by Viktor Belenyesi on 18/04/15. // Copyright (c) 2015 Viktor Belenyesi. All rights reserved. // func ==(lhs: NodeTuple, rhs: NodeTuple) -> Bool { return lhs.source.hashValue == rhs.source.hashValue && lhs.reactor.hashValue == rhs.source.hashValue } public class Propagator { public static var async: Bool = false public static let propagationQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) static func dispatch(block: () -> ()) { if async { dispatch_async(propagationQueue) { block() } } else { block() } } static func propagate(nodes: [NodeTuple]) { self.propagate(Set(nodes)) } static func propagate(nodes: Set<NodeTuple>) { guard nodes.count > 0 else { return } let minLevel = nodes.map{ $0.reactor.level }.min(0) let (now, later) = nodes.partition { $0.reactor.level == minLevel } let next = now.groupBy{ $0.reactor }.mapValues{ $0.map{ $0.source } }.map{ (target, pingers) in return target.ping(pingers).map { NodeTuple(target, $0) } }.flatten() propagate(next + later) } }
mit
34a44bfd0a26fa793470735850de9eb5
25.075472
105
0.524602
4.213415
false
false
false
false
laszlokorte/reform-swift
ReformCore/ReformCore/CreateFormInstruction.swift
1
1809
// // CreateFormInstruction.swift // ReformCore // // Created by Laszlo Korte on 14.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // public struct CreateFormInstruction : Instruction { public typealias DestinationType = RuntimeInitialDestination & Labeled public var target : FormIdentifier? { return form.identifier } public let form : Form & Creatable public let destination : DestinationType public init(form : Form & Creatable, destination: DestinationType) { self.form = form self.destination = destination } public func evaluate<T:Runtime>(_ runtime: T) { guard let (min, max) = destination.getMinMaxFor(runtime) else { runtime.reportError(.invalidDestination) return } runtime.declare(form) form.initWithRuntime(runtime, min: min, max: max) } public func getDescription(_ stringifier: Stringifier) -> String { return "Create \(form.name) \(destination.getDescription(stringifier))" } public func analyze<T:Analyzer>(_ analyzer: T) { analyzer.announceForm(form) if let picture = form as? PictureForm, let id = picture.pictureIdentifier { analyzer.announceDepencency(id) } } public var isDegenerated : Bool { return destination.isDegenerated } } extension CreateFormInstruction : Mergeable { public func mergeWith(_ other: CreateFormInstruction, force: Bool) -> CreateFormInstruction? { guard type(of: other.form) == type(of: form) else { return nil } if force { return CreateFormInstruction(form: form, destination: other.destination) } return nil } }
mit
347a31d70c0c84454adc42dd4887ab66
26.815385
98
0.628319
4.659794
false
false
false
false
ktmswzw/jwtSwiftDemoClient
Temp/JWTTools.swift
1
2656
// // JWTTools.swift // Temp // // Created by vincent on 8/2/16. // Copyright © 2016 xecoder. All rights reserved. // import Foundation import JWT class JWTTools { let SECERT: String = "FEELING_ME007"; let JWTDEMOTOKEN: String = "JWTDEMOTOKEN"; let JWTDEMOTEMP: String = "JWTDEMOTEMP"; let JWTSIGN: String = "JWTSIGN"; let AUTHORIZATION_STR: String = "Authorization"; var token: String { get { if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(JWTDEMOTOKEN) as? String { NSLog("\(returnValue)") return returnValue } else { return "" //Default value } } set { NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: JWTDEMOTOKEN) NSUserDefaults.standardUserDefaults().synchronize() } } var sign: String { get { if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(JWTSIGN) as? String { NSLog("\(returnValue)") return returnValue } else { return "" //Default value } } set { NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: JWTSIGN) NSUserDefaults.standardUserDefaults().synchronize() } } var jwtTemp: String { get { if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(JWTDEMOTEMP) as? String { NSLog("\(returnValue)") return returnValue } else { return "" //Default value } } set { NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: JWTDEMOTEMP) NSUserDefaults.standardUserDefaults().synchronize() } } func getHeader(tokenNew: String, myDictionary: Dictionary<String, String> ) -> [String : String] { if jwtTemp.isEmpty || !myDictionary.isEmpty {//重复使用上次计算结果 let jwt = JWT.encode(.HS256(SECERT)) { builder in for (key, value) in myDictionary { builder[key] = value } builder["token"] = tokenNew } NSLog("\(jwt)") if !myDictionary.isEmpty && tokenNew == self.token {//不填充新数据 jwtTemp = jwt } return [ AUTHORIZATION_STR : jwt ] } else { NSLog("\(jwtTemp)") return [ AUTHORIZATION_STR : jwtTemp ] } } }
apache-2.0
eaf29d04d2cc8155e6b7cd7089ffab40
30.238095
110
0.538696
4.911985
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/Objects/SearchResult.swift
1
2005
import Foundation @objcMembers @objc class SearchResult: NSObject { let variants: [HLResultVariant] let nearbyCities: [HDKCity] let searchInfo: HLSearchInfo var searchId: String? var counters: VariantsCounters = VariantsCounters(variants: []) lazy var allGatesNames: Set<String> = SearchResult.gatesNames(from: self.variants) lazy var allDistrictsNames: Set<String> = SearchResult.districtsNames(from: self.variants) init(searchInfo: HLSearchInfo, variants: [HLResultVariant] = [], nearbyCities: [HDKCity] = []) { self.searchInfo = searchInfo self.variants = variants self.nearbyCities = nearbyCities self.counters = VariantsCounters(variants: self.variants) super.init() } convenience init(searchInfo: HLSearchInfo) { self.init(searchInfo: searchInfo, variants: [], nearbyCities: []) } func hasAnyRoomWithPrice() -> Bool { return variants.index(where: { variant -> Bool in return variant.roomWithMinPrice != nil }) != nil } static func districtsNames(from variants: [HLResultVariant]) -> Set<String> { var districtsNames = Set<String>() for variant in variants { let hotel = variant.hotel if let firstDistrictName = hotel.firstDistrictName() { districtsNames.insert(firstDistrictName) } } return districtsNames } static func gatesNames(from variants: [HLResultVariant]) -> Set<String> { var gatesNames = Set<String>() for variant in variants { if let rooms = variant.roomsCopy() { for room in rooms { if room.hasHotelWebsiteOption { gatesNames.insert(FilterLogic.hotelWebsiteAgencyName()) } else { gatesNames.insert(room.gate.name ?? "") } } } } return gatesNames } }
mit
8308c80a0109a3804c164ab6b5544031
30.825397
100
0.602993
4.485459
false
false
false
false
harlanhaskins/Swips
Sources/Swips/InstructionBuilder.swift
1
891
final class InstructionBuilder { var insertBlock: BasicBlock? let program: Program init(program: Program) { self.program = program } @discardableResult func createBlock(name: String, global: Bool = false, insert: Bool = false) -> BasicBlock { let block = BasicBlock(label: name, global: global) program.add(block) if insert { insertBlock = block } return block } @discardableResult func createData(name: String, kind: DataDeclarationKind) -> DataDeclaration { let data = DataDeclaration(label: name, kind: kind) program.add(data) return data } func build(_ instruction: Instruction) { guard let block = insertBlock else { fatalError("must set insert block before building") } block.add(instruction) } }
mit
b1c3bd9ebc1f58f25667647e296a8267
26.84375
94
0.603816
4.764706
false
false
false
false
tkremenek/swift
stdlib/public/core/DropWhile.swift
19
5536
//===--- DropWhile.swift - Lazy views for drop(while:) --------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A sequence whose elements consist of the elements that follow the initial /// consecutive elements of some base sequence that satisfy a given predicate. @frozen // lazy-performance public struct LazyDropWhileSequence<Base: Sequence> { public typealias Element = Base.Element /// Create an instance with elements `transform(x)` for each element /// `x` of base. @inlinable // lazy-performance internal init(_base: Base, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // lazy-performance internal var _base: Base @usableFromInline // lazy-performance internal let _predicate: (Element) -> Bool } extension LazyDropWhileSequence { /// An iterator over the elements traversed by a base iterator that follow the /// initial consecutive elements that satisfy a given predicate. /// /// This is the associated iterator for the `LazyDropWhileSequence`, /// `LazyDropWhileCollection`, and `LazyDropWhileBidirectionalCollection` /// types. @frozen // lazy-performance public struct Iterator { public typealias Element = Base.Element @inlinable // lazy-performance internal init(_base: Base.Iterator, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // lazy-performance internal var _predicateHasFailed = false @usableFromInline // lazy-performance internal var _base: Base.Iterator @usableFromInline // lazy-performance internal let _predicate: (Element) -> Bool } } extension LazyDropWhileSequence.Iterator: IteratorProtocol { @inlinable // lazy-performance public mutating func next() -> Element? { // Once the predicate has failed for the first time, the base iterator // can be used for the rest of the elements. if _predicateHasFailed { return _base.next() } // Retrieve and discard elements from the base iterator until one fails // the predicate. while let nextElement = _base.next() { if !_predicate(nextElement) { _predicateHasFailed = true return nextElement } } return nil } } extension LazyDropWhileSequence: Sequence { /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // lazy-performance public __consuming func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), predicate: _predicate) } } extension LazyDropWhileSequence: LazySequenceProtocol { public typealias Elements = LazyDropWhileSequence } extension LazySequenceProtocol { /// Returns a lazy sequence that skips any initial elements that satisfy /// `predicate`. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns `true` if the element should be skipped or /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @inlinable // lazy-performance public __consuming func drop( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyDropWhileSequence<Self.Elements> { return LazyDropWhileSequence(_base: self.elements, predicate: predicate) } } /// A lazy wrapper that includes the elements of an underlying /// collection after any initial consecutive elements that satisfy a /// predicate. /// /// - Note: The performance of accessing `startIndex`, `first`, or any methods /// that depend on `startIndex` depends on how many elements satisfy the /// predicate at the start of the collection, and may not offer the usual /// performance given by the `Collection` protocol. Be aware, therefore, /// that general operations on lazy collections may not have the /// documented complexity. public typealias LazyDropWhileCollection<T: Collection> = LazyDropWhileSequence<T> extension LazyDropWhileCollection: Collection { public typealias SubSequence = Slice<LazyDropWhileCollection<Base>> public typealias Index = Base.Index @inlinable // lazy-performance public var startIndex: Index { var index = _base.startIndex while index != _base.endIndex && _predicate(_base[index]) { _base.formIndex(after: &index) } return index } @inlinable // lazy-performance public var endIndex: Index { return _base.endIndex } @inlinable // lazy-performance public func index(after i: Index) -> Index { _precondition(i < _base.endIndex, "Can't advance past endIndex") return _base.index(after: i) } @inlinable // lazy-performance public subscript(position: Index) -> Element { return _base[position] } } extension LazyDropWhileCollection: BidirectionalCollection where Base: BidirectionalCollection { @inlinable // lazy-performance public func index(before i: Index) -> Index { _precondition(i > startIndex, "Can't move before startIndex") return _base.index(before: i) } } extension LazyDropWhileCollection: LazyCollectionProtocol { }
apache-2.0
bfcd7df6cd84bc4edf5d605325c6093c
33.385093
82
0.700867
4.648195
false
false
false
false
zqqf16/SYM
SYM/Regex.swift
1
3320
// The MIT License (MIT) // // Copyright (c) 2017 - present zqqf16 // // 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 struct Regex { class Match { let string: String fileprivate let result: NSTextCheckingResult init(_ string: String, result: NSTextCheckingResult) { self.string = string self.result = result } lazy var captures: [String]? = { let number = result.numberOfRanges guard number >= 1 else { return nil } var groups = [String]() for index in 0 ..< number { if let range = Range(result.range(at: index), in: string) { groups.append(String(string[range])) } } return groups }() var range: NSRange { return result.range } } fileprivate let _regex: NSRegularExpression var pattern: String { return _regex.pattern } typealias Options = NSRegularExpression.Options typealias MatchingOptions = NSRegularExpression.MatchingOptions init(_ pattern: String, options: Options = []) throws { try _regex = NSRegularExpression(pattern: pattern, options: options) } func firstMatch(in string: String, options: MatchingOptions = []) -> Match? { let range = NSRange(string.startIndex..., in: string) guard let result = _regex.firstMatch(in: string, options: options, range: range) else { return nil } return Match(string, result: result) } func matches(in string: String, options: MatchingOptions = []) -> [Match]? { let range = NSRange(string.startIndex..., in: string) let matches = _regex.matches(in: string, options: options, range: range) if matches.count == 0 { return nil } return matches.map { Match(string, result: $0) } } } // MARK: dwarfdump extension Regex { // UUID: F9E72B35-ACE9-3B64-8D8C-6A59BE609683 (armv7) /path/to/xxx.dSYM/Contents/Resources/DWARF/xxx static let dwarfdump = try! Regex("^UUID: ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}) \\(.*\\) (.*)", options: [.anchorsMatchLines, .caseInsensitive]) }
mit
8733a069ff3149d5567d4e89bca637ac
34.319149
173
0.638855
4.306096
false
false
false
false
cdmx/MiniMancera
miniMancera/View/Settings/VSettingsCellReview.swift
1
1187
import UIKit class VSettingsCellReview:VSettingsCell { override init(frame:CGRect) { super.init(frame:frame) let button:UIButton = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.clipsToBounds = true button.setTitle( String.localized(key:"VSettingsCellReview_button"), for:UIControlState.normal) button.setTitleColor( UIColor.white, for:UIControlState.normal) button.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) button.addTarget( self, action:#selector(actionButton(sender:)), for:UIControlEvents.touchUpInside) button.titleLabel!.font = UIFont.bold(size:15) addSubview(button) NSLayoutConstraint.equals( view:button, toView:self) } required init?(coder:NSCoder) { return nil } //MARK: actions func actionButton(sender button:UIButton) { controller?.review() } }
mit
ddc732915e33e1ede8a8714838fda254
24.804348
64
0.588037
5.183406
false
false
false
false
swipe-org/swipe
core/SwipeElement.swift
2
88094
// // SwipeElement.swift // Swipe // // Created by satoshi on 8/10/15. // Copyright (c) 2015 Satoshi Nakajima. All rights reserved. // #if os(OSX) import Cocoa public typealias UIView = NSView public typealias UIButton = NSButton public typealias UIScreen = NSScreen #else import UIKit #endif import AVFoundation import ImageIO import CoreText private func MyLog(_ text:String, level:Int = 0) { let s_verbosLevel = 0 if level <= s_verbosLevel { print(text) } } // HACK: // AVPlayerLayer causes a crash in deinit when it was rendered by presentationPlayer, // which calls init(layer: Any) to create a copy before the rendering. // We can work-around this bug by calling super.init(). class XAVPlayerLayer: AVPlayerLayer { override init(layer: Any) { //print("XAVPlayerLayer init with layer") super.init() // HACK to avoid crash } init(player: AVPlayer) { super.init() self.player = player } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { } } protocol SwipeElementDelegate:NSObjectProtocol { func prototypeWith(_ name:String?) -> [String:Any]? func pathWith(_ name:String?) -> Any? func shouldRepeat(_ element:SwipeElement) -> Bool func onAction(_ element:SwipeElement) func didStartPlaying(_ element:SwipeElement) func didFinishPlaying(_ element:SwipeElement, completed:Bool) func parseMarkdown(_ element:SwipeElement, markdowns:[String]) -> NSAttributedString func baseURL() -> URL? func map(_ url:URL) -> URL? func addedResourceURLs(_ urls:[URL:String], callback:@escaping () -> Void) func pageIndex() -> Int // for debugging func localizedStringForKey(_ key:String) -> String? func languageIdentifier() -> String? } class SwipeElement: SwipeView, SwipeViewDelegate { // Debugging static var objectCount = 0 private let pageIndex:Int // public properties weak var delegate:SwipeElementDelegate! var action:String? private var layer:CALayer? private var btn:UIButton? private let scale:CGSize private var screenDimension = CGSize(width: 0, height: 0) private var repeatCount = CGFloat(1.0) private let blackColor = UIColor.black.cgColor private let whiteColor = UIColor.white.cgColor #if os(OSX) private let contentScale = CGFloat(1.0) // REVIEW #else private let contentScale = UIScreen.main.scale #endif private var fRepeat = false var helper: SwipeView? // Example: SwipeList // Image Element Specific private var imageLayer:CALayer? // Text Element Specific private var textLayer:CATextLayer? // Shape Element Specific private var shapeLayer:CAShapeLayer? // Video Element Specific private var videoPlayer:AVPlayer? private var fNeedRewind = false private var fSeeking = false private var pendingOffset:CGFloat? private var fPlaying = false private var videoStart = CGFloat(0.0) private var videoDuration:CGFloat? private var hasObserver = false private let tolerance = CMTimeMake(value:10, timescale:600) // 1/60sec // Sprite Element Specific private var spriteLayer:CALayer? private var slice = CGSize(width: 1.0, height: 1.0) private var contentsRect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0) private var step = -1 // invalid to start private var slot = CGPoint(x: 0.0, y: 0.0) // actually Ints //private var dir:(Int, Int)? #if os(iOS) // HTML Specific //private var webView:WKWebView? #endif // Lazy properties private lazy var notificationManager = SNNotificationManager() init(info:[String:Any], scale:CGSize, parent:SwipeNode, delegate:SwipeElementDelegate) { var template = info["template"] as? String if template == nil { template = info["element"] as? String if template != nil { MyLog("SwElement DEPRECATED element; use 'template'") } } self.scale = scale self.delegate = delegate self.pageIndex = delegate.pageIndex() // only for debugging let elementInfo = SwipeParser.inheritProperties(info, baseObject: delegate.prototypeWith(template)) super.init(parent: parent, info: elementInfo) self.setTimeOffsetTo(0.0) SwipeElement.objectCount += 1 MyLog("SWElem init \(pageIndex) \(scale.width)", level:1) } deinit { #if os(iOS) /* if let webView = self.webView { webView.removeFromSuperview() SwipeWebViewPool.sharedInstance().storeWebView(webView) self.webView = nil } */ #endif SwipeElement.objectCount -= 1 MyLog("SWElem deinit \(pageIndex) \(scale.width)", level: 1) if (SwipeElement.objectCount == 0) { MyLog("SWElem zero object!", level:1) } } static func checkMemoryLeak() { //assert(SwipeElement.objectCount == 0) if SwipeElement.objectCount > 0 { NSLog("SWElem memory leak detected ###") } } private func value<T:FloatingPoint>(from info:[String:Any], key:String, defaultValue:T) -> T { if let value = info[key] as? T { return value } return defaultValue } private func booleanValue(from info:[String:Any], key:String, defaultValue:Bool) -> Bool { if let value = info[key] as? Bool { return value } return defaultValue } func loadView(_ dimension:CGSize) -> UIView? { return self.loadViewInternal(dimension, screenDimension: dimension) } // Returns the list of URLs of required resources for this element (including children) lazy var resourceURLs:[URL:String] = { var urls = [URL:String]() let baseURL = self.delegate.baseURL() for (key, prefix) in ["img":"", "mask":"", "video":".mov", "sprite":""] { if let src = self.info[key] as? String, let url = URL.url(src, baseURL: baseURL) { if let fStream = self.info["stream"] as? Bool, fStream == true { MyLog("SWElem no need to cache streaming video \(url)", level: 2) } else { urls[url] = prefix } } } if let elementsInfo = self.info["elements"] as? [[String:Any]] { let scaleDummy = CGSize(width: 1.0, height: 1.0) for e in elementsInfo { let element = SwipeElement(info: e, scale:scaleDummy, parent:self, delegate:self.delegate!) for (url, prefix) in element.resourceURLs { urls[url] = prefix } } } if let listInfo = self.info["list"] as? [String:Any] { if let itemsInfo = listInfo["items"] as? [[String:Any]] { for itemInfo in itemsInfo { if let elementsInfo = itemInfo["elements"] as? [[String:Any]] { let scaleDummy = CGSize(width: 1.0, height: 1.0) for e in elementsInfo { let element = SwipeElement(info: e, scale:scaleDummy, parent:self, delegate:self.delegate!) for (url, prefix) in element.resourceURLs { urls[url] = prefix } } } } } } return urls }() func loadViewInternal(_ dimension:CGSize, screenDimension:CGSize) -> UIView? { self.screenDimension = screenDimension let baseURL = delegate.baseURL() var x = CGFloat(0.0) var y = CGFloat(0.0) var w0 = dimension.width var h0 = dimension.height var fNaturalW = true var fNaturalH = true var imageRef:CGImage? var imageSrc:CGImageSource? var maskSrc:CGImage? var pathSrc:CGPath? var innerLayer:CALayer? // for loop shift let fScaleToFill = info["w"] as? String == "fill" || info["h"] as? String == "fill" if fScaleToFill { w0 = dimension.width // we'll adjust it later h0 = dimension.height // we'll adjust it later } else { if let value = info["w"] as? CGFloat { w0 = value fNaturalW = false } else if let value = info["w"] as? String { w0 = SwipeParser.parsePercent(value, full: dimension.width, defaultValue: dimension.width) fNaturalW = false } if let value = info["h"] as? CGFloat { h0 = value fNaturalH = false } else if let value = info["h"] as? String { h0 = SwipeParser.parsePercent(value, full: dimension.height, defaultValue: dimension.height) fNaturalH = false } } if let src = info["img"] as? String { //imageSrc = SwipeParser.imageSourceWith(src) if let url = URL.url(src, baseURL: baseURL) { if let urlLocal = self.delegate.map(url) { imageSrc = CGImageSourceCreateWithURL(urlLocal as CFURL, nil) } else { imageSrc = CGImageSourceCreateWithURL(url as CFURL, nil) } if imageSrc != nil && CGImageSourceGetCount(imageSrc!) > 0 { imageRef = CGImageSourceCreateImageAtIndex(imageSrc!, 0, nil) } } } if let src = info["mask"] as? String { //maskSrc = SwipeParser.imageWith(src) if let url = URL.url(src, baseURL: baseURL), let urlLocal = self.delegate.map(url), let image = CGImageSourceCreateWithURL(urlLocal as CFURL, nil) { if CGImageSourceGetCount(image) > 0 { maskSrc = CGImageSourceCreateImageAtIndex(image, 0, nil) } } } pathSrc = parsePath(info["path"], w: w0, h: h0, scale:scale) // The natural size is determined by the contents (either image or mask) var sizeContents:CGSize? if imageRef != nil { sizeContents = CGSize(width: CGFloat((imageRef?.width)!), height: CGFloat((imageRef?.height)!)) } else if maskSrc != nil { sizeContents = CGSize(width: CGFloat((maskSrc?.width)!), height: CGFloat((maskSrc?.height)!)) } else if let path = pathSrc { let rc = path.boundingBoxOfPath sizeContents = CGSize(width: rc.origin.x + rc.width, height: rc.origin.y + rc.height) } if let sizeNatural = sizeContents { if fScaleToFill { if w0 / sizeNatural.width * sizeNatural.height > h0 { h0 = w0 / sizeNatural.width * sizeNatural.height } else { w0 = h0 / sizeNatural.height * sizeNatural.width } } else if fNaturalW { if fNaturalH { w0 = sizeNatural.width h0 = sizeNatural.height } else { w0 = h0 / sizeNatural.height * sizeNatural.width } } else { if fNaturalH { h0 = w0 / sizeNatural.width * sizeNatural.height } } } let w = w0 * scale.width let h = h0 * scale.height let frame:CGRect = { if let value = info["x"] as? CGFloat { x = value } else if let value = info["x"] as? String { if value == "right" { x = dimension.width - w0 } else if value == "left" { x = 0 } else if value == "center" { x = (dimension.width - w0) / 2.0 } else { x = SwipeParser.parsePercent(value, full: dimension.width, defaultValue: 0) } } if let value = info["y"] as? CGFloat { y = value } else if let value = info["y"] as? String { if value == "bottom" { y = dimension.height - h0 } else if value == "top" { y = 0 } else if value == "center" { y = (dimension.height - h0) / 2.0 } else { y = SwipeParser.parsePercent(value, full: dimension.height, defaultValue: 0) } } //NSLog("SWEleme \(x),\(y),\(w0),\(h0),\(sizeContents),\(dimension),\(scale)") x *= scale.width y *= scale.height return CGRect(x: x, y: y, width: w, height: h) }() let view = InternalView(wrapper: self, frame: frame) #if os(OSX) let layer = view.makeBackingLayer() #else let layer = view.layer #endif self.layer = layer if let values = info["anchor"] as? [Any], values.count == 2 && w0 > 0 && h0 > 0, let posx = SwipeParser.parsePercentAny(values[0], full: w0, defaultValue: 0), let posy = SwipeParser.parsePercentAny(values[1], full: h0, defaultValue: 0) { layer.anchorPoint = CGPoint(x: posx / w0, y: posy / h0) } if let values = info["pos"] as? [Any], values.count == 2, let posx = SwipeParser.parsePercentAny(values[0], full: dimension.width, defaultValue: 0), let posy = SwipeParser.parsePercentAny(values[1], full: dimension.height, defaultValue: 0) { layer.position = CGPoint(x: posx * scale.width, y: posy * scale.height) } if let value = info["action"] as? String { action = value #if os(iOS) // tvOS has some focus issue with UIButton, figure out OSX later let btn = UIButton(type: UIButton.ButtonType.custom) btn.frame = view.bounds btn.addTarget(self, action: #selector(SwipeElement.buttonPressed), for: UIControl.Event.touchUpInside) btn.addTarget(self, action: #selector(SwipeElement.touchDown), for: UIControl.Event.touchDown) btn.addTarget(self, action: #selector(SwipeElement.touchUpOutside), for: UIControl.Event.touchUpOutside) view.addSubview(btn) self.btn = btn #endif if action == "play" { notificationManager.addObserver(forName: .SwipePageDidStartPlaying, object: self.delegate, queue: OperationQueue.main) { /*[unowned self]*/ (_: Notification!) -> Void in // NOTE: Animation does not work because we are performing animation using the parent layer //UIView.animateWithDuration(0.2, animations: { () -> Void in layer.opacity = 0.0 //}) } notificationManager.addObserver(forName: .SwipePageDidFinishPlaying, object: self.delegate, queue: OperationQueue.main) { /*[unowned self]*/ (_: Notification!) -> Void in // NOTE: Animation does not work because we are performing animation using the parent layer //UIView.animateWithDuration(0.2, animations: { () -> Void in layer.opacity = 1.0 //}) } } } else if let eventsInfo = info["events"] as? [String:Any] { eventHandler.parse(eventsInfo) } if let enabled = info["enabled"] as? Bool { self.fEnabled = enabled } if let focusable = info["focusable"] as? Bool { self.fFocusable = focusable } if let value = info["clip"] as? Bool { //view.clipsToBounds = value layer.masksToBounds = value } if let image = imageRef { let rc = view.bounds let imageLayer = CALayer() imageLayer.contentsScale = contentScale imageLayer.frame = rc imageLayer.contents = image imageLayer.contentsGravity = CALayerContentsGravity.resizeAspectFill imageLayer.masksToBounds = true layer.addSublayer(imageLayer) if let tiling = info["tiling"] as? Bool, tiling { let hostLayer = CALayer() innerLayer = hostLayer //rc.origin = CGPointZero //imageLayer.frame = rc hostLayer.addSublayer(imageLayer) layer.addSublayer(hostLayer) layer.masksToBounds = true var rcs = [rc, rc, rc, rc] rcs[0].origin.x -= rc.size.width rcs[1].origin.x += rc.size.width rcs[2].origin.y -= rc.size.height rcs[3].origin.y += rc.size.height for rc in rcs { let subLayer = CALayer() subLayer.contentsScale = contentScale subLayer.frame = rc subLayer.contents = image subLayer.contentsGravity = CALayerContentsGravity.resizeAspectFill subLayer.masksToBounds = true hostLayer.addSublayer(subLayer) } } // Handling GIF animation if let isrc = imageSrc { self.step = 0 var images = [CGImage]() // NOTE: Using non-main thread has some side-effect //let queue = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0) //dispatch_async(queue) { () -> Void in let count = CGImageSourceGetCount(isrc) for i in 1..<count { if let image = CGImageSourceCreateImageAtIndex(isrc, i, nil) { images.append(image) } } let ani = CAKeyframeAnimation(keyPath: "contents") ani.values = images ani.beginTime = 1e-10 ani.duration = 1.0 ani.fillMode = CAMediaTimingFillMode.both imageLayer.add(ani, forKey: "contents") //} } self.imageLayer = imageLayer } #if os(iOS) /* var htmlText = info["html"] as? String if let htmls = info["html"] as? [String] { htmlText = htmls.joinWithSeparator("\n") } if let html = htmlText { let webview = SwipeWebViewPool.sharedInstance().getWebView() webview.frame = view.bounds webview.opaque = false webview.backgroundColor = UIColor.clearColor() webview.userInteractionEnabled = false let header = "<head><meta name='viewport' content='initial-scale=\(scale.width), user-scalable=no, width=\(Int(w0))'></head>" let style:String if let value = self.delegate.styleWith(info["style"] as? String) { style = "<style>\(value)</style>" } else { style = "" } webview.loadHTMLString("<html>\(header)\(style)<body>\(html)</body></html>", baseURL: nil) view.addSubview(webview) self.webView = webview } */ #endif if let src = info["sprite"] as? String, let slice = info["slice"] as? [Int] { //view.clipsToBounds = true layer.masksToBounds = true if let values = self.info["slot"] as? [Int], values.count == 2 { slot = CGPoint(x: CGFloat(values[0]), y: CGFloat(values[1])) } if let url = URL.url(src, baseURL: baseURL), let urlLocal = self.delegate.map(url), let imageSource = CGImageSourceCreateWithURL(urlLocal as CFURL, nil), CGImageSourceGetCount(imageSource) > 0, let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) { let imageLayer = CALayer() imageLayer.contentsScale = contentScale imageLayer.frame = view.bounds imageLayer.contents = image if slice.count > 0 { self.slice.width = CGFloat(slice[0]) if slice.count > 1 { self.slice.height = CGFloat(slice[1]) } } contentsRect = CGRect(x: slot.x/self.slice.width, y: slot.y/self.slice.height, width: 1.0/self.slice.width, height: 1.0/self.slice.height) imageLayer.contentsRect = contentsRect layer.addSublayer(imageLayer) spriteLayer = imageLayer } } layer.backgroundColor = SwipeParser.parseColor(info["bc"]) if let value = self.info["videoDuration"] as? CGFloat { videoDuration = value } if let value = self.info["videoStart"] as? CGFloat { videoStart = value } if let image = maskSrc { let imageLayer = CALayer() imageLayer.contentsScale = contentScale imageLayer.frame = CGRect(x: 0,y: 0,width: w,height: h) imageLayer.contents = image layer.mask = imageLayer } if let radius = info["cornerRadius"] as? CGFloat { layer.cornerRadius = radius * scale.width; //view.clipsToBounds = true; } if let borderWidth = info["borderWidth"] as? CGFloat { layer.borderWidth = borderWidth * scale.width layer.borderColor = SwipeParser.parseColor(info["borderColor"], defaultColor: blackColor) } if let path = pathSrc { let shapeLayer = CAShapeLayer() shapeLayer.frame = view.bounds shapeLayer.contentsScale = contentScale if let xpath = SwipeParser.transformedPath(path, param: info, size:frame.size) { shapeLayer.path = xpath } else { shapeLayer.path = path } shapeLayer.fillColor = SwipeParser.parseColor(info["fillColor"]) shapeLayer.strokeColor = SwipeParser.parseColor(info["strokeColor"], defaultColor: blackColor) shapeLayer.lineWidth = SwipeParser.parseCGFloat(info["lineWidth"]) * self.scale.width SwipeElement.processShadow(info, scale:scale, layer: shapeLayer) shapeLayer.lineCap = CAShapeLayerLineCap(rawValue: "round") shapeLayer.strokeStart = SwipeParser.parseCGFloat(info["strokeStart"], defaultValue: 0.0) shapeLayer.strokeEnd = SwipeParser.parseCGFloat(info["strokeEnd"], defaultValue: 1.0) layer.addSublayer(shapeLayer) self.shapeLayer = shapeLayer if let tiling = info["tiling"] as? Bool, tiling { let hostLayer = CALayer() innerLayer = hostLayer let rc = view.bounds hostLayer.addSublayer(shapeLayer) layer.addSublayer(hostLayer) layer.masksToBounds = true var rcs = [rc, rc, rc, rc] rcs[0].origin.x -= rc.size.width rcs[1].origin.x += rc.size.width rcs[2].origin.y -= rc.size.height rcs[3].origin.y += rc.size.height for rc in rcs { let subLayer = CAShapeLayer() subLayer.frame = rc subLayer.contentsScale = shapeLayer.contentsScale subLayer.path = shapeLayer.path subLayer.fillColor = shapeLayer.fillColor subLayer.strokeColor = shapeLayer.strokeColor subLayer.lineWidth = shapeLayer.lineWidth subLayer.shadowColor = shapeLayer.shadowColor subLayer.shadowOffset = shapeLayer.shadowOffset subLayer.shadowOpacity = shapeLayer.shadowOpacity subLayer.shadowRadius = shapeLayer.shadowRadius subLayer.lineCap = shapeLayer.lineCap subLayer.strokeStart = shapeLayer.strokeStart subLayer.strokeEnd = shapeLayer.strokeEnd hostLayer.addSublayer(subLayer) } } } else { SwipeElement.processShadow(info, scale:scale, layer: layer) } var mds: Any? = info["markdown"] if let md = mds as? String { mds = [md] } if let markdowns = mds as? [String] { #if !os(OSX) // REVIEW let attrString = self.delegate.parseMarkdown(self, markdowns: markdowns) let rcLabel = view.bounds let label = UILabel(frame: rcLabel) label.attributedText = attrString label.numberOfLines = 999 view.addSubview(label) #endif } if let value = info["textArea"] as? [String:Any] { let textView = SwipeTextArea(parent: self, info: value, frame: view.bounds, screenDimension: self.screenDimension) helper = textView view.addSubview(helper!.view!) } else if let value = info["textField"] as? [String:Any] { let textView = SwipeTextField(parent: self, info: value, frame: view.bounds, screenDimension: self.screenDimension) helper = textView view.addSubview(helper!.view!) } else if let value = info["list"] as? [String:Any] { let list = SwipeList(parent: self, info: value, scale:self.scale, frame: view.bounds, screenDimension: self.screenDimension, delegate: self.delegate) helper = list view.addSubview(list.tableView) list.tableView.reloadData() } if let text = parseText(self, info: info, key:"text") { if self.helper == nil || !self.helper!.setText(text, scale:self.scale, info: info, dimension:screenDimension, layer: layer) { self.textLayer = SwipeElement.addTextLayer(text, scale:scale, info: info, dimension: screenDimension, layer: layer) } } // http://stackoverflow.com/questions/9290972/is-it-possible-to-make-avurlasset-work-without-a-file-extension var fStream:Bool = { if let fStream = info["stream"] as? Bool { return fStream } return false }() let urlVideoOrRadio:URL? = { if let src = info["video"] as? String, let url = URL.url(src, baseURL: baseURL) { return url } if let src = info["radio"] as? String, let url = URL.url(src, baseURL: baseURL) { fStream = true return url } return nil }() if let url = urlVideoOrRadio { let videoPlayer = AVPlayer() self.videoPlayer = videoPlayer self.hasObserver = false let videoLayer = XAVPlayerLayer(player: videoPlayer) videoLayer.frame = CGRect(x: 0.0, y: 0.0, width: w, height: h) if fScaleToFill { videoLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill } layer.addSublayer(videoLayer) let urlLocalOrStream:URL? if fStream { MyLog("SWElem stream=\(url)", level:2) urlLocalOrStream = url } else if let urlLocal = self.delegate.map(url) { urlLocalOrStream = urlLocal } else { urlLocalOrStream = nil } if let urlVideo = urlLocalOrStream { let playerItem = AVPlayerItem(url: urlVideo) videoPlayer.replaceCurrentItem(with: playerItem) if (videoStart > 0) { MyLog("SWElem A seekTo \(videoStart)", level:0) } let timescale = videoPlayer.currentItem?.asset.duration.timescale ?? 600 videoPlayer.seek(to: CMTime(seconds:Double(videoStart), preferredTimescale: timescale), toleranceBefore: tolerance, toleranceAfter: tolerance) notificationManager.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: playerItem, queue: OperationQueue.main) { [unowned self] (_:Notification!) -> Void in MyLog("SWElem play to end!", level: 1) self.handleVideoEnd(videoPlayer: videoPlayer) } } notificationManager.addObserver(forName: .SwipePageShouldPauseAutoPlay, object: delegate, queue: OperationQueue.main) { [unowned self] (_:Notification!) -> Void in if self.fPlaying { self.fPlaying = false self.delegate.didFinishPlaying(self, completed:false) videoPlayer.pause() } } notificationManager.addObserver(forName: .SwipePageShouldStartAutoPlay, object: delegate, queue: OperationQueue.main) { [unowned self] (_:Notification!) -> Void in if !self.fPlaying && layer.opacity > 0 { self.fPlaying = true self.delegate.didStartPlaying(self) MyLog("SWElem videoPlayer.state = \(videoPlayer.status.rawValue)", level: 1) if self.fNeedRewind { MyLog("SWElem B seekTo \(self.videoStart)", level:0) let timescale = videoPlayer.currentItem?.asset.duration.timescale ?? 600 videoPlayer.seek(to: CMTime(seconds:Double(self.videoStart), preferredTimescale: timescale), toleranceBefore: self.tolerance, toleranceAfter: self.tolerance) } videoPlayer.play() self.fNeedRewind = false if let duration = self.videoDuration, !self.hasObserver { // Async call to give the play time to seek (LATER: we may need to wait a bit) self.hasObserver = true DispatchQueue.main.async() { MyLog("SWElem duration=\(duration) from \(self.videoStart) seeking=\(self.fSeeking)", level:0) let time = CMTime(seconds: Double(self.videoStart + duration), preferredTimescale: 600) videoPlayer.addBoundaryTimeObserver(forTimes: [NSValue(time: time)], queue: nil) { [weak self] in MyLog("SWElem timeObserver pausing", level:0) videoPlayer.pause() self?.handleVideoEnd(videoPlayer: videoPlayer) } } } } } } if let transform = SwipeParser.parseTransform(info, scaleX:scale.width, scaleY:scale.height, base: nil, fSkipTranslate: false, fSkipScale: self.shapeLayer != nil) { layer.transform = transform } layer.opacity = SwipeParser.parseFloat(info["opacity"]) if let visible = info["visible"] as? Bool, !visible { layer.opacity = 0.0 } if let to = info["to"] as? [String:Any] { let start, duration:Double if let timing = to["timing"] as? [Double], timing.count == 2 && timing[0] >= 0 && timing[0] <= timing[1] && timing[1] <= 1 { start = timing[0] == 0 ? 1e-10 : timing[0] duration = timing[1] - start } else { start = 1e-10 duration = 1.0 } var fSkipTranslate = false if let path = parsePath(to["pos"], w: w0, h: h0, scale:scale) { let pos = layer.position var xform = CGAffineTransform(translationX: pos.x, y: pos.y) let ani = CAKeyframeAnimation(keyPath: "position") ani.path = path.copy(using: &xform) ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both ani.calculationMode = CAAnimationCalculationMode.paced if let mode = to["mode"] as? String { switch(mode) { case "auto": ani.rotationMode = CAAnimationRotationMode.rotateAuto case "reverse": ani.rotationMode = CAAnimationRotationMode.rotateAutoReverse default: // or "none" ani.rotationMode = nil } } layer.add(ani, forKey: "position") fSkipTranslate = true } if let transform = SwipeParser.parseTransform(to, scaleX:scale.width, scaleY:scale.height, base:info, fSkipTranslate: fSkipTranslate, fSkipScale: self.shapeLayer != nil) { let ani = CABasicAnimation(keyPath: "transform") ani.fromValue = NSValue(caTransform3D : layer.transform) ani.toValue = NSValue(caTransform3D : transform) ani.fillMode = CAMediaTimingFillMode.both ani.beginTime = start ani.duration = duration layer.add(ani, forKey: "transform") } if let opacity = to["opacity"] as? Float { let ani = CABasicAnimation(keyPath: "opacity") ani.fromValue = layer.opacity ani.toValue = opacity ani.fillMode = CAMediaTimingFillMode.both ani.beginTime = start ani.duration = duration layer.add(ani, forKey: "opacity") } if let backgroundColor = to["bc"] { let ani = CABasicAnimation(keyPath: "backgroundColor") ani.fromValue = layer.backgroundColor ani.toValue = SwipeParser.parseColor(backgroundColor) ani.fillMode = CAMediaTimingFillMode.both ani.beginTime = start ani.duration = duration layer.add(ani, forKey: "backgroundColor") } if let borderColor = to["borderColor"] { let ani = CABasicAnimation(keyPath: "borderColor") ani.fromValue = layer.borderColor ani.toValue = SwipeParser.parseColor(borderColor) ani.fillMode = CAMediaTimingFillMode.both ani.beginTime = start ani.duration = duration layer.add(ani, forKey: "borderColor") } if let borderWidth = to["borderWidth"] as? CGFloat { let ani = CABasicAnimation(keyPath: "borderWidth") ani.fromValue = layer.borderWidth ani.toValue = borderWidth * scale.width ani.fillMode = CAMediaTimingFillMode.both ani.beginTime = start ani.duration = duration layer.add(ani, forKey: "borderWidth") } if let borderWidth = to["cornerRadius"] as? CGFloat { let ani = CABasicAnimation(keyPath: "cornerRadius") ani.fromValue = layer.cornerRadius ani.toValue = borderWidth * scale.width ani.fillMode = CAMediaTimingFillMode.both ani.beginTime = start ani.duration = duration layer.add(ani, forKey: "cornerRadius") } if let textLayer = self.textLayer { if let textColor = to["textColor"] { let ani = CABasicAnimation(keyPath: "foregroundColor") ani.fromValue = textLayer.foregroundColor ani.toValue = SwipeParser.parseColor(textColor) ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both textLayer.add(ani, forKey: "foregroundColor") } } if let srcs = to["img"] as? [String] { var images = [CGImage]() for src in srcs { if let url = URL.url(src, baseURL: baseURL), let urlLocal = self.delegate.map(url), let image = CGImageSourceCreateWithURL(urlLocal as CFURL, nil) { if CGImageSourceGetCount(image) > 0 { images.append(CGImageSourceCreateImageAtIndex(image, 0, nil)!) } } //if let image = SwipeParser.imageWith(src) { //images.append(image.CGImage!) //} } if let imageLayer = self.imageLayer { let ani = CAKeyframeAnimation(keyPath: "contents") ani.values = images ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both imageLayer.add(ani, forKey: "contents") } } if let shapeLayer = self.shapeLayer { if let params = to["path"] as? [Any] { var values = [shapeLayer.path!] for param in params { if let path = parsePath(param, w: w0, h: h0, scale:scale) { values.append(path) } } let ani = CAKeyframeAnimation(keyPath: "path") ani.values = values ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "path") } else if let path = parsePath(to["path"], w: w0, h: h0, scale:scale) { let ani = CABasicAnimation(keyPath: "path") ani.fromValue = shapeLayer.path ani.toValue = path ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "path") } else if let path = SwipeParser.transformedPath(pathSrc!, param: to, size:frame.size) { let ani = CABasicAnimation(keyPath: "path") ani.fromValue = shapeLayer.path ani.toValue = path ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "path") } if let fillColor = to["fillColor"] { let ani = CABasicAnimation(keyPath: "fillColor") ani.fromValue = shapeLayer.fillColor ani.toValue = SwipeParser.parseColor(fillColor) ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "fillColor") } if let strokeColor = to["strokeColor"] { let ani = CABasicAnimation(keyPath: "strokeColor") ani.fromValue = shapeLayer.strokeColor ani.toValue = SwipeParser.parseColor(strokeColor) ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "strokeColor") } if let lineWidth = to["lineWidth"] as? CGFloat { let ani = CABasicAnimation(keyPath: "lineWidth") ani.fromValue = shapeLayer.lineWidth ani.toValue = lineWidth * scale.width ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "lineWidth") } if let strokeStart = to["strokeStart"] as? CGFloat { let ani = CABasicAnimation(keyPath: "strokeStart") ani.fromValue = shapeLayer.strokeStart ani.toValue = strokeStart ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "strokeStart") } if let strokeEnd = to["strokeEnd"] as? CGFloat { let ani = CABasicAnimation(keyPath: "strokeEnd") ani.fromValue = shapeLayer.strokeEnd ani.toValue = strokeEnd ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "strokeEnd") } } } if let fRepeat = info["repeat"] as? Bool, fRepeat { //NSLog("SE detected an element with repeat") self.fRepeat = fRepeat layer.speed = 0 // Independently animate it } if let animation = info["loop"] as? [String:Any], let style = animation["style"] as? String { // // Note: Use the inner layer (either image or shape) for the loop animation // to avoid any conflict with other transformation if it is available. // In this case, the loop animation does not effect chold elements (because // we use UIView hierarchy instead of CALayer hierarchy. // // It means the loop animation on non-image/non-shape element does not work well // with other transformation. // var loopLayer = layer if let l = imageLayer { loopLayer = l } else if let l = shapeLayer { loopLayer = l } let start, duration:Double if let timing = animation["timing"] as? [Double], timing.count == 2 && timing[0] >= 0 && timing[0] <= timing[1] && timing[1] <= 1 { start = timing[0] == 0 ? 1e-10 : timing[0] duration = timing[1] - start } else { start = 1e-10 duration = 1.0 } let repeatCount = value(from: animation, key: "count", defaultValue: 1) as Float switch(style) { case "vibrate": let delta = value(from: animation, key: "delta", defaultValue: 10.0) as CGFloat let ani = CAKeyframeAnimation(keyPath: "transform") ani.values = [NSValue(caTransform3D:loopLayer.transform), NSValue(caTransform3D:CATransform3DConcat(CATransform3DMakeTranslation(delta, 0.0, 0.0), loopLayer.transform)), NSValue(caTransform3D:loopLayer.transform), NSValue(caTransform3D:CATransform3DConcat(CATransform3DMakeTranslation(-delta, 0.0, 0.0), loopLayer.transform)), NSValue(caTransform3D:loopLayer.transform)] ani.repeatCount = repeatCount ani.beginTime = start ani.duration = CFTimeInterval(duration / Double(ani.repeatCount)) ani.fillMode = CAMediaTimingFillMode.both loopLayer.add(ani, forKey: "transform") case "shift": let shiftLayer = (innerLayer == nil) ? layer : innerLayer! let ani = CAKeyframeAnimation(keyPath: "transform") let shift:CGSize = { if let dir = animation["direction"] as? String { switch(dir) { case "n": return CGSize(width: 0, height: -h) case "e": return CGSize(width: w, height: 0) case "w": return CGSize(width: -w, height: 0) default: return CGSize(width: 0, height: h) } } else { return CGSize(width: 0, height: h) } }() ani.values = [NSValue(caTransform3D:shiftLayer.transform), NSValue(caTransform3D:CATransform3DConcat(CATransform3DMakeTranslation(shift.width, shift.height, 0.0), shiftLayer.transform))] ani.repeatCount = repeatCount ani.beginTime = start ani.duration = CFTimeInterval(duration / Double(ani.repeatCount)) ani.fillMode = CAMediaTimingFillMode.both shiftLayer.add(ani, forKey: "transform") case "blink": let ani = CAKeyframeAnimation(keyPath: "opacity") ani.values = [1.0, 0.0, 1.0] ani.repeatCount = repeatCount ani.beginTime = start ani.duration = CFTimeInterval(duration / Double(ani.repeatCount)) ani.fillMode = CAMediaTimingFillMode.both loopLayer.add(ani, forKey: "opacity") case "spin": let fClockwise = booleanValue(from: animation, key: "clockwise", defaultValue: true) let degree = (fClockwise ? 120 : -120) * CGFloat(CGFloat.pi / 180.0) let ani = CAKeyframeAnimation(keyPath: "transform") ani.values = [NSValue(caTransform3D:loopLayer.transform), NSValue(caTransform3D:CATransform3DConcat(CATransform3DMakeRotation(degree, 0.0, 0.0, 1.0), loopLayer.transform)), NSValue(caTransform3D:CATransform3DConcat(CATransform3DMakeRotation(degree * 2, 0.0, 0.0, 1.0), loopLayer.transform)), NSValue(caTransform3D:CATransform3DConcat(CATransform3DMakeRotation(degree * 3, 0.0, 0.0, 1.0), loopLayer.transform))] ani.repeatCount = repeatCount ani.beginTime = start ani.duration = CFTimeInterval(duration / Double(ani.repeatCount)) ani.fillMode = CAMediaTimingFillMode.both loopLayer.add(ani, forKey: "transform") case "wiggle": let delta = value(from: animation, key: "delta", defaultValue: 15) * CGFloat(CGFloat.pi / 180.0) let ani = CAKeyframeAnimation(keyPath: "transform") ani.values = [NSValue(caTransform3D:loopLayer.transform), NSValue(caTransform3D:CATransform3DConcat(CATransform3DMakeRotation(delta, 0.0, 0.0, 1.0), loopLayer.transform)), NSValue(caTransform3D:loopLayer.transform), NSValue(caTransform3D:CATransform3DConcat(CATransform3DMakeRotation(-delta, 0.0, 0.0, 1.0), loopLayer.transform)), NSValue(caTransform3D:loopLayer.transform)] ani.repeatCount = repeatCount ani.beginTime = start ani.duration = CFTimeInterval(duration / Double(ani.repeatCount)) ani.fillMode = CAMediaTimingFillMode.both loopLayer.add(ani, forKey: "transform") case "path": if let shapeLayer = self.shapeLayer { var values = [shapeLayer.path!] if let params = animation["path"] as? [Any] { for param in params { if let path = parsePath(param, w: w0, h: h0, scale:scale) { values.append(path) } } } else if let path = parsePath(animation["path"], w: w0, h: h0, scale:scale) { values.append(path) } if values.count >= 2 { values.append(shapeLayer.path!) let ani = CAKeyframeAnimation(keyPath: "path") ani.values = values ani.repeatCount = repeatCount ani.beginTime = start ani.duration = CFTimeInterval(duration / Double(ani.repeatCount)) ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "path") } } case "sprite": if let targetLayer = spriteLayer { let ani = CAKeyframeAnimation(keyPath: "contentsRect") let rc0 = CGRect(x: 0, y: slot.y/self.slice.height, width: 1.0/self.slice.width, height: 1.0/self.slice.height) ani.values = Array(0..<Int(slice.width)).map() { (index:Int) -> NSValue in NSValue(cgRect: CGRect(origin: CGPoint(x: CGFloat(index) / self.slice.width, y: rc0.origin.y), size: rc0.size)) } ani.repeatCount = repeatCount ani.beginTime = start ani.duration = CFTimeInterval(duration / Double(ani.repeatCount)) ani.fillMode = CAMediaTimingFillMode.both ani.calculationMode = CAAnimationCalculationMode.discrete targetLayer.add(ani, forKey: "contentsRect") } //self.dir = (1,0) //self.repeatCount = CGFloat(repeatCount) default: break } } // Nested Elements if let elementsInfo = info["elements"] as? [[String:Any]] { for e in elementsInfo { let element = SwipeElement(info: e, scale:scale, parent:self, delegate:self.delegate!) if let subview = element.loadViewInternal(CGSize(width: w0, height: h0), screenDimension: screenDimension) { view.addSubview(subview) children.append(element) } } } self.view = view setupGestureRecognizers() if let actions = eventHandler.actionsFor("load") { execute(self, actions: actions) } return view } // This function is called by SwipePage when unloading the view. // PARANOIA: Extra effort to clean up everything func clear() { notificationManager.clear() } private func parsePath(_ shape:Any?, w:CGFloat, h:CGFloat, scale:CGSize) -> CGPath? { var shape0: Any? = shape if let refs = shape as? [String:Any], let key = refs["ref"] as? String { shape0 = delegate.pathWith(key) } return SwipePath.parse(shape0, w: w, h: h, scale: scale) } @objc func buttonPressed() { MyLog("SWElem buttonPressed", level: 1) layer?.opacity = 1.0 if let delegate = self.delegate { delegate.onAction(self) } } @objc func touchDown() { MyLog("SWElem touchDown", level: 1) layer?.opacity = 0.5 } @objc func touchUpOutside() { MyLog("SWElem touchUpOutside", level: 1) layer?.opacity = 1.0 } func setTimeOffsetTo(_ offset:CGFloat, fAutoPlay:Bool = false, fElementRepeat:Bool = false) { if offset < 0.0 || offset > 1.0 { return } if let layer = self.layer, layer.speed == 0 { // independently animated layer.timeOffset = CFTimeInterval(offset) } for c in children { if let element = c as? SwipeElement { element.setTimeOffsetTo(offset, fAutoPlay: fAutoPlay, fElementRepeat: fElementRepeat) } } if fElementRepeat && !self.fRepeat { return } // This block of code was replaced by CAKeyFrameAnimation (sprite) /* if let layer = spriteLayer, let _ = self.dir { let step:Int if offset == 1 && self.repeatCount == 1 { step = Int(self.slice.width) - 1 // always end at the last one if repeatCount==1 } else { step = Int(offset * self.repeatCount * self.slice.width) % Int(self.slice.width) } if step != self.step /* || offset == 0.0 */ { contentsRect.origin.x = CGFloat(step) / self.slice.width contentsRect.origin.y = slot.y / self.slice.height layer.contentsRect = contentsRect self.step = step } } */ if let player = self.videoPlayer { if fAutoPlay { return } if self.fSeeking { self.pendingOffset = offset return } let timeSec = videoStart + offset * (videoDuration ?? 1.0) let time = CMTimeMakeWithSeconds(Float64(timeSec), preferredTimescale: 600) if player.status == AVPlayer.Status.readyToPlay { self.fSeeking = true SwipeElement.objectCount -= 1 // to avoid false memory leak detection player.seek(to: time, toleranceBefore: tolerance, toleranceAfter: tolerance) { (_:Bool) -> Void in assert(Thread.current == Thread.main, "thread error") SwipeElement.objectCount += 1 self.fSeeking = false if let pendingOffset = self.pendingOffset { self.pendingOffset = nil self.setTimeOffsetTo(pendingOffset, fAutoPlay: false, fElementRepeat: fElementRepeat) } } } } } /* func autoplay() { if let player = self.videoPlayer { if !fPlaying { fPlaying = true self.delegate?.didStartPlaying(self) player.play() } } } func pause() { if let player = self.videoPlayer { if fPlaying { fPlaying = false self.delegate?.didFinishPlaying(self) player.pause() } } } */ func handleVideoEnd(videoPlayer:AVPlayer) { if self.delegate != nil && self.delegate!.shouldRepeat(self) { MyLog("SWElem C seekTo \(self.videoStart)", level:0) let timescale = videoPlayer.currentItem?.asset.duration.timescale ?? 600 videoPlayer.seek(to: CMTime(seconds:Double(videoStart), preferredTimescale: timescale), toleranceBefore: tolerance, toleranceAfter: tolerance) videoPlayer.play() } else { self.fNeedRewind = true if self.fPlaying { self.fPlaying = false self.delegate.didFinishPlaying(self, completed:true) } } } func isVideoElement() -> Bool { if self.videoPlayer != nil { return true } for c in children { if let element = c as? SwipeElement { if element.isVideoElement() { return true } } } return false } func isRepeatElement() -> Bool { if fRepeat { return true } for c in children { if let element = c as? SwipeElement { if element.isRepeatElement() { return true } } } return false } func parseText(_ originator: SwipeNode, info:[String:Any], key:String) -> String? { guard let value = info[key] else { return nil } if let text = value as? String { return text } guard let params = value as? [String:Any] else { return nil } if let valInfo = params["valueOf"] as? [String:Any] { if let text = originator.getValue(originator, info: valInfo) as? String { return text } return nil } else if let key = params["ref"] as? String, let text = delegate.localizedStringForKey(key) { return text } return SwipeParser.localizedString(params, langId: delegate.languageIdentifier()) } static func processShadow(_ info:[String:Any], scale:CGSize, layer:CALayer) { if let shadowInfo = info["shadow"] as? [String:Any] { layer.shadowColor = SwipeParser.parseColor(shadowInfo["color"], defaultColor: UIColor.black.cgColor) layer.shadowOffset = SwipeParser.parseSize(shadowInfo["offset"], defaultValue: CGSize(width: 1, height: 1), scale:scale) layer.shadowOpacity = SwipeParser.parseFloat(shadowInfo["opacity"], defaultValue:0.5) layer.shadowRadius = SwipeParser.parseCGFloat(shadowInfo["radius"], defaultValue: 1.0) * scale.width } } static func processTextInfo(_ info:[String:Any], dimension:CGSize, scale:CGSize) -> ([NSAttributedString.Key:Any], String, Bool, Bool, CTFont, CGFloat) { var fTextBottom = false var fTextTop = false let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle paragraphStyle.alignment = NSTextAlignment.center paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping var alignmentMode = CATextLayerAlignmentMode.center func processAlignment(_ alignment:String) { switch(alignment) { case "left": paragraphStyle.alignment = NSTextAlignment.left alignmentMode = CATextLayerAlignmentMode.left case "right": paragraphStyle.alignment = NSTextAlignment.right alignmentMode = CATextLayerAlignmentMode.right case "justified": paragraphStyle.alignment = NSTextAlignment.justified alignmentMode = CATextLayerAlignmentMode.justified case "top": fTextTop = true case "bottom": fTextBottom = true default: break } } if let alignment = info["textAlign"] as? String { processAlignment(alignment) } else if let alignments = info["textAlign"] as? [String] { for alignment in alignments { processAlignment(alignment) } } let fontSize: CGFloat = { let defaultSize = 20.0 / 480.0 * dimension.height let size = SwipeParser.parseFontSize(info, full: dimension.height, defaultValue: defaultSize, markdown: false) return round(size * scale.height) }() let fontNames = SwipeParser.parseFontName(info, markdown: false) func createFont() -> CTFont { for fontName in fontNames { return CTFontCreateWithName((fontName as CFString?)!, fontSize, nil) } return CTFontCreateWithName(("Helvetica" as CFString?)!, fontSize, nil) } let font:CTFont = createFont() let attr:[NSAttributedString.Key:Any] = [ NSAttributedString.Key.font:font, //NSForegroundColorAttributeName:UIColor(CGColor: SwipeParser.parseColor(info["textColor"], defaultColor: UIColor.blackColor().CGColor)), NSAttributedString.Key.paragraphStyle:paragraphStyle] return (attr, alignmentMode.rawValue, fTextTop, fTextBottom, font, fontSize) } static func processTextStorage(_ text:String, attr:[NSAttributedString.Key:Any], fTextBottom:Bool, fTextTop:Bool, rcBound:CGRect) -> CGRect { let textStorage = NSTextStorage(string: text, attributes: attr) let manager = NSLayoutManager() textStorage.addLayoutManager(manager) let container = NSTextContainer(size: CGSize(width: rcBound.width, height: 99999)) manager.addTextContainer(container) manager.ensureLayout(for: container) let box = manager.usedRect(for: container) var rcText = rcBound if fTextTop { rcText.origin.y = rcText.size.height - box.size.height } else if !fTextBottom { rcText.origin.y = (rcText.size.height - box.size.height) / 2 } return rcText } static func addTextLayer(_ text:String, scale:CGSize, info:[String:Any], dimension:CGSize, layer:CALayer) -> CATextLayer { let (attr, alignmentMode, fTextBottom, fTextTop, font, fontSize) = SwipeElement.processTextInfo(info, dimension: dimension, scale: scale) // NOTE: CATextLayer does not use the paragraph style in NSAttributedString (*). // In addition, we can't use NSAttributedString if we want to animate something, // such as foregroundColor and fontSize (**). let textLayer = CATextLayer() #if !os(OSX) textLayer.contentsScale = UIScreen.main.scale #endif textLayer.isWrapped = true // * textLayer.alignmentMode = CATextLayerAlignmentMode(rawValue: alignmentMode) // * textLayer.foregroundColor = SwipeParser.parseColor(info["textColor"], defaultColor: UIColor.black.cgColor) // animatable ** textLayer.fontSize = fontSize // animatable ** textLayer.font = font textLayer.string = text // NOTE: This is no longer an attributed string SwipeElement.processShadow(info, scale:scale, layer: layer) textLayer.frame = SwipeElement.processTextStorage(text, attr: attr, fTextBottom: fTextBottom, fTextTop: fTextTop, rcBound: layer.bounds) layer.addSublayer(textLayer) return textLayer } static func updateTextLayer(_ textLayer:CATextLayer, text:String, scale:CGSize, info:[String:Any], dimension:CGSize, layer:CALayer) { let (attr, alignmentMode, fTextBottom, fTextTop, font, fontSize) = SwipeElement.processTextInfo(info, dimension: dimension, scale: scale) textLayer.alignmentMode = CATextLayerAlignmentMode(rawValue: alignmentMode) // * textLayer.foregroundColor = SwipeParser.parseColor(info["textColor"], defaultColor: UIColor.black.cgColor) // animatable ** textLayer.fontSize = fontSize // animatable ** textLayer.font = font textLayer.string = text // NOTE: This is no longer an attributed string SwipeElement.processShadow(info, scale:scale, layer: layer) textLayer.frame = SwipeElement.processTextStorage(text, attr: attr, fTextBottom: fTextBottom, fTextTop: fTextTop, rcBound: layer.bounds) } /* func isPlaying() -> Bool { if self.fPlaying { return true } for element in elements { if element.isPlaying() { return true } } return false } */ // SwipeView override func isFirstResponder() -> Bool { if let v = self.view { if v.isFirstResponder { return true } if helper != nil { return helper!.isFirstResponder() } } return super.isFirstResponder() } // SwipeNode override func getPropertyValue(_ originator: SwipeNode, property: String) -> Any? { if let val = helper?.getPropertyValue(originator, property: property) { return val } switch (property) { case "text": if let string = self.textLayer?.string as? String { return string } else { MyLog("SWElem textLayer.string is not a String!") return nil } case "text.length": if let string = self.textLayer?.string as? String { return string.count } else { MyLog("SWElem textLayer.string is not a String!") return nil } case "enabled": return self.fEnabled case "focusable": return self.fFocusable default: return super.getPropertyValue(originator, property: property) } } override func getPropertiesValue(_ originator: SwipeNode, info: [String:Any]) -> Any? { if let val = self.helper?.getPropertiesValue(originator, info: info) { return val } let key = info.keys.first! if let val = info[key] as? String { return getPropertyValue(originator, property: val) } else { return nil } } override func getValue(_ originator: SwipeNode, info: [String:Any]) -> Any? { var name = "*" if let val = info["id"] as? String { name = val } var up = true if let val = info["search"] as? String { up = val != "children" } if (name == "*" || self.name.caseInsensitiveCompare(name) == .orderedSame) { if let attribute = info["property"] as? String { return getPropertyValue(originator, property: attribute) } else if let attributeInfo = info["property"] as? [String:Any] { return getPropertiesValue(originator, info: attributeInfo) } } var node: SwipeNode? = self if up { while node?.parent != nil { if let viewNode = node?.parent as? SwipeView { for c in viewNode.children { if let e = c as? SwipeElement { if name == "*" || e.name.caseInsensitiveCompare(name) == .orderedSame { if let attribute = info["property"] as? String { return e.getPropertyValue(originator, property: attribute) } else if let attributeInfo = info["property"] as? [String:Any] { return e.getPropertiesValue(originator, info: attributeInfo) } } } } node = node?.parent } else { return nil } } } else { for c in children { if let e = c as? SwipeElement { return e.getValue(originator, info: info) } } } return nil } func setupAnimations(_ layer: CALayer, originator: SwipeNode, info: [String:Any]) { let dimension = self.screenDimension let baseURL = self.delegate.baseURL() var x = layer.frame.origin.x var y = layer.frame.origin.y var w0 = layer.frame.size.width var h0 = layer.frame.size.height let fScaleToFill = info["w"] as? String == "fill" || info["h"] as? String == "fill" if !fScaleToFill { if let value = info["w"] as? CGFloat { w0 = value } else if let value = info["w"] as? String { w0 = SwipeParser.parsePercent(value, full: dimension.width, defaultValue: dimension.width) } else if let valInfo = info["w"] as? [String:Any], let valOfInfo = valInfo["valueOf"] as? [String:Any], let value = originator.getValue(originator, info:valOfInfo) as? CGFloat { w0 = value } if let value = info["h"] as? CGFloat { h0 = value } else if let value = info["h"] as? String { h0 = SwipeParser.parsePercent(value, full: dimension.height, defaultValue: dimension.height) } else if let valInfo = info["h"] as? [String:Any], let valOfInfo = valInfo["valueOf"] as? [String:Any], let value = originator.getValue(originator, info:valOfInfo) as? CGFloat { h0 = value } } if let value = info["x"] as? CGFloat { x = value } else if let value = info["x"] as? String { if value == "right" { x = dimension.width - w0 } else if value == "left" { x = 0 } else if value == "center" { x = (dimension.width - w0) / 2.0 } else { x = SwipeParser.parsePercent(value, full: dimension.width, defaultValue: 0) } } else if let valInfo = info["x"] as? [String:Any], let valOfInfo = valInfo["valueOf"] as? [String:Any], let value = originator.getValue(originator, info:valOfInfo) as? CGFloat { x = value } if let value = info["y"] as? CGFloat { y = value } else if let value = info["y"] as? String { if value == "bottom" { y = dimension.height - h0 } else if value == "top" { y = 0 } else if value == "center" { y = (dimension.height - h0) / 2.0 } else { y = SwipeParser.parsePercent(value, full: dimension.height, defaultValue: 0) } } else if let valInfo = info["y"] as? [String:Any], let valOfInfo = valInfo["valueOf"] as? [String:Any], let value = originator.getValue(originator, info:valOfInfo) as? CGFloat { y = value } //NSLog("SWEleme \(x),\(y),\(w0),\(h0),\(sizeContents),\(dimension),\(scale)") x *= self.scale.width y *= self.scale.height let w = w0 * self.scale.width let h = h0 * self.scale.height let frame = CGRect(x: x, y: y, width: w, height: h) layer.frame = frame let start, duration:Double if let timing = info["timing"] as? [Double], timing.count == 2 && timing[0] >= 0 && timing[0] <= timing[1] && timing[1] <= 1 { start = timing[0] == 0 ? 1e-10 : timing[0] duration = timing[1] - start } else { start = 1e-10 duration = 1.0 } if let durationSec = info["duration"] as? Double { CATransaction.setAnimationDuration(durationSec) } var fSkipTranslate = false if let path = self.parsePath(info["pos"], w: w0, h: h0, scale:self.scale) { let pos = layer.position var xform = CGAffineTransform(translationX: pos.x, y: pos.y) let ani = CAKeyframeAnimation(keyPath: "position") ani.path = path.copy(using: &xform) ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both ani.calculationMode = CAAnimationCalculationMode.paced if let mode = info["mode"] as? String { switch(mode) { case "auto": ani.rotationMode = CAAnimationRotationMode.rotateAuto case "reverse": ani.rotationMode = CAAnimationRotationMode.rotateAutoReverse default: // or "none" ani.rotationMode = nil } } layer.add(ani, forKey: "position") fSkipTranslate = true } if let transform = SwipeParser.parseTransform(info, scaleX:self.scale.width, scaleY:self.scale.height, base:info, fSkipTranslate: fSkipTranslate, fSkipScale: self.shapeLayer != nil) { let ani = CABasicAnimation(keyPath: "transform") ani.fromValue = NSValue(caTransform3D : layer.transform) ani.toValue = NSValue(caTransform3D : transform) ani.fillMode = CAMediaTimingFillMode.both ani.beginTime = start ani.duration = duration layer.add(ani, forKey: "transform") } if let opacity = info["opacity"] as? Float { let ani = CABasicAnimation(keyPath: "opacity") ani.fromValue = layer.opacity layer.opacity = opacity ani.toValue = layer.opacity //ani.fillMode = kCAFillModeBoth //ani.beginTime = start //ani.duration = duration layer.add(ani, forKey: "opacity") } if let backgroundColor = info["bc"] { let ani = CABasicAnimation(keyPath: "backgroundColor") ani.fromValue = layer.backgroundColor layer.backgroundColor = SwipeParser.parseColor(backgroundColor) ani.toValue = layer.backgroundColor //ani.fillMode = kCAFillModeBoth //ani.beginTime = start //ani.duration = duration layer.add(ani, forKey: "backgroundColor") } if let borderColor = info["borderColor"] { let ani = CABasicAnimation(keyPath: "borderColor") ani.fromValue = layer.borderColor layer.borderColor = SwipeParser.parseColor(borderColor) ani.toValue = layer.borderColor //ani.fillMode = kCAFillModeBoth //ani.beginTime = start //ani.duration = duration layer.add(ani, forKey: "borderColor") } if let borderWidth = info["borderWidth"] as? CGFloat { let ani = CABasicAnimation(keyPath: "borderWidth") ani.fromValue = layer.borderWidth ani.toValue = borderWidth * scale.width //ani.fillMode = kCAFillModeBoth //ani.beginTime = start //ani.duration = duration layer.add(ani, forKey: "borderWidth") } if let borderWidth = info["cornerRadius"] as? CGFloat { let ani = CABasicAnimation(keyPath: "cornerRadius") ani.fromValue = layer.cornerRadius ani.toValue = borderWidth * scale.width ani.fillMode = CAMediaTimingFillMode.both ani.beginTime = start ani.duration = duration layer.add(ani, forKey: "cornerRadius") } if let textLayer = self.textLayer { if let textColor = info["textColor"] { let ani = CABasicAnimation(keyPath: "foregroundColor") ani.fromValue = textLayer.foregroundColor textLayer.foregroundColor = SwipeParser.parseColor(textColor) ani.toValue = textLayer.foregroundColor //ani.beginTime = start //ani.duration = duration //ani.fillMode = kCAFillModeBoth textLayer.add(ani, forKey: "foregroundColor") } } if info["img"] != nil && self.imageLayer != nil { var urls = [URL:String]() var urlStr: String? if let str = info["img"] as? String { urlStr = str } else if let valInfo = info["img"] as? [String:Any], let valOfInfo = valInfo["valueOf"] as? [String:Any], let str = originator.getValue(originator, info:valOfInfo) as? String { urlStr = str } if urlStr != nil { if let url = URL.url(urlStr!, baseURL: baseURL) { urls[url] = "img" self.delegate.addedResourceURLs(urls) { if let urlLocal = self.delegate.map(urls.first!.0), let image = CGImageSourceCreateWithURL(urlLocal as CFURL, nil) { if CGImageSourceGetCount(image) > 0 { self.imageLayer!.contents = CGImageSourceCreateImageAtIndex(image, 0, nil)! } } } } } } if let shapeLayer = self.shapeLayer { if let params = info["path"] as? [Any] { var values = [shapeLayer.path!] for param in params { if let path = self.parsePath(param, w: w0, h: h0, scale:self.scale) { values.append(path) } } let ani = CAKeyframeAnimation(keyPath: "path") ani.values = values ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "path") } else if let path = self.parsePath(info["path"], w: w0, h: h0, scale:self.scale) { let ani = CABasicAnimation(keyPath: "path") ani.fromValue = shapeLayer.path ani.toValue = path ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "path") } /*else if let path = SwipeParser.transformedPath(pathSrc!, param: info, size:frame.size) { let ani = CABasicAnimation(keyPath: "path") ani.fromValue = shapeLayer.path ani.toValue = path ani.beginTime = start ani.duration = duration ani.fillMode = kCAFillModeBoth shapeLayer.addAnimation(ani, forKey: "path") } */ if let fillColor = info["fillColor"] { let ani = CABasicAnimation(keyPath: "fillColor") ani.fromValue = shapeLayer.fillColor ani.toValue = SwipeParser.parseColor(fillColor) ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "fillColor") } if let strokeColor = info["strokeColor"] { let ani = CABasicAnimation(keyPath: "strokeColor") ani.fromValue = shapeLayer.strokeColor ani.toValue = SwipeParser.parseColor(strokeColor) ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "strokeColor") } if let lineWidth = info["lineWidth"] as? CGFloat { let ani = CABasicAnimation(keyPath: "lineWidth") ani.fromValue = shapeLayer.lineWidth ani.toValue = lineWidth * self.scale.width ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "lineWidth") } if let strokeStart = info["strokeStart"] as? CGFloat { let ani = CABasicAnimation(keyPath: "strokeStart") ani.fromValue = shapeLayer.strokeStart ani.toValue = strokeStart ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "strokeStart") } if let strokeEnd = info["strokeEnd"] as? CGFloat { let ani = CABasicAnimation(keyPath: "strokeEnd") ani.fromValue = shapeLayer.strokeEnd ani.toValue = strokeEnd ani.beginTime = start ani.duration = duration ani.fillMode = CAMediaTimingFillMode.both shapeLayer.add(ani, forKey: "strokeEnd") } } } func update(_ originator: SwipeNode, info: [String:Any]) { for key in info.keys { if key != "events" { self.info[key] = info[key] } } DispatchQueue.main.async { self.layer?.removeAllAnimations() self.textLayer?.removeAllAnimations() UIView.animate(withDuration: 0.25, animations: { CATransaction.begin() CATransaction.setDisableActions(true) CATransaction.setCompletionBlock({ if let eventsInfo = info["events"] as? [String:Any], self.delegate != nil { let eventHandler = SwipeEventHandler() eventHandler.parse(eventsInfo) if let actions = eventHandler.actionsFor("completion") { originator.execute(self, actions:actions) } } }) if let text = self.parseText(originator, info: self.info, key:"text") { if let textHelper = self.helper as? SwipeTextArea { _ = textHelper.setText(text, scale: self.scale, info: self.info, dimension: self.screenDimension, layer: nil) } else if let textHelper = self.helper as? SwipeTextField { _ = textHelper.setText(text, scale: self.scale, info: self.info, dimension: self.screenDimension, layer: nil) } else { if self.textLayer == nil { self.textLayer = SwipeElement.addTextLayer(text, scale: self.scale, info: self.info, dimension: self.screenDimension, layer: self.layer!) } else { SwipeElement.updateTextLayer(self.textLayer!, text: text, scale: self.scale, info: self.info, dimension: self.screenDimension, layer: self.layer!) } } } if let text = self.textLayer?.string as? String, self.info["textAlign"] != nil || self.info["textColor"] != nil || self.info["fontName"] != nil || self.info["fontSize"] != nil { SwipeElement.updateTextLayer(self.textLayer!, text: text, scale: self.scale, info: self.info, dimension: self.screenDimension, layer: self.layer!) } self.setupAnimations(self.layer!, originator: originator, info: self.info) CATransaction.commit() }, completion: { (done: Bool) in //print("uiview done: \(done)") }) if let enabled = SwipeParser.parseAndEvalBool(originator, key: "enabled", info: self.info), self.fEnabled != enabled { self.fEnabled = enabled if enabled { self.execute(self, actions: self.eventHandler.actionsFor("enabled")) } else { self.execute(self, actions: self.eventHandler.actionsFor("disabled")) } } if let focusable = SwipeParser.parseAndEvalBool(originator, key: "focusable", info: self.info), self.fFocusable != focusable { self.fFocusable = focusable if focusable { self.execute(self, actions: self.eventHandler.actionsFor("focusable")) } else { self.execute(self, actions: self.eventHandler.actionsFor("unfocusable")) } self.view?.superview?.setNeedsFocusUpdate() } } } override func updateElement(_ originator: SwipeNode, name: String, up: Bool, info: [String:Any]) -> Bool { if let textHelper = self.helper as? SwipeTextArea { if textHelper.updateElement(originator, name: name, up: up, info: info) { return true } } if let textHelper = self.helper as? SwipeTextField { if textHelper.updateElement(originator, name: name, up: up, info: info) { return true } } if (name == "*" || self.name.caseInsensitiveCompare(name) == .orderedSame) { // Update self update(originator, info: info) return true } // Find named element in parent hierarchy and update var node: SwipeNode? = self if up { while node?.parent != nil { if let viewNode = node?.parent as? SwipeView { for c in viewNode.children { if let e = c as? SwipeElement { if e.name.caseInsensitiveCompare(name) == .orderedSame { e.update(originator, info: info) return true } } } node = node?.parent } else { return false } } } else { for c in children { if let e = c as? SwipeElement { if e.updateElement(originator, name:name, up:up, info:info) { return true } } } } return false } override func appendList(_ originator: SwipeNode, info: [String:Any]) { self.helper?.appendList(originator, info: info) } override func appendList(_ originator: SwipeNode, name: String, up: Bool, info: [String:Any]) -> Bool { if (name == "*" || self.name.caseInsensitiveCompare(name) == .orderedSame) { // Update self appendList(originator, info: info) return true } // Find named element in parent hierarchy and update var node: SwipeNode? = self if up { while node?.parent != nil { if let viewNode = node?.parent as? SwipeView { for c in viewNode.children { if let e = c as? SwipeElement { if e.name.caseInsensitiveCompare(name) == .orderedSame { e.appendList(originator, info: info) return true } } } node = node?.parent } else { return false } } } else { for c in children { if let e = c as? SwipeElement { if e.appendList(originator, name:name, up:up, info:info) { return true } } } } return false } // SwipeViewDelegate func addedResourceURLs(_ urls:[URL:String], callback:@escaping () -> Void) { for (url,prefix) in urls { self.resourceURLs[url as URL] = prefix } self.delegate?.addedResourceURLs(urls) { callback() } } }
mit
19a5faba58a1d04642ebbebeb1ae09b1
42.246932
193
0.527947
5.029632
false
false
false
false
alexzatsepin/omim
iphone/Maps/Bookmarks/Catalog/CatalogCategoryCell.swift
3
1507
protocol CatalogCategoryCellDelegate : AnyObject { func cell(_ cell: CatalogCategoryCell, didCheck visible: Bool) func cell(_ cell: CatalogCategoryCell, didPress moreButton: UIButton) } final class CatalogCategoryCell: MWMTableViewCell { weak var delegate: CatalogCategoryCellDelegate? @IBOutlet weak var visibleCheckmark: Checkmark! { didSet { visibleCheckmark.offTintColor = .blackHintText() visibleCheckmark.onTintColor = .linkBlue() } } @IBOutlet weak var titleLabel: UILabel! { didSet { titleLabel.font = .regular16() titleLabel.textColor = .blackPrimaryText() } } @IBOutlet weak var subtitleLabel: UILabel! { didSet { subtitleLabel.font = .regular14() subtitleLabel.textColor = .blackSecondaryText() } } @IBOutlet weak var moreButton: UIButton! @IBAction func onVisibleChanged(_ sender: Checkmark) { delegate?.cell(self, didCheck: sender.isChecked) } @IBAction func onMoreButton(_ sender: UIButton) { delegate?.cell(self, didPress: sender) } func update(with category: MWMCategory, delegate: CatalogCategoryCellDelegate?) { titleLabel.text = category.title let placesString = String(format: L("bookmarks_places"), category.bookmarksCount) let authorString = String(coreFormat: L("author_name_by_prefix"), arguments: [category.author]) subtitleLabel.text = "\(placesString) • \(authorString)" visibleCheckmark.isChecked = category.isVisible self.delegate = delegate } }
apache-2.0
3f4b69246c3491fc0371b0aba7039e8e
31.717391
99
0.718937
4.533133
false
false
false
false
MR-Zong/ZGResource
Project/FamilyEducationApp-master/家教/FreeTimeTableViewController.swift
1
5577
// // FreeTimeTableViewController.swift // 家教 // // Created by goofygao on 15/10/21. // Copyright © 2015年 goofyy. All rights reserved. // import UIKit class FreeTimeTableViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.initView() } //MARK: -初始化当前视图 func initView() { // self.view.backgroundColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1) let navBar = self.navigationController?.navigationBar navBar?.barTintColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1) navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default self.view.backgroundColor = UIColor(patternImage: UIImage(named: "kechengbiaoBg.png")!) /** * 画线 */ let shapeLayer = CAShapeLayer() shapeLayer.strokeColor = UIColor.blueColor().CGColor shapeLayer.lineWidth = 0.5 let bezier = UIBezierPath() bezier.moveToPoint(CGPointMake(0, 95)) bezier.addLineToPoint(CGPointMake(DeviceData.width, 95)) shapeLayer.path = bezier.CGPath self.view.layer.addSublayer(shapeLayer) bezier.moveToPoint(CGPointMake(30, 0)) bezier.addLineToPoint(CGPointMake(30, DeviceData.height)) shapeLayer.path = bezier.CGPath self.view.layer.addSublayer(shapeLayer) let monthLabel = UILabel() monthLabel.frame = CGRectMake(3, 65, 40, 30) monthLabel.textColor = UIColor.whiteColor() monthLabel.text = "11月" monthLabel.font = UIFont.systemFontOfSize(10) self.view.addSubview(monthLabel) for i in 1...6 { bezier.moveToPoint(CGPointMake(30 + ((DeviceData.width - 30)/7) * CGFloat(i), 0)) print(((DeviceData.width ))) bezier.addLineToPoint(CGPointMake(30 + ((DeviceData.width - 30)/7) * CGFloat(i), 95)) shapeLayer.path = bezier.CGPath self.view.layer.addSublayer(shapeLayer) } for i in 1...4 { bezier.moveToPoint(CGPointMake(0, 95 + ((DeviceData.height - 95)/5) * CGFloat(i))) print(((DeviceData.width ))) bezier.addLineToPoint(CGPointMake(30,95 + ((DeviceData.height - 95)/5) * CGFloat(i))) shapeLayer.path = bezier.CGPath self.view.layer.addSublayer(shapeLayer) } for i in 1...5 { //一天第几节课标记 let courseLabel = UILabel() courseLabel.text = "\(i)" courseLabel.textColor = UIColor.whiteColor() courseLabel.frame = CGRectMake(10, 95 + ((DeviceData.height - 95)/5) * CGFloat(Double(i) - 0.55), 15, 15) self.view.addSubview(courseLabel) } for i in 1...7 { //一天第几节课标记 let weekLabel = UILabel() let weekArray = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"] weekLabel.font = UIFont.systemFontOfSize(10) weekLabel.text = "1 \(weekArray[i - 1])" weekLabel.numberOfLines = 0 weekLabel.textColor = UIColor.whiteColor() weekLabel.frame = CGRectMake(30 + ((DeviceData.width - 30)/7) * CGFloat(Double(i) - 0.95), 55, 40, 40) self.view.addSubview(weekLabel) } self.createClass(4, whichClass: 1, courseName: "信号与系统@北主楼203") self.createClass(3, whichClass: 2, courseName: "计算机网络@北主楼301") self.createClass(1, whichClass: 1, courseName: "高等数学@北主楼303") self.createClass(5, whichClass: 4, courseName: "大学英语@黄浩川301") self.createClass(4, whichClass: 3, courseName: "linux系统@北主楼604") self.createClass(7, whichClass: 2, courseName: "信号与系统@北主楼203") self.createClass(2, whichClass: 1, courseName: "密码学@北主楼203") self.createClass(2, whichClass: 3, courseName: "信号与系统@北主楼203") } /** 创建课程view - parameter whichWeekDay: 一周的第几天 - parameter whichClass: 哪一节课 1、2、3、4、5 - parameter courseName: 课程名字 */ func createClass(whichWeekDay:Int,whichClass:Int,courseName:String) { let bgView = UIView() bgView.frame.size = CGSizeMake(((DeviceData.width - 30)/7), (DeviceData.height - 95)/5) bgView.frame.origin = CGPointMake(30 + ((DeviceData.width - 30)/7) * CGFloat(whichWeekDay - 1) , 95 + ((DeviceData.height - 95)/5) * CGFloat(whichClass - 1)) bgView.backgroundColor = UIColor.clearColor() self.view.addSubview(bgView) let bgImageView = UIImageView(frame: bgView.bounds) let randNum = arc4random_uniform(15) bgImageView.image = UIImage(named: NSString(format: "ic_week_course_half_bg_%d", randNum) as String) bgView.addSubview(bgImageView) let courseNameTittle = UILabel(frame: bgView.bounds) courseNameTittle.text = courseName courseNameTittle.font = UIFont.systemFontOfSize(12) courseNameTittle.textColor = UIColor.whiteColor() courseNameTittle.numberOfLines = 3 bgImageView.addSubview(courseNameTittle) } }
gpl-2.0
1b81e62f8369613279bd4b52c4f2b841
37.258993
165
0.608876
3.995492
false
false
false
false
dclelland/AudioKit
AudioKit/OSX/AudioKit/AudioKit for OSX.playground/Pages/Recording from Microphone.xcplaygroundpage/Contents.swift
1
1288
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Recording from Microphone //: import XCPlayground import AudioKit let mic = AKMicrophone() let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("recording", ofType: "wav") var player = AKAudioPlayer(file!) var reverb = AKReverb(mic) reverb.loadFactoryPreset(.Plate) AudioKit.output = AKMixer(reverb, player) AudioKit.start() class PlaygroundView: AKPlaygroundView { var recorder = AKMicrophoneRecorder(file!) override func setup() { addTitle("Recording from Microphone") addButton("Record", action: #selector(record)) addButton("Stop", action: #selector(stop)) addLabel("Playback") addButton("Play", action: #selector(play)) } func play() { player.stop() player.replaceFile(file!) player.play() } func record() { recorder.record() } func stop() { recorder.stop() } } let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 350)) XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = view //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
5d6087775beb5990c5291a7b88854b61
22
77
0.643634
4.128205
false
false
false
false
kstaring/swift
test/SILGen/existential_erasure.swift
4
4595
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s protocol P { func downgrade(_ m68k: Bool) -> Self func upgrade() throws -> Self } protocol Q {} struct X: P, Q { func downgrade(_ m68k: Bool) -> X { return self } func upgrade() throws -> X { return self } } func makePQ() -> P & Q { return X() } func useP(_ x: P) { } func throwingFunc() throws -> Bool { return true } // CHECK-LABEL: sil hidden @_TF19existential_erasure5PQtoPFT_T_ : $@convention(thin) () -> () { func PQtoP() { // CHECK: [[PQ_PAYLOAD:%.*]] = open_existential_addr [[PQ:%.*]] : $*P & Q to $*[[OPENED_TYPE:@opened(.*) P & Q]] // CHECK: [[P_PAYLOAD:%.*]] = init_existential_addr [[P:%.*]] : $*P, $[[OPENED_TYPE]] // CHECK: copy_addr [take] [[PQ_PAYLOAD]] to [initialization] [[P_PAYLOAD]] // CHECK: deinit_existential_addr [[PQ]] // CHECK-NOT: destroy_addr [[P]] // CHECK-NOT: destroy_addr [[P_PAYLOAD]] // CHECK-NOT: destroy_addr [[PQ]] // CHECK-NOT: destroy_addr [[PQ_PAYLOAD]] useP(makePQ()) } // Make sure uninitialized existentials are properly deallocated when we // have an early return. // CHECK-LABEL: sil hidden @_TF19existential_erasure19openExistentialToP1FzPS_1P_T_ func openExistentialToP1(_ p: P) throws { // CHECK: bb0(%0 : $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.downgrade!1, [[OPEN]] // CHECK: [[FUNC:%.*]] = function_ref @_TF19existential_erasure12throwingFuncFzT_Sb // CHECK: try_apply [[FUNC]]() // // CHECK: bb1([[SUCCESS:%.*]] : $Bool): // CHECK: apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[SUCCESS]], [[OPEN]]) // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: return // // CHECK: bb2([[FAILURE:%.*]] : $Error): // CHECK: deinit_existential_addr [[RESULT]] // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: throw [[FAILURE]] // try useP(p.downgrade(throwingFunc())) } // CHECK-LABEL: sil hidden @_TF19existential_erasure19openExistentialToP2FzPS_1P_T_ func openExistentialToP2(_ p: P) throws { // CHECK: bb0(%0 : $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.upgrade!1, [[OPEN]] // CHECK: try_apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: return // // CHECK: bb2([[FAILURE:%.*]]: $Error): // CHECK: deinit_existential_addr [[RESULT]] // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: throw [[FAILURE]] // try useP(p.upgrade()) } // Same as above but for boxed existentials extension Error { func returnOrThrowSelf() throws -> Self { throw self } } // CHECK-LABEL: sil hidden @_TF19existential_erasure12errorHandlerFzPs5Error_PS0__ func errorHandler(_ e: Error) throws -> Error { // CHECK: bb0(%0 : $Error): // CHECK: debug_value %0 : $Error // CHECK: [[OPEN:%.*]] = open_existential_box %0 : $Error to $*[[OPEN_TYPE:@opened\(.*\) Error]] // CHECK: [[RESULT:%.*]] = alloc_existential_box $Error, $[[OPEN_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[OPEN_TYPE]] in [[RESULT]] : $Error // CHECK: [[FUNC:%.*]] = function_ref @_TFE19existential_erasurePs5Error17returnOrThrowSelf // CHECK: try_apply [[FUNC]]<[[OPEN_TYPE]]>([[ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: destroy_value %0 : $Error // CHECK: return [[RESULT]] : $Error // // CHECK: bb2([[FAILURE:%.*]] : $Error): // CHECK: dealloc_existential_box [[RESULT]] // CHECK: destroy_value %0 : $Error // CHECK: throw [[FAILURE]] : $Error // return try e.returnOrThrowSelf() } // rdar://problem/22003864 -- SIL verifier crash when init_existential_addr // references dynamic Self type class EraseDynamicSelf { required init() {} // CHECK-LABEL: sil hidden @_TZFC19existential_erasure16EraseDynamicSelf7factoryfT_DS0_ : $@convention(method) (@thick EraseDynamicSelf.Type) -> @owned EraseDynamicSelf // CHECK: [[ANY:%.*]] = alloc_stack $Any // CHECK: init_existential_addr [[ANY]] : $*Any, $@dynamic_self EraseDynamicSelf // class func factory() -> Self { let instance = self.init() let _: Any = instance return instance } }
apache-2.0
8ef58a3cbf6750c2e3ed2dbd74152e14
33.291045
168
0.615669
3.251946
false
false
false
false
sekouperry/PullToRefresh
PullToRefresh/PullToRefresh.swift
3
7531
// // PullToRefresh.swift // CookingPullToRefresh // // Created by Anastasiya Gorban on 4/14/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import UIKit import Foundation public protocol RefreshViewAnimator { func animateState(state: State) } // MARK: PullToRefresh public class PullToRefresh: NSObject { let refreshView: UIView var action: (() -> ())? private let animator: RefreshViewAnimator private var scrollViewDefaultInsets = UIEdgeInsetsZero weak var scrollView: UIScrollView? { didSet { oldValue?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext) if let scrollView = scrollView { scrollViewDefaultInsets = scrollView.contentInset scrollView.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &KVOContext) } } } // MARK: - State var state: State = .Inital { didSet { animator.animateState(state) switch state { case .Loading: if let scrollView = scrollView where (oldValue != .Loading) { scrollView.contentOffset = previousScrollViewOffset scrollView.bounces = false UIView.animateWithDuration(0.3, animations: { let insets = self.refreshView.frame.height + self.scrollViewDefaultInsets.top scrollView.contentInset.top = insets scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -insets) }, completion: { finished in scrollView.bounces = true }) action?() } case .Finished: UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveLinear, animations: { self.scrollView?.contentInset = self.scrollViewDefaultInsets self.scrollView?.contentOffset.y = -self.scrollViewDefaultInsets.top }, completion: nil) default: break } } } // MARK: - Initialization public init(refreshView: UIView, animator: RefreshViewAnimator) { self.refreshView = refreshView self.animator = animator } public override convenience init() { let refreshView = DefaultRefreshView() self.init(refreshView: refreshView, animator: DefaultViewAnimator(refreshView: refreshView)) } deinit { scrollView?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext) } // MARK: KVO private var KVOContext = "PullToRefreshKVOContext" private let contentOffsetKeyPath = "contentOffset" private var previousScrollViewOffset: CGPoint = CGPointZero override public func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) { if (context == &KVOContext && keyPath == contentOffsetKeyPath && object as? UIScrollView == scrollView) { let offset = previousScrollViewOffset.y + scrollViewDefaultInsets.top let refreshViewHeight = refreshView.frame.size.height switch offset { case 0 where (state != .Loading): state = .Inital case -refreshViewHeight...0 where (state != .Loading && state != .Finished): state = .Releasing(progress: -offset / refreshViewHeight) case -1000...(-refreshViewHeight): if state == State.Releasing(progress: 1) && scrollView?.dragging == false { state = .Loading } else if state != State.Loading && state != State.Finished { state = .Releasing(progress: 1) } default: break } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } previousScrollViewOffset.y = scrollView!.contentOffset.y } // MARK: - Start/End Refreshing func startRefreshing() { if self.state != State.Inital { return } scrollView?.setContentOffset(CGPointMake(0, -refreshView.frame.height - scrollViewDefaultInsets.top), animated: true) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.27 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue(), { self.state = State.Loading }) } func endRefreshing() { if state == .Loading { state = .Finished } } } // MARK: - State enumeration public enum State:Equatable, Printable { case Inital, Loading, Finished case Releasing(progress: CGFloat) public var description: String { switch self { case .Inital: return "Inital" case .Releasing(let progress): return "Releasing:\(progress)" case .Loading: return "Loading" case .Finished: return "Finished" } } } public func ==(a: State, b: State) -> Bool { switch (a, b) { case (.Inital, .Inital): return true case (.Loading, .Loading): return true case (.Finished, .Finished): return true case (.Releasing(let a), .Releasing(let b)): return true default: return false } } // MARK: Default PullToRefresh class DefaultRefreshView: UIView { private(set) var activicyIndicator: UIActivityIndicatorView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { frame = CGRectMake(frame.origin.x, frame.origin.y, frame.width, 40) } override func layoutSubviews() { if (activicyIndicator == nil) { activicyIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) activicyIndicator.center = convertPoint(center, fromView: superview) activicyIndicator.hidesWhenStopped = false addSubview(activicyIndicator) } super.layoutSubviews() } override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) if let superview = newSuperview { frame = CGRectMake(frame.origin.x, frame.origin.y, superview.frame.width, 40) } } } class DefaultViewAnimator: RefreshViewAnimator { private let refreshView: DefaultRefreshView init(refreshView: DefaultRefreshView) { self.refreshView = refreshView } func animateState(state: State) { switch state { case .Inital: refreshView.activicyIndicator?.stopAnimating() case .Releasing(let progress): var transform = CGAffineTransformIdentity transform = CGAffineTransformScale(transform, progress, progress); transform = CGAffineTransformRotate(transform, 3.14 * progress * 2); refreshView.activicyIndicator.transform = transform case .Loading: refreshView.activicyIndicator.startAnimating() default: break } } }
mit
ee7cc15a051bb598542dfc094de9183d
33.545872
171
0.610676
5.27381
false
false
false
false
Witcast/witcast-ios
Pods/Material/Sources/iOS/NavigationController.swift
1
6814
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit extension NavigationController { /// Device status bar style. open var statusBarStyle: UIStatusBarStyle { get { return Application.statusBarStyle } set(value) { Application.statusBarStyle = value } } } open class NavigationController: UINavigationController { /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** An initializer that initializes the object with an Optional nib and bundle. - Parameter nibNameOrNil: An Optional String for the nib. - Parameter bundle: An Optional NSBundle where the nib is located. */ public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } /** An initializer that initializes the object with a rootViewController. - Parameter rootViewController: A UIViewController for the rootViewController. */ public override init(rootViewController: UIViewController) { super.init(navigationBarClass: NavigationBar.self, toolbarClass: nil) setViewControllers([rootViewController], animated: false) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let v = interactivePopGestureRecognizer else { return } guard let x = navigationDrawerController else { return } if let l = x.leftPanGesture { l.require(toFail: v) } if let r = x.rightPanGesture { r.require(toFail: v) } } open override func viewDidLoad() { super.viewDidLoad() prepare() } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard let v = navigationBar as? NavigationBar else { return } guard let item = v.topItem else { return } v.layoutNavigationItem(item: item) } open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() layoutSubviews() } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { navigationBar.heightPreset = .normal navigationBar.width = view.width view.clipsToBounds = true view.backgroundColor = .white view.contentScaleFactor = Screen.scale // This ensures the panning gesture is available when going back between views. if let v = interactivePopGestureRecognizer { v.isEnabled = true v.delegate = self } } /// Calls the layout functions for the view heirarchy. open func layoutSubviews() { navigationBar.updateConstraints() navigationBar.setNeedsLayout() navigationBar.layoutIfNeeded() } } extension NavigationController: UINavigationBarDelegate { /** Delegation method that is called when a new UINavigationItem is about to be pushed. This is used to prepare the transitions between UIViewControllers on the stack. - Parameter navigationBar: A UINavigationBar that is used in the NavigationController. - Parameter item: The UINavigationItem that will be pushed on the stack. - Returns: A Boolean value that indicates whether to push the item on to the stack or not. True is yes, false is no. */ public func navigationBar(_ navigationBar: UINavigationBar, shouldPush item: UINavigationItem) -> Bool { if let v = navigationBar as? NavigationBar { if nil == item.backButton.image && nil == item.backButton.title { item.backButton.image = v.backButtonImage } item.backButton.addTarget(self, action: #selector(handleBackButton), for: .touchUpInside) if !item.backButton.isHidden { item.leftViews.insert(item.backButton, at: 0) } v.layoutNavigationItem(item: item) } return true } /// Handler for the back button. @objc internal func handleBackButton() { popViewController(animated: true) } } extension NavigationController: UIGestureRecognizerDelegate { /** Detects the gesture recognizer being used. This is necessary when using NavigationDrawerController. It eliminates the conflict in panning. - Parameter gestureRecognizer: A UIGestureRecognizer to detect. - Parameter touch: The UITouch event. - Returns: A Boolean of whether to continue the gesture or not, true yes, false no. */ public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return interactivePopGestureRecognizer == gestureRecognizer && nil != navigationBar.backItem } }
apache-2.0
1090d12c7ab2c007d8f942b89a7d0336
35.244681
115
0.689903
5.100299
false
false
false
false
andre-alves/PHDiff
Tests/Test Helpers/Random.swift
2
696
// // Random.swift // PHDiff // // Created by Andre Alves on 10/16/16. // Copyright © 2016 Andre Alves. All rights reserved. // import Foundation func randomArray(length: Int) -> [String] { let charactersString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let charactersArray: [Character] = Array(charactersString) var array: [String] = [] for _ in 0..<length { array.append(String(charactersArray[Int(arc4random()) % charactersArray.count])) } return array } func randomNumber(_ range: Range<Int>) -> Int { let min = range.lowerBound let max = range.upperBound return Int(arc4random_uniform(UInt32(max - min))) + min }
mit
fb01deaf08911d5e7ae7de6aa0f79902
24.740741
91
0.684892
3.882682
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift
14
2680
// // TakeWhile.swift // RxSwift // // Created by Krunoslav Zaher on 6/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Returns elements from an observable sequence as long as a specified condition is true. - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) - parameter predicate: A function to test each element for a condition. - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ public func takeWhile(_ predicate: @escaping (Element) throws -> Bool) -> Observable<Element> { return TakeWhile(source: self.asObservable(), predicate: predicate) } } final private class TakeWhileSink<Observer: ObserverType> : Sink<Observer> , ObserverType { typealias Element = Observer.Element typealias Parent = TakeWhile<Element> fileprivate let _parent: Parent fileprivate var _running = true init(parent: Parent, observer: Observer, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if !self._running { return } do { self._running = try self._parent._predicate(value) } catch let e { self.forwardOn(.error(e)) self.dispose() return } if self._running { self.forwardOn(.next(value)) } else { self.forwardOn(.completed) self.dispose() } case .error, .completed: self.forwardOn(event) self.dispose() } } } final private class TakeWhile<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool fileprivate let _source: Observable<Element> fileprivate let _predicate: Predicate init(source: Observable<Element>, predicate: @escaping Predicate) { self._source = source self._predicate = predicate } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = TakeWhileSink(parent: self, observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
mit
554b32b1a3acb8727f520d80681e6158
30.517647
171
0.615528
4.853261
false
false
false
false
vamsirajendra/firefox-ios
Extensions/SendTo/ClientPickerViewController.swift
2
11223
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Storage import SnapKit protocol ClientPickerViewControllerDelegate { func clientPickerViewControllerDidCancel(clientPickerViewController: ClientPickerViewController) -> Void func clientPickerViewController(clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) -> Void } struct ClientPickerViewControllerUX { static let TableHeaderRowHeight = CGFloat(50) static let TableHeaderTextFont = UIFont.systemFontOfSize(16) static let TableHeaderTextColor = UIColor.grayColor() static let TableHeaderTextPaddingLeft = CGFloat(20) static let DeviceRowTintColor = UIColor(red:0.427, green:0.800, blue:0.102, alpha:1.0) static let DeviceRowHeight = CGFloat(50) static let DeviceRowTextFont = UIFont.systemFontOfSize(16) static let DeviceRowTextPaddingLeft = CGFloat(72) static let DeviceRowTextPaddingRight = CGFloat(50) } /// The ClientPickerViewController displays a list of clients associated with the provided Account. /// The user can select a number of devices and hit the Send button. /// This viewcontroller does not implement any specific business logic that needs to happen with the selected clients. /// That is up to it's delegate, who can listen for cancellation and success events. class ClientPickerViewController: UITableViewController { var profile: Profile? var clientPickerDelegate: ClientPickerViewControllerDelegate? var reloading = true var clients: [RemoteClient] = [] var selectedClients = NSMutableSet() override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Send Tab", tableName: "SendTo", comment: "Title of the dialog that allows you to send a tab to a different device") refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancel") tableView.registerClass(ClientPickerTableViewHeaderCell.self, forCellReuseIdentifier: ClientPickerTableViewHeaderCell.CellIdentifier) tableView.registerClass(ClientPickerTableViewCell.self, forCellReuseIdentifier: ClientPickerTableViewCell.CellIdentifier) tableView.registerClass(ClientPickerNoClientsTableViewCell.self, forCellReuseIdentifier: ClientPickerNoClientsTableViewCell.CellIdentifier) tableView.tableFooterView = UIView(frame: CGRectZero) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let refreshControl = refreshControl { refreshControl.beginRefreshing() let height = -(refreshControl.bounds.size.height + (self.navigationController?.navigationBar.bounds.size.height ?? 0)) self.tableView.contentOffset = CGPointMake(0, height) } reloadClients() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if clients.count == 0 { return 1 } else { return 2 } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if clients.count == 0 { return 1 } else { if section == 0 { return 1 } else { return clients.count } } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell if clients.count > 0 { if indexPath.section == 0 { cell = tableView.dequeueReusableCellWithIdentifier(ClientPickerTableViewHeaderCell.CellIdentifier, forIndexPath: indexPath) as! ClientPickerTableViewHeaderCell } else { let clientCell = tableView.dequeueReusableCellWithIdentifier(ClientPickerTableViewCell.CellIdentifier, forIndexPath: indexPath) as! ClientPickerTableViewCell clientCell.nameLabel.text = clients[indexPath.row].name clientCell.clientType = clients[indexPath.row].type == "mobile" ? ClientType.Mobile : ClientType.Desktop clientCell.checked = selectedClients.containsObject(indexPath) cell = clientCell } } else { if reloading == false { cell = tableView.dequeueReusableCellWithIdentifier(ClientPickerNoClientsTableViewCell.CellIdentifier, forIndexPath: indexPath) as! ClientPickerNoClientsTableViewCell } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "ClientCell") } } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if clients.count > 0 && indexPath.section == 1 { tableView.deselectRowAtIndexPath(indexPath, animated: true) if selectedClients.containsObject(indexPath) { selectedClients.removeObject(indexPath) } else { selectedClients.addObject(indexPath) } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None) navigationItem.rightBarButtonItem?.enabled = (selectedClients.count != 0) } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if clients.count > 0 { if indexPath.section == 0 { return ClientPickerViewControllerUX.TableHeaderRowHeight } else { return ClientPickerViewControllerUX.DeviceRowHeight } } else { return tableView.frame.height } } private func reloadClients() { reloading = true profile?.getClients().upon({ result in self.reloading = false if let c = result.successValue { self.clients = c dispatch_async(dispatch_get_main_queue()) { if self.clients.count == 0 { self.navigationItem.rightBarButtonItem = nil } else { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Send", tableName: "SendTo", comment: "Navigation bar button to Send the current page to a device"), style: UIBarButtonItemStyle.Done, target: self, action: "send") self.navigationItem.rightBarButtonItem?.enabled = false } self.selectedClients.removeAllObjects() self.tableView.reloadData() self.refreshControl?.endRefreshing() } } }) } func refresh() { reloadClients() } func cancel() { clientPickerDelegate?.clientPickerViewControllerDidCancel(self) } func send() { var clients = [RemoteClient]() for indexPath in selectedClients { clients.append(self.clients[indexPath.row]) } clientPickerDelegate?.clientPickerViewController(self, didPickClients: clients) } } class ClientPickerTableViewHeaderCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewSectionHeader" let nameLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(nameLabel) nameLabel.font = ClientPickerViewControllerUX.TableHeaderTextFont nameLabel.text = NSLocalizedString("Available devices:", tableName: "SendTo", comment: "Header for the list of devices table") nameLabel.textColor = ClientPickerViewControllerUX.TableHeaderTextColor nameLabel.snp_makeConstraints{ (make) -> Void in make.left.equalTo(ClientPickerViewControllerUX.TableHeaderTextPaddingLeft) make.centerY.equalTo(self) make.right.equalTo(self) } preservesSuperviewLayoutMargins = false layoutMargins = UIEdgeInsetsZero separatorInset = UIEdgeInsetsZero } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public enum ClientType: String { case Mobile = "deviceTypeMobile" case Desktop = "deviceTypeDesktop" } class ClientPickerTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewCell" var nameLabel: UILabel var checked: Bool = false { didSet { self.accessoryType = checked ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None } } var clientType: ClientType = ClientType.Mobile { didSet { self.imageView?.image = UIImage(named: clientType.rawValue) } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { nameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(nameLabel) nameLabel.font = ClientPickerViewControllerUX.DeviceRowTextFont nameLabel.numberOfLines = 2 nameLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping self.tintColor = ClientPickerViewControllerUX.DeviceRowTintColor self.preservesSuperviewLayoutMargins = false self.selectionStyle = UITableViewCellSelectionStyle.None } override func layoutSubviews() { super.layoutSubviews() nameLabel.snp_makeConstraints{ (make) -> Void in make.left.equalTo(ClientPickerViewControllerUX.DeviceRowTextPaddingLeft) make.centerY.equalTo(self.snp_centerY) make.right.equalTo(self.snp_right).offset(-ClientPickerViewControllerUX.DeviceRowTextPaddingRight) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ClientPickerNoClientsTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerNoClientsTableViewCell" override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupHelpView(contentView, introText: NSLocalizedString("You don't have any other devices connected to this Firefox Account available to sync.", tableName: "SendTo", comment: "Error message shown in the remote tabs panel"), showMeText: "") // TODO We used to have a 'show me how to ...' text here. But, we cannot open web pages from the extension. So this is clear for now until we decide otherwise. // Move the separator off screen separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
68630c0f5ae775908e33f77cd3c5b4b0
41.673004
270
0.685378
5.589143
false
false
false
false
nvkiet/XYZHappyCoding
XYZPlugin/XYZMenuHandler.swift
1
1527
// // XYZMenuHandler.swift // XYZPlugin // // Created by Kiet Nguyen on 12/25/15. // Copyright © 2015 Kiet Nguyen. All rights reserved. // import AppKit class XYZMenuHandler: NSObject { lazy var center = NSNotificationCenter.defaultCenter() override init() { super.init() center.addObserver(self, selector: Selector("createMenuItems"), name: NSApplicationDidFinishLaunchingNotification, object: nil) } deinit { removeObserver() } func removeObserver() { center.removeObserver(self) } func createMenuItems() { removeObserver() setup() } func setup() { guard let editMenuItem = NSApp.mainMenu!.itemWithTitle("Edit") else { return } let childMenuItem = NSMenuItem(title:"Happy Coding", action:nil, keyEquivalent:"") childMenuItem.enabled = true childMenuItem.submenu = NSMenu(title: childMenuItem.title) editMenuItem.submenu!.addItem(NSMenuItem.separatorItem()) editMenuItem.submenu!.addItem(childMenuItem) let subChildMenuItem = NSMenuItem(title: "Enable", action: "subChildMenuItemAction:", keyEquivalent: "") subChildMenuItem.target = self subChildMenuItem.state = NSOnState childMenuItem.submenu?.addItem(subChildMenuItem) } func subChildMenuItemAction(menuItem: NSMenuItem) { menuItem.state = XYZTogglingHandler.toggleMenu() } }
mit
1459ae7f97de348b1e7c297cb295efe1
26.745455
90
0.634338
4.844444
false
false
false
false
jum/CocoaLumberjack
Classes/DDAssert.swift
1
2393
// Software License Agreement (BSD License) // // Copyright (c) 2010-2019, Deusty, LLC // All rights reserved. // // Redistribution and use of this software in source and binary forms, // with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Neither the name of Deusty nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission of Deusty, LLC. /** * Replacement for Swift's `assert` function that will output a log message even when assertions * are disabled. * * - Parameters: * - condition: The condition to test. Unlike `Swift.assert`, `condition` is always evaluated, * even when assertions are disabled. * - message: A string to log (using `DDLogError`) if `condition` evaluates to `false`. * The default is an empty string. */ @inlinable public func DDAssert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = "", level: DDLogLevel = DDDefaultLogLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = false, ddlog: DDLog = DDLog.sharedInstance) { if !condition() { DDLogError(message(), level: level, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) Swift.assertionFailure(message(), file: file, line: line) } } /** * Replacement for Swift's `assertionFailure` function that will output a log message even * when assertions are disabled. * * - Parameters: * - message: A string to log (using `DDLogError`). The default is an empty string. */ @inlinable public func DDAssertionFailure(_ message: @autoclosure () -> String = "", level: DDLogLevel = DDDefaultLogLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = false, ddlog: DDLog = DDLog.sharedInstance) { DDLogError(message(), level: level, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) Swift.assertionFailure(message(), file: file, line: line) }
bsd-3-clause
32c5acf0b77961a66a169ef66889cf40
52.177778
332
0.711659
4.154514
false
false
false
false
squall09s/VegOresto
VegoResto/VGAbstractFilterViewController.swift
1
8081
// // VGAbstractFilterViewController.swift // VegoResto // // Created by Nicolas on 07/11/2017. // Copyright © 2017 Nicolas Laurent. All rights reserved. // import UIKit import BEMCheckBox class VGAbstractFilterViewController: UIViewController { let colorUnselected = UIColor.lightGray @IBOutlet weak var varIB_check_categorie_1: BEMCheckBox? @IBOutlet weak var varIB_check_categorie_2: BEMCheckBox? @IBOutlet weak var varIB_check_categorie_3: BEMCheckBox? @IBOutlet weak var varIB_bt_filtre_categorie_1: UIButton! @IBOutlet weak var varIB_bt_filtre_categorie_2: UIButton! @IBOutlet weak var varIB_bt_filtre_categorie_3: UIButton! @IBOutlet weak var varIB_separator_categorie_1: UIView! @IBOutlet weak var varIB_separator_categorie_2: UIView! @IBOutlet weak var varIB_separator_categorie_3: UIView! @IBOutlet weak var varIB_label_categorie_1: UILabel! @IBOutlet weak var varIB_label_categorie_2: UILabel! @IBOutlet weak var varIB_label_categorie_3: UILabel! var filtre_categorie_Vegetarien_active = true var filtre_categorie_Vegan_active = true var filtre_categorie_VeganFriendly_active = true @IBAction func touch_bt_categorie(sender: UIButton) { if sender == self.varIB_bt_filtre_categorie_1 { if self.filtre_categorie_Vegetarien_active == false || ( self.filtre_categorie_Vegan_active || self.filtre_categorie_VeganFriendly_active ) { self.filtre_categorie_Vegetarien_active = !(self.filtre_categorie_Vegetarien_active) } } else if sender == self.varIB_bt_filtre_categorie_2 { if self.filtre_categorie_Vegan_active == false || ( self.filtre_categorie_Vegetarien_active || self.filtre_categorie_VeganFriendly_active ) { self.filtre_categorie_Vegan_active = !(self.filtre_categorie_Vegan_active) } } else if sender == self.varIB_bt_filtre_categorie_3 { if self.filtre_categorie_VeganFriendly_active == false || ( self.filtre_categorie_Vegan_active || self.filtre_categorie_Vegetarien_active ) { self.filtre_categorie_VeganFriendly_active = !(self.filtre_categorie_VeganFriendly_active) } } let MidWidthSeparator = ((Device.WIDTH - 40.0 ) / 3.0 ) / 2.0 if self.filtre_categorie_Vegetarien_active { if self.varIB_check_categorie_1!.on == false { self.varIB_check_categorie_1?.setOn(true, animated: true) UIView.animate(withDuration: 0.5, animations: { self.varIB_label_categorie_1?.textColor = COLOR_VIOLET }) } } else { if self.varIB_check_categorie_1!.on == true { self.varIB_check_categorie_1?.setOn(false, animated: true) UIView.animate(withDuration: 0.5, animations: { self.varIB_label_categorie_1?.textColor = self.colorUnselected }) } } self.varIB_separator_categorie_1?.mdInflateAnimatedFromPoint(point: CGPoint(x: MidWidthSeparator, y: 0), backgroundColor: self.filtre_categorie_Vegetarien_active ? COLOR_VIOLET : UIColor.lightGray.withAlphaComponent(0.4), duration: 0.5, completion: { }) if self.filtre_categorie_Vegan_active { if self.varIB_check_categorie_2!.on == false { self.varIB_check_categorie_2?.setOn(true, animated: true) UIView.animate(withDuration: 0.5, animations: { self.varIB_label_categorie_2?.textColor = COLOR_VERT }) } } else { if self.varIB_check_categorie_2!.on == true { self.varIB_check_categorie_2?.setOn(false, animated: true) UIView.animate(withDuration: 0.5, animations: { self.varIB_label_categorie_2?.textColor = self.colorUnselected }) } } self.varIB_separator_categorie_2?.mdInflateAnimatedFromPoint(point: CGPoint(x: MidWidthSeparator, y: 0), backgroundColor: self.filtre_categorie_Vegan_active ? COLOR_VERT : UIColor.lightGray.withAlphaComponent(0.4), duration: 0.5, completion: { }) if self.filtre_categorie_VeganFriendly_active { if self.varIB_check_categorie_3!.on == false { self.varIB_check_categorie_3?.setOn(true, animated: true) UIView.animate(withDuration: 0.5, animations: { self.varIB_label_categorie_3?.textColor = COLOR_BLEU }) } } else { if self.varIB_check_categorie_3!.on == true { self.varIB_check_categorie_3?.setOn(false, animated: true) UIView.animate(withDuration: 0.5, animations: { self.varIB_label_categorie_3?.textColor = self.colorUnselected }) } } self.varIB_separator_categorie_3?.mdInflateAnimatedFromPoint(point: CGPoint(x: MidWidthSeparator, y: 0), backgroundColor: self.filtre_categorie_VeganFriendly_active ? COLOR_BLEU : UIColor.lightGray.withAlphaComponent(0.4), duration: 0.5, completion: { }) self.updateData() } func updateData() { } override func viewDidLoad() { super.viewDidLoad() self.varIB_bt_filtre_categorie_1?.layer.cornerRadius = 15.0 self.varIB_bt_filtre_categorie_2?.layer.cornerRadius = 15.0 self.varIB_bt_filtre_categorie_3?.layer.cornerRadius = 15.0 self.varIB_check_categorie_1?.boxType = .square self.varIB_check_categorie_2?.boxType = .square self.varIB_check_categorie_3?.boxType = .square self.varIB_check_categorie_1?.onAnimationType = .bounce self.varIB_check_categorie_1?.offAnimationType = .bounce self.varIB_check_categorie_2?.onAnimationType = .bounce self.varIB_check_categorie_2?.offAnimationType = .bounce self.varIB_check_categorie_3?.onAnimationType = .bounce self.varIB_check_categorie_3?.offAnimationType = .bounce self.varIB_check_categorie_1?.onFillColor = COLOR_VIOLET self.varIB_check_categorie_2?.onFillColor = COLOR_VERT self.varIB_check_categorie_3?.onFillColor = COLOR_BLEU self.varIB_check_categorie_1?.onTintColor = UIColor.white self.varIB_check_categorie_2?.onTintColor = UIColor.white self.varIB_check_categorie_3?.onTintColor = UIColor.white self.varIB_check_categorie_1?.tintColor = colorUnselected self.varIB_check_categorie_2?.tintColor = colorUnselected self.varIB_check_categorie_3?.tintColor = colorUnselected self.varIB_check_categorie_1?.onCheckColor = UIColor.white self.varIB_check_categorie_2?.onCheckColor = UIColor.white self.varIB_check_categorie_3?.onCheckColor = UIColor.white self.varIB_check_categorie_1?.setOn(true, animated: false) self.varIB_label_categorie_1?.textColor = COLOR_VIOLET self.varIB_check_categorie_2?.setOn(true, animated: false) self.varIB_label_categorie_2?.textColor = COLOR_VERT self.varIB_check_categorie_3?.setOn(true, animated: false) self.varIB_label_categorie_3?.textColor = COLOR_BLEU self.varIB_separator_categorie_1?.backgroundColor = COLOR_VIOLET self.varIB_separator_categorie_2?.backgroundColor = COLOR_VERT self.varIB_separator_categorie_3?.backgroundColor = COLOR_BLEU // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
98c019a1429b971501b530d1aa8d03a9
41.083333
259
0.652723
3.545415
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/KeyStore/KeyStore+CloudBackup.swift
1
8651
// // KeyStore+CloudBackup.swift // breadwallet // // Created by Adrian Corscadden on 2020-08-12. // Copyright © 2020 Breadwinner AG. All rights reserved. // // See the LICENSE file at the project root for license information. // import Foundation import WalletKit @available(iOS 13.6, *) extension KeyStore: Trackable { func doesCurrentWalletHaveBackup() -> Bool { let id = Store.state.walletID ?? CloudBackup.noIDKey let backup = listBackups().first(where: { $0.identifier == id }) return backup != nil } func unlockBackup(pin: String, key: String) -> Result<Account, Error> { guard unlockBackupPinAttemptsRemaining > 0 else { return .failure(UnlockBackupError.backupDeleted) } let backups = listBackups() guard let backup = backups.first(where: { $0.identifier == key }) else { return .failure(UnlockBackupError.noBackupFound) } let phrase = backup.recoverPhrase(withPin: pin, salt: backup.salt) guard !phrase.isEmpty else { if unlockBackupPinAttemptsRemaining == 1 { deleteBackupFor(key: key) return .failure(UnlockBackupError.backupDeleted) } else { let attemptsRemaining = incrementFailedBackupCount(pin: pin) return .failure(UnlockBackupError.wrongPin(attemptsRemaining)) } } resetFailedBackupCount() guard let account = setSeedPhrase(phrase) else { return .failure(UnlockBackupError.couldNotCreateAccount)} guard setPin(pin) else { fatalError() } return .success(account) } // Increments pin failed count and returns // attempts remaining private func incrementFailedBackupCount(pin: String) -> Int { var failCount: Int64 = (try? keychainItem(key: KeychainKey.cloudPinFailCount)) ?? 0 if !KeyStore.failedBackupPins.contains(pin) { KeyStore.failedBackupPins.append(pin) failCount += 1 try? setKeychainItem(key: KeychainKey.cloudPinFailCount, item: Int64(failCount)) } return unlockBackupPinAttemptsRemaining } private func resetFailedBackupCount() { try? setKeychainItem(key: KeychainKey.cloudPinFailCount, item: Int64(0)) KeyStore.failedBackupPins.removeAll() } private func deleteBackupFor(key: String) { guard let backup = listBackups().first(where: { $0.identifier == key }) else { return } _ = deleteBackup(backup) resetFailedBackupCount() } /// number of unique failed pin attempts remaining before wallet is wiped private var unlockBackupPinAttemptsRemaining: Int { do { let failCount: Int64 = try keychainItem(key: KeychainKey.cloudPinFailCount) ?? 0 return Int(maxBackupPinAttemptsBeforeWipe - failCount) } catch { return -1 } } func listBackups() -> [CloudBackup] { let data = getAllKeyChainItemsOfClass(kSecClassGenericPassword as String) var results = [CloudBackup]() data.forEach { (key, val) in do { let backup = try JSONDecoder().decode(CloudBackup.self, from: val) results.append(backup) } catch _ { print("[CloudBackups] found unknown: \(key)") } } return results } func deleteBackup(_ backupData: CloudBackup) -> Bool { let query = [kSecClass as String: kSecClassGenericPassword as String, kSecAttrService as String: WalletSecAttrService, kSecAttrAccount as String: backupData.identifier, kSecAttrSynchronizable as String: true as CFBoolean ] as [String: Any] var status = noErr if SecItemCopyMatching(query as CFDictionary, nil) != errSecItemNotFound { status = SecItemDelete(query as CFDictionary) saveEvent("backup.delete") } guard status == noErr else { return false } return true } //Used for backing up existing wallet //Since this happens after onboarding, we will have a walletId func addBackup(forPin pin: String) -> Bool { guard let phrase = seedPhrase(pin: pin) else { return false } guard let id = Store.state.walletID else { return false } let backup = CloudBackup(phrase: phrase, identifier: id, pin: pin) return addBackup(backup) } func addBackup() -> Bool { guard let pin: String = try? keychainItem(key: KeychainKey.pin) else { return false } guard let phrase = seedPhrase(pin: pin) else { return false } let id = CloudBackup.noIDKey let backup = CloudBackup(phrase: phrase, identifier: id, pin: pin) return addBackup(backup) } func migrateNoKeyBackup(id: String) { guard let oldBackup = listBackups().first(where: { $0.identifier == CloudBackup.noIDKey }) else { return } let newBackup = oldBackup.migrateId(toId: id) _ = deleteBackup(oldBackup) _ = addBackup(newBackup) } func updateBackupPin(newPin: String, currentPin: String, forKey: String) -> Bool { guard let backup = listBackups().first(where: { $0.identifier == forKey }) else { return false } let phrase = backup.recoverPhrase(withPin: currentPin, salt: backup.salt) guard !phrase.isEmpty else { return false } let newBackup = CloudBackup(phrase: phrase, identifier: backup.identifier, pin: newPin) return addBackup(newBackup) } func deleteAllBackups() { listBackups().forEach { _ = self.deleteBackup($0) } } func deleteCurrentBackup() { let ids = [Store.state.walletID, CloudBackup.noIDKey].compactMap { $0 } ids.forEach { id in print("[CloudBackups] deleting key: \(id)") let backups = listBackups().filter({ $0.identifier == id }) backups.forEach { _ = self.deleteBackup($0) } } } func addBackup(_ backupData: CloudBackup) -> Bool { let query = [kSecClass as String: kSecClassGenericPassword as String, kSecAttrService as String: WalletSecAttrService, kSecAttrAccount as String: backupData.identifier, kSecAttrSynchronizable as String: true as CFBoolean ] as [String: Any] var status = noErr var data: Data do { data = try JSONEncoder().encode(backupData) } catch _ { return false } if SecItemCopyMatching(query as CFDictionary, nil) != errSecItemNotFound { // update existing item let update = [kSecValueData as String: data as Any] status = SecItemUpdate(query as CFDictionary, update as CFDictionary) } else { // add new item let item = [kSecClass as String: kSecClassGenericPassword as String, kSecAttrService as String: WalletSecAttrService, kSecAttrAccount as String: backupData.identifier, kSecValueData as String: data as Any, kSecAttrSynchronizable as String: true as CFBoolean ] status = SecItemAdd(item as CFDictionary, nil) saveEvent("backup.add") } guard status == noErr else { return false } return true } private func getAllKeyChainItemsOfClass(_ secClass: String) -> [String: Data] { let query: [String: Any] = [ kSecClass as String: secClass, kSecReturnData as String: true as CFBoolean, kSecReturnAttributes as String: true as CFBoolean, kSecMatchLimit as String: kSecMatchLimitAll, kSecAttrService as String: WalletSecAttrService, kSecAttrSynchronizable as String: true as CFBoolean ] var result: AnyObject? let lastResultCode = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } var values = [String: Data]() if lastResultCode == noErr { if let array = result as? [[String: Any]] { for item in array { if let key = item[kSecAttrAccount as String] as? String, let value = item[kSecValueData as String] as? Data { values[key] = value } } } } return values } }
mit
944f3132f8832afb0d68cf2f2532ed16
39.046296
131
0.606821
4.859551
false
false
false
false
xayoung/CS193P-DemoCode
LearnSwift-07/Psychologist/Psychologist/DianosedHappinessViewController.swift
1
1658
// // DianosedHappinessViewController.swift // Psychologist // // Created by xayoung on 16/5/2. // Copyright © 2016年 xayoung. All rights reserved. // import UIKit class DianosedHappinessViewController: HappinessViewController, UIPopoverPresentationControllerDelegate{ override var happiness: Int{ //先执行父类didSet,后执行子类的didSet。不会覆盖 didSet{ dianosticHistory += [happiness] } } private let defaults = NSUserDefaults.standardUserDefaults() var dianosticHistory: [Int] { get{ return defaults.objectForKey(History.DefaultsKey) as? [Int] ?? [] } set{ defaults.setObject(newValue, forKey: History.DefaultsKey) } } private struct History{ static let SegueIdentifier = "Show Diagnostic History" static let DefaultsKey = "DianosedHappinessViewController.History" } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case History.SegueIdentifier: if let tvc = segue.destinationViewController as? TextViewController{ if let ppc = tvc.popoverPresentationController { ppc.delegate = self } tvc.text = "\(dianosticHistory)" } default: break } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { //在iPhone上不做处理 return UIModalPresentationStyle.None } }
mit
ffb5c1c73aaf8728fca58162f7992eeb
34.755556
127
0.646986
5.310231
false
false
false
false
SuPair/VPNOn
VPNOnKit/Vendor/Wormhole.swift
1
7613
// // Wormhole.swift // Remote // // Created by NIX on 15/5/20. // Copyright (c) 2015年 nixWork. All rights reserved. // import Foundation func ==(lhs: Wormhole.MessageListener, rhs: Wormhole.MessageListener) -> Bool { return lhs.hashValue == rhs.hashValue } public class Wormhole: NSObject { let appGroupIdentifier: String let messageDirectoryName: String public init(appGroupIdentifier: String, messageDirectoryName: String) { self.appGroupIdentifier = appGroupIdentifier if messageDirectoryName.isEmpty { fatalError("ERROR: Wormhole need a message passing directory") } self.messageDirectoryName = messageDirectoryName } deinit { if let center = CFNotificationCenterGetDarwinNotifyCenter() { CFNotificationCenterRemoveEveryObserver(center, unsafeAddressOf(self)) } } public typealias Message = NSCoding public func passMessage(message: Message?, withIdentifier identifier: String) { if identifier.isEmpty { fatalError("ERROR: Message need identifier") } if let message = message { var success = false if let filePath = filePathForIdentifier(identifier) { let data = NSKeyedArchiver.archivedDataWithRootObject(message) success = data.writeToFile(filePath, atomically: true) } if success { if let center = CFNotificationCenterGetDarwinNotifyCenter() { CFNotificationCenterPostNotification(center, identifier, nil, nil, 1) } } } else { if let center = CFNotificationCenterGetDarwinNotifyCenter() { CFNotificationCenterPostNotification(center, identifier, nil, nil, 1) } } } public struct Listener { public typealias Action = Message? -> Void let name: String let action: Action public init(name: String, action: Action) { self.name = name self.action = action } } struct MessageListener: Hashable { let messageIdentifier: String let listener: Listener var hashValue: Int { return (messageIdentifier + "<nixzhu.Wormhole>" + listener.name).hashValue } } var messageListenerSet = Set<MessageListener>() public func bindListener(listener: Listener, forMessageWithIdentifier identifier: String) { if let center = CFNotificationCenterGetDarwinNotifyCenter() { let messageListener = MessageListener(messageIdentifier: identifier, listener: listener) messageListenerSet.insert(messageListener) let block: @objc_block (CFNotificationCenter!, UnsafeMutablePointer<Void>, CFString!, UnsafePointer<Void>, CFDictionary!) -> Void = { _, _, _, _, _ in if self.messageListenerSet.contains(messageListener) { messageListener.listener.action(self.messageWithIdentifier(identifier)) } } let imp: COpaquePointer = imp_implementationWithBlock(unsafeBitCast(block, AnyObject.self)) let callBack: CFNotificationCallback = unsafeBitCast(imp, CFNotificationCallback.self) CFNotificationCenterAddObserver(center, unsafeAddressOf(self), callBack, identifier, nil, CFNotificationSuspensionBehavior.DeliverImmediately) // Try fire Listener's action for first time listener.action(messageWithIdentifier(identifier)) } } public func removeListener(listener: Listener, forMessageWithIdentifier identifier: String) { let messageListener = MessageListener(messageIdentifier: identifier, listener: listener) messageListenerSet.remove(messageListener) } public func removeListenerByName(name: String, forMessageWithIdentifier identifier: String) { for messageListener in messageListenerSet { if messageListener.messageIdentifier == identifier && messageListener.listener.name == name { messageListenerSet.remove(messageListener) break } } } public func removeAllListenersForMessageWithIdentifier(identifier: String) { if let center = CFNotificationCenterGetDarwinNotifyCenter() { CFNotificationCenterRemoveObserver(center, unsafeAddressOf(self), identifier, nil) for listener in messageListenerSet { if listener.messageIdentifier == identifier { messageListenerSet.remove(listener) } } } } public func messageWithIdentifier(identifier: String) -> Message? { if let filePath = filePathForIdentifier(identifier), data = NSData(contentsOfFile: filePath), message = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Message { return message } return nil } public func destroyMessageWithIdentifier(identifier: String) { if let filePath = filePathForIdentifier(identifier) { let fileManager = NSFileManager.defaultManager() do { try fileManager.removeItemAtPath(filePath) } catch _ { } } } public func destroyAllMessages() { if let directoryPath = messagePassingDirectoryPath() { let fileManager = NSFileManager.defaultManager() if let fileNames = (try? fileManager.contentsOfDirectoryAtPath(directoryPath)) as? [String] { for fileName in fileNames { let filePath = (directoryPath as NSString).stringByAppendingPathComponent(fileName) do { try fileManager.removeItemAtPath(filePath) } catch _ { } } } } } // MARK: Helpers func filePathForIdentifier(identifier: String) -> String? { if identifier.isEmpty { return nil } if let directoryPath = messagePassingDirectoryPath() { let fileName = identifier + ".archive" let filePath = (directoryPath as NSString).stringByAppendingPathComponent(fileName) return filePath } return nil } func messagePassingDirectoryPath() -> String? { let fileManager = NSFileManager.defaultManager() if let appGroupContainer = fileManager.containerURLForSecurityApplicationGroupIdentifier(self.appGroupIdentifier), appGroupContainerPath = appGroupContainer.path { let directoryPath = (appGroupContainerPath as NSString).stringByAppendingPathComponent(messageDirectoryName) do { try fileManager.createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil) } catch _ { } return directoryPath } return nil } }
mit
cb02c32257ef7f9b9cb1823de170ccef
32.53304
162
0.586914
6.187805
false
false
false
false
MartinOSix/DemoKit
dSwift/SwiftDemoKit/SwiftDemoKit/DrawPaintViewController.swift
1
2088
// // DrawPaintViewController.swift // SwiftDemoKit // // Created by runo on 17/3/21. // Copyright © 2017年 com.runo. All rights reserved. // import UIKit class DrawPaintViewController: UIViewController { let pathView = DrawPaintView.init(frame: kScreenBounds) override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = .init(rawValue: 0) self.view.addSubview(pathView) } } class DrawPaintView: UIView { override func draw(_ rect: CGRect) { //圆角矩形 let roundPath = UIBezierPath(roundedRect: CGRect.init(x: 20, y: 20, width: 100, height: 100), cornerRadius: 20) roundPath.lineWidth = 5 UIColor.green.set() roundPath.fill() UIColor.red.set() roundPath.stroke() //圆弧 let arcPath = UIBezierPath() arcPath.move(to: CGPoint.init(x: 20, y: 150)) arcPath.addLine(to: CGPoint.init(x: 120, y: 150)) arcPath.addArc(withCenter: CGPoint.init(x: 20, y: 150), radius: 100, startAngle: 0, endAngle: CGFloat(M_PI_2), clockwise: true) arcPath.close() arcPath.lineCapStyle = .square arcPath.lineJoinStyle = .bevel//miter bevel arcPath.lineWidth = 5 UIColor.red.set() arcPath.stroke() //三角形 let triangle = UIBezierPath() triangle.move(to: CGPoint(x: 20, y: 300)) triangle.addLine(to: CGPoint.init(x: 150, y: 400)) triangle.addLine(to: CGPoint.init(x: 20, y: 400)) triangle.close() triangle.lineWidth = 5 UIColor.green.set() triangle.fill() UIColor.red.set() triangle.stroke() //贝塞尔曲线 let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint.init(x: 170, y: 50)) bezierPath.addQuadCurve(to: CGPoint.init(x: 170, y: 400), controlPoint: CGPoint.init(x: kScreenWidth-20, y: 200)) bezierPath.lineWidth = 5 UIColor.red.set() bezierPath.stroke() } }
apache-2.0
292e375a49a2080af440f815e3bc71da
24.7125
135
0.593097
3.873823
false
false
false
false
salesawagner/WASKit
Sources/Extensions/Array/Array+WASUtils.swift
1
2543
// // WASKit // // Copyright (c) Wagner Sales (http://wagnersales.com.br/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Array where Element: Hashable { // MARK: - Public properties /// Remove duplicate elements. /// /// ### Usage Example: ### /// ``` /// let array = [1, 1, 2, 2, 3, 4] /// let newArray = array.WASremoveDuplicates // [1, 2, 3, 4] /// ``` public var WASremoveDuplicates: [Element] { var result: [Element] = [] for value in self { if !result.contains(value) { result.append(value) } } return result } // MARK: - Public mutating methods /// Mutating remove duplicate elements. /// /// ### Usage Example: ### /// ``` /// var array = [1, 1, 2, 2, 3, 4] /// array.WASremoveDuplicates // [1, 2, 3, 4] /// ``` public mutating func WASremoveDuplicatesInPlace() { self = self.WASremoveDuplicates } // MARK: - Public methods /// Convert `Array` to `String` /// /// ### Usage Example: ### /// ``` /// var array = [1, 2, 3, 4] /// array.WAStoString() // "1234" /// array..WAStoString(withSeparator: ",") // "1,2,3,4" /// ``` /// /// - Parameter separator: `String` to separate `Array` elements. /// /// - Returns: The `String` formatted. public func WAStoString(withSeparator separator: String? = nil) -> String { var filter = "" for element in self { if filter.isEmpty { filter = "\(element)" } else { filter += separator ?? "" + "\(element)" } } return filter } }
mit
a462120173ce36921939091ec6ab31fe
28.569767
81
0.655918
3.512431
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Comments/EditCommentMultiLineCell.swift
1
1512
import Foundation protocol EditCommentMultiLineCellDelegate: AnyObject { func textViewHeightUpdated() func textUpdated(_ updatedText: String?) } class EditCommentMultiLineCell: UITableViewCell, NibReusable { // MARK: - Properties @IBOutlet weak var textView: UITextView! @IBOutlet weak var textViewMinHeightConstraint: NSLayoutConstraint! weak var delegate: EditCommentMultiLineCellDelegate? // MARK: - View override func awakeFromNib() { super.awakeFromNib() configureCell() } func configure(text: String? = nil) { textView.text = text adjustHeight() } } // MARK: - UITextViewDelegate extension EditCommentMultiLineCell: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { delegate?.textUpdated(textView.text) adjustHeight() } } // MARK: - Private Extension private extension EditCommentMultiLineCell { func configureCell() { textView.font = .preferredFont(forTextStyle: .body) textView.textColor = .text textView.backgroundColor = .clear } func adjustHeight() { let originalHeight = textView.frame.size.height textView.sizeToFit() let textViewHeight = ceilf(Float(max(textView.frame.size.height, textViewMinHeightConstraint.constant))) textView.frame.size.height = CGFloat(textViewHeight) if textViewHeight != Float(originalHeight) { delegate?.textViewHeightUpdated() } } }
gpl-2.0
e700004c6a4af1a8f188e7a042c8dbc2
23.387097
112
0.686508
5.04
false
false
false
false
hooman/swift
test/SILGen/generic_closures.swift
5
15349
// RUN: %target-swift-emit-silgen -module-name generic_closures -parse-stdlib %s | %FileCheck %s import Swift var zero: Int // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A21_nondependent_context{{[_0-9a-zA-Z]*}}F func generic_nondependent_context<T>(_ x: T, y: Int) -> Int { func foo() -> Int { return y } func bar() -> Int { return y } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]](%1) // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[BAR:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[BAR_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[BAR]](%1) // CHECK: destroy_value [[BAR_CLOSURE]] let _ = bar // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] _ = foo() // CHECK: [[BAR:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[BAR_CLOSURE:%.*]] = apply [[BAR]] // CHECK: [[BAR_CLOSURE]] return bar() } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A8_capture{{[_0-9a-zA-Z]*}}F func generic_capture<T>(_ x: T) -> Any.Type { func foo() -> Any.Type { return T.self } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>() // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>() // CHECK: return [[FOO_CLOSURE]] return foo() } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A13_capture_cast{{[_0-9a-zA-Z]*}}F func generic_capture_cast<T>(_ x: T, y: Any) -> Bool { func foo(_ a: Any) -> Bool { return a is T } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed Any) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>() // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed Any) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>([[ARG:%.*]]) // CHECK: return [[FOO_CLOSURE]] return foo(y) } protocol Concept { var sensical: Bool { get } } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A22_nocapture_existential{{[_0-9a-zA-Z]*}}F func generic_nocapture_existential<T>(_ x: T, y: Concept) -> Bool { func foo(_ a: Concept) -> Bool { return a.sensical } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in_guaranteed Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = thin_to_thick_function [[FOO]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in_guaranteed Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]([[ARG:%.*]]) // CHECK: return [[FOO_CLOSURE]] return foo(y) } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A18_dependent_context{{[_0-9a-zA-Z]*}}F func generic_dependent_context<T>(_ x: T, y: Int) -> T { func foo() -> T { return x } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>([[BOX:%.*]]) // CHECK: [[FOO_CLOSURE_CONV:%.*]] = convert_function [[FOO_CLOSURE]] // CHECK: destroy_value [[FOO_CLOSURE_CONV]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T> // CHECK: return return foo() } enum Optionable<Wrapped> { case none case some(Wrapped) } class NestedGeneric<U> { class func generic_nondependent_context<T>(_ x: T, y: Int, z: U) -> Int { func foo() -> Int { return y } let _ = foo return foo() } class func generic_dependent_inner_context<T>(_ x: T, y: Int, z: U) -> T { func foo() -> T { return x } let _ = foo return foo() } class func generic_dependent_outer_context<T>(_ x: T, y: Int, z: U) -> U { func foo() -> U { return z } let _ = foo return foo() } class func generic_dependent_both_contexts<T>(_ x: T, y: Int, z: U) -> (T, U) { func foo() -> (T, U) { return (x, z) } let _ = foo return foo() } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures13NestedGenericC20nested_reabstraction{{[_0-9a-zA-Z]*}}F // CHECK: [[REABSTRACT:%.*]] = function_ref @$sIeg_ytIegr_TR // CHECK: partial_apply [callee_guaranteed] [[REABSTRACT]] func nested_reabstraction<T>(_ x: T) -> Optionable<() -> ()> { return .some({}) } } // <rdar://problem/15417773> // Ensure that nested closures capture the generic parameters of their nested // context. // CHECK: sil hidden [ossa] @$s16generic_closures018nested_closure_in_A0yxxlF : $@convention(thin) <T> (@in_guaranteed T) -> @out T // CHECK: function_ref [[OUTER_CLOSURE:@\$s16generic_closures018nested_closure_in_A0yxxlFxyXEfU_]] // CHECK: sil private [ossa] [[OUTER_CLOSURE]] : $@convention(thin) <T> (@in_guaranteed T) -> @out T // CHECK: function_ref [[INNER_CLOSURE:@\$s16generic_closures018nested_closure_in_A0yxxlFxyXEfU_xyXEfU_]] // CHECK: sil private [ossa] [[INNER_CLOSURE]] : $@convention(thin) <T> (@in_guaranteed T) -> @out T { func nested_closure_in_generic<T>(_ x:T) -> T { return { { x }() }() } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures16local_properties{{[_0-9a-zA-Z]*}}F func local_properties<T>(_ t: inout T) { var prop: T { get { return t } set { t = newValue } } // CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER_REF]] t = prop // CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @inout_aliasable τ_0_0) -> () // CHECK: apply [[SETTER_REF]] prop = t var prop2: T { get { return t } set { // doesn't capture anything } } // CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER2_REF]] t = prop2 // CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> () // CHECK: apply [[SETTER2_REF]] prop2 = t } protocol Fooable { static func foo() -> Bool } // <rdar://problem/16399018> func shmassert(_ f: @autoclosure () -> Bool) {} // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures08capture_A6_param{{[_0-9a-zA-Z]*}}F func capture_generic_param<A: Fooable>(_ x: A) { shmassert(A.foo()) } // Make sure we use the correct convention when capturing class-constrained // member types: <rdar://problem/24470533> class Class {} protocol HasClassAssoc { associatedtype Assoc : Class } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlF // CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : @guaranteed $@callee_guaranteed @substituted <τ_0_0, τ_0_1 where τ_0_0 : _RefCountedObject, τ_0_1 : _RefCountedObject> (@guaranteed τ_0_0) -> @owned τ_0_1 for <T.Assoc, T.Assoc>): // CHECK: [[GENERIC_FN:%.*]] = function_ref @$s16generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlFA2EcycfU_ // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] // CHECK: [[CONCRETE_FN:%.*]] = partial_apply [callee_guaranteed] [[GENERIC_FN]]<T>([[ARG2_COPY]]) func captures_class_constrained_generic<T : HasClassAssoc>(_ x: T, f: @escaping (T.Assoc) -> T.Assoc) { let _: () -> (T.Assoc) -> T.Assoc = { f } } // Make sure local generic functions can have captures // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures06outer_A01t1iyx_SitlF : $@convention(thin) <T> (@in_guaranteed T, Int) -> () func outer_generic<T>(t: T, i: Int) { func inner_generic_nocapture<U>(u: U) -> U { return u } func inner_generic1<U>(u: U) -> Int { return i } func inner_generic2<U>(u: U) -> T { return t } let _: (()) -> () = inner_generic_nocapture // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>() : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 // CHECK: [[THUNK:%.*]] = function_ref @$sytytIegnr_Ieg_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 _ = inner_generic_nocapture(u: t) // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>(%1) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @$sytSiIegnd_SiIegd_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> Int = inner_generic1 // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int _ = inner_generic1(u: t) // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>([[ARG:%.*]]) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[THUNK:%.*]] = function_ref @$sytxIegnr_xIegr_lTR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]<T>([[CLOSURE]]) // CHECK: [[THUNK_CLOSURE_CONV:%.*]] = convert_function [[THUNK_CLOSURE]] // CHECK: destroy_value [[THUNK_CLOSURE_CONV]] let _: (()) -> T = inner_generic2 // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0 _ = inner_generic2(u: t) } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures14outer_concrete1iySi_tF : $@convention(thin) (Int) -> () func outer_concrete(i: Int) { func inner_generic_nocapture<U>(u: U) -> U { return u } func inner_generic<U>(u: U) -> Int { return i } // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>() : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[THUNK:%.*]] = function_ref @$sytytIegnr_Ieg_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> () = inner_generic_nocapture // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 _ = inner_generic_nocapture(u: i) // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>(%0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @$sytSiIegnd_SiIegd_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> Int = inner_generic // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int _ = inner_generic(u: i) } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF : $@convention(thin) <T> (@in_guaranteed T) -> () func mixed_generic_nongeneric_nesting<T>(t: T) { func outer() { func middle<U>(u: U) { func inner() -> U { return u } inner() } middle(u: 11) } outer() } // CHECK-LABEL: sil private [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF : $@convention(thin) <T> () -> () // CHECK-LABEL: sil private [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF : $@convention(thin) <T><U> (@in_guaranteed U) -> () // CHECK-LABEL: sil private [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF5innerL_qd__yr__lF : $@convention(thin) <T><U> (@in_guaranteed U) -> @out U protocol Doge { associatedtype Nose : NoseProtocol } protocol NoseProtocol { associatedtype Squeegee } protocol Doggo {} struct DogSnacks<A : Doggo> {} func capture_same_type_representative<Daisy: Doge, Roo: Doggo>(slobber: Roo, daisy: Daisy) where Roo == Daisy.Nose.Squeegee { var s = DogSnacks<Daisy.Nose.Squeegee>() _ = { _ = s } }
apache-2.0
90724cd24dbaaac99da298b49cec00c3
44.264095
228
0.61538
2.947633
false
false
false
false
SandcastleApps/partyup
PartyUP/AppDelegate.swift
1
10243
// // AppDelegate.swift // PartyUP // // Created by Fritz Vander Heide on 2015-09-13. // Copyright © 2015 Sandcastle Application Development. All rights reserved. // import UIKit import AWSCore import AWSS3 import AWSCognito import Flurry_iOS_SDK import FBSDKCoreKit struct PartyUpPreferences { static let VideoQuality = "VideoQuality" static let ListingRadius = "ListRadius" static let SampleRadius = "SampleRadius" static let VenueCategories = "VenueCategories" static let StaleSampleInterval = "StaleSampleInterval" static let CameraJump = "CameraJump" static let StickyTowns = "StickyTowns" static let PlayTutorial = "Tutorial" static let TutorialViewed = "TutorialViewed" static let AgreedToTerms = "Terms" static let RemindersInterface = "RemindersInterface" static let RemindersInterval = "RemindersInterval" static let SampleSuppressionThreshold = "SampleSuppressionThreshold" static let FeedNavigationArrows = "FeedNavigationArrows" static let SeedFacebookVideo = "SeedFacebookVideo" static let SeedFacebookBroadcast = "SeedFacebookBroadcast" static let SeedFacebookTimeline = "SeedFacebookTimeline" static let SeedStaleInterval = "SeedStaleInterval" static let PromptAuthentication = "PromptAuthentication" static let AllowAuthenticationPutoff = "AllowAuthenticationPutoff" } struct PartyUpConstants { static let FavoriteLocationNotification = "FavoriteLocationNotification" static let RecordVideoNotification = "RecordVideoNotification" static let DefaultStoragePrefix = "media" static let TitleLogo: ()->UIImageView = { let logoView = UIImageView(image: UIImage(named: "Logo")) logoView.contentMode = .ScaleAspectFit logoView.bounds = CGRect(x: 0, y: 0, width: 24, height: 40) return logoView } } struct FacebookConstants { static let GraphApiHost = NSURL(scheme: "https", host: "graph.facebook.com/v2.7", path: "/")! } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private struct AwsConstants { static let BackgroundSession = "com.sandcastleapps.partyup.session" } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { NSSetUncaughtExceptionHandler({ (error) in Flurry.logError("Uncaught_Exception", message: "Uh oh", exception: error) }) Flurry.setUserID(UIDevice.currentDevice().identifierForVendor?.UUIDString) Flurry.startSession(PartyUpKeys.FlurryIdentifier) let tint = UIColor(r: 247, g: 126, b: 86, alpha: 255) window?.tintColor = tint UINavigationBar.appearance().backgroundColor = UIColor.whiteColor() UINavigationBar.appearance().backIndicatorImage = UIImage(named: "Back") UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "Back") UINavigationBar.appearance().translucent = false UINavigationBar.appearance().tintColor = tint UIToolbar.appearance().tintColor = tint UITextView.appearance().tintColor = tint UIButton.appearance().tintColor = tint let defaults = NSUserDefaults.standardUserDefaults() if let defaultsUrl = NSBundle.mainBundle().URLForResource("PartyDefaults", withExtension: "plist") { if let defaultsDictionary = NSDictionary(contentsOfURL: defaultsUrl) as? [String:AnyObject] { defaults.registerDefaults(defaultsDictionary) } } observeSettingsChange() application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert], categories: nil)) let manager = NSFileManager.defaultManager() let mediaTemp = NSTemporaryDirectory() + PartyUpConstants.DefaultStoragePrefix if !manager.fileExistsAtPath(mediaTemp) { try! NSFileManager.defaultManager().createDirectoryAtPath(mediaTemp, withIntermediateDirectories: true, attributes: nil) } #if DEBUG AWSLogger.defaultLogger().logLevel = .Warn #else AWSLogger.defaultLogger().logLevel = .Error #endif NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.observeSettingsChange), name: NSUserDefaultsDidChangeNotification, object: nil) Sample.InitializeStamps() return AuthenticationManager.shared.application(application, didFinishLaunchingWithOptions: launchOptions) } func observeSettingsChange() { let defaults = NSUserDefaults.standardUserDefaults() if defaults.boolForKey(PartyUpPreferences.PlayTutorial) { defaults.setBool(false, forKey: PartyUpPreferences.PlayTutorial) defaults.setObject([], forKey: PartyUpPreferences.TutorialViewed) } } func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { application.cancelAllLocalNotifications() if notificationSettings.types != .None { scheduleReminders() if let notifyUrl = NSBundle.mainBundle().URLForResource("PartyNotify", withExtension: "plist") { scheduleNotificationsFromUrl(notifyUrl, inApplication: application, withNotificationSettings: notificationSettings) } } } func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) { AWSS3TransferUtility.interceptApplication(application, handleEventsForBackgroundURLSession: AwsConstants.BackgroundSession, completionHandler: completionHandler) } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return AuthenticationManager.shared.application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } func scheduleNotificationsFromUrl(url: NSURL, inApplication application: UIApplication, withNotificationSettings notificationSettings: UIUserNotificationSettings) { if let notifications = NSArray(contentsOfURL: url) as? [[String:AnyObject]] { for notify in notifications { scheduleNotificationFromDictionary(notify, inApplication: application, withNotificationSettings: notificationSettings) } } } func scheduleNotificationFromDictionary(notify: [String : AnyObject], inApplication application: UIApplication, withNotificationSettings notificationSettings: UIUserNotificationSettings) { if let whens = notify["whens"] as? [[String:Int]], what = notify["messages"] as? [String], action = notify["action"] as? String, tag = notify["tag"] as? Int where what.count > 0 { let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) for when in whens { let relative = NSDateComponents() relative.calendar = calendar relative.hour = when["hour"] ?? NSDateComponentUndefined relative.minute = when["minute"] ?? NSDateComponentUndefined relative.weekday = when["weekday"] ?? NSDateComponentUndefined let range = when["range"] ?? 0 let prebook = notify["prebook"] as? Int ?? 0 let iterations = prebook < 0 ? 1 : prebook let randomize = notify["randomize"] as? Bool ?? false var date = NSDate().dateByAddingTimeInterval(NSTimeInterval(range/2)*60) for i in 0..<iterations { if let futureDate = calendar?.nextDateAfterDate(date, matchingComponents: relative, options: .MatchNextTime) { let localNote = UILocalNotification() localNote.alertAction = action localNote.alertBody = what[randomize ? Int(arc4random_uniform(UInt32(what.count))) : i % what.count] localNote.userInfo = ["tag" : tag] localNote.soundName = "drink.caf" let offset = (NSTimeInterval(arc4random_uniform(UInt32(range))) - (NSTimeInterval(range/2))) * 60 localNote.fireDate = futureDate.dateByAddingTimeInterval(offset) localNote.timeZone = NSTimeZone.defaultTimeZone() if prebook < 0 { localNote.repeatInterval = .WeekOfYear localNote.repeatCalendar = calendar } application.scheduleLocalNotification(localNote) date = futureDate } } } } } func scheduleReminders() { let application = UIApplication.sharedApplication() let interval = NSUserDefaults.standardUserDefaults().integerForKey(PartyUpPreferences.RemindersInterval) if let notes = application.scheduledLocalNotifications { for note in notes { if note.userInfo?["reminder"] != nil { application.cancelLocalNotification(note) } } } if NSUserDefaults.standardUserDefaults().boolForKey(PartyUpPreferences.RemindersInterface) { var minutes = [Int]() if interval > 0 { minutes.append(0) } if interval == 30 { minutes.append(30) } let now = NSDate() let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let relative = NSDateComponents() relative.calendar = calendar relative.timeZone = NSTimeZone.defaultTimeZone() for minute in minutes { relative.minute = minute let future = calendar.nextDateAfterDate(now, matchingComponents: relative, options: .MatchNextTime) let localNote = UILocalNotification() localNote.alertAction = NSLocalizedString("submit a video", comment: "Reminders alert action") localNote.alertBody = NSLocalizedString("Time to record a party video!", comment: "Reminders alert body") localNote.userInfo = ["reminder" : interval] localNote.soundName = "drink.caf" localNote.fireDate = future localNote.repeatInterval = .Hour localNote.repeatCalendar = calendar localNote.timeZone = NSTimeZone.defaultTimeZone() application.scheduleLocalNotification(localNote) } } } }
mit
0b8a65f5af900e76dee66fbaf621c5ff
42.033613
192
0.710115
5.018128
false
false
false
false
kykim/SwiftCheck
Sources/Modifiers.swift
1
19044
// // Modifiers.swift // SwiftCheck // // Created by Robert Widmann on 1/29/15. // Copyright (c) 2015 CodaFi. All rights reserved. // // MARK: - Modifier Types /// A Modifier Type is a type that wraps another to provide special semantics or /// simply to generate values of an underlying type that would be unusually /// difficult to express given the limitations of Swift's type system. /// /// For an example of the former, take the `Blind` modifier. Because /// SwiftCheck's counterexamples come from a description a particular object /// provides for itself, there are many cases where console output can become /// unbearably long, or just simply isn't useful to your test suite. By /// wrapping that type in `Blind` SwiftCheck ignores whatever description the /// property provides and just print "(*)". /// /// property("All blind variables print '(*)'") <- forAll { (x : Blind<Int>) in /// return x.description == "(*)" /// } /// /// For an example of the latter see the `ArrowOf` modifier. Because Swift's /// type system treats arrows (`->`) as an opaque entity that you can't interact /// with or extend, SwiftCheck provides `ArrowOf` to enable the generation of /// functions between 2 types. That's right, we can generate arbitrary /// functions! /// /// property("map accepts SwiftCheck arrows") <- forAll { (xs : [Int]) in /// return forAll { (f : ArrowOf<Int, Int>) in /// /// Just to prove it really is a function (that is, every input /// /// always maps to the same output), and not just a trick, we /// /// map twice and should get equal arrays. /// return xs.map(f.getArrow) == xs.map(f.getArrow) /// } /// } /// /// Finally, modifiers nest to allow the generation of intricate structures that /// would not otherwise be possible due to the limitations above. For example, /// to generate an Array of Arrays of Dictionaries of Integers and Strings (a /// type that normally looks like `Array<Array<Dictionary<String, Int>>>`), /// would look like this: /// /// property("Generating monstrous data types is possible") <- forAll { (xs : ArrayOf<ArrayOf<DictionaryOf<String, Int>>>) in /// /// We're gonna need a bigger boat. /// } /// For types that either do not have a `CustomStringConvertible` instance or /// that wish to have no description to print, Blind will create a default /// description for them. public struct Blind<A : Arbitrary> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying value. public let getBlind : A public init(_ blind : A) { self.getBlind = blind } /// A default short description for the blind value. /// /// By default, the value of this property is `(*)`. public var description : String { return "(*)" } /// Returns a generator of `Blind` values. public static var arbitrary : Gen<Blind<A>> { return A.arbitrary.map(Blind.init) } /// The default shrinking function for `Blind` values. public static func shrink(_ bl : Blind<A>) -> [Blind<A>] { return A.shrink(bl.getBlind).map(Blind.init) } } extension Blind : CoArbitrary { // Take the lazy way out. public static func coarbitrary<C>(_ x : Blind) -> ((Gen<C>) -> Gen<C>) { return coarbitraryPrintable(x) } } /// Guarantees test cases for its underlying type will not be shrunk. public struct Static<A : Arbitrary> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying value. public let getStatic : A public init(_ fixed : A) { self.getStatic = fixed } /// A textual representation of `self`. public var description : String { return "Static( \(self.getStatic) )" } /// Returns a generator of `Static` values. public static var arbitrary : Gen<Static<A>> { return A.arbitrary.map(Static.init) } } extension Static : CoArbitrary { // Take the lazy way out. public static func coarbitrary<C>(_ x : Static) -> ((Gen<C>) -> Gen<C>) { return coarbitraryPrintable(x) } } /// Generates an array of arbitrary values of type A. public struct ArrayOf<A : Arbitrary> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying array of values. public let getArray : [A] /// Retrieves the underlying array of values as a contiguous array. public var getContiguousArray : ContiguousArray<A> { return ContiguousArray(self.getArray) } public init(_ array : [A]) { self.getArray = array } /// A textual representation of `self`. public var description : String { return "\(self.getArray)" } /// Returns a generator of `ArrayOf` values. public static var arbitrary : Gen<ArrayOf<A>> { return Array<A>.arbitrary.map(ArrayOf.init) } /// The default shrinking function for an `ArrayOf` values. public static func shrink(_ bl : ArrayOf<A>) -> [ArrayOf<A>] { return Array<A>.shrink(bl.getArray).map(ArrayOf.init) } } extension ArrayOf : CoArbitrary { public static func coarbitrary<C>(_ x : ArrayOf) -> ((Gen<C>) -> Gen<C>) { let a = x.getArray if a.isEmpty { return { $0.variant(0) } } return comp({ $0.variant(1) }, ArrayOf.coarbitrary(ArrayOf([A](a[1..<a.endIndex])))) } } /// Generates a sorted array of arbitrary values of type A. public struct OrderedArrayOf<A : Arbitrary & Comparable> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying sorted array of values. public let getOrderedArray : [A] /// Retrieves the underlying sorted array of values as a contiguous /// array. public var getContiguousArray : ContiguousArray<A> { return ContiguousArray(self.getOrderedArray) } public init(_ array : [A]) { self.getOrderedArray = array.sorted() } /// A textual representation of `self`. public var description : String { return "\(self.getOrderedArray)" } /// Returns a generator for an `OrderedArrayOf` values. public static var arbitrary : Gen<OrderedArrayOf<A>> { return Array<A>.arbitrary.map(OrderedArrayOf.init) } /// The default shrinking function for an `OrderedArrayOf` values. public static func shrink(_ bl : OrderedArrayOf<A>) -> [OrderedArrayOf<A>] { return Array<A>.shrink(bl.getOrderedArray).filter({ $0.sorted() == $0 }).map(OrderedArrayOf.init) } } /// Generates an dictionary of arbitrary keys and values. public struct DictionaryOf<K : Hashable & Arbitrary, V : Arbitrary> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying dictionary of values. public let getDictionary : Dictionary<K, V> public init(_ dict : Dictionary<K, V>) { self.getDictionary = dict } /// A textual representation of `self`. public var description : String { return "\(self.getDictionary)" } /// Returns a generator for a `DictionaryOf` values. public static var arbitrary : Gen<DictionaryOf<K, V>> { return Dictionary<K, V>.arbitrary.map(DictionaryOf.init) } /// The default shrinking function for a `DictionaryOf` values. public static func shrink(_ d : DictionaryOf<K, V>) -> [DictionaryOf<K, V>] { return Dictionary.shrink(d.getDictionary).map(DictionaryOf.init) } } extension DictionaryOf : CoArbitrary { public static func coarbitrary<C>(_ x : DictionaryOf) -> ((Gen<C>) -> Gen<C>) { return Dictionary.coarbitrary(x.getDictionary) } } /// Generates an Optional of arbitrary values of type A. public struct OptionalOf<A : Arbitrary> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying optional value. public let getOptional : A? public init(_ opt : A?) { self.getOptional = opt } /// A textual representation of `self`. public var description : String { return "\(self.getOptional)" } /// Returns a generator for `OptionalOf` values. public static var arbitrary : Gen<OptionalOf<A>> { return Optional<A>.arbitrary.map(OptionalOf.init) } /// The default shrinking function for `OptionalOf` values. public static func shrink(_ bl : OptionalOf<A>) -> [OptionalOf<A>] { return Optional<A>.shrink(bl.getOptional).map(OptionalOf.init) } } extension OptionalOf : CoArbitrary { public static func coarbitrary<C>(_ x : OptionalOf) -> ((Gen<C>) -> Gen<C>) { if let _ = x.getOptional { return { $0.variant(0) } } return { $0.variant(1) } } } /// Generates a set of arbitrary values of type A. public struct SetOf<A : Hashable & Arbitrary> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying set of values. public let getSet : Set<A> public init(_ set : Set<A>) { self.getSet = set } /// A textual representation of `self`. public var description : String { return "\(self.getSet)" } /// Returns a generator for a `SetOf` values. public static var arbitrary : Gen<SetOf<A>> { return Gen.sized { n in return Gen<Int>.choose((0, n)).flatMap { k in if k == 0 { return Gen.pure(SetOf(Set([]))) } return sequence(Array((0...k)).map { _ in A.arbitrary }).map(comp(SetOf.init, Set.init)) } } } /// The default shrinking function for a `SetOf` values. public static func shrink(_ s : SetOf<A>) -> [SetOf<A>] { return ArrayOf.shrink(ArrayOf([A](s.getSet))).map({ SetOf(Set($0.getArray)) }) } } extension SetOf : CoArbitrary { public static func coarbitrary<C>(_ x : SetOf) -> ((Gen<C>) -> Gen<C>) { if x.getSet.isEmpty { return { $0.variant(0) } } return { $0.variant(1) } } } /// Generates pointers of varying size of random values of type T. public struct PointerOf<T : Arbitrary> : Arbitrary, CustomStringConvertible { fileprivate let _impl : PointerOfImpl<T> /// Retrieves the underlying pointer value. public var getPointer : UnsafePointer<T> { return UnsafePointer(self._impl.ptr!) } public var size : Int { return self._impl.size } /// A textual representation of `self`. public var description : String { return self._impl.description } /// Returns a generator for a `PointerOf` values. public static var arbitrary : Gen<PointerOf<T>> { return PointerOfImpl.arbitrary.map(PointerOf.init) } } /// Generates a Swift function from T to U. public struct ArrowOf<T : Hashable & CoArbitrary, U : Arbitrary> : Arbitrary, CustomStringConvertible { fileprivate let _impl : ArrowOfImpl<T, U> /// Retrieves the underlying function value, `T -> U`. public var getArrow : (T) -> U { return self._impl.arr } /// A textual representation of `self`. public var description : String { return self._impl.description } /// Returns a generator for an `ArrowOf` function values. public static var arbitrary : Gen<ArrowOf<T, U>> { return ArrowOfImpl<T, U>.arbitrary.map(ArrowOf.init) } } extension ArrowOf : CustomReflectable { public var customMirror : Mirror { return Mirror(self, children: [ "types": "\(T.self) -> \(U.self)", "currentMap": self._impl.table, ]) } } /// Generates two isomorphic Swift functions from `T` to `U` and back again. public struct IsoOf<T : Hashable & CoArbitrary & Arbitrary, U : Equatable & CoArbitrary & Arbitrary> : Arbitrary, CustomStringConvertible { fileprivate let _impl : IsoOfImpl<T, U> /// Retrieves the underlying embedding function, `T -> U`. public var getTo : (T) -> U { return self._impl.embed } /// Retrieves the underlying projecting function, `U -> T`. public var getFrom : (U) -> T { return self._impl.project } /// A textual representation of `self`. public var description : String { return self._impl.description } /// Returns a generator for an `IsoOf` function values. public static var arbitrary : Gen<IsoOf<T, U>> { return IsoOfImpl<T, U>.arbitrary.map(IsoOf.init) } } extension IsoOf : CustomReflectable { public var customMirror : Mirror { return Mirror(self, children: [ "embed": "\(T.self) -> \(U.self)", "project": "\(U.self) -> \(T.self)", "currentMap": self._impl.table, ]) } } /// By default, SwiftCheck generates values drawn from a small range. `Large` /// gives you values drawn from the entire range instead. public struct Large<A : RandomType & LatticeType & Integer> : Arbitrary { /// Retrieves the underlying large value. public let getLarge : A public init(_ lrg : A) { self.getLarge = lrg } /// A textual representation of `self`. public var description : String { return "Large( \(self.getLarge) )" } /// Returns a generator of `Large` values. public static var arbitrary : Gen<Large<A>> { return Gen<A>.choose((A.min, A.max)).map(Large.init) } /// The default shrinking function for `Large` values. public static func shrink(_ bl : Large<A>) -> [Large<A>] { return bl.getLarge.shrinkIntegral.map(Large.init) } } /// Guarantees that every generated integer is greater than 0. public struct Positive<A : Arbitrary & SignedNumber> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying positive value. public let getPositive : A public init(_ pos : A) { self.getPositive = pos } /// A textual representation of `self`. public var description : String { return "Positive( \(self.getPositive) )" } /// Returns a generator of `Positive` values. public static var arbitrary : Gen<Positive<A>> { return A.arbitrary.map(comp(Positive.init, abs)).suchThat { $0.getPositive > 0 } } /// The default shrinking function for `Positive` values. public static func shrink(_ bl : Positive<A>) -> [Positive<A>] { return A.shrink(bl.getPositive).filter({ $0 > 0 }).map(Positive.init) } } extension Positive : CoArbitrary { // Take the lazy way out. public static func coarbitrary<C>(_ x : Positive) -> ((Gen<C>) -> Gen<C>) { return coarbitraryPrintable(x) } } /// Guarantees that every generated integer is never 0. public struct NonZero<A : Arbitrary & Integer> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying non-zero value. public let getNonZero : A public init(_ non : A) { self.getNonZero = non } /// A textual representation of `self`. public var description : String { return "NonZero( \(self.getNonZero) )" } /// Returns a generator of `NonZero` values. public static var arbitrary : Gen<NonZero<A>> { return A.arbitrary.suchThat({ $0 != 0 }).map(NonZero.init) } /// The default shrinking function for `NonZero` values. public static func shrink(_ bl : NonZero<A>) -> [NonZero<A>] { return A.shrink(bl.getNonZero).filter({ $0 != 0 }).map(NonZero.init) } } extension NonZero : CoArbitrary { public static func coarbitrary<C>(_ x : NonZero) -> ((Gen<C>) -> Gen<C>) { return x.getNonZero.coarbitraryIntegral() } } /// Guarantees that every generated integer is greater than or equal to 0. public struct NonNegative<A : Arbitrary & Integer> : Arbitrary, CustomStringConvertible { /// Retrieves the underlying non-negative value. public let getNonNegative : A public init(_ non : A) { self.getNonNegative = non } /// A textual representation of `self`. public var description : String { return "NonNegative( \(self.getNonNegative) )" } /// Returns a generator of `NonNegative` values. public static var arbitrary : Gen<NonNegative<A>> { return A.arbitrary.suchThat({ $0 >= 0 }).map(NonNegative.init) } /// The default shrinking function for `NonNegative` values. public static func shrink(_ bl : NonNegative<A>) -> [NonNegative<A>] { return A.shrink(bl.getNonNegative).filter({ $0 >= 0 }).map(NonNegative.init) } } extension NonNegative : CoArbitrary { public static func coarbitrary<C>(_ x : NonNegative) -> ((Gen<C>) -> Gen<C>) { return x.getNonNegative.coarbitraryIntegral() } } // MARK: - Implementation Details Follow private func undefined<A>() -> A { fatalError("") } fileprivate final class ArrowOfImpl<T : Hashable & CoArbitrary, U : Arbitrary> : Arbitrary, CustomStringConvertible { fileprivate var table : Dictionary<T, U> fileprivate var arr : (T) -> U init (_ table : Dictionary<T, U>, _ arr : @escaping (T) -> U) { self.table = table self.arr = arr } convenience init(_ arr : @escaping (T) -> U) { self.init(Dictionary(), { (_ : T) -> U in return undefined() }) self.arr = { [unowned self] x in if let v = self.table[x] { return v } let y = arr(x) self.table[x] = y return y } } var description : String { return "\(T.self) -> \(U.self)" } static var arbitrary : Gen<ArrowOfImpl<T, U>> { return promote({ a in return T.coarbitrary(a)(U.arbitrary) }).map(ArrowOfImpl.init) } static func shrink(_ f : ArrowOfImpl<T, U>) -> [ArrowOfImpl<T, U>] { return f.table.flatMap { (x, y) in return U.shrink(y).map({ (y2 : U) -> ArrowOfImpl<T, U> in return ArrowOfImpl<T, U>({ (z : T) -> U in if x == z { return y2 } return f.arr(z) }) }) } } } fileprivate final class IsoOfImpl<T : Hashable & CoArbitrary & Arbitrary, U : Equatable & CoArbitrary & Arbitrary> : Arbitrary, CustomStringConvertible { fileprivate var table : Dictionary<T, U> fileprivate var embed : (T) -> U fileprivate var project : (U) -> T init (_ table : Dictionary<T, U>, _ embed : @escaping (T) -> U, _ project : @escaping (U) -> T) { self.table = table self.embed = embed self.project = project } convenience init(_ embed : @escaping (T) -> U, _ project : @escaping (U) -> T) { self.init(Dictionary(), { (_ : T) -> U in return undefined() }, { (_ : U) -> T in return undefined() }) self.embed = { [unowned self] t in if let v = self.table[t] { return v } let y = embed(t) self.table[t] = y return y } self.project = { [unowned self] u in let ts = self.table.filter { $1 == u }.map { $0.0 } if let k = ts.first, let _ = self.table[k] { return k } let y = project(u) self.table[y] = u return y } } var description : String { return "IsoOf<\(T.self) -> \(U.self), \(U.self) -> \(T.self)>" } static var arbitrary : Gen<IsoOfImpl<T, U>> { return Gen<((T) -> U, (U) -> T)>.zip(promote({ a in return T.coarbitrary(a)(U.arbitrary) }), promote({ a in return U.coarbitrary(a)(T.arbitrary) })).map(IsoOfImpl.init) } static func shrink(_ f : IsoOfImpl<T, U>) -> [IsoOfImpl<T, U>] { return f.table.flatMap { (x, y) in return Zip2Sequence(_sequence1: T.shrink(x), _sequence2: U.shrink(y)).map({ (y1 , y2) -> IsoOfImpl<T, U> in return IsoOfImpl<T, U>({ (z : T) -> U in if x == z { return y2 } return f.embed(z) }, { (z : U) -> T in if y == z { return y1 } return f.project(z) }) }) } } } private final class PointerOfImpl<T : Arbitrary> : Arbitrary { var ptr : UnsafeMutablePointer<T>? let size : Int var description : String { return "\(self.ptr)" } init(_ ptr : UnsafeMutablePointer<T>, _ size : Int) { self.ptr = ptr self.size = size } deinit { if self.size > 0 && self.ptr != nil { self.ptr?.deallocate(capacity: self.size) self.ptr = nil } } static var arbitrary : Gen<PointerOfImpl<T>> { return Gen.sized { n in if n <= 0 { let size = 1 return Gen.pure(PointerOfImpl(UnsafeMutablePointer<T>.allocate(capacity: size), size)) } let pt = UnsafeMutablePointer<T>.allocate(capacity: n) let gt = sequence(Array((0..<n)).map { _ in T.arbitrary }).map(pt.initialize) return gt.map { _ in PointerOfImpl(pt, n) } } } }
mit
2d46206224bc00e7f5544e680f0a173d
28.253456
153
0.666509
3.349279
false
false
false
false
anthonypuppo/GDAXSwift
GDAXSwift/Classes/GDAXTime.swift
1
800
// // GDAXTime.swift // GDAXSwift // // Created by Anthony on 6/4/17. // Copyright © 2017 Anthony Puppo. All rights reserved. // public struct GDAXTime: JSONInitializable { public let iso: Date public let epoch: Double internal init(json: Any) throws { var jsonData: Data? if let json = json as? Data { jsonData = json } else { jsonData = try JSONSerialization.data(withJSONObject: json, options: []) } guard let json = jsonData?.json else { throw GDAXError.invalidResponseData } guard let iso = (json["iso"] as? String)?.dateFromISO8601 else { throw GDAXError.responseParsingFailure("iso") } guard let epoch = json["epoch"] as? Double else { throw GDAXError.responseParsingFailure("epoch") } self.iso = iso self.epoch = epoch } }
mit
ae0ae723717dbc673d73da0020947f22
19.487179
75
0.669587
3.519824
false
false
false
false
StreamOneNL/iOS-SDK-ObjC
StreamOneSDK/SessionRequest.swift
1
2582
// // SessionRequest.swift // StreamOneSDK // // Created by Nicky Gerritsen on 25-07-15. // Copyright © 2015 StreamOne. All rights reserved. // import Foundation import Alamofire /** Arequest to the StreamOne API with an active session Note that it is only possible to use sessions when application authentication is enabled in Config. Trying to use sessions with user authentication will always result in an authentication error. Refer to the StreamOne Platform Documentation on Sessions for more information on using sessions. */ public class SessionRequest : Request { /** The session store containing the required session information */ public let sessionStore: SessionStore /** Initialize a request for a given command and action and set the session - Parameter command: The command to use - Parameter action: The action to use - Parameter confi: The configuration to use */ public init?(command: String, action: String, config: Config, sessionStore: SessionStore) { self.sessionStore = sessionStore super.init(command: command, action: action, config: config) switch config.authenticationType { case .User: return nil default: break } } /** This function will return the key used for signing the request - Returns: The key used for signing */ override internal func signingKey() -> String { return "\(super.signingKey())\(sessionStore.getKey(nil))" } /** Retrieve the parameters used for signing - Returns: A dictionary containing the parameters needed for signing */ override internal func parametersForSigning() -> [String : String] { var parameters = super.parametersForSigning() parameters["session"] = sessionStore.getId(nil) return parameters } /** Process the result from a request - Parameter result: The result from a HTTP request - Parameter callback: The callback to call when processing the result is done */ override internal func processResult(result: Result<AnyObject, NSError>, callback: (response: Response) -> Void) { super.processResult(result) { response in if let header = response.header, let sessionTimeout = header.allFields["sessiontimeout"] as? Double { self.sessionStore.setTimeout(sessionTimeout, error: nil) } callback(response: response) } } }
mit
dd6a8f4e07af4f7aa27eb33f0bb497d7
30.487805
118
0.657497
5.031189
false
true
false
false
shahmishal/swift
test/SILGen/vtable_thunks.swift
2
13437
// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s protocol AddrOnly {} func callMethodsOnD<U>(d: D, b: B, a: AddrOnly, u: U, i: Int) { _ = d.iuo(x: b, y: b, z: b) _ = d.f(x: b, y: b) _ = d.f2(x: b, y: b) _ = d.f3(x: b, y: b) _ = d.f4(x: b, y: b) _ = d.g(x: a, y: a) _ = d.g2(x: a, y: a) _ = d.g3(x: a, y: a) _ = d.g4(x: a, y: a) _ = d.h(x: u, y: u) _ = d.h2(x: u, y: u) _ = d.h3(x: u, y: u) _ = d.h4(x: u, y: u) _ = d.i(x: i, y: i) _ = d.i2(x: i, y: i) _ = d.i3(x: i, y: i) _ = d.i4(x: i, y: i) } func callMethodsOnF<U>(d: F, b: B, a: AddrOnly, u: U, i: Int) { _ = d.iuo(x: b, y: b, z: b) _ = d.f(x: b, y: b) _ = d.f2(x: b, y: b) _ = d.f3(x: b, y: b) _ = d.f4(x: b, y: b) _ = d.g(x: a, y: a) _ = d.g2(x: a, y: a) _ = d.g3(x: a, y: a) _ = d.g4(x: a, y: a) _ = d.h(x: u, y: u) _ = d.h2(x: u, y: u) _ = d.h3(x: u, y: u) _ = d.h4(x: u, y: u) _ = d.i(x: i, y: i) _ = d.i2(x: i, y: i) _ = d.i3(x: i, y: i) _ = d.i4(x: i, y: i) } @objc class B { // We only allow B! -> B overrides for @objc methods. // The IUO force-unwrap requires a thunk. @objc func iuo(x: B, y: B!, z: B) -> B? {} // f* don't require thunks, since the parameters and returns are object // references. func f(x: B, y: B) -> B? {} func f2(x: B, y: B) -> B? {} func f3(x: B, y: B) -> B {} func f4(x: B, y: B) -> B {} // Thunking monomorphic address-only params and returns func g(x: AddrOnly, y: AddrOnly) -> AddrOnly? {} func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly? {} func g3(x: AddrOnly, y: AddrOnly) -> AddrOnly {} func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} // Thunking polymorphic address-only params and returns func h<T>(x: T, y: T) -> T? {} func h2<T>(x: T, y: T) -> T? {} func h3<T>(x: T, y: T) -> T {} func h4<T>(x: T, y: T) -> T {} // Thunking value params and returns func i(x: Int, y: Int) -> Int? {} func i2(x: Int, y: Int) -> Int? {} func i3(x: Int, y: Int) -> Int {} func i4(x: Int, y: Int) -> Int {} // Note: i3, i4 are implicitly @objc } class D: B { override func iuo(x: B?, y: B, z: B) -> B {} override func f(x: B?, y: B) -> B {} override func f2(x: B, y: B) -> B {} override func f3(x: B?, y: B) -> B {} override func f4(x: B, y: B) -> B {} override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func h<U>(x: U?, y: U) -> U {} override func h2<U>(x: U, y: U) -> U {} override func h3<U>(x: U?, y: U) -> U {} override func h4<U>(x: U, y: U) -> U {} override func i(x: Int?, y: Int) -> Int {} override func i2(x: Int, y: Int) -> Int {} // Int? cannot be represented in ObjC so the override has to be // explicitly @nonobjc @nonobjc override func i3(x: Int?, y: Int) -> Int {} override func i4(x: Int, y: Int) -> Int {} } // Inherits the thunked impls from D class E: D { } // Overrides w/ its own thunked impls class F: D { override func f(x: B?, y: B) -> B {} override func f2(x: B, y: B) -> B {} override func f3(x: B?, y: B) -> B {} override func f4(x: B, y: B) -> B {} override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func h<U>(x: U?, y: U) -> U {} override func h2<U>(x: U, y: U) -> U {} override func h3<U>(x: U?, y: U) -> U {} override func h4<U>(x: U, y: U) -> U {} override func i(x: Int?, y: Int) -> Int {} override func i2(x: Int, y: Int) -> Int {} // Int? cannot be represented in ObjC so the override has to be // explicitly @nonobjc @nonobjc override func i3(x: Int?, y: Int) -> Int {} override func i4(x: Int, y: Int) -> Int {} } protocol Proto {} class G { func foo<T: Proto>(arg: T) {} } class H: G { override func foo<T>(arg: T) {} } // This test is incorrect in semantic SIL today. But it will be fixed in // forthcoming commits. // // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks1DC3iuo{{[_0-9a-zA-Z]*}}FTV // CHECK: bb0([[X:%.*]] : @guaranteed $B, [[Y:%.*]] : @guaranteed $Optional<B>, [[Z:%.*]] : @guaranteed $B, [[W:%.*]] : @guaranteed $D): // CHECK: [[WRAP_X:%.*]] = enum $Optional<B>, #Optional.some!enumelt.1, [[X]] : $B // CHECK: [[Y_COPY:%.*]] = copy_value [[Y]] // CHECK: switch_enum [[Y_COPY]] : $Optional<B>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[NONE_BB]]: // CHECK: [[DIAGNOSE_UNREACHABLE_FUNC:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{.*}} // CHECK: apply [[DIAGNOSE_UNREACHABLE_FUNC]] // CHECK: unreachable // CHECK: [[SOME_BB]]([[UNWRAP_Y:%.*]] : @owned $B): // CHECK: [[BORROWED_UNWRAP_Y:%.*]] = begin_borrow [[UNWRAP_Y]] // CHECK: [[THUNK_FUNC:%.*]] = function_ref @$s13vtable_thunks1DC3iuo{{.*}} // CHECK: [[RES:%.*]] = apply [[THUNK_FUNC]]([[WRAP_X]], [[BORROWED_UNWRAP_Y]], [[Z]], [[W]]) // CHECK: [[WRAP_RES:%.*]] = enum $Optional<B>, {{.*}} [[RES]] // CHECK: return [[WRAP_RES]] // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks1DC1g{{[_0-9a-zA-Z]*}}FTV // TODO: extra copies here // CHECK: [[WRAPPED_X_ADDR:%.*]] = init_enum_data_addr [[WRAP_X_ADDR:%.*]] : // CHECK: copy_addr [take] {{%.*}} to [initialization] [[WRAPPED_X_ADDR]] // CHECK: inject_enum_addr [[WRAP_X_ADDR]] // CHECK: [[RES_ADDR:%.*]] = alloc_stack // CHECK: apply {{%.*}}([[RES_ADDR]], [[WRAP_X_ADDR]], %2, %3) // CHECK: [[DEST_ADDR:%.*]] = init_enum_data_addr %0 // CHECK: copy_addr [take] [[RES_ADDR]] to [initialization] [[DEST_ADDR]] // CHECK: inject_enum_addr %0 class ThrowVariance { func mightThrow() throws {} } class NoThrowVariance: ThrowVariance { override func mightThrow() {} } // rdar://problem/20657811 class X<T: B> { func foo(x: T) { } } class Y: X<D> { override func foo(x: D) { } } // rdar://problem/21154055 // Ensure reabstraction happens when necessary to get a value in or out of an // optional. class Foo { func foo(x: @escaping (Int) -> Int) -> ((Int) -> Int)? {} } class Bar: Foo { override func foo(x: ((Int) -> Int)?) -> (Int) -> Int {} } // rdar://problem/21364764 // Ensure we can override an optional with an IUO or vice-versa. struct S {} class Aap { func cat(b: B?) -> B? {} func dog(b: B!) -> B! {} func catFast(s: S?) -> S? {} func dogFast(s: S!) -> S! {} func flip() -> (() -> S?) {} func map() -> (S) -> () -> Aap? {} } class Noot : Aap { override func cat(b: B!) -> B! {} override func dog(b: B?) -> B? {} override func catFast(s: S!) -> S! {} override func dogFast(s: S?) -> S? {} override func flip() -> (() -> S) {} override func map() -> (S?) -> () -> Noot {} } // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks3BarC3foo{{[_0-9a-zA-Z]*}}FTV : $@convention(method) (@guaranteed @callee_guaranteed (Int) -> Int, @guaranteed Bar) -> @owned Optional<@callee_guaranteed (Int) -> Int> // CHECK: [[IMPL:%.*]] = function_ref @$s13vtable_thunks3BarC3foo{{[_0-9a-zA-Z]*}}F // CHECK: apply [[IMPL]] // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks4NootC4flip{{[_0-9a-zA-Z]*}}FTV // CHECK: [[IMPL:%.*]] = function_ref @$s13vtable_thunks4NootC4flip{{[_0-9a-zA-Z]*}}F // CHECK: [[INNER:%.*]] = apply %1(%0) // CHECK: [[THUNK:%.*]] = function_ref @$s13vtable_thunks1SVIegd_ACSgIegd_TR // CHECK: [[OUTER:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[INNER]]) // CHECK: return [[OUTER]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s13vtable_thunks1SVIegd_ACSgIegd_TR // CHECK: [[INNER:%.*]] = apply %0() // CHECK: [[OUTER:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, [[INNER]] : $S // CHECK: return [[OUTER]] : $Optional<S> // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks4NootC3map{{[_0-9a-zA-Z]*}}FTV // CHECK: [[IMPL:%.*]] = function_ref @$s13vtable_thunks4NootC3map{{[_0-9a-zA-Z]*}}F // CHECK: [[INNER:%.*]] = apply %1(%0) // CHECK: [[THUNK:%.*]] = function_ref @$s13vtable_thunks1SVSgAA4NootCIego_Iegyo_AcA3AapCSgIego_Iegyo_TR // CHECK: [[OUTER:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[INNER]]) // CHECK: return [[OUTER]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s13vtable_thunks1SVSgAA4NootCIego_Iegyo_AcA3AapCSgIego_Iegyo_TR // CHECK: [[ARG:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, %0 // CHECK: [[INNER:%.*]] = apply %1([[ARG]]) // CHECK: [[OUTER:%.*]] = convert_function [[INNER]] : $@callee_guaranteed () -> @owned Noot to $@callee_guaranteed () -> @owned Optional<Aap> // CHECK: return [[OUTER]] // CHECK-LABEL: sil_vtable D { // CHECK: #B.iuo!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.g!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.h!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.i!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable E { // CHECK: #B.iuo!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.g!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.h!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.i!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable F { // CHECK: #B.iuo!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.g!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.h!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.i!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable H { // CHECK: #G.foo!1: <T where T : Proto> (G) -> (T) -> () : @$s13vtable_thunks1H{{[A-Z0-9a-z_]*}}FTV [override] // CHECK: #H.foo!1: <T> (H) -> (T) -> () : @$s13vtable_thunks1H{{[A-Z0-9a-z_]*}}tlF // CHECK-LABEL: sil_vtable NoThrowVariance { // CHECK: #ThrowVariance.mightThrow!1: {{.*}} : @$s13vtable_thunks{{[A-Z0-9a-z_]*}}F
apache-2.0
4ca079e41aa19dc7398df28a5eb6f914
40.600619
220
0.520578
2.506903
false
false
false
false
ngageoint/mage-ios
MageTests/Observation/Fields/CheckboxFieldViewTests.swift
1
9762
// // EditCheckboxFieldView.swift // MAGETests // // Created by Daniel Barela on 5/28/20. // Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import Quick import Nimble //import Nimble_Snapshots @testable import MAGE class CheckboxFieldViewTests: KIFSpec { override func spec() { describe("CheckboxFieldView") { var controller: UIViewController! var window: UIWindow!; var checkboxFieldView: CheckboxFieldView! var view: UIView! var field: [String: Any]! beforeEach { controller = UIViewController(); view = UIView(forAutoLayout: ()); view.autoSetDimension(.width, toSize: 300); window = TestHelpers.getKeyWindowVisible(); window.rootViewController = controller; field = [ "title": "Field Title", "name": "field8", "id": 8 ]; // Nimble_Snapshots.setNimbleTolerance(0.0); // Nimble_Snapshots.recordAllSnapshots() } afterEach { controller.dismiss(animated: false, completion: nil); window.rootViewController = nil; controller = nil; } it("non edit mode") { checkboxFieldView = CheckboxFieldView(field: field, editMode: false, value: true); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); tester().waitForView(withAccessibilityLabel: field["name"] as? String); expect((viewTester().usingLabel(field["name"] as? String)?.view as! UISwitch).isUserInteractionEnabled).to(beFalse()); expect((viewTester().usingLabel(field["name"] as? String)?.view as! UISwitch).isEnabled).to(beTrue()); // expect(view).to(haveValidSnapshot()); } it("no initial value") { checkboxFieldView = CheckboxFieldView(field: field); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); // expect(view).to(haveValidSnapshot()); } it("initial value true") { checkboxFieldView = CheckboxFieldView(field: field, value: true); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); // expect(view).to(haveValidSnapshot()); } it("initial value false") { checkboxFieldView = CheckboxFieldView(field: field, value: false); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); // expect(view).to(haveValidSnapshot()); } it("set value later") { checkboxFieldView = CheckboxFieldView(field: field); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); checkboxFieldView.setValue(true); // expect(view).to(haveValidSnapshot()); } it("set value simulated touch") { checkboxFieldView = CheckboxFieldView(field: field); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); tester().waitForView(withAccessibilityLabel: field["name"] as? String); tester().setOn(true, forSwitchWithAccessibilityLabel: field["name"] as? String); // expect(view).to(haveValidSnapshot()); } it("required") { field["required"] = true; checkboxFieldView = CheckboxFieldView(field: field); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); checkboxFieldView.setValue(true); // expect(view).to(haveValidSnapshot()); } it("set valid false") { checkboxFieldView = CheckboxFieldView(field: field); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); checkboxFieldView.setValid(false); // expect(view).to(haveValidSnapshot()); } it("set valid true after being invalid") { checkboxFieldView = CheckboxFieldView(field: field); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); checkboxFieldView.setValid(false); checkboxFieldView.setValid(true); // expect(view).to(haveValidSnapshot()); } it("required field is invalid if false") { field[FieldKey.required.key] = true; checkboxFieldView = CheckboxFieldView(field: field); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); expect(checkboxFieldView.isEmpty()) == true; expect(checkboxFieldView.isValid(enforceRequired: true)) == false; checkboxFieldView.setValid(checkboxFieldView.isValid()); // expect(view).to(haveValidSnapshot()); } it("required field is valid if true") { field[FieldKey.required.key] = true; checkboxFieldView = CheckboxFieldView(field: field); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); checkboxFieldView.setValue(true); expect(checkboxFieldView.isEmpty()) == false; expect(checkboxFieldView.isValid(enforceRequired: true)) == true; checkboxFieldView.setValid(checkboxFieldView.isValid()); // expect(view).to(haveValidSnapshot()); } it("test delegate false value") { let delegate = MockFieldDelegate(); checkboxFieldView = CheckboxFieldView(field: field, delegate: delegate); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); checkboxFieldView.switchValueChanged(theSwitch: checkboxFieldView.checkboxSwitch); expect(delegate.fieldChangedCalled) == true; expect(delegate.newValue as? Bool) == false; } it("test delegate true value") { let delegate = MockFieldDelegate(); checkboxFieldView = CheckboxFieldView(field: field, delegate: delegate); checkboxFieldView.applyTheme(withScheme: MAGEScheme.scheme()); view.addSubview(checkboxFieldView) checkboxFieldView.autoPinEdgesToSuperviewEdges(); controller.view.addSubview(view); checkboxFieldView.setValue(true); checkboxFieldView.switchValueChanged(theSwitch: checkboxFieldView.checkboxSwitch); expect(delegate.fieldChangedCalled) == true; expect(delegate.newValue as? Bool) == true; } } } }
apache-2.0
1f89165472ec4e75e30da38525e4e35b
41.073276
134
0.538572
6.455688
false
false
false
false
crazypoo/PTools
Pods/JXSegmentedView/Sources/Common/JXSegmentedListContainerView.swift
1
21966
// // JXSegmentedListContainerView.swift // JXSegmentedView // // Created by jiaxin on 2018/12/26. // Copyright © 2018 jiaxin. All rights reserved. // import UIKit /// 列表容器视图的类型 ///- ScrollView: UIScrollView。优势:没有其他副作用。劣势:视图内存占用相对大一点。因为所有的列表视图都在UIScrollView的视图层级里面。 /// - CollectionView: 使用UICollectionView。优势:因为列表被添加到cell上,视图的内存占用更少,适合内存要求特别高的场景。劣势:因为cell重用机制的问题,导致列表下拉刷新视图(比如MJRefresh),会因为被removeFromSuperview而被隐藏。所以,列表有下拉刷新需求的,请使用scrollView type。 public enum JXSegmentedListContainerType { case scrollView case collectionView } @objc public protocol JXSegmentedListContainerViewListDelegate { /// 如果列表是VC,就返回VC.view /// 如果列表是View,就返回View自己 /// /// - Returns: 返回列表视图 func listView() -> UIView @objc optional func listWillAppear() @objc optional func listDidAppear() @objc optional func listWillDisappear() @objc optional func listDidDisappear() } @objc public protocol JXSegmentedListContainerViewDataSource { /// 返回list的数量 func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int /// 根据index初始化一个对应列表实例,需要是遵从`JXSegmentedListContainerViewListDelegate`协议的对象。 /// 如果列表是用自定义UIView封装的,就让自定义UIView遵从`JXSegmentedListContainerViewListDelegate`协议,该方法返回自定义UIView即可。 /// 如果列表是用自定义UIViewController封装的,就让自定义UIViewController遵从`JXSegmentedListContainerViewListDelegate`协议,该方法返回自定义UIViewController即可。 /// 注意:一定要是新生成的实例!!! /// /// - Parameters: /// - listContainerView: JXSegmentedListContainerView /// - index: 目标index /// - Returns: 遵从JXSegmentedListContainerViewListDelegate协议的实例 func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate /// 控制能否初始化对应index的列表。有些业务需求,需要在某些情况才允许初始化某些列表,通过通过该代理实现控制。 @objc optional func listContainerView(_ listContainerView: JXSegmentedListContainerView, canInitListAt index: Int) -> Bool /// 返回自定义UIScrollView或UICollectionView的Class /// 某些特殊情况需要自己处理UIScrollView内部逻辑。比如项目用了FDFullscreenPopGesture,需要处理手势相关代理。 /// /// - Parameter listContainerView: JXSegmentedListContainerView /// - Returns: 自定义UIScrollView实例 @objc optional func scrollViewClass(in listContainerView: JXSegmentedListContainerView) -> AnyClass } open class JXSegmentedListContainerView: UIView, JXSegmentedViewListContainer, JXSegmentedViewRTLCompatible { open private(set) var type: JXSegmentedListContainerType open private(set) weak var dataSource: JXSegmentedListContainerViewDataSource? open private(set) var scrollView: UIScrollView! /// 已经加载过的列表字典。key是index,value是对应的列表 open private(set) var validListDict = [Int:JXSegmentedListContainerViewListDelegate]() /// 滚动切换的时候,滚动距离超过一页的多少百分比,就触发列表的初始化。默认0.01(即列表显示了一点就触发加载)。范围0~1,开区间不包括0和1 open var initListPercent: CGFloat = 0.01 { didSet { if initListPercent <= 0 || initListPercent >= 1 { assertionFailure("initListPercent值范围为开区间(0,1),即不包括0和1") } } } open var listCellBackgroundColor: UIColor = .white /// 需要和segmentedView.defaultSelectedIndex保持一致,用于触发默认index列表的加载 open var defaultSelectedIndex: Int = 0 { didSet { currentIndex = defaultSelectedIndex } } private var currentIndex: Int = 0 private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 if let collectionViewClass = dataSource?.scrollViewClass?(in: self) as? UICollectionView.Type { return collectionViewClass.init(frame: CGRect.zero, collectionViewLayout: layout) }else { return UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout) } }() private lazy var containerVC = JXSegmentedListContainerViewController() private var willAppearIndex: Int = -1 private var willDisappearIndex: Int = -1 public init(dataSource: JXSegmentedListContainerViewDataSource, type: JXSegmentedListContainerType = .scrollView) { self.dataSource = dataSource self.type = type super.init(frame: CGRect.zero) commonInit() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func commonInit() { containerVC.view.backgroundColor = .clear addSubview(containerVC.view) containerVC.viewWillAppearClosure = {[weak self] in self?.listWillAppear(at: self?.currentIndex ?? 0) } containerVC.viewDidAppearClosure = {[weak self] in self?.listDidAppear(at: self?.currentIndex ?? 0) } containerVC.viewWillDisappearClosure = {[weak self] in self?.listWillDisappear(at: self?.currentIndex ?? 0) } containerVC.viewDidDisappearClosure = {[weak self] in self?.listDidDisappear(at: self?.currentIndex ?? 0) } if type == .scrollView { if let scrollViewClass = dataSource?.scrollViewClass?(in: self) as? UIScrollView.Type { scrollView = scrollViewClass.init() }else { scrollView = UIScrollView.init() } scrollView.delegate = self scrollView.isPagingEnabled = true scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = .never } if segmentedViewShouldRTLLayout() { segmentedView(horizontalFlipForView: scrollView) } containerVC.view.addSubview(scrollView) }else if type == .collectionView { collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.scrollsToTop = false collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(JXSegmentedRTLCollectionCell.self, forCellWithReuseIdentifier: "cell") if #available(iOS 10.0, *) { collectionView.isPrefetchingEnabled = false } if #available(iOS 11.0, *) { self.collectionView.contentInsetAdjustmentBehavior = .never } if segmentedViewShouldRTLLayout() { collectionView.semanticContentAttribute = .forceLeftToRight segmentedView(horizontalFlipForView: collectionView) } containerVC.view.addSubview(collectionView) //让外部统一访问scrollView scrollView = collectionView } } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) var next: UIResponder? = newSuperview while next != nil { if let vc = next as? UIViewController{ vc.addChild(containerVC) break } next = next?.next } } open override func layoutSubviews() { super.layoutSubviews() containerVC.view.frame = bounds guard let count = dataSource?.numberOfLists(in: self) else { return } if type == .scrollView { if scrollView.frame == CGRect.zero || scrollView.bounds.size != bounds.size { scrollView.frame = bounds scrollView.contentSize = CGSize(width: scrollView.bounds.size.width*CGFloat(count), height: scrollView.bounds.size.height) for (index, list) in validListDict { list.listView().frame = CGRect(x: CGFloat(index)*scrollView.bounds.size.width, y: 0, width: scrollView.bounds.size.width, height: scrollView.bounds.size.height) } scrollView.contentOffset = CGPoint(x: CGFloat(currentIndex)*scrollView.bounds.size.width, y: 0) }else { scrollView.frame = bounds scrollView.contentSize = CGSize(width: scrollView.bounds.size.width*CGFloat(count), height: scrollView.bounds.size.height) } }else { if collectionView.frame == CGRect.zero || collectionView.bounds.size != bounds.size { collectionView.frame = bounds collectionView.collectionViewLayout.invalidateLayout() collectionView.setContentOffset(CGPoint(x: CGFloat(currentIndex)*collectionView.bounds.size.width, y: 0), animated: false) }else { collectionView.frame = bounds } } } //MARK: - JXSegmentedViewListContainer public func contentScrollView() -> UIScrollView { return scrollView } public func scrolling(from leftIndex: Int, to rightIndex: Int, percent: CGFloat, selectedIndex: Int) { } open func didClickSelectedItem(at index: Int) { guard checkIndexValid(index) else { return } willAppearIndex = -1 willDisappearIndex = -1 if currentIndex != index { listWillDisappear(at: currentIndex) listWillAppear(at: index) listDidDisappear(at: currentIndex) listDidAppear(at: index) } } open func reloadData() { guard let dataSource = dataSource else { return } if currentIndex < 0 || currentIndex >= dataSource.numberOfLists(in: self) { defaultSelectedIndex = 0 currentIndex = 0 } validListDict.values.forEach { (list) in if let listVC = list as? UIViewController { listVC.removeFromParent() } list.listView().removeFromSuperview() } validListDict.removeAll() if type == .scrollView { scrollView.contentSize = CGSize(width: scrollView.bounds.size.width*CGFloat(dataSource.numberOfLists(in: self)), height: scrollView.bounds.size.height) }else { collectionView.reloadData() } listWillAppear(at: currentIndex) listDidAppear(at: currentIndex) } //MARK: - Private func initListIfNeeded(at index: Int) { guard let dataSource = dataSource else { return } if dataSource.listContainerView?(self, canInitListAt: index) == false { return } var existedList = validListDict[index] if existedList != nil { //列表已经创建好了 return } existedList = dataSource.listContainerView(self, initListAt: index) guard let list = existedList else { return } if let vc = list as? UIViewController { containerVC.addChild(vc) } validListDict[index] = list if type == .scrollView { list.listView().frame = CGRect(x: CGFloat(index)*scrollView.bounds.size.width, y: 0, width: scrollView.bounds.size.width, height: scrollView.bounds.size.height) scrollView.addSubview(list.listView()) if segmentedViewShouldRTLLayout() { segmentedView(horizontalFlipForView: list.listView()) } }else { let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) cell?.contentView.subviews.forEach { $0.removeFromSuperview() } list.listView().frame = cell?.contentView.bounds ?? CGRect.zero cell?.contentView.addSubview(list.listView()) } } private func listWillAppear(at index: Int) { guard let dataSource = dataSource else { return } guard checkIndexValid(index) else { return } var existedList = validListDict[index] if existedList != nil { existedList?.listWillAppear?() if let vc = existedList as? UIViewController { vc.beginAppearanceTransition(true, animated: false) } }else { //当前列表未被创建(页面初始化或通过点击触发的listWillAppear) guard dataSource.listContainerView?(self, canInitListAt: index) != false else { return } existedList = dataSource.listContainerView(self, initListAt: index) guard let list = existedList else { return } if let vc = list as? UIViewController { containerVC.addChild(vc) } validListDict[index] = list if type == .scrollView { if list.listView().superview == nil { list.listView().frame = CGRect(x: CGFloat(index)*scrollView.bounds.size.width, y: 0, width: scrollView.bounds.size.width, height: scrollView.bounds.size.height) scrollView.addSubview(list.listView()) if segmentedViewShouldRTLLayout() { segmentedView(horizontalFlipForView: list.listView()) } } list.listWillAppear?() if let vc = list as? UIViewController { vc.beginAppearanceTransition(true, animated: false) } }else { let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) cell?.contentView.subviews.forEach { $0.removeFromSuperview() } list.listView().frame = cell?.contentView.bounds ?? CGRect.zero cell?.contentView.addSubview(list.listView()) list.listWillAppear?() if let vc = list as? UIViewController { vc.beginAppearanceTransition(true, animated: false) } } } } private func listDidAppear(at index: Int) { guard checkIndexValid(index) else { return } currentIndex = index let list = validListDict[index] list?.listDidAppear?() if let vc = list as? UIViewController { vc.endAppearanceTransition() } } private func listWillDisappear(at index: Int) { guard checkIndexValid(index) else { return } let list = validListDict[index] list?.listWillDisappear?() if let vc = list as? UIViewController { vc.beginAppearanceTransition(false, animated: false) } } private func listDidDisappear(at index: Int) { guard checkIndexValid(index) else { return } let list = validListDict[index] list?.listDidDisappear?() if let vc = list as? UIViewController { vc.endAppearanceTransition() } } private func checkIndexValid(_ index: Int) -> Bool { guard let dataSource = dataSource else { return false } let count = dataSource.numberOfLists(in: self) if count <= 0 || index >= count { return false } return true } private func listDidAppearOrDisappear(scrollView: UIScrollView) { let currentIndexPercent = scrollView.contentOffset.x/scrollView.bounds.size.width if willAppearIndex != -1 || willDisappearIndex != -1 { let disappearIndex = willDisappearIndex let appearIndex = willAppearIndex if willAppearIndex > willDisappearIndex { //将要出现的列表在右边 if currentIndexPercent >= CGFloat(willAppearIndex) { willDisappearIndex = -1 willAppearIndex = -1 listDidDisappear(at: disappearIndex) listDidAppear(at: appearIndex) } }else { //将要出现的列表在左边 if currentIndexPercent <= CGFloat(willAppearIndex) { willDisappearIndex = -1 willAppearIndex = -1 listDidDisappear(at: disappearIndex) listDidAppear(at: appearIndex) } } } } } extension JXSegmentedListContainerView: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let dataSource = dataSource else { return 0 } return dataSource.numberOfLists(in: self) } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) cell.contentView.backgroundColor = listCellBackgroundColor cell.contentView.subviews.forEach { $0.removeFromSuperview() } let list = validListDict[indexPath.item] if list != nil { list?.listView().frame = cell.contentView.bounds cell.contentView.addSubview(list!.listView()) } return cell } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return bounds.size } public func scrollViewDidScroll(_ scrollView: UIScrollView) { guard scrollView.isTracking || scrollView.isDragging else { return } let percent = scrollView.contentOffset.x/scrollView.bounds.size.width let maxCount = Int(round(scrollView.contentSize.width/scrollView.bounds.size.width)) var leftIndex = Int(floor(Double(percent))) leftIndex = max(0, min(maxCount - 1, leftIndex)) let rightIndex = leftIndex + 1; if percent < 0 || rightIndex >= maxCount { listDidAppearOrDisappear(scrollView: scrollView) return } let remainderRatio = percent - CGFloat(leftIndex) if rightIndex == currentIndex { //当前选中的在右边,用户正在从右边往左边滑动 if validListDict[leftIndex] == nil && remainderRatio < (1 - initListPercent) { initListIfNeeded(at: leftIndex) }else if validListDict[leftIndex] != nil { if willAppearIndex == -1 { willAppearIndex = leftIndex; listWillAppear(at: willAppearIndex) } } if willDisappearIndex == -1 { willDisappearIndex = rightIndex listWillDisappear(at: willDisappearIndex) } }else { //当前选中的在左边,用户正在从左边往右边滑动 if validListDict[rightIndex] == nil && remainderRatio > initListPercent { initListIfNeeded(at: rightIndex) }else if validListDict[rightIndex] != nil { if willAppearIndex == -1 { willAppearIndex = rightIndex listWillAppear(at: willAppearIndex) } } if willDisappearIndex == -1 { willDisappearIndex = leftIndex listWillDisappear(at: willDisappearIndex) } } listDidAppearOrDisappear(scrollView: scrollView) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { //滑动到一半又取消滑动处理 if willAppearIndex != -1 || willDisappearIndex != -1 { listWillDisappear(at: willAppearIndex) listWillAppear(at: willDisappearIndex) listDidDisappear(at: willAppearIndex) listDidAppear(at: willDisappearIndex) willDisappearIndex = -1 willAppearIndex = -1 } } } class JXSegmentedListContainerViewController: UIViewController { var viewWillAppearClosure: (()->())? var viewDidAppearClosure: (()->())? var viewWillDisappearClosure: (()->())? var viewDidDisappearClosure: (()->())? override var shouldAutomaticallyForwardAppearanceMethods: Bool { return false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewWillAppearClosure?() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) viewDidAppearClosure?() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) viewWillDisappearClosure?() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) viewDidDisappearClosure?() } }
mit
3c6ae4e768d6bd79f35898888c9109c6
39.490234
183
0.625006
5.053876
false
false
false
false
jegumhon/URWeatherView
URWeatherView/Filter/URFilterBootLoading.swift
1
2979
// // URFilter.swift // URWeatherView // // Created by DongSoo Lee on 2017. 6. 9.. // Copyright © 2017년 zigbang. All rights reserved. // import Foundation typealias URFilterShaderCode = String protocol URFilterBootLoading: class { var inputImage: CIImage? { get set } var customKernel: CIKernel? { get set } var customAttributes: [Any]? { get set } var extent: CGRect { get set } var outputCGImage: CGImage? { get } func applyFilter() -> CIImage init(frame: CGRect, cgImage: CGImage, inputValues: [Any]) init(frame: CGRect, imageView: UIImageView, inputValues: [Any]) } extension URFilterBootLoading { // MARK: - kernel shader loader func loadCIKernel(from filename: String) { let shaderCode = self.loadKernelShaderCode(filename) self.customKernel = CIKernel(source: shaderCode) } func loadCIColorKernel(from filename: String) { let shaderCode = self.loadKernelShaderCode(filename) self.customKernel = CIColorKernel(source: shaderCode) } private func loadKernelShaderCode(_ filename: String) -> URFilterShaderCode { let bundle = Bundle(for: Self.self) guard let path = bundle.path(forResource: filename, ofType: nil) else { fatalError("\(Self.self) \(#function) \(#line) : Shader file is not found!!") } let shaderCode: String do { shaderCode = try String(contentsOfFile: path) } catch { fatalError("\(Self.self) \(#function) \(#line) : Shader file is failed to be CIKernel instance!!") } return shaderCode } // MARK: - handler of Input Image public func extractInputImage(cgImage: CGImage) { let ciImage = CIImage(cgImage: cgImage) self.inputImage = ciImage } public func extractInputImage(_ image: UIImage) { if let ciImage = CIImage(image: image) { self.inputImage = ciImage return } if let ciImage = image.ciImage { self.inputImage = ciImage return } fatalError("Cannot get Core Image!!") } public func extractInputImage(imageView: UIImageView) { guard let rawImage = imageView.image else { fatalError("The UIImageView must have image!!") } self.extractInputImage(rawImage) } // MARK: - util func destToSource(x: CGFloat, center: CGFloat, k: CGFloat) -> CGFloat { var sourceX: CGFloat = x sourceX -= center sourceX = sourceX / (1.0 + abs(sourceX / k)) sourceX += center return sourceX } func region(of r: CGRect, center: CGFloat, k: CGFloat) -> CGRect { let leftP: CGFloat = destToSource(x: r.origin.x, center: center, k: k) let rightP: CGFloat = destToSource(x: r.origin.x + r.size.width, center: center, k: k) return CGRect(x: leftP, y: r.origin.y, width: rightP - leftP, height: r.size.height) } }
mit
9ceee501253e893c9535221a621b0473
28.465347
110
0.622312
4.150628
false
false
false
false
WangYang-iOS/YiDeXuePin_Swift
DiYa/DiYa/Class/Home/View/YYScrollView.swift
1
3526
// // YYScrollView.swift // DiYa // // Created by wangyang on 2017/11/10. // Copyright © 2017年 wangyang. All rights reserved. // import UIKit let ITEM_WIDTH:CGFloat = SCREEN_WIDTH / 2.5 class YYScrollView: UIScrollView { var moreBlock : (() -> ())? var goodsList : [GoodsModel]? { didSet{ // guard let array = goodsList else { return } contentOffset = CGPoint(x: 0, y: 0) for (index,subView) in subviews.enumerated() { // if subView.isMember(of: GoodsItem.self) { let item = subView as! GoodsItem item.frame.origin.y = 0 item.frame.size.height = bounds.height if array.count > index { item.isHidden = false moreButton.frame = CGRect(x: item.frame.origin.x + item.bounds.width, y: 0, width: 50, height: bounds.height) item.goodsModel = array[index] }else { item.isHidden = true } contentSize = CGSize(width: CGFloat(array.count)*ITEM_WIDTH + CGFloat(50), height: 0) } } } } var moreButton = UIButton(title: "查\n看\n更\n多", fontSize: 14, normalColor: UIColor.hexString(colorString: "777777"), highLightColor: UIColor.hexString(colorString: "777777"), imageName: "ic_loadAll") override func awakeFromNib() { super.awakeFromNib() setUI() } func loadImage(array:[GoodsModel]) { contentOffset = CGPoint(x: 0, y: 0) for (index,subView) in subviews.enumerated() { // if subView.isMember(of: GoodsItem.self) { let item = subView as! GoodsItem item.frame.origin.y = 0 item.frame.size.height = bounds.height if array.count > index { item.loadImage(imgUrl: array[index].picture) }else { item.loadImage(imgUrl: "") } } } } @objc func tapItem(tap:UITapGestureRecognizer) { guard let item = tap.view as? GoodsItem, let goodsList = goodsList else { return } NotificationCenter.default.post(name: NSNotification.Name(rawValue:NSNotificationNameHomeGoodsClick), object: self, userInfo: ["model":goodsList[item.tag - 100]]) } @objc func clickMore(button:UIButton) { if moreBlock != nil { moreBlock!() } } } extension YYScrollView { fileprivate func setUI() { for i in 0..<9 { let X = ITEM_WIDTH * CGFloat(i) let item = GoodsItem.loadNib() item.frame = CGRect(x: X, y: 0, width: ITEM_WIDTH, height: bounds.height) item.tag = 100 + i addSubview(item) let tap = UITapGestureRecognizer(target: self, action: #selector(tapItem)) item.addGestureRecognizer(tap) } let view = subviews.last as! GoodsItem moreButton.frame = CGRect(x: view.frame.origin.x + view.bounds.width, y: 0, width: 50, height: bounds.height) moreButton.titleLabel?.numberOfLines = 0; moreButton.titleLabel?.lineBreakMode = .byWordWrapping addSubview(moreButton) moreButton.addTarget(self, action: #selector(clickMore), for: .touchUpInside) } }
mit
9ddd7de75ab925767945f37304a70909
33.80198
202
0.540256
4.415829
false
false
false
false
GeoffSpielman/SimonSays
simon_says_iOS_app/SocketPacket.swift
1
6872
// // SocketPacket.swift // Socket.IO-Client-Swift // // Created by Erik Little on 1/18/15. // // 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 struct SocketPacket { enum PacketType: Int { case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck } private let placeholders: Int private static let logType = "SocketPacket" let nsp: String let id: Int let type: PacketType var binary: [NSData] var data: [AnyObject] var args: [AnyObject] { if type == .Event || type == .BinaryEvent && data.count != 0 { return Array(data.dropFirst()) } else { return data } } var description: String { return "SocketPacket {type: \(String(type.rawValue)); data: " + "\(String(data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}" } var event: String { return String(data[0]) } var packetString: String { return createPacketString() } init(type: PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1, nsp: String, placeholders: Int = 0, binary: [NSData] = [NSData]()) { self.data = data self.id = id self.nsp = nsp self.type = type self.placeholders = placeholders self.binary = binary } mutating func addData(data: NSData) -> Bool { if placeholders == binary.count { return true } binary.append(data) if placeholders == binary.count { fillInPlaceholders() return true } else { return false } } private func completeMessage(message: String) -> String { let restOfMessage: String if data.count == 0 { return message + "[]" } do { let jsonSend = try data.toJSON() guard let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding) else { return message + "[]" } restOfMessage = jsonString } catch { DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage", type: SocketPacket.logType) restOfMessage = "[]" } return message + restOfMessage } private func createPacketString() -> String { let typeString = String(type.rawValue) // Binary count? let binaryCountString = typeString + (type == .BinaryEvent || type == .BinaryAck ? String(binary.count) + "-" : "") // Namespace? let nspString = binaryCountString + (nsp != "/" ? nsp + "," : "") // Ack number? let idString = nspString + (id != -1 ? String(id) : "") return completeMessage(idString) } // Called when we have all the binary data for a packet // calls _fillInPlaceholders, which replaces placeholders with the // corresponding binary private mutating func fillInPlaceholders() { data = data.map(_fillInPlaceholders) } // Helper method that looks for placeholders // If object is a collection it will recurse // Returns the object if it is not a placeholder or the corresponding // binary data private func _fillInPlaceholders(object: AnyObject) -> AnyObject { switch object { case let dict as NSDictionary: if dict["_placeholder"] as? Bool ?? false { return binary[dict["num"] as! Int] } else { return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1) return cur }) } case let arr as [AnyObject]: return arr.map(_fillInPlaceholders) default: return object } } } extension SocketPacket { private static func findType(binCount: Int, ack: Bool) -> PacketType { switch binCount { case 0 where !ack: return .Event case 0 where ack: return .Ack case _ where !ack: return .BinaryEvent case _ where ack: return .BinaryAck default: return .Error } } static func packetFromEmit(items: [AnyObject], id: Int, nsp: String, ack: Bool) -> SocketPacket { let (parsedData, binary) = deconstructData(items) let packet = SocketPacket(type: findType(binary.count, ack: ack), data: parsedData, id: id, nsp: nsp, binary: binary) return packet } } private extension SocketPacket { // Recursive function that looks for NSData in collections static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject { let placeholder = ["_placeholder": true, "num": binary.count] switch data { case let bin as NSData: binary.append(bin) return placeholder case let arr as [AnyObject]: return arr.map({shred($0, binary: &binary)}) case let dict as NSDictionary: return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in cur[keyValue.0 as! NSCopying] = shred(keyValue.1, binary: &binary) return cur }) default: return data } } // Removes binary data from emit data // Returns a type containing the de-binaryed data and the binary static func deconstructData(data: [AnyObject]) -> ([AnyObject], [NSData]) { var binary = [NSData]() return (data.map({shred($0, binary: &binary)}), binary) } }
mit
ec271ebdb63a28f2bb5a6002e6e5bc52
32.198068
123
0.58862
4.67483
false
false
false
false
zjjzmw1/robot
robot/robot/CodeFragment/Category/UIButton+IOSUtil.swift
2
3831
// // UIButton+IOSUtil.swift // niaoyutong // // Created by zhangmingwei on 2017/5/24. // Copyright © 2017年 niaoyutong. All rights reserved. // import Foundation import UIKit extension UIButton { /// - 设置按钮是否可以点击的状态 (不可点击为灰色,可点击为蓝色) public func setButtonEnabled(isEnable: Bool) { if isEnable { self.backgroundColor = UIColor.getMainColorSwift() self.setTitleColor(UIColor.white, for: .normal) self.isUserInteractionEnabled = true } else { self.backgroundColor = UIColor.colorRGB16(value: 0xececec) self.setTitleColor(UIColor.getContentSecondColorSwift(), for: .normal) self.isUserInteractionEnabled = false } } } /// MARK: - 避免按钮多次点击的方法 - (按钮的touchUpInside和Down能做到相互不影响) extension UIButton { /// 默认是0.5秒内不能重复点击按钮 private struct AssociatedKeys { static var xlx_defaultInterval:TimeInterval = 0.5 static var xlx_customInterval = "xlx_customInterval" // 需要自定义事件间隔的话例如 :TimeInterval = 1.0 static var xlx_ignoreInterval = "xlx_ignoreInterval" } // 自定义属性用来添加自定义的间隔时间。可以设置 1秒、2秒,等等 var customInterval: TimeInterval { get { let xlx_customInterval = objc_getAssociatedObject(self, &AssociatedKeys.xlx_customInterval) if let time = xlx_customInterval { return time as! TimeInterval }else{ return AssociatedKeys.xlx_defaultInterval } } set { objc_setAssociatedObject(self, &AssociatedKeys.xlx_customInterval, newValue as TimeInterval ,.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// 自定义属性 - 是否忽略间隔 var ignoreInterval: Bool { get { return (objc_getAssociatedObject(self, &AssociatedKeys.xlx_ignoreInterval) != nil) } set { objc_setAssociatedObject(self, &AssociatedKeys.xlx_ignoreInterval, newValue as Bool, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } override open class func initialize() { if self == UIButton.self { DispatchQueue.once("com.wj.niaoyutong", block: { // DispatchQueue.once(NSUUID().uuidString, block: { // 先获取到系统和自己的 selector let systemSel = #selector(UIButton.sendAction(_:to:for:)) let swizzSel = #selector(UIButton.mySendAction(_:to:for:)) // 再根据seletor获取到Method let systemMethod = class_getInstanceMethod(self, systemSel) let swizzMethod = class_getInstanceMethod(self, swizzSel) /// 把系统的方法添加到类里面 - 如果存在就添加失败 let isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod)) if isAdd { class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod)); } else { method_exchangeImplementations(systemMethod, swizzMethod); } }) } } private dynamic func mySendAction(_ action: Selector, to target: Any?, for event: UIEvent?) { if !ignoreInterval { isUserInteractionEnabled = false DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+customInterval, execute: { [weak self] in self?.isUserInteractionEnabled = true }) } mySendAction(action, to: target, for: event) } }
mit
6501747549c0a8e111a191f53b344058
36.446809
141
0.617614
4.389027
false
false
false
false
shridharmalimca/iOSDev
iOS/Swift 3.0/UnitTesting/UnitTesting/ViewController.swift
2
1290
// // ViewController.swift // UnitTesting // // Created by Shridhar Mali on 12/27/16. // Copyright © 2016 TIS. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tblView: UITableView! var rowNumber: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func buttonTapped(_ sender: Any) { rowNumber = 10 self.tblView.reloadData() } func isNumberEven(num: Int) -> Bool { if num % 2 == 0 { return true } else { return false } } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rowNumber } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = "cell \(indexPath.row)" return cell } }
apache-2.0
741c2b9f0887067a1fcdc40c95074793
25.306122
100
0.635376
4.845865
false
false
false
false
antonvmironov/PhysicalValue
PhysicalValue/Operators/Multiplication.swift
1
1254
// // Multiplication.swift // PhysicalValue // // Created by Anton Mironov on 5/27/16. // Copyright © 2016 Anton Mironov. All rights reserved. // import Foundation public func *(lhs: _PhysicalUnit, rhs: _PhysicalUnit) -> CompoundPhysicalUnit { let kinds = lhs.compoundPhysicalUnit.kinds + rhs.compoundPhysicalUnit.kinds return CompoundPhysicalUnit(kinds: kinds) } public func *(lhs: _PhysicalValue, rhs: _PhysicalValue) -> CompoundPhysicalValue { let normal = lhs.normal * rhs.normal let unit = lhs._unit * rhs._unit let amount = unit.amount(normal: normal) return CompoundPhysicalValue(amount: amount, unit: unit) } public func *<T: PhysicalValue>(lhs: T.Unit, rhs: MathValue) -> T { return T(amount: rhs, unit: lhs) } public func *<T: PhysicalValue>(lhs: MathValue, rhs: T) -> T { var result = rhs result.amount *= lhs return result } public func *<T: PhysicalValue>(lhs: T, rhs: MathValue) -> T { var result = lhs result.amount *= rhs return result } public func *(lhs: PhysicalUnitKind, rhs: PhysicalUnitKind) -> PhysicalUnitKind { return .compound(lhs.compoundPhysicalUnit * rhs.compoundPhysicalUnit) } public func *<T: PhysicalValue>(lhs: MathValue, rhs: T.Unit) -> T { return T(amount: lhs, unit: rhs) }
mit
325fc877a8b46e0aed2a4b2104585985
26.844444
82
0.707901
3.395664
false
false
false
false
SteveClement/iOS-Open-GPX-Tracker
OpenGpxTracker/GPXFilesTableViewController.swift
1
7491
// // GPXFilesTableViewController.swift // OpenGpxTracker // // Created by merlos on 14/09/14. // Copyright (c) 2014 TransitBox. All rights reserved. // import Foundation let kNoFiles = "No gpx files" import UIKit import MessageUI class GPXFilesTableViewController : UITableViewController, UINavigationBarDelegate, MFMailComposeViewControllerDelegate, UIActionSheetDelegate { var fileList:NSMutableArray = [kNoFiles] var selectedRowIndex = -1 var delegate: GPXFilesTableViewControllerDelegate? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func viewDidLoad() { super.viewDidLoad() let navBarFrame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64) //let navigationBar : UINavigationBar = UINavigationBar(frame: navBarFrame) self.tableView.frame = CGRect(x: navBarFrame.width + 1, y: 0, width: self.view.frame.width, height: self.view.frame.height - navBarFrame.height) self.title = "Your GPX Files" let shareItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "closeGPXFilesTableViewController") self.navigationItem.rightBarButtonItems = [shareItem] //get gpx files let list: NSArray = GPXFileManager.fileList if list.count != 0 { self.fileList.removeAllObjects() self.fileList.addObjectsFromArray(list as [AnyObject]) } } func closeGPXFilesTableViewController() { print("closeGPXFIlesTableViewController()") self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } override func viewDidAppear(animated: Bool) { self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //#pragma mark - Table view data source override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return fileList.count; } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true; } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if(editingStyle == UITableViewCellEditingStyle.Delete) { actionDeleteFileAtIndex(indexPath.row) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell") //cell.accessoryType = UITableViewCellAccessoryType.DetailDisclosureButton //cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:@"Something" ]]; cell.textLabel?.text = fileList.objectAtIndex(indexPath.row) as! NSString as String return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // self.showAlert(fileList.objectAtIndex(indexPath.row) as NSString, rowToUseInAlert: indexPath.row) let sheet = UIActionSheet() sheet.title = "Select option" sheet.addButtonWithTitle("Send by email") sheet.addButtonWithTitle("Load in Map") sheet.addButtonWithTitle("Cancel") sheet.addButtonWithTitle("Delete") sheet.cancelButtonIndex = 2 sheet.destructiveButtonIndex = 3 sheet.delegate = self sheet.showInView(self.view) self.selectedRowIndex = indexPath.row } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { print("action sheet clicked button at index \(buttonIndex)") switch buttonIndex { case 0: self.actionSendEmailWithAttachment(self.selectedRowIndex) case 1: self.actionLoadFileAtIndex(self.selectedRowIndex) case 2: print("ActionSheet: Cancel") case 3: //Delete self.actionDeleteFileAtIndex(self.selectedRowIndex) default: //cancel print("action Sheet do nothing") } } func actionSheetCancel(actionSheet: UIActionSheet) { print("actionsheet cancel") } //#pragma mark - UIAlertView delegate methods func alertView(alertView: UIAlertView!, didDismissWithButtonIndex buttonIndex: Int) { NSLog("Did dismiss button: %d", buttonIndex) } func actionDeleteFileAtIndex(rowIndex: Int) { //Delete File let filename: String = fileList.objectAtIndex(rowIndex) as! String GPXFileManager.removeFile(filename) //Delete from list and Table fileList.removeObjectAtIndex(rowIndex) let indexPath = NSIndexPath(forRow: rowIndex, inSection: 0) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) tableView.reloadData() } func actionLoadFileAtIndex(rowIndex: Int) { let filename: String = fileList.objectAtIndex(rowIndex) as! String print("load gpx File: \(filename)") let fileURL: NSURL = GPXFileManager.URLForFilename(filename) let gpx = GPXParser.parseGPXAtPath(fileURL.path) self.delegate?.didLoadGPXFileWithName(filename, gpxRoot: gpx) self.dismissViewControllerAnimated(true, completion: nil) } //#pragma mark - Send email func actionSendEmailWithAttachment(rowIndex: Int) { let filename: String = fileList.objectAtIndex(rowIndex) as! String let fileURL: NSURL = GPXFileManager.URLForFilename(filename) let composer = MFMailComposeViewController() composer.mailComposeDelegate = self // set the subject composer.setSubject("[Open GPX tracker] Gpx File") //Add some text to the body and attach the file let body = "Open GPX Tracker \n is an open source app for Apple devices. Create GPS tracks and export them to GPX files." composer.setMessageBody(body, isHTML: true) let fileData: NSData = try! NSData(contentsOfFile: fileURL.path!, options: .DataReadingMappedIfSafe) composer.addAttachmentData(fileData, mimeType:"application/gpx+xml", fileName: fileURL.lastPathComponent!) //Display the comopser view controller self.presentViewController(composer, animated: true, completion: nil) } func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?){ switch(result.rawValue){ case MFMailComposeResultSent.rawValue: print("Email sent") default: print("Whoops") } self.dismissViewControllerAnimated(true, completion: nil) } }
gpl-3.0
53458d0177216079153d034b99a6dc3d
35.541463
155
0.686424
5.253156
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/HorizVertPanGestureViewController.swift
1
1601
// // HorizVertPanGestureViewController.swift // ApiDemo-Swift // // Created by Jacob su on 8/9/16. // Copyright © 2016 suzp1984@gmail.com. All rights reserved. // import UIKit class HorizVertPanGestureViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white let v = UIView(frame: CGRect(x: 120, y: 120, width: 150, height: 150)) v.backgroundColor = UIColor.red self.view.addSubview(v) let horizGesture = HorizPanGestureRecognizer(target: self, action: #selector(HorizVertPanGestureViewController.dragging(_:))) v.addGestureRecognizer(horizGesture) let vertGesture = VertPanGestureRecognizer(target: self, action: #selector(HorizVertPanGestureViewController.dragging(_:))) v.addGestureRecognizer(vertGesture) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dragging(_ p: UIPanGestureRecognizer) { if let v = p.view { switch p.state { case .began, .changed: let delta = p.translation(in: v.superview) var c = v.center c.x += delta.x c.y += delta.y v.center = c p.setTranslation(CGPoint.zero, in: v.superview) case .failed: print("Dragging states is failed.") default: break } } } }
apache-2.0
f71495792f6a2a01d39abb74abf5e956
29.188679
133
0.594375
4.664723
false
false
false
false
wikimedia/wikipedia-ios
Command Line Tools/Update Localizations/localization.swift
1
28633
import Foundation /// **THIS IS NOT PART OF THE MAIN APP - IT'S A COMMAND LINE UTILITY** fileprivate var dictionaryRegex: NSRegularExpression? = { do { return try NSRegularExpression(pattern: "(?:[{][{])(:?[^{]*)(?:[}][}])", options: []) } catch { assertionFailure("Localization regex failed to compile") } return nil }() fileprivate var curlyBraceRegex: NSRegularExpression? = { do { return try NSRegularExpression(pattern: "(?:[{][{][a-z]+:)(:?[^{]*)(?:[}][}])", options: [.caseInsensitive]) } catch { assertionFailure("Localization regex failed to compile") } return nil }() fileprivate var twnTokenRegex: NSRegularExpression? = { do { return try NSRegularExpression(pattern: "(?:[$])(:?[0-9]+)", options: []) } catch { assertionFailure("Localization token regex failed to compile") } return nil }() fileprivate var iOSTokenRegex: NSRegularExpression? = { do { return try NSRegularExpression(pattern: "%([0-9]*)\\$?([@dDuUxXoOfeEgGcCsSpaAF])", options: []) } catch { assertionFailure("Localization token regex failed to compile") } return nil }() fileprivate var mwLocalizedStringRegex: NSRegularExpression? = { do { return try NSRegularExpression(pattern: "(?:WMLocalizedString\\(@\\\")(:?[^\"]+)(?:[^\\)]*\\))", options: []) } catch { assertionFailure("mwLocalizedStringRegex failed to compile") } return nil }() fileprivate var countPrefixRegex: NSRegularExpression? = { do { return try NSRegularExpression(pattern: "(:?^[^\\=]+)(?:=)", options: []) } catch { assertionFailure("countPrefixRegex failed to compile") } return nil }() // lookup from translatewiki prefix to iOS-supported stringsdict key let keysByPrefix = [ "0":"zero", // "1":"one" digits on translatewiki mean only use the translation when the replacement number === that digit. On iOS one, two, and few are more generic. for example, the translation for one could map to 1, 21, 31, etc // "2":"two", // "3":"few" "zero":"zero", "one":"one", "two":"two", "few":"few", "many":"many", "other":"other" ] extension String { var fullRange: NSRange { return NSRange(startIndex..<endIndex, in: self) } var escapedString: String { return self.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\\n") } /* supportsOneEquals indicates that the language's singular translation on iOS is only valid for n=1. digits on translatewiki mean only use the translation when the replacement number === that digit. On iOS one, two, and few are more generic. for example, the translation for one could map to 1, 21, 31, etc. Only use 1= for one when the iOS definition matches the translatewiki definition for a given language. */ func pluralDictionary(with keys: [String], tokens: [String: String], supportsOneEquals: Bool) -> NSDictionary? { //https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPInternational/StringsdictFileFormat/StringsdictFileFormat.html#//apple_ref/doc/uid/10000171i-CH16-SW1 guard let dictionaryRegex = dictionaryRegex else { return nil } var remainingKeys = keys let fullRange = self.fullRange let mutableDictionary = NSMutableDictionary(capacity: 5) let results = dictionaryRegex.matches(in: self, options: [], range: fullRange) let nsSelf = self as NSString // format is the full string with the plural tokens replaced by variables // it will be built by enumerating through the matches for the plural regex var format = "" var location = 0 for result in results { // append the next part of the string after the last match and before this one format += nsSelf.substring(with: NSRange(location: location, length: result.range.location - location)).iOSNativeLocalization(tokens: tokens) location = result.range.location + result.range.length // get the contents of the match - the content between {{ and }} let contents = dictionaryRegex.replacementString(for: result, in: self, offset: 0, template: "$1") let components = contents.components(separatedBy: "|") let countOfComponents = components.count guard countOfComponents > 1 else { continue } let pluralPrefix = "PLURAL:" let firstComponent = components[0] guard firstComponent.hasPrefix(pluralPrefix) else { continue } if firstComponent == pluralPrefix { print("Incorrectly formatted plural: \(self)") abort() } let token = firstComponent.suffix(from: firstComponent.index(firstComponent.startIndex, offsetBy: 7)).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let nsToken = (token as NSString) let tokenNumber = nsToken.substring(from: 1) guard let tokenInt = Int(tokenNumber), tokenInt > 0 else { continue } let keyDictionary = NSMutableDictionary(capacity: 5) let formatValueType = tokens[tokenNumber] ?? "d" keyDictionary["NSStringFormatSpecTypeKey"] = "NSStringPluralRuleType" keyDictionary["NSStringFormatValueTypeKey"] = formatValueType guard let countPrefixRegex = countPrefixRegex else { abort() } var unlabeledComponents: [String] = [] for component in components[1..<countOfComponents] { var keyForComponent: String? var actualComponent: String? = component guard let match = countPrefixRegex.firstMatch(in: component, options: [], range: component.fullRange) else { if component.contains("=") { print("Unsupported prefix: \(String(describing: component))") abort() } unlabeledComponents.append(component) continue } // Support for 0= 1= 2= zero= one= few= many= let numberString = countPrefixRegex.replacementString(for: match, in: component, offset: 0, template: "$1") if let key = (supportsOneEquals && (numberString == "1" || numberString == "one")) ? "one" : keysByPrefix[numberString] { keyForComponent = key remainingKeys = remainingKeys.filter({ (aKey) -> Bool in return key != aKey }) actualComponent = String(component.suffix(from: component.index(component.startIndex, offsetBy: match.range.length))) } else { #if DEBUG print("Translatewiki prefix \(numberString) not supported on iOS for this language. Ignoring \(String(describing: component))") #endif } guard let keyToInsert = keyForComponent, let componentToInsert = actualComponent else { continue } keyDictionary[keyToInsert] = componentToInsert.iOSNativeLocalization(tokens: tokens) } if let other = unlabeledComponents.last { keyDictionary["other"] = other.iOSNativeLocalization(tokens: tokens) for (keyIndex, component) in unlabeledComponents.enumerated() { guard keyIndex < unlabeledComponents.count - 1, keyIndex < remainingKeys.count else { break } keyDictionary[remainingKeys[keyIndex]] = component.iOSNativeLocalization(tokens: tokens) } } else if keyDictionary["other"] == nil { if keyDictionary["many"] != nil { keyDictionary["other"] = keyDictionary["many"] } else { print("missing default translation") abort() } } // set the variable name for the plural replacement let key = "v\(tokenInt)" // include the dictionary of possible replacements for the plural token mutableDictionary[key] = keyDictionary // append the variable name to the format string where the plural token used to be format += "%#@\(key)@" } // append the final part of the string after the last match format += nsSelf.substring(with: NSRange(location: location, length: nsSelf.length - location)).iOSNativeLocalization(tokens: tokens) mutableDictionary["NSStringLocalizedFormatKey"] = format return mutableDictionary } public func replacingMatches(fromRegex regex: NSRegularExpression, withFormat format: String) -> String { let nativeLocalization = NSMutableString(string: self) var offset = 0 let fullRange = NSRange(location: 0, length: nativeLocalization.length) var index = 1 regex.enumerateMatches(in: self, options: [], range: fullRange) { (result, flags, stop) in guard let result = result else { return } var token = regex.replacementString(for: result, in: nativeLocalization as String, offset: offset, template: "$1") // If the token doesn't have an index, give it one // This allows us to support unordered tokens for single token strings if token == "" { token = "\(index)" } let replacement = String(format: format, token) let replacementRange = NSRange(location: result.range.location + offset, length: result.range.length) nativeLocalization.replaceCharacters(in: replacementRange, with: replacement) offset += (replacement as NSString).length - result.range.length index += 1 } return nativeLocalization as String } public func replacingMatches(fromTokenRegex regex: NSRegularExpression, withFormat format: String, tokens: [String: String]) -> String { let nativeLocalization = NSMutableString(string: self) var offset = 0 let fullRange = NSRange(location: 0, length: nativeLocalization.length) regex.enumerateMatches(in: self, options: [], range: fullRange) { (result, flags, stop) in guard let result = result else { return } let token = regex.replacementString(for: result, in: nativeLocalization as String, offset: offset, template: "$1") let replacement = String(format: format, token, tokens[token] ?? "@") let replacementRange = NSRange(location: result.range.location + offset, length: result.range.length) nativeLocalization.replaceCharacters(in: replacementRange, with: replacement) offset += (replacement as NSString).length - result.range.length } return nativeLocalization as String } func iOSNativeLocalization(tokens: [String: String]) -> String { guard let tokenRegex = twnTokenRegex, let braceRegex = curlyBraceRegex else { return "" } return self.replacingMatches(fromRegex: braceRegex, withFormat: "%@").replacingMatches(fromTokenRegex: tokenRegex, withFormat: "%%%@$%@", tokens: tokens) } var twnNativeLocalization: String { guard let tokenRegex = iOSTokenRegex else { return "" } return self.replacingMatches(fromRegex: tokenRegex, withFormat: "$%@") } var iOSTokenDictionary: [String: String] { guard let iOSTokenRegex = iOSTokenRegex else { print("Unable to compile iOS token regex") abort() } var tokenDictionary = [String:String]() iOSTokenRegex.enumerateMatches(in: self, options: [], range:self.fullRange, using: { (result, flags, stop) in guard let result = result else { return } var number = iOSTokenRegex.replacementString(for: result, in: self as String, offset: 0, template: "$1") // treat an un-numbered token as 1 if number == "" { number = "1" } let token = iOSTokenRegex.replacementString(for: result, in: self as String, offset: 0, template: "$2") if tokenDictionary[number] == nil { tokenDictionary[number] = token } else if token != tokenDictionary[number] { print("Internal token mismatch: \(self)") abort() } }) return tokenDictionary } } func writeStrings(fromDictionary dictionary: NSDictionary, toFile: String) throws { var shouldWrite = true if let existingDictionary = NSDictionary(contentsOfFile: toFile) { shouldWrite = existingDictionary.count != dictionary.count if !shouldWrite { for (key, value) in dictionary { guard let value = value as? String, let existingValue = existingDictionary[key] as? NSString else { shouldWrite = true break } shouldWrite = !existingValue.isEqual(to: value) if shouldWrite { break } } } } guard shouldWrite else { return } let folder = (toFile as NSString).deletingLastPathComponent do { try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true, attributes: nil) } catch { } let output = dictionary.descriptionInStringsFileFormat try output.write(toFile: toFile, atomically: true, encoding: .utf16) // From Apple: Note: It is recommended that you save strings files using the UTF-16 encoding, which is the default encoding for standard strings files. It is possible to create strings files using other property-list formats, including binary property-list formats and XML formats that use the UTF-8 encoding, but doing so is not recommended. For more information about Unicode and its text encodings, go to http://www.unicode.org/ or http://en.wikipedia.org/wiki/Unicode. } // See "Localized Metadata" section here: https://docs.fastlane.tools/actions/deliver/ func fileURLForFastlaneMetadataFolder(for locale: String) -> URL { return URL(fileURLWithPath:"\(path)/fastlane/metadata/\(locale)") } func fileURLForFastlaneMetadataFile(_ file: String, for locale: String) -> URL { return fileURLForFastlaneMetadataFolder(for: locale).appendingPathComponent(file) } let defaultAppStoreMetadataLocale = "en-us" func writeFastlaneMetadata(_ metadata: Any?, to filename: String, for locale: String) throws { let metadataFileURL = fileURLForFastlaneMetadataFile(filename, for: locale) guard let metadata = metadata as? String, metadata.count > 0 else { let defaultDescriptionFileURL = fileURLForFastlaneMetadataFile(filename, for: defaultAppStoreMetadataLocale) let fm = FileManager.default try fm.removeItem(at: metadataFileURL) try fm.copyItem(at: defaultDescriptionFileURL, to: metadataFileURL) return } try metadata.write(to: metadataFileURL, atomically: true, encoding: .utf8) } func writeTWNStrings(fromDictionary dictionary: [String: String], toFile: String, escaped: Bool) throws { var output = "" let sortedDictionary = dictionary.sorted(by: { (kv1, kv2) -> Bool in return kv1.key < kv2.key }) for (key, value) in sortedDictionary { output.append("\"\(key)\" = \"\(escaped ? value.escapedString : value)\";\n") } try output.write(toFile: toFile, atomically: true, encoding: .utf8) } func exportLocalizationsFromSourceCode(_ path: String) { let iOSENPath = "\(path)/Wikipedia/iOS Native Localizations/en.lproj/Localizable.strings" let twnQQQPath = "\(path)/Wikipedia/Localizations/qqq.lproj/Localizable.strings" let twnENPath = "\(path)/Wikipedia/Localizations/en.lproj/Localizable.strings" guard let iOSEN = NSDictionary(contentsOfFile: iOSENPath) else { print("Unable to read \(iOSENPath)") abort() } let twnQQQ = NSMutableDictionary() let twnEN = NSMutableDictionary() do { let commentSet = CharacterSet(charactersIn: "/* ") let quoteSet = CharacterSet(charactersIn: "\"") let string = try String(contentsOfFile: iOSENPath) let lines = string.components(separatedBy: .newlines) var currentComment: String? var currentKey: String? var commentsByKey = [String: String]() for line in lines { let cleanedLine = line.trimmingCharacters(in: .whitespaces) if cleanedLine.hasPrefix("/*") { currentComment = cleanedLine.trimmingCharacters(in: commentSet) currentKey = nil } else if currentComment != nil { let quotesRemoved = cleanedLine.trimmingCharacters(in: quoteSet) if let range = quotesRemoved.range(of: "\" = \"") { currentKey = String(quotesRemoved.prefix(upTo: range.lowerBound)) } } if let key = currentKey, let comment = currentComment { commentsByKey[key] = comment } } for (key, comment) in commentsByKey { twnQQQ[key] = comment.twnNativeLocalization } try writeTWNStrings(fromDictionary: twnQQQ as! [String: String], toFile: twnQQQPath, escaped: false) for (key, value) in iOSEN { guard let value = value as? String, let key = key as? String else { continue } twnEN[key] = value.twnNativeLocalization } try writeTWNStrings(fromDictionary: twnEN as! [String: String], toFile: twnENPath, escaped: true) } catch let error { print("Error exporting localizations: \(error)") abort() } } let locales: Set<String> = { var identifiers = Locale.availableIdentifiers if let filenames = try? FileManager.default.contentsOfDirectory(atPath: "\(path)/Wikipedia/iOS Native Localizations") { let additional = filenames.compactMap { $0.components(separatedBy: ".").first?.lowercased() } identifiers += additional } identifiers += ["ku"] // iOS 13 added support for ku but macOS 10.14 doesn't include it, add it manually. This line can be removed when macOS 10.15 ships. return Set<String>(identifiers) }() // See supportsOneEquals documentation. Utilized this list: https://unicode-org.github.io/cldr-staging/charts/37/supplemental/language_plural_rules.html to verify languages where that applies for the cardinal -> one rule let localesWhereMediaWikiPluralRulesDoNotMatchiOSPluralRulesForOne = { return Set<String>(["be", "bs", "br", "ceb", "tzm", "hr", "fil", "is", "lv", "lt", "dsb", "mk", "gv", "prg", "ru", "gd", "sr", "sl", "uk", "hsb"]).intersection(locales) }() func localeIsAvailable(_ locale: String) -> Bool { let prefix = locale.components(separatedBy: "-").first ?? locale return locales.contains(prefix) } func importLocalizationsFromTWN(_ path: String) { let enPath = "\(path)/Wikipedia/iOS Native Localizations/en.lproj/Localizable.strings" guard let enDictionary = NSDictionary(contentsOfFile: enPath) as? [String: String] else { print("Unable to read \(enPath)") abort() } var enTokensByKey = [String: [String: String]]() for (key, value) in enDictionary { enTokensByKey[key] = value.iOSTokenDictionary } let fm = FileManager.default do { let keysByLanguage = ["pl": ["one", "few"], "sr": ["one", "few", "many"], "ru": ["one", "few", "many"]] let defaultKeys = ["one"] let appStoreMetadataLocales: [String: [String]] = [ "da": ["da"], "de": ["de-de"], "el": ["el"], // "en": ["en-au", "en-ca", "en-gb"], "es": ["es-mx", "es-es"], "fi": ["fi"], "fr": ["fr-ca", "fr-fr"], "id": ["id"], "it": ["it"], "ja": ["ja"], "ko": ["ko"], "ms": ["ms"], "nl": ["nl-nl"], "no": ["no"], "pt": ["pt-br", "pt-pt"], "ru": ["ru"], "sv": ["sv"], "th": ["th"], "tr": ["tr"], "vi": ["vi"], "zh-hans": ["zh-hans"], "zh-hant": ["zh-hant"] ] let contents = try fm.contentsOfDirectory(atPath: "\(path)/Wikipedia/Localizations") var pathsForEnglishPlurals: [String] = [] // write english plurals to these paths as placeholders var englishPluralDictionary: NSMutableDictionary? for filename in contents { guard let locale = filename.components(separatedBy: ".").first?.lowercased() else { continue } let localeFolder = "\(path)/Wikipedia/iOS Native Localizations/\(locale).lproj" guard localeIsAvailable(locale), let twnStrings = NSDictionary(contentsOfFile: "\(path)/Wikipedia/Localizations/\(locale).lproj/Localizable.strings") else { try? fm.removeItem(atPath: localeFolder) continue } let stringsDictFilePath = "\(localeFolder)/Localizable.stringsdict" let stringsFilePath = "\(localeFolder)/Localizable.strings" let stringsDict = NSMutableDictionary(capacity: twnStrings.count) let strings = NSMutableDictionary(capacity: twnStrings.count) for (key, value) in twnStrings { guard let twnString = value as? String, let key = key as? String, let enTokens = enTokensByKey[key] else { continue } let nativeLocalization = twnString.iOSNativeLocalization(tokens: enTokens) let nativeLocalizationTokens = nativeLocalization.iOSTokenDictionary guard nativeLocalizationTokens == enTokens else { #if DEBUG print("Mismatched tokens in \(locale) for \(key):\n\(enDictionary[key] ?? "")\n\(nativeLocalization)") #endif continue } if twnString.contains("{{PLURAL:") { let lang = locale.components(separatedBy: "-").first ?? "" let keys = keysByLanguage[lang] ?? defaultKeys let supportsOneEquals = !localesWhereMediaWikiPluralRulesDoNotMatchiOSPluralRulesForOne.contains(lang) stringsDict[key] = twnString.pluralDictionary(with: keys, tokens:enTokens, supportsOneEquals: supportsOneEquals) strings[key] = nativeLocalization } else { strings[key] = nativeLocalization } } if locale != "en" { // only write the english plurals, skip the main file if strings.count > 0 { try writeStrings(fromDictionary: strings, toFile: stringsFilePath) } else { try? fm.removeItem(atPath: stringsFilePath) } } else { englishPluralDictionary = stringsDict } if let metadataLocales = appStoreMetadataLocales[locale] { for metadataLocale in metadataLocales { let folderURL = fileURLForFastlaneMetadataFolder(for: metadataLocale) try fm.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil) let infoPlistPath = "\(path)/Wikipedia/iOS Native Localizations/\(locale).lproj/InfoPlist.strings" let infoPlist = NSDictionary(contentsOfFile: infoPlistPath) try? writeFastlaneMetadata(strings["app-store-short-description"], to: "description.txt", for: metadataLocale) try? writeFastlaneMetadata(strings["app-store-keywords"], to: "keywords.txt", for: metadataLocale) try? writeFastlaneMetadata(nil, to: "marketing_url.txt", for: metadataLocale) // use nil to copy from en-US. all fields need to be specified. try? writeFastlaneMetadata(infoPlist?["CFBundleDisplayName"], to: "name.txt", for: metadataLocale) try? writeFastlaneMetadata(nil, to: "privacy_url.txt", for: metadataLocale) // use nil to copy from en-US. all fields need to be specified. try? writeFastlaneMetadata(nil, to: "promotional_text.txt", for: metadataLocale) // use nil to copy from en-US. all fields need to be specified. try? writeFastlaneMetadata(nil, to: "release_notes.txt", for: metadataLocale) // use nil to copy from en-US. all fields need to be specified. try? writeFastlaneMetadata(strings["app-store-subtitle"], to: "subtitle.txt", for: metadataLocale) try? writeFastlaneMetadata(nil, to: "support_url.txt", for: metadataLocale) // use nil to copy from en-US. all fields need to be specified. } } else { let folderURL = fileURLForFastlaneMetadataFolder(for: locale) try? fm.removeItem(at: folderURL) } if stringsDict.count > 0 { stringsDict.write(toFile: stringsDictFilePath, atomically: true) } else { pathsForEnglishPlurals.append(stringsDictFilePath) } } for stringsDictFilePath in pathsForEnglishPlurals { englishPluralDictionary?.write(toFile: stringsDictFilePath, atomically: true) } } catch let error { print("Error importing localizations: \(error)") abort() } } // Code that updated source translations // var replacements = [String: String]() // for (key, comment) in qqq { // guard let value = en[key] else { // continue // } // replacements[key] = "WMFLocalizedStringWithDefaultValue(@\"\(key.escapedString)\", nil, NSBundle.mainBundle, @\"\(value.iOSNativeLocalization.escapedString)\", \"\(comment.escapedString)\")" // } // // let codePath = "WMF Framework" // let contents = try FileManager.default.contentsOfDirectory(atPath: codePath) // guard let mwLocalizedStringRegex = mwLocalizedStringRegex else { // abort() // } // for filename in contents { // do { // let path = codePath + "/" + filename // let string = try String(contentsOfFile: path) // //let string = try String(contentsOf: #fileLiteral(resourceName: "WMFContentGroup+WMFFeedContentDisplaying.m")) // let mutableString = NSMutableString(string: string) // var offset = 0 // let fullRange = NSRange(location: 0, length: mutableString.length) // mwLocalizedStringRegex.enumerateMatches(in: string, options: [], range: fullRange) { (result, flags, stop) in // guard let result = result else { // return // } // let key = mwLocalizedStringRegex.replacementString(for: result, in: mutableString as String, offset: offset, template: "$1") // guard let replacement = replacements[key] else { // return // } // let replacementRange = NSRange(location: result.range.location + offset, length: result.range.length) // mutableString.replaceCharacters(in: replacementRange, with: replacement) // offset += (replacement as NSString).length - replacementRange.length // } // try mutableString.write(toFile: path, atomically: true, encoding: String.Encoding.utf8.rawValue) // } catch { } // }
mit
2e5dcc8616c7d02c4d963510cdeb6158
46.01642
545
0.599064
4.786526
false
false
false
false
danielgindi/ChartsRealm
ChartsRealm/Classes/Data/RealmBaseDataSet.swift
1
19509
// // RealmBaseDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import Charts import Realm import RealmSwift import Realm.Dynamic open class RealmBaseDataSet: ChartBaseDataSet { @objc open func initialize() { fatalError("RealmBaseDataSet is an abstract class, you must inherit from it. Also please do not call super.initialize().") } public required init() { super.init() // default color colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) initialize() } public override init(label: String?) { super.init() // default color colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) self.label = label initialize() } @objc public init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String, label: String?) { super.init() // default color colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) self.label = label _results = results _yValueField = yValueField _xValueField = xValueField if _xValueField != nil { _results = _results?.sortedResults(usingKeyPath: _xValueField!, ascending: true) } notifyDataSetChanged() initialize() } public convenience init(results: Results<Object>?, xValueField: String?, yValueField: String, label: String?) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) as? RLMResults<RLMObject> } self.init(results: converted, xValueField: xValueField, yValueField: yValueField, label: label) } @objc public convenience init(results: RLMResults<RLMObject>?, yValueField: String, label: String?) { self.init(results: results, xValueField: nil, yValueField: yValueField, label: label) } public convenience init(results: Results<Object>?, yValueField: String, label: String?) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) as? RLMResults<RLMObject> } self.init(results: converted, yValueField: yValueField, label: label) } @objc public convenience init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String) { self.init(results: results, xValueField: xValueField, yValueField: yValueField, label: "DataSet") } public convenience init(results: Results<Object>?, xValueField: String?, yValueField: String) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) as? RLMResults<RLMObject> } self.init(results: converted, xValueField: xValueField, yValueField: yValueField) } @objc public convenience init(results: RLMResults<RLMObject>?, yValueField: String) { self.init(results: results, xValueField: nil, yValueField: yValueField) } public convenience init(results: Results<Object>?, yValueField: String) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) as? RLMResults<RLMObject> } self.init(results: converted, yValueField: yValueField) } @objc public init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, label: String?) { super.init() // default color colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) self.label = label _yValueField = yValueField _xValueField = xValueField if realm != nil { loadResults(realm: realm!, modelName: modelName) } initialize() } public convenience init(realm: Realm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, label: String?) { var converted: RLMRealm? if realm != nil { converted = ObjectiveCSupport.convert(object: realm!) } self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, label: label) } @objc public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, label: String?) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, label: label) } public convenience init(realm: Realm?, modelName: String, resultsWhere: String, yValueField: String, label: String?) { var converted: RLMRealm? if realm != nil { converted = ObjectiveCSupport.convert(object: realm!) } self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, label: label) } @objc open func loadResults(realm: RLMRealm, modelName: String) { loadResults(realm: realm, modelName: modelName, predicate: nil) } @objc open func loadResults(realm: RLMRealm, modelName: String, predicate: NSPredicate?) { if predicate == nil { _results = realm.allObjects(modelName) } else { _results = realm.objects(modelName, with: predicate!) } if _xValueField != nil { _results = _results?.sortedResults(usingKeyPath: _xValueField!, ascending: true) } notifyDataSetChanged() } @nonobjc open func loadResults(realm: Realm, modelName: String) { loadResults(realm: ObjectiveCSupport.convert(object: realm), modelName: modelName) } @nonobjc open func loadResults(realm: Realm, modelName: String, predicate: NSPredicate?) { loadResults(realm: ObjectiveCSupport.convert(object: realm), modelName: modelName, predicate: predicate) } // MARK: - Data functions and accessors @objc internal var _results: RLMResults<RLMObject>? @objc internal var _yValueField: String? @objc internal var _xValueField: String? @objc internal var _cache = [ChartDataEntry]() @objc internal var _yMax: Double = -Double.greatestFiniteMagnitude @objc internal var _yMin: Double = Double.greatestFiniteMagnitude @objc internal var _xMax: Double = -Double.greatestFiniteMagnitude @objc internal var _xMin: Double = Double.greatestFiniteMagnitude /// Makes sure that the cache is populated for the specified range @objc internal func buildCache() { guard let results = _results else { return } _cache.removeAll() _cache.reserveCapacity(Int(results.count)) var xValue: Double = 0.0 var iterator = NSFastEnumerationIterator(results) while let e = iterator.next() { _cache.append(buildEntryFromResultObject(e as! RLMObject, x: xValue)) xValue += 1.0 } } @objc internal func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry { let entry = ChartDataEntry(x: _xValueField == nil ? x : object[_xValueField!] as! Double, y: object[_yValueField!] as! Double) return entry } /// Makes sure that the cache is populated for the specified range @objc internal func clearCache() { _cache.removeAll() } /// Use this method to tell the data set that the underlying data has changed open override func notifyDataSetChanged() { buildCache() calcMinMax() } open override func calcMinMax() { if _cache.count == 0 { return } _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude _xMax = -Double.greatestFiniteMagnitude _xMin = Double.greatestFiniteMagnitude for e in _cache { calcMinMax(entry: e) } } /// Updates the min and max x and y value of this DataSet based on the given Entry. /// /// - parameter e: @objc internal func calcMinMax(entry e: ChartDataEntry) { if e.y < _yMin { _yMin = e.y } if e.y > _yMax { _yMax = e.y } if e.x < _xMin { _xMin = e.x } if e.x > _xMax { _xMax = e.x } } /// - returns: The minimum y-value this DataSet holds open override var yMin: Double { return _yMin } /// - returns: The maximum y-value this DataSet holds open override var yMax: Double { return _yMax } /// - returns: The minimum x-value this DataSet holds open override var xMin: Double { return _xMin } /// - returns: The maximum x-value this DataSet holds open override var xMax: Double { return _xMax } /// - returns: The number of y-values this DataSet represents open override var entryCount: Int { return Int(_results?.count ?? 0) } /// - returns: The entry object found at the given index (not x-value!) /// - throws: out of bounds /// if `i` is out of bounds, it may throw an out-of-bounds exception open override func entryForIndex(_ i: Int) -> ChartDataEntry? { if _cache.count == 0 { buildCache() } return _cache[i] } /// - returns: The first Entry object found at the given x-value with binary search. /// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value according to the rounding. /// nil if no Entry object at that x-value. /// - parameter xValue: the x-value /// - parameter closestToY: If there are multiple y-values for the specified x-value, /// - parameter rounding: determine whether to round up/down/closest if there is no Entry matching the provided x-value open override func entryForXValue( _ xValue: Double, closestToY yValue: Double, rounding: ChartDataSetRounding) -> ChartDataEntry? { let index = self.entryIndex(x: xValue, closestToY: yValue, rounding: rounding) if index > -1 { return entryForIndex(index) } return nil } /// - returns: The first Entry object found at the given x-value with binary search. /// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value. /// nil if no Entry object at that x-value. /// - parameter xValue: the x-value /// - parameter closestToY: If there are multiple y-values for the specified x-value, open override func entryForXValue( _ xValue: Double, closestToY y: Double) -> ChartDataEntry? { return entryForXValue(xValue, closestToY: y, rounding: .closest) } /// - returns: All Entry objects found at the given x-value with binary search. /// An empty array if no Entry object at that x-value. open override func entriesForXValue(_ xValue: Double) -> [ChartDataEntry] { /*var entries = [ChartDataEntry]() guard let results = _results else { return entries } if _xValueField != nil { let foundObjects = results.objectsWithPredicate( NSPredicate(format: "%K == %f", _xValueField!, x) ) for e in foundObjects { entries.append(buildEntryFromResultObject(e as! RLMObject, x: x)) } } return entries*/ var entries = [ChartDataEntry]() var low = 0 var high = _cache.count - 1 while low <= high { var m = (high + low) / 2 var entry = _cache[m] if xValue == entry.x { while m > 0 && _cache[m - 1].x == xValue { m -= 1 } high = _cache.count while m < high { entry = _cache[m] if entry.x == xValue { entries.append(entry) } else { break } m += 1 } break } else { if xValue > entry.x { low = m + 1 } else { high = m - 1 } } } return entries } /// - returns: The array-index of the specified entry. /// If the no Entry at the specified x-value is found, this method returns the index of the Entry at the closest x-value according to the rounding. /// /// - parameter xValue: x-value of the entry to search for /// - parameter closestToY: If there are multiple y-values for the specified x-value, /// - parameter rounding: Rounding method if exact value was not found open override func entryIndex( x xValue: Double, closestToY yValue: Double, rounding: ChartDataSetRounding) -> Int { /*guard let results = _results else { return -1 } let foundIndex = results.indexOfObjectWithPredicate( NSPredicate(format: "%K == %f", _xValueField!, x) ) // TODO: Figure out a way to quickly find the closest index return Int(foundIndex)*/ var low = 0 var high = _cache.count - 1 var closest = high while low < high { let m = (low + high) / 2 let d1 = _cache[m].x - xValue let d2 = _cache[m + 1].x - xValue let ad1 = abs(d1), ad2 = abs(d2) if ad2 < ad1 { // [m + 1] is closer to xValue // Search in an higher place low = m + 1 } else if ad1 < ad2 { // [m] is closer to xValue // Search in a lower place high = m } else { // We have multiple sequential x-value with same distance if d1 >= 0.0 { // Search in a lower place high = m } else if d1 < 0.0 { // Search in an higher place low = m + 1 } } closest = high } if closest != -1 { let closestXValue = _cache[closest].x if rounding == .up { // If rounding up, and found x-value is lower than specified x, and we can go upper... if closestXValue < xValue && closest < _cache.count - 1 { closest += 1 } } else if rounding == .down { // If rounding down, and found x-value is upper than specified x, and we can go lower... if closestXValue > xValue && closest > 0 { closest -= 1 } } // Search by closest to y-value if !yValue.isNaN { while closest > 0 && _cache[closest - 1].x == closestXValue { closest -= 1 } var closestYValue = _cache[closest].y var closestYIndex = closest while true { closest += 1 if closest >= _cache.count { break } let value = _cache[closest] if value.x != closestXValue { break } if abs(value.y - yValue) < abs(closestYValue - yValue) { closestYValue = yValue closestYIndex = closest } } closest = closestYIndex } } return closest } /// - returns: The array-index of the specified entry /// /// - parameter e: the entry to search for open override func entryIndex(entry e: ChartDataEntry) -> Int { for i in 0 ..< _cache.count { if _cache[i] === e || _cache[i].isEqual(e) { return i } } return -1 } /// Not supported on Realm datasets open override func addEntry(_ e: ChartDataEntry) -> Bool { return false } /// Not supported on Realm datasets open override func addEntryOrdered(_ e: ChartDataEntry) -> Bool { return false } /// Not supported on Realm datasets open override func removeEntry(_ entry: ChartDataEntry) -> Bool { return false } /// Checks if this DataSet contains the specified Entry. /// - returns: `true` if contains the entry, `false` ifnot. open override func contains(_ e: ChartDataEntry) -> Bool { for entry in _cache { if entry.isEqual(e) { return true } } return false } /// - returns: The fieldname that represents the "y-values" in the realm-data. @objc open var yValueField: String? { get { return _yValueField } } /// - returns: The fieldname that represents the "x-values" in the realm-data. @objc open var xValueField: String? { get { return _xValueField } } // MARK: - NSCopying open override func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) as! RealmBaseDataSet copy._results = _results copy._yValueField = _yValueField copy._xValueField = _xValueField copy._yMax = _yMax copy._yMin = _yMin copy._xMax = _xMax copy._xMin = _xMin return copy } }
apache-2.0
67b25a3e6e88bb4742424c215612f848
29.340591
151
0.531139
4.95278
false
false
false
false
HongliYu/DPSlideMenuKit-Swift
DPSlideMenuKitDemo/ViewController.swift
1
2741
// // ViewController.swift // DPSlideMenuKitDemo // // Created by Hongli Yu on 8/17/16. // Copyright © 2016 Hongli Yu. All rights reserved. // import UIKit class ViewController: UIViewController { // 1. IF embed in storyboard override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? DPDrawerViewController, segue.identifier == "Main_Drawer" { DPSlideMenuManager.shared.setDrawer(drawer: destination) } } override func viewDidLoad() { super.viewDidLoad() // 2. IF NOT embed in storyboard, set drawer manually // let drawer = DPDrawerViewController() // addChild(drawer) // view.addSubview(drawer.view) // DPSlideMenuManager.shared.setDrawer(drawer: drawer) // 3. Add view controllers in the left & right side, which shall be inherited from DPBaseEmbedViewController // Tips: If the viewcontroller is not generated from storyboard, set the storyboard param to nil, // let leftMenuVCTypes = [DPTestViewController.self] // let leftMenuViewControllers = UIViewController.baseEmbedControllers(leftMenuVCTypes, storyboard: nil) // 4. Center viewcontroller shall be inherited from DPCenterContentViewController, which also can not be nil let leftMenuVCTypes = [DPTeamViewController.self, DPChannelListViewController.self, DPMessageListViewController.self] let rightMenuVCTypes = [DPSettingsViewController.self] guard let leftMenuViewControllers = UIViewController.viewControllers(leftMenuVCTypes, storyboard: "Pages") as? [DPBaseEmbedViewController], let rightMenuViewControllers = UIViewController.viewControllers(rightMenuVCTypes, storyboard: "Pages") as? [DPBaseEmbedViewController], let homeViewController = UIViewController.viewController(DPHomeViewController.self, storyboard: "Pages") as? DPHomeViewController else { return } // 5. Combine center, left, right, together. Meanwhile, left or right can be nil DPSlideMenuManager.shared.setup(homeViewController, leftContentEmbedViewControllers: leftMenuViewControllers, rightContentEmbedViewControllers: rightMenuViewControllers) } // 6. Pass status bar hide/show delegate to drawer, let drawer manager the logic open override var childForStatusBarHidden: UIViewController? { return DPSlideMenuManager.shared.drawer } public override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
mit
527d8f3d7d5b2842bdfed10fbdbc0050
38.710145
112
0.685401
5.209125
false
false
false
false
HarwordLiu/Ing.
Ing/Ing/Manager/CloudKitManager.swift
1
25988
// // HLCloudKitManager.swift // Ing // // Created by 刘浩 on 2017/8/16. // Copyright © 2017年 刘浩. All rights reserved. // import UIKit import CoreData import CloudKit import Foundation class CloudKitManager: NSObject { // MARK: Class Properties fileprivate let privateDB: CKDatabase fileprivate let coreDataManager: CoreDataManager fileprivate let operationQueue: OperationQueue // MARK: init init(coreDataManager: CoreDataManager) { self.coreDataManager = coreDataManager self.operationQueue = OperationQueue() self.operationQueue.maxConcurrentOperationCount = 1 self.privateDB = CKContainer.default().privateCloudDatabase super.init() CKContainer.default().accountStatus { [unowned self] (accountStatus, error) in switch accountStatus { case .available: self.initializeCloudKit() default: self.handleCloudKitUnavailable(accountStatus, error: error! as NSError) } } } // MARK: Public Functions func saveChangesToCloudKit(_ insertedObjects: [NSManagedObjectID], modifiedManagedObjectIDs: [NSManagedObjectID], deletedRecordIDs: [CKRecordID]) { // create the operations let createRecordsForNewObjectsOperation = CreateRecordsForNewObjectsOperation(insertedManagedObjectIDs: insertedObjects, coreDataManager: coreDataManager) let fetchModifiedRecordsOperation = FetchRecordsForModifiedObjectsOperation(coreDataManager: coreDataManager, modifiedManagedObjectIDs: modifiedManagedObjectIDs) let modifyRecordsOperation = ModifyRecordsFromManagedObjectsOperation(coreDataManager: coreDataManager, cloudKitManager: self, modifiedManagedObjectIDs: modifiedManagedObjectIDs, deletedRecordIDs: deletedRecordIDs) let clearDeletedCloudKitObjectsOperation = ClearDeletedCloudKitObjectsOperation(coreDataManager: coreDataManager) let transferCreatedRecordsOperation = BlockOperation() { [unowned modifyRecordsOperation, unowned createRecordsForNewObjectsOperation] in modifyRecordsOperation.recordsToSave = createRecordsForNewObjectsOperation.createdRecords } let transferFetchedRecordsOperation = BlockOperation() { [unowned modifyRecordsOperation, unowned fetchModifiedRecordsOperation] in modifyRecordsOperation.fetchedRecordsToModify = fetchModifiedRecordsOperation.fetchedRecords } // setup dependencies transferCreatedRecordsOperation.addDependency(createRecordsForNewObjectsOperation) transferFetchedRecordsOperation.addDependency(fetchModifiedRecordsOperation) modifyRecordsOperation.addDependency(transferCreatedRecordsOperation) modifyRecordsOperation.addDependency(transferFetchedRecordsOperation) clearDeletedCloudKitObjectsOperation.addDependency(modifyRecordsOperation) // add the operations to the queue operationQueue.addOperation(createRecordsForNewObjectsOperation) operationQueue.addOperation(transferCreatedRecordsOperation) operationQueue.addOperation(fetchModifiedRecordsOperation) operationQueue.addOperation(transferFetchedRecordsOperation) operationQueue.addOperation(modifyRecordsOperation) operationQueue.addOperation(clearDeletedCloudKitObjectsOperation) } func performFullSync() { queueFullSyncOperations() } func syncZone(_ zoneName: String, completionBlockOperation: BlockOperation) { if let cloudKitZone = CloudKitZone(rawValue: zoneName) { // suspend the queue so nothing finishes before all our dependencies are setup operationQueue.isSuspended = true // queue up the change operations for a zone let saveChangedRecordsToCoreDataOperation = queueChangeOperationsForZone(cloudKitZone, modifyRecordZonesOperation: nil) // add our completion block to the queue as well to handle background fetches completionBlockOperation.addDependency(saveChangedRecordsToCoreDataOperation) operationQueue.addOperation(completionBlockOperation) // let the queue begin firing again operationQueue.isSuspended = false } } // MARK: CloudKit Unavailable Functions fileprivate func handleCloudKitUnavailable(_ accountStatus: CKAccountStatus, error:NSError?) { cloudKitEnabled = false var errorText = "Synchronization is disabled\n" if let error = error { print("handleCloudKitUnavailable ERROR: \(error)") print("An error occured: \(error.localizedDescription)") errorText += error.localizedDescription } switch accountStatus { case .restricted: errorText += "iCloud is not available due to restrictions" case .noAccount: errorText += "There is no CloudKit account setup.\nYou can setup iCloud in the Settings app." default: break } displayCloudKitNotAvailableError(errorText) } fileprivate func displayCloudKitNotAvailableError(_ errorText: String) { if !suppressCloudKitEnabledError { DispatchQueue.main.async(execute: { let alertController = UIAlertController(title: "iCloud Synchronization Error", message: errorText, preferredStyle: UIAlertControllerStyle.alert) let firstButton = CloudKitPromptButtonType.OK let firstButtonAction = UIAlertAction(title: firstButton.rawValue, style: firstButton.actionStyle(), handler: { (action: UIAlertAction) -> Void in firstButton.performAction() }); alertController.addAction(firstButtonAction) let secondButton = CloudKitPromptButtonType.DontShowAgain let secondButtonAction = UIAlertAction(title: secondButton.rawValue, style: secondButton.actionStyle(), handler: { (action: UIAlertAction) -> Void in secondButton.performAction() }); alertController.addAction(secondButtonAction) if let appDelegate = UIApplication.shared.delegate, let appWindow = appDelegate.window!, // yes the UIWindow really is window?? - http://stackoverflow.com/questions/28901893/why-is-main-window-of-type-double-optional let rootViewController = appWindow.rootViewController { rootViewController.present(alertController, animated: true, completion: nil) } }) } } // MARK: CloudKit Init Functions fileprivate func initializeCloudKit() { print("CloudKit IS available") cloudKitEnabled = true // suspend the operation queue until all operations are created and enqueued operationQueue.isSuspended = true // self.deleteRecordZone() let modifyRecordZonesOperation = queueZoneInitilizationOperations() let modifySubscriptionsOperation = queueSubscriptionInitilizationOperations() // set the dependencies between zones and subscriptions (we need the zones to exist before any subscriptions can be created) modifySubscriptionsOperation.addDependency(modifyRecordZonesOperation) let syncAllZonesOperation = BlockOperation { [unowned self] in self.queueFullSyncOperations() } syncAllZonesOperation.addDependency(modifyRecordZonesOperation) operationQueue.addOperation(syncAllZonesOperation) // all init operations are ready, start the queue operationQueue.isSuspended = false } fileprivate func queueFullSyncOperations() { // 1. Fetch all the changes both locally and from each zone let fetchOfflineChangesFromCoreDataOperation = FetchOfflineChangesFromCoreDataOperation(coreDataManager: coreDataManager, cloudKitManager: self, entityNames: ModelObjectType.allCloudKitModelObjectTypes) let fetchTaskZoneChangesOperation = FetchRecordChangesForCloudKitZoneOperation(cloudKitZone: CloudKitZone.Task) let fetchTaskTypeZoneChangesOperation = FetchRecordChangesForCloudKitZoneOperation(cloudKitZone: CloudKitZone.TaskType) // 2. Process the changes after transfering let processSyncChangesOperation = ProcessSyncChangesOperation(coreDataManager: coreDataManager) let transferDataToProcessSyncChangesOperation = BlockOperation { [unowned processSyncChangesOperation, unowned fetchOfflineChangesFromCoreDataOperation, unowned fetchTaskZoneChangesOperation, unowned fetchTaskTypeZoneChangesOperation] in processSyncChangesOperation.preProcessLocalChangedObjectIDs.append(contentsOf: fetchOfflineChangesFromCoreDataOperation.updatedManagedObjects) processSyncChangesOperation.preProcessLocalDeletedRecordIDs.append(contentsOf: fetchOfflineChangesFromCoreDataOperation.deletedRecordIDs) processSyncChangesOperation.preProcessServerChangedRecords.append(contentsOf: fetchTaskZoneChangesOperation.changedRecords) processSyncChangesOperation.preProcessServerChangedRecords.append(contentsOf: fetchTaskTypeZoneChangesOperation.changedRecords) processSyncChangesOperation.preProcessServerDeletedRecordIDs.append(contentsOf: fetchTaskZoneChangesOperation.deletedRecordIDs) processSyncChangesOperation.preProcessServerDeletedRecordIDs.append(contentsOf: fetchTaskTypeZoneChangesOperation.deletedRecordIDs) } // 3. Fetch records from the server that we need to change let fetchRecordsForModifiedObjectsOperation = FetchRecordsForModifiedObjectsOperation(coreDataManager: coreDataManager) let transferDataToFetchRecordsOperation = BlockOperation { [unowned fetchRecordsForModifiedObjectsOperation, unowned processSyncChangesOperation] in fetchRecordsForModifiedObjectsOperation.preFetchModifiedRecords = processSyncChangesOperation.postProcessChangesToServer } // 4. Modify records in the cloud let modifyRecordsFromManagedObjectsOperation = ModifyRecordsFromManagedObjectsOperation(coreDataManager: coreDataManager, cloudKitManager: self) let transferDataToModifyRecordsOperation = BlockOperation { [unowned fetchRecordsForModifiedObjectsOperation, unowned modifyRecordsFromManagedObjectsOperation, unowned processSyncChangesOperation] in if let fetchedRecordsDictionary = fetchRecordsForModifiedObjectsOperation.fetchedRecords { modifyRecordsFromManagedObjectsOperation.fetchedRecordsToModify = fetchedRecordsDictionary } modifyRecordsFromManagedObjectsOperation.preModifiedRecords = processSyncChangesOperation.postProcessChangesToServer // also set the recordIDsToDelete from what we processed modifyRecordsFromManagedObjectsOperation.recordIDsToDelete = processSyncChangesOperation.postProcessDeletesToServer } // 5. Modify records locally let saveChangedRecordsToCoreDataOperation = SaveChangedRecordsToCoreDataOperation(coreDataManager: coreDataManager) let transferDataToSaveChangesToCoreDataOperation = BlockOperation { [unowned saveChangedRecordsToCoreDataOperation, unowned processSyncChangesOperation] in saveChangedRecordsToCoreDataOperation.changedRecords = processSyncChangesOperation.postProcessChangesToCoreData saveChangedRecordsToCoreDataOperation.deletedRecordIDs = processSyncChangesOperation.postProcessDeletesToCoreData } // 6. Delete all of the DeletedCloudKitObjects let clearDeletedCloudKitObjectsOperation = ClearDeletedCloudKitObjectsOperation(coreDataManager: coreDataManager) // set dependencies // 1. transfering all the fetched data to process for conflicts transferDataToProcessSyncChangesOperation.addDependency(fetchOfflineChangesFromCoreDataOperation) transferDataToProcessSyncChangesOperation.addDependency(fetchTaskZoneChangesOperation) transferDataToProcessSyncChangesOperation.addDependency(fetchTaskTypeZoneChangesOperation) // 2. processing the data onces its transferred processSyncChangesOperation.addDependency(transferDataToProcessSyncChangesOperation) // 3. fetching records changed local transferDataToFetchRecordsOperation.addDependency(processSyncChangesOperation) fetchRecordsForModifiedObjectsOperation.addDependency(transferDataToFetchRecordsOperation) // 4. modifying records in CloudKit transferDataToModifyRecordsOperation.addDependency(fetchRecordsForModifiedObjectsOperation) modifyRecordsFromManagedObjectsOperation.addDependency(transferDataToModifyRecordsOperation) // 5. modifying records in CoreData transferDataToSaveChangesToCoreDataOperation.addDependency(processSyncChangesOperation) saveChangedRecordsToCoreDataOperation.addDependency(transferDataToModifyRecordsOperation) // 6. clear the deleteCloudKitObjects clearDeletedCloudKitObjectsOperation.addDependency(saveChangedRecordsToCoreDataOperation) // add operations to the queue operationQueue.addOperation(fetchOfflineChangesFromCoreDataOperation) operationQueue.addOperation(fetchTaskZoneChangesOperation) operationQueue.addOperation(fetchTaskTypeZoneChangesOperation) operationQueue.addOperation(transferDataToProcessSyncChangesOperation) operationQueue.addOperation(processSyncChangesOperation) operationQueue.addOperation(transferDataToFetchRecordsOperation) operationQueue.addOperation(fetchRecordsForModifiedObjectsOperation) operationQueue.addOperation(transferDataToModifyRecordsOperation) operationQueue.addOperation(modifyRecordsFromManagedObjectsOperation) operationQueue.addOperation(transferDataToSaveChangesToCoreDataOperation) operationQueue.addOperation(saveChangedRecordsToCoreDataOperation) operationQueue.addOperation(clearDeletedCloudKitObjectsOperation) } // MARK: RecordZone Functions fileprivate func queueZoneInitilizationOperations() -> CKModifyRecordZonesOperation { // 1. Fetch all the zones // 2. Process the returned zones and create arrays for zones that need creating and those that need deleting // 3. Modify the zones in cloudkit let fetchAllRecordZonesOperation = FetchAllRecordZonesOperation.fetchAllRecordZonesOperation() let processServerRecordZonesOperation = ProcessServerRecordZonesOperation() let modifyRecordZonesOperation = createModifyRecordZoneOperation(nil, recordZoneIDsToDelete: nil) let transferFetchedZonesOperation = BlockOperation() { [unowned fetchAllRecordZonesOperation, unowned processServerRecordZonesOperation] in if let fetchedRecordZones = fetchAllRecordZonesOperation.fetchedRecordZones { processServerRecordZonesOperation.preProcessRecordZoneIDs = Array(fetchedRecordZones.keys) } } let transferProcessedZonesOperation = BlockOperation() { [unowned modifyRecordZonesOperation, unowned processServerRecordZonesOperation] in modifyRecordZonesOperation.recordZonesToSave = processServerRecordZonesOperation.postProcessRecordZonesToCreate modifyRecordZonesOperation.recordZoneIDsToDelete = processServerRecordZonesOperation.postProcessRecordZoneIDsToDelete } transferFetchedZonesOperation.addDependency(fetchAllRecordZonesOperation) processServerRecordZonesOperation.addDependency(transferFetchedZonesOperation) transferProcessedZonesOperation.addDependency(processServerRecordZonesOperation) modifyRecordZonesOperation.addDependency(transferProcessedZonesOperation) operationQueue.addOperation(fetchAllRecordZonesOperation) operationQueue.addOperation(transferFetchedZonesOperation) operationQueue.addOperation(processServerRecordZonesOperation) operationQueue.addOperation(transferProcessedZonesOperation) operationQueue.addOperation(modifyRecordZonesOperation) return modifyRecordZonesOperation } fileprivate func deleteRecordZone() { let fetchAllRecordZonesOperation = FetchAllRecordZonesOperation.fetchAllRecordZonesOperation() let modifyRecordZonesOperation = createModifyRecordZoneOperation(nil, recordZoneIDsToDelete: nil) let dataTransferOperation = BlockOperation() { [unowned modifyRecordZonesOperation, unowned fetchAllRecordZonesOperation] in if let fetchedRecordZones = fetchAllRecordZonesOperation.fetchedRecordZones { modifyRecordZonesOperation.recordZoneIDsToDelete = Array(fetchedRecordZones.keys) } } dataTransferOperation.addDependency(fetchAllRecordZonesOperation) modifyRecordZonesOperation.addDependency(dataTransferOperation) operationQueue.addOperation(fetchAllRecordZonesOperation) operationQueue.addOperation(dataTransferOperation) operationQueue.addOperation(modifyRecordZonesOperation) } // MARK: Subscription Functions fileprivate func queueSubscriptionInitilizationOperations() -> CKModifySubscriptionsOperation { // 1. Fetch all subscriptions // 2. Process which need to be created and which need to be deleted // 3. Make the adjustments in iCloud let fetchAllSubscriptionsOperation = FetchAllSubscriptionsOperation.fetchAllSubscriptionsOperation() let processServerSubscriptionsOperation = ProcessServerSubscriptionsOperation() let modifySubscriptionsOperation = createModifySubscriptionOperation() let transferFetchedSubscriptionsOperation = BlockOperation() { [unowned processServerSubscriptionsOperation, unowned fetchAllSubscriptionsOperation] in processServerSubscriptionsOperation.preProcessFetchedSubscriptions = fetchAllSubscriptionsOperation.fetchedSubscriptions } let transferProcessedSubscriptionsOperation = BlockOperation() { [unowned modifySubscriptionsOperation, unowned processServerSubscriptionsOperation] in modifySubscriptionsOperation.subscriptionsToSave = processServerSubscriptionsOperation.postProcessSubscriptionsToCreate modifySubscriptionsOperation.subscriptionIDsToDelete = processServerSubscriptionsOperation.postProcessSubscriptionIDsToDelete } transferFetchedSubscriptionsOperation.addDependency(fetchAllSubscriptionsOperation) processServerSubscriptionsOperation.addDependency(transferFetchedSubscriptionsOperation) transferProcessedSubscriptionsOperation.addDependency(processServerSubscriptionsOperation) modifySubscriptionsOperation.addDependency(transferProcessedSubscriptionsOperation) operationQueue.addOperation(fetchAllSubscriptionsOperation) operationQueue.addOperation(transferFetchedSubscriptionsOperation) operationQueue.addOperation(processServerSubscriptionsOperation) operationQueue.addOperation(transferProcessedSubscriptionsOperation) operationQueue.addOperation(modifySubscriptionsOperation) return modifySubscriptionsOperation } // MARK: Sync Records fileprivate func queueChangeOperationsForZone(_ cloudKitZone: CloudKitZone, modifyRecordZonesOperation: CKModifyRecordZonesOperation?) -> SaveChangedRecordsToCoreDataOperation { // there are two operations that need to be chained together for each zone // the first is to fetch record changes // the second is to save those changes to CoreData // we'll also need a block operation to transfer data between them let fetchRecordChangesOperation = FetchRecordChangesForCloudKitZoneOperation(cloudKitZone: cloudKitZone) let saveChangedRecordsToCoreDataOperation = SaveChangedRecordsToCoreDataOperation(coreDataManager: coreDataManager) let dataTransferOperation = BlockOperation() { [unowned saveChangedRecordsToCoreDataOperation, unowned fetchRecordChangesOperation] in print("addChangeOperationsForZone.dataTransferOperation") saveChangedRecordsToCoreDataOperation.changedRecords = fetchRecordChangesOperation.changedRecords saveChangedRecordsToCoreDataOperation.deletedRecordIDs = fetchRecordChangesOperation.deletedRecordIDs } // set the dependencies if let modifyRecordZonesOperation = modifyRecordZonesOperation { fetchRecordChangesOperation.addDependency(modifyRecordZonesOperation) } dataTransferOperation.addDependency(fetchRecordChangesOperation) saveChangedRecordsToCoreDataOperation.addDependency(dataTransferOperation) // add the operations to the queue operationQueue.addOperation(fetchRecordChangesOperation) operationQueue.addOperation(dataTransferOperation) operationQueue.addOperation(saveChangedRecordsToCoreDataOperation) return saveChangedRecordsToCoreDataOperation } // MARK: Create Operation Helper Functions fileprivate func createModifyRecordZoneOperation(_ recordZonesToSave: [CKRecordZone]?, recordZoneIDsToDelete: [CKRecordZoneID]?) -> CKModifyRecordZonesOperation { let modifyRecordZonesOperation = CKModifyRecordZonesOperation(recordZonesToSave: recordZonesToSave, recordZoneIDsToDelete: recordZoneIDsToDelete) modifyRecordZonesOperation.modifyRecordZonesCompletionBlock = { (modifiedRecordZones: [CKRecordZone]?, deletedRecordZoneIDs: [CKRecordZoneID]?, error: NSError?) -> Void in print("--- CKModifyRecordZonesOperation.modifyRecordZonesOperation") if let error = error { print("createModifyRecordZoneOperation ERROR: \(error)") return } if let modifiedRecordZones = modifiedRecordZones { for recordZone in modifiedRecordZones { print("Modified recordZone: \(recordZone)") } } if let deletedRecordZoneIDs = deletedRecordZoneIDs { for zoneID in deletedRecordZoneIDs { print("Deleted zoneID: \(zoneID)") } } } as? ([CKRecordZone]?, [CKRecordZoneID]?, Error?) -> Void return modifyRecordZonesOperation } fileprivate func createModifySubscriptionOperation() -> CKModifySubscriptionsOperation { let modifySubscriptionsOperation = CKModifySubscriptionsOperation() modifySubscriptionsOperation.modifySubscriptionsCompletionBlock = { (modifiedSubscriptions: [CKSubscription]?, deletedSubscriptionIDs: [String]?, error: NSError?) -> Void in print("--- CKModifySubscriptionsOperation.modifySubscriptionsCompletionBlock") if let error = error { print("createModifySubscriptionOperation ERROR: \(error)") return } if let modifiedSubscriptions = modifiedSubscriptions { for subscription in modifiedSubscriptions { print("Modified subscription: \(subscription)") } } if let deletedSubscriptionIDs = deletedSubscriptionIDs { for subscriptionID in deletedSubscriptionIDs { print("Deleted subscriptionID: \(subscriptionID)") } } } as? ([CKSubscription]?, [String]?, Error?) -> Void return modifySubscriptionsOperation } // MARK: NSUserDefault Properties var lastCloudKitSyncTimestamp: Date { get { if let lastCloudKitSyncTimestamp = UserDefaults.standard.object(forKey: CloudKitUserDefaultKeys.LastCloudKitSyncTimestamp.rawValue) as? Date { return lastCloudKitSyncTimestamp } else { return Date.distantPast } } set { UserDefaults.standard.set(newValue, forKey: CloudKitUserDefaultKeys.LastCloudKitSyncTimestamp.rawValue) } } fileprivate var cloudKitEnabled: Bool { get { return UserDefaults.standard.bool(forKey: CloudKitUserDefaultKeys.CloudKitEnabledKey.rawValue) } set { UserDefaults.standard.set(newValue, forKey: CloudKitUserDefaultKeys.CloudKitEnabledKey.rawValue) } } fileprivate var suppressCloudKitEnabledError: Bool { get { return UserDefaults.standard.bool(forKey: CloudKitUserDefaultKeys.SuppressCloudKitErrorKey.rawValue) } } }
mit
fca7b2fe3a14fdb2dc97da65b3a0ce37
49.935294
222
0.717019
6.393552
false
false
false
false
kay-kim/stitch-examples
todo/ios/MongoDBSample/Classes/AppDelegate/AppDelegate.swift
1
4926
// // AppDelegate.swift // MongoDBSample // // import UIKit import FBSDKLoginKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Facebook FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: open url func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { var openUrl = GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) || FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options) if !openUrl && url.scheme! == "stitchtodo" { openUrl = true if let navVC = window?.rootViewController as? UINavigationController, let todoVC = navVC.topViewController as? TodoListViewController{ let components = URLComponents(url: url, resolvingAgainstBaseURL: false) guard let queryItems = components?.queryItems else { return false } var params: [String : String] = [:] for item in queryItems { params[item.name] = item.value } guard let token = params["token"], let tokenId = params["tokenId"] else { return false } if let host = url.host { var emailAuthOpType: EmailAuthOperationType? if host == "confirmEmail" { emailAuthOpType = .confirmEmail(token: token, tokenId: tokenId) } if host == "resetPassword" { emailAuthOpType = .resetPassword(token: token, tokenId: tokenId) } guard let emailAuthOperationType = emailAuthOpType else { return false } if todoVC.isViewLoaded { todoVC.presentEmailAuthViewController(operationType: emailAuthOperationType) } else { todoVC.emailAuthOpToPresentWhenOpened = emailAuthOperationType } } } } return openUrl } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation) || FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) } }
apache-2.0
348fd397ecd04ef9eaa6c98ea00aee48
46.825243
304
0.631547
6.235443
false
false
false
false
mastahyeti/SoftU2F
APDU/AuthenticationRequest.swift
2
2250
// // AuthenticationRequest.swift // SoftU2F // // Created by Benjamin P Toews on 9/14/16. // import Foundation public struct AuthenticationRequest: RawConvertible { public let header: CommandHeader public let body: Data public let trailer: CommandTrailer public var control: Control { return Control(rawValue: header.p1) ?? .Invalid } public var challengeParameter: Data { let lowerBound = 0 let upperBound = lowerBound + U2F_CHAL_SIZE return body.subdata(in: lowerBound..<upperBound) } public var applicationParameter: Data { let lowerBound = U2F_CHAL_SIZE let upperBound = lowerBound + U2F_APPID_SIZE return body.subdata(in: lowerBound..<upperBound) } var keyHandleLength: Int { return Int(body[U2F_CHAL_SIZE + U2F_APPID_SIZE]) } public var keyHandle: Data { let lowerBound = U2F_CHAL_SIZE + U2F_APPID_SIZE + 1 let upperBound = lowerBound + keyHandleLength return body.subdata(in: lowerBound..<upperBound) } public init(challengeParameter: Data, applicationParameter: Data, keyHandle: Data, control: Control) { let writer = DataWriter() writer.writeData(challengeParameter) writer.writeData(applicationParameter) writer.write(UInt8(keyHandle.count)) writer.writeData(keyHandle) self.body = writer.buffer self.header = CommandHeader(ins: .Authenticate, p1: control.rawValue, dataLength: body.count) self.trailer = CommandTrailer(noBody: false) } } extension AuthenticationRequest: Command { public init(header: CommandHeader, body: Data, trailer: CommandTrailer) { self.header = header self.body = body self.trailer = trailer } public func validateBody() throws { // Make sure it's at least long enough to have key-handle length. if body.count < U2F_CHAL_SIZE + U2F_APPID_SIZE + 1 { throw ResponseStatus.WrongLength } if body.count != U2F_CHAL_SIZE + U2F_APPID_SIZE + 1 + keyHandleLength { throw ResponseStatus.WrongLength } if control == .Invalid { throw ResponseStatus.OtherError } } }
mit
97e4cd7f4c341ac00de07dea79ae7751
29
106
0.650667
4.166667
false
false
false
false
bhadresh13/BMNYearPicker
BMNYearPicker/ViewController.swift
1
1120
// // ViewController.swift // BMNYearPicker // // Created by Harry on 6/16/16. // Copyright © 2016 Harry. All rights reserved. // import UIKit class ViewController: UIViewController, BMNYearPickerViewDelegate { @IBOutlet weak var lblPickerValue: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func btnOpenPickerClicked(sender: AnyObject) { let picker : BMNYearPicker = BMNYearPicker() picker.startYear = 2000 picker.endYear = 2016 picker.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext picker.delegate = self self.presentViewController(picker, animated: true, completion: nil) } //MARK: - PICKER DELEGATE func pickerCancel() { } func pickerDone(year: String) { self.lblPickerValue.text = "\(year)" } }
mit
e33f1e7058c786bfc25c393cc52d7c4d
24.431818
83
0.659517
4.6625
false
false
false
false
yuppielabel/YPMagnifyingGlass
source/YPMagnifyingGlass.swift
2
2169
// // YPMagnifyingGlass.swift // YPMagnifyingGlass // // Created by Geert-Jan Nilsen on 02/06/15. // Copyright (c) 2015 Yuppielabel.com All rights reserved. // import UIKit import QuartzCore public class YPMagnifyingGlass: UIView { public var viewToMagnify: UIView! public var touchPoint: CGPoint! { didSet { self.center = CGPoint(x: touchPoint.x + touchPointOffset.x, y: touchPoint.y + touchPointOffset.y) } } public var touchPointOffset: CGPoint! public var scale: CGFloat! public var scaleAtTouchPoint: Bool! public var YPMagnifyingGlassDefaultRadius: CGFloat = 40.0 public var YPMagnifyingGlassDefaultOffset: CGFloat = -40.0 public var YPMagnifyingGlassDefaultScale: CGFloat = 2.0 public func initViewToMagnify(viewToMagnify: UIView, touchPoint: CGPoint, touchPointOffset: CGPoint, scale: CGFloat, scaleAtTouchPoint: Bool) { self.viewToMagnify = viewToMagnify self.touchPoint = touchPoint self.touchPointOffset = touchPointOffset self.scale = scale self.scaleAtTouchPoint = scaleAtTouchPoint } required public convenience init(coder aDecoder: NSCoder) { self.init(coder: aDecoder) } required public override init(frame: CGRect) { super.init(frame: frame) self.layer.borderColor = UIColor.lightGray.cgColor self.layer.borderWidth = 3 self.layer.cornerRadius = frame.size.width / 2 self.layer.masksToBounds = true self.touchPointOffset = CGPoint(x: 0, y: YPMagnifyingGlassDefaultOffset) self.scale = YPMagnifyingGlassDefaultScale self.viewToMagnify = nil self.scaleAtTouchPoint = true } private func setFrame(frame: CGRect) { super.frame = frame self.layer.cornerRadius = frame.size.width / 2 } public override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext()! context.translateBy(x: self.frame.size.width/2, y: self.frame.size.height/2) context.scaleBy(x: self.scale, y: self.scale) context.translateBy(x: -self.touchPoint.x, y: -self.touchPoint.y + (self.scaleAtTouchPoint != nil ? 0 : self.bounds.size.height/2)) self.viewToMagnify.layer.render(in: context) } }
mit
3911a5e65b1a789931c381c3de8f340b
30.897059
145
0.724297
3.811951
false
false
false
false
wl879/SwiftyCss
SwiftyCss/SwiftyNode/Creater/Creater.swift
1
5335
// Created by Wang Liang on 2017/4/8. // Copyright © 2017年 Wang Liang. All rights reserved. import UIKit import SwiftyBox public func NodeParser(text: String, appendTo parent: NodeProtocol? = nil, object: AnyClass? = nil, parser: [String: AnyClass]? = nil) -> [NodeProtocol]? { return NodeParser(lines: Re.lexer(code: text, separator: "\n"), appendTo: parent, object: object, parser: parser) } public func NodeParser(lines: [String], appendTo parent: NodeProtocol? = nil, object: AnyClass? = nil, parser: [String: AnyClass]? = nil) -> [NodeProtocol]? { var attrs = [Int: [String]]() var parser = parser ?? [:] if object != nil { parser["default"] = object } if var nodes = _parseJade(lines: lines, attrs: &attrs, parser: &parser) { if let parent = parent { for node in nodes { parent.addChild(node) } } _checkAttribute(&attrs, nodes: &nodes) return nodes } return nil } // MARK: - Private private let _jade_syntax = Re("^([ \t]*)(.+) *$") private let _bundle_name = Bundle.main.infoDictionary!["CFBundleName"] as? String private var _object_cache: [String: AnyClass] = [:] private func _parseJade(lines: [String], attrs: inout [Int: [String]], parser: inout [String: AnyClass]) -> [NodeProtocol]?{ var res = [NodeProtocol]() var level = -1 var level_stack = [Int]() var parent_stack = [NodeProtocol]() for line in lines { guard let m = _jade_syntax.match(line), let text = m[2] else{ continue } let nodes = _createByText(text, &attrs, &parser) let indent = m[1]!.replacingOccurrences(of: "\t", with: " ").characters.count if level == -1 { level_stack.append( indent ) }else if indent > level_stack[level] { level_stack.append( indent ) }else if indent < level_stack[level] { while level >= 0 && indent <= level_stack[level] { level_stack.removeLast() level = level_stack.count - 1 if parent_stack.count > 0 { parent_stack.removeLast() } } level_stack.append(indent) }else{ parent_stack.removeLast() } level = level_stack.count - 1 if parent_stack.count > 0 { for node in nodes { parent_stack.last!.addChild(node) } }else{ res += nodes } parent_stack.append(nodes.last!) } return res.isEmpty ? nil : res } private func _createByText(_ text: String, _ attrs: inout [Int: [String]], _ parser: inout [String: AnyClass]) -> [NodeProtocol] { let selector = Select(text: text, byCreater: true) var res = [NodeProtocol]() var tar: NodeProtocol? = nil for rule in selector.rules { guard let node = _createByTag(rule.tag, rule.id, rule.clas, &parser) else { fatalError("[SwiftyNode Creater Error] pattern error: \(selector.description)") } attrs[node.hash] = rule.attributes if rule.combinator == "+" { tar = tar?.parentNode }else if rule.combinator == "~" { tar = tar?.parentNode?.parentNode } if tar != nil { tar!.addChild( node ) }else{ res.append(node) } tar = node } assert(res.isEmpty == false, "[SwiftyNode Creater Error] pattern error: \(selector.description)") return res } private func _createByTag(_ tag: String?, _ id: String? = nil, _ clas: Set<String>? = nil, _ parser: inout [String: AnyClass]) -> NodeProtocol? { var type: AnyClass? if let tag = tag, String.isCapital(tag[0]!) { type = parser[tag] ?? _object_cache[tag] if type == nil { type = NSClassFromString(tag) if type == nil { type = NSClassFromString(_bundle_name! + "." + tag) } _object_cache[tag] = type if type == nil { type = parser["default"] } } }else{ type = parser["default"] } if let type = type as? NodeProtocol.Type { let node = type.init() if tag != nil { node.tagName = tag! } if id != nil { node.idName = id! } if clas != nil { node.classNames = clas! } return node } return nil } private func _checkAttribute(_ cache: inout [Int: [String]], nodes: inout [NodeProtocol]) { for node in nodes { if let attr = cache[node.hash] { cache[node.hash] = nil for str in attr { if let kv = str.components(separatedBy: "=", atAfter: 0, trim: .whitespacesAndNewlines) { if kv.count == 2 { node.setAttribute(kv[0], value: kv[1]) } }else{ node.setAttribute("style", value: str) } } } if cache.isEmpty { return } if var children = node.childNodes { _checkAttribute(&cache, nodes: &children) } } }
mit
c09745ffaa50a8180f49bff48cc239a1
31.120482
158
0.521755
4.120556
false
false
false
false
adauguet/ClusterMapView
Example/Example/Toilet.swift
1
650
import Foundation import MapKit public final class Toilet: NSObject, MKAnnotation { var name: String public var coordinate: CLLocationCoordinate2D public required init?(json: [String : Any]) { guard let name = json["name"] as? String, let coordinate = json["coordinates"] as? [String : Any], let latitude = coordinate["latitude"] as? Double, let longitude = coordinate["longitude"] as? Double else { return nil } self.name = name self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } } extension Toilet: JSONInstantiable {}
mit
c15152fed89d2a03daf945fd74cc2ffc
33.210526
90
0.652308
4.710145
false
false
false
false
filipealva/WWDC15-Scholarship
Filipe Alvarenga/Model/CustomAppearance.swift
1
936
// // CustomAppearance.swift // Filipe Alvarenga // // Created by Filipe Alvarenga on 25/04/15. // Copyright (c) 2015 Filipe Alvarenga. All rights reserved. // import Foundation /** Custom Appearance structure. Contains all attributes and methods required to apply custom appearance who are not related to a component or a class. - parameter navFont: The font style used in the navigation bar title */ struct CustomAppearance { static let navFont = UIFont(name: "OpenSans-Bold", size: 17.0)! static func applyCustomAppearanceToNavigationBar() { UINavigationBar.appearance().translucent = false UINavigationBar.appearance().barTintColor = UIColor.whiteColor() UINavigationBar.appearance().tintColor = UIColor.blackColor() UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: navFont, NSForegroundColorAttributeName: UIColor.blackColor()] } }
mit
c51d81c5c40356e4808b9cb5311e092a
31.310345
151
0.730769
5.005348
false
false
false
false
salemoh/GoldenQuraniOS
GoldenQuranSwift/Pods/GRDB.swift/GRDB/QueryInterface/VirtualTableModule.swift
2
4660
/// The protocol for SQLite virtual table modules. It lets you define a DSL for /// the `Database.create(virtualTable:using:)` method: /// /// let module = ... /// try db.create(virtualTable: "items", using: module) { t in /// ... /// } /// /// GRDB ships with three concrete classes that implement this protocol: FTS3, /// FTS4 and FTS5. public protocol VirtualTableModule { /// The type of the closure argument in the /// `Database.create(virtualTable:using:)` method: /// /// try db.create(virtualTable: "items", using: module) { t in /// // t is TableDefinition /// } associatedtype TableDefinition /// The name of the module. var moduleName: String { get } /// Returns a table definition that is passed as the closure argument in the /// `Database.create(virtualTable:using:)` method: /// /// try db.create(virtualTable: "items", using: module) { t in /// // t is the result of makeTableDefinition() /// } func makeTableDefinition() -> TableDefinition /// Returns the module arguments for the `CREATE VIRTUAL TABLE` query. func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String] /// Execute any relevant database statement after the virtual table has /// been created. func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws } extension Database { // MARK: - Database Schema: Virtual Table /// Creates a virtual database table. /// /// try db.create(virtualTable: "vocabulary", using: "spellfix1") /// /// See https://www.sqlite.org/lang_createtable.html /// /// - parameters: /// - name: The table name. /// - ifNotExists: If false, no error is thrown if table already exists. /// - module: The name of an SQLite virtual table module. /// - throws: A DatabaseError whenever an SQLite error occurs. public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws { var chunks: [String] = [] chunks.append("CREATE VIRTUAL TABLE") if ifNotExists { chunks.append("IF NOT EXISTS") } chunks.append(name.quotedDatabaseIdentifier) chunks.append("USING") chunks.append(module) let sql = chunks.joined(separator: " ") try execute(sql) } /// Creates a virtual database table. /// /// let module = ... /// try db.create(virtualTable: "pointOfInterests", using: module) { t in /// ... /// } /// /// The type of the closure argument `t` depends on the type of the module /// argument: refer to this module's documentation. /// /// Use this method to create full-text tables using the FTS3, FTS4, or /// FTS5 modules: /// /// try db.create(virtualTable: "books", using: FTS4()) { t in /// t.column("title") /// t.column("author") /// t.column("body") /// } /// /// See https://www.sqlite.org/lang_createtable.html /// /// - parameters: /// - name: The table name. /// - ifNotExists: If false, no error is thrown if table already exists. /// - module: a VirtualTableModule /// - body: An optional closure that defines the virtual table. /// - throws: A DatabaseError whenever an SQLite error occurs. public func create<Module: VirtualTableModule>(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) throws { // Define virtual table let definition = module.makeTableDefinition() if let body = body { body(definition) } // Create virtual table var chunks: [String] = [] chunks.append("CREATE VIRTUAL TABLE") if ifNotExists { chunks.append("IF NOT EXISTS") } chunks.append(tableName.quotedDatabaseIdentifier) chunks.append("USING") let arguments = try module.moduleArguments(for: definition, in: self) if arguments.isEmpty { chunks.append(module.moduleName) } else { chunks.append(module.moduleName + "(" + arguments.joined(separator: ", ") + ")") } let sql = chunks.joined(separator: " ") try inSavepoint { try execute(sql) try module.database(self, didCreate: tableName, using: definition) return .commit } } }
mit
d2e929e3873b18f30fec9e7b0e963d96
36.580645
191
0.594421
4.467881
false
false
false
false
e78l/swift-corelibs-foundation
TestFoundation/TestBundle.swift
1
23986
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT #if canImport(SwiftFoundation) && !DEPLOYMENT_RUNTIME_OBJC @testable import SwiftFoundation #else @testable import Foundation #endif #endif internal func testBundle() -> Bundle { #if DARWIN_COMPATIBILITY_TESTS for bundle in Bundle.allBundles { if let bundleId = bundle.bundleIdentifier, bundleId == "org.swift.DarwinCompatibilityTests", bundle.resourcePath != nil { return bundle } } fatalError("Cant find test bundle") #else return Bundle.main #endif } #if DARWIN_COMPATIBILITY_TESTS extension Bundle { static let _supportsFreestandingBundles = false static let _supportsFHSBundles = false } #endif internal func testBundleName() -> String { // Either 'TestFoundation' or 'DarwinCompatibilityTests' return testBundle().infoDictionary!["CFBundleName"] as! String } internal func xdgTestHelperURL() -> URL { guard let url = testBundle().url(forAuxiliaryExecutable: "xdgTestHelper") else { fatalError("Cant find xdgTestHelper") } return url } class BundlePlayground { enum ExecutableType: CaseIterable { case library case executable var pathExtension: String { switch self { case .library: #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) return "dylib" #elseif os(Windows) return "dll" #else return "so" #endif case .executable: #if os(Windows) return "exe" #else return "" #endif } } var flatPathExtension: String { #if os(Windows) return self.pathExtension #else return "" #endif } var fhsPrefix: String { switch self { case .executable: return "bin" case .library: return "lib" } } var nonFlatFilePrefix: String { switch self { case .executable: return "" case .library: return "lib" } } } enum Layout { case flat(ExecutableType) case fhs(ExecutableType) case freestanding(ExecutableType) static var allApplicable: [Layout] { let layouts: [Layout] = [ .flat(.library), .flat(.executable), .fhs(.library), .fhs(.executable), .freestanding(.library), .freestanding(.executable), ] return layouts.filter { $0.isSupported } } var isFreestanding: Bool { switch self { case .freestanding(_): return true default: return false } } var isFHS: Bool { switch self { case .fhs(_): return true default: return false } } var isFlat: Bool { switch self { case .flat(_): return true default: return false } } var isSupported: Bool { switch self { case .flat(_): return true case .freestanding(_): return Bundle._supportsFreestandingBundles case .fhs(_): return Bundle._supportsFHSBundles } } } let bundleName: String let bundleExtension: String let resourceFilenames: [String] let resourceSubdirectory: String let subdirectoryResourcesFilenames: [String] let auxiliaryExecutableName: String let layout: Layout private(set) var bundlePath: String! private(set) var mainExecutableURL: URL! private var playgroundPath: String? init?(bundleName: String, bundleExtension: String, resourceFilenames: [String], resourceSubdirectory: String, subdirectoryResourcesFilenames: [String], auxiliaryExecutableName: String, layout: Layout) { self.bundleName = bundleName self.bundleExtension = bundleExtension self.resourceFilenames = resourceFilenames self.resourceSubdirectory = resourceSubdirectory self.subdirectoryResourcesFilenames = subdirectoryResourcesFilenames self.auxiliaryExecutableName = auxiliaryExecutableName self.layout = layout if !_create() { destroy() return nil } } private func _create() -> Bool { // Make sure the directory is uniquely named let temporaryDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("TestFoundation_Playground_" + UUID().uuidString) switch layout { case .flat(let executableType): do { try FileManager.default.createDirectory(atPath: temporaryDirectory.path, withIntermediateDirectories: false, attributes: nil) // Make a flat bundle in the playground let bundleURL = temporaryDirectory.appendingPathComponent(bundleName).appendingPathExtension(self.bundleExtension) try FileManager.default.createDirectory(atPath: bundleURL.path, withIntermediateDirectories: false, attributes: nil) // Make a main and an auxiliary executable: self.mainExecutableURL = bundleURL .appendingPathComponent(bundleName) .appendingPathExtension(executableType.flatPathExtension) guard FileManager.default.createFile(atPath: mainExecutableURL.path, contents: nil) else { return false } let auxiliaryExecutableURL = bundleURL .appendingPathComponent(auxiliaryExecutableName) .appendingPathExtension(executableType.flatPathExtension) guard FileManager.default.createFile(atPath: auxiliaryExecutableURL.path, contents: nil) else { return false } // Put some resources in the bundle for resourceName in resourceFilenames { guard FileManager.default.createFile(atPath: bundleURL.appendingPathComponent(resourceName).path, contents: nil, attributes: nil) else { return false } } // Add a resource into a subdirectory let subdirectoryURL = bundleURL.appendingPathComponent(resourceSubdirectory) try FileManager.default.createDirectory(atPath: subdirectoryURL.path, withIntermediateDirectories: false, attributes: nil) for resourceName in subdirectoryResourcesFilenames { guard FileManager.default.createFile(atPath: subdirectoryURL.appendingPathComponent(resourceName).path, contents: nil, attributes: nil) else { return false } } self.bundlePath = bundleURL.path } catch { return false } case .fhs(let executableType): do { // Create a FHS /usr/local-style hierarchy: try FileManager.default.createDirectory(atPath: temporaryDirectory.path, withIntermediateDirectories: false, attributes: nil) try FileManager.default.createDirectory(atPath: temporaryDirectory.appendingPathComponent("share").path, withIntermediateDirectories: false, attributes: nil) try FileManager.default.createDirectory(atPath: temporaryDirectory.appendingPathComponent("lib").path, withIntermediateDirectories: false, attributes: nil) // Make a main and an auxiliary executable: self.mainExecutableURL = temporaryDirectory .appendingPathComponent(executableType.fhsPrefix) .appendingPathComponent(executableType.nonFlatFilePrefix + bundleName) .appendingPathExtension(executableType.pathExtension) guard FileManager.default.createFile(atPath: mainExecutableURL.path, contents: nil) else { return false } let executablesDirectory = temporaryDirectory.appendingPathComponent("libexec").appendingPathComponent("\(bundleName).executables") try FileManager.default.createDirectory(atPath: executablesDirectory.path, withIntermediateDirectories: true, attributes: nil) let auxiliaryExecutableURL = executablesDirectory .appendingPathComponent(executableType.nonFlatFilePrefix + auxiliaryExecutableName) .appendingPathExtension(executableType.pathExtension) guard FileManager.default.createFile(atPath: auxiliaryExecutableURL.path, contents: nil) else { return false } // Make a .resources directory in …/share: let resourcesDirectory = temporaryDirectory.appendingPathComponent("share").appendingPathComponent("\(bundleName).resources") try FileManager.default.createDirectory(atPath: resourcesDirectory.path, withIntermediateDirectories: false, attributes: nil) // Put some resources in the bundle for resourceName in resourceFilenames { guard FileManager.default.createFile(atPath: resourcesDirectory.appendingPathComponent(resourceName).path, contents: nil, attributes: nil) else { return false } } // Add a resource into a subdirectory let subdirectoryURL = resourcesDirectory.appendingPathComponent(resourceSubdirectory) try FileManager.default.createDirectory(atPath: subdirectoryURL.path, withIntermediateDirectories: false, attributes: nil) for resourceName in subdirectoryResourcesFilenames { guard FileManager.default.createFile(atPath: subdirectoryURL.appendingPathComponent(resourceName).path, contents: nil, attributes: nil) else { return false } } self.bundlePath = resourcesDirectory.path } catch { return false } case .freestanding(let executableType): do { let bundleName = URL(string:self.bundleName)!.deletingPathExtension().path try FileManager.default.createDirectory(atPath: temporaryDirectory.path, withIntermediateDirectories: false, attributes: nil) // Make a main executable: self.mainExecutableURL = temporaryDirectory .appendingPathComponent(executableType.nonFlatFilePrefix + bundleName) .appendingPathExtension(executableType.pathExtension) guard FileManager.default.createFile(atPath: mainExecutableURL.path, contents: nil) else { return false } // Make a .resources directory: let resourcesDirectory = temporaryDirectory.appendingPathComponent("\(bundleName).resources") try FileManager.default.createDirectory(atPath: resourcesDirectory.path, withIntermediateDirectories: false, attributes: nil) // Make an auxiliary executable: let auxiliaryExecutableURL = resourcesDirectory .appendingPathComponent(executableType.nonFlatFilePrefix + auxiliaryExecutableName) .appendingPathExtension(executableType.pathExtension) guard FileManager.default.createFile(atPath: auxiliaryExecutableURL.path, contents: nil) else { return false } // Put some resources in the bundle for resourceName in resourceFilenames { guard FileManager.default.createFile(atPath: resourcesDirectory.appendingPathComponent(resourceName).path, contents: nil, attributes: nil) else { return false } } // Add a resource into a subdirectory let subdirectoryURL = resourcesDirectory.appendingPathComponent(resourceSubdirectory) try FileManager.default.createDirectory(atPath: subdirectoryURL.path, withIntermediateDirectories: false, attributes: nil) for resourceName in subdirectoryResourcesFilenames { guard FileManager.default.createFile(atPath: subdirectoryURL.appendingPathComponent(resourceName).path, contents: nil, attributes: nil) else { return false } } self.bundlePath = resourcesDirectory.path } catch { return false } } self.playgroundPath = temporaryDirectory.path return true } func destroy() { guard let path = self.playgroundPath else { return } self.playgroundPath = nil try? FileManager.default.removeItem(atPath: path) } deinit { assert(playgroundPath == nil, "All playgrounds should have .destroy() invoked on them before they go out of scope.") } } class TestBundle : XCTestCase { func test_paths() { let bundle = testBundle() // bundlePath XCTAssert(!bundle.bundlePath.isEmpty) XCTAssertEqual(bundle.bundleURL.path, bundle.bundlePath) let path = bundle.bundlePath // etc #if os(macOS) XCTAssertEqual("\(path)/Contents/Resources", bundle.resourcePath) #if DARWIN_COMPATIBILITY_TESTS XCTAssertEqual("\(path)/Contents/MacOS/DarwinCompatibilityTests", bundle.executablePath) #else XCTAssertEqual("\(path)/Contents/MacOS/TestFoundation", bundle.executablePath) #endif XCTAssertEqual("\(path)/Contents/Frameworks", bundle.privateFrameworksPath) XCTAssertEqual("\(path)/Contents/SharedFrameworks", bundle.sharedFrameworksPath) XCTAssertEqual("\(path)/Contents/SharedSupport", bundle.sharedSupportPath) #endif XCTAssertNil(bundle.path(forAuxiliaryExecutable: "no_such_file")) #if !DARWIN_COMPATIBILITY_TESTS XCTAssertNil(bundle.appStoreReceiptURL) #endif } func test_resources() { let bundle = testBundle() // bad resources XCTAssertNil(bundle.url(forResource: nil, withExtension: nil, subdirectory: nil)) XCTAssertNil(bundle.url(forResource: "", withExtension: "", subdirectory: nil)) XCTAssertNil(bundle.url(forResource: "no_such_file", withExtension: nil, subdirectory: nil)) // test file let testPlist = bundle.url(forResource: "Test", withExtension: "plist") XCTAssertNotNil(testPlist) XCTAssertEqual("Test.plist", testPlist!.lastPathComponent) XCTAssert(FileManager.default.fileExists(atPath: testPlist!.path)) // aliases, paths XCTAssertEqual(testPlist!.path, bundle.url(forResource: "Test", withExtension: "plist", subdirectory: nil)!.path) XCTAssertEqual(testPlist!.path, bundle.path(forResource: "Test", ofType: "plist")) XCTAssertEqual(testPlist!.path, bundle.path(forResource: "Test", ofType: "plist", inDirectory: nil)) } func test_infoPlist() { let bundle = testBundle() // bundleIdentifier #if DARWIN_COMPATIBILITY_TESTS XCTAssertEqual("org.swift.DarwinCompatibilityTests", bundle.bundleIdentifier) #else XCTAssertEqual("org.swift.TestFoundation", bundle.bundleIdentifier) #endif // infoDictionary let info = bundle.infoDictionary XCTAssertNotNil(info) #if DARWIN_COMPATIBILITY_TESTS XCTAssert("DarwinCompatibilityTests" == info!["CFBundleName"] as! String) XCTAssert("org.swift.DarwinCompatibilityTests" == info!["CFBundleIdentifier"] as! String) #else XCTAssert("TestFoundation" == info!["CFBundleName"] as! String) XCTAssert("org.swift.TestFoundation" == info!["CFBundleIdentifier"] as! String) #endif // localizedInfoDictionary XCTAssertNil(bundle.localizedInfoDictionary) // FIXME: Add a localized Info.plist for testing } func test_localizations() { let bundle = testBundle() XCTAssertEqual(["en"], bundle.localizations) XCTAssertEqual(["en"], bundle.preferredLocalizations) XCTAssertEqual(["en"], Bundle.preferredLocalizations(from: ["en", "pl", "es"])) } private let _bundleName = "MyBundle" private let _bundleExtension = "bundle" private let _bundleResourceNames = ["hello.world", "goodbye.world", "swift.org"] private let _subDirectory = "Sources" private let _main = "main" private let _type = "swift" private let _auxiliaryExecutable = "auxiliaryExecutable" private func _setupPlayground(layout: BundlePlayground.Layout) -> BundlePlayground? { return BundlePlayground(bundleName: _bundleName, bundleExtension: _bundleExtension, resourceFilenames: _bundleResourceNames, resourceSubdirectory: _subDirectory, subdirectoryResourcesFilenames: [ "\(_main).\(_type)" ], auxiliaryExecutableName: _auxiliaryExecutable, layout: layout) } private func _withEachPlaygroundLayout(execute: (BundlePlayground) throws -> Void) rethrows { for layout in BundlePlayground.Layout.allApplicable { if let playground = _setupPlayground(layout: layout) { try execute(playground) playground.destroy() } } } private func _cleanupPlayground(_ location: String) { try? FileManager.default.removeItem(atPath: location) } func test_URLsForResourcesWithExtension() { _withEachPlaygroundLayout { (playground) in let bundle = Bundle(path: playground.bundlePath)! XCTAssertNotNil(bundle) let worldResources = bundle.urls(forResourcesWithExtension: "world", subdirectory: nil) XCTAssertNotNil(worldResources) XCTAssertEqual(worldResources?.count, 2) let path = bundle.path(forResource: _main, ofType: _type, inDirectory: _subDirectory) XCTAssertNotNil(path) } } func test_bundleLoad() { let bundle = testBundle() let _ = bundle.load() XCTAssertTrue(bundle.isLoaded) } func test_bundleLoadWithError() { let bundleValid = testBundle() // Test valid load using loadAndReturnError do { try bundleValid.loadAndReturnError() } catch{ XCTFail("should not fail to load") } // Executable cannot be located try! _withEachPlaygroundLayout { (playground) in let bundle = Bundle(path: playground.bundlePath) XCTAssertThrowsError(try bundle!.loadAndReturnError()) } } func test_bundleWithInvalidPath() { let bundleInvalid = Bundle(path: NSTemporaryDirectory() + "test.playground") XCTAssertNil(bundleInvalid) } func test_bundlePreflight() { XCTAssertNoThrow(try testBundle().preflight()) try! _withEachPlaygroundLayout { (playground) in let bundle = Bundle(path: playground.bundlePath)! // Must throw as the main executable is a dummy empty file. XCTAssertThrowsError(try bundle.preflight()) } } func test_bundleFindExecutable() { XCTAssertNotNil(testBundle().executableURL) _withEachPlaygroundLayout { (playground) in let bundle = Bundle(path: playground.bundlePath)! XCTAssertNotNil(bundle.executableURL) } } func test_bundleFindAuxiliaryExecutables() { _withEachPlaygroundLayout { (playground) in let bundle = Bundle(path: playground.bundlePath)! XCTAssertNotNil(bundle.url(forAuxiliaryExecutable: _auxiliaryExecutable)) XCTAssertNil(bundle.url(forAuxiliaryExecutable: "does_not_exist_at_all")) } } #if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT func test_bundleReverseBundleLookup() { _withEachPlaygroundLayout { (playground) in #if !os(Windows) if playground.layout.isFreestanding { // TODO: Freestanding bundles reverse lookup pending to be implemented on non-Windows platforms. return } #endif if playground.layout.isFHS { // TODO: FHS bundles reverse lookup pending to be implemented on all platforms. return } let bundle = Bundle(_executableURL: playground.mainExecutableURL) XCTAssertNotNil(bundle) XCTAssertEqual(bundle?.bundlePath, playground.bundlePath) } } func test_mainBundleExecutableURL() { let maybeURL = Bundle.main.executableURL XCTAssertNotNil(maybeURL) guard let url = maybeURL else { return } XCTAssertEqual(url.path, ProcessInfo.processInfo._processPath) } #endif func test_bundleForClass() { XCTAssertEqual(testBundle(), Bundle(for: type(of: self))) } static var allTests: [(String, (TestBundle) -> () throws -> Void)] { var tests: [(String, (TestBundle) -> () throws -> Void)] = [ ("test_paths", test_paths), ("test_resources", test_resources), ("test_infoPlist", test_infoPlist), ("test_localizations", test_localizations), ("test_URLsForResourcesWithExtension", test_URLsForResourcesWithExtension), ("test_bundleLoad", test_bundleLoad), ("test_bundleLoadWithError", test_bundleLoadWithError), ("test_bundleWithInvalidPath", test_bundleWithInvalidPath), ("test_bundlePreflight", test_bundlePreflight), ("test_bundleFindExecutable", test_bundleFindExecutable), ("test_bundleFindAuxiliaryExecutables", test_bundleFindAuxiliaryExecutables), ("test_bundleForClass", testExpectedToFailOnWindows(test_bundleForClass, "Functionality not yet implemented on Windows. SR-XXXX")), ] #if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT tests.append(contentsOf: [ ("test_mainBundleExecutableURL", test_mainBundleExecutableURL), ("test_bundleReverseBundleLookup", test_bundleReverseBundleLookup), ]) #endif return tests } }
apache-2.0
e3cf5af5521b89cfd15f49f153bef38c
39.445194
180
0.603444
5.75018
false
true
false
false
Wolkabout/WolkSense-Hexiwear-
iOS/Hexiwear/FirmwareSelectionTableViewController.swift
1
12321
// // Hexiwear application is used to pair with Hexiwear BLE devices // and send sensor readings to WolkSense sensor data cloud // // Copyright (C) 2016 WolkAbout Technology s.r.o. // // Hexiwear is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Hexiwear is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // // FirmwareSelectionTableViewController.swift // import UIKit import CoreBluetooth struct FirmwareFileItem { let fileName: String let fileVersion: String let factory: Bool } class FirmwareSelectionTableViewController: UITableViewController { var firmwareFilesKW40: [FirmwareFileItem] = [] var firmwareFilesMK64: [FirmwareFileItem] = [] var peri: CBPeripheral! var selectedFile: String = "" var selectedFileName: String = "" var selectedType: String = "" var selectedFileVersion: String = "" var privateDocsDir: String? var refreshCont: UIRefreshControl! var hexiwearDelegate: HexiwearPeripheralDelegate? var otapDelegate: OTAPDelegate? override func viewDidLoad() { super.viewDidLoad() self.refreshCont = UIRefreshControl() self.refreshCont.addTarget(self, action: #selector(FirmwareSelectionTableViewController.refresh(_:)), for: UIControlEvents.valueChanged) self.tableView.addSubview(refreshCont) title = "Select firmware file" } func refresh(_ sender:AnyObject) { // Code to refresh table view getFirmwareFiles() tableView.reloadData() self.refreshCont.endRefreshing() } override func viewWillAppear(_ animated: Bool) { getFirmwareFiles() } override func viewWillDisappear(_ animated: Bool) { if isMovingFromParentViewController { hexiwearDelegate?.didUnwind() } } fileprivate func getFactorySettingsFirmwareFiles() { firmwareFilesKW40 = [] firmwareFilesMK64 = [] guard let pathKW40 = Bundle.main.path(forResource: "HEXIWEAR_KW40_factory_settings", ofType: "img") else { return } guard let kw40Data = NSData(contentsOfFile: pathKW40) else { return } var kw40dataBytes: [UInt8] = [UInt8](repeating: 0x00, count: kw40Data.length) let kw40dataLength = kw40Data.length kw40Data.getBytes(&kw40dataBytes, length: kw40dataLength) // Parse FW file header if let otapKW40ImageFileHeader = OTAImageFileHeader(data: kw40Data as Data) { selectedFileVersion = "version: \(otapKW40ImageFileHeader.imageVersionAsString())" let kw40FW = FirmwareFileItem(fileName: "HEXIWEAR_KW40_factory_settings.img", fileVersion: selectedFileVersion, factory: true) firmwareFilesKW40.append(kw40FW) } guard let pathMK64 = Bundle.main.path(forResource: "HEXIWEAR_MK64_factory_settings", ofType: "img") else { return } guard let mk64Data = NSData(contentsOfFile: pathMK64) else { return } var mk64dataBytes: [UInt8] = [UInt8](repeating: 0x00, count: mk64Data.length) let mk64dataLength = mk64Data.length mk64Data.getBytes(&mk64dataBytes, length: mk64dataLength) // Parse FW file header if let otapMK64ImageFileHeader = OTAImageFileHeader(data: mk64Data as Data) { selectedFileVersion = "version: \(otapMK64ImageFileHeader.imageVersionAsString())" let mk64FW = FirmwareFileItem(fileName: "HEXIWEAR_MK64_factory_settings.img", fileVersion: selectedFileVersion, factory: true) firmwareFilesMK64.append(mk64FW) } } fileprivate func getFirmwareFiles() { firmwareFilesKW40 = [] firmwareFilesMK64 = [] getFactorySettingsFirmwareFiles() privateDocsDir = getPrivateDocumentsDirectory() let fileManager = FileManager.default do { let fwFilesPaths = try fileManager.contentsOfDirectory(atPath: privateDocsDir!) for file in fwFilesPaths { let fullFileName = (self.privateDocsDir! as NSString).appendingPathComponent(file) if let data = try? Data(contentsOf: URL(fileURLWithPath: fullFileName)) { var dataBytes: [UInt8] = [UInt8](repeating: 0x00, count: data.count) let length = data.count (data as NSData).getBytes(&dataBytes, length: length) // Parse FW file header if let otapImageFileHeader = OTAImageFileHeader(data: data) { selectedFileVersion = "version: \(otapImageFileHeader.imageVersionAsString())" let firmwareFile = FirmwareFileItem(fileName: file, fileVersion: selectedFileVersion, factory: false) if otapImageFileHeader.imageId == 1 { firmwareFilesKW40.append(firmwareFile) } else if otapImageFileHeader.imageId == 2 { firmwareFilesMK64.append(firmwareFile) } } } } } catch { print(error) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toFWUpgrade" { if let vc = segue.destination as? FWUpgradeViewController { vc.fwPath = selectedFile vc.fwFileName = selectedFileName vc.fwTypeString = selectedType vc.fwVersion = selectedFileVersion vc.hexiwearPeripheral = peri vc.hexiwearDelegate = self.hexiwearDelegate vc.otapDelegate = self.otapDelegate } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? firmwareFilesKW40.count : firmwareFilesMK64.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "KW40" } return "MK64" } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let headerView = view as? UITableViewHeaderFooterView { headerView.contentView.backgroundColor = UIColor(red: 127.0/255.0, green: 147.0/255.0, blue: 0.0, alpha: 0.6) headerView.alpha = 0.95 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "firmwareCell", for: indexPath) if indexPath.section == 0 { let firmwareFile = firmwareFilesKW40[indexPath.row] cell.textLabel?.text = firmwareFile.fileName cell.detailTextLabel?.text = firmwareFile.fileVersion } else { let firmwareFile = firmwareFilesMK64[indexPath.row] cell.textLabel?.text = firmwareFile.fileName cell.detailTextLabel?.text = firmwareFile.fileVersion } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // If the first item of any section is tapped, that is factory file which is embedded in bundle // File path is different than for other FW files if indexPath.section == 0 && indexPath.row == 0 { // factory KW40 guard let strPathKW40 = Bundle.main.path(forResource: "HEXIWEAR_KW40_factory_settings", ofType: "img") else { return } selectedType = "KW40" selectedFileVersion = "1.0.0" selectedFileName = "HEXIWEAR_KW40_factory_settings.img" selectedFile = strPathKW40 performSegue(withIdentifier: "toFWUpgrade", sender: nil) return } if indexPath.section == 1 && indexPath.row == 0 { // factory MK64 guard let strPathMK64 = Bundle.main.path(forResource: "HEXIWEAR_MK64_factory_settings", ofType: "img") else { return } selectedType = "MK64" selectedFileVersion = "1.0.0" selectedFileName = "HEXIWEAR_MK64_factory_settings.img" selectedFile = strPathMK64 performSegue(withIdentifier: "toFWUpgrade", sender: nil) return } guard let selectedFWFile = getFileForIndexPath(indexPath) else { return } selectedFileName = selectedFWFile let fullFileName = (self.privateDocsDir! as NSString).appendingPathComponent(selectedFWFile) selectedFile = fullFileName if let data = try? Data(contentsOf: URL(fileURLWithPath: fullFileName)) { var dataBytes: [UInt8] = [UInt8](repeating: 0x00, count: data.count) let length = data.count (data as NSData).getBytes(&dataBytes, length: length) // Parse FW file header if let otapImageFileHeader = OTAImageFileHeader(data: data) { if otapImageFileHeader.imageId == 1 { selectedType = "KW40" } else if otapImageFileHeader.imageId == 2 { selectedType = "MK64" } selectedFileVersion = otapImageFileHeader.imageVersionAsString() } } performSegue(withIdentifier: "toFWUpgrade", sender: nil) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // let the controller to know that able to edit tableView's row return true } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action , indexPath) -> Void in let item = indexPath.section == 0 ? self.firmwareFilesKW40[indexPath.row] : self.firmwareFilesMK64[indexPath.row] let fileManager = FileManager.default do { let fullFileName = (self.privateDocsDir! as NSString).appendingPathComponent(item.fileName) try fileManager.removeItem(atPath: fullFileName) DispatchQueue.main.async { if indexPath.section == 0 { self.firmwareFilesKW40.remove(at: indexPath.row) } else { self.firmwareFilesMK64.remove(at: indexPath.row) } self.tableView.deleteRows(at: [indexPath], with: .fade) } } catch { print(error) } }) deleteAction.backgroundColor = UIColor.red return [deleteAction] } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60.0 } fileprivate func getFileForIndexPath(_ indexPath: IndexPath) -> String? { if indexPath.section == 0 { return indexPath.row >= firmwareFilesKW40.count ? nil : firmwareFilesKW40[indexPath.row].fileName } return indexPath.row >= firmwareFilesMK64.count ? nil : firmwareFilesMK64[indexPath.row].fileName } }
gpl-3.0
736b4d0429a3354e213b073edbd1233b
39.663366
144
0.6131
4.850787
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00232-swift-lookupresult-filter.swift
1
1245
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class c { func b((Any, c))(a: (Any, AnyObject)) { b(a) C: B, A { override func d() -> String { return "" } func c() -> String { return "" } } func e<T where T: A, T: B>(t: T) { t.c() } func f(c: i, l: i) -> (((i, i) -> i) -> i) { b { (h -> i) d $k } let e: a { } class b<h, i> { } protocol c { typealias g } var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) func C<D, E: A where D.C == E> { } func prefix(with: String) -> <T>(() -> T) -> String { { g in "\(withing } clasnintln(some(xs)) func f<e>() -> (e, e -> e) -> e { e b e.c = {} { e) { f } } protocol f { class func c() } class e: f { class func c } } func i(c: () -> ()) { } class a { var _ = i() { } }
apache-2.0
c8a3c81d3b5333037c31102dca4aaa71
17.863636
79
0.496386
2.855505
false
false
false
false
ben-ng/swift
test/DebugInfo/Imports.swift
17
1566
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-swift-frontend -emit-module-path %t/basic.swiftmodule %S/basic.swift // RUN: %target-swift-frontend -emit-ir -module-name Foo %s -I %t -g -o - | %FileCheck %s // RUN: %target-swift-frontend -c -module-name Foo %s -I %t -g -o %t.o // RUN: %llvm-dwarfdump %t.o | %FileCheck --check-prefix=DWARF %s // CHECK-DAG: ![[FOOMODULE:[0-9]+]] = !DIModule({{.*}}, name: "Foo", includePath: "{{.*}}test{{.*}}DebugInfo{{.*}}" // CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[THISFILE:[0-9]+]], entity: ![[FOOMODULE]] // CHECK-DAG: ![[THISFILE]] = !DIFile(filename: "Imports.swift", directory: "{{.*}}test/DebugInfo") // CHECK-DAG: ![[SWIFTFILE:[0-9]+]] = !DIFile(filename: "Swift.swiftmodule" // CHECK-DAG: ![[SWIFTMODULE:[0-9]+]] = !DIModule({{.*}}, name: "Swift" // CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[THISFILE]], entity: ![[SWIFTMODULE]] // CHECK-DAG: ![[BASICMODULE:[0-9]+]] = !DIModule({{.*}}, name: "basic" // CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[THISFILE]], entity: ![[BASICMODULE]] import basic import typealias Swift.Optional func markUsed<T>(_ t: T) {} markUsed(basic.foo(1, 2)) // DWARF: .debug_info // DWARF: DW_TAG_module // DWARF: DW_AT_name {{.*}}"Foo" // DWARF: DW_AT_LLVM_include_path // DWARF: DW_TAG_module // DWARF: DW_AT_name {{.*}}"Swift" // DWARF: DW_AT_LLVM_include_path // DWARF: DW_TAG_module // DWARF: DW_AT_name {{.*}}"basic" // DWARF-NOT: "Swift.Optional" // DWARF-DAG: file_names{{.*}} Imports.swift
apache-2.0
0396b39aaeafcdb6645f5eff2eaaad85
45.058824
115
0.626437
2.910781
false
true
false
false
IndisputableLabs/Swifthereum
Swifthereum/Classes/Geth/Hash.swift
1
1401
// // Hash.swift // GethTest // // Created by Ronald Mannak on 9/24/17. // Copyright © 2017 Indisputable. All rights reserved. // import Foundation import Geth // TODO: move this to typeAlias and extension of String(?) /** Hash represents the 32 byte Keccak256 hash of arbitrary data. 64 char / 32 byte can be a private key: https://ethereum.stackexchange.com/questions/3542/how-are-ethereum-addresses-generated what about 128 char / 64 byte open key? */ public struct Hash { public let _gethHash: GethHash /** GetBytes retrieves the byte representation of the hash. */ var bytes: Data { return _gethHash.getBytes() } /** * GetHex retrieves the hex string representation of the hash. */ var hex: String { return _gethHash.getHex() } public init(hash: GethHash) { _gethHash = hash } /** NewHashFromBytes converts a slice of bytes to a hash value. */ public init?(bytes: Data) { guard let hash = GethHash(fromBytes: bytes) else { return nil } _gethHash = hash } /** NewHashFromHex converts a hex string to a hash value. */ public init?(hex: String) { guard let hash = GethHash(fromHex: hex) else { return nil } _gethHash = hash } } //extension Hash: Codable { // open init(from decoder: Decoder) throws { // // } //}
mit
f20f5067aed83e7042ad945560de7574
23.137931
127
0.623571
3.733333
false
false
false
false
hironytic/Formulitic
Sources/Formulitic.swift
1
2446
// // Formulitic.swift // Formulitic // // Copyright (c) 2016-2018 Hironori Ichimiya <hiron@hironytic.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// A central object of formula parsing and evaluating it. public class Formulitic { /// A reference producer. public let referenceProducer: ReferenceProducer /// A function provider. public let functionProvider: FunctionProvider /// Initializes the object. /// - Parameters: /// - referenceProducer: A reference producer to manage references. public init(referenceProducer: ReferenceProducer = NullReferenceProducer(), functionProvider: FunctionProvider = BasicFunctionProvider()) { self.referenceProducer = referenceProducer self.functionProvider = functionProvider } /// Parses a formula string. /// - Parameters: /// - formulaString A formula string. /// - Returns: A `Formula` object. public func parse(_ formulaString: String) -> Formula { return FormulaParser(formulitic: self, formulaString: formulaString) .parseFormula() } func evaluateFunction(name: String, parameters: [Expression], context: EvaluateContext) -> Value { guard let function = functionProvider.function(for: name) ?? operatorFunctions[name] else { return ErrorValue.unknownFunction } return function(parameters, context) } }
mit
2b2926bbbb3ee832959e0f86fba5852a
41.912281
143
0.72731
4.667939
false
false
false
false
gxfeng/iOS-
TabBarButton.swift
1
1867
// // TabBarButton.swift // ProjectSwift // // Created by ZJQ on 2016/12/22. // Copyright © 2016年 ZJQ. All rights reserved. // import UIKit class TabBarButton: UIButton { let tabbarImageRatio = 0.65 var item : UITabBarItem = UITabBarItem(){ didSet{ self.setTitle(self.item.title, for: UIControlState()) self.setTitle(self.item.title, for: .selected) self.setImage(self.item.image, for: UIControlState()) self.setImage(self.item.selectedImage, for: .selected) } } override init(frame: CGRect) { super.init(frame: frame) // 图片居中 self.imageView?.contentMode = .center // 去掉高亮状态 self.adjustsImageWhenHighlighted = false // 文字居中 self.titleLabel?.textAlignment = .center self.titleLabel?.font = UIFont.systemFont(ofSize: 11) // title两种状态的颜色 self.setTitleColor(UIColor.orange, for: .selected) self.setTitleColor(UIColor.black, for: UIControlState()) } // MARK: title override func titleRect(forContentRect contentRect: CGRect) -> CGRect { let titleY = contentRect.size.height * CGFloat(tabbarImageRatio) let titleH = contentRect.size.height - titleY let titleW = contentRect.size.width return CGRect(x: 0, y: titleY, width: titleW, height: titleH) } // MARK: image override func imageRect(forContentRect contentRect: CGRect) -> CGRect { let imageH = contentRect.size.height * CGFloat(tabbarImageRatio) let imageW = contentRect.size.width return CGRect(x: 0, y: 0, width: imageW, height: imageH) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
e7993539cb497cc7cef75a4152b76b01
31.535714
75
0.619649
4.287059
false
false
false
false
oursky/Redux
Pod/Classes/combineReducers.swift
1
986
// // combineReducers.swift // Redux.swift // // Created by Mark Wise on 11/4/15. // Copyright © 2015 InstaJams. All rights reserved. // import Foundation public func combineReducers(_ reducers: [String: Reducer]) -> Reducer { func combination(_ previousState: Any, action: ReduxAction) -> Any { if let appState = previousState as? ReduxAppState { var nextState: ReduxAppState = appState for (key, reducer) in reducers { if let previousStateForKey = nextState.get(key) { let nextStateForKey = reducer(previousStateForKey, action) if let ns = nextStateForKey as? AnyEquatable { nextState.set(key, value: ns) } else { print("AppState value must conform AnyEquatable") } } } return nextState } return previousState } return combination }
mit
9771936ddd0f9c8e58f08eddc59e158f
31.833333
78
0.561421
5.02551
false
false
false
false
BlackSourceLabs/BlackNectar-iOS
BlackNectar/BlackNectar/UIViewControllers+.swift
1
1356
// // UIViewControllers+.swift // BlackNectar // // Created by Cordero Hernandez on 2/6/17. // Copyright © 2017 BlackSource. All rights reserved. // import Archeota import AromaSwiftClient import Foundation import NVActivityIndicatorView import UIKit extension UIViewController { func startSpinningIndicator() { UIApplication.shared.isNetworkActivityIndicatorVisible = true } func stopSpinningIndicator() { UIApplication.shared.isNetworkActivityIndicatorVisible = false } func startSpinningNVActivityIndicator() { let activityData = ActivityData() NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData) } func stopSpinningNVActivityIndicator() { NVActivityIndicatorPresenter.sharedInstance.stopAnimating() } func hideNavigationBar() { guard let nav = self.navigationController?.navigationBar else { return } nav.isTranslucent = true nav.setBackgroundImage(UIImage(), for: .default) nav.shadowImage = UIImage() nav.backgroundColor = UIColor.clear } func showNavigationBar() { guard let nav = self.navigationController?.navigationBar else { return } nav.isTranslucent = false } }
apache-2.0
0c606b43dd1fe1a2d4f09300dfb8534e
22.77193
80
0.660517
5.790598
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Picker/Model/PhotoAssetCollection.swift
1
3752
// // PhotoAssetCollection.swift // 照片选择器-Swift // // Created by Silence on 2019/7/3. // Copyright © 2019年 Silence. All rights reserved. // import UIKit import Photos open class PhotoAssetCollection: Equatable { /// 相册名称 public var albumName: String? /// 相册里的资源数量 public var count: Int = 0 /// PHAsset 集合 public var result: PHFetchResult<PHAsset>? /// 相册对象 public var collection: PHAssetCollection? /// 获取 PHFetchResult 中的 PHAsset 时的选项 public var options: PHFetchOptions? /// 是否选中 public var isSelected: Bool = false /// 是否是相机胶卷 public var isCameraRoll: Bool = false /// 真实的封面图片,如果不为nil就是封面 var realCoverImage: UIImage? private var coverImage: UIImage? public init( collection: PHAssetCollection?, options: PHFetchOptions? ) { self.collection = collection self.options = options } public init( albumName: String?, coverImage: UIImage? ) { self.albumName = albumName self.coverImage = coverImage } public static func == (lhs: PhotoAssetCollection, rhs: PhotoAssetCollection) -> Bool { return lhs === rhs } } // MARK: Fetch Asset extension PhotoAssetCollection { /// 请求获取相册封面图片 /// - Parameter completion: 会回调多次 /// - Returns: 请求ID open func requestCoverImage( completion: ((UIImage?, PhotoAssetCollection, [AnyHashable: Any]?) -> Void)? ) -> PHImageRequestID? { if realCoverImage != nil { completion?(realCoverImage, self, nil) return nil } if let result = result, result.count > 0 { let asset = result.object(at: result.count - 1) return AssetManager.requestThumbnailImage( for: asset, targetWidth: 160 ) { (image, info) in completion?(image, self, info) } } completion?(coverImage, self, nil) return nil } /// 枚举相册里的资源 open func enumerateAssets( options opts: NSEnumerationOptions = .concurrent, usingBlock: ((PhotoAsset, Int, UnsafeMutablePointer<ObjCBool>) -> Void)? ) { if result == nil { fetchResult() } guard let result = result else { return } if opts == .reverse { result.enumerateObjects( options: opts ) { asset, index, stop in let photoAsset = PhotoAsset(asset: asset) usingBlock?(photoAsset, index, stop) } }else { result.enumerateObjects { asset, index, stop in let photoAsset = PhotoAsset(asset: asset) usingBlock?(photoAsset, index, stop) } } } } extension PhotoAssetCollection { func fetchResult() { guard let collection = collection else { return } albumName = PhotoTools.transformAlbumName(for: collection) result = PHAsset.fetchAssets(in: collection, options: options) count = result?.count ?? 0 } func changeResult(for result: PHFetchResult<PHAsset>) { self.result = result count = result.count if let collection = collection { albumName = PhotoTools.transformAlbumName(for: collection) } } func change(albumName: String?, coverImage: UIImage?) { self.albumName = albumName self.coverImage = coverImage } }
mit
5f4b3e69e7aad1f0cc196576c1963518
25.153285
90
0.569634
4.881471
false
false
false
false
Edovia/SwiftPasscodeLock
PasscodeLock/PasscodeLockPresenter.swift
1
3664
// // PasscodeLockPresenter.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/29/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import UIKit public class PasscodeLockPresenter { private var mainWindow: UIWindow? private var passcodeLockWindow: UIWindow? private let passcodeConfiguration: PasscodeLockConfigurationType public var isPasscodePresented = false public let passcodeLockVC: PasscodeLockViewController public init(mainWindow window: UIWindow?, configuration: PasscodeLockConfigurationType, viewController: PasscodeLockViewController) { mainWindow = window mainWindow?.windowLevel = UIWindow.Level(rawValue: 1) passcodeConfiguration = configuration passcodeLockVC = viewController } public convenience init(mainWindow window: UIWindow?, configuration: PasscodeLockConfigurationType) { let passcodeLockVC = PasscodeLockViewController(state: .enterPasscode, configuration: configuration) self.init(mainWindow: window, configuration: configuration, viewController: passcodeLockVC) } public func presentPasscodeLock(_ completion: (() -> Void)?) { guard passcodeConfiguration.repository.hasPasscode else { return } guard !isPasscodePresented else { return } isPasscodePresented = true self.passcodeLockWindow = UIWindow(frame: UIScreen.main.bounds) self.passcodeLockWindow?.windowLevel = UIWindow.Level(rawValue: 0) self.passcodeLockWindow?.makeKeyAndVisible() self.passcodeLockWindow?.windowLevel = UIWindow.Level(rawValue: 2) self.passcodeLockWindow?.isHidden = false mainWindow?.windowLevel = UIWindow.Level(rawValue: 1) mainWindow?.endEditing(true) let passcodeLockVC = PasscodeLockViewController(state: .enterPasscode, configuration: passcodeConfiguration) let userDismissCompletionCallback = passcodeLockVC.dismissCompletionCallback passcodeLockVC.dismissCompletionCallback = { [weak self] in userDismissCompletionCallback?() self?.dismissPasscodeLock() completion?() } self.passcodeLockWindow?.rootViewController = passcodeLockVC } public func dismissPasscodeLock(animated: Bool = true) { isPasscodePresented = false mainWindow?.windowLevel = UIWindow.Level(rawValue: 1) mainWindow?.makeKeyAndVisible() if animated { animatePasscodeLockDismissal() } else { self.passcodeLockWindow?.windowLevel = UIWindow.Level(rawValue: 0) self.passcodeLockWindow?.rootViewController = nil self.passcodeLockWindow = nil } } internal func animatePasscodeLockDismissal() { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions(), animations: { [weak self] in self?.passcodeLockWindow?.alpha = 0 }, completion: { [weak self] _ in self?.passcodeLockWindow?.windowLevel = UIWindow.Level(rawValue: 0) self?.passcodeLockWindow?.rootViewController = nil self?.passcodeLockWindow?.alpha = 1 self?.passcodeLockWindow = nil } ) } }
mit
98d61fb8869469008c9b872796117d23
33.233645
137
0.630631
6.27226
false
true
false
false
liuguya/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/foodMaterial/view/CBMaterialView.swift
1
2064
// // CBMaterialView.swift // TestKitchen // // Created by 阳阳 on 16/8/23. // Copyright © 2016年 liuguyang. All rights reserved. // import UIKit class CBMaterialView: UIView { //表格 private var tbView:UITableView? //数据 var model:CBMaterialModel?{ didSet{ tbView?.reloadData() } } init() { super.init(frame: CGRectZero) //创建表格 tbView = UITableView(frame: CGRectZero,style: .Plain) tbView?.delegate = self tbView?.dataSource = self addSubview(tbView!) //添加约束 tbView?.snp_makeConstraints(closure: { [weak self] (make) in make.edges.equalTo(self!) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:UITableView代理 extension CBMaterialView:UITableViewDelegate,UITableViewDataSource{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rowNum = 0 if model?.data?.data?.count > 0{ rowNum = (model?.data?.data?.count)! } return rowNum } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var h:CGFloat = 0 if model?.data?.data?.count > 0{ let typeModel = model?.data?.data![indexPath.row] h = CBMaterialCell.heightWithModel(typeModel!) } return h } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellId = "materialCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBMaterialCell if nil == cell{ cell = CBMaterialCell(style: .Default, reuseIdentifier: cellId) } let typeModel = model?.data?.data![indexPath.row] cell?.model = typeModel return cell! } }
mit
28a3ce7132a7aa9781f6ffd58a8edb03
25.012821
109
0.586496
4.675115
false
false
false
false
rhwood/roster-decoder
Sources/Roster.swift
1
3179
// // Roster.swift // Roster Decoder // // Created by Randall Wood on 29/4/2015. // Copyright (c) 2015, 2016 Alexandria Software. All rights reserved. // import Foundation import Fuzi import CoreGraphics import os.log class Roster { var name = "Roster" var entries = [RosterEntry]() var containsIcons = false var xml: FileWrapper? { return self.profile?.rosterFile } var rosterDir: FileWrapper? { return self.profile?.rosterDir } var profile: Profile? init(profile: Profile) throws { self.profile = profile self.name = profile.name if self.profile?.rosterFile != nil { try self.updateRoster((self.xml?.regularFileContents!)!) } else { os_log("Roster is empty") } } init(data: Data) throws { self.profile = nil self.name = "roster.xml" try self.updateRoster(data) } func updateRoster(_ data: Data) throws { let XML: XMLDocument! do { XML = try XMLDocument(data: data) if XML.root?.attr("noNamespaceSchemaLocation") != "http://jmri.org/xml/schema/roster.xsd" { os_log("Invalid roster (invalid schema)") throw ProfileError.invalidRoster } } catch _ as XMLError { throw ProfileError.invalidRoster } var newEntries = Set<RosterEntry>() var deadEntries = Set<RosterEntry>() // for RosterElement in roster // create RosterEntry in entries for element in XML.xpath("//roster/locomotive") { let entry = RosterEntry(element: element, profile: profile) if !self.entries.contains(entry) { self.entries.append(entry) NotificationCenter.default.post(name: NSNotification.Name(rawValue: "EntryAdded"), object: self, userInfo: ["entry": entry]) } newEntries.insert(entry) } for entry in self.entries { if !newEntries.contains(entry) { deadEntries.insert(entry) } } for entry in deadEntries { self.entries.remove(at: self.entries.index(of: entry)!) NotificationCenter.default.post(name: Notification.Name(rawValue: "EntryRemoved"), object: self, userInfo: ["entry": entry]) } self.entries = newEntries.sorted(by: <) for entry in self.entries where entry.iconFileWrapper != nil { self.containsIcons = true } // todo: read groups from RosterEntries // display entries in groups } /// Get the entry matching the identifer. /// /// - parameter identifier: the requested entry identifier /// - returns: the matching entry or nil if there is no match func entry(_ identifier: String) -> RosterEntry? { for (entry) in self.entries where entry.identifier == identifier { return entry } return nil } }
mit
8e67d60fb80cac5fb309afcfc51509e2
31.773196
103
0.557408
4.668135
false
false
false
false
testpress/ios-app
ios-app/Model/Course.swift
1
2835
// // Course.swift // ios-app // // Copyright © 2017 Testpress. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import ObjectMapper import Realm import RealmSwift class Course: DBModel { @objc dynamic var url: String = "" @objc dynamic var id = 0 @objc dynamic var title: String = "" @objc dynamic var image: String = "" @objc dynamic var modified: String = "" @objc dynamic var modifiedDate: Double = 0 @objc dynamic var contentsUrl: String = "" @objc dynamic var chaptersUrl: String = "" @objc dynamic var slug: String = "" @objc dynamic var trophiesCount = 0 @objc dynamic var chaptersCount = 0 @objc dynamic var contentsCount = 0 @objc dynamic var order = 0 @objc dynamic var active = true @objc dynamic var external_content_link: String = "" @objc dynamic var external_link_label: String = "" var tags = List<String>() public override func mapping(map: Map) { url <- map["url"] id <- map["id"] title <- map["title"] image <- map["image"] modified <- map["modified"] modifiedDate = FormatDate.getDate(from: modified)?.timeIntervalSince1970 ?? 0 contentsUrl <- map["contents_url"] chaptersUrl <- map["chapters_url"] slug <- map["slug"] trophiesCount <- map["trophies_count"] chaptersCount <- map["chapters_count"] contentsCount <- map["contents_count"] order <- map["order"] active <- map["active"] external_content_link <- map["external_content_link"] external_link_label <- map["external_link_label"] tags <- (map["tags"], StringArrayTransform()) } override public static func primaryKey() -> String? { return "id" } }
mit
116a624dde3e429188811b1b0cb6cca6
37.821918
85
0.667255
4.280967
false
false
false
false
joerocca/GitHawk
Classes/Repository/RepositorySummaryCell.swift
1
4330
// // RepositorySummaryCell.swift // Freetime // // Created by Sherlock, James on 29/07/2017. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit final class RepositorySummaryCell: SelectableCell { static let labelDotSize = CGSize(width: 10, height: 10) static let titleInset = UIEdgeInsets( top: Styles.Sizes.rowSpacing, left: Styles.Sizes.icon.width + 2*Styles.Sizes.columnSpacing, bottom: Styles.Sizes.rowSpacing, right: Styles.Sizes.gutter ) private let reasonImageView = UIImageView() private let titleView = AttributedStringView() private let detailsStackView = UIStackView() private let secondaryLabel = UILabel() private let labelDotView = DotListView(dotSize: RepositorySummaryCell.labelDotSize) override init(frame: CGRect) { super.init(frame: frame) accessibilityTraits |= UIAccessibilityTraitButton isAccessibilityElement = true backgroundColor = .white contentView.addSubview(reasonImageView) contentView.addSubview(titleView) contentView.addSubview(detailsStackView) reasonImageView.backgroundColor = .clear reasonImageView.contentMode = .scaleAspectFit reasonImageView.tintColor = Styles.Colors.Blue.medium.color reasonImageView.snp.makeConstraints { make in make.size.equalTo(Styles.Sizes.icon) make.centerY.equalToSuperview() make.left.equalTo(Styles.Sizes.columnSpacing) } detailsStackView.axis = .vertical detailsStackView.alignment = .leading detailsStackView.distribution = .fill detailsStackView.spacing = Styles.Sizes.rowSpacing detailsStackView.addArrangedSubview(secondaryLabel) detailsStackView.addArrangedSubview(labelDotView) detailsStackView.snp.makeConstraints { (make) in make.bottom.equalTo(contentView).offset(-Styles.Sizes.rowSpacing) make.left.equalTo(reasonImageView.snp.right).offset(Styles.Sizes.columnSpacing) make.right.equalTo(contentView.snp.right).offset(-Styles.Sizes.columnSpacing) } secondaryLabel.numberOfLines = 1 secondaryLabel.font = Styles.Fonts.secondary secondaryLabel.textColor = Styles.Colors.Gray.light.color labelDotView.snp.makeConstraints { make in make.height.equalTo(RepositorySummaryCell.labelDotSize.height) make.left.right.equalTo(detailsStackView) } contentView.addBorder(.bottom, left: RepositorySummaryCell.titleInset.left) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() titleView.reposition(width: contentView.bounds.width) } // MARK: Public API func configure(_ model: RepositoryIssueSummaryModel) { titleView.configureAndSizeToFit(text: model.title, width: contentView.bounds.width) let format = NSLocalizedString("#%d opened %@ by %@", comment: "") secondaryLabel.text = String.localizedStringWithFormat(format, model.number, model.created.agoString, model.author) let imageName: String let tint: UIColor switch model.status { case .closed: imageName = model.pullRequest ? "git-pull-request" : "issue-closed" tint = Styles.Colors.Red.medium.color case .open: imageName = model.pullRequest ? "git-pull-request" : "issue-opened" tint = Styles.Colors.Green.medium.color case .merged: imageName = "git-merge" tint = Styles.Colors.purple.color } reasonImageView.image = UIImage(named: imageName)?.withRenderingMode(.alwaysTemplate) reasonImageView.tintColor = tint if model.labels.count > 0 { labelDotView.isHidden = false let colors = model.labels.map { UIColor.fromHex($0.color) } labelDotView.configure(colors: colors) } else { labelDotView.isHidden = true } } override var accessibilityLabel: String? { get { return AccessibilityHelper.generatedLabel(forCell: self) } set { } } }
mit
6294c47c31d419e1602440ddfd9dc979
34.483607
123
0.670825
4.842282
false
false
false
false
LiuSky/RxExtension
RxExtension/Classes/UICollectionReusableView+Rx.swift
1
1388
// // UICollectionReusableView+Rx.swift // RxExtension // // Created by LiuSky on 03/19/2020. // Copyright (c) 2020 LiuSky. All rights reserved. // import Foundation import UIKit import RxSwift private var prepareForReuseBag: Int8 = 0 public extension UICollectionReusableView { var rx_prepareForReuse: Observable<Void> { return Observable.of(self.rx.sentMessage(#selector(UICollectionReusableView.prepareForReuse)).map { _ in () }, self.rx.deallocated).merge() } var rx_prepareForReuseBag: DisposeBag { MainScheduler.ensureExecutingOnScheduler() if let bag = objc_getAssociatedObject(self, &prepareForReuseBag) as? DisposeBag { return bag } let bag = DisposeBag() objc_setAssociatedObject(self, &prepareForReuseBag, bag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) _ = self.rx.sentMessage(#selector(UICollectionReusableView.prepareForReuse)).subscribe(onNext: { [weak self] _ in let newBag = DisposeBag() objc_setAssociatedObject(self as Any, &prepareForReuseBag, newBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }) return bag } } public extension Reactive where Base: UICollectionReusableView { var prepareForReuseBag: DisposeBag { return base.rx_prepareForReuseBag } }
mit
28003504aabf036cf9b02bf219390dd1
28.531915
147
0.679395
4.887324
false
false
false
false