repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
xuephil/Perfect
Examples/Ultimate Noughts and Crosses/Ultimate Noughts and Crosses Server/PlayerBot.swift
2
2623
// // PlayerBot.swift // Ultimate Noughts and Crosses // // Created by Kyle Jessup on 2015-11-16. // Copyright © 2015 PerfectlySoft. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version, as supplemented by the // Perfect Additional Terms. // // This program 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 Affero General Public License, as supplemented by the // Perfect Additional Terms, for more details. // // You should have received a copy of the GNU Affero General Public License // and the Perfect Additional Terms that immediately follow the terms and // conditions of the GNU Affero General Public License along with this // program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>. // import Darwin class PlayerBotRandom: Player { init(gameId: Int, type: PieceType) { super.init(nick: "Random-Bot", gameId: gameId, type: type) } func move(gameState: GameState) { let (_, _, x, y) = gameState.currentPlayer(self.gameId) if x != INVALID_ID { let boardId = gameState.boardId(gameId, x: x, y: y) return self.moveOnBoard(gameState, boardId: boardId) } // we can move on any board // pick an unowned board at random var boards = [Int]() for x in 0..<3 { for y in 0..<3 { let boardId = gameState.boardId(self.gameId, x: x, y: y) let boardOwner = gameState.boardOwner(boardId) if boardOwner == .None { boards.append(boardId) } } } guard boards.count > 0 else { fatalError("It's my turn but there are no valid boards on which to play") } let rnd = arc4random_uniform(UInt32(boards.count)) let boardId = boards[Int(rnd)] self.moveOnBoard(gameState, boardId: boardId) } private func moveOnBoard(gameState: GameState, boardId: Int) { // find a random slot var slots = [Int]() for x in 0..<3 { for y in 0..<3 { let slotId = gameState.slotId(boardId, x: x, y: y) let slotOwner = gameState.slotOwner(slotId) if slotOwner == .None { slots.append(slotId) } } } guard slots.count > 0 else { fatalError("It's my turn but there are no valid slots on which to play") } let rnd = arc4random_uniform(UInt32(slots.count)) let slotId = slots[Int(rnd)] gameState.setSlotOwner(slotId, type: self.type) } }
agpl-3.0
2d525aa2a732157aac9a513e8c9dc843
31.775
92
0.696034
3.289837
false
false
false
false
PJayRushton/stats
Stats/UIFont+stats.swift
1
6026
// // /||\ // / || \ // / )( \ // /__/ \__\ // import UIKit // MARK: - Font Constructable protocol FontContructable { var fontFamily: String? { get } func preferredFont(forTextStyle textStyle: UIFontTextStyle, italicized: Bool) -> UIFont func font(ofSize size: CGFloat) -> UIFont } extension FontContructable { func preferredFont(forTextStyle textStyle: UIFontTextStyle, italicized: Bool = false) -> UIFont { if let fontFamilyName = fontFamily { return customFont(from: fontFamilyName, textStyle: textStyle, italicized: italicized) } else { let defaultDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle) return italicized ? UIFont.italicSystemFont(ofSize: defaultDescriptor.pointSize) : UIFont(descriptor: defaultDescriptor, size: 0) } } func font(ofSize size: CGFloat) -> UIFont { if let fontFamilyName = fontFamily { let descriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptor.AttributeName.family: fontFamilyName]) return UIFont(descriptor: descriptor, size: size) } return UIFont.systemFont(ofSize: size) } private func customFont(from fontFamilyName: String, textStyle: UIFontTextStyle, italicized: Bool = false) -> UIFont { let defaultDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle) let customDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptor.AttributeName.family: fontFamilyName, UIFontDescriptor.AttributeName.family: fontFamilyName]) let size = defaultDescriptor.pointSize if italicized { let italicDescriptor = customDescriptor.withSymbolicTraits(.traitItalic)! if defaultDescriptor.isBold { let boldDescriptor = italicDescriptor.withSymbolicTraits(.traitBold)! return UIFont(descriptor: boldDescriptor, size: size) } return UIFont(descriptor: italicDescriptor, size: size) } if defaultDescriptor.isBold { let boldDescriptor = customDescriptor.withSymbolicTraits(.traitBold)! return UIFont(descriptor: boldDescriptor, size: size) } return UIFont(descriptor: customDescriptor, size: size) } } extension UIFontDescriptor { var isBold: Bool { return symbolicTraits.contains(.traitBold) } } // MARK: - Trait extension UIFont { /// The Trait of the Font /// /// - regular: the default font /// - italic: italic font /// - bold: bold font enum Trait { case regular case italic case bold } struct Courier: FontContructable { var fontFamily: String? { return "Courier" } } struct System: FontContructable { var fontFamily: String? { return nil } } } extension UIFont { static let appFont = system static let courier = Courier() static let system = System() /// Default Size: 34B static var largeTitle: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .largeTitle) } /// Default Size: 28B static var title1: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .title1) } /// Default Size: 22B static var title2: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .title2) } /// Default Size: 20B static var title3: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .title3) } /// Default Size: 17 static var body: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .body) } /// Default Size: 17I static var bodyItalic: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .body, italicized: true) } /// Default Size: 17B static var headline: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .headline) } /// Default Size: 17BI static var headlineItalic: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .headline, italicized: true) } /// Default Size: 16 static var callout: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .callout) } /// Default Size: 15 static var subhead: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .subheadline) } /// Default Size: 13 static var footnote: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .footnote) } /// Default Size: 12B static var caption1: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .caption1) } /// Default Size: 11 static var caption2: UIFont { return UIFont.appFont.preferredFont(forTextStyle: .caption2) } /// Courier: Body static var code: UIFont { return UIFont.courier.preferredFont(forTextStyle: .body) } // MARK: - Computed /// Style: Title3 (20B) static var title: UIFont { return title3 } /// Style: Headline (17B) static var navTitle: UIFont { return headline } /// Style: Body (17) static var barButtonItem: UIFont { return body } /// Style: Callout (16) static var button: UIFont { return callout } /// Style: Callout (16) static var cellTitle: UIFont { return callout } /// Style: Caption1 (12B) static var sectionHeader: UIFont { return caption1 } /// Style: Footnote (13) static var segmentedControl: UIFont { return footnote } /// Style: Caption2 (11) static var tabBarItem: UIFont { return caption2 } /// Style: Caption2 (11) static var cellSubtitle: UIFont { return caption2 } }
mit
9a975814e50fd3a9e1a25886fa0daf5c
25.2
175
0.617159
4.793954
false
false
false
false
VijayMay/WJLive
DouYuTV/DouYuTV/Code/Home/ViewModels/RecommendViewModel.swift
1
3283
// // RecommendViewModel.swift // DouYuTV // // Created by mwj on 17/4/14. // Copyright © 2017年 MWJ. All rights reserved. // import UIKit class RecommendViewModel { // MARK:- 懒加载属性 lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() lazy var hotGroup : AnchorGroup = AnchorGroup() lazy var prettyGroup : AnchorGroup = AnchorGroup() } extension RecommendViewModel{ func requestData(_ finishCallback : @escaping ()->()) { // 定义参数 let parameters = ["limit" : "4", "offset" : "0", "time" : Date.getCurrentTime()] //创建队列 let dGroup = DispatchGroup() //进队列 dGroup.enter() //热门数据 http://capi.douyucdn.cn/api/v1/getbigDataRoom NetworkTools.requestData(type: .get, urlString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" :Date.getCurrentTime]) { (result) in guard let resultDict = result as? [String : Any] else { return } guard let dataArray = resultDict["data"] as? [[String : Any]] else { return } let hotGroup = AnchorGroup() hotGroup.icon_name = "home_header_hot" hotGroup.tag_name = "热门" for dict in dataArray { hotGroup.anchors.append(AnchorModel(dict: dict)) } self.hotGroup = hotGroup //出队列 dGroup.leave() } //进队列 dGroup.enter() //颜值数据 http://capi.douyucdn.cn/api/v1/getVerticalRoom NetworkTools.requestData(type: .get, urlString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in guard let resultDict = result as? [String : Any] else{ return } guard let dataArray = resultDict["data"] as? [[String : Any]] else { return } let prettyGroup = AnchorGroup() prettyGroup.icon_name = "home_header_phone" prettyGroup.tag_name = "颜值" for dict in dataArray { prettyGroup.anchors.append( AnchorModel(dict: dict)) } self.prettyGroup = prettyGroup //出队列 dGroup.leave() } //进队列 dGroup.enter() // 请求2-12部分游戏数据 http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time=1474252024 NetworkTools.requestData(type: .get, urlString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { (result) in guard let resultDict = result as? [String : Any] else { return } guard let dataArray = resultDict["data"] as? [[String : Any]] else{ return } for dict in dataArray{ self.anchorGroups.append(AnchorGroup(dict: dict)) } //出队列 dGroup.leave() } //数据都出列了,进行排序 dGroup.notify(queue: DispatchQueue.main){ self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.hotGroup, at: 0) //完成回调 finishCallback() } } }
mit
8becc8fc1b281cc092e629f92d6a1fec
32.849462
161
0.554638
4.360111
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadKit/Services/Creator/WalletCreator.swift
1
12243
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import Foundation import MetadataKit import ObservabilityKit import ToolKit import WalletCore public enum WalletCreateError: LocalizedError, Equatable { case genericFailure case expectedEncodedPayload case encryptionFailure case uuidFailure case verificationFailure(EncryptAndVerifyError) case mnemonicFailure(MnemonicProviderError) case encodingError(WalletEncodingError) case networkError(NetworkError) case legacyError(LegacyWalletCreationError) case usedAccountsFinderError(UsedAccountsFinderError) } struct WalletCreationContext: Equatable { let mnemonic: String let guid: String let sharedKey: String let accountName: String let totalAccounts: Int } typealias UUIDProvider = () -> AnyPublisher<(guid: String, sharedKey: String), WalletCreateError> typealias GenerateWalletProvider = (WalletCreationContext) -> Result<NativeWallet, WalletCreateError> typealias GenerateWrapperProvider = (NativeWallet, String, WalletVersion) -> Wrapper typealias ProcessWalletCreation = ( _ context: WalletCreationContext, _ email: String, _ password: String, _ language: String, _ recaptchaToken: String?, _ siteKey: String ) -> AnyPublisher<WalletCreation, WalletCreateError> public protocol WalletCreatorAPI { /// Creates a new wallet using the given email and password. /// - Returns: `AnyPublisher<WalletCreation, WalletCreateError>` func createWallet( email: String, password: String, accountName: String, recaptchaToken: String?, siteKey: String, language: String ) -> AnyPublisher<WalletCreation, WalletCreateError> /// Imports and creates a new wallet from the mnemonic and using the given email and password. /// - Returns: `AnyPublisher<WalletCreation, WalletCreateError>` func importWallet( mnemonic: String, email: String, password: String, accountName: String, language: String ) -> AnyPublisher<WalletCreation, WalletCreateError> } final class WalletCreator: WalletCreatorAPI { private let entropyService: RNGServiceAPI private let walletEncoder: WalletEncodingAPI private let encryptor: PayloadCryptoAPI private let createWalletRepository: CreateWalletRepositoryAPI private let usedAccountsFinder: UsedAccountsFinderAPI private let operationQueue: DispatchQueue private let tracer: LogMessageServiceAPI private let uuidProvider: UUIDProvider private let generateWallet: GenerateWalletProvider private let generateWrapper: GenerateWrapperProvider private let logger: NativeWalletLoggerAPI private let checksumProvider: (Data) -> String private let processWalletCreation: ProcessWalletCreation init( entropyService: RNGServiceAPI, walletEncoder: WalletEncodingAPI, encryptor: PayloadCryptoAPI, createWalletRepository: CreateWalletRepositoryAPI, usedAccountsFinder: UsedAccountsFinderAPI, operationQueue: DispatchQueue, logger: NativeWalletLoggerAPI, tracer: LogMessageServiceAPI, uuidProvider: @escaping UUIDProvider, generateWallet: @escaping GenerateWalletProvider, generateWrapper: @escaping GenerateWrapperProvider, checksumProvider: @escaping (Data) -> String ) { self.uuidProvider = uuidProvider self.walletEncoder = walletEncoder self.encryptor = encryptor self.createWalletRepository = createWalletRepository self.usedAccountsFinder = usedAccountsFinder self.operationQueue = operationQueue self.logger = logger self.tracer = tracer self.entropyService = entropyService self.generateWallet = generateWallet self.generateWrapper = generateWrapper self.checksumProvider = checksumProvider processWalletCreation = provideProcessCreationOfWallet( walletEncoder: walletEncoder, encryptor: encryptor, createWalletRepository: createWalletRepository, logger: logger, generateWallet: generateWallet, generateWrapper: generateWrapper, checksumProvider: checksumProvider ) } func createWallet( email: String, password: String, accountName: String, recaptchaToken: String?, siteKey: String, language: String = "en" ) -> AnyPublisher<WalletCreation, WalletCreateError> { provideMnemonic( strength: .normal, queue: operationQueue, entropyProvider: entropyService.generateEntropy(count:) ) .mapError(WalletCreateError.mnemonicFailure) .receive(on: operationQueue) .flatMap { [uuidProvider] mnemonic -> AnyPublisher<WalletCreationContext, WalletCreateError> in uuidProvider() .map { guid, sharedKey in WalletCreationContext( mnemonic: mnemonic, guid: guid, sharedKey: sharedKey, accountName: accountName, totalAccounts: 1 ) } .eraseToAnyPublisher() } .flatMap { [processWalletCreation] context -> AnyPublisher<WalletCreation, WalletCreateError> in processWalletCreation( context, email, password, language, recaptchaToken, siteKey ) } .logErrorOrCrash(tracer: tracer) .eraseToAnyPublisher() } func importWallet( mnemonic: String, email: String, password: String, accountName: String, language: String ) -> AnyPublisher<WalletCreation, WalletCreateError> { hdWallet(from: mnemonic) .subscribe(on: operationQueue) .receive(on: operationQueue) .map(\.seed.toHexString) .map { masterNode -> (MetadataKit.PrivateKey, MetadataKit.PrivateKey) in let legacy = deriveMasterAccountKey(masterNode: masterNode, type: .legacy) let bech32 = deriveMasterAccountKey(masterNode: masterNode, type: .segwit) return (legacy, bech32) } .flatMap { [usedAccountsFinder] legacy, bech32 -> AnyPublisher<Int, WalletCreateError> in usedAccountsFinder .findUsedAccounts( batch: 10, xpubRetriever: generateXpub(legacyKey: legacy, bech32Key: bech32) ) .map { totalAccounts in // we still need to create one account in case account discovery returned zero. max(1, totalAccounts) } .mapError(WalletCreateError.usedAccountsFinderError) .eraseToAnyPublisher() } .flatMap { [uuidProvider] totalAccounts -> AnyPublisher<WalletCreationContext, WalletCreateError> in uuidProvider() .map { guid, sharedKey in WalletCreationContext( mnemonic: mnemonic, guid: guid, sharedKey: sharedKey, accountName: accountName, totalAccounts: totalAccounts ) } .eraseToAnyPublisher() } .flatMap { [processWalletCreation] context -> AnyPublisher<WalletCreation, WalletCreateError> in processWalletCreation( context, email, password, language, nil, "" ) } .logErrorOrCrash(tracer: tracer) .eraseToAnyPublisher() } func hdWallet( from mnemonic: String ) -> AnyPublisher<WalletCore.HDWallet, WalletCreateError> { Deferred { Future<WalletCore.HDWallet, WalletCreateError> { promise in switch getHDWallet(from: mnemonic) { case .success(let wallet): promise(.success(wallet)) case .failure(let error): promise(.failure(error)) } } } .eraseToAnyPublisher() } } /// Final process for creating a wallet /// 1. Create the wallet and wrapper /// 2. Encrypt and verify the wrapper /// 3. Encode the wrapper payload /// 4. Create the wallet on the backend /// 5. Return a `WalletCreation` or failure if any // swiftlint:disable function_parameter_count private func provideProcessCreationOfWallet( walletEncoder: WalletEncodingAPI, encryptor: PayloadCryptoAPI, createWalletRepository: CreateWalletRepositoryAPI, logger: NativeWalletLoggerAPI, generateWallet: @escaping GenerateWalletProvider, generateWrapper: @escaping GenerateWrapperProvider, checksumProvider: @escaping (Data) -> String ) -> ProcessWalletCreation { { context, email, password, language, recaptchaToken, siteKey -> AnyPublisher<WalletCreation, WalletCreateError> in generateWallet(context) .map { wallet -> Wrapper in generateWrapper(wallet, language, WalletVersion.v4) } .publisher .eraseToAnyPublisher() .flatMap { [walletEncoder, encryptor, logger] wrapper -> AnyPublisher<EncodedWalletPayload, WalletCreateError> in encryptAndVerifyWrapper( walletEncoder: walletEncoder, encryptor: encryptor, logger: logger, password: password, wrapper: wrapper ) .mapError(WalletCreateError.verificationFailure) .eraseToAnyPublisher() } .flatMap { [walletEncoder, checksumProvider] payload -> AnyPublisher<WalletCreationPayload, WalletCreateError> in walletEncoder.encode(payload: payload, applyChecksum: checksumProvider) .mapError(WalletCreateError.encodingError) .eraseToAnyPublisher() } .flatMap { [createWalletRepository] payload -> AnyPublisher<WalletCreationPayload, WalletCreateError> in createWalletRepository.createWallet( email: email, payload: payload, recaptchaToken: recaptchaToken, siteKey: siteKey ) .map { _ in payload } .mapError(WalletCreateError.networkError) .eraseToAnyPublisher() } .map { payload in WalletCreation( guid: payload.guid, sharedKey: payload.sharedKey, password: password ) } .eraseToAnyPublisher() } } /// Provides UUIDs to be used as guid and sharedKey in wallet creation /// - Returns: `AnyPublisher<(guid: String, sharedKey: String), WalletCreateError>` func uuidProvider() -> AnyPublisher<(guid: String, sharedKey: String), WalletCreateError> { let guid = UUID().uuidString.lowercased() let sharedKey = UUID().uuidString.lowercased() guard guid.count == 36 || sharedKey.count == 36 else { return .failure(.uuidFailure) } return .just((guid, sharedKey)) } /// (LegacyKey, Bech32Key) -> (DerivationType, Index) -> String func generateXpub( legacyKey: MetadataKit.PrivateKey, bech32Key: MetadataKit.PrivateKey ) -> XpubRetriever { { type, index -> String in switch type { case .legacy: return legacyKey.derive(at: .hardened(UInt32(index))).xpub case .segwit: return bech32Key.derive(at: .hardened(UInt32(index))).xpub } } }
lgpl-3.0
a69c131b824f5c00684d32af227c7c01
36.552147
119
0.613462
5.374012
false
false
false
false
billdonner/sheetcheats9
sc9/PlatformMasterViewController.swift
1
3315
// // PlatformMasterViewController.swift // UIPageViewController Post // // import UIKit class PlatformMasterViewController: UIViewController { //@IBOutlet weak //var containerView: UIView! // var platformPageViewController: PlatformPageViewController? { // didSet { // platformPageViewController?.platformDelegate = self // } // } override var prefersStatusBarHidden: Bool { get { return true } } func addSubview(subView:UIView,toView parentView:UIView) { parentView.addSubview(subView) var viewBindingsDict = [String: AnyObject]() viewBindingsDict["subView"] = subView parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { self.view.setNeedsLayout() } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Col.r(.tableBackground) AppDelegate.tinyPrint("SC9 logging to TinyConsole") // self.containerView = UIView(frame:self.view.bounds) // self.view.addSubview(self.containerView) //let storyboard = UIStoryboard(name:"Main",bundle:nil) //if let vc = storyboard.instantiateViewController(withIdentifier: "PlatformPageViewControllerID") as? PlatformPageViewController { let vc = PlatformPageViewController() vc.platformDelegate = self vc.view.translatesAutoresizingMaskIntoConstraints = false self.addChildViewController( vc) self.addSubview(subView: vc.view, toView: self.view) vc.didMove(toParentViewController: self) // self.platformPageViewController = vc //} } } // override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // if let platformPageViewController = segue.destination as? PlatformPageViewController { // self.platformPageViewController = platformPageViewController // } // } // @IBAction func didTapNextButton(_ sender: UIButton) { // platformPageViewController?.scrollToNextViewController() // } /** Fired when the user taps on the pageControl to change its current page. */ // func didChangePageControlValue() { // platformPageViewController?.scrollToViewController(index: pageControl.currentPage) // } //} extension PlatformMasterViewController: PlatformPageViewControllerDelegate { func platformPageViewController(_ platformPageViewController: PlatformPageViewController, didUpdatePageCount count: Int) { // pageControl.numberOfPages = count } func platformPageViewController(_ platformPageViewController: PlatformPageViewController, didUpdatePageIndex index: Int) { // pageControl.currentPage = index } }
apache-2.0
f85c83a7e89f789c35fb716a858d1219
34.265957
153
0.660332
5.543478
false
false
false
false
elpassion/el-space-ios
ELSpace/Commons/Validators/EmailValidator.swift
1
1236
import RxSwift protocol EmailValidation { var error: Observable<Error> { get } func validateEmail(email: String, hostedDomain: String) -> Bool } class EmailValidator: EmailValidation { enum EmailValidationError: String, Error { case emailFormat = "Incorrect email format" case incorrectDomain = "Incorrect domain" } // MARK: - EmailValidation var error: Observable<Error> { return errorSubject.asObservable() } func validateEmail(email: String, hostedDomain: String) -> Bool { if isValidEmail(email: email) == false { errorSubject.onNext(EmailValidator.EmailValidationError.emailFormat) } else if isValidDomain(email: email, hostedDomain: hostedDomain) == false { errorSubject.onNext(EmailValidator.EmailValidationError.incorrectDomain) } else { return true } return false } // MARK: - Private private func isValidEmail(email: String) -> Bool { return email.isValidEmail() } private func isValidDomain(email: String, hostedDomain: String) -> Bool { return email.emailDomain() == hostedDomain } private let errorSubject = PublishSubject<Error>() }
gpl-3.0
c21b161681ec7dbaeff0cef2cf203ed2
25.869565
84
0.661812
4.717557
false
false
false
false
taktem/TAKSwiftSupport
TAKSwiftSupport/Core/Model/HttpRequest/RequestBase.swift
1
8221
// // RequestBase.swift // TAKSwiftSupport // // Created by 西村 拓 on 2015/11/06. // Copyright © 2015年 TakuNishimura. All rights reserved. // import UIKit import Alamofire import RxSwift import ObjectMapper public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } /// APiリクエストのベースとなるクラス public class RequestBase: NSObject { /// Rx public let requestDisposeBag = DisposeBag() // Time out public static var timeoutIntervalForRequest = NSTimeInterval(15.0) { didSet { manager = RequestBase.updateManager() } } public static var timeoutIntervalForResource = NSTimeInterval(20.0) { didSet { manager = RequestBase.updateManager() } } // Cache Policy public static var cachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy { didSet { manager = RequestBase.updateManager() } } /// Alamofire object private static var manager: Manager = RequestBase.updateManager() private final class func updateManager() -> Manager { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders // Time out configuration.timeoutIntervalForRequest = RequestBase.timeoutIntervalForRequest configuration.timeoutIntervalForResource = RequestBase.timeoutIntervalForResource // Cache policy configuration.requestCachePolicy = RequestBase.cachePolicy return Manager(configuration: configuration) } // Requestオブジェクト private var request: Request? /** 基礎設定を指定してリクエストオブジェクト生成 - parameter hostName: FQDN - parameter path: URLパス - parameter method: httpメソッド - parameter parameters: クエリ - parameter encording: リクエストエンコードタイプ */ public final func createRequest( hostName hostName: String, path: String, method: Method, parameters: [String: AnyObject], encording: ParameterEncoding, headers: [String: String]) -> Request? { guard let requestUrl = hostName.appending(pathComponent: path) else { return nil } request = RequestBase.manager.request( Alamofire.Method(rawValue: method.rawValue)!, requestUrl, parameters: parameters, encoding: encording, headers: headers) return request } /** Add basic authentication - parameter user: username - parameter password: password */ public final func authenticate(user: String?, password: String?) { guard let user = user, password = password else { return } request?.authenticate(user: user, password: password) } /** レスポンス形式がJsonの場合、Entityを指定してObjectMapperでマッピングまで行う - returns: <T: Responsible> */ public final func requestJson<T: Responsible>( ) -> Observable<T> { let source: Observable<T> = Observable.create { [weak self] (observer: AnyObserver<T>) in let _ = self?.responseJson() .subscribe( onNext: { jsonString in if let mapper = Mapper<T>().map(jsonString) { observer.onNext(mapper) observer.onCompleted() self?.successLog(jsonString) } else { let error = NSError(errorType: .ModelMappingError) observer.onError(error) self?.errorLog(error) } }, onError: { error in observer.onError(error) }, onCompleted: { }, onDisposed: { } ) return AnonymousDisposable { } } return source } /** レスポンス形式がルート配列のJsonの場合、Entityを指定してObjectMapperでマッピングまで行う - returns: <T: [Responsible]> */ public final func requestJson<T: Responsible>( ) -> Observable<[T]> { let source: Observable<[T]> = Observable.create { [weak self] (observer: AnyObserver<[T]>) in let _ = self?.responseJson() .subscribe( onNext: { jsonString in if let mapper = Mapper<T>().mapArray(jsonString) { observer.onNext(mapper) observer.onCompleted() self?.successLog(jsonString) } else { let error = NSError(errorType: .ModelMappingError) observer.onError(error) self?.errorLog(error) } }, onError: { error in observer.onError(error) }, onCompleted: { }, onDisposed: { } ) return AnonymousDisposable { } } return source } //MARK: - Util /** レスポンスをJsonマッピングする */ private final func responseJson() -> Observable<String> { let source: Observable<String> = Observable.create { [weak self] (observer: AnyObserver<String>) in self?.request?.responseData { [weak self] response in let result = self?.mappingJson(response: response) if let jsonString = result?.jsonString { observer.onNext(jsonString) observer.onCompleted() } else if let error = result?.error { observer.onError(error) self?.errorLog(error) } } return AnonymousDisposable { } } return source } /** JsonString from Response */ private final func mappingJson(response response: Response<NSData, NSError>?) -> (jsonString: String?, error: NSError?) { // 入力値がない場合 guard let response = response else { return (nil, NSError(errorType: .JsonMappingError)) } switch response.result { case .Success(let value): if let jsonString = self.jsonString(value) { return (jsonString, nil) } else { return (nil, NSError(errorType: .JsonMappingError)) } case .Failure(let error): return (nil, error) } } /** NSData to Json */ private final func jsonString(data: NSData) -> String? { var buffer = [UInt8](count:data.length, repeatedValue:0) data.getBytes(&buffer, length:data.length) if let jsonString = String(bytes:buffer, encoding:NSJapaneseEUCStringEncoding) { return jsonString } else if let jsonString = String(bytes:buffer, encoding:NSUTF8StringEncoding) { return jsonString } return nil } //MARK: - Log /** Success log */ private final func successLog(resultMessage: String) { DLog("\(self.request?.request?.URL):Result = \(resultMessage)") } /** Error log */ private final func errorLog(error: NSError) { DLog("\(self.request?.request?.URL):Error(\(error.code) = \(error.localizedDescription)") } }
mit
2231eb6126d2ed971ee024cfc96c3e42
29.9375
125
0.522348
5.402456
false
false
false
false
abertelrud/swift-package-manager
Sources/Commands/PackageTools/Init.swift
2
2301
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2022 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 ArgumentParser import Basics import CoreCommands import Workspace extension SwiftPackageTool { struct Init: SwiftCommand { public static let configuration = CommandConfiguration( abstract: "Initialize a new package") @OptionGroup(_hiddenFromHelp: true) var globalOptions: GlobalOptions @Option( name: .customLong("type"), help: ArgumentHelp("Package type: empty | library | executable | system-module | manifest", discussion: """ empty - Create an empty package library - Create a package that contains a library executable - Create a package that contains a binary executable system-module - Create a package that contains a system module manifest - Create a Package.swift file """)) var initMode: InitPackage.PackageType = .library @Option(name: .customLong("name"), help: "Provide custom package name") var packageName: String? func run(_ swiftTool: SwiftTool) throws { guard let cwd = swiftTool.fileSystem.currentWorkingDirectory else { throw InternalError("Could not find the current working directory") } let packageName = self.packageName ?? cwd.basename let initPackage = try InitPackage( name: packageName, packageType: initMode, destinationPath: cwd, fileSystem: swiftTool.fileSystem ) initPackage.progressReporter = { message in print(message) } try initPackage.writePackageStructure() } } } extension InitPackage.PackageType: ExpressibleByArgument {}
apache-2.0
71ae63d686eae03204b669588face4db
37.35
119
0.587571
5.869898
false
false
false
false
everlof/RestKit-n-Django-Sample
Project_iOS/Cite/Quote.swift
1
2823
// // Quote.swift // Cite // // Created by David Everlöf on 06/08/16. // // import Foundation import CoreData class Quote: RemoteEntity { static let listName = "LIST_QUOTES" static let mapping: RKEntityMapping = { let mapping = RKEntityMapping( forEntityForName: String(Quote), inManagedObjectStore: appDelegate().managedObjectStore) mapping.identificationAttributes = [ "pk" ] mapping.addAttributeMappingsFromDictionary([ "pk": "pk", "quote": "quote", "author": "author", "created": "created", "modified": "modified", ]) mapping.addPropertyMapping( RKRelationshipMapping( fromKeyPath: "likers", toKeyPath: "likers", withMapping: User.mapping) ) mapping.addPropertyMapping( RKRelationshipMapping( fromKeyPath: "owner", toKeyPath: "owner", withMapping: User.mapping) ) mapping.addPropertyMapping( RKRelationshipMapping( fromKeyPath: "hashtags", toKeyPath: "hashtags", withMapping: HashTag.mapping) ) return mapping }() static let reqMapping: RKEntityMapping = { let mapping = RKEntityMapping( forEntityForName: String(Quote), inManagedObjectStore: appDelegate().managedObjectStore) mapping.identificationAttributes = [ "pk" ] mapping.addAttributeMappingsFromDictionary([ "pk": "pk", "quote": "quote", "author": "author", "owner": "owner.pk" ]) return mapping }() override class func rkSetupRouter() { RKObjectManager.sharedManager().addResponseDescriptorsFromArray([ RKResponseDescriptor( mapping: mapping, method: .Any, pathPattern: "/quotes/:pk/", keyPath: nil, statusCodes: RKStatusCodeIndexSetForClass(.Successful) ), RKResponseDescriptor( mapping: mapping, method: .Any, pathPattern: "/quotes/", keyPath: nil, statusCodes: RKStatusCodeIndexSetForClass(.Successful) ) ]) RKObjectManager.sharedManager().addRequestDescriptorsFromArray([ RKRequestDescriptor( mapping: reqMapping.inverseMapping(), objectClass: Quote.self, rootKeyPath: nil, method: .Any ) ]) RKObjectManager.sharedManager().router.routeSet.addRoutes([ RKRoute(name: Quote.listName, pathPattern: "/quotes/", method: .GET), RKRoute(withClass: Quote.self, pathPattern: "/quotes/:pk/", method: .GET), RKRoute(withClass: Quote.self, pathPattern: "/quotes/", method: .POST), RKRoute(withClass: Quote.self, pathPattern: "/quotes/:pk/", method: .PUT), RKRoute(withClass: Quote.self, pathPattern: "/quotes/:pk/", method: .DELETE) ]) } }
mit
a56187f8d1e96b0282a40b0562a49b3a
25.12963
82
0.622608
4.430141
false
false
false
false
kiliankoe/ParkenDD
ParkenDD/Colors.swift
1
3017
// // Colors.swift // ParkenDD // // Created by Kilian Költzsch on 06/04/15. // Copyright (c) 2015 Kilian Koeltzsch. All rights reserved. // import UIKit struct Colors { static let favYellow = UIColor(rgba: "#F9E510") static let unfavYellow = UIColor(rgba: "#F4E974") /** Return a color between green and red based on a percentage value - parameter percentage: value between 0 and 1 - parameter emptyLots: number of empty lots - returns: UIColor */ static func colorBasedOnPercentage(_ percentage: Double, emptyLots: Int) -> UIColor { let hue = 1 - (percentage * 0.3 + 0.7) // I want to limit this to the colors between 0 and 0.3 let useGrayscale = UserDefaults.standard.bool(forKey: Defaults.grayscaleUI) if useGrayscale { if emptyLots <= 0 { return UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0) } return UIColor(red: CGFloat(1 - (hue+0.2)), green: CGFloat(1 - (hue+0.2)), blue: CGFloat(1 - (hue+0.2)), alpha: 1.0) } if emptyLots <= 0 { return UIColor(hue: CGFloat(hue), saturation: 0.54, brightness: 0.7, alpha: 1.0) } return UIColor(hue: CGFloat(hue), saturation: 0.54, brightness: 0.8, alpha: 1.0) } } extension UIColor { /** Initializes and returns a color object from a given hex string. Props to github.com/yeahdongcn/UIColor-Hex-Swift - parameter rgba: hex string - returns: color object */ convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = rgba.characters.index(rgba.startIndex, offsetBy: 1) let hex = rgba.substring(from: index) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch hex.characters.count { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: preconditionFailure("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8") } } else { preconditionFailure("Scan hex error") } } else { preconditionFailure("Invalid RGB string, missing '#' as prefix") } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
mit
84ab9e7090f6ca4da98310f94e5af5b5
31.430108
119
0.627984
3.068159
false
false
false
false
joelconnects/FlipTheBlinds
FlipTheBlinds/IBNavRootViewController.swift
1
1927
// // IBNavRootViewController.swift // FlipTheBlinds // // Created by Joel Bell on 1/2/17. // Copyright © 2017 Joel Bell. All rights reserved. // import UIKit // MARK: Main class IBNavRootViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() configImageView() // POD: Set UINavigationControllerDelegate self.navigationController?.delegate = self } } // MARK: Configure View extension IBNavRootViewController { private func configImageView() { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = #imageLiteral(resourceName: "noCoupleImage") view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true imageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true } } // POD: Add Navigtation Extension extension IBNavRootViewController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { switch operation { case .pop: return FTBAnimationController(displayType: .pop, direction: .right, speed: .moderate) case .push: return FTBAnimationController(displayType: .push, direction: .left, speed: .moderate) default: return nil } } }
mit
c86d07f620dfb5cb2fd4b0fd07fd698e
27.746269
247
0.677051
5.487179
false
false
false
false
denizsokmen/Raid
Raid/BugReport.swift
1
1138
// // BugReport.swift // Raid // // Created by student7 on 30/12/14. // Copyright (c) 2014 student7. All rights reserved. // import Foundation class BugReport { var description: String! var title: String! var priority: Int! var solved: Bool! var id: Int! var assignee: Int! var assigner: Int! init(nm : String, prio: Int) { title = nm priority = prio id = 1 solved = false } init(dict : [String:AnyObject]) { self.description = dict["desc"] as String self.title = dict["title"] as String self.priority = dict["priority"] as Int self.id = dict["id"] as Int self.solved = dict["solved"] as Bool self.assignee = dict["assignee"] as Int self.assigner = dict["assigner"] as Int } func convertToDict() -> [String: AnyObject] { var dict : [String: AnyObject] = ["desc": self.description, "title": self.title, "solved": self.solved, "id": self.id, "priority": self.priority, "assignee": self.assignee, "assigner": self.assigner] return dict } }
gpl-2.0
cf38fafaa33c6eeab2439cbc03c49fa2
24.288889
207
0.572935
3.755776
false
false
false
false
jdbateman/Lendivine
OAuthSwift-master/OAuthSwiftDemo/KivaLender.swift
1
2546
// // KivaLender.swift // OAuthSwift // // Created by john bateman on 10/29/15. // Copyright © 2015 Dongri Jin. All rights reserved. // import Foundation class KivaLender { var countryCode: String = "" var inviteeCount: NSNumber = 0 var lenderID: String = "" var loanBecause: String = "" var loanCount: NSNumber = 0 var memberSince: String = "" var name: String = "" var occupation: String = "" var occupationalInfo: String = "" var personalUrl: String = "" var uid: String = "" var whereabouts: String = "" var imageID: NSNumber = -1 var imageTemplateID: NSNumber = -1 // designated initializer init(dictionary: [String: AnyObject]?) { if let dictionary = dictionary { if let country = dictionary["country_code"] as? String { countryCode = country } if let count = dictionary["invitee_count"] as? NSNumber { inviteeCount = count } if let liD = dictionary["lender_id"] as? String { lenderID = liD } if let because = dictionary["loan_because"] as? String { loanBecause = because } if let lcount = dictionary["loan_count"] as? NSNumber { loanCount = lcount } if let since = dictionary["member_since"] as? String { memberSince = since } if let n = dictionary["name"] as? String { name = n } if let oc = dictionary["occupation"] as? String { occupation = oc } if let occupational = dictionary["occupational_info"] as? String { occupationalInfo = occupational } if let personal = dictionary["personal_url"] as? String { personalUrl = personal } if let iD = dictionary["uid"] as? String { uid = iD } if let location = dictionary["whereabouts"] as? String { whereabouts = location } // image if let imageDict = dictionary["image"] as? [String: AnyObject] { if let templateId = imageDict["template_id"] as? NSNumber { imageTemplateID = templateId } if let imgId = imageDict["id"] as? NSNumber { imageID = imgId } } } } }
mit
62ff8d276aef9c014f4d36cc62f08dd9
31.227848
78
0.504519
4.686924
false
false
false
false
BlurredSoftware/BSWInterfaceKit
Sources/BSWInterfaceKit/Operations/PresentAlertOperation.swift
1
2285
// // Created by Pierluigi Cifani on 20/03/2017. // #if canImport(UIKit) import UIKit class PresentAlertOperation: Operation { let title: String? let message: String? weak var presentingViewController: UIViewController? init(title: String?, message: String?, presentingViewController: UIViewController) { self.title = title self.message = message self.presentingViewController = { //Find the parent in the hierarchy var parentVC: UIViewController! = presentingViewController while parentVC.parent != nil { parentVC = parentVC.parent } return parentVC }() super.init() } override func main() { guard isCancelled == false else { self.finishOperation() return } self.isExecuting = true self.isFinished = false OperationQueue.main.addOperation { guard let presentingViewController = self.presentingViewController, let _ = presentingViewController.view.window else { self.finishOperation() return } let alert = UIAlertController(title: self.title, message: self.message, preferredStyle: .alert) let action = UIAlertAction(title: "dismiss".localized, style: .cancel) { _ in self.finishOperation() } alert.addAction(action) presentingViewController.present(alert, animated: true, completion: nil) } } //Don't look here, it's disgusting var _finished = false var _executing = false override var isExecuting: Bool { get { return _executing } set { willChangeValue(forKey: "isExecuting") _executing = newValue didChangeValue(forKey: "isExecuting") } } override var isFinished: Bool { get { return _finished } set { willChangeValue(forKey: "isFinished") _finished = newValue didChangeValue(forKey: "isFinished") } } private func finishOperation() { self.isExecuting = false self.isFinished = true } } #endif
mit
305b44e075f1ab81f61f88eaaae95c27
25.569767
131
0.575055
5.414692
false
false
false
false
jdkelley/Udacity-OnTheMap-ExampleApps
MyFavoriteMovies/MyFavoriteMovies/GenreTableViewController.swift
1
7707
// // GenreTableViewController.swift // MyFavoriteMovies // // Created by Jarrod Parkes on 1/23/15. // Copyright (c) 2015 Udacity. All rights reserved. // import UIKit // MARK: - GenreTableViewController: UITableViewController class GenreTableViewController: UITableViewController { // MARK: Properties var appDelegate: AppDelegate! var movies: [Movie] = [Movie]() var genreID: Int? = nil // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() // get the app delegate appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // get the correct genre id genreID = genreIDFromItemTag(tabBarItem.tag) // create and set logout button navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Reply, target: self, action: #selector(logout)) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) /* TASK: Get movies by a genre id, then populate the table */ /* 1. Set the parameters */ let methodParameters = [ Constants.TMDBParameterKeys.ApiKey: Constants.TMDBParameterValues.ApiKey, ] /* 2/3. Build the URL, Configure the request */ let request = NSMutableURLRequest(URL: appDelegate.tmdbURLFromParameters(methodParameters, withPathExtension: "/genre/\(genreID!)/movies")) request.addValue("application/json", forHTTPHeaderField: "Accept") /* 4. Make the request */ let task = appDelegate.sharedSession.dataTaskWithRequest(request) { (data, response, error) in /* GUARD: Was there an error? */ guard (error == nil) else { print("There was an error with your request: \(error)") return } /* GUARD: Did we get a successful 2XX response? */ guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else { print("Your request returned a status code other than 2xx!") return } /* GUARD: Was there any data returned? */ guard let data = data else { print("No data was returned by the request!") return } /* 5. Parse the data */ let parsedResult: AnyObject! do { parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) } catch { print("Could not parse the data as JSON: '\(data)'") return } /* GUARD: Did TheMovieDB return an error? */ if let _ = parsedResult[Constants.TMDBResponseKeys.StatusCode] as? Int { print("TheMovieDB returned an error. See the '\(Constants.TMDBResponseKeys.StatusCode)' and '\(Constants.TMDBResponseKeys.StatusMessage)' in \(parsedResult)") return } /* GUARD: Is the "results" key in parsedResult? */ guard let results = parsedResult[Constants.TMDBResponseKeys.Results] as? [[String:AnyObject]] else { print("Cannot find key '\(Constants.TMDBResponseKeys.Results)' in \(parsedResult)") return } /* 6. Use the data! */ self.movies = Movie.moviesFromResults(results) performUIUpdatesOnMain { self.tableView.reloadData() } } /* 7. Start the request */ task.resume() } // MARK: Logout func logout() { dismissViewControllerAnimated(true, completion: nil) } } // MARK: - GenreTableViewController (UITableViewController) extension GenreTableViewController { override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // get cell type let cellReuseIdentifier = "MovieTableViewCell" let movie = movies[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell! // set cell defaults cell.textLabel!.text = movie.title cell.imageView!.image = UIImage(named: "Film Icon") cell.imageView!.contentMode = UIViewContentMode.ScaleAspectFit /* TASK: Get the poster image, then populate the image view */ if let posterPath = movie.posterPath { /* 1. Set the parameters */ // There are none... /* 2. Build the URL */ let baseURL = NSURL(string: appDelegate.config.baseImageURLString)! let url = baseURL.URLByAppendingPathComponent("w154").URLByAppendingPathComponent(posterPath) /* 3. Configure the request */ let request = NSURLRequest(URL: url) /* 4. Make the request */ let task = appDelegate.sharedSession.dataTaskWithRequest(request) { (data, response, error) in /* GUARD: Was there an error? */ guard (error == nil) else { print("There was an error with your request: \(error)") return } /* GUARD: Did we get a successful 2XX response? */ guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else { print("Your request returned a status code other than 2xx!") return } /* GUARD: Was there any data returned? */ guard let data = data else { print("No data was returned by the request!") return } /* 5. Parse the data */ // No need, the data is already raw image data. /* 6. Use the data! */ if let image = UIImage(data: data) { performUIUpdatesOnMain { cell.imageView!.image = image } } else { print("Could not create image from \(data)") } } /* 7. Start the request */ task.resume() } return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // push the movie detail view let controller = storyboard!.instantiateViewControllerWithIdentifier("MovieDetailViewController") as! MovieDetailViewController controller.movie = movies[indexPath.row] navigationController!.pushViewController(controller, animated: true) } } // MARK: - GenreTableViewController (Genre Map) extension GenreTableViewController { private func genreIDFromItemTag(itemTag: Int) -> Int { let genres: [String] = [ "Sci-Fi", "Comedy", "Action" ] let genreMap: [String:Int] = [ "Action": 28, "Sci-Fi": 878, "Comedy": 35 ] return genreMap[genres[itemTag]]! } }
mit
bc78660ceed59157d2746cf465d395c7
34.680556
174
0.551187
5.605091
false
false
false
false
nathawes/swift
test/AutoDiff/stdlib/anydifferentiable.swift
9
6921
// RUN: %target-run-simple-swift // REQUIRES: executable_test import _Differentiation import StdlibUnittest var TypeErasureTests = TestSuite("DifferentiableTypeErasure") struct Vector: Differentiable, Equatable { var x, y: Float } struct Generic<T: Differentiable & Equatable>: Differentiable, Equatable { var x: T } extension AnyDerivative { // This exists only to faciliate testing. func moved(along direction: TangentVector) -> Self { var result = self result.move(along: direction) return result } } TypeErasureTests.test("AnyDifferentiable operations") { do { var any = AnyDifferentiable(Vector(x: 1, y: 1)) let tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1)) any.move(along: tan) expectEqual(Vector(x: 2, y: 2), any.base as? Vector) } do { var any = AnyDifferentiable(Generic<Float>(x: 1)) let tan = AnyDerivative(Generic<Float>.TangentVector(x: 1)) any.move(along: tan) expectEqual(Generic<Float>(x: 2), any.base as? Generic<Float>) } } TypeErasureTests.test("AnyDerivative operations") { do { var tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1)) tan += tan expectEqual(AnyDerivative(Vector.TangentVector(x: 2, y: 2)), tan) expectEqual(AnyDerivative(Vector.TangentVector(x: 4, y: 4)), tan + tan) expectEqual(AnyDerivative(Vector.TangentVector(x: 0, y: 0)), tan - tan) expectEqual(AnyDerivative(Vector.TangentVector(x: 4, y: 4)), tan.moved(along: tan)) expectEqual(AnyDerivative(Vector.TangentVector(x: 2, y: 2)), tan) } do { var tan = AnyDerivative(Generic<Float>.TangentVector(x: 1)) tan += tan expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 2)), tan) expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 4)), tan + tan) expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 0)), tan - tan) expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 4)), tan.moved(along: tan)) } } TypeErasureTests.test("AnyDerivative.zero") { var zero = AnyDerivative.zero zero += zero zero -= zero expectEqual(zero, zero + zero) expectEqual(zero, zero - zero) expectEqual(zero, zero.moved(along: zero)) var tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1)) expectEqual(zero, zero) expectEqual(AnyDerivative(Vector.TangentVector.zero), tan - tan) expectNotEqual(AnyDerivative(Vector.TangentVector.zero), zero) expectNotEqual(AnyDerivative.zero, tan - tan) tan += zero tan -= zero expectEqual(tan, tan + zero) expectEqual(tan, tan - zero) expectEqual(tan, tan.moved(along: zero)) expectEqual(tan, zero.moved(along: tan)) expectEqual(zero, zero) expectEqual(tan, tan) } TypeErasureTests.test("AnyDifferentiable casting") { let any = AnyDifferentiable(Vector(x: 1, y: 1)) expectEqual(Vector(x: 1, y: 1), any.base as? Vector) let genericAny = AnyDifferentiable(Generic<Float>(x: 1)) expectEqual(Generic<Float>(x: 1), genericAny.base as? Generic<Float>) expectEqual(nil, genericAny.base as? Generic<Double>) } TypeErasureTests.test("AnyDerivative casting") { let tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1)) expectEqual(Vector.TangentVector(x: 1, y: 1), tan.base as? Vector.TangentVector) let genericTan = AnyDerivative(Generic<Float>.TangentVector(x: 1)) expectEqual(Generic<Float>.TangentVector(x: 1), genericTan.base as? Generic<Float>.TangentVector) expectEqual(nil, genericTan.base as? Generic<Double>.TangentVector) let zero = AnyDerivative.zero expectEqual(nil, zero.base as? Float) expectEqual(nil, zero.base as? Vector.TangentVector) expectEqual(nil, zero.base as? Generic<Float>.TangentVector) } TypeErasureTests.test("AnyDifferentiable differentiation") { // Test `AnyDifferentiable` initializer. do { let x: Float = 3 let v = AnyDerivative(Float(2)) let 𝛁x = pullback(at: x, in: { AnyDifferentiable($0) })(v) let expectedVJP: Float = 2 expectEqual(expectedVJP, 𝛁x) } do { let x = Vector(x: 4, y: 5) let v = AnyDerivative(Vector.TangentVector(x: 2, y: 2)) let 𝛁x = pullback(at: x, in: { AnyDifferentiable($0) })(v) let expectedVJP = Vector.TangentVector(x: 2, y: 2) expectEqual(expectedVJP, 𝛁x) } do { let x = Generic<Double>(x: 4) let v = AnyDerivative(Generic<Double>.TangentVector(x: 2)) let 𝛁x = pullback(at: x, in: { AnyDifferentiable($0) })(v) let expectedVJP = Generic<Double>.TangentVector(x: 2) expectEqual(expectedVJP, 𝛁x) } } TypeErasureTests.test("AnyDerivative differentiation") { // Test `AnyDerivative` operations. func tripleSum(_ x: AnyDerivative, _ y: AnyDerivative) -> AnyDerivative { let sum = x + y return sum + sum + sum } do { let x = AnyDerivative(Float(4)) let y = AnyDerivative(Float(-2)) let v = AnyDerivative(Float(1)) let expectedVJP: Float = 3 let (𝛁x, 𝛁y) = pullback(at: x, y, in: tripleSum)(v) expectEqual(expectedVJP, 𝛁x.base as? Float) expectEqual(expectedVJP, 𝛁y.base as? Float) } do { let x = AnyDerivative(Vector.TangentVector(x: 4, y: 5)) let y = AnyDerivative(Vector.TangentVector(x: -2, y: -1)) let v = AnyDerivative(Vector.TangentVector(x: 1, y: 1)) let expectedVJP = Vector.TangentVector(x: 3, y: 3) let (𝛁x, 𝛁y) = pullback(at: x, y, in: tripleSum)(v) expectEqual(expectedVJP, 𝛁x.base as? Vector.TangentVector) expectEqual(expectedVJP, 𝛁y.base as? Vector.TangentVector) } do { let x = AnyDerivative(Generic<Double>.TangentVector(x: 4)) let y = AnyDerivative(Generic<Double>.TangentVector(x: -2)) let v = AnyDerivative(Generic<Double>.TangentVector(x: 1)) let expectedVJP = Generic<Double>.TangentVector(x: 3) let (𝛁x, 𝛁y) = pullback(at: x, y, in: tripleSum)(v) expectEqual(expectedVJP, 𝛁x.base as? Generic<Double>.TangentVector) expectEqual(expectedVJP, 𝛁y.base as? Generic<Double>.TangentVector) } // Test `AnyDerivative` initializer. func typeErased<T>(_ x: T) -> AnyDerivative where T: Differentiable, T.TangentVector == T { let any = AnyDerivative(x) return any + any } do { let x: Float = 3 let v = AnyDerivative(Float(1)) let 𝛁x = pullback(at: x, in: { x in typeErased(x) })(v) let expectedVJP: Float = 2 expectEqual(expectedVJP, 𝛁x) } do { let x = Vector.TangentVector(x: 4, y: 5) let v = AnyDerivative(Vector.TangentVector(x: 1, y: 1)) let 𝛁x = pullback(at: x, in: { x in typeErased(x) })(v) let expectedVJP = Vector.TangentVector(x: 2, y: 2) expectEqual(expectedVJP, 𝛁x) } do { let x = Generic<Double>.TangentVector(x: 4) let v = AnyDerivative(Generic<Double>.TangentVector(x: 1)) let 𝛁x = pullback(at: x, in: { x in typeErased(x) })(v) let expectedVJP = Generic<Double>.TangentVector(x: 2) expectEqual(expectedVJP, 𝛁x) } } runAllTests()
apache-2.0
5745956cced9f3ba49e4932e6f9e6a73
31.770335
89
0.679077
3.441709
false
true
false
false
IAskWind/IAWExtensionTool
Pods/Easy/Easy/Classes/Core/EasyKeychain.swift
1
3204
// // EasyKeychain.swift // Easy // // Created by OctMon on 2018/9/29. // import UIKit public extension Easy { typealias Keychain = EasyKeychain } public struct EasyKeychain { private init() {} private static func searchInfoInKeyChain(service: String) -> [CFString: Any] { return [kSecClass: kSecClassGenericPassword, kSecAttrService: service, kSecAttrAccount: service, kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock] } } public extension EasyKeychain { /// 增 @discardableResult static func save(service: String, value: Any) -> Bool { var keyChain = self.searchInfoInKeyChain(service: service) if SecItemCopyMatching(keyChain as CFDictionary, nil) == noErr { SecItemDelete(keyChain as CFDictionary) } keyChain[kSecValueData] = NSKeyedArchiver.archivedData(withRootObject: value) if SecItemAdd(keyChain as CFDictionary, nil) == noErr { EasyLog.debug("EasyKeychain save: \(service)->\(value) saved.") return true } else { EasyLog.debug("EasyKeychain save: \(service)->\(value) failed.") return false } } /// 删 @discardableResult static func delete(service: String) -> Bool { let keyChain = self.searchInfoInKeyChain(service: service) if SecItemDelete(keyChain as CFDictionary) == noErr { EasyLog.debug("EasyKeychain delete: \(service) deleted.") return true } else { EasyLog.debug("EasyKeychain delete: \(service) failed.") return false } } /// 改 @discardableResult static func update(service: String, value: Any) -> Bool { let keyChain = self.searchInfoInKeyChain(service: service) let changes = [kSecValueData: NSKeyedArchiver.archivedData(withRootObject: value)] if SecItemUpdate(keyChain as CFDictionary, changes as CFDictionary) == noErr { EasyLog.debug("EasyKeychain update: \(service)->\(value) updated.") return true } else { EasyLog.debug("EasyKeychain update: \(service)->\(value) failed.") return false } } /// 查 static func get(service: String) -> Any? { var keyChain = self.searchInfoInKeyChain(service: service) keyChain[kSecReturnData] = kCFBooleanTrue keyChain[kSecMatchLimit] = kSecMatchLimitOne var any: Any? var keyData: CFTypeRef? if SecItemCopyMatching(keyChain as CFDictionary, &keyData) == noErr { guard let keyData = keyData as? Data else { return nil } any = NSKeyedUnarchiver.unarchiveObject(with: keyData) } else { EasyLog.debug("EasyKeychain load: \(service) item not founded.") } return any } static func getUUID(service: String) -> String? { let uuid = get(service: service) as? String if uuid == nil { if let uuid = UIDevice.current.identifierForVendor?.uuidString { save(service: service, value: uuid) return uuid } } return uuid } }
mit
63e6362c75ef07fb1ef3386100b3a44d
31.948454
160
0.612641
4.924499
false
false
false
false
feighter09/Cloud9
Pods/Bond/Bond/Bond+UIDatePicker.swift
1
3757
// // Bond+UIDatePicker.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 class DatePickerDynamicHelper: NSObject { weak var control: UIDatePicker? var listener: (NSDate -> Void)? init(control: UIDatePicker) { self.control = control super.init() control.addTarget(self, action: Selector("valueChanged:"), forControlEvents: .ValueChanged) } func valueChanged(control: UIDatePicker) { self.listener?(control.date) } deinit { control?.removeTarget(self, action: nil, forControlEvents: .ValueChanged) } } class DatePickerDynamic<T>: InternalDynamic<NSDate> { let helper: DatePickerDynamicHelper init(control: UIDatePicker) { self.helper = DatePickerDynamicHelper(control: control) super.init(control.date) self.helper.listener = { [unowned self] in self.updatingFromSelf = true self.value = $0 self.updatingFromSelf = false } } } private var dateDynamicHandleUIDatePicker: UInt8 = 0; extension UIDatePicker /*: Dynamical, Bondable */ { public var dynDate: Dynamic<NSDate> { if let d: AnyObject = objc_getAssociatedObject(self, &dateDynamicHandleUIDatePicker) { return (d as? Dynamic<NSDate>)! } else { let d = DatePickerDynamic<NSDate>(control: self) let bond = Bond<NSDate>() { [weak self, weak d] v in if let s = self, d = d where !d.updatingFromSelf { s.date = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &dateDynamicHandleUIDatePicker, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return d } } public var designatedDynamic: Dynamic<NSDate> { return self.dynDate } public var designatedBond: Bond<NSDate> { return self.dynDate.valueBond } } public func ->> (left: UIDatePicker, right: Bond<NSDate>) { left.designatedDynamic ->> right } public func ->> <U: Bondable where U.BondType == NSDate>(left: UIDatePicker, right: U) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: UIDatePicker, right: UIDatePicker) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: Dynamic<NSDate>, right: UIDatePicker) { left ->> right.designatedBond } public func <->> (left: UIDatePicker, right: UIDatePicker) { left.designatedDynamic <->> right.designatedDynamic } public func <->> (left: Dynamic<NSDate>, right: UIDatePicker) { left <->> right.designatedDynamic } public func <->> (left: UIDatePicker, right: Dynamic<NSDate>) { left.designatedDynamic <->> right }
lgpl-3.0
d5ff3f07d6198619721f259597ff021c
29.795082
129
0.70189
4.202461
false
false
false
false
Hout/SwiftDate
Sources/SwiftDate/DateInRegion/DateInRegion+Components.swift
5
6481
// // SwiftDate // Parse, validate, manipulate, and display dates, time and timezones in Swift // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. // import Foundation public extension DateInRegion { /// Indicates whether the month is a leap month. var isLeapMonth: Bool { let calendar = region.calendar // Library function for leap contains a bug for Gregorian calendars, implemented workaround if calendar.identifier == Calendar.Identifier.gregorian && year > 1582 { guard let range: Range<Int> = calendar.range(of: .day, in: .month, for: date) else { return false } return ((range.upperBound - range.lowerBound) == 29) } // For other calendars: return calendar.dateComponents([.day, .month, .year], from: date).isLeapMonth! } /// Indicates whether the year is a leap year. var isLeapYear: Bool { let calendar = region.calendar // Library function for leap contains a bug for Gregorian calendars, implemented workaround if calendar.identifier == Calendar.Identifier.gregorian { var newComponents = dateComponents newComponents.month = 2 newComponents.day = 10 let testDate = DateInRegion(components: newComponents, region: region) return testDate!.isLeapMonth } else if calendar.identifier == Calendar.Identifier.chinese { /// There are 12 or 13 months in each year and 29 or 30 days in each month. /// A 13-month year is a leap year, which meaning more than 376 days is a leap year. return ( dateAtStartOf(.year).toUnit(.day, to: dateAtEndOf(.year)) > 375 ) } // For other calendars: return calendar.dateComponents([.day, .month, .year], from: date).isLeapMonth! } /// Julian day is the continuous count of days since the beginning of /// the Julian Period used primarily by astronomers. var julianDay: Double { let destRegion = Region(calendar: Calendars.gregorian, zone: Zones.gmt, locale: Locales.english) let utc = convertTo(region: destRegion) let year = Double(utc.year) let month = Double(utc.month) let day = Double(utc.day) let hour = Double(utc.hour) + Double(utc.minute) / 60.0 + (Double(utc.second) + Double(utc.nanosecond) / 1e9) / 3600.0 var jd = 367.0 * year - floor( 7.0 * ( year + floor((month + 9.0) / 12.0)) / 4.0 ) jd -= floor( 3.0 * (floor( (year + (month - 9.0) / 7.0) / 100.0 ) + 1.0) / 4.0 ) jd += floor(275.0 * month / 9.0) + day + 1_721_028.5 + hour / 24.0 return jd } /// The Modified Julian Date (MJD) was introduced by the Smithsonian Astrophysical Observatory /// in 1957 to record the orbit of Sputnik via an IBM 704 (36-bit machine) /// and using only 18 bits until August 7, 2576. var modifiedJulianDay: Double { return julianDay - 2_400_000.5 } /// Return elapsed time expressed in given components since the current receiver and a reference date. /// Time is evaluated with the fixed measumerent of each unity. /// /// - Parameters: /// - refDate: reference date (`nil` to use current date in the same region of the receiver) /// - component: time unit to extract. /// - Returns: value func getInterval(toDate: DateInRegion?, component: Calendar.Component) -> Int64 { let refDate = (toDate ?? region.nowInThisRegion()) switch component { case .year: let end = calendar.ordinality(of: .year, in: .era, for: refDate.date) let start = calendar.ordinality(of: .year, in: .era, for: date) return Int64(end! - start!) case .month: let end = calendar.ordinality(of: .month, in: .era, for: refDate.date) let start = calendar.ordinality(of: .month, in: .era, for: date) return Int64(end! - start!) case .day: let end = calendar.ordinality(of: .day, in: .era, for: refDate.date) let start = calendar.ordinality(of: .day, in: .era, for: date) return Int64(end! - start!) case .hour: let interval = refDate.date.timeIntervalSince(date) return Int64(interval / 1.hours.timeInterval) case .minute: let interval = refDate.date.timeIntervalSince(date) return Int64(interval / 1.minutes.timeInterval) case .second: return Int64(refDate.date.timeIntervalSince(date)) case .weekday: let end = calendar.ordinality(of: .weekday, in: .era, for: refDate.date) let start = calendar.ordinality(of: .weekday, in: .era, for: date) return Int64(end! - start!) case .weekdayOrdinal: let end = calendar.ordinality(of: .weekdayOrdinal, in: .era, for: refDate.date) let start = calendar.ordinality(of: .weekdayOrdinal, in: .era, for: date) return Int64(end! - start!) case .weekOfYear: let end = calendar.ordinality(of: .weekOfYear, in: .era, for: refDate.date) let start = calendar.ordinality(of: .weekOfYear, in: .era, for: date) return Int64(end! - start!) default: debugPrint("Passed component cannot be used to extract values using interval() function between two dates. Returning 0.") return 0 } } /// The interval between the receiver and the another parameter. /// If the receiver is earlier than anotherDate, the return value is negative. /// If anotherDate is nil, the results are undefined. /// /// - Parameter date: The date with which to compare the receiver. /// - Returns: time interval between two dates func timeIntervalSince(_ date: DateInRegion) -> TimeInterval { return self.date.timeIntervalSince(date.date) } /// Extract DateComponents from the difference between two dates. /// /// - Parameter rhs: date to compare /// - Returns: components func componentsTo(_ rhs: DateInRegion) -> DateComponents { return calendar.dateComponents(DateComponents.allComponentsSet, from: rhs.date, to: date) } /// Returns the difference between two dates (`date - self`) expressed as date components. /// /// - Parameters: /// - date: reference date as initial date (left operand) /// - components: components to extract, `nil` to use default `DateComponents.allComponentsSet` /// - Returns: extracted date components func componentsSince(_ date: DateInRegion, components: [Calendar.Component]? = nil) -> DateComponents { if date.calendar != calendar { debugPrint("Date has different calendar, results maybe wrong") } let cmps = (components != nil ? Calendar.Component.toSet(components!) : DateComponents.allComponentsSet) return date.calendar.dateComponents(cmps, from: date.date, to: self.date) } }
mit
2e4eeb0dad8ca7f035749e6a561f7b3f
38.512195
124
0.701698
3.572216
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Dynamic Programming/115_Distinct Subsequences.swift
1
4480
// 115_Distinct Subsequences // https://leetcode.com/problems/distinct-subsequences/ // // Created by Honghao Zhang on 10/2/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a string S and a string T, count the number of distinct subsequences of S which equals T. // //A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). // //Example 1: // //Input: S = "rabbbit", T = "rabbit" //Output: 3 //Explanation: // //As shown below, there are 3 ways you can generate "rabbit" from S. //(The caret symbol ^ means the chosen letters) // //rabbbit //^^^^ ^^ //rabbbit //^^ ^^^^ //rabbbit //^^^ ^^^ //Example 2: // //Input: S = "babgbag", T = "bag" //Output: 5 //Explanation: // //As shown below, there are 5 ways you can generate "bag" from S. //(The caret symbol ^ means the chosen letters) // //babgbag //^^ ^ //babgbag //^^ ^ //babgbag //^ ^^ //babgbag // ^ ^^ //babgbag // ^^^ // import Foundation class Num115 { // DP, 有点不好理解 // https://leetcode.com/problems/distinct-subsequences/discuss/37327/Easy-to-understand-DP-in-Java // 双序列题目,不理解 TODO: revisit this later. func numDistinct(_ word1: String, _ word2: String) -> Int { guard word1.count > 0 else { return 0 } guard word2.count > 0 else { return 1 } let word1 = Array(word1) let word2 = Array(word2) // s[i][j] represents the number of distinct subsequence for s[0..<i] and t[0..<j] var s: [[Int]] = Array(repeating: Array(repeating: 0, count: word2.count + 1), count: word1.count + 1) // non-empty to empty for i in 0...word1.count { s[i][0] = 1 // the "" is the only one unique subsequence } for i in 1...word1.count { for j in 1...word2.count { // if last two char equals if word1[i - 1] == word2[j - 1] { // case1: assume it doesn't match // case2: assume it matches s[i][j] = s[i - 1][j] + s[i - 1][j - 1] } else { // if not equal, word1有没有最后一个char没有关系 s[i][j] = s[i - 1][j] } } } return s[word1.count][word2.count] } // MARK: Recursion Time Limit Exceeded func numDistinct_recursive(_ s: String, _ t: String) -> Int { return numDistinctHelper(Array(s), Array(t)) } private func numDistinctHelper(_ s: [Character], _ t: [Character]) -> Int { if s.isEmpty { return 0 } if t.isEmpty { return 1 // remove all chars in s } if s[0] == t[0] { return numDistinctHelper([Character](s[1...]), [Character](t[1...])) // if first char matched + numDistinctHelper([Character](s[1...]), t) // if first char is not matched } else { return numDistinctHelper([Character](s[1...]), t) } } // MARK: Recursion + Memoization // Still have one test case doesn't pass. struct Input: Equatable, Hashable { let s: [Character] let t: [Character] // static func ==(lhs: Input, rhs: Input) -> Bool { // return lhs.s == rhs.s && lhs.t == rhs.t // } // func hash(into hasher: inout Hasher) { // hasher.combine(self.s) // hasher.combine(self.t) // } } var cache: [Input: Int] = [:] func numDistinct_recursive_mem(_ s: String, _ t: String) -> Int { let input = Input(s: Array(s), t: Array(t)) return numDistinctHelper(input) } private func numDistinctHelper(_ input: Input) -> Int { let s = input.s let t = input.t // Should check t is empty first then check s if t.isEmpty { return 1 // remove all chars in s } if s.isEmpty { return 0 } if let result = cache[input] { return result } if s.firstIndex(of: t[0]) == nil { print("s") return 0 } let unmatchedInput = Input(s: [Character](s[1...]), t: t) if s[0] == t[0] { let matchedInput = Input(s: [Character](s[1...]), t: [Character](t[1...])) let result = numDistinctHelper(matchedInput) // if first char matched + numDistinctHelper(unmatchedInput) // if first char is not matched cache[input] = result return result } else { let result = numDistinctHelper(unmatchedInput) cache[input] = result return result } } }
mit
122698a097bef8c55eebbd0c0e71fa48
25.35119
264
0.589338
3.298808
false
false
false
false
benjaminsnorris/CustomTabBar
CustomTabBar/TabButton.swift
1
7213
// // TabButton.swift // CustomTabBar // // Created by Ben Norris on 2/11/16. // Copyright © 2016 BSN Design. All rights reserved. // import UIKit protocol TabButtonDelegate { func tabButtonTouched(_ index: Int) } class TabButton: UIView { // MARK: - Internal properties var delegate: TabButtonDelegate? let index: Int let dataObject: TabDataObject var selected = false { didSet { updateColors() } } var unselectedColor: UIColor = .black { didSet { updateColors() } } var selectedColor: UIColor = .blue { didSet { updateColors() } } var badgeColor: UIColor = .red { didSet { updateBadge() } } var badgeTextColor: UIColor = .white { didSet { updateBadge() } } var inset: CGFloat = 0.0 { didSet { updateInsets() } } var titleFont: UIFont? = nil { didSet { updateFont() } } var badgeFont: UIFont? = nil { didSet { updateBadge() } } // MARK: - Private properties fileprivate let stackView = UIStackView() fileprivate let imageButton = UIButton() fileprivate let titleLabel = UILabel() fileprivate let button = UIButton() fileprivate let badgeLabel = UILabel() // MARK: - Constants fileprivate static let margin: CGFloat = 4.0 fileprivate static var badgeMargin: CGFloat { return margin / 2 } // MARK: - Initializers init(index: Int, dataObject: TabDataObject) { self.index = index self.dataObject = dataObject super.init(frame: CGRect.zero) setupViews() setupAccessibilityInformation() } required init?(coder aDecoder: NSCoder) { fatalError("TabButton should not be initialized with decoder\(aDecoder)") } // MARK: - Internal functions @objc func highlightButton() { UIView.animate(withDuration: 0.2, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: [], animations: { self.stackView.alpha = 0.2 }, completion: nil) } @objc func resetButton() { UIView.animate(withDuration: 0.2, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: [], animations: { self.stackView.alpha = 1.0 }, completion: nil) } @objc func buttonTouched() { delegate?.tabButtonTouched(index) resetButton() } } // MARK: - Private TabButton functions private extension TabButton { func setupAccessibilityInformation() { isAccessibilityElement = true accessibilityLabel = dataObject.title.capitalized accessibilityIdentifier = dataObject.identifier accessibilityTraits = UIAccessibilityTraitButton imageButton.isAccessibilityElement = false button.isAccessibilityElement = false } func setupViews() { backgroundColor = .clear stackView.axis = .vertical addFullSize(stackView, withMargin: true) stackView.spacing = 1.0 if let image = dataObject.image { stackView.addArrangedSubview(imageButton) imageButton.setImage(image, for: UIControlState()) imageButton.imageView?.contentMode = .scaleAspectFit } if !dataObject.hideTitle { stackView.addArrangedSubview(titleLabel) titleLabel.text = dataObject.title titleLabel.textAlignment = .center titleLabel.setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical) titleLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .vertical) } titleLabel.adjustsFontSizeToFitWidth = true titleLabel.minimumScaleFactor = 0.9 button.addTarget(self, action: #selector(buttonTouched), for: .touchUpInside) button.addTarget(self, action: #selector(highlightButton), for: .touchDown) button.addTarget(self, action: #selector(resetButton), for: .touchDragExit) updateColors() updateFont() updateBadge() addFullSize(button) } func updateColors() { titleLabel.textColor = selected ? selectedColor : unselectedColor imageButton.tintColor = selected ? selectedColor : unselectedColor } func updateFont() { if let titleFont = titleFont { titleLabel.font = titleFont } else if dataObject.image != nil { titleLabel.font = UIFont.systemFont(ofSize: 10) } else { titleLabel.font = UIFont.systemFont(ofSize: 16) } } func updateBadge() { guard let value = dataObject.badgeValue else { badgeLabel.removeFromSuperview(); return } badgeLabel.text = value badgeLabel.textAlignment = .center badgeLabel.backgroundColor = badgeColor if let badgeFont = badgeFont { badgeLabel.font = badgeFont } else { badgeLabel.font = UIFont.boldSystemFont(ofSize: 12) } badgeLabel.textColor = badgeTextColor addBadgeLabel() } func addFullSize(_ view: UIView, withMargin margin: Bool = false) { addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false view.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin ? TabButton.margin : 0).isActive = true view.topAnchor.constraint(equalTo: topAnchor, constant: margin ? TabButton.margin : 0).isActive = true view.trailingAnchor.constraint(equalTo: trailingAnchor, constant: margin ? -TabButton.margin : 0).isActive = true view.bottomAnchor.constraint(equalTo: bottomAnchor, constant: margin ? -TabButton.margin : 0).isActive = true } func addBadgeLabel() { guard badgeLabel.superview == nil else { return } addSubview(badgeLabel) badgeLabel.translatesAutoresizingMaskIntoConstraints = false if let imageAnchor = imageButton.imageView?.trailingAnchor, imageButton.imageView?.image != nil { badgeLabel.centerXAnchor.constraint(equalTo: imageAnchor, constant: TabButton.badgeMargin).isActive = true } else { badgeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -TabButton.badgeMargin).isActive = true } badgeLabel.topAnchor.constraint(equalTo: topAnchor, constant: TabButton.badgeMargin).isActive = true let badgeHeight = badgeLabel.intrinsicContentSize.height * 1.1 let badgeWidth = badgeLabel.intrinsicContentSize.width + badgeHeight / 2 badgeLabel.heightAnchor.constraint(equalToConstant: badgeHeight).isActive = true badgeLabel.widthAnchor.constraint(equalToConstant: badgeWidth).isActive = true badgeLabel.layer.cornerRadius = badgeHeight / 2 badgeLabel.clipsToBounds = true } func updateInsets() { imageButton.imageEdgeInsets = UIEdgeInsetsMake(inset, inset, inset, inset) } }
mit
38e140119f745f8283e8cd9cc9df8384
31.340807
137
0.634359
5.248908
false
false
false
false
swift-lang/swift-k
tests/language-behaviour/mappers/07513-fixed-array-mapper-filename.swift
2
322
type messagefile; (messagefile t) write(string s) { app { echo s stdout=@filename(t); } } string fns="q r s t"; messagefile outfile[] <fixed_array_mapper; files=fns>; messagefile realoutput <"07513-fixed-array-mapper-filename.real.out">; string fn; fn = @filename(outfile); realoutput = write(fn);
apache-2.0
33659d5fd4228912fe39da39dbf465f3
15.947368
70
0.670807
3.126214
false
false
true
false
sergeyzenchenko/react-swift
ReactSwift/ReactSwift/Cartography/LayoutProxy.swift
5
1370
// // LayoutProxy.swift // Cartography // // Created by Robert Böhnke on 17/06/14. // Copyright (c) 2014 Robert Böhnke. All rights reserved. // import Foundation public class LayoutProxy { public let width: Dimension public let height: Dimension public let size: Size public let top: Edge public let right: Edge public let bottom: Edge public let left: Edge public let edges: Edges public let leading: Edge public let trailing: Edge public let centerX: Edge public let centerY: Edge public let center: Point public let baseline: Edge let view: View public var superview: LayoutProxy? { if let superview = view.superview { return LayoutProxy(superview) } else { return nil } } init(_ view: View) { self.view = view width = Dimension.Width(view) height = Dimension.Height(view) size = Size.Size(view) top = Edge.Top(view) right = Edge.Right(view) bottom = Edge.Bottom(view) left = Edge.Left(view) edges = Edges.Edges(view) leading = Edge.Leading(view) trailing = Edge.Trailing(view) centerX = Edge.CenterX(view) centerY = Edge.CenterY(view) center = Point.Center(view) baseline = Edge.Baseline(view) } }
mit
9e58d2b2220f08d9a883006e32b12cf0
19.41791
58
0.605263
4.248447
false
false
false
false
allen-zeng/PromiseKit
Sources/Promise.swift
8
25967
import Dispatch import Foundation.NSError /** A *promise* represents the future value of a task. To obtain the value of a promise we call `then`. Promises are chainable: `then` returns a promise, you can call `then` on that promise, which returns a promise, you can call `then` on that promise, et cetera. Promises start in a pending state and *resolve* with a value to become *fulfilled* or with an `ErrorType` to become rejected. - SeeAlso: [PromiseKit `then` Guide](http://promisekit.org/then/) - SeeAlso: [PromiseKit Chaining Guide](http://promisekit.org/chaining/) */ public class Promise<T> { let state: State<Resolution<T>> /** Create a new pending promise. Use this method when wrapping asynchronous systems that do *not* use promises so that they can be involved in promise chains. Don’t use this method if you already have promises! Instead, just return your promise! The closure you pass is executed immediately on the calling thread. func fetchKitten() -> Promise<UIImage> { return Promise { fulfill, reject in KittenFetcher.fetchWithCompletionBlock({ img, err in if err == nil { if img.size.width > 0 { fulfill(img) } else { reject(Error.ImageTooSmall) } } else { reject(err) } }) } } - Parameter resolvers: The provided closure is called immediately. Inside, execute your asynchronous system, calling fulfill if it suceeds and reject for any errors. - Returns: return A new promise. - Note: If you are wrapping a delegate-based system, we recommend to use instead: Promise.pendingPromise() - SeeAlso: http://promisekit.org/sealing-your-own-promises/ - SeeAlso: http://promisekit.org/wrapping-delegation/ - SeeAlso: init(resolver:) */ public init(@noescape resolvers: (fulfill: (T) -> Void, reject: (ErrorType) -> Void) throws -> Void) { var resolve: ((Resolution<T>) -> Void)! state = UnsealedState(resolver: &resolve) do { try resolvers(fulfill: { resolve(.Fulfilled($0)) }, reject: { error in if self.pending { resolve(.Rejected(error, ErrorConsumptionToken(error))) } else { NSLog("PromiseKit: Warning: reject called on already rejected Promise: %@", "\(error)") } }) } catch { resolve(.Rejected(error, ErrorConsumptionToken(error))) } } /** Create a new pending promise. This initializer is convenient when wrapping asynchronous systems that use common patterns. For example: func fetchKitten() -> Promise<UIImage> { return Promise { resolve in KittenFetcher.fetchWithCompletionBlock(resolve) } } - SeeAlso: init(resolvers:) */ public convenience init(@noescape resolver: ((T?, NSError?) -> Void) throws -> Void) { self.init(sealant: { resolve in try resolver { obj, err in if let obj = obj { resolve(.Fulfilled(obj)) } else if let err = err { resolve(.Rejected(err, ErrorConsumptionToken(err as ErrorType))) } else { resolve(.Rejected(Error.DoubleOhSux0r, ErrorConsumptionToken(Error.DoubleOhSux0r))) } } }) } /** Create a new pending promise. This initializer is convenient when wrapping asynchronous systems that use common patterns. For example: func fetchKitten() -> Promise<UIImage> { return Promise { resolve in KittenFetcher.fetchWithCompletionBlock(resolve) } } - SeeAlso: init(resolvers:) */ public convenience init(@noescape resolver: ((T, NSError?) -> Void) throws -> Void) { self.init(sealant: { resolve in try resolver { obj, err in if let err = err { resolve(.Rejected(err, ErrorConsumptionToken(err))) } else { resolve(.Fulfilled(obj)) } } }) } /** Create a new fulfilled promise. */ public init(_ value: T) { state = SealedState(resolution: .Fulfilled(value)) } @available(*, unavailable, message="T cannot conform to ErrorType") public init<T: ErrorType>(_ value: T) { abort() } /** Create a new rejected promise. */ public init(error: ErrorType) { /** Implementation note, the error label is necessary to prevent: let p = Promise(ErrorType()) Resulting in Promise<ErrorType>. The above @available annotation does not help for some reason. A work-around is: let p: Promise<Void> = Promise(ErrorType()) But I can’t expect users to do this. */ state = SealedState(resolution: .Rejected(error, ErrorConsumptionToken(error))) } /** Careful with this, it is imperative that sealant can only be called once or you will end up with spurious unhandled-errors due to possible double rejections and thus immediately deallocated ErrorConsumptionTokens. */ init(@noescape sealant: ((Resolution<T>) -> Void) throws -> Void) { var resolve: ((Resolution<T>) -> Void)! state = UnsealedState(resolver: &resolve) do { try sealant(resolve) } catch { resolve(.Rejected(error, ErrorConsumptionToken(error))) } } /** A `typealias` for the return values of `pendingPromise()`. Simplifies declaration of properties that reference the values' containing tuple when this is necessary. For example, when working with multiple `pendingPromise()`s within the same scope, or when the promise initialization must occur outside of the caller's initialization. class Foo: BarDelegate { var pendingPromise: Promise<Int>.PendingPromise? } - SeeAlso: pendingPromise() */ public typealias PendingPromise = (promise: Promise, fulfill: (T) -> Void, reject: (ErrorType) -> Void) /** Making promises that wrap asynchronous delegation systems or other larger asynchronous systems without a simple completion handler is easier with pendingPromise. class Foo: BarDelegate { let (promise, fulfill, reject) = Promise<Int>.pendingPromise() func barDidFinishWithResult(result: Int) { fulfill(result) } func barDidError(error: NSError) { reject(error) } } - Returns: A tuple consisting of: 1) A promise 2) A function that fulfills that promise 3) A function that rejects that promise */ public class func pendingPromise() -> PendingPromise { var fulfill: ((T) -> Void)! var reject: ((ErrorType) -> Void)! let promise = Promise { fulfill = $0; reject = $1 } return (promise, fulfill, reject) } func pipe(body: (Resolution<T>) -> Void) { state.get { seal in switch seal { case .Pending(let handlers): handlers.append(body) case .Resolved(let resolution): body(resolution) } } } private convenience init<U>(when: Promise<U>, body: (Resolution<U>, (Resolution<T>) -> Void) -> Void) { self.init { resolve in when.pipe { resolution in body(resolution, resolve) } } } /** The provided closure is executed when this Promise is resolved. - Parameter on: The queue on which body should be executed. - Parameter body: The closure that is executed when this Promise is fulfilled. - Returns: A new promise that is resolved with the value returned from the provided closure. For example: NSURLConnection.GET(url).then { (data: NSData) -> Int in //… return data.length }.then { length in //… } - SeeAlso: `thenInBackground` */ public func then<U>(on q: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: (T) throws -> U) -> Promise<U> { return Promise<U>(when: self) { resolution, resolve in switch resolution { case .Rejected(let error): resolve(.Rejected((error.0, error.1))) case .Fulfilled(let value): contain_zalgo(q, rejecter: resolve) { resolve(.Fulfilled(try body(value))) } } } } /** The provided closure is executed when this Promise is resolved. - Parameter on: The queue on which body should be executed. - Parameter body: The closure that is executed when this Promise is fulfilled. - Returns: A new promise that is resolved when the Promise returned from the provided closure resolves. For example: NSURLSession.GET(url1).then { (data: NSData) -> Promise<NSData> in //… return NSURLSession.GET(url2) }.then { data in //… } - SeeAlso: `thenInBackground` */ public func then<U>(on q: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: (T) throws -> Promise<U>) -> Promise<U> { return Promise<U>(when: self) { resolution, resolve in switch resolution { case .Rejected(let error): resolve(.Rejected((error.0, error.1))) case .Fulfilled(let value): contain_zalgo(q, rejecter: resolve) { let promise = try body(value) guard promise !== self else { throw Error.ReturnedSelf } promise.pipe(resolve) } } } } @available(*, unavailable) public func then<U>(on: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: (T) throws -> Promise<U>?) -> Promise<U> { abort() } /** The provided closure is executed when this Promise is resolved. - Parameter on: The queue on which body should be executed. - Parameter body: The closure that is executed when this Promise is fulfilled. - Returns: A new promise that is resolved when the AnyPromise returned from the provided closure resolves. For example: NSURLSession.GET(url).then { (data: NSData) -> AnyPromise in //… return SCNetworkReachability() }.then { _ in //… } - SeeAlso: `thenInBackground` */ public func then(on q: dispatch_queue_t = PMKDefaultDispatchQueue(), body: (T) throws -> AnyPromise) -> Promise<AnyObject?> { return Promise<AnyObject?>(when: self) { resolution, resolve in switch resolution { case .Rejected(let error): resolve(.Rejected((error.0, error.1))) case .Fulfilled(let value): contain_zalgo(q, rejecter: resolve) { try body(value).pipe(resolve) } } } } @available(*, unavailable) public func then(on: dispatch_queue_t = PMKDefaultDispatchQueue(), body: (T) throws -> AnyPromise?) -> Promise<AnyObject?> { abort() } /** The provided closure is executed on the default background queue when this Promise is fulfilled. This method is provided as a convenience for `then`. - SeeAlso: `then` */ public func thenInBackground<U>(body: (T) throws -> U) -> Promise<U> { return then(on: dispatch_get_global_queue(0, 0), body) } /** The provided closure is executed on the default background queue when this Promise is fulfilled. This method is provided as a convenience for `then`. - SeeAlso: `then` */ public func thenInBackground<U>(body: (T) throws -> Promise<U>) -> Promise<U> { return then(on: dispatch_get_global_queue(0, 0), body) } @available(*, unavailable) public func thenInBackground<U>(body: (T) throws -> Promise<U>?) -> Promise<U> { abort() } /** The provided closure is executed when this promise is rejected. Rejecting a promise cascades: rejecting all subsequent promises (unless recover is invoked) thus you will typically place your catch at the end of a chain. Often utility promises will not have a catch, instead delegating the error handling to the caller. The provided closure runs on PMKDefaultDispatchQueue by default. - Parameter policy: The default policy does not execute your handler for cancellation errors. See registerCancellationError for more documentation. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: `errorOnQueue` */ public func error(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, _ body: (ErrorType) -> Void) { errorOnQueue(policy: policy, body) } /** The provided closure is executed when this promise is rejected. Rejecting a promise cascades: rejecting all subsequent promises (unless recover is invoked) thus you will typically place your catch at the end of a chain. Often utility promises will not have a catch, instead delegating the error handling to the caller. The provided closure runs on PMKDefaultDispatchQueue by default. - Parameter on: The queue on which body should be executed. - Parameter policy: The default policy does not execute your handler for cancellation errors. See registerCancellationError for more documentation. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: `registerCancellationError` */ public func errorOnQueue(on q: dispatch_queue_t = PMKDefaultDispatchQueue(), policy: ErrorPolicy = .AllErrorsExceptCancellation, _ body: (ErrorType) -> Void) { func consume(error: ErrorType, _ token: ErrorConsumptionToken) { token.consumed = true body(error) } pipe { resolution in switch (resolution, policy) { case (let .Rejected(error, token), .AllErrorsExceptCancellation): contain_zalgo(q) { guard let cancellableError = error as? CancellableErrorType where cancellableError.cancelled else { consume(error, token) return } } case (let .Rejected(error, token), _): contain_zalgo(q) { consume(error, token) } case (.Fulfilled, _): break } } } /** Provides an alias for the `error` function for cases where the Swift compiler cannot disambiguate from our `error` property. If you're having trouble with `error`, before using this alias, first try being as explicit as possible with the types e.g.: }.error { (error:ErrorType) -> Void in //... } Or even using verbose function syntax: }.error({ (error:ErrorType) -> Void in //... }) If you absolutely cannot get Swift to accept `error` then `onError` may be used instead as it does the same thing. - Warning: This alias will be unavailable in PromiseKit 4.0.0 - SeeAlso: [https://github.com/mxcl/PromiseKit/issues/347](https://github.com/mxcl/PromiseKit/issues/347) */ @available(*, deprecated, renamed="error", message="Temporary alias `onError` will eventually be removed and should only be used when the Swift compiler cannot be satisfied with `error`") public func onError(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, _ body: (ErrorType) -> Void) { error(policy: policy, body) } /** The provided closure is executed when this promise is rejected giving you an opportunity to recover from the error and continue the promise chain. */ public func recover(on q: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: (ErrorType) throws -> Promise) -> Promise { return Promise(when: self) { resolution, resolve in switch resolution { case .Rejected(let error, let token): contain_zalgo(q, rejecter: resolve) { token.consumed = true let promise = try body(error) guard promise !== self else { throw Error.ReturnedSelf } promise.pipe(resolve) } case .Fulfilled: resolve(resolution) } } } @available(*, unavailable) public func recover(on: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: (ErrorType) throws -> Promise?) -> Promise { abort() } public func recover(on q: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: (ErrorType) throws -> T) -> Promise { return Promise(when: self) { resolution, resolve in switch resolution { case .Rejected(let error, let token): contain_zalgo(q, rejecter: resolve) { token.consumed = true resolve(.Fulfilled(try body(error))) } case .Fulfilled: resolve(resolution) } } } /** The provided closure is executed when this Promise is resolved. UIApplication.sharedApplication().networkActivityIndicatorVisible = true somePromise().then { //… }.always { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } - Parameter on: The queue on which body should be executed. - Parameter body: The closure that is executed when this Promise is resolved. */ public func always(on q: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: () -> Void) -> Promise { return Promise(when: self) { resolution, resolve in contain_zalgo(q) { body() resolve(resolution) } } } @available(*, unavailable, renamed="ensure") public func finally(on: dispatch_queue_t = PMKDefaultDispatchQueue(), body: () -> Void) -> Promise { abort() } @available(*, unavailable, renamed="report") public func catch_(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, body: () -> Void) -> Promise { abort() } @available(*, unavailable, renamed="pendingPromise") public class func defer_() -> (promise: Promise, fulfill: (T) -> Void, reject: (ErrorType) -> Void) { abort() } @available(*, deprecated, renamed="error") public func report(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, _ body: (ErrorType) -> Void) { error(policy: policy, body) } @available(*, deprecated, renamed="always") public func ensure(on q: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: () -> Void) -> Promise { return always(on: q, body) } } /** Zalgo is dangerous. Pass as the `on` parameter for a `then`. Causes the handler to be executed as soon as it is resolved. That means it will be executed on the queue it is resolved. This means you cannot predict the queue. In the case that the promise is already resolved the handler will be executed immediately. zalgo is provided for libraries providing promises that have good tests that prove unleashing zalgo is safe. You can also use it in your application code in situations where performance is critical, but be careful: read the essay at the provided link to understand the risks. - SeeAlso: http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony */ public let zalgo: dispatch_queue_t = dispatch_queue_create("Zalgo", nil) /** Waldo is dangerous. Waldo is zalgo, unless the current queue is the main thread, in which case we dispatch to the default background queue. If your block is likely to take more than a few milliseconds to execute, then you should use waldo: 60fps means the main thread cannot hang longer than 17 milliseconds. Don’t contribute to UI lag. Conversely if your then block is trivial, use zalgo: GCD is not free and for whatever reason you may already be on the main thread so just do what you are doing quickly and pass on execution. It is considered good practice for asynchronous APIs to complete onto the main thread. Apple do not always honor this, nor do other developers. However, they *should*. In that respect waldo is a good choice if your then is going to take a while and doesn’t interact with the UI. Please note (again) that generally you should not use zalgo or waldo. The performance gains are neglible and we provide these functions only out of a misguided sense that library code should be as optimized as possible. If you use zalgo or waldo without tests proving their correctness you may unwillingly introduce horrendous, near-impossible-to-trace bugs. - SeeAlso: zalgo */ public let waldo: dispatch_queue_t = dispatch_queue_create("Waldo", nil) func contain_zalgo(q: dispatch_queue_t, block: () -> Void) { if q === zalgo { block() } else if q === waldo { if NSThread.isMainThread() { dispatch_async(dispatch_get_global_queue(0, 0), block) } else { block() } } else { dispatch_async(q, block) } } func contain_zalgo<T>(q: dispatch_queue_t, rejecter resolve: (Resolution<T>) -> Void, block: () throws -> Void) { contain_zalgo(q) { do { try block() } catch { resolve(.Rejected(error, ErrorConsumptionToken(error))) } } } extension Promise { /** Void promises are less prone to generics-of-doom scenarios. - SeeAlso: when.swift contains enlightening examples of using `Promise<Void>` to simplify your code. */ public func asVoid() -> Promise<Void> { return then(on: zalgo) { _ in return } } } extension Promise: CustomStringConvertible { public var description: String { return "Promise: \(state)" } } /** `firstly` can make chains more readable. Compare: NSURLConnection.GET(url1).then { NSURLConnection.GET(url2) }.then { NSURLConnection.GET(url3) } With: firstly { NSURLConnection.GET(url1) }.then { NSURLConnection.GET(url2) }.then { NSURLConnection.GET(url3) } */ public func firstly<T>(@noescape promise: () throws -> Promise<T>) -> Promise<T> { do { return try promise() } catch { return Promise(error: error) } } /** `firstly` can make chains more readable. Compare: SCNetworkReachability().then { NSURLSession.GET(url2) }.then { NSURLSession.GET(url3) } With: firstly { SCNetworkReachability() }.then { NSURLSession.GET(url2) }.then { NSURLSession.GET(url3) } */ public func firstly(@noescape promise: () throws -> AnyPromise) -> Promise<AnyObject?> { return Promise { resolve in try promise().pipe(resolve) } } @available(*, unavailable, message="Instead, throw") public func firstly<T: ErrorType>(@noescape promise: () throws -> Promise<T>) -> Promise<T> { fatalError("Unavailable function") } public enum ErrorPolicy { case AllErrors case AllErrorsExceptCancellation } extension AnyPromise { private func pipe(resolve: (Resolution<AnyObject?>) -> Void) -> Void { pipe { (obj: AnyObject?) in if let error = obj as? NSError { resolve(.Rejected(error, ErrorConsumptionToken(error))) } else { // possibly the value of this promise is a PMKManifold, if so // calling the objc `value` method will return the first item. resolve(.Fulfilled(self.valueForKey("value"))) } } } } extension Promise { @available(*, unavailable, message="T cannot conform to ErrorType") public convenience init<T: ErrorType>(@noescape resolvers: (fulfill: (T) -> Void, reject: (ErrorType) -> Void) throws -> Void) { abort() } @available(*, unavailable, message="T cannot conform to ErrorType") public convenience init<T: ErrorType>(@noescape resolver: ((T?, NSError?) -> Void) throws -> Void) { abort() } @available(*, unavailable, message="T cannot conform to ErrorType") public convenience init<T: ErrorType>(@noescape resolver: ((T, NSError?) -> Void) throws -> Void) { abort() } @available(*, unavailable, message="T cannot conform to ErrorType") public class func pendingPromise<T: ErrorType>() -> (promise: Promise, fulfill: (T) -> Void, reject: (ErrorType) -> Void) { abort() } @available (*, unavailable, message="U cannot conform to ErrorType") public func then<U: ErrorType>(on: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: (T) throws -> U) -> Promise<U> { abort() } @available (*, unavailable, message="U cannot conform to ErrorType") public func then<U: ErrorType>(on: dispatch_queue_t = PMKDefaultDispatchQueue(), _ body: (T) throws -> Promise<U>) -> Promise<U> { abort() } @available(*, unavailable, message="U cannot conform to ErrorType") public func thenInBackground<U: ErrorType>(body: (T) throws -> U) -> Promise<U> { abort() } @available(*, unavailable, message="U cannot conform to ErrorType") public func thenInBackground<U: ErrorType>(body: (T) throws -> Promise<U>) -> Promise<U> { abort() } }
mit
423cb1792c06c383753e0db7132369c4
35.490858
337
0.612565
4.639664
false
false
false
false
zxpLearnios/MyProject
test_projectDemo1/Tools/Banner/未设置图片加载/MyBannerFlowLayout.swift
1
6325
// // MyBannerFlowLayout.swift // test_projectDemo1 // // Created by Jingnan Zhang on 2017/3/23. // Copyright © 2017年 Jingnan Zhang. All rights reserved. // 170 为cell的宽度, 70为cell间距 import UIKit class MyBannerFlowLayout: UICollectionViewFlowLayout { private let cellW:CGFloat = 170 private let cellH:CGFloat = 100 /** 有效距离:当item的中间x距离屏幕的中间x在HMActiveDistance以内,才会开始放大, 其它情况都是缩小 */ private let activeDistance:CGFloat = 150 /** 缩放因素: 值越大, item就会越大 */ private let scaleFactor:CGFloat = 0.6 override init() { super.init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** * 1. 只要显示的边界发生改变就重新布局:Invalidate 使无效 内部会重新调用prepareLayout和layoutAttributesForElementsInRect方法获得所有cell的布局属性 */ override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } /** * 一些初始化工作最好在这里实现 */ override func prepare() { super.prepare() // 每个cell的尺寸 self.itemSize = CGSize.init(width: cellW, height: cellH) // CGFloat inset = (self.collectionView.frame.size.width - HMItemWH) * 0.5; // self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset); // 设置水平滚动 self.scrollDirection = .horizontal self.minimumLineSpacing = cellH * 0.7 // item之间的距离 self.minimumInteritemSpacing = 0 //设置边距(让第一张图片与最后一张图片出现在最中央) // self.sectionInset = UIEdgeInsetsMake(0, (kwidth - self.itemSize.width) / 2, 0, (kwidth - self.itemSize.width) / 2) // [self registerClass:[CVDEView class] forDecorationViewOfKind:@"CDV"]; // 注册Decoration View 装饰view // 每一个cell(item)都有自己的UICollectionViewLayoutAttributes // 每一个indexPath都有自己的UICollectionViewLayoutAttributes } /** * 2. 用来设置collectionView停止滚动那一刻的位置,这是swift3里用的 * * @param proposedContentOffset 原本collectionView停止滚动那一刻的位置 * @param velocity 滚动速度 */ override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { // 1.计算出scrollView最后会停留的范围 var lastRect = CGRect.zero lastRect.origin = proposedContentOffset lastRect.size = (self.collectionView?.frame.size)! // 计算屏幕最中间的x let centerX:CGFloat = proposedContentOffset.x + (self.collectionView?.width)! * 0.5 // 2.取出这个范围内的所有属性,调用了自己的复写了父类的方法 let array = self.layoutAttributesForElements(in: lastRect) // 3.遍历所有属性 var adjustOffsetX:CGFloat = CGFloat(MAXFLOAT) for attrs in array! { if abs(attrs.center.x - centerX) < abs(adjustOffsetX) { adjustOffsetX = attrs.center.x - centerX } } return CGPoint.init(x: proposedContentOffset.x + CGFloat(adjustOffsetX), y: proposedContentOffset.y) } /** * 2.1 用来设置collectionView停止滚动那一刻的位置 这是OC里用的,swift3里用此法无效 * * @param proposedContentOffset 原本collectionView停止滚动那一刻的位置 * @param velocity 滚动速度 */ // override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { // 1.计算出scrollView最后会停留的范围 // var lastRect = CGRect.zero // lastRect.origin = proposedContentOffset // // lastRect.size = (self.collectionView?.frame.size)! // // // 计算屏幕最中间的x // let centerX:CGFloat = proposedContentOffset.x + (self.collectionView?.width)! * 0.5 // // // 2.取出这个范围内的所有属性,调用了自己的复写了父类的方法 // let array = self.layoutAttributesForElements(in: lastRect) // // // 3.遍历所有属性 // var adjustOffsetX:CGFloat = CGFloat(MAXFLOAT) // for attrs in array! { // if abs(attrs.center.x - centerX) < abs(adjustOffsetX) { // adjustOffsetX = attrs.center.x - centerX // } // } // // return CGPoint.init(x: proposedContentOffset.x + CGFloat(adjustOffsetX), y: proposedContentOffset.y) // // // } /** * 3. 布局每个cell的样式,放大、缩小 */ override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { // 0. 计算可见的矩形框,即collectionView当前显示的区域在collectionView上面的具体坐标区域 var visiableRect = CGRect.zero visiableRect.size = (self.collectionView?.frame.size)! visiableRect.origin = (self.collectionView?.contentOffset)! // 1.取得默认的cell的UICollectionViewLayoutAttributes let array = super.layoutAttributesForElements(in: rect) // 计算屏幕最中间的x let centerX:CGFloat = self.collectionView!.contentOffset.x + self.collectionView!.frame.size.width * 0.5 // 2.遍历所有的布局属性 for attrs in array! { // 如果不在屏幕上,直接跳过 Intersects:交叉 if !visiableRect.intersects(attrs.frame){ continue } // 每一个item的中点x let itemCenterX = attrs.center.x // 差距越小, 缩放比例越大 // 根据跟屏幕最中间的距离计算缩放比例 // let scale = 1 + scaleFactor * (1 - (abs(itemCenterX - centerX) / activeDistance)) // attrs.transform = CGAffineTransform.init(scaleX: scale, y: scale) } return array } }
mit
01cb78f0b1f042574b2f843c0d02de99
29.772727
148
0.615399
4.087547
false
false
false
false
entotsu/PullToBounce
PullToBounce/Source/BallView.swift
1
7503
// // LoadingBallView.swift // BezierPathAnimation // // Created by Takuya Okamoto on 2015/08/11. // Copyright (c) 2015年 Uniface. All rights reserved. // import UIKit private var timeFunc : CAMediaTimingFunction! private var upDuration: Double! class BallView: UIView { var circleLayer: CircleLayer! init(frame:CGRect, circleSize:CGFloat = 40, timingFunc:CAMediaTimingFunction = timeFunc, moveUpDuration:CFTimeInterval = upDuration, moveUpDist:CGFloat, color:UIColor = UIColor.white) { timeFunc = timingFunc upDuration = moveUpDuration super.init(frame:frame) let circleMoveView = UIView() circleMoveView.frame = CGRect(x: 0, y: 0, width: moveUpDist, height: moveUpDist) circleMoveView.center = CGPoint(x: frame.width/2, y: frame.height + circleSize / 2) self.addSubview(circleMoveView) circleLayer = CircleLayer( size: circleSize, moveUpDist: moveUpDist, superViewFrame: circleMoveView.frame, color: color ) circleMoveView.layer.addSublayer(circleLayer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func startAnimation() { circleLayer.startAnimation() } func endAnimation(_ complition:(()->())? = nil) { circleLayer.endAnimation(complition) } } class CircleLayer :CAShapeLayer, CAAnimationDelegate { let moveUpDist: CGFloat! let spiner: SpinerLayer! var didEndAnimation: (()->())? init(size:CGFloat, moveUpDist:CGFloat , superViewFrame:CGRect, color:UIColor = UIColor.white) { self.moveUpDist = moveUpDist let selfFrame = CGRect(x: 0, y: 0, width: superViewFrame.size.width, height: superViewFrame.size.height) self.spiner = SpinerLayer(superLayerFrame: selfFrame, ballSize: size, color: color) super.init() self.addSublayer(spiner) let radius:CGFloat = size / 2 self.frame = selfFrame let center = CGPoint(x: superViewFrame.size.width / 2, y: superViewFrame.size.height/2) let startAngle = 0 - Double.pi / 2 let endAngle = Double.pi * (Double.pi / 2) let clockwise: Bool = true self.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise).cgPath self.fillColor = color.withAlphaComponent(1).cgColor self.strokeColor = self.fillColor self.lineWidth = 0 self.strokeEnd = 1 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func startAnimation() { self.moveUp(moveUpDist) _ = Timer.schedule(delay: upDuration) { timer in self.spiner.animation() } } func endAnimation(_ complition:(()->())? = nil) { spiner.stopAnimation() self.moveDown(moveUpDist) didEndAnimation = complition } func moveUp(_ distance: CGFloat) { let move = CABasicAnimation(keyPath: "position") move.fromValue = NSValue(cgPoint: position) move.toValue = NSValue(cgPoint: CGPoint(x: position.x, y: position.y - distance)) move.duration = upDuration move.timingFunction = timeFunc move.fillMode = CAMediaTimingFillMode.forwards move.isRemovedOnCompletion = false self.add(move, forKey: move.keyPath) } func moveDown(_ distance: CGFloat) { let move = CABasicAnimation(keyPath: "position") move.fromValue = NSValue(cgPoint: CGPoint(x: position.x, y: position.y - distance)) move.toValue = NSValue(cgPoint: position) move.duration = upDuration move.timingFunction = timeFunc move.fillMode = CAMediaTimingFillMode.forwards move.isRemovedOnCompletion = false move.delegate = self self.add(move, forKey: move.keyPath) } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { didEndAnimation?() } } class SpinerLayer :CAShapeLayer, CAAnimationDelegate { init(superLayerFrame:CGRect, ballSize:CGFloat, color:UIColor = UIColor.white) { super.init() let radius:CGFloat = (ballSize / 2) * 1.2//1.45 self.frame = CGRect(x: 0, y: 0, width: superLayerFrame.height, height: superLayerFrame.height) let center = CGPoint(x: superLayerFrame.size.width / 2, y: superLayerFrame.origin.y + superLayerFrame.size.height/2) let startAngle = 0 - Double.pi / 2 let endAngle = (Double.pi * 2 - (Double.pi / 2)) + Double.pi / 8 let clockwise: Bool = true self.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise).cgPath self.fillColor = nil self.strokeColor = color.withAlphaComponent(1).cgColor self.lineWidth = 2 self.lineCap = CAShapeLayerLineCap.round self.strokeStart = 0 self.strokeEnd = 0 self.isHidden = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func animation() { self.isHidden = false let rotate = CABasicAnimation(keyPath: "transform.rotation.z") rotate.fromValue = 0 rotate.toValue = Double.pi * 2 rotate.duration = 1 rotate.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) rotate.repeatCount = HUGE rotate.fillMode = CAMediaTimingFillMode.forwards rotate.isRemovedOnCompletion = false self.add(rotate, forKey: rotate.keyPath) strokeEndAnimation() } func strokeEndAnimation() { let endPoint = CABasicAnimation(keyPath: "strokeEnd") endPoint.fromValue = 0 endPoint.toValue = 1.0 endPoint.duration = 0.8 endPoint.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) endPoint.repeatCount = 1 endPoint.fillMode = CAMediaTimingFillMode.forwards endPoint.isRemovedOnCompletion = false endPoint.delegate = self self.add(endPoint, forKey: endPoint.keyPath) } func strokeStartAnimation() { let startPoint = CABasicAnimation(keyPath: "strokeStart") startPoint.fromValue = 0 startPoint.toValue = 1.0 startPoint.duration = 0.8 startPoint.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) startPoint.repeatCount = 1 // startPoint.fillMode = kCAFillModeForwards // startPoint.removedOnCompletion = false startPoint.delegate = self self.add(startPoint, forKey: startPoint.keyPath) } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if self.isHidden == false { let a:CABasicAnimation = anim as! CABasicAnimation if a.keyPath == "strokeStart" { strokeEndAnimation() } else if a.keyPath == "strokeEnd" { strokeStartAnimation() } } } func stopAnimation() { self.isHidden = true self.removeAllAnimations() } }
mit
322c22b0c0b8dec962c45da1eb865cf0
32.788288
158
0.630983
4.732492
false
false
false
false
crspybits/SyncServerII
Tests/ServerTests/SharingGroupsControllerTests.swift
1
31895
// // SharingGroupsControllerTests.swift // ServerTests // // Created by Christopher G Prince on 7/15/18. // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class SharingGroupsControllerTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testCreateSharingGroupWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupName = "Louisiana Guys" let sharingGroupUUID2 = UUID().uuidString guard createSharingGroup(sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID, sharingGroup: sharingGroup) else { XCTFail() return } guard let (_, sharingGroups) = getIndex() else { XCTFail() return } let filtered = sharingGroups.filter {$0.sharingGroupUUID == sharingGroupUUID2} guard filtered.count == 1 else { XCTFail() return } XCTAssert(filtered[0].sharingGroupName == sharingGroup.sharingGroupName) } func testThatNonOwningUserCannotCreateASharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let testAccount:TestAccount = .nonOwningSharingAccount redeemSharingInvitation(sharingUser: testAccount, sharingInvitationUUID: sharingInvitationUUID) { _, expectation in expectation.fulfill() } let deviceUUID2 = Foundation.UUID().uuidString let sharingGroupUUID2 = Foundation.UUID().uuidString createSharingGroup(testAccount: testAccount, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID2, errorExpected: true) } func testNewlyCreatedSharingGroupHasNoFiles() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupName = "Louisiana Guys" let sharingGroupUUID2 = Foundation.UUID().uuidString guard createSharingGroup(sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID, sharingGroup: sharingGroup) else { XCTFail() return } guard let (files, sharingGroups) = getIndex(sharingGroupUUID: sharingGroupUUID2) else { XCTFail() return } guard files != nil && files?.count == 0 else { XCTFail() return } guard sharingGroups.count == 2 else { XCTFail() return } sharingGroups.forEach { sharingGroup in guard let deleted = sharingGroup.deleted else { XCTFail() return } XCTAssert(!deleted) XCTAssert(sharingGroup.permission == .admin) XCTAssert(sharingGroup.masterVersion == 0) } let filtered = sharingGroups.filter {$0.sharingGroupUUID == sharingGroupUUID2} guard filtered.count == 1 else { XCTFail() return } XCTAssert(filtered[0].sharingGroupName == sharingGroup.sharingGroupName) guard let users = filtered[0].sharingGroupUsers, users.count == 1, users[0].name != nil, users[0].name.count > 0 else { XCTFail() return } } func testUpdateSharingGroupWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupUUID = sharingGroupUUID sharingGroup.sharingGroupName = "Louisiana Guys" guard updateSharingGroup(deviceUUID:deviceUUID, sharingGroup: sharingGroup, masterVersion: masterVersion) else { XCTFail() return } } func testUpdateSharingGroupWithBadMasterVersionFails() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupUUID = sharingGroupUUID sharingGroup.sharingGroupName = "Louisiana Guys" updateSharingGroup(deviceUUID:deviceUUID, sharingGroup: sharingGroup, masterVersion: masterVersion+1, expectMasterVersionUpdate: true) } // MARK: Remove sharing groups func testRemoveSharingGroupWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let key1 = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result1 = SharingGroupRepository(db).lookup(key: key1, modelInit: SharingGroup.init) guard case .found(let model) = result1, let sharingGroup = model as? Server.SharingGroup else { XCTFail() return } guard sharingGroup.deleted else { XCTFail() return } guard let count = SharingGroupUserRepository(db).count(), count == 0 else { XCTFail() return } } func testRemoveSharingGroupWorks_filesMarkedAsDeleted() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } // Can't do a file index because no one is left in the sharing group. So, just look up in the db directly. let key = FileIndexRepository.LookupKey.sharingGroupUUID(sharingGroupUUID: sharingGroupUUID) let result = FileIndexRepository(db).lookup(key: key, modelInit: FileIndex.init) switch result { case .noObjectFound: XCTFail() case .error: XCTFail() case .found(let model): let file = model as! FileIndex XCTAssert(file.deleted) } } func testRemoveSharingGroupWorks_multipleUsersRemovedFromSharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let sharingUser: TestAccount = .secondaryOwningAccount redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } guard let count = SharingGroupUserRepository(db).count(), count == 0 else { XCTFail() return } } func testRemoveSharingGroupWorks_cannotThenInviteSomeoneToThatGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID, errorExpected: true) { expectation, _ in expectation.fulfill() } } func testRemoveSharingGroupWorks_cannotThenUploadFileToThatSharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } uploadTextFile(deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), masterVersion:masterVersion+1, errorExpected:true) } func testRemoveSharingGroupWorks_cannotThenDoDoneUploads() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 0, deviceUUID:deviceUUID, masterVersion: masterVersion+1, sharingGroupUUID: sharingGroupUUID, failureExpected: true) } func testRemoveSharingGroupWorks_cannotDeleteFile() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = masterVersion + 1 uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false, expectError: true) } func testRemoveSharingGroupWorks_uploadAppMetaDataFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let appMetaData = AppMetaData(version: 0, contents: "Foo") uploadAppMetaDataVersion(deviceUUID: deviceUUID, fileUUID: uploadResult.request.fileUUID, masterVersion:masterVersion+1, appMetaData: appMetaData, sharingGroupUUID:sharingGroupUUID, expectedError: true) } func testRemoveSharingGroupWorks_downloadAppMetaDataFails() { let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Foo") guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID, appMetaData: appMetaData), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } downloadAppMetaDataVersion(deviceUUID: deviceUUID, fileUUID: uploadResult.request.fileUUID, masterVersionExpectedWithDownload:masterVersion + 1, appMetaDataVersion: 0, sharingGroupUUID: sharingGroupUUID, expectedError: true) } func testRemoveSharingGroupWorks_downloadFileFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } downloadTextFile(masterVersionExpectedWithDownload:Int(masterVersion+1), downloadFileVersion:0, uploadFileRequest:uploadResult.request, expectedError: true) } func testRemoveSharingGroup_failsWithBadMasterVersion() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard !removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion+1) else { XCTFail() return } } func testUpdateSharingGroupForDeletedSharingGroupFails() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard var masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } masterVersion += 1 let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupUUID = sharingGroupUUID sharingGroup.sharingGroupName = "Louisiana Guys" let result = updateSharingGroup(deviceUUID:deviceUUID, sharingGroup: sharingGroup, masterVersion: masterVersion, expectFailure: true) XCTAssert(result == false) } // MARK: Remove user from sharing group func testRemoveUserFromSharingGroup_lastUserInSharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let addUserResponse = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeUserFromSharingGroup(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let key1 = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result1 = SharingGroupRepository(db).lookup(key: key1, modelInit: SharingGroup.init) guard case .found(let model) = result1, let sharingGroup = model as? Server.SharingGroup else { XCTFail() return } guard sharingGroup.deleted else { XCTFail() return } let key2 = SharingGroupUserRepository.LookupKey.userId(addUserResponse.userId) let result2 = SharingGroupUserRepository(db).lookup(key: key2 , modelInit: SharingGroupUser.init) guard case .noObjectFound = result2 else { XCTFail() return } } func testRemoveUserFromSharingGroup_notLastUserInSharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let addUserResponse = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let sharingUser: TestAccount = .secondaryOwningAccount redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeUserFromSharingGroup(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } guard let masterVersion2 = getMasterVersion(testAccount: sharingUser, sharingGroupUUID: sharingGroupUUID), masterVersion + 1 == masterVersion2 else { XCTFail() return } let key1 = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result1 = SharingGroupRepository(db).lookup(key: key1, modelInit: SharingGroup.init) guard case .found(let model) = result1, let sharingGroup = model as? Server.SharingGroup else { XCTFail() return } // Still one user in sharing group-- should not be deleted. guard !sharingGroup.deleted else { XCTFail() return } let key2 = SharingGroupUserRepository.LookupKey.userId(addUserResponse.userId) let result2 = SharingGroupUserRepository(db).lookup(key: key2 , modelInit: SharingGroupUser.init) guard case .noObjectFound = result2 else { XCTFail() return } } func testRemoveUserFromSharingGroup_failsWithBadMasterVersion() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } removeUserFromSharingGroup(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion + 1, expectMasterVersionUpdate: true) } // When user has files in the sharing group-- those should be marked as deleted. func testRemoveUserFromSharingGroup_userHasFiles() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) // Need a second user as a member of the sharing group so we can do a file index on the sharing group after the first user is removed. var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let sharingUser: TestAccount = .secondaryOwningAccount redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeUserFromSharingGroup(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } guard let (files, _) = getIndex(testAccount: sharingUser, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let filtered = files!.filter {$0.fileUUID == uploadResult.request.fileUUID} guard filtered.count == 1 else { XCTFail() return } XCTAssert(filtered[0].deleted == true) } // When owning user has sharing users in sharing group: Those should no longer be able to upload to the sharing group. func testRemoveUserFromSharingGroup_owningUserHasSharingUsers() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString let owningUser:TestAccount = .primaryOwningAccount guard let _ = self.addNewUser(testAccount: owningUser, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(testAccount: owningUser, permission: .write, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let sharingUser: TestAccount = .nonOwningSharingAccount redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeUserFromSharingGroup(testAccount: owningUser, deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let result = uploadTextFile(testAccount: sharingUser, owningAccountType: owningUser.scheme.accountName, deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID:sharingGroupUUID), masterVersion: masterVersion + 1, errorExpected: true) XCTAssert(result == nil) } func testInterleavedUploadsToDifferentSharingGroupsWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID1 = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID1, deviceUUID:deviceUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() let sharingGroupUUID2 = UUID().uuidString guard createSharingGroup(sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID, sharingGroup: sharingGroup) else { XCTFail() return } // Upload (only; no DoneUploads) to sharing group 1 guard let masterVersion1 = getMasterVersion(sharingGroupUUID: sharingGroupUUID1) else { XCTFail() return } uploadTextFile(deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID:sharingGroupUUID1), masterVersion: masterVersion1) // Upload (only; no DoneUploads) to sharing group 2 guard let masterVersion2 = getMasterVersion(sharingGroupUUID: sharingGroupUUID2) else { XCTFail() return } uploadTextFile(deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID:sharingGroupUUID2), masterVersion: masterVersion2) self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID1) self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID2) } } extension SharingGroupsControllerTests { static var allTests : [(String, (SharingGroupsControllerTests) -> () throws -> Void)] { return [ ("testCreateSharingGroupWorks", testCreateSharingGroupWorks), ("testThatNonOwningUserCannotCreateASharingGroup", testThatNonOwningUserCannotCreateASharingGroup), ("testNewlyCreatedSharingGroupHasNoFiles", testNewlyCreatedSharingGroupHasNoFiles), ("testUpdateSharingGroupWorks", testUpdateSharingGroupWorks), ("testUpdateSharingGroupWithBadMasterVersionFails", testUpdateSharingGroupWithBadMasterVersionFails), ("testRemoveSharingGroupWorks", testRemoveSharingGroupWorks), ("testRemoveSharingGroupWorks_filesMarkedAsDeleted", testRemoveSharingGroupWorks_filesMarkedAsDeleted), ("testRemoveSharingGroupWorks_multipleUsersRemovedFromSharingGroup", testRemoveSharingGroupWorks_multipleUsersRemovedFromSharingGroup), ("testRemoveSharingGroupWorks_cannotThenInviteSomeoneToThatGroup", testRemoveSharingGroupWorks_cannotThenInviteSomeoneToThatGroup), ("testRemoveSharingGroupWorks_cannotThenUploadFileToThatSharingGroup", testRemoveSharingGroupWorks_cannotThenUploadFileToThatSharingGroup), ("testRemoveSharingGroupWorks_cannotThenDoDoneUploads", testRemoveSharingGroupWorks_cannotThenDoDoneUploads), ("testRemoveSharingGroupWorks_cannotDeleteFile", testRemoveSharingGroupWorks_cannotDeleteFile), ("testRemoveSharingGroupWorks_uploadAppMetaDataFails", testRemoveSharingGroupWorks_uploadAppMetaDataFails), ("testRemoveSharingGroupWorks_downloadAppMetaDataFails", testRemoveSharingGroupWorks_downloadAppMetaDataFails), ("testRemoveSharingGroupWorks_downloadFileFails", testRemoveSharingGroupWorks_downloadFileFails), ("testRemoveSharingGroup_failsWithBadMasterVersion", testRemoveSharingGroup_failsWithBadMasterVersion), ("testUpdateSharingGroupForDeletedSharingGroupFails", testUpdateSharingGroupForDeletedSharingGroupFails), ("testRemoveUserFromSharingGroup_lastUserInSharingGroup", testRemoveUserFromSharingGroup_lastUserInSharingGroup), ("testRemoveUserFromSharingGroup_notLastUserInSharingGroup", testRemoveUserFromSharingGroup_notLastUserInSharingGroup), ("testRemoveUserFromSharingGroup_failsWithBadMasterVersion", testRemoveUserFromSharingGroup_failsWithBadMasterVersion), ("testRemoveUserFromSharingGroup_userHasFiles", testRemoveUserFromSharingGroup_userHasFiles), ("testRemoveUserFromSharingGroup_owningUserHasSharingUsers", testRemoveUserFromSharingGroup_owningUserHasSharingUsers), ("testInterleavedUploadsToDifferentSharingGroupsWorks", testInterleavedUploadsToDifferentSharingGroupsWorks) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SharingGroupsControllerTests.self) } }
mit
0f16dff75f363b14b15ffb2a4dc94725
40.048906
238
0.659602
5.837299
false
true
false
false
dpettigrew/Swallow
Source/Core/Request.swift
1
9420
// // Request.swift // Swallow // // Created by Angelo Di Paolo on 2/25/15. // Copyright (c) 2015 TheHolyGrail. All rights reserved. // import Foundation /// Defines an interface for encoding parameters in a HTTP request. protocol ParameterEncoder { func encodeURL(url: NSURL, parameters: [String : AnyObject]) -> NSURL? func encodeBody(parameters: [String : AnyObject]) -> NSData? } /// Defines an interface for encoding a `NSURLRequest`. protocol URLRequestEncodable { var urlRequestValue: NSURLRequest {get} } protocol RequestEncoder { func encodeRequest(method: Request.Method, url: String, parameters: [String : AnyObject]?, options: [Request.Option]?) -> Request } /** Encapsulates the data required to send an HTTP request. */ public struct Request { /// The `Method` enum defines the supported HTTP methods. public enum Method: String { case GET = "GET" case HEAD = "HEAD" case POST = "POST" case PUT = "PUT" case DELETE = "DELETE" } // MARK: Parameter Encodings /// A `ParameterEncoding` value defines how to encode request parameters public enum ParameterEncoding: ParameterEncoder { /// Encode parameters with percent encoding case Percent /// Encode parameters as JSON case JSON /** Encode query parameters in an existing URL. - parameter url: Query string will be appended to this NSURL value. - parameter parameters: Query parameters to be encoded as a query string. - returns: A NSURL value with query string parameters encoded. */ public func encodeURL(url: NSURL, parameters: [String : AnyObject]) -> NSURL? { if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) { components.appendPercentEncodedQuery(parameters.percentEncodedQueryString) return components.URL } return nil } /** Encode query parameters into a NSData value for request body. - parameter parameters: Query parameters to be encoded as HTTP body. - returns: NSData value with containing encoded parameters. */ public func encodeBody(parameters: [String : AnyObject]) -> NSData? { switch self { case .Percent: return parameters.percentEncodedQueryString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) case .JSON: do { return try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions()) } catch _ { return nil } } } } /// A group of static constants for referencing HTTP header field names. public struct Headers { public static let userAgent = "User-Agent" public static let contentType = "Content-Type" public static let contentLength = "Content-Length" public static let accept = "Accept" public static let cacheControl = "Cache-Control" } /// A group of static constants for referencing supported HTTP /// `Content-Type` header values. public struct ContentType { public static let formEncoded = "application/x-www-form-urlencoded" public static let json = "application/json" } /// The HTTP method of the request. public let method: Method /// The URL string of the HTTP request. public let url: String /** The parameters to encode in the HTTP request. Request parameters are percent encoded and are appended as a query string or set as the request body depending on the HTTP request method. */ public var parameters = [String : AnyObject]() /** The HTTP header fields of the request. Each key/value pair represents a HTTP header field value using the key as the field name. */ internal(set) var headers = [String : String]() /// The cache policy of the request. See NSURLRequestCachePolicy. internal(set) var cachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy /// The type of parameter encoding to use when encoding request parameters. public var parameterEncoding = ParameterEncoding.Percent { didSet { if parameterEncoding == .JSON { contentType = ContentType.json } } } /// The HTTP `Content-Type` header field value of the request. internal(set) var contentType: String? { set { headers[Headers.contentType] = newValue } get { return headers[Headers.contentType] } } /// The HTTP `User-Agent` header field value of the request. internal(set) var userAgent: String? { set { headers[Headers.userAgent] = newValue } get { return headers[Headers.userAgent] } } // MARK: Initialization /** Intialize a request value. - parameter method: The HTTP request method. - parameter url: The URL string of the HTTP request. */ init(_ method: Method, url: String) { self.method = method self.url = url } } // MARK: - URLRequestEncodable extension Request: URLRequestEncodable { /** Encode a NSURLRequest based on the value of Request. - returns: A NSURLRequest encoded based on the Request data. */ public var urlRequestValue: NSURLRequest { let urlRequest = NSMutableURLRequest(URL: NSURL(string: url)!) urlRequest.HTTPMethod = method.rawValue urlRequest.cachePolicy = cachePolicy for (name, value) in headers { urlRequest.addValue(value, forHTTPHeaderField: name) } switch method { case .GET, .DELETE: if let url = urlRequest.URL, encodedURL = parameterEncoding.encodeURL(url, parameters: parameters) { urlRequest.URL = encodedURL } default: if let data = parameterEncoding.encodeBody(parameters) { urlRequest.HTTPBody = data if urlRequest.valueForHTTPHeaderField(Headers.contentType) == nil { urlRequest.setValue(ContentType.formEncoded, forHTTPHeaderField: Headers.contentType) } } } return urlRequest.copy() as! NSURLRequest } } // MARK: - Request Options extension Request { /// An `Option` value defines a rule for encoding part of a `Request` value. public enum Option { /// Defines the parameter encoding for the HTTP request. case ParameterEncoding(Request.ParameterEncoding) /// Defines a HTTP header field name and value to set in the `Request`. case Header(String, String) /// Defines the cache policy to set in the `Request` value. case CachePolicy(NSURLRequestCachePolicy) } /// Uses an array of `Option` values as rules for mutating a `Request` value. func encodeOptions(options: [Option]) -> Request { var request = self for option in options { switch option { case .ParameterEncoding(let encoding): request.parameterEncoding = encoding case .Header(let name, let value): request.headers[name] = value case .CachePolicy(let cachePolicy): request.cachePolicy = cachePolicy } } return request } } // MARK: - Query String extension Dictionary { /// Return an encoded query string using the elements in the dictionary. var percentEncodedQueryString: String { var components = [String]() for (name, value) in self { if let percentEncodedPair = percentEncode((name, value)) { components.append(percentEncodedPair) } } return components.joinWithSeparator("&") } /// Percent encode a Key/Value pair. func percentEncode(element: Element) -> String? { let (name, value) = element let encodedName = "\(name)".percentEncodeURLQueryCharacters let encodedValue = "\(value)".percentEncodeURLQueryCharacters return "\(encodedName)=\(encodedValue)" } } // MARK: - Percent Encoded String extension String { /** Returns a new string by replacing all characters allowed in an URL's query component with percent encoded characters. */ var percentEncodeURLQueryCharacters: String { let escapedString = CFURLCreateStringByAddingPercentEscapes( nil, self, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue ) return escapedString as String } } // MARK: - Percent Encoded Query extension NSURLComponents { /// Append an encoded query string to the existing percentEncodedQuery value. func appendPercentEncodedQuery(query: String) { if percentEncodedQuery == nil { percentEncodedQuery = query } else { percentEncodedQuery = "\(percentEncodedQuery)&\(query)" } } }
mit
37001bf26adff29c3433870abe21d6c0
31.371134
133
0.612845
5.33711
false
false
false
false
ruilin/RLMap
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/NavigationAddPointToastView.swift
1
2248
@objc(MWMNavigationAddPointToastView) final class NavigationAddPointToastView: UIVisualEffectView { @IBOutlet private var descriptionLabel: UILabel! { didSet { descriptionLabel.font = UIFont.regular14() descriptionLabel.textColor = UIColor.whitePrimaryText() } } @IBOutlet private var actionButton: UIButton! { didSet { actionButton.setTitle(L("button_use"), for: .normal) actionButton.setTitleColor(UIColor.linkBlue(), for: .normal) actionButton.tintColor = UIColor.linkBlue() actionButton.titleLabel?.font = UIFont.regular17() let flipTransform = CGAffineTransform(scaleX: -1, y: 1) actionButton.transform = flipTransform actionButton.titleLabel?.transform = flipTransform actionButton.imageView?.transform = flipTransform } } @IBOutlet private var actionButtonHidden: NSLayoutConstraint! @IBOutlet private var multilineConstraints: [NSLayoutConstraint]! func config(text: String, withActionButton: Bool) { descriptionLabel.text = text setNeedsLayout() if withActionButton { actionButtonHidden.priority = UILayoutPriorityDefaultHigh actionButton.isHidden = false } else { actionButtonHidden.priority = UILayoutPriorityDefaultLow actionButton.isHidden = true } UIView.animate(withDuration: kDefaultAnimationDuration) { self.layoutIfNeeded() } } private var recentSuperviewSize: CGSize? { didSet { guard recentSuperviewSize != oldValue else { return } DispatchQueue.main.async { self.descriptionLabelLines = self.descriptionLabel.numberOfVisibleLines } } } private var descriptionLabelLines = 0 { didSet { guard descriptionLabelLines != oldValue else { return } let priority: UILayoutPriority if recentSuperviewSize!.width > recentSuperviewSize!.height { priority = UILayoutPriorityDefaultLow } else { priority = descriptionLabelLines > 1 ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow } multilineConstraints.forEach { $0.priority = priority } setNeedsLayout() } } override func layoutSubviews() { super.layoutSubviews() recentSuperviewSize = superview?.frame.size } }
apache-2.0
32298533a5b70d1ec1f0b96659452949
32.552239
103
0.717972
5.339667
false
false
false
false
huankong/Weibo
Weibo/Weibo/Main/Home/Model/UserModel.swift
1
1934
// // UserModel.swift // Weibo // // Created by ldy on 16/7/11. // Copyright © 2016年 ldy. All rights reserved. // import UIKit class UserModel: NSObject { /// 昵称 var screen_name: String? /// 用户ID var id: Int = 0 /// 性别 var gender: String? /// 粉丝数 var followers_count: Int = 0 /// 关注数 var friends_count: Int = 0 /// 微博数 var statuses_count: Int = 0 /// 头像地址 var avatar_hd: String? { didSet { if let urlStr = avatar_hd { profileURL = NSURL(string: urlStr) } } } /// 头像地址URL var profileURL: NSURL? /// 是否是微博认证用户,即加V用户,true:是,false:否 var verified: Bool = false /// 用户的认证类型,-1:没有认证,0,认证用户,2,3,5: 企业认证,220: 达人 var verified_type: Int = -1 { didSet { switch verified_type { case 2,3,5: verified_Image = UIImage(named: "avatar_enterprise_vip") case 0: verified_Image = UIImage(named: "avatar_vip") case 220: verified_Image = UIImage(named: "avatar_grassroot") default: verified_Image = nil } } } /// 用户的认证图片 var verified_Image: UIImage? /// 会员等级 var mbrank: Int = 0 { didSet { if mbrank > 0 && mbrank < 7 { mbrankImage = UIImage(named: "common_icon_membership_level" + "\(mbrank)") } } } // 会员等级图片 var mbrankImage: UIImage? // 字典转模型 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } }
apache-2.0
a4d0186ffd5a4b4c0b5a2eced9ffe19a
22.293333
90
0.503148
3.8061
false
false
false
false
ulrikdamm/Forbind
ForbindTests/ForbindBindTests.swift
1
2981
// // ForbindBindTests.swift // Forbind // // Created by Ulrik Damm on 26/03/15. // Copyright (c) 2015 Ufd.dk. All rights reserved. // import Foundation import XCTest /// Tests binding (=>) a value to a function. That function should only get /// called if and when the value is valid. If the value is invalid, the /// binding will quit early, eventually returning an error. class ForbindBindTests : XCTestCase { func testBindValue() { let a = 1 let b = (a => increment) XCTAssert(b == 2) } func testBindOptionalSome() { let a : Int? = 1 let b = (a => increment) XCTAssert(b != nil) XCTAssert(b == 2) } func testBindOptionalNone() { let a : Int? = nil let b = (a => increment) XCTAssert(b == nil) } func testBindResultOk() { let a = Result<Int>(1) let b = (a => increment) switch b { case .ok(let value): XCTAssert(value == 2) case .error(_): XCTAssert(false) } } func testBindResultError() { let a = Result<Int>(GenericError()) let b = (a => increment) switch b { case .ok(_): XCTAssert(false) case .error(let error): XCTAssert(error is GenericError) } } func testBindPromise() { let a = Promise<Int>() let b = (a => increment) var callbackCalled = false b.getValue { value in XCTAssert(value == 2) callbackCalled = true } a.setValue(1) XCTAssert(callbackCalled) } func testBindOptionalPromiseSome() { let a = Promise<Int?>() let b = (a => increment) var callbackCalled = false b.getValue { value in XCTAssert(value != nil) XCTAssert(value == 2) callbackCalled = true } a.setValue(1) XCTAssert(callbackCalled) } func testBindOptionalPromiseNone() { let a = Promise<Int?>() let b = (a => increment) var callbackCalled = false b.getValue { value in XCTAssert(value == nil) callbackCalled = true } a.setValue(nil) XCTAssert(callbackCalled) } func testBindResultPromiseOk() { let a = Promise<Result<Int>>() let b = (a => increment) var callbackCalled = false b.getValue { value in switch value { case .ok(let value): XCTAssert(value == 2) case .error(_): XCTAssert(false) } callbackCalled = true } a.setValue(.ok(1)) XCTAssert(callbackCalled) } func testBindResultPromiseError() { let a = Promise<Result<Int>>() let b = (a => increment) var callbackCalled = false b.getValue { value in switch value { case .ok(_): XCTAssert(false) case .error(let error): XCTAssert(error is GenericError) } callbackCalled = true } a.setValue(.error(GenericError())) XCTAssert(callbackCalled) } func testBindOptionalToOptional() { let promise = Promise<Int?>(value: 1) let result = promise => { (v : Int?) in "\(String(describing: v))" } var gotValue = false result.getValue { result in gotValue = true XCTAssert(result == "Optional(1)") } XCTAssert(gotValue) } }
mit
be740ce83039d2c8b5e6cc5a37c49cf7
17.066667
75
0.625294
3.293923
false
true
false
false
Ticketfly/pact-ios
Pact/ServiceProvider.swift
1
2277
// // ServiceProvider.swift // Pact // // Created by Patrick Tescher on 3/24/15. // Copyright (c) 2015 Ticketfly. All rights reserved. // import Foundation public class ServiceProvider { let name: String let serviceConsumer: ServiceConsumer var service: MockService? public init(_ name: String, serviceConsumer: ServiceConsumer) { self.name = name self.serviceConsumer = serviceConsumer } public func mockService(name: String, port: UInt) -> MockService { let mockService = MockService(name: name, port: port) service = mockService return mockService } public var jsonDictionary: NSDictionary { get { return ["name": name] as NSDictionary } } public var specJsonDictionary: NSDictionary { get { if let service = service as MockService! { return [ "provider": jsonDictionary, "consumer": serviceConsumer.jsonDictionary, "interactions": service.interactions.map({ (interaction) -> NSDictionary in interaction.jsonDictionary }) ] as NSDictionary } return NSDictionary() } } public var specFileName: String { get { let consumerName = serviceConsumer.name.stringByReplacingOccurrencesOfString(" ", withString:"_").lowercaseString let providerName = service!.name.stringByReplacingOccurrencesOfString(" ", withString:"_").lowercaseString return "\(consumerName)-\(providerName).json" } } public func writeSpecFileInDirectory(directory: String) { if let jsonData = NSJSONSerialization.dataWithJSONObject(specJsonDictionary, options: NSJSONWritingOptions.PrettyPrinted, error: nil) { if let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as? String { let pactFilePath = directory.stringByAppendingPathComponent(specFileName) NSString(string: jsonString).writeToFile(pactFilePath, atomically: true, encoding: NSUTF8StringEncoding, error: nil) println("Wrote pact to \(pactFilePath)") } } } }
mit
763a984aeda1caa8df96c147c1ae387a
34.046154
143
0.624067
5.408551
false
false
false
false
hayashi311/iosdcjp2016app
iOSApp/iOSDCJP2016/DataSource.swift
1
5911
// // DataSource.swift // iOSDCJP2016 // // Created by hayashi311 on 6/9/16. // Copyright © 2016 hayashi311. All rights reserved. // import UIKit import AlamofireImage typealias SpeakerEntity = Speaker typealias SessionEntity = Session typealias NotificationEntity = Notification typealias SponsorEntity = Sponsor enum AnyEntity { case Speaker(speaker: SpeakerEntity) case Session(session: SessionEntity) case Notification(notification: NotificationEntity) case Sponsor(sponsor: SponsorEntity) var cellId: String { get { switch self { case .Speaker: return "SpeakerTableViewCell" case .Session: return "SessionTableViewCell" case .Notification: return "NotificationTableViewCell" case .Sponsor: return "SponsorTableViewCell" } } } var url: NSURL? { get { switch self { case let .Sponsor(sponsor): guard let url = sponsor.url else { return nil } return NSURL(string: url) case let .Notification(notification): guard let url = notification.url else { return nil } return NSURL(string: url) default: return nil } } } } protocol EntityProvider: class { func entityAtIndexPath(index: NSIndexPath) -> AnyEntity? func numberOfSections() -> Int func numberOfEntitiesInSection(section: Int) -> Int } class EntityCellMapper: NSObject, UITableViewDataSource { static let cellIds = ["SpeakerTableViewCell", "SessionTableViewCell", "NotificationTableViewCell", "SponsorTableViewCell"] weak var entityProvider: EntityProvider? = nil func numberOfSectionsInTableView(tableView: UITableView) -> Int { return entityProvider?.numberOfSections() ?? 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return entityProvider?.numberOfEntitiesInSection(section) ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let entity = entityProvider?.entityAtIndexPath(indexPath), let cell = tableView.dequeueReusableCellWithIdentifier(entity.cellId) else { return UITableViewCell() } switch (cell, entity) { case let (c as SpeakerTableViewCell, .Speaker(s)): c.nameLabel.attributedText = NSAttributedString(string: s.name, style: .Title) switch s.company { case let .Some(company): c.companyLabel.attributedText = NSAttributedString(string: company, style: .Small) default: c.companyLabel.hidden = true } if let image = s.image { let URL = NSURL(string: APIBaseURL)!.URLByAppendingPathComponent(image) let filter = AspectScaledToFillSizeWithRoundedCornersFilter( size: c.iconImageView.frame.size, radius: iconImageRadius ) c.iconImageView.af_setImageWithURL( URL, placeholderImage: nil, filter: filter, imageTransition: .CrossDissolve(0.2) ) } else { c.iconImageView.image = nil } case let (c as SessionTableViewCell, .Session(s)): c.titleLabel.attributedText = NSAttributedString(string: s.title, style: .Title) if let speakerName = s.speaker?.name { c.speakerLabel.attributedText = NSAttributedString(string: speakerName, style: .Body) } c.roomLabel.attributedText = NSAttributedString(string: s.room.title, style: .Body) { builder in builder.color = UIColor.colorForRoom(s.room) } case let (c as NotificationTableViewCell, .Notification(n)): c.notificationImageView.image = nil if let i = n.image, let URL = NSURL(string: i) { let filter = AspectScaledToFillSizeWithRoundedCornersFilter( size: c.notificationImageView.frame.size, radius: iconImageRadius ) c.notificationImageView.af_setImageWithURL( URL, placeholderImage: nil, filter: filter, imageTransition: .CrossDissolve(0.2) ) } c.textView.attributedText = NSAttributedString(string: n.message, style: .Body) switch n.url { case _?: c.accessoryType = .DisclosureIndicator case nil: c.accessoryType = .None } case let (c as SponsorTableViewCell, .Sponsor(s)): c.sponsorImageView.image = nil c.sponsorImageView.af_cancelImageRequest() if let i = s.image, let imageURL = NSURL(string: i) { c.sponsorImageView.af_setImageWithURL(imageURL, placeholderImage: nil, filter: nil, imageTransition: .CrossDissolve(0.2)) } c.nameLabel.attributedText = NSAttributedString(string: s.name, style: .Body) if let url = s.url { c.urlLabel.hidden = false c.urlLabel.attributedText = NSAttributedString(string: url, style: .Small, tweak: { builder in builder.color = UIColor.accentColor() }) } else { c.urlLabel.hidden = true } default: break } return cell } }
mit
5def402ff1fac529eca64a159e553037
35.257669
126
0.567513
5.426997
false
false
false
false
SvenTiigi/PerfectAPIClient
Sources/PerfectAPIClient/Environment/APIClientEnvironmentManager.swift
1
2191
// // APIClientEnvironmentManager.swift // PerfectAPIClient // // Created by Sven Tiigi on 10.01.18. // /// The APIClientEnvironmentManager Singleton holds the environment states class APIClientEnvironmentManager { /// Shared instance static let shared = APIClientEnvironmentManager() /// The APIClient Environments var clientEnvironment: [String: APIClientEnvironment] = [:] /// Private initializer private init() { // Initialize Dictionary self.clientEnvironment = [:] } /// Set the environment for an APIClient /// /// - Parameters: /// - mode: The environment /// - apiClient: The APIClient func set<T: APIClient>(_ mode: APIClientEnvironment, forAPIClient apiClient: T.Type) { // Retrieve SubjectTypeName from APIClient let name = self.getSubjectTypeName(apiClient) // Set the APIClient enviroment self.clientEnvironment[name] = mode } /// Retrieve the environment for an APIClient /// /// - Parameter apiClient: The APIClient /// - Returns: The environment. If no environment has been set default value will be returned func get<T: APIClient>(forAPIClient apiClient: T.Type) -> APIClientEnvironment { // Retrieve SubjectTypeName from APIClient let name = self.getSubjectTypeName(apiClient) // Unwrap environment mode for APIClient name guard let mode = self.clientEnvironment[name] else { // No mode has been specified return default value return .default } // Return the APIClient environment return mode } /// Retrieve SubjectType name of an APIClient /// /// - Parameter apiClient: The APIClient /// - Returns: The SubjectType name string private func getSubjectTypeName<T: APIClient>(_ apiClient: T.Type) -> String { // Initialize APIClient Mirror let apiClientTypeMirror = Mirror(reflecting: apiClient) // Initialize String with subjectType mirror let name = String(describing: apiClientTypeMirror.subjectType) // Return the SubjectTypeName return name } }
mit
8690e4b0f9306834a67ae3bffc7f7377
33.234375
97
0.656321
5.216667
false
false
false
false
peferron/algo
EPI/Primitive Types/Compute x raised to the power y/swift/main.swift
1
1128
// O(exponent). public func powerBruteforce(base: Double, exponent: Int) -> Double { if exponent < 0 { return powerBruteforce(base: 1 / base, exponent: -exponent) } var result: Double = 1 for _ in 0..<exponent { result *= base } return result } // O(log exponent). public func powerSmartRecursive(base: Double, exponent: Int) -> Double { switch exponent { case Int.min..<0: return powerSmartRecursive(base: 1 / base, exponent: -exponent) case 0: return 1 case 1: return base default: let half = powerSmartRecursive(base: base, exponent: exponent / 2) let remainder = powerSmartRecursive(base: base, exponent: exponent % 2) return half * half * remainder } } // O(log exponent). public func powerSmartIterative(base: Double, exponent: Int) -> Double { var b = base var e = exponent if e < 0 { b = 1 / b e = -e } var result: Double = 1 while e != 0 { if e & 1 == 1 { result *= b } b *= b e >>= 1 } return result }
mit
5b64905bb25ccaeae71d16411ce7c938
19.142857
79
0.554078
3.836735
false
false
false
false
phimage/MomXML
Sources/Equatable/MomElement+Equatable.swift
1
436
// // MomElement+Equatable.swift // MomXML // // Created by anass talii on 12/06/2017. // Copyright © 2017 phimage. All rights reserved. // import Foundation extension MomElement: Equatable { public static func == (lhs: MomElement, rhs: MomElement) -> Bool { return lhs.name == rhs.name && lhs.positionX == rhs.positionX && lhs.positionY == rhs.positionY && lhs.width == rhs.width && lhs.height == rhs.height } }
mit
93919571e87ecbdc46dc4f55debc95e6
28
157
0.662069
3.346154
false
false
false
false
firebase/firebase-ios-sdk
FirebaseMLModelDownloader/Tests/Integration/ModelDownloaderIntegrationTests.swift
1
20619
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Skip keychain tests on Catalyst and macOS. Tests are skipped because they // involve interactions with the keychain that require a provisioning profile. // This is because MLModelDownloader depends on Installations. // See go/firebase-macos-keychain-popups for more details. #if !targetEnvironment(macCatalyst) && !os(macOS) import XCTest @testable import FirebaseCore @testable import FirebaseInstallations @testable import FirebaseMLModelDownloader extension UserDefaults { /// Returns a new cleared instance of user defaults. static func createTestInstance(testName: String) -> UserDefaults { let suiteName = "com.google.firebase.ml.test.\(testName)" let defaults = UserDefaults(suiteName: suiteName)! defaults.removePersistentDomain(forName: suiteName) return defaults } /// Returns the existing user defaults instance. static func getTestInstance(testName: String) -> UserDefaults { let suiteName = "com.google.firebase.ml.test.\(testName)" return UserDefaults(suiteName: suiteName)! } } final class ModelDownloaderIntegrationTests: XCTestCase { override class func setUp() { super.setUp() // TODO: Use FirebaseApp internal for test app. let bundle = Bundle(for: self) if let plistPath = bundle.path(forResource: "GoogleService-Info", ofType: "plist"), let options = FirebaseOptions(contentsOfFile: plistPath) { FirebaseApp.configure(options: options) } else { XCTFail("Could not locate GoogleService-Info.plist.") } FirebaseConfiguration.shared.setLoggerLevel(.debug) } override func setUp() { do { try ModelFileManager.emptyModelsDirectory() } catch { XCTFail("Could not empty models directory.") } } /// Test to download model info - makes an actual network call. func testDownloadModelInfo() { guard let testApp = FirebaseApp.app() else { XCTFail("Default app was not configured.") return } testApp.isDataCollectionDefaultEnabled = false let testName = String(#function.dropLast(2)) let testModelName = "pose-detection" let modelInfoRetriever = ModelInfoRetriever( modelName: testModelName, projectID: testApp.options.projectID!, apiKey: testApp.options.apiKey!, appName: testApp.name, installations: Installations.installations(app: testApp) ) let modelInfoDownloadExpectation = expectation(description: "Wait for model info to download.") modelInfoRetriever.downloadModelInfo(completion: { result in switch result { case let .success(modelInfoResult): switch modelInfoResult { case let .modelInfo(modelInfo): XCTAssertNotNil(modelInfo.urlExpiryTime) XCTAssertGreaterThan(modelInfo.downloadURL.absoluteString.count, 0) XCTAssertGreaterThan(modelInfo.modelHash.count, 0) XCTAssertGreaterThan(modelInfo.size, 0) let localModelInfo = LocalModelInfo(from: modelInfo) localModelInfo.writeToDefaults( .createTestInstance(testName: testName), appName: testApp.name ) case .notModified: XCTFail("Failed to retrieve model info.") } case let .failure(error): XCTAssertNotNil(error) XCTFail("Failed to retrieve model info - \(error)") } modelInfoDownloadExpectation.fulfill() }) wait(for: [modelInfoDownloadExpectation], timeout: 5) if let localInfo = LocalModelInfo( fromDefaults: .getTestInstance(testName: testName), name: testModelName, appName: testApp.name ) { XCTAssertNotNil(localInfo) testRetrieveModelInfo(localInfo: localInfo) } else { XCTFail("Could not save model info locally.") } } func testRetrieveModelInfo(localInfo: LocalModelInfo) { guard let testApp = FirebaseApp.app() else { XCTFail("Default app was not configured.") return } let testModelName = "pose-detection" let modelInfoRetriever = ModelInfoRetriever( modelName: testModelName, projectID: testApp.options.projectID!, apiKey: testApp.options.apiKey!, appName: testApp.name, installations: Installations.installations(app: testApp), localModelInfo: localInfo ) let modelInfoRetrieveExpectation = expectation(description: "Wait for model info to be retrieved.") modelInfoRetriever.downloadModelInfo(completion: { result in switch result { case let .success(modelInfoResult): switch modelInfoResult { case .modelInfo: XCTFail("Local model info is already the latest and should not be set again.") case .notModified: break } case let .failure(error): XCTAssertNotNil(error) XCTFail("Failed to retrieve model info - \(error)") } modelInfoRetrieveExpectation.fulfill() }) wait(for: [modelInfoRetrieveExpectation], timeout: 5) } /// Test to download model file - makes an actual network call. func testModelDownload() throws { guard let testApp = FirebaseApp.app() else { XCTFail("Default app was not configured.") return } testApp.isDataCollectionDefaultEnabled = false let testName = String(#function.dropLast(2)) let testModelName = "\(testName)-test-model" let urlString = "https://tfhub.dev/tensorflow/lite-model/ssd_mobilenet_v1/1/metadata/1?lite-format=tflite" let url = URL(string: urlString)! let remoteModelInfo = RemoteModelInfo( name: testModelName, downloadURL: url, modelHash: "mock-valid-hash", size: 10, urlExpiryTime: Date() ) let conditions = ModelDownloadConditions() let downloadExpectation = expectation(description: "Wait for model to download.") let downloader = ModelFileDownloader(conditions: conditions) let taskProgressHandler: ModelDownloadTask.ProgressHandler = { progress in XCTAssertLessThanOrEqual(progress, 1) XCTAssertGreaterThanOrEqual(progress, 0) } let taskCompletion: ModelDownloadTask.Completion = { result in switch result { case let .success(model): let modelURL = URL(fileURLWithPath: model.path) XCTAssertTrue(ModelFileManager.isFileReachable(at: modelURL)) // Remove downloaded model file. do { try ModelFileManager.removeFile(at: modelURL) } catch { XCTFail("Model removal failed - \(error)") } case let .failure(error): XCTFail("Error: \(error)") } downloadExpectation.fulfill() } let modelDownloadManager = ModelDownloadTask( remoteModelInfo: remoteModelInfo, appName: testApp.name, defaults: .createTestInstance(testName: testName), downloader: downloader, progressHandler: taskProgressHandler, completion: taskCompletion ) modelDownloadManager.resume() wait(for: [downloadExpectation], timeout: 5) XCTAssertEqual(modelDownloadManager.downloadStatus, .complete) } func testGetModel() { guard let testApp = FirebaseApp.app() else { XCTFail("Default app was not configured.") return } testApp.isDataCollectionDefaultEnabled = false let testName = String(#function.dropLast(2)) let testModelName = "image-classification" let conditions = ModelDownloadConditions() let modelDownloader = ModelDownloader.modelDownloaderWithDefaults( .createTestInstance(testName: testName), app: testApp ) /// Test download type - latest model. var downloadType: ModelDownloadType = .latestModel let latestModelExpectation = expectation(description: "Get latest model.") modelDownloader.getModel( name: testModelName, downloadType: downloadType, conditions: conditions, progressHandler: { progress in XCTAssertTrue(Thread.isMainThread, "Completion must be called on the main thread.") XCTAssertLessThanOrEqual(progress, 1) XCTAssertGreaterThanOrEqual(progress, 0) } ) { result in XCTAssertTrue(Thread.isMainThread, "Completion must be called on the main thread.") switch result { case let .success(model): XCTAssertNotNil(model.path) let modelURL = URL(fileURLWithPath: model.path) XCTAssertTrue(ModelFileManager.isFileReachable(at: modelURL)) case let .failure(error): XCTFail("Failed to download model - \(error)") } latestModelExpectation.fulfill() } wait(for: [latestModelExpectation], timeout: 5) /// Test download type - local model update in background. downloadType = .localModelUpdateInBackground let backgroundModelExpectation = expectation(description: "Get local model and update in background.") modelDownloader.getModel( name: testModelName, downloadType: downloadType, conditions: conditions, progressHandler: { progress in XCTFail("Model is already available on device.") } ) { result in switch result { case let .success(model): XCTAssertNotNil(model.path) let modelURL = URL(fileURLWithPath: model.path) XCTAssertTrue(ModelFileManager.isFileReachable(at: modelURL)) case let .failure(error): XCTFail("Failed to download model - \(error)") } backgroundModelExpectation.fulfill() } wait(for: [backgroundModelExpectation], timeout: 5) /// Test download type - local model. downloadType = .localModel let localModelExpectation = expectation(description: "Get local model.") modelDownloader.getModel( name: testModelName, downloadType: downloadType, conditions: conditions, progressHandler: { progress in XCTFail("Model is already available on device.") } ) { result in switch result { case let .success(model): XCTAssertNotNil(model.path) let modelURL = URL(fileURLWithPath: model.path) XCTAssertTrue(ModelFileManager.isFileReachable(at: modelURL)) // Remove downloaded model file. do { try ModelFileManager.removeFile(at: modelURL) } catch { XCTFail("Model removal failed - \(error)") } case let .failure(error): XCTFail("Failed to download model - \(error)") } localModelExpectation.fulfill() } wait(for: [localModelExpectation], timeout: 5) } func testGetModelWhenNameIsEmpty() { guard let testApp = FirebaseApp.app() else { XCTFail("Default app was not configured.") return } testApp.isDataCollectionDefaultEnabled = false let testName = String(#function.dropLast(2)) let emptyModelName = "" let conditions = ModelDownloadConditions() let modelDownloader = ModelDownloader.modelDownloaderWithDefaults( .createTestInstance(testName: testName), app: testApp ) let completionExpectation = expectation(description: "getModel") let progressExpectation = expectation(description: "progressHandler") progressExpectation.isInverted = true modelDownloader.getModel( name: emptyModelName, downloadType: .latestModel, conditions: conditions, progressHandler: { progress in progressExpectation.fulfill() } ) { result in XCTAssertTrue(Thread.isMainThread, "Completion must be called on the main thread.") switch result { case .failure(.emptyModelName): // The expected error. break default: XCTFail("Unexpected result: \(result)") } completionExpectation.fulfill() } wait(for: [completionExpectation, progressExpectation], timeout: 5) } /// Delete previously downloaded model. func testDeleteModel() { guard let testApp = FirebaseApp.app() else { XCTFail("Default app was not configured.") return } testApp.isDataCollectionDefaultEnabled = false let testName = String(#function.dropLast(2)) let testModelName = "pose-detection" let conditions = ModelDownloadConditions() let modelDownloader = ModelDownloader.modelDownloaderWithDefaults( .createTestInstance(testName: testName), app: testApp ) let downloadType: ModelDownloadType = .latestModel let latestModelExpectation = expectation(description: "Get latest model for deletion.") modelDownloader.getModel( name: testModelName, downloadType: downloadType, conditions: conditions, progressHandler: { progress in XCTAssertTrue(Thread.isMainThread, "Completion must be called on the main thread.") XCTAssertLessThanOrEqual(progress, 1) XCTAssertGreaterThanOrEqual(progress, 0) } ) { result in XCTAssertTrue(Thread.isMainThread, "Completion must be called on the main thread.") switch result { case let .success(model): XCTAssertNotNil(model.path) let filePath = URL(fileURLWithPath: model.path) XCTAssertTrue(ModelFileManager.isFileReachable(at: filePath)) case let .failure(error): XCTFail("Failed to download model - \(error)") } latestModelExpectation.fulfill() } wait(for: [latestModelExpectation], timeout: 5) let deleteExpectation = expectation(description: "Wait for model deletion.") modelDownloader.deleteDownloadedModel(name: testModelName) { result in deleteExpectation.fulfill() XCTAssertTrue(Thread.isMainThread, "Completion must be called on the main thread.") switch result { case .success: break case let .failure(error): XCTFail("Failed to delete model - \(error)") } } wait(for: [deleteExpectation], timeout: 5) } /// Test listing models in model directory. func testListModels() { guard let testApp = FirebaseApp.app() else { XCTFail("Default app was not configured.") return } testApp.isDataCollectionDefaultEnabled = false let testName = String(#function.dropLast(2)) let testModelName = "pose-detection" let conditions = ModelDownloadConditions() let modelDownloader = ModelDownloader.modelDownloaderWithDefaults( .createTestInstance(testName: testName), app: testApp ) let downloadType: ModelDownloadType = .latestModel let latestModelExpectation = expectation(description: "Get latest model.") modelDownloader.getModel( name: testModelName, downloadType: downloadType, conditions: conditions, progressHandler: { progress in XCTAssertLessThanOrEqual(progress, 1) XCTAssertGreaterThanOrEqual(progress, 0) } ) { result in switch result { case let .success(model): XCTAssertNotNil(model.path) let filePath = URL(fileURLWithPath: model.path) XCTAssertTrue(ModelFileManager.isFileReachable(at: filePath)) case let .failure(error): XCTFail("Failed to download model - \(error)") } latestModelExpectation.fulfill() } wait(for: [latestModelExpectation], timeout: 5) let listExpectation = expectation(description: "Wait for list models.") modelDownloader.listDownloadedModels { result in listExpectation.fulfill() switch result { case let .success(models): XCTAssertGreaterThan(models.count, 0) case let .failure(error): XCTFail("Failed to list models - \(error)") } } wait(for: [listExpectation], timeout: 5) } /// Test logging telemetry event. func testLogTelemetryEvent() { guard let testApp = FirebaseApp.app() else { XCTFail("Default app was not configured.") return } // Flip this to `true` to test logging. testApp.isDataCollectionDefaultEnabled = false let testModelName = "digit-classification" let testName = String(#function.dropLast(2)) let conditions = ModelDownloadConditions() let modelDownloader = ModelDownloader.modelDownloaderWithDefaults( .createTestInstance(testName: testName), app: testApp ) let latestModelExpectation = expectation(description: "Test get model telemetry.") modelDownloader.getModel( name: testModelName, downloadType: .latestModel, conditions: conditions ) { result in switch result { case .success: break case let .failure(error): XCTFail("Failed to download model - \(error)") } latestModelExpectation.fulfill() } wait(for: [latestModelExpectation], timeout: 5) let deleteModelExpectation = expectation(description: "Test delete model telemetry.") modelDownloader.deleteDownloadedModel(name: testModelName) { result in switch result { case .success(()): break case let .failure(error): XCTFail("Failed to delete model - \(error)") } deleteModelExpectation.fulfill() } wait(for: [deleteModelExpectation], timeout: 5) let notFoundModelName = "fakeModelName" let notFoundModelExpectation = expectation(description: "Test get model telemetry with unknown model.") modelDownloader.getModel( name: notFoundModelName, downloadType: .latestModel, conditions: conditions ) { result in switch result { case .success: XCTFail("Unexpected model success.") case let .failure(error): XCTAssertEqual(error, .notFound) } notFoundModelExpectation.fulfill() } wait(for: [notFoundModelExpectation], timeout: 5) } func testGetModelWithConditions() { guard let testApp = FirebaseApp.app() else { XCTFail("Default app was not configured.") return } testApp.isDataCollectionDefaultEnabled = false let testModelName = "pose-detection" let testName = String(#function.dropLast(2)) let conditions = ModelDownloadConditions(allowsCellularAccess: false) let modelDownloader = ModelDownloader.modelDownloaderWithDefaults( .createTestInstance(testName: testName), app: testApp ) let latestModelExpectation = expectation(description: "Get latest model with conditions.") modelDownloader.getModel( name: testModelName, downloadType: .latestModel, conditions: conditions, progressHandler: { progress in XCTAssertTrue(Thread.isMainThread, "Completion must be called on the main thread.") XCTAssertLessThanOrEqual(progress, 1) XCTAssertGreaterThanOrEqual(progress, 0) } ) { result in XCTAssertTrue(Thread.isMainThread, "Completion must be called on the main thread.") switch result { case let .success(model): XCTAssertNotNil(model.path) let filePath = URL(fileURLWithPath: model.path) XCTAssertTrue(ModelFileManager.isFileReachable(at: filePath)) case let .failure(error): XCTFail("Failed to download model - \(error)") } latestModelExpectation.fulfill() } wait(for: [latestModelExpectation], timeout: 5) } } #endif // !targetEnvironment(macCatalyst) && !os(macOS)
apache-2.0
c7d1d96ecfce8e836b78cc53e543e0d2
34.066327
98
0.653281
5.121461
false
true
false
false
Herb-Sun/OKKLineSwift
OKKLineSwift-iOS-Demo/OKKLineViewController.swift
1
2792
// // OKKLineViewController.swift // OKKLineSwift // // Copyright © 2016年 Herb - https://github.com/Herb-Sun/OKKLineSwift // import UIKit class OKKLineViewController: UIViewController { var klineView: OKKLineView! override func viewDidLoad() { super.viewDidLoad() klineView = OKKLineView() klineView.doubleTapHandle = { () -> Void in self.dismiss(animated: true, completion: nil) } view.addSubview(self.klineView) klineView.snp.makeConstraints { (make) in make.edges.equalTo(OKEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)) } // let timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(fetchData), userInfo: nil, repeats: true) fetchData() // timer.fire() //let unitValue = (limitValue.maxValue - limitValue.minValue) / Double(drawHeight) //let drawValue = Double(drawMaxY - drawY) * unitValue + limitValue.minValue //let drawY: CGFloat = abs(self.drawMaxY - CGFloat((drawValue - limitValue.minValue) / unitValue)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.isStatusBarHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIApplication.shared.isStatusBarHidden = false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscape } @objc func fetchData() { let param = ["type" : "5min", "symbol" : "okcoincnbtccny", "size" : "300"] Just.post("https://www.btc123.com/kline/klineapi", params: param, asyncCompletionHandler: { (result) -> Void in print(result) DispatchQueue.main.async(execute: { if result.ok { let resultData = result.json as! [String : Any] let datas = resultData["datas"] as! [[Double]] var dataArray = [OKKLineModel]() for data in datas { let model = OKKLineModel(date: data[0], open: data[1], close: data[4], high: data[2], low: data[3], volume: data[5]) dataArray.append(model) } // for model in OKConfiguration.shared.klineModels { // print(model.propertyDescription()) // } self.klineView.drawKLineView(klineModels: dataArray) } }) }) } }
mit
a78a4138ca9b3a54202130e670ee314b
33.012195
140
0.544281
4.671692
false
false
false
false
Jillderon/daily-deals
DailyDeals/AddDealViewController.swift
1
5716
// // AddDealViewController.swift // DailyDeals // // Description: // In this ViewController a user with a company account can add a deal to the map // by entering the name of the deal, name of the company, category and valid until date. // // Created by practicum on 12/01/17. // Copyright © 2017 Jill de Ron. All rights reserved. // import UIKit import FirebaseDatabase import FirebaseAuth import CoreLocation class AddDealViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { // MARK: Outlets. @IBOutlet weak var textfieldNameDeal: UITextField! @IBOutlet weak var textfieldNameCompany: UITextField! @IBOutlet weak var textfieldAddress: UITextField! @IBOutlet weak var pickerView: UIPickerView! @IBOutlet weak var datePicker: UIDatePicker! // MARK: Variables. let deals = ["Shopping", "Food", "Hotels", "Activities", "Party", "Other"] let reference = FIRDatabase.database().reference(withPath: "deals") var PlacementAnswer = 0 var interval = Double() var dateDeal = NSDate() var longitude = Double() var latitude = Double() // MARK: Standard functions. override func viewDidLoad() { super.viewDidLoad() hideKeyboardWhenTappedAround() pickerView.delegate = self pickerView.dataSource = self datePicker.setValue(UIColor.white, forKey: "textColor") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: PickerView functionality. func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let str = deals[row] return NSAttributedString(string: str, attributes: [NSForegroundColorAttributeName:UIColor.white]) } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return deals.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { PlacementAnswer = row } // MARK: Alert functions. private func alert(title: String, message: String) { let alertController = UIAlertController(title: title , message: message, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil)) self.present(alertController, animated: true, completion: nil) } // Special alert function to inform the user about the address format. private func alertAdressFormat() { let alertController = UIAlertController(title: "The address must be formatted as streetname + number", message: "Is " + textfieldAddress.text! + " formatted this way? If not the deal won't be shown on the map", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "No, change Adress", style: UIAlertActionStyle.default,handler: nil)) alertController.addAction(UIAlertAction(title: "Yes it is", style: UIAlertActionStyle.default) { action -> Void in self.performSegue(withIdentifier: "toMapAgain", sender: self) }) self.present(alertController, animated: true, completion: nil) } // MARK: Actions. @IBAction func AddDeal(_ sender: Any) { guard textfieldNameDeal.text != "" && textfieldNameCompany.text != "" && textfieldAddress.text != "" else { self.alert(title: "Error with adding deal", message: "Enter the title of the deal and the name and address of the company") return } alertAdressFormat() geocodeAddress() } private func geocodeAddress() { // Create address string. let location = "Netherlands, Amsterdam," + textfieldAddress.text! var coordinate = CLLocationCoordinate2D() // Geocode Address String to latitude and longitude. let geocoder = CLGeocoder() geocoder.geocodeAddressString(location) { (placemarks, error) in if let error = error { print("Unable to Forward Geocode Address (\(error))") } else { var locationAnnotation: CLLocation? if let placemarks = placemarks, placemarks.count > 0 { locationAnnotation = placemarks.first?.location } if let locationAnnotation = locationAnnotation { coordinate = locationAnnotation.coordinate self.latitude = coordinate.latitude self.longitude = coordinate.longitude // After address is formatted to long and lat call addDealInFirebase(). self.addDealInFirebase() } } } } private func addDealInFirebase() { // Make sure valid until date is a Double (because Firebase can't save a NSDATE) dateDeal = datePicker.date as NSDate interval = dateDeal.timeIntervalSince1970 // Place Deal in Firebase let deal = Deal(nameDeal: self.textfieldNameDeal.text!, nameCompany: self.textfieldNameCompany.text!, longitude: self.longitude, latitude: self.latitude, category: self.deals[self.PlacementAnswer], date: self.interval, uid: (FIRAuth.auth()?.currentUser?.uid)!) let dealRef = self.reference.child(self.textfieldNameDeal.text!.lowercased()) dealRef.setValue(deal.toAnyObject()) } }
mit
bc80d7deaf7e22e00614e19cd05ad335
40.115108
268
0.655643
5.130162
false
false
false
false
Monnoroch/Cuckoo
Generator/Dependencies/SourceKitten/Source/SourceKittenFramework/Xcode.swift
1
6100
// // Xcode.swift // SourceKitten // // Created by JP Simard on 7/15/15. // Copyright © 2015 SourceKitten. All rights reserved. // import Foundation /** Run `xcodebuild clean build` along with any passed in build arguments. - parameter arguments: Arguments to pass to `xcodebuild`. - parameter path: Path to run `xcodebuild` from. - returns: `xcodebuild`'s STDERR+STDOUT output combined. */ internal func runXcodeBuild(arguments: [String], inPath path: String) -> String? { fputs("Running xcodebuild\n", stderr) let task = Process() task.launchPath = "/usr/bin/xcodebuild" task.currentDirectoryPath = path task.arguments = arguments + ["clean", "build", "CODE_SIGN_IDENTITY=", "CODE_SIGNING_REQUIRED=NO"] let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe task.launch() let file = pipe.fileHandleForReading defer { file.closeFile() } return String(data: file.readDataToEndOfFile(), encoding: .utf8) } /** Parses likely module name from compiler or `xcodebuild` arguments. Will the following values, in this priority: module name, target name, scheme name. - parameter arguments: Compiler or `xcodebuild` arguments to parse. - returns: Module name if successful. */ internal func moduleName(fromArguments arguments: [String]) -> String? { for flag in ["-module-name", "-target", "-scheme"] { if let flagIndex = arguments.index(of: flag), flagIndex + 1 < arguments.count { return arguments[flagIndex + 1] } } return nil } /** Partially filters compiler arguments from `xcodebuild` to something that SourceKit/Clang will accept. - parameter args: Compiler arguments, as parsed from `xcodebuild`. - returns: A tuple of partially filtered compiler arguments in `.0`, and whether or not there are more flags to remove in `.1`. */ private func partiallyFilter(arguments args: [String]) -> ([String], Bool) { guard let indexOfFlagToRemove = args.index(of: "-output-file-map") else { return (args, false) } var args = args args.remove(at: args.index(after: indexOfFlagToRemove)) args.remove(at: indexOfFlagToRemove) return (args, true) } /** Filters compiler arguments from `xcodebuild` to something that SourceKit/Clang will accept. - parameter args: Compiler arguments, as parsed from `xcodebuild`. - returns: Filtered compiler arguments. */ private func filter(arguments args: [String]) -> [String] { var args = args args.append(contentsOf: ["-D", "DEBUG"]) var shouldContinueToFilterArguments = true while shouldContinueToFilterArguments { (args, shouldContinueToFilterArguments) = partiallyFilter(arguments: args) } return args.filter { ![ "-parseable-output", "-incremental", "-serialize-diagnostics", "-emit-dependencies" ].contains($0) }.map { if $0 == "-O" { return "-Onone" } else if $0 == "-DNDEBUG=1" { return "-DDEBUG=1" } return $0 } } /** Parses the compiler arguments needed to compile the `language` files. - parameter xcodebuildOutput: Output of `xcodebuild` to be parsed for compiler arguments. - parameter language: Language to parse for. - parameter moduleName: Name of the Module for which to extract compiler arguments. - returns: Compiler arguments, filtered for suitable use by SourceKit if `.Swift` or Clang if `.ObjC`. */ internal func parseCompilerArguments(xcodebuildOutput: NSString, language: Language, moduleName: String?) -> [String]? { let pattern: String if language == .objc { pattern = "/usr/bin/clang.*" } else if let moduleName = moduleName { pattern = "/usr/bin/swiftc.*-module-name \(moduleName) .*" } else { pattern = "/usr/bin/swiftc.*" } let regex = try! NSRegularExpression(pattern: pattern, options: []) // Safe to force try let range = NSRange(location: 0, length: xcodebuildOutput.length) guard let regexMatch = regex.firstMatch(in: xcodebuildOutput as String, options: [], range: range) else { return nil } let escapedSpacePlaceholder = "\u{0}" let args = filter(arguments: xcodebuildOutput .substring(with: regexMatch.range) .replacingOccurrences(of: "\\ ", with: escapedSpacePlaceholder) .components(separatedBy: " ")) // Remove first argument (swiftc/clang) and re-add spaces in arguments return (args[1..<args.count]).map { $0.replacingOccurrences(of: escapedSpacePlaceholder, with: " ") } } /** Extracts Objective-C header files and `xcodebuild` arguments from an array of header files followed by `xcodebuild` arguments. - parameter sourcekittenArguments: Array of Objective-C header files followed by `xcodebuild` arguments. - returns: Tuple of header files and xcodebuild arguments. */ public func parseHeaderFilesAndXcodebuildArguments(sourcekittenArguments: [String]) -> (headerFiles: [String], xcodebuildArguments: [String]) { var xcodebuildArguments = sourcekittenArguments var headerFiles = [String]() while let headerFile = xcodebuildArguments.first, headerFile.isObjectiveCHeaderFile() { headerFiles.append(xcodebuildArguments.remove(at: 0).absolutePathRepresentation()) } return (headerFiles, xcodebuildArguments) } public func sdkPath() -> String { let task = Process() task.launchPath = "/usr/bin/xcrun" task.arguments = ["--show-sdk-path"] let pipe = Pipe() task.standardOutput = pipe task.launch() let file = pipe.fileHandleForReading let sdkPath = String(data: file.readDataToEndOfFile(), encoding: .utf8) file.closeFile() return sdkPath?.replacingOccurrences(of: "\n", with: "") ?? "" } // MARK: - migration support @available(*, unavailable, renamed: "parseHeaderFilesAndXcodebuildArguments(sourcekittenArguments:)") public func parseHeaderFilesAndXcodebuildArguments(_ sourcekittenArguments: [String]) -> (headerFiles: [String], xcodebuildArguments: [String]) { fatalError() }
mit
eb54f2bcc602a21cab1bbaebaf2d8e16
33.072626
145
0.686014
4.274001
false
false
false
false
kelvin13/maxpng
sources/png/parser.swift
2
131299
// 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 https://mozilla.org/MPL/2.0/. extension PNG { /// struct PNG.Percentmille /// : Swift.AdditiveArithmetic /// : Swift.ExpressibleByIntegerLiteral /// A rational percentmille value. /// ## (currency-types) public struct Percentmille:AdditiveArithmetic, ExpressibleByIntegerLiteral { /// var PNG.Percentmille.points : Swift.Int /// The numerator of this percentmille value. /// /// The numerical value of this percentmille instance is this integer /// divided by `100000`. public var points:Int /// static let PNG.Percentmille.zero : Self /// ?: Swift.AdditiveArithmetic /// A percentmille value of zero. public static let zero:Self = 0 /// init PNG.Percentmille.init<T>(_:) /// where T:Swift.BinaryInteger /// Creates a percentmille value with the given numerator. /// /// The numerical value of this percentmille value will be the given /// numerator divided by `100000`. /// - points : T /// The numerator. public init<T>(_ points:T) where T:BinaryInteger { self.points = .init(points) } /// init PNG.Percentmille.init(integerLiteral:) /// ?: Swift.ExpressibleByIntegerLiteral /// Creates a percentmille value using the given integer literal as /// the numerator. /// /// The provided integer literal is *not* the numerical value of the /// created percentmille value. It will be interpreted as the numerator /// of a rational value. /// - integerLiteral : Swift.Int /// The integer literal. public init(integerLiteral:Int) { self.init(integerLiteral) } /// static func PNG.Percentmille.(+)(_:_:) /// ?: Swift.AdditiveArithmetic /// Adds two percentmille values and produces their sum. /// - lhs : Self /// The first value to add. /// - rhs : Self /// The second value to add. /// - -> : Self /// The sum of the two given percentmille values. public static func + (lhs:Self, rhs:Self) -> Self { .init(lhs.points + rhs.points) } /// static func PNG.Percentmille.(+=)(_:_:) /// ?: Swift.AdditiveArithmetic /// Adds two percentmille values and stores the result in the /// left-hand-side variable. /// - lhs : inout Self /// The first value to add. /// - rhs : Self /// The second value to add. public static func += (lhs:inout Self, rhs:Self) { lhs.points += rhs.points } /// static func PNG.Percentmille.(-)(_:_:) /// ?: Swift.AdditiveArithmetic /// Subtracts one percentmille value from another and produces their /// difference. /// - lhs : Self /// A percentmille value. /// - rhs : Self /// The value to subtract from `lhs`. /// - -> : Self /// The difference of the two given percentmille values. public static func - (lhs:Self, rhs:Self) -> Self { .init(lhs.points - rhs.points) } /// static func PNG.Percentmille.(-=)(_:_:) /// ?: Swift.AdditiveArithmetic /// Subtracts one percentmille value from another and stores the /// result in the left-hand-side variable. /// - lhs : inout Self /// A percentmille value. /// - rhs : Self /// The value to subtract from `lhs`. public static func -= (lhs:inout Self, rhs:Self) { lhs.points -= rhs.points } } /// enum PNG.Format /// A color format. /// /// This color format enumeration combines two sets of PNG color formats. /// It can represent the fifteen standard color formats from the core /// [PNG specification](http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.IHDR), /// as well as two iphone-optimized color formats from Apple’s PNG extensions. /// /// Some color formats contain a `palette`, an optional background `fill` color, /// and an optional chroma `key`. For most use cases, the background `fill` /// and chroma `key` can be set to `nil`. For the indexed color formats, /// a non-empty `palette` is mandatory. For all other color formats, the `palette` /// can be set to the empty array `[]`. /// /// Color format validation takes place when initializing a [`Layout`] instance, /// which stores the color format in a [`Data.Rectangular`] image. /// # [Grayscale formats](grayscale-color-formats) /// # [Grayscale-alpha formats](grayscale-alpha-color-formats) /// # [Indexed formats](indexed-color-formats) /// # [RGB formats](rgb-color-formats) /// # [RGBA formats](rgba-color-formats) /// # [iPhone-optimized color formats](ios-color-formats) /// # [See also](color-formats) /// ## (0:color-formats) public enum Format { /// enum PNG.Format.Pixel /// A pixel format. /// /// A pixel format specifies the color model and bit depth used by an /// image. They do not specify the ordering of the color samples within /// the internal representation of a PNG image. For example, the color formats /// [`(Format).rgba8(palette:fill:)`] and [`(Format).bgra8(palette:fill:)`] /// both correspond to the pixel format [`(Pixel).rgba8`]. /// /// The pixel format associated with a color format can be accessed /// through the [`(Format).pixel`] instance property. /// # [Pixel formats](pixel-formats) /// # [See also](color-formats) /// ## (0:color-formats) public enum Pixel { /// case PNG.Format.Pixel.v1 /// Pixels are stored as 1-bit grayscale values. /// /// An image with this pixel format has a bit depth and a color /// depth of `1`. Each sample is in the range `0 ... 1`. /// ## (pixel-formats) case v1 /// case PNG.Format.Pixel.v2 /// Pixels are stored as 2-bit grayscale values. /// /// An image with this pixel format has a bit depth and a color /// depth of `2`. Each sample is in the range `0 ... 3`. /// ## (pixel-formats) case v2 /// case PNG.Format.Pixel.v4 /// Pixels are stored as 4-bit grayscale values. /// /// An image with this pixel format has a bit depth and a color /// depth of `4`. Each sample is in the range `0 ... 15`. /// ## (pixel-formats) case v4 /// case PNG.Format.Pixel.v8 /// Pixels are stored as 8-bit grayscale values. /// /// An image with this pixel format has a bit depth and a color /// depth of `8`. Each sample is in the range `0 ... 255`. /// ## (pixel-formats) case v8 /// case PNG.Format.Pixel.v16 /// Pixels are stored as 16-bit grayscale values. /// /// An image with this pixel format has a bit depth and a color /// depth of `16`. Each sample is in the range `0 ... 65535`. /// ## (pixel-formats) case v16 /// case PNG.Format.Pixel.rgb8 /// Pixels are stored as 8-bit RGB triplets. /// /// An image with this pixel format has a bit depth and a color /// depth of `8`, for a total stride of `24` bits. /// Each sample is in the range `0 ... 255`. /// ## (pixel-formats) case rgb8 /// case PNG.Format.Pixel.rgb16 /// Pixels are stored as 16-bit RGB triplets. /// /// An image with this pixel format has a bit depth and a color /// depth of `16`, for a total stride of `48` bits. /// Each sample is in the range `0 ... 65535`. /// ## (pixel-formats) case rgb16 /// case PNG.Format.Pixel.indexed1 /// Pixels are stored as 1-bit indices. /// /// An image with this pixel format has a bit depth of `1`, and /// a color depth of `8`. Each index is in the range `0 ... 1`, /// and can reference an entry in a palette with at most `2` elements. /// ## (pixel-formats) case indexed1 /// case PNG.Format.Pixel.indexed2 /// Pixels are stored as 2-bit indices. /// /// An image with this pixel format has a bit depth of `2`, and /// a color depth of `8`. Each index is in the range `0 ... 3`, /// and can reference an entry in a palette with at most `4` elements. /// ## (pixel-formats) case indexed2 /// case PNG.Format.Pixel.indexed4 /// Pixels are stored as 4-bit indices. /// /// An image with this pixel format has a bit depth of `4`, and /// a color depth of `8`. Each index is in the range `0 ... 15`, /// and can reference an entry in a palette with at most `16` elements. /// ## (pixel-formats) case indexed4 /// case PNG.Format.Pixel.indexed8 /// Pixels are stored as 8-bit indices. /// /// An image with this pixel format has a bit depth and color depth /// of `8`. Each index is in the range `0 ... 255`, and can reference /// an entry in a palette with at most `256` elements. /// ## (pixel-formats) case indexed8 /// case PNG.Format.Pixel.va8 /// Pixels are stored as 8-bit grayscale-alpha pairs. /// /// An image with this pixel format has a bit depth and a color /// depth of `8`, for a total stride of `16` bits. Each sample /// is in the range `0 ... 255`. /// ## (pixel-formats) case va8 /// case PNG.Format.Pixel.va16 /// Pixels are stored as 16-bit grayscale-alpha pairs. /// /// An image with this pixel format has a bit depth and a color /// depth of `16`, for a total stride of `32` bits. Each sample /// is in the range `0 ... 65535`. /// ## (pixel-formats) case va16 /// case PNG.Format.Pixel.rgba8 /// Pixels are stored as 8-bit RGBA quadruplets. /// /// An image with this pixel format has a bit depth and a color /// depth of `8`, for a total stride of `32` bits. /// Each sample is in the range `0 ... 255`. /// ## (pixel-formats) case rgba8 /// case PNG.Format.Pixel.rgba16 /// Pixels are stored as 16-bit RGBA quadruplets. /// /// An image with this pixel format has a bit depth and a color /// depth of `16`, for a total stride of `64` bits. /// Each sample is in the range `0 ... 65535`. /// ## (pixel-formats) case rgba16 } /// case PNG.Format.v1(fill:key:) /// A 1-bit grayscale color format. /// /// This color format has a [`pixel`] format of [`(Pixel).v1`]. /// - fill : Swift.UInt8? /// An optional background color. The sample is unscaled, and must /// be in the range `0 ... 1`. Most PNG viewers ignore this field. /// - key : Swift.UInt8? /// An optional chroma key. If present, pixels matching it /// will be displayed as transparent, if possible. The sample is /// unscaled, and must be in the range `0 ... 1`. /// ## (grayscale-color-formats) /// case PNG.Format.v2(fill:key:) /// A 2-bit grayscale color format. /// /// This color format has a [`pixel`] format of [`(Pixel).v2`]. /// - fill : Swift.UInt8? /// An optional background color. The sample is unscaled, and must /// be in the range `0 ... 3`. Most PNG viewers ignore this field. /// - key : Swift.UInt8? /// An optional chroma key. If present, pixels matching it /// will be displayed as transparent, if possible. The sample is /// unscaled, and must be in the range `0 ... 3`. /// ## (grayscale-color-formats) /// case PNG.Format.v4(fill:key:) /// A 4-bit grayscale color format. /// /// This color format has a [`pixel`] format of [`(Pixel).v4`]. /// - fill : Swift.UInt8? /// An optional background color. The sample is unscaled, and must /// be in the range `0 ... 15`. Most PNG viewers ignore this field. /// - key : Swift.UInt8? /// An optional chroma key. If present, pixels matching it /// will be displayed as transparent, if possible. The sample is /// unscaled, and must be in the range `0 ... 15`. /// ## (grayscale-color-formats) /// case PNG.Format.v8(fill:key:) /// An 8-bit grayscale color format. /// /// This color format has a [`pixel`] format of [`(Pixel).v8`]. /// - fill : Swift.UInt8? /// An optional background color. Most PNG viewers ignore this field. /// - key : Swift.UInt8? /// An optional chroma key. If present, pixels matching it /// will be displayed as transparent, if possible. /// ## (grayscale-color-formats) /// case PNG.Format.v16(fill:key:) /// A 16-bit grayscale color format. /// /// This color format has a [`pixel`] format of [`(Pixel).v16`]. /// - fill : Swift.UInt16? /// An optional background color. Most PNG viewers ignore this field. /// - key : Swift.UInt16? /// An optional chroma key. If present, pixels matching it /// will be displayed as transparent, if possible. /// ## (grayscale-color-formats) /// case PNG.Format.bgr8(palette:fill:key:) /// An 8-bit BGR color format. /// /// This color format is an iphone-optimized format. /// It has a [`pixel`] format of [`(Pixel).rgb8`]. /// - palette : [(b:Swift.UInt8, g:Swift.UInt8, r:Swift.UInt8)] /// An palette of suggested posterization values. Most PNG viewers /// ignore this field. /// /// This field is unrelated to, and should not be confused with a /// [`SuggestedPalette`]. /// - fill : (b:Swift.UInt8, g:Swift.UInt8, r:Swift.UInt8)? /// An optional background color. Most PNG viewers ignore this field. /// - key : (b:Swift.UInt8, g:Swift.UInt8, r:Swift.UInt8)? /// An optional chroma key. If present, pixels matching it /// will be displayed as transparent, if possible. /// ## (ios-color-formats) /// case PNG.Format.rgb8(palette:fill:key:) /// An 8-bit RGB color format. /// /// This color format has a [`pixel`] format of [`(Pixel).rgb8`]. /// - palette : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8)] /// An palette of suggested posterization values. Most PNG viewers /// ignore this field. /// /// This field is unrelated to, and should not be confused with a /// [`SuggestedPalette`]. /// - fill : (r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8)? /// An optional background color. Most PNG viewers ignore this field. /// - key : (r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8)? /// An optional chroma key. If present, pixels matching it /// will be displayed as transparent, if possible. /// ## (rgb-color-formats) /// case PNG.Format.rgb16(palette:fill:key:) /// A 16-bit RGB color format. /// /// This color format has a [`pixel`] format of [`(Pixel).rgb16`]. /// - palette : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8)] /// An palette of suggested posterization values. Most PNG viewers /// ignore this field. Although the image color depth is `16`, the /// palette atom type is [`Swift.UInt8`], not [`Swift.UInt16`]. /// /// This field is unrelated to, and should not be confused with a /// [`SuggestedPalette`]. /// - fill : (r:Swift.UInt16, g:Swift.UInt16, b:Swift.UInt16)? /// An optional background color. Most PNG viewers ignore this field. /// - key : (r:Swift.UInt16, g:Swift.UInt16, b:Swift.UInt16)? /// An optional chroma key. If present, pixels matching it /// will be displayed as transparent, if possible. /// ## (rgb-color-formats) /// case PNG.Format.indexed1(palette:fill:) /// A 1-bit indexed color format. /// /// This color format has a [`pixel`] format of [`(Pixel).indexed1`]. /// - palette : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8, a:Swift.UInt8)] /// The palette values referenced by an image with this color format. /// This palette must be non-empty, and can have at most `2` entries. /// - fill : Swift.Int? /// A palette index specifying an optional background color. This index /// must be within the index range of the `palette` array. /// /// Most PNG viewers ignore this field. /// ## (indexed-color-formats) /// case PNG.Format.indexed2(palette:fill:) /// A 2-bit indexed color format. /// /// This color format has a [`pixel`] format of [`(Pixel).indexed2`]. /// - palette : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8, a:Swift.UInt8)] /// The palette values referenced by an image with this color format. /// This palette must be non-empty, and can have at most `4` entries. /// - fill : Swift.Int? /// A palette index specifying an optional background color. This index /// must be within the index range of the `palette` array. /// /// Most PNG viewers ignore this field. /// ## (indexed-color-formats) /// case PNG.Format.indexed4(palette:fill:) /// A 4-bit indexed color format. /// /// This color format has a [`pixel`] format of [`(Pixel).indexed4`]. /// - palette : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8, a:Swift.UInt8)] /// The palette values referenced by an image with this color format. /// This palette must be non-empty, and can have at most `16` entries. /// - fill : Swift.Int? /// A palette index specifying an optional background color. This index /// must be within the index range of the `palette` array. /// /// Most PNG viewers ignore this field. /// ## (indexed-color-formats) /// case PNG.Format.indexed8(palette:fill:) /// An 8-bit indexed color format. /// /// This color format has a [`pixel`] format of [`(Pixel).indexed8`]. /// - palette : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8, a:Swift.UInt8)] /// The palette values referenced by an image with this color format. /// This palette must be non-empty, and can have at most `256` entries. /// - fill : Swift.Int? /// A palette index specifying an optional background color. This index /// must be within the index range of the `palette` array. /// /// Most PNG viewers ignore this field. /// ## (indexed-color-formats) /// case PNG.Format.va8(fill:) /// An 8-bit grayscale-alpha color format. /// /// This color format has a [`pixel`] format of [`(Pixel).va8`]. /// - fill : Swift.UInt8? /// An optional background color. Most PNG viewers ignore this field. /// ## (grayscale-alpha-color-formats) /// case PNG.Format.va16(fill:) /// A 16-bit grayscale-alpha color format. /// /// This color format has a [`pixel`] format of [`(Pixel).va16`]. /// - fill : Swift.UInt16? /// An optional background color. Most PNG viewers ignore this field. /// ## (grayscale-alpha-color-formats) /// case PNG.Format.bgra8(palette:fill:) /// An 8-bit BGRA color format. /// /// This color format is an iphone-optimized format. /// It has a [`pixel`] format of [`(Pixel).rgba8`]. /// - palette : [(b:Swift.UInt8, g:Swift.UInt8, r:Swift.UInt8)] /// An palette of suggested posterization values. Most PNG viewers /// ignore this field. /// /// This field is unrelated to, and should not be confused with a /// [`SuggestedPalette`]. /// - fill : (b:Swift.UInt8, g:Swift.UInt8, r:Swift.UInt8)? /// An optional background color. Most PNG viewers ignore this field. /// ## (ios-color-formats) /// case PNG.Format.rgba8(palette:fill:) /// An 8-bit RGBA color format. /// /// This color format has a [`pixel`] format of [`(Pixel).rgba8`]. /// - palette : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8)] /// An palette of suggested posterization values. Most PNG viewers /// ignore this field. /// /// This field is unrelated to, and should not be confused with a /// [`SuggestedPalette`]. /// - fill : (r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8)? /// An optional background color. Most PNG viewers ignore this field. /// ## (rgba-color-formats) /// case PNG.Format.rgba16(palette:fill:) /// A 16-bit RGBA color format. /// /// This color format has a [`pixel`] format of [`(Pixel).rgba16`]. /// - palette : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8)] /// An palette of suggested posterization values. Most PNG viewers /// ignore this field. Although the image color depth is `16`, the /// palette atom type is [`Swift.UInt8`], not [`Swift.UInt16`]. /// /// This field is unrelated to, and should not be confused with a /// [`SuggestedPalette`]. /// - fill : (r:Swift.UInt16, g:Swift.UInt16, b:Swift.UInt16)? /// An optional background color. Most PNG viewers ignore this field. /// ## (rgba-color-formats) case v1 ( fill: UInt8?, key: UInt8? ) case v2 ( fill: UInt8?, key: UInt8? ) case v4 ( fill: UInt8?, key: UInt8? ) case v8 ( fill: UInt8?, key: UInt8? ) case v16 ( fill: UInt16?, key: UInt16? ) case bgr8 (palette:[(b:UInt8, g:UInt8, r:UInt8 )], fill:(b:UInt8, g:UInt8, r:UInt8 )?, key:(b:UInt8, g:UInt8, r:UInt8 )?) case rgb8 (palette:[(r:UInt8, g:UInt8, b:UInt8 )], fill:(r:UInt8, g:UInt8, b:UInt8 )?, key:(r:UInt8, g:UInt8, b:UInt8 )?) case rgb16 (palette:[(r:UInt8, g:UInt8, b:UInt8 )], fill:(r:UInt16, g:UInt16, b:UInt16)?, key:(r:UInt16, g:UInt16, b:UInt16)?) case indexed1(palette:[(r:UInt8, g:UInt8, b:UInt8, a:UInt8)], fill: Int? ) case indexed2(palette:[(r:UInt8, g:UInt8, b:UInt8, a:UInt8)], fill: Int? ) case indexed4(palette:[(r:UInt8, g:UInt8, b:UInt8, a:UInt8)], fill: Int? ) case indexed8(palette:[(r:UInt8, g:UInt8, b:UInt8, a:UInt8)], fill: Int? ) case va8 ( fill: UInt8? ) case va16 ( fill: UInt16? ) case bgra8 (palette:[(b:UInt8, g:UInt8, r:UInt8 )], fill:(b:UInt8, g:UInt8, r:UInt8 )? ) case rgba8 (palette:[(r:UInt8, g:UInt8, b:UInt8 )], fill:(r:UInt8, g:UInt8, b:UInt8 )? ) case rgba16 (palette:[(r:UInt8, g:UInt8, b:UInt8 )], fill:(r:UInt16, g:UInt16, b:UInt16)? ) } } extension PNG.Format.Pixel { /// var PNG.Format.Pixel.hasColor : Swift.Bool { get } /// @ inlinable /// Indicates whether an image with this pixel format contains more than one /// non-alpha color component. /// /// This property is `true` for all RGB, RGBA, and indexed pixel formats, /// and `false` otherwise. @inlinable public var hasColor:Bool { switch self { case .v1, .v2, .v4, .v8, .v16, .va8, .va16: return false case .rgb8, .rgb16, .indexed1, .indexed2, .indexed4, .indexed8, .rgba8, .rgba16: return true } } /// var PNG.Format.Pixel.hasAlpha : Swift.Bool { get } /// @ inlinable /// Indicates whether an image with this pixel format contains an alpha /// component. /// /// This property is `true` for all grayscale-alpha and RGBA pixel formats, /// and `false` otherwise. Note that indexed pixel formats are not /// considered transparent pixel formats, even though images using them /// can contain per-pixel alpha information. @inlinable public var hasAlpha:Bool { switch self { case .v1, .v2, .v4, .v8, .v16, .rgb8, .rgb16, .indexed1, .indexed2, .indexed4, .indexed8: return false case .va8, .va16, .rgba8, .rgba16: return true } } @inlinable var volume:Int { self.depth * self.channels } /// var PNG.Format.Pixel.channels : Swift.Int { get } /// @ inlinable /// The number of channels encoded per-pixel in the internal representation /// of an image with this pixel format. /// /// This number is *not* the number of components in the encoded image; /// it indicates the dimensionality of the stored image data. Notably, /// indexed images are defined as having one channel, even though each /// scalar index represents a four-component color value. /// /// This property returns `1` for all grayscale and indexed pixel formats. /// /// This property returns `2` for all grayscale-alpha pixel formats. /// /// This property returns `3` for all RGB pixel formats. /// /// This property returns `4` for all RGBA pixel formats. @inlinable public var channels:Int { switch self { case .v1, .v2, .v4, .v8, .v16, .indexed1, .indexed2, .indexed4, .indexed8: return 1 case .va8, .va16: return 2 case .rgb8, .rgb16: return 3 case .rgba8, .rgba16: return 4 } } /// var PNG.Format.Pixel.depth : Swift.Int { get } /// @ inlinable /// The bit depth of an image with this pixel format. /// /// This number is *not* the color depth the encoded image; /// it indicates the bit depth of the stored image data. Notably, /// indexed images always have a color depth of `8`, even though they may /// have a bit depth less than `8`. /// /// This property returns `1` for the [`v1`] and [`indexed1`] pixel formats. /// /// This property returns `2` for the [`v2`] and [`indexed2`] pixel formats. /// /// This property returns `4` for the [`v4`] and [`indexed4`] pixel formats. /// /// This property returns `8` for the [`v8`], [`va8`], [`indexed8`], /// [`rgb8`], and [`rgba8`] pixel formats. /// /// This property returns `16` for the [`v16`], [`va16`], /// [`rgb16`], and [`rgba16`] pixel formats. @inlinable public var depth:Int { switch self { case .v1, .indexed1: return 1 case .v2, .indexed2: return 2 case .v4, .indexed4: return 4 case .v8, .rgb8, .indexed8, .va8, .rgba8: return 8 case .v16, .rgb16, .va16, .rgba16: return 16 } } var code:(depth:UInt8, type:UInt8) { switch self { case .v1: return ( 1, 0) case .v2: return ( 2, 0) case .v4: return ( 4, 0) case .v8: return ( 8, 0) case .v16: return (16, 0) case .rgb8: return ( 8, 2) case .rgb16: return (16, 2) case .indexed1: return ( 1, 3) case .indexed2: return ( 2, 3) case .indexed4: return ( 4, 3) case .indexed8: return ( 8, 3) case .va8: return ( 8, 4) case .va16: return (16, 4) case .rgba8: return ( 8, 6) case .rgba16: return (16, 6) } } static func recognize(code:(depth:UInt8, type:UInt8)) -> Self? { switch code { case ( 1, 0): return .v1 case ( 2, 0): return .v2 case ( 4, 0): return .v4 case ( 8, 0): return .v8 case (16, 0): return .v16 case ( 8, 2): return .rgb8 case (16, 2): return .rgb16 case ( 1, 3): return .indexed1 case ( 2, 3): return .indexed2 case ( 4, 3): return .indexed4 case ( 8, 3): return .indexed8 case ( 8, 4): return .va8 case (16, 4): return .va16 case ( 8, 6): return .rgba8 case (16, 6): return .rgba16 default: return nil } } } extension PNG.Format { // can’t use these in the enum cases because they are `internal` only typealias RGB<T> = (r:T, g:T, b:T) typealias RGBA<T> = (r:T, g:T, b:T, a:T) /// var PNG.Format.pixel : Pixel { get } /// @ inlinable /// The pixel format used by an image with this color format. @inlinable public var pixel:Pixel { switch self { case .v1: return .v1 case .v2: return .v2 case .v4: return .v4 case .v8: return .v8 case .v16: return .v16 case .bgr8: return .rgb8 case .rgb8: return .rgb8 case .rgb16: return .rgb16 case .indexed1: return .indexed1 case .indexed2: return .indexed2 case .indexed4: return .indexed4 case .indexed8: return .indexed8 case .va8: return .va8 case .va16: return .va16 case .bgra8: return .rgba8 case .rgba8: return .rgba8 case .rgba16: return .rgba16 } } // enum case constructors can’t perform validation, so we need to check // the range of the sample values with this function. func validate() -> Self { let max:(sample:UInt16, count:Int, index:Int) max.sample = .max >> (UInt16.bitWidth - self.pixel.depth) max.count = 1 << min(self.pixel.depth, 8) // palette cannot contain more entries than bit depth allows switch self { case .bgr8 (palette: let palette, fill: _, key: _), .bgra8 (palette: let palette, fill: _): max.index = palette.count - 1 case .rgb8 (palette: let palette, fill: _, key: _), .rgb16 (palette: let palette, fill: _, key: _), .rgba8 (palette: let palette, fill: _), .rgba16 (palette: let palette, fill: _): max.index = palette.count - 1 case .indexed1(palette: let palette, fill: _), .indexed2(palette: let palette, fill: _), .indexed4(palette: let palette, fill: _), .indexed8(palette: let palette, fill: _): guard !palette.isEmpty else { PNG.ParsingError.invalidPaletteCount(0, max: max.count).fatal } max.index = palette.count - 1 default: max.index = -1 } guard max.index < max.count else { PNG.ParsingError.invalidPaletteCount(max.index + 1, max: max.count).fatal } switch self { case .v1(fill: let fill?, key: _), .v2(fill: let fill?, key: _), .v4(fill: let fill?, key: _): let fill:UInt16 = .init(fill) guard fill <= max.sample else { PNG.ParsingError.invalidBackgroundSample(fill, max: max.sample).fatal } case .indexed1(palette: _, fill: let i?), .indexed2(palette: _, fill: let i?), .indexed4(palette: _, fill: let i?), .indexed8(palette: _, fill: let i?): guard i <= max.index else { PNG.ParsingError.invalidBackgroundIndex(i, max: max.index).fatal } default: break } switch self { case .v1(fill: _?, key: let key?), .v2(fill: _?, key: let key?), .v4(fill: _?, key: let key?): let key:UInt16 = .init(key) guard key <= max.sample else { PNG.ParsingError.invalidTransparencySample(key, max: max.sample).fatal } default: break } return self } // this function assumes all inputs have been validated for consistency, // except for the presence of the palette argument itself. static func recognize(standard:PNG.Standard, pixel:PNG.Format.Pixel, palette:PNG.Palette?, background:PNG.Background?, transparency:PNG.Transparency?) -> Self? { let format:Self switch pixel { case .v1, .v2, .v4, .v8, .v16: guard palette == nil else { PNG.ParsingError.unexpectedPalette(pixel: pixel).fatal } let f:UInt16?, k:UInt16? switch background?.case { case .v(let v)?: f = v case nil: f = nil default: fatalError("expected background of case `v` for pixel format `\(pixel)`") } switch transparency?.case { case .v(let v)?: k = v case nil: k = nil default: fatalError("expected transparency of case `v` for pixel format `\(pixel)`") } switch pixel { case .v1: format = .v1(fill: f.map(UInt8.init(_:)), key: k.map(UInt8.init(_:))) case .v2: format = .v2(fill: f.map(UInt8.init(_:)), key: k.map(UInt8.init(_:))) case .v4: format = .v4(fill: f.map(UInt8.init(_:)), key: k.map(UInt8.init(_:))) case .v8: format = .v8(fill: f.map(UInt8.init(_:)), key: k.map(UInt8.init(_:))) case .v16: format = .v16(fill: f, key: k) default: fatalError("unreachable") } case .rgb8, .rgb16: let palette:[RGB<UInt8>] = palette?.entries ?? [] let f:RGB<UInt16>?, k:RGB<UInt16>? switch background?.case { case .rgb(let c)?: f = c case nil: f = nil default: fatalError("expected background of case `rgb` for pixel format `\(pixel)`") } switch transparency?.case { case .rgb(let c)?: k = c case nil: k = nil default: fatalError("expected transparency of case `rgb` for pixel format `\(pixel)`") } switch (standard, pixel) { case (.common, .rgb8): format = .rgb8(palette: palette, fill: f.map{ (.init($0.r), .init($0.g), .init($0.b)) }, key: k.map{ (.init($0.r), .init($0.g), .init($0.b)) }) case (.ios, .rgb8): format = .bgr8(palette: palette.map{ ($0.b, $0.g, $0.r) }, fill: f.map{ (.init($0.b), .init($0.g), .init($0.r)) }, key: k.map{ (.init($0.b), .init($0.g), .init($0.r)) }) case (_, .rgb16): format = .rgb16(palette: palette, fill: f, key: k) default: fatalError("unreachable") } case .indexed1, .indexed2, .indexed4, .indexed8: guard let solid:PNG.Palette = palette else { return nil } let f:Int? switch background?.case { case .palette(let i): f = i case nil: f = nil default: fatalError("expected background of case `palette` for pixel format `\(pixel)`") } let palette:[RGBA<UInt8>] switch transparency?.case { case nil: palette = solid.entries.map { ( $0.r, $0.g, $0.b, .max) } case .palette(let alpha): guard alpha.count <= solid.entries.count else { PNG.ParsingError.invalidTransparencyCount(alpha.count, max: solid.entries.count).fatal } palette = zip(solid.entries, alpha).map{ ($0.0.r, $0.0.g, $0.0.b, $0.1) } + solid.entries.dropFirst(alpha.count).map{ ( $0.r, $0.g, $0.b, .max) } default: fatalError("expected transparency of case `palette` for pixel format `\(pixel)`") } switch pixel { case .indexed1: format = .indexed1(palette: palette, fill: f) case .indexed2: format = .indexed2(palette: palette, fill: f) case .indexed4: format = .indexed4(palette: palette, fill: f) case .indexed8: format = .indexed8(palette: palette, fill: f) default: fatalError("unreachable") } case .va8, .va16: guard palette == nil else { PNG.ParsingError.unexpectedPalette(pixel: pixel).fatal } guard transparency == nil else { PNG.ParsingError.unexpectedTransparency(pixel: pixel).fatal } let f:UInt16? switch background?.case { case .v(let v)?: f = v case nil: f = nil default: fatalError("expected background of case `v` for pixel format `\(pixel)`") } switch pixel { case .va8: format = .va8( fill: f.map(UInt8.init(_:))) case .va16: format = .va16(fill: f) default: fatalError("unreachable") } case .rgba8, .rgba16: guard transparency == nil else { PNG.ParsingError.unexpectedTransparency(pixel: pixel).fatal } let palette:[RGB<UInt8>] = palette?.entries ?? [] let f:RGB<UInt16>? switch background?.case { case .rgb(let c)?: f = c case nil: f = nil default: fatalError("expected background of case `rgb` for pixel format `\(pixel)`") } switch (standard, pixel) { case (.common, .rgba8): format = .rgba8(palette: palette, fill: f.map{ (.init($0.r), .init($0.g), .init($0.b)) }) case (.ios, .rgba8): format = .bgra8(palette: palette.map{ ($0.b, $0.g, $0.r) }, fill: f.map{ (.init($0.b), .init($0.g), .init($0.r)) }) case (_, .rgba16): format = .rgba16(palette: palette, fill: f) default: fatalError("unreachable") } } // do not call `.validate()` on `format` because this will be done when // the `PNG.Layout` struct is initialized return format } } extension PNG { /// struct PNG.Header /// An image header. /// /// This type models the information stored in a [`(Chunk).IHDR`] chunk. /// # [Parsing and serialization](header-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct Header { /// let PNG.Header.size : (x:Swift.Int, y:Swift.Int) /// The size of an image, measured in pixels. public let size:(x:Int, y:Int), /// let PNG.Header.pixel : Format.Pixel /// The pixel format of an image. pixel:PNG.Format.Pixel, /// let PNG.Header.interlaced : Swift.Bool /// Indicates whether an image uses interlacing. interlaced:Bool /// init PNG.Header.init(size:pixel:interlaced:standard:) /// Creates an image header. /// /// This initializer validates the image `size`, and validates the /// `pixel` format against the given PNG `standard`. /// - size : (x:Swift.Int, y:Swift.Int) /// An image size, measured in pixels. /// /// Passing a `size` with a zero or negative dimension /// will result in a precondition failure. /// - pixel : Format.Pixel /// A pixel format. /// - interlaced: Swift.Bool /// Indicates if interlacing is enabled. /// - standard : Standard /// Specifies if the header is for a standard image, /// or an iphone-optimized image. /// /// If `standard` is [`(Standard).ios`], then the `pixel` format /// must be either [`(Format.Pixel).rgb8`] or [`(Format.Pixel).rgba8`]. /// Otherwise, this initializer will suffer a precondition failure. public init(size:(x:Int, y:Int), pixel:PNG.Format.Pixel, interlaced:Bool, standard:PNG.Standard) { guard size.x > 0, size.y > 0 else { PNG.ParsingError.invalidHeaderSize(size).fatal } // iphone-optimized PNG can only have pixel type rgb8 or rgb16 switch (standard, pixel) { case (.common, _): break case (.ios, .rgb8), (.ios, .rgba8): break default: PNG.ParsingError.invalidHeaderPixelFormat(pixel, standard: standard).fatal } self.size = size self.pixel = pixel self.interlaced = interlaced } } } extension PNG.Header { /// init PNG.Header.init(parsing:standard:) /// throws /// Creates an image header by parsing the given chunk data, interpreting it /// according to the given PNG `standard`. /// - data : [Swift.UInt8] /// The contents of an [`(Chunk).IHDR`] chunk to parse. /// - standard : Standard /// Specifies if the header should be interpreted as a standard PNG header, /// or an iphone-optimized PNG header. /// ## (header-parsing-and-serialization) public init(parsing data:[UInt8], standard:PNG.Standard) throws { guard data.count == 13 else { throw PNG.ParsingError.invalidHeaderChunkLength(data.count) } guard let pixel:PNG.Format.Pixel = .recognize(code: (data[8], data[9])) else { throw PNG.ParsingError.invalidHeaderPixelFormatCode((data[8], data[9])) } // iphone-optimized PNG can only have pixel type rgb8 or rgb16 switch (standard, pixel) { case (.common, _): break case (.ios, .rgb8), (.ios, .rgba8): break default: throw PNG.ParsingError.invalidHeaderPixelFormat(pixel, standard: standard) } self.pixel = pixel // validate other fields guard data[10] == 0 else { throw PNG.ParsingError.invalidHeaderCompressionMethodCode(data[10]) } guard data[11] == 0 else { throw PNG.ParsingError.invalidHeaderFilterCode(data[11]) } switch data[12] { case 0: self.interlaced = false case 1: self.interlaced = true case let code: throw PNG.ParsingError.invalidHeaderInterlacingCode(code) } self.size.x = data.load(bigEndian: UInt32.self, as: Int.self, at: 0) self.size.y = data.load(bigEndian: UInt32.self, as: Int.self, at: 4) // validate size guard self.size.x > 0, self.size.y > 0 else { throw PNG.ParsingError.invalidHeaderSize(self.size) } } /// var PNG.Header.serialized : [Swift.UInt8] { get } /// Encodes this image header as the contents of an [`(Chunk).IHDR`] chunk. /// ## (header-parsing-and-serialization) public var serialized:[UInt8] { .init(unsafeUninitializedCapacity: 13) { $0.store(self.size.x, asBigEndian: UInt32.self, at: 0) $0.store(self.size.y, asBigEndian: UInt32.self, at: 4) ($0[8], $0[9]) = self.pixel.code $0[10] = 0 $0[11] = 0 $0[12] = self.interlaced ? 1 : 0 $1 = 13 } } } extension PNG { /// struct PNG.Palette /// An image palette. /// /// This type models the information stored in a [`(Chunk).PLTE`] chunk. /// This information is used to populate the non-alpha components of the /// `palette` field in an image color [`Format`], when appropriate. /// # [Parsing and serialization](palette-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct Palette { /// let PNG.Palette.entries : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8)] /// The entries in this palette. public let entries:[(r:UInt8, g:UInt8, b:UInt8)] } } extension PNG.Palette { /// init PNG.Palette.init(entries:pixel:) /// Creates an image palette. /// /// This initializer validates the palette information against the given /// `pixel` format. /// - entries : [(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8)] /// An array of palette entries. This array must be non-empty, and can /// contain at most `256`, or `1 << pixel.`[`(Format.Pixel).depth`] elements, /// whichever is lower. /// - pixel : Format.Pixel /// The pixel format of the image this palette is to be used for. /// If this parameter is a grayscale or grayscale-alpha format, this /// initializer will suffer a precondition failure. public init(entries:[(r:UInt8, g:UInt8, b:UInt8)], pixel:PNG.Format.Pixel) { guard pixel.hasColor else { PNG.ParsingError.unexpectedPalette(pixel: pixel).fatal } let max:Int = 1 << Swift.min(pixel.depth, 8) guard 1 ... max ~= entries.count else { PNG.ParsingError.invalidPaletteCount(entries.count, max: max).fatal } self.entries = entries } /// init PNG.Palette.init(parsing:pixel:) /// throws /// Creates an image palette by parsing the given chunk data, interpreting /// and validating it according to the given `pixel` format. /// - data : [Swift.UInt8] /// The contents of a [`(Chunk).PLTE`] chunk to parse. /// - pixel : Format.Pixel /// The pixel format specifying how the chunk data is to be interpreted. /// ## (palette-parsing-and-serialization) public init(parsing data:[UInt8], pixel:PNG.Format.Pixel) throws { guard pixel.hasColor else { throw PNG.ParsingError.unexpectedPalette(pixel: pixel) } let (count, remainder):(Int, Int) = data.count.quotientAndRemainder(dividingBy: 3) guard remainder == 0 else { throw PNG.ParsingError.invalidPaletteChunkLength(data.count) } // check number of palette entries let max:Int = 1 << Swift.min(pixel.depth, 8) guard 1 ... max ~= count else { throw PNG.ParsingError.invalidPaletteCount(count, max: max) } self.entries = stride(from: data.startIndex, to: data.endIndex, by: 3).map { (base:Int) in (r: data[base], g: data[base + 1], b: data[base + 2]) } } /// var PNG.Palette.serialized : [Swift.UInt8] { get } /// Encodes this image palette as the contents of a [`(Chunk).PLTE`] chunk. /// ## (palette-parsing-and-serialization) public var serialized:[UInt8] { .init(unsafeUninitializedCapacity: 3 * self.entries.count) { for (i, c):(Int, (r:UInt8, g:UInt8, b:UInt8)) in zip(stride(from: $0.startIndex, to: $0.endIndex, by: 3), self.entries) { $0[i ] = c.r $0[i + 1] = c.g $0[i + 2] = c.b } $1 = $0.count } } } extension PNG { /// struct PNG.Transparency /// A transparency descriptor. /// /// This type models the information stored in a [`(Chunk).tRNS`] chunk. /// This information either used to populate the `key` field in /// an image color [`Format`], or augment its `palette` field, when appropriate. /// /// The value of this descriptor is stored in the [`(PNG.Transparency).case`] /// property, after validation. /// # [Parsing and serialization](transparency-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct Transparency { /// enum PNG.Transparency.Case /// A transparency case. public enum Case { /// case PNG.Transparency.Case.palette(alpha:) /// A transparency descriptor for an indexed image. /// - alpha : [Swift.UInt8] /// An array of alpha samples, where each sample augments an /// RGB triple in an image [`Palette`]. This array can contain no /// more elements than entries in the image palette, but it can /// contain fewer. /// /// It is acceptable (though pointless) for the `alpha` array to be /// empty. case palette(alpha:[UInt8]) /// case PNG.Transparency.Case.rgb(key:) /// A transparency descriptor for an RGB or BGR image. /// - key : (r:Swift.UInt16, g:Swift.UInt16, b:Swift.UInt16) /// A chroma key used to display transparency. Pixels /// matching this key will be displayed as transparent, if possible. /// /// Note that the chroma key components are unscaled samples. If /// the image color depth is less than `16`, only the least-significant /// bits of each sample are inhabited. case rgb(key:(r:UInt16, g:UInt16, b:UInt16)) /// case PNG.Transparency.Case.v(key:) /// A transparency descriptor for a grayscale image. /// - key : Swift.UInt16 /// A chroma key used to display transparency. Pixels /// matching this key will be displayed as transparent, if possible. /// /// Note that the chroma key is an unscaled sample. If /// the image color depth is less than `16`, only the least-significant /// bits are inhabited. case v(key:UInt16) } /// let PNG.Transparency.case : Case /// The value of this transparency descriptor. public let `case`:Case } } extension PNG.Transparency { /// init PNG.Transparency.init(case:pixel:palette:) /// Creates a transparency descriptor. /// /// This initializer validates the transparency information against the /// given pixel format and image palette. Some `pixel` formats imply /// that `palette` must be `nil`. This initializer does not check this /// assumption, as it is expected to have been verified by /// [`Palette.init(entries:pixel:)`]. /// - case : Case /// A transparency descriptor value. /// /// If this parameter is a [`(Case).v(key:)`] or [`(Case).rgb(key:)`] case, /// the samples in its chroma key payload must fall within the /// range determined by the image color depth. Passing an enumeration /// case with an invalid chroma key sample will result in a precondition /// failure. /// - pixel : Format.Pixel /// The pixel format of the image this transparency descriptor is to be /// used for. Passing a mismatched enumeration `case` will result in a /// precondition failure. /// /// Transparency descriptors are not allowed for grayscale-alpha or RGBA /// images, so setting `pixel` to one of those pixel formats will always /// result in a precondition failure. /// - palette : PNG.Palette? /// The palette of the image this transparency descriptor is to be /// used for. /// /// If `case` is a [`(Case).palette(alpha:)`] case, this palette must /// not be `nil`, and must contain at least as many entries as the /// number of alpha samples in the [`(Case).palette(alpha:)`] payload. /// Otherwise, this initializer will suffer a precondition failure. /// /// If `case` is a [`(Case).v(key:)`] or [`(Case).rgb(key:)`] case, /// this parameter is ignored. public init(case:Case, pixel:PNG.Format.Pixel, palette:PNG.Palette?) { switch pixel { case .v1, .v2, .v4, .v8, .v16: guard case .v(key: let v) = `case` else { fatalError("expected transparency of case `v` for pixel format `\(pixel)`") } let max:UInt16 = .max >> (UInt16.bitWidth - pixel.depth) guard v <= max else { PNG.ParsingError.invalidTransparencySample(v, max: max).fatal } case .rgb8, .rgb16: guard case .rgb(key: let (r, g, b)) = `case` else { fatalError("expected transparency of case `rgb` for pixel format `\(pixel)`") } let max:UInt16 = .max >> (UInt16.bitWidth - pixel.depth) guard r <= max, g <= max, b <= max else { PNG.ParsingError.invalidTransparencySample(Swift.max(r, g, b), max: max).fatal } case .indexed1, .indexed2, .indexed4, .indexed8: guard let palette:PNG.Palette = palette else { PNG.DecodingError.required(chunk: .PLTE, before: .tRNS).fatal } guard case .palette(alpha: let alpha) = `case` else { fatalError("expected transparency of case `palette` for pixel format `\(pixel)`") } guard alpha.count <= palette.entries.count else { PNG.ParsingError.invalidTransparencyCount(alpha.count, max: palette.entries.count).fatal } case .va8, .va16, .rgba8, .rgba16: PNG.ParsingError.unexpectedTransparency(pixel: pixel).fatal } self.case = `case` } /// init PNG.Transparency.init(parsing:pixel:palette:) /// throws /// Creates a transparency descriptor by parsing the given chunk data, /// interpreting and validating it according to the given `pixel` format and /// image `palette`. /// /// Some `pixel` formats imply that `palette` must be `nil`. /// This initializer does not check this assumption, as it is expected /// to have been verified by [`Palette.init(parsing:pixel:)`]. /// - data : [Swift.UInt8] /// The contents of a [`(Chunk).tRNS`] chunk to parse. /// - pixel : Format.Pixel /// The pixel format specifying how the chunk data is to be interpreted /// and validated against. /// - palette : Palette? /// The image palette the chunk data is to be validated against, if /// applicable. /// ## (transparency-parsing-and-serialization) public init(parsing data:[UInt8], pixel:PNG.Format.Pixel, palette:PNG.Palette?) throws { switch pixel { case .v1, .v2, .v4, .v8, .v16: guard data.count == 2 else { throw PNG.ParsingError.invalidTransparencyChunkLength(data.count, expected: 2) } let max:UInt16 = .max >> (UInt16.bitWidth - pixel.depth) let v:UInt16 = data.load(bigEndian: UInt16.self, as: UInt16.self, at: 0) guard v <= max else { throw PNG.ParsingError.invalidTransparencySample(v, max: max) } self.case = .v(key: v) case .rgb8, .rgb16: guard data.count == 6 else { throw PNG.ParsingError.invalidTransparencyChunkLength(data.count, expected: 6) } let max:UInt16 = .max >> (UInt16.bitWidth - pixel.depth) let r:UInt16 = data.load(bigEndian: UInt16.self, as: UInt16.self, at: 0), g:UInt16 = data.load(bigEndian: UInt16.self, as: UInt16.self, at: 2), b:UInt16 = data.load(bigEndian: UInt16.self, as: UInt16.self, at: 4) guard r <= max, g <= max, b <= max else { throw PNG.ParsingError.invalidTransparencySample(Swift.max(r, g, b), max: max) } self.case = .rgb(key: (r, g, b)) case .indexed1, .indexed2, .indexed4, .indexed8: guard let palette:PNG.Palette = palette else { throw PNG.DecodingError.required(chunk: .PLTE, before: .tRNS) } guard data.count <= palette.entries.count else { throw PNG.ParsingError.invalidTransparencyCount(data.count, max: palette.entries.count) } self.case = .palette(alpha: data) case .va8, .va16, .rgba8, .rgba16: throw PNG.ParsingError.unexpectedTransparency(pixel: pixel) } } /// var PNG.Transparency.serialized : [Swift.UInt8] { get } /// Encodes this transparency descriptor as the contents of a /// [`(Chunk).tRNS`] chunk. /// ## (transparency-parsing-and-serialization) public var serialized:[UInt8] { switch self.case { case .palette(alpha: let alpha): return .init(unsafeUninitializedCapacity: alpha.count) { $0.baseAddress?.assign(from: alpha, count: $0.count) $1 = $0.count } case .rgb(key: let c): return .init(unsafeUninitializedCapacity: 6) { $0.store(c.r, asBigEndian: UInt16.self, at: 0) $0.store(c.g, asBigEndian: UInt16.self, at: 2) $0.store(c.b, asBigEndian: UInt16.self, at: 4) $1 = $0.count } case .v(key: let v): return .init(unsafeUninitializedCapacity: 2) { $0.store(v, asBigEndian: UInt16.self, at: 0) $1 = $0.count } } } } extension PNG { /// struct PNG.Background /// A background descriptor. /// /// This type models the information stored in a [`(Chunk).bKGD`] chunk. /// This information is used to populate the `fill` field in /// an image color [`Format`]. /// /// The value of this descriptor is stored in the [`(PNG.Background).case`] /// property, after validation. /// # [Parsing and serialization](background-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct Background { /// enum PNG.Background.Case /// A background case. public enum Case { /// case PNG.Background.Case.palette(index:) /// A background descriptor for an indexed image. /// - index : Swift.Int /// The index of the palette entry to be used as a background color. /// /// This index must be within the index range of the image palette. case palette(index:Int) /// case PNG.Background.Case.rgb(_:) /// A background descriptor for an RGB, BGR, RGBA, or BGRA image. /// - _ : (r:Swift.UInt16, g:Swift.UInt16, b:Swift.UInt16) /// A background color. /// /// Note that the background components are unscaled samples. If /// the image color depth is less than `16`, only the least-significant /// bits of each sample are inhabited. case rgb((r:UInt16, g:UInt16, b:UInt16)) /// case PNG.Background.Case.v(_:) /// A background descriptor for a grayscale or grayscale-alpha image. /// - _ : Swift.UInt16 /// A background color. /// /// Note that the background value is an unscaled sample. If /// the image color depth is less than `16`, only the least-significant /// bits are inhabited. case v(UInt16) } /// let PNG.Background.case : Case /// The value of this background descriptor. public let `case`:Case } } extension PNG.Background { /// init PNG.Background.init(case:pixel:palette:) /// Creates a background descriptor. /// /// This initializer validates the background information against the /// given pixel format and image palette. Some `pixel` formats imply /// that `palette` must be `nil`. This initializer does not check this /// assumption, as it is expected to have been verified by /// [`Palette.init(entries:pixel:)`]. /// - case : Case /// A background descriptor value. /// /// If this parameter is a [`(Case).v(_:)`] or [`(Case).rgb(_:)`] case, /// the samples in its background color payload must fall within the /// range determined by the image color depth. Passing an enumeration /// case with an invalid background sample will result in a precondition /// failure. /// - pixel : Format.Pixel /// The pixel format of the image this background descriptor is to be /// used for. Passing a mismatched enumeration `case` will result in a /// precondition failure. /// - palette : PNG.Palette? /// The palette of the image this background descriptor is to be /// used for. /// /// If `case` is a [`(Case).palette(index:)`] case, this palette must /// not be `nil`, and the number of entries in it must be at least `1` /// greater than the value of the [`(Case).palette(index:)`] payload. /// If the index payload is out of range, this function will suffer a /// precondition failure. /// /// If `case` is a [`(Case).v(_:)`] or [`(Case).rgb(_:)`] case, /// this parameter is ignored. public init(case:Case, pixel:PNG.Format.Pixel, palette:PNG.Palette?) { switch pixel { case .v1, .v2, .v4, .v8, .v16, .va8, .va16: guard case .v(let v) = `case` else { fatalError("expected background of case `v` for pixel format `\(pixel)`") } let max:UInt16 = .max >> (UInt16.bitWidth - pixel.depth) guard v <= max else { PNG.ParsingError.invalidBackgroundSample(v, max: max).fatal } case .rgb8, .rgb16, .rgba8, .rgba16: guard case .rgb(let (r, g, b)) = `case` else { fatalError("expected background of case `v` for pixel format `\(pixel)`") } let max:UInt16 = .max >> (UInt16.bitWidth - pixel.depth) guard r <= max, g <= max, b <= max else { PNG.ParsingError.invalidBackgroundSample(Swift.max(r, g, b), max: max).fatal } case .indexed1, .indexed2, .indexed4, .indexed8: guard let palette:PNG.Palette = palette else { PNG.DecodingError.required(chunk: .PLTE, before: .bKGD).fatal } guard case .palette(index: let index) = `case` else { fatalError("expected background of case `palette` for pixel format `\(pixel)`") } guard index < palette.entries.count else { PNG.ParsingError.invalidBackgroundIndex(index, max: palette.entries.count - 1).fatal } } self.case = `case` } /// init PNG.Background.init(parsing:pixel:palette:) /// throws /// Creates a background descriptor by parsing the given chunk data, /// interpreting and validating it according to the given `pixel` format and /// image `palette`. /// /// Some `pixel` formats imply that `palette` must be `nil`. This /// initializer does not check this assumption, as it is expected to have /// been verified by [`Palette.init(parsing:pixel:)`]. /// - data : [Swift.UInt8] /// The contents of a [`(Chunk).bKGD`] chunk to parse. /// - pixel : Format.Pixel /// The pixel format specifying how the chunk data is to be interpreted /// and validated against. /// - palette : Palette? /// The image palette the chunk data is to be validated against, if /// applicable. /// ## (background-parsing-and-serialization) public init(parsing data:[UInt8], pixel:PNG.Format.Pixel, palette:PNG.Palette?) throws { switch pixel { case .v1, .v2, .v4, .v8, .v16, .va8, .va16: guard data.count == 2 else { throw PNG.ParsingError.invalidBackgroundChunkLength(data.count, expected: 2) } let max:UInt16 = .max >> (UInt16.bitWidth - pixel.depth) let v:UInt16 = data.load(bigEndian: UInt16.self, as: UInt16.self, at: 0) guard v <= max else { throw PNG.ParsingError.invalidBackgroundSample(v, max: max) } self.case = .v(v) case .rgb8, .rgb16, .rgba8, .rgba16: guard data.count == 6 else { throw PNG.ParsingError.invalidBackgroundChunkLength(data.count, expected: 6) } let max:UInt16 = .max >> (UInt16.bitWidth - pixel.depth) let r:UInt16 = data.load(bigEndian: UInt16.self, as: UInt16.self, at: 0), g:UInt16 = data.load(bigEndian: UInt16.self, as: UInt16.self, at: 2), b:UInt16 = data.load(bigEndian: UInt16.self, as: UInt16.self, at: 4) guard r <= max, g <= max, b <= max else { throw PNG.ParsingError.invalidBackgroundSample(Swift.max(r, g, b), max: max) } self.case = .rgb((r, g, b)) case .indexed1, .indexed2, .indexed4, .indexed8: guard let palette:PNG.Palette = palette else { throw PNG.DecodingError.required(chunk: .PLTE, before: .bKGD) } guard data.count == 1 else { throw PNG.ParsingError.invalidBackgroundChunkLength(data.count, expected: 1) } let index:Int = .init(data[0]) guard index < palette.entries.count else { throw PNG.ParsingError.invalidBackgroundIndex(index, max: palette.entries.count - 1) } self.case = .palette(index: index) } } /// var PNG.Background.serialized : [Swift.UInt8] { get } /// Encodes this background descriptor as the contents of a /// [`(Chunk).bKGD`] chunk. /// ## (background-parsing-and-serialization) public var serialized:[UInt8] { switch self.case { case .palette(index: let i): return [.init(i)] case .rgb(let c): return .init(unsafeUninitializedCapacity: 6) { $0.store(c.r, asBigEndian: UInt16.self, at: 0) $0.store(c.g, asBigEndian: UInt16.self, at: 2) $0.store(c.b, asBigEndian: UInt16.self, at: 4) $1 = $0.count } case .v(let v): return .init(unsafeUninitializedCapacity: 2) { $0.store(v, asBigEndian: UInt16.self, at: 0) $1 = $0.count } } } } extension PNG { /// struct PNG.Histogram /// A palette frequency histogram. /// /// This type models the information stored in a [`(Chunk).hIST`] chunk. /// # [Parsing and serialization](histogram-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct Histogram { /// let PNG.Histogram.frequencies : [Swift.UInt16] /// The frequency values of this histogram. /// /// The *i*th frequency value corresponds to the *i*th entry in the /// image palette. public let frequencies:[UInt16] } } extension PNG.Histogram { /// init PNG.Histogram.init(frequencies:palette:) /// Creates a palette histogram. /// /// This initializer validates the background information against the /// given image palette. /// - frequencies : [Swift.UInt16] /// The frequency of each palette entry in the image. The *i*th frequency /// value corresponds to the *i*th palette entry. This array must have the /// the exact same number of elements as entries in the image palette. /// Passing an array of the wrong length will result in a precondition /// failure. /// - palette : PNG.Palette /// The image palette this histogram provides frequency information for. public init(frequencies:[UInt16], palette:PNG.Palette) { guard frequencies.count == palette.entries.count else { fatalError("number of histogram entries (\(frequencies.count)) must match number of palette entries (\(palette.entries.count))") } self.frequencies = frequencies } /// init PNG.Histogram.init(parsing:palette:) /// throws /// Creates a palette histogram by parsing the given chunk data, /// validating it according to the given image `palette`. /// - data : [Swift.UInt8] /// The contents of a [`(Chunk).hIST`] chunk to parse. /// - palette : Palette /// The image palette the chunk data is to be validated against. /// ## (histogram-parsing-and-serialization) public init(parsing data:[UInt8], palette:PNG.Palette) throws { guard data.count == 2 * palette.entries.count else { throw PNG.ParsingError.invalidHistogramChunkLength(data.count, expected: 2 * palette.entries.count) } self.frequencies = (0 ..< data.count >> 1).map { data.load(bigEndian: UInt16.self, as: UInt16.self, at: $0 << 1) } } /// var PNG.Histogram.serialized : [Swift.UInt8] { get } /// Encodes this histogram as the contents of a /// [`(Chunk).hIST`] chunk. /// ## (histogram-parsing-and-serialization) public var serialized:[UInt8] { .init(unsafeUninitializedCapacity: 2 * self.frequencies.count) { for (i, frequency):(Int, UInt16) in self.frequencies.enumerated() { $0.store(frequency, asBigEndian: UInt16.self, at: i << 1) } $1 = 2 * self.frequencies.count } } } extension PNG { /// struct PNG.Gamma /// A gamma descriptor. /// /// This type models the information stored in a [`(Chunk).gAMA`] chunk. /// # [Parsing and serialization](gamma-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct Gamma { /// let PNG.Gamma.value : Percentmille /// The gamma value of an image, expressed as a fraction. public let value:Percentmille /// init PNG.Gamma.init(value:) /// Creates a gamma descriptor with the given value. /// - value : Percentmille /// A rational gamma value. public init(value:Percentmille) { self.value = value } } } extension PNG.Gamma { /// init PNG.Gamma.init(parsing:) /// throws /// Creates a gamma descriptor by parsing the given chunk data. /// - data : [Swift.UInt8] /// The contents of a [`(Chunk).gAMA`] chunk to parse. /// ## (gamma-parsing-and-serialization) public init(parsing data:[UInt8]) throws { guard data.count == 4 else { throw PNG.ParsingError.invalidGammaChunkLength(data.count) } self.value = .init(data.load(bigEndian: UInt32.self, as: Int.self, at: 0)) } /// var PNG.Gamma.serialized : [Swift.UInt8] { get } /// Encodes this gamma descriptor as the contents of a /// [`(Chunk).gAMA`] chunk. /// ## (gamma-parsing-and-serialization) public var serialized:[UInt8] { .init(unsafeUninitializedCapacity: MemoryLayout<UInt32>.size) { $0.store(self.value.points, asBigEndian: UInt32.self, at: 0) $1 = $0.count } } } extension PNG { /// struct PNG.Chromaticity /// A chromaticity descriptor. /// /// This type models the information stored in a [`(Chunk).cHRM`] chunk. /// # [Parsing and serialization](chromaticity-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct Chromaticity { /// let PNG.Chromaticity.w : (x:Percentmille, y:Percentmille) /// The white point of an image, expressed as a pair of fractions. /// ## () /// let PNG.Chromaticity.r : (x:Percentmille, y:Percentmille) /// The chromaticity of the red component of an image, /// expressed as a pair of fractions. /// ## () /// let PNG.Chromaticity.g : (x:Percentmille, y:Percentmille) /// The chromaticity of the green component of an image, /// expressed as a pair of fractions. /// ## () /// let PNG.Chromaticity.b : (x:Percentmille, y:Percentmille) /// The chromaticity of the blue component of an image, /// expressed as a pair of fractions. /// ## () public let w:(x:Percentmille, y:Percentmille), r:(x:Percentmille, y:Percentmille), g:(x:Percentmille, y:Percentmille), b:(x:Percentmille, y:Percentmille) /// init PNG.Chromaticity.init(w:r:g:b:) /// Creates a chromaticity descriptor with the given values. /// - w : (x:Percentmille, y:Percentmille) /// The white point, expressed as a pair of fractions. /// - r : (x:Percentmille, y:Percentmille) /// The red chromaticity, expressed as a pair of fractions. /// - g : (x:Percentmille, y:Percentmille) /// The green chromaticity, expressed as a pair of fractions. /// - b : (x:Percentmille, y:Percentmille) /// The blue chromaticity, expressed as a pair of fractions. public init( w:(x:Percentmille, y:Percentmille), r:(x:Percentmille, y:Percentmille), g:(x:Percentmille, y:Percentmille), b:(x:Percentmille, y:Percentmille)) { self.w = w self.r = r self.g = g self.b = b } } } extension PNG.Chromaticity { /// init PNG.Chromaticity.init(parsing:) /// throws /// Creates a chromaticity descriptor by parsing the given chunk data. /// - data : [Swift.UInt8] /// The contents of a [`(Chunk).cHRM`] chunk to parse. /// ## (chromaticity-parsing-and-serialization) public init(parsing data:[UInt8]) throws { guard data.count == 32 else { throw PNG.ParsingError.invalidChromaticityChunkLength(data.count) } self.w.x = .init(data.load(bigEndian: UInt32.self, as: Int.self, at: 0)) self.w.y = .init(data.load(bigEndian: UInt32.self, as: Int.self, at: 4)) self.r.x = .init(data.load(bigEndian: UInt32.self, as: Int.self, at: 8)) self.r.y = .init(data.load(bigEndian: UInt32.self, as: Int.self, at: 12)) self.g.x = .init(data.load(bigEndian: UInt32.self, as: Int.self, at: 16)) self.g.y = .init(data.load(bigEndian: UInt32.self, as: Int.self, at: 20)) self.b.x = .init(data.load(bigEndian: UInt32.self, as: Int.self, at: 24)) self.b.y = .init(data.load(bigEndian: UInt32.self, as: Int.self, at: 28)) } /// var PNG.Chromaticity.serialized : [Swift.UInt8] { get } /// Encodes this chromaticity descriptor as the contents of a /// [`(Chunk).cHRM`] chunk. /// ## (chromaticity-parsing-and-serialization) public var serialized:[UInt8] { .init(unsafeUninitializedCapacity: 32) { $0.store(self.w.x.points, asBigEndian: UInt32.self, at: 0) $0.store(self.w.y.points, asBigEndian: UInt32.self, at: 4) $0.store(self.r.x.points, asBigEndian: UInt32.self, at: 8) $0.store(self.r.y.points, asBigEndian: UInt32.self, at: 12) $0.store(self.g.x.points, asBigEndian: UInt32.self, at: 16) $0.store(self.g.y.points, asBigEndian: UInt32.self, at: 20) $0.store(self.b.x.points, asBigEndian: UInt32.self, at: 24) $0.store(self.b.y.points, asBigEndian: UInt32.self, at: 28) $1 = $0.count } } } extension PNG { /// enum PNG.ColorRendering /// A color rendering mode. /// /// This type models the information stored in an [`(Chunk).sRGB`] chunk. /// It is not recommended for the same image to include both a `ColorRendering` /// mode and a [`ColorProfile`]. /// # [Parsing and serialization](colorrendering-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public enum ColorRendering { /// case PNG.ColorRendering.perceptual /// The perceptual rendering mode. /// ## () case perceptual /// case PNG.ColorRendering.relative /// The relative colorimetric rendering mode. /// ## () case relative /// case PNG.ColorRendering.saturation /// The saturation rendering mode. /// ## () case saturation /// case PNG.ColorRendering.absolute /// The absolute colorimetric rendering mode. /// ## () case absolute } } extension PNG.ColorRendering { /// init PNG.ColorRendering.init(parsing:) /// throws /// Creates a color rendering mode by parsing the given chunk data. /// - data : [Swift.UInt8] /// The contents of an [`(Chunk).sRGB`] chunk to parse. /// ## (colorrendering-parsing-and-serialization) public init(parsing data:[UInt8]) throws { guard data.count == 1 else { throw PNG.ParsingError.invalidColorRenderingChunkLength(data.count) } switch data[0] { case 0: self = .perceptual case 1: self = .relative case 2: self = .saturation case 3: self = .absolute case let code: throw PNG.ParsingError.invalidColorRenderingCode(code) } } /// var PNG.ColorRendering.serialized : [Swift.UInt8] { get } /// Encodes this color rendering mode as the contents of an /// [`(Chunk).sRGB`] chunk. /// ## (colorrendering-parsing-and-serialization) public var serialized:[UInt8] { switch self { case .perceptual: return [0] case .relative: return [1] case .saturation: return [2] case .absolute: return [3] } } } extension PNG { /// struct PNG.SignificantBits /// A color precision descriptor. /// /// This type models the information stored in an [`(Chunk).sBIT`] chunk. /// # [Parsing and serialization](significantbits-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct SignificantBits { /// enum PNG.SignificantBits.Case /// A color precision case. public enum Case { /// case PNG.SignificantBits.Case.v(_:) /// A color precision descriptor for a grayscale image. /// - _ : Swift.Int /// The number of significant bits in each grayscale sample. /// /// This value must be greater than zero, and can be no greater /// than the color depth of the image color format. /// ## () case v(Int) /// case PNG.SignificantBits.Case.va(_:) /// A color precision descriptor for a grayscale-alpha image. /// - _ : (v:Swift.Int, a:Swift.Int) /// The number of significant bits in each grayscale and alpha /// sample, respectively. /// /// Both precision values must be greater than zero, and neither /// can be greater than the color depth of the image color format. /// ## () case va((v:Int, a:Int)) /// case PNG.SignificantBits.Case.rgb(_:) /// A color precision descriptor for an RGB, BGR, or indexed image. /// - _ : (r:Swift.Int, g:Swift.Int, b:Swift.Int) /// The number of significant bits in each red, green, and blue /// sample, respectively. If the image uses an indexed color format, /// the precision values refer to the precision of the palette /// entries, not the indices. The [`(Chunk).sBIT`] chunk type is /// not capable of specifying the precision of the alpha component /// of the palette entries. If the image palette was augmented with /// alpha samples from a [`Transparency`] descriptor, the precision /// of those samples is left undefined. /// /// The meaning of a color precision descriptor is /// poorly-defined for BGR images. It is strongly recommended that /// iphone-optimized images use [`(PNG).SignificantBits`] only if all /// samples have the same precision. /// /// Each precision value must be greater than zero, and none of them /// can be greater than the color depth of the image color format. /// ## () case rgb((r:Int, g:Int, b:Int)) /// case PNG.SignificantBits.Case.rgba(_:) /// A color precision descriptor for an RGBA or BGRA image. /// - _ : (r:Swift.Int, g:Swift.Int, b:Swift.Int, a:Swift.Int) /// The number of significant bits in each red, green, blue, and alpha /// sample, respectively. /// /// The meaning of a color precision descriptor is /// poorly-defined for BGRA images. It is strongly recommended that /// iphone-optimized images use [`(PNG).SignificantBits`] only if all /// samples have the same precision. /// /// Each precision value must be greater than zero, and none of them /// can be greater than the color depth of the image color format. /// ## () case rgba((r:Int, g:Int, b:Int, a:Int)) } /// let PNG.SignificantBits.case : Case /// The value of this color precision descriptor. let `case`:Case } } extension PNG.SignificantBits { /// init PNG.SignificantBits.init(case:pixel:) /// Creates a color precision descriptor. /// /// This initializer validates the precision information against the /// given pixel format. /// - case : Case /// A color precision case. Each precision value in the enumeration /// payload must be greater than zero, and none of them /// can be greater than the color depth of the image color format. /// - pixel : Format.Pixel /// The pixel format of the image this color precision descriptor is to be /// used for. Passing a mismatched enumeration `case` will result in a /// precondition failure. public init(case:Case, pixel:PNG.Format.Pixel) { let precision:[Int] switch `case` { case .v (let v ): precision = [v] case .va (let (v, a)): precision = [v, a] case .rgb (let (r, g, b )): precision = [r, g, b] case .rgba(let (r, g, b, a)): precision = [r, g, b, a] } let max:Int switch pixel { case .indexed1, .indexed2, .indexed4, .indexed8: max = 8 default: max = pixel.depth } for v:Int in precision where !(1 ... max ~= v) { PNG.ParsingError.invalidSignificantBitsPrecision(v, max: max).fatal } self.case = `case` } /// init PNG.SignificantBits.init(parsing:pixel:) /// throws /// Creates a color precision descriptor by parsing the given chunk data, /// interpreting and validating it according to the given `pixel` format. /// - data : [Swift.UInt8] /// The contents of an [`(Chunk).sBIT`] chunk to parse. /// - pixel : Format.Pixel /// The pixel format specifying how the chunk data is to be interpreted /// and validated against. /// ## (significantbits-parsing-and-serialization) public init(parsing data:[UInt8], pixel:PNG.Format.Pixel) throws { let arity:Int = (pixel.hasColor ? 3 : 1) + (pixel.hasAlpha ? 1 : 0) guard data.count == arity else { throw PNG.ParsingError.invalidSignificantBitsChunkLength(data.count, expected: arity) } let precision:[Int] switch pixel { case .v1, .v2, .v4, .v8, .v16: let v:Int = .init(data[0]) self.case = .v(v) precision = [v] case .rgb8, .rgb16, .indexed1, .indexed2, .indexed4, .indexed8: let r:Int = .init(data[0]), g:Int = .init(data[1]), b:Int = .init(data[2]) self.case = .rgb((r, g, b)) precision = [r, g, b] case .va8, .va16: let v:Int = .init(data[0]), a:Int = .init(data[1]) self.case = .va((v, a)) precision = [v, a] case .rgba8, .rgba16: let r:Int = .init(data[0]), g:Int = .init(data[1]), b:Int = .init(data[2]), a:Int = .init(data[3]) self.case = .rgba((r, g, b, a)) precision = [r, g, b, a] } let max:Int switch pixel { case .indexed1, .indexed2, .indexed4, .indexed8: max = 8 default: max = pixel.depth } for v:Int in precision where !(1 ... max ~= v) { throw PNG.ParsingError.invalidSignificantBitsPrecision(v, max: max) } } /// var PNG.SignificantBits.serialized : [Swift.UInt8] { get } /// Encodes this color precision descriptor as the contents of an /// [`(Chunk).sBIT`] chunk. /// ## (significantbits-parsing-and-serialization) public var serialized:[UInt8] { switch self.case { case .v( let c): return [c].map(UInt8.init(_:)) case .va( let c): return [c.v, c.a].map(UInt8.init(_:)) case .rgb( let c): return [c.r, c.g, c.b].map(UInt8.init(_:)) case .rgba(let c): return [c.r, c.g, c.b, c.a].map(UInt8.init(_:)) } } } extension PNG { /// struct PNG.ColorProfile /// An embedded color profile. /// /// This type models the information stored in an [`(Chunk).iCCP`] chunk. /// # [Parsing and serialization](colorprofile-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct ColorProfile { /// let PNG.ColorProfile.name : Swift.String /// The name of this profile. public let name:String /// let PNG.ColorProfile.profile : [Swift.UInt8] /// The uncompressed [ICC](http://www.color.org/index.xalter) color /// profile data. public let profile:[UInt8] /// init PNG.ColorProfile.init(name:profile:) /// Creates a color profile. /// - name : Swift.String /// The profile name. /// /// This string must contain only unicode scalars /// in the ranges `"\u{20}" ... "\u{7d}"` or `"\u{a1}" ... "\u{ff}"`. /// Leading, trailing, and consecutive spaces are not allowed. /// Passing an invalid string will result in a precondition failure. /// - profile : [Swift.UInt8] /// The uncompressed [ICC](http://www.color.org/index.xalter) color /// profile data. The data will be compressed when this color profile /// is [`serialized`] into an [`(Chunk).iCCP`] chunk. public init(name:String, profile:[UInt8]) { guard PNG.Text.validate(name: name.unicodeScalars) else { PNG.ParsingError.invalidColorProfileName(name).fatal } self.name = name self.profile = profile } } } extension PNG.ColorProfile { /// init PNG.ColorProfile.init(parsing:) /// throws /// Creates a color profile by parsing the given chunk data. /// - data : [Swift.UInt8] /// The contents of an [`(Chunk).iCCP`] chunk to parse. /// ## (colorprofile-parsing-and-serialization) public init(parsing data:[UInt8]) throws { // ┌ ╶ ╶ ╶ ╶ ╶ ╶┬───┬───┬ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶┐ // │ name │ 0 │ M │ profile │ // └ ╶ ╶ ╶ ╶ ╶ ╶┴───┴───┴ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶┘ // k k+1 k+2 let k:Int (self.name, k) = try PNG.Text.name(parsing: data[...]) { PNG.ParsingError.invalidColorProfileName($0) } // assert existence of method byte guard k + 1 < data.endIndex else { throw PNG.ParsingError.invalidColorProfileChunkLength(data.count, min: k + 2) } guard data[k + 1] == 0 else { throw PNG.ParsingError.invalidColorProfileCompressionMethodCode(data[k + 1]) } var inflator:LZ77.Inflator = .init() guard try inflator.push(.init(data.dropFirst(k + 2))) == nil else { throw PNG.ParsingError.incompleteColorProfileCompressedDatastream } self.profile = inflator.pull() } /// var PNG.ColorProfile.serialized : [Swift.UInt8] { get } /// Encodes this color profile as the contents of an /// [`(Chunk).iCCP`] chunk. /// ## (colorprofile-parsing-and-serialization) public var serialized:[UInt8] { var data:[UInt8] = [] data.reserveCapacity(2 + self.name.count) data.append(contentsOf: self.name.unicodeScalars.map{ .init($0.value) }) data.append(0) data.append(0) // compression method var deflator:LZ77.Deflator = .init(level: 13, exponent: 15, hint: 4096) deflator.push(self.profile, last: true) while true { let segment:[UInt8] = deflator.pull() guard !segment.isEmpty else { break } data.append(contentsOf: segment) } return data } } extension PNG { /// struct PNG.PhysicalDimensions /// A physical dimensions descriptor. /// /// This type models the information stored in a [`(Chunk).pHYs`] chunk. /// # [Parsing and serialization](physicaldimensions-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct PhysicalDimensions { /// enum PNG.PhysicalDimensions.Unit /// A unit of measurement. public enum Unit { /// case PNG.PhysicalDimensions.Unit.meter /// The meter. /// /// For conversion purposes, one inch is assumed to equal exactly /// `254 / 10000` meters. case meter } /// let PNG.PhysicalDimensions.density : (x:Swift.Int, y:Swift.Int, unit:Unit?) /// The number of pixels in each dimension per the given `unit` of /// measurement. /// /// If `unit` is `nil`, the pixel density is unknown, /// and the `x` and `y` values specify the pixel aspect ratio only. public let density:(x:Int, y:Int, unit:Unit?) /// init PNG.PhysicalDimensions.init(density:) /// Creates a physical dimensions descriptor. /// - density : (x:Swift.Int, y:Swift.Int, unit:Unit?) /// The number of pixels in each dimension per the given `unit` of /// measurement. /// /// If `unit` is `nil`, the pixel density is unknown, /// and the `x` and `y` values specify the pixel aspect ratio only. public init(density:(x:Int, y:Int, unit:Unit?)) { self.density = density } } } extension PNG.PhysicalDimensions { /// init PNG.PhysicalDimensions.init(parsing:) /// throws /// Creates a physical dimensions descriptor by parsing the given chunk data. /// - data : [Swift.UInt8] /// The contents of a [`(Chunk).pHYs`] chunk to parse. /// ## (physicaldimensions-parsing-and-serialization) public init(parsing data:[UInt8]) throws { guard data.count == 9 else { throw PNG.ParsingError.invalidPhysicalDimensionsChunkLength(data.count) } self.density.x = data.load(bigEndian: UInt32.self, as: Int.self, at: 0) self.density.y = data.load(bigEndian: UInt32.self, as: Int.self, at: 4) switch data[8] { case 0: self.density.unit = nil case 1: self.density.unit = .meter case let code: throw PNG.ParsingError.invalidPhysicalDimensionsDensityUnitCode(code) } } /// var PNG.PhysicalDimensions.serialized : [Swift.UInt8] { get } /// Encodes this physical dimensions descriptor as the contents of a /// [`(Chunk).pHYs`] chunk. /// ## (physicaldimensions-parsing-and-serialization) public var serialized:[UInt8] { .init(unsafeUninitializedCapacity: 9) { $0.store(self.density.x, asBigEndian: UInt32.self, at: 0) $0.store(self.density.y, asBigEndian: UInt32.self, at: 4) switch self.density.unit { case nil: $0[8] = 0 case .meter?: $0[8] = 1 } $1 = $0.count } } } extension PNG { /// struct PNG.SuggestedPalette /// A suggested image palette. /// /// This type models the information stored in an [`(Chunk).sPLT`] chunk. /// It should not be confused with the suggested palette stored in the /// color [`Format`] of an RGB, BGR, RGBA, or BGRA image. /// # [Parsing and serialization](suggestedpalette-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct SuggestedPalette { /// enum PNG.SuggestedPalette.Entries /// A variant array of palette colors and frequencies. public enum Entries { /// case PNG.SuggestedPalette.Entries.rgba8(_:) /// A suggested palette with an 8-bit color depth. /// - _ : [(color:(r:Swift.UInt8, g:Swift.UInt8, b:Swift.UInt8, a:Swift.UInt8), frequency:Swift.UInt16)] /// An array of 8-bit palette colors and frequencies. /// ## () case rgba8( [(color:(r:UInt8, g:UInt8, b:UInt8, a:UInt8), frequency:UInt16)]) /// case PNG.SuggestedPalette.Entries.rgba16(_:) /// A suggested palette with a 16-bit color depth. /// - _ : [(color:(r:Swift.UInt16, g:Swift.UInt16, b:Swift.UInt16, a:Swift.UInt16), frequency:Swift.UInt16)] /// An array of 16-bit palette colors and frequencies. /// ## () case rgba16([(color:(r:UInt16, g:UInt16, b:UInt16, a:UInt16), frequency:UInt16)]) } /// let PNG.SuggestedPalette.name : Swift.String /// The name of this suggested palette. public let name:String /// let PNG.SuggestedPalette.entries : Entries /// The colors in this suggested palette, and their frequencies. public var entries:Entries /// init PNG.SuggestedPalette.init(name:entries:) /// Creates a suggested palette. /// - name : Swift.String /// The palette name. /// /// This string must contain only unicode scalars /// in the ranges `"\u{20}" ... "\u{7d}"` or `"\u{a1}" ... "\u{ff}"`. /// Leading, trailing, and consecutive spaces are not allowed. /// Passing an invalid string will result in a precondition failure. /// - entries : Entries /// A variant array of palette colors and frequencies. public init(name:String, entries:Entries) { guard PNG.Text.validate(name: name.unicodeScalars) else { PNG.ParsingError.invalidSuggestedPaletteName(name).fatal } self.name = name self.entries = entries guard self.descendingFrequency else { PNG.ParsingError.invalidSuggestedPaletteFrequency.fatal } } } } extension PNG.SuggestedPalette { /// init PNG.SuggestedPalette.init(parsing:) /// throws /// Creates a suggested palette by parsing the given chunk data. /// - data : [Swift.UInt8] /// The contents of an [`(Chunk).sPLT`] chunk to parse. /// ## (suggestedpalette-parsing-and-serialization) public init(parsing data:[UInt8]) throws { let k:Int (self.name, k) = try PNG.Text.name(parsing: data[...]) { PNG.ParsingError.invalidSuggestedPaletteName($0) } guard k + 1 < data.count else { throw PNG.ParsingError.invalidSuggestedPaletteChunkLength(data.count, min: k + 2) } let bytes:Int = data.count - k - 2 switch data[k + 1] { case 8: guard bytes % 6 == 0 else { throw PNG.ParsingError.invalidSuggestedPaletteDataLength(bytes, stride: 6) } self.entries = .rgba8(stride(from: k + 2, to: data.endIndex, by: 6).map { (base:Int) -> (color:(r:UInt8, g:UInt8, b:UInt8, a:UInt8), frequency:UInt16) in ( ( data[base ], data[base + 1], data[base + 2], data[base + 3] ), data.load(bigEndian: UInt16.self, as: UInt16.self, at: base + 4) ) }) case 16: guard bytes % 10 == 0 else { throw PNG.ParsingError.invalidSuggestedPaletteDataLength(bytes, stride: 10) } self.entries = .rgba16(stride(from: k + 2, to: data.endIndex, by: 10).map { (base:Int) -> (color:(r:UInt16, g:UInt16, b:UInt16, a:UInt16), frequency:UInt16) in ( ( data.load(bigEndian: UInt16.self, as: UInt16.self, at: base ), data.load(bigEndian: UInt16.self, as: UInt16.self, at: base + 2), data.load(bigEndian: UInt16.self, as: UInt16.self, at: base + 4), data.load(bigEndian: UInt16.self, as: UInt16.self, at: base + 6) ), data.load(bigEndian: UInt16.self, as: UInt16.self, at: base + 8) ) }) case let code: throw PNG.ParsingError.invalidSuggestedPaletteDepthCode(code) } guard self.descendingFrequency else { throw PNG.ParsingError.invalidSuggestedPaletteFrequency } } private var descendingFrequency:Bool { var previous:UInt16 = .max switch self.entries { case .rgba8(let entries): for current:UInt16 in entries.lazy.map(\.frequency) { guard current <= previous else { return false } previous = current } case .rgba16(let entries): for current:UInt16 in entries.lazy.map(\.frequency) { guard current <= previous else { return false } previous = current } } return true } /// var PNG.SuggestedPalette.serialized : [Swift.UInt8] { get } /// Encodes this suggested palette as the contents of an /// [`(Chunk).sPLT`] chunk. /// ## (suggestedpalette-parsing-and-serialization) public var serialized:[UInt8] { let head:Int = self.name.unicodeScalars.count let tail:Int switch self.entries { case .rgba8( let entries): tail = 6 * entries.count case .rgba16(let entries): tail = 10 * entries.count } return .init(unsafeUninitializedCapacity: head + 2 + tail) { for (i, u):(Int, Unicode.Scalar) in zip($0.indices, self.name.unicodeScalars) { $0[i] = .init(u.value) } $0[head] = 0 switch self.entries { case .rgba8( let entries): $0[head + 1] = 8 for (base, (color, frequency)): ( Int, ((r:UInt8, g:UInt8, b:UInt8, a:UInt8), UInt16) ) in zip(stride(from: head + 2, to: $0.endIndex, by: 6), entries) { $0[base ] = color.r $0[base + 1] = color.g $0[base + 2] = color.b $0[base + 3] = color.a $0.store(frequency, asBigEndian: UInt16.self, at: base + 4) } case .rgba16(let entries): $0[head + 1] = 16 for (base, (color, frequency)): ( Int, ((r:UInt16, g:UInt16, b:UInt16, a:UInt16), UInt16) ) in zip(stride(from: head + 2, to: $0.endIndex, by: 10), entries) { $0.store(color.r, asBigEndian: UInt16.self, at: base ) $0.store(color.g, asBigEndian: UInt16.self, at: base + 2) $0.store(color.b, asBigEndian: UInt16.self, at: base + 4) $0.store(color.a, asBigEndian: UInt16.self, at: base + 6) $0.store(frequency, asBigEndian: UInt16.self, at: base + 8) } } $1 = $0.count } } } extension PNG { /// struct PNG.TimeModified /// An image modification time. /// /// This type models the information stored in a [`(Chunk).tIME`] chunk. /// This type is time-zone agnostic, and so all time values are assumed /// to be in universal time (UTC). /// # [Parsing and serialization](timemodified-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct TimeModified { /// let PNG.TimeModified.year : Swift.Int /// The complete [gregorian](https://en.wikipedia.org/wiki/Gregorian_calendar) /// year. /// ## () public let year:Int, /// let PNG.TimeModified.month : Swift.Int /// The calendar month, expressed as a 1-indexed integer. /// ## () month:Int, /// let PNG.TimeModified.day : Swift.Int /// The calendar day, expressed as a 1-indexed integer. /// ## () day:Int, /// let PNG.TimeModified.hour : Swift.Int /// The hour, in 24-hour time, expressed as a 0-indexed integer. /// ## () hour:Int, /// let PNG.TimeModified.minute : Swift.Int /// The minute, expressed as a 0-indexed integer. /// ## () minute:Int, /// let PNG.TimeModified.second : Swift.Int /// The second, expressed as a 0-indexed integer. /// ## () second:Int /// init PNG.TimeModified.init(year:month:day:hour:minute:second:) /// Creates an image modification time. /// /// The time is time-zone agnostic, and so all time parameters are /// assumed to be in universal time (UTC). Passing out-of-range /// time parameters will result in a precondition failure. /// - year : Swift.Int /// The complete [gregorian](https://en.wikipedia.org/wiki/Gregorian_calendar) /// year. It must be in the range `0 ..< 1 << 16`. It can be /// reasonably expected to have four decimal digits. /// - month : Swift.Int /// The calendar month, expressed as a 1-indexed integer. It must /// be in the range `1 ... 12`. /// - day : Swift.Int /// The calendar day, expressed as a 1-indexed integer. /// It must be in the range `1 ... 31`. /// - hour : Swift.Int /// The hour, in 24-hour time, expressed as a 0-indexed integer. /// It must be in the range `0 ... 23`. /// - minute : Swift.Int /// The minute, expressed as a 0-indexed integer. /// It must be in the range `0 ... 59`. /// - second : Swift.Int /// The second, expressed as a 0-indexed integer. /// It must be in the range `0 ... 60`, where the value `60` is /// used to represent leap seconds. public init(year:Int, month:Int, day:Int, hour:Int, minute:Int, second:Int) { guard 0 ..< 1 << 16 ~= year, 1 ... 12 ~= month, 1 ... 31 ~= day, 0 ... 23 ~= hour, 0 ... 59 ~= minute, 0 ... 60 ~= second else { PNG.ParsingError.invalidTimeModifiedTime( year: year, month: month, day: day, hour: hour, minute: minute, second: second).fatal } self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second } } } extension PNG.TimeModified { /// init PNG.TimeModified.init(parsing:) /// throws /// Creates an image modification time by parsing the given chunk data. /// - data : [Swift.UInt8] /// The contents of a [`(Chunk).tIME`] chunk to parse. /// ## (timemodified-parsing-and-serialization) public init(parsing data:[UInt8]) throws { guard data.count == 7 else { throw PNG.ParsingError.invalidTimeModifiedChunkLength(data.count) } self.year = data.load(bigEndian: UInt16.self, as: Int.self, at: 0) self.month = .init(data[2]) self.day = .init(data[3]) self.hour = .init(data[4]) self.minute = .init(data[5]) self.second = .init(data[6]) guard 0 ..< 1 << 16 ~= self.year, 1 ... 12 ~= self.month, 1 ... 31 ~= self.day, 0 ... 23 ~= self.hour, 0 ... 59 ~= self.minute, 0 ... 60 ~= self.second else { throw PNG.ParsingError.invalidTimeModifiedTime( year: self.year, month: self.month, day: self.day, hour: self.hour, minute: self.minute, second: self.second) } } /// var PNG.TimeModified.serialized : [Swift.UInt8] { get } /// Encodes this image modification time as the contents of a /// [`(Chunk).tIME`] chunk. /// ## (timemodified-parsing-and-serialization) public var serialized:[UInt8] { .init(unsafeUninitializedCapacity: 7) { $0.store(self.year, asBigEndian: UInt16.self, at: 0) $0[2] = .init(self.month) $0[3] = .init(self.day) $0[4] = .init(self.hour) $0[5] = .init(self.minute) $0[6] = .init(self.second) $1 = $0.count } } } extension PNG { /// struct PNG.Text /// A text comment. /// /// This type models the information stored in a [`(Chunk).tEXt`], /// [`(Chunk).zTXt`], or [`(Chunk).iTXt`] chunk. /// # [Parsing and serialization](text-parsing-and-serialization) /// # [See also](parsed-chunk-types) /// ## (parsed-chunk-types) public struct Text { /// let PNG.Text.compressed : Swift.Bool /// Indicates if the text is (or is to be) stored in compressed or /// uncompressed form within a PNG file. /// /// This flag is `true` if the original text chunk was a /// [`(Chunk).zTXt`] chunk, and `false` if it was a [`(Chunk).tEXt`] /// chunk. If the original chunk was an [`(Chunk).iTXt`] chunk, /// this flag can be either `true` or `false`. public let compressed:Bool /// let PNG.Text.keyword : (english:Swift.String, localized:Swift.String) /// A keyword tag, in english, and possibly a non-english language. /// /// If the text is in english, the `localized` keyword is the empty /// string `""`. public let keyword:(english:String, localized:String), /// let PNG.Text.language : [Swift.String] /// An array representing an [rfc-1766](https://www.ietf.org/rfc/rfc1766.txt) /// language tag, where each element is a language subtag. /// /// If this array is empty, then the language is unspecified. language:[String] /// let PNG.Text.content : Swift.String /// The text content. public let content:String /// init PNG.Text.init(compressed:keyword:language:content:) /// Creates a text comment. /// - compressed : Swift.Bool /// Indicates if the text is to be stored in compressed or /// uncompressed form within a PNG file. /// - keyword : (english:Swift.String, localized:Swift.String) /// A keyword tag, in english, and possibly a non-english language. /// /// The english keyword must contain only unicode scalars /// in the ranges `"\u{20}" ... "\u{7d}"` or `"\u{a1}" ... "\u{ff}"`. /// Leading, trailing, and consecutive spaces are not allowed. /// There are no restrictions on the `localized` keyword, other than /// that it must not contain any null characters. /// /// Passing invalid keyword strings will result in a precondition failure. /// /// If the text is in english, the `localized` keyword should be /// set to the empty string `""`. /// - language : [Swift.String] /// An array representing an [rfc-1766](https://www.ietf.org/rfc/rfc1766.txt) /// language tag, where each element is a language subtag. /// /// Each subtag must be a 1–8 character string containing alphabetical /// ASCII characters only. Passing an invalid language tag array /// will result in a precondition failure. /// /// If this array is empty, then the language is unspecified. /// - content : Swift.String /// The text content. There are no restrictions on it. It is allowed /// (but not recommended) to contain null characters. public init(compressed:Bool, keyword:(english:String, localized:String), language:[String], content:String) { guard Self.validate(name: keyword.english.unicodeScalars) else { PNG.ParsingError.invalidTextEnglishKeyword(keyword.english).fatal } guard (keyword.localized.unicodeScalars.allSatisfy{ $0 != "\u{0}" }) else { fatalError("localized keyword must not contain any null characters") } for tag:String in language { guard Self.validate(language: tag.unicodeScalars) else { PNG.ParsingError.invalidTextLanguageTag(tag).fatal } } self.compressed = compressed self.keyword = keyword self.language = language self.content = content } } } extension PNG.Text { /// init PNG.Text.init(parsing:unicode:) /// throws /// Creates a text comment by parsing the given chunk data, interpreting /// it either as a unicode text chunk, or a latin-1 text chunk. /// - data : [Swift.UInt8] /// The contents of a [`(Chunk).tEXt`], [`(Chunk).zTXt`], or [`(Chunk).iTXt`] /// chunk to parse. /// - unicode : Swift.Bool /// Specifies if the given chunk `data` should be interpreted as a /// unicode chunk, or a latin-1 chunk. It should be set to `true` if the /// original text chunk was an [`(Chunk).iTXt`] chunk, and `false` /// otherwise. The default value is `true`. /// /// If this flag is set to `false`, the text is assumed to be in english, /// and the [`language`] tag will be set to `["en"]`. /// ## (text-parsing-and-serialization) public init(parsing data:[UInt8], unicode:Bool = true) throws { // ┌ ╶ ╶ ╶ ╶ ╶ ╶┬───┬───┬───┬ ╶ ╶ ╶ ╶ ╶ ╶┬───┬ ╶ ╶ ╶ ╶ ╶ ╶┬───┬ ╶ ╶ ╶ ╶ ╶ ╶┐ // │ keyword │ 0 │ C │ M │ language │ 0 │ keyword │ 0 │ text │ // └ ╶ ╶ ╶ ╶ ╶ ╶┴───┴───┴───┴ ╶ ╶ ╶ ╶ ╶ ╶┴───┴ ╶ ╶ ╶ ╶ ╶ ╶┴───┴ ╶ ╶ ╶ ╶ ╶ ╶┘ // k k+1 k+2 k+3 l l+1 m m+1 let k:Int (self.keyword.english, k) = try Self.name(parsing: data[...]) { PNG.ParsingError.invalidTextEnglishKeyword($0) } // parse iTXt chunk if unicode { // assert existence of compression flag and method bytes guard k + 2 < data.endIndex else { throw PNG.ParsingError.invalidTextChunkLength(data.count, min: k + 3) } let l:Int // language can be empty, in which case it is unknown (self.language, l) = try Self.language(parsing: data[(k + 3)...]) { PNG.ParsingError.invalidTextLanguageTag($0) } guard let m:Int = data[(l + 1)...].firstIndex(of: 0) else { throw PNG.ParsingError.invalidTextLocalizedKeyword } let localized:String = .init(decoding: data[l + 1 ..< m], as: Unicode.UTF8.self) self.keyword.localized = self.keyword.english == localized ? "" : localized let uncompressed:ArraySlice<UInt8> switch data[k + 1] { case 0: uncompressed = data[(m + 1)...] self.compressed = false case 1: guard data[k + 2] == 0 else { throw PNG.ParsingError.invalidTextCompressionMethodCode(data[k + 2]) } var inflator:LZ77.Inflator = .init() guard try inflator.push(.init(data[(m + 1)...])) == nil else { throw PNG.ParsingError.incompleteTextCompressedDatastream } uncompressed = inflator.pull()[...] self.compressed = true case let code: throw PNG.ParsingError.invalidTextCompressionCode(code) } self.content = .init(decoding: uncompressed, as: Unicode.UTF8.self) } // parse tEXt/zTXt chunk else { self.keyword.localized = "" self.language = ["en"] // if the next byte is also null, the chunk uses compression let uncompressed:ArraySlice<UInt8> if k + 1 < data.endIndex, data[k + 1] == 0 { var inflator:LZ77.Inflator = .init() guard try inflator.push(.init(data[(k + 2)...])) == nil else { throw PNG.ParsingError.incompleteTextCompressedDatastream } uncompressed = inflator.pull()[...] self.compressed = true } else { uncompressed = data[(k + 1)...] self.compressed = false } self.content = .init(uncompressed.map{ Character.init(Unicode.Scalar.init($0)) }) } } static func name<E>(parsing data:ArraySlice<UInt8>, else error:(String?) -> E) throws -> (name:String, offset:Int) where E:Swift.Error { guard let offset:Int = data.firstIndex(of: 0) else { throw error(nil) } let scalars:LazyMapSequence<ArraySlice<UInt8>, Unicode.Scalar> = data[..<offset].lazy.map(Unicode.Scalar.init(_:)) let name:String = .init(scalars.map(Character.init(_:))) guard Self.validate(name: scalars) else { throw error(name) } return (name, offset) } static func validate<C>(name scalars:C) -> Bool where C:Collection, C.Element == Unicode.Scalar { // `count` in range `1 ... 80` guard var previous:Unicode.Scalar = scalars.first, scalars.count <= 80 else { return false } for scalar:Unicode.Scalar in scalars { guard "\u{20}" ... "\u{7d}" ~= scalar || "\u{a1}" ... "\u{ff}" ~= scalar, // no multiple spaces, also checks for no leading spaces (previous, scalar) != (" ", " ") else { return false } previous = scalar } // no trailing spaces return previous != " " } private static func language<E>(parsing data:ArraySlice<UInt8>, else error:(String?) -> E) throws -> (language:[String], offset:Int) where E:Swift.Error { guard let offset:Int = data.firstIndex(of: 0) else { throw error(nil) } // check for empty language tag guard offset > data.startIndex else { return ([], offset) } // split on '-' let language:[String] = try data[..<offset].split(separator: 0x2d, omittingEmptySubsequences: false).map { let scalars:LazyMapSequence<ArraySlice<UInt8>, Unicode.Scalar> = $0.lazy.map(Unicode.Scalar.init(_:)) let tag:String = .init(scalars.map(Character.init(_:))) guard Self.validate(language: scalars) else { throw error(tag) } // canonical lowercase return tag.lowercased() } return (language, offset) } private static func validate<C>(language scalars:C) -> Bool where C:Collection, C.Element == Unicode.Scalar { guard 1 ... 8 ~= scalars.count else { return false } return scalars.allSatisfy{ "a" ... "z" ~= $0 || "A" ... "Z" ~= $0 } } /// var PNG.Text.serialized : [Swift.UInt8] { get } /// Encodes this text comment as the contents of a /// [`(Chunk).iTXt`] chunk. /// /// This property *always* emits a unicode [`(Chunk).iTXt`] /// chunk, regardless of the type of the original chunk, if it was parsed /// from raw chunk data. It is the opinion of the library that the /// latin-1 chunk types [`(Chunk).tEXt`] and [`(Chunk).zTXt`] are /// deprecated. /// ## (text-parsing-and-serialization) public var serialized:[UInt8] { let size:Int = 5 + self.keyword.english.count + self.keyword.localized.count + self.language.reduce(0){ $0 + $1.count + 1 } + self.content.utf8.count var data:[UInt8] = [] data.reserveCapacity(size) data.append(contentsOf: self.keyword.english.unicodeScalars.map{ .init($0.value) }) data.append(0) data.append(self.compressed ? 1 : 0) data.append(0) // compression method data.append(contentsOf: self.language.map { $0.unicodeScalars.map{ .init($0.value) } }.joined(separator: [0x2d])) data.append(0) if self.keyword.localized != self.keyword.english { data.append(contentsOf: self.keyword.localized.utf8) } data.append(0) if self.compressed { var deflator:LZ77.Deflator = .init(level: 13, exponent: 15, hint: 4096) deflator.push(.init(self.content.utf8), last: true) while true { let segment:[UInt8] = deflator.pull() guard !segment.isEmpty else { break } data.append(contentsOf: segment) } } else { data.append(contentsOf: self.content.utf8) } return data } }
gpl-3.0
ca811645104426f3b1d76b381033d5c9
38.383158
144
0.505693
4.220349
false
false
false
false
AndreMuis/Algorithms
DepthFirstSearch.playground/Contents.swift
1
1168
//: Playground - noun: a place where people can play import UIKit // // B - C - D // | | | // A E - F - G // class Vertex { let name : String var parent : Vertex? var neighbors : [Vertex] init(name: String) { self.name = name self.parent = nil self.neighbors = [Vertex]() } } var aVertex = Vertex(name: "A") var bVertex = Vertex(name: "B") var cVertex = Vertex(name: "C") var dVertex = Vertex(name: "D") var eVertex = Vertex(name: "E") var fVertex = Vertex(name: "F") var gVertex = Vertex(name: "G") aVertex.neighbors = [bVertex] bVertex.neighbors = [aVertex, cVertex] cVertex.neighbors = [bVertex, dVertex, eVertex] dVertex.neighbors = [cVertex, eVertex, fVertex] eVertex.neighbors = [cVertex, dVertex, fVertex] fVertex.neighbors = [dVertex, eVertex, gVertex] gVertex.neighbors = [fVertex] func depthFirstSearch(vertex : Vertex) { for neighbor in vertex.neighbors { if neighbor.parent == nil { neighbor.parent = vertex depthFirstSearch(neighbor) } } print(vertex.name) } depthFirstSearch(cVertex)
mit
c5efba5e9536809490eb0faa6761749b
15.222222
52
0.601884
3.356322
false
false
false
false
iluuu1994/2048
2048/Classes/GameScene.swift
1
2964
// // GameScene.swift // 2048 // // Created by Ilija Tovilo on 30/07/14. // Copyright (c) 2014 Ilija Tovilo. All rights reserved. // import Foundation @objc(TFGameScene) class GameScene: CCScene { // MARK: Instanc Variables private var _gameBoardMargin: CGFloat = 20.0 lazy private var _backgroundNode: CCNodeColor = { CCNodeColor(color: CCColor(red: 0.98, green: 0.97, blue: 0.94)) }() lazy private var _gameBoard: GameBoard = { let gb = GameBoard(gridSize: 4) let size = self.contentSize.width - self._gameBoardMargin*2 gb.view.contentSize = CGSize(width: size, height: size) gb.view.positionType = CCPositionType( xUnit: .Normalized, yUnit: .Normalized, corner: gb.view.positionType.corner ) gb.view.anchorPoint = CGPoint(x: 0.5, y: 0.5) gb.view.position = CGPoint(x: 0.5, y: 0.5) gb.delegate = self return gb }() lazy var _scoreLabel: CCLabelTTF = { let l = CCLabelTTF(string: "Score: 0", fontName: "ClearSans-Bold", fontSize: 40) l.position = CGPoint(x: 0.5, y: 0.1) l.positionType = CCPositionType( xUnit: .Normalized, yUnit: .Normalized, corner: .TopLeft ) l.fontColor = CCColor(red: 0.47, green: 0.43, blue: 0.4) return l }() lazy var _restartButton: CCButton = { let l = Button(title: "RESTART", fontName: "ClearSans-Bold", fontSize: 28) l.position = CGPoint(x: 0.5, y: 0.1) l.positionType = CCPositionType( xUnit: .Normalized, yUnit: .Normalized, corner: .BottomLeft ) l.setTarget(self, selector: "restartGame") return l }() // MARK: Init class func scene() -> GameScene { return GameScene() } override init() { super.init() initSubnodes() } func initSubnodes() { addChild(_backgroundNode) addChild(_gameBoard.view) addChild(_scoreLabel) addChild(_restartButton) } // MARK: Target Actions func restartGame() { CCDirector.sharedDirector().replaceScene(GameScene.scene()) } } extension GameScene: GameBoardDelegate { func playerScoreIncreased(by: Int, totalScore: Int) { _scoreLabel.string = "Score: \(totalScore)" } func playerWonWithScore(score: Int) { scheduleBlock({ (timer) in CCDirector.sharedDirector().replaceScene(YouWinScene.scene(gameScene: self, score: score)) }, delay: kYouWonDelay) } func gameOverWithScore(score: Int) { scheduleBlock({ (timer) in CCDirector.sharedDirector().replaceScene(GameOverScene(score: score)) }, delay: kGameOverDelay) } }
bsd-3-clause
b83b48813ee7b3e6798d8b61772044b9
24.118644
102
0.561741
4.038147
false
false
false
false
rockgarden/swift_language
Playground/Swift Language Guide.playground/Pages/Type Casting.xcplaygroundpage/Contents.swift
1
8100
//: [Previous](@previous) import UIKit /*: # Type Casting 类型转换 Type casting is a way to check the type of an instance, or to treat that instance as a different superclass or subclass from somewhere else in its own class hierarchy. 类型转换是一种检查实例类型的方法,或者将该实例视为来自其自身类层次结构中的其他地方的不同超类或子类。 Type casting in Swift is implemented with the is and as operators. These two operators provide a simple and expressive way to check the type of a value or cast a value to a different type. Swift中的类型转换使用is和as运算符实现。 这两个操作符提供了一种简单和表达方式来检查值的类型或将值转换为不同类型。 You can also use type casting to check whether a type conforms to a protocol, as described in Checking for Protocol Conformance. 您还可以使用类型转换来检查类型是否符合协议,如检查协议一致性中所述。 */ /*: # Defining a Class Hierarchy for Type Casting You can use type casting with a hierarchy of classes and subclasses to check the type of a particular class instance and to cast that instance to another class within the same hierarchy. */ class MediaItem { var name: String init(name: String) { self.name = name } } class Movie: MediaItem { var director: String init(name: String, director: String) { self.director = director super.init(name: name) } } class Song: MediaItem { var artist: String init(name: String, artist: String) { self.artist = artist super.init(name: name) } } let library = [ Movie(name: "Casablanca", director: "Michael Curtiz"), Song(name: "Blue Suede Shoes", artist: "Elvis Presley"), Movie(name: "Citizen Kane", director: "Orson Welles"), Song(name: "The One And Only", artist: "Chesney Hawkes"), Song(name: "Never Gonna Give You Up", artist: "Rick Astley") ] /*: The type of the library array is inferred by initializing it with the contents of an array literal. Swift’s type checker is able to deduce that Movie and Song have a common superclass of MediaItem, and so it infers a type of [MediaItem] for the library array. The items stored in library are still Movie and Song instances behind the scenes. However, if you iterate over the contents of this array, the items you receive back are typed as MediaItem, and not as Movie or Song. In order to work with them as their native type, you need to check their type, or downcast them to a different type, as described below. */ /*: # Checking Type 类型判断 Use the type check operator (is) to check whether an instance is of a certain subclass type. 通过 is 来判断一个实例是否属于指定类或者其子类.类似以 OC 中的 isKindOfClass. */ do { var movieCount = 0 var songCount = 0 for item in library { if item is Movie { movieCount += 1 } else if item is Song { songCount += 1 } } print("Media library contains \(movieCount) movies and \(songCount) songs") } /* # Downcasting 向下转型 A constant or variable of a certain class type may actually refer to an instance of a subclass behind the scenes. Where you believe this is the case, you can try to downcast to the subclass type with a type cast operator (as? or as!). Because downcasting can fail, the type cast operator comes in two different forms. The conditional form, as?, returns an optional value of the type you are trying to downcast to. The forced form, as!, attempts the downcast and force-unwraps the result as a single compound action. Use the conditional form of the type cast operator (as?) when you are not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. This enables you to check for a successful downcast. Use the forced form of the type cast operator (as!) only when you are sure that the downcast will always succeed. This form of the operator will trigger a runtime error if you try to downcast to an incorrect class type. 可以用类型转换操作符 as 尝试将某个实例转换到它的子类型. 转换没有真的改变实例或它的值. 转型的实例保持不变,只是简单地把它作为它被转换成的类来使用。 */ do { for item in library { if let movie = item as? Movie { print("Movie: '\(movie.name)', dir. \(movie.director)") } else if let song = item as? Song { print("Song: '\(song.name)', by \(song.artist)") } } } /*: - NOTE: Casting does not actually modify the instance or change its values. The underlying instance remains the same; it is simply treated and accessed as an instance of the type to which it has been cast. 转型不会实际修改实例或更改其值。 底层实例保持不变; 它被简单地处理和访问作为它已经被转换的类型的实例。 */ /* # Type Casting for Any and AnyObject Swift provides two special type aliases for working with non-specific types: - AnyObject can represent an instance of any class type. 可以代表任何class类型的实例. - Any can represent an instance of any type at all, including function types. 可以表示任何类型, 包括方法类型function types. */ //: ## AnyObject let someObjects: [AnyObject] = [ Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"), Movie(name: "Moon", director: "Duncan Jones"), Movie(name: "Alien", director: "Ridley Scott") ] for movie in someObjects as! [Movie] { ("Movie: '\(movie.name)', dir. \(movie.director)") } //: ## Any var things = [Any]() things.append(0) things.append(0.0) things.append(42) things.append(3.14159) things.append("hello") things.append((3.0, 5.0)) things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) things.append({ (name: String) -> String in "Hello, \(name)" }) /*: You can use the is and as operators in a switch statement’s cases to discover the specific type of a constant or variablen that is known only to be of type Any or AnyObject. */ for thing in things { switch thing { case 0 as Int: ("zero as an Int") case 0 as Double: ("zero as a Double") case let someInt as Int: ("an integer value of \(someInt)") case let someDouble as Double where someDouble > 0: ("a positive double value of \(someDouble)") case is Double: // Here it's valid to use is, since the only thing being queried is the type. Other case statements store values in vars, so they use as. ("some other double value that I don't want to print") case let someString as String: ("a string value of \"\(someString)\"") case let (x, y) as (Double, Double): ("an (x, y) point at \(x), \(y)") case let movie as Movie: ("a movie called '\(movie.name)', dir. \(movie.director)") case let stringConverter as (String) -> String: (stringConverter("Michael")) default: ("something else") } } /*: - NOTE: The Any type represents values of any type, including optional types. Swift gives you a warning if you use an optional value where a value of type Any is expected. If you really do need to use an optional value as an Any value, you can use the as operator to explicitly cast the optional to Any, as shown below. */ let optionalNumber: Int? = 3 things.append(optionalNumber)//警告 things.append(optionalNumber as Any)//没有警告 //: # Example do { let a1: UInt8 = 10 let b1: UInt16 = 100 print("\(UInt16(a1) + b1)") let sa = 3 let pi = 3.1415 let add = Double(sa) + pi print(add) /*: 显式类型如整型,在使用时要显式转换 Explicit conversion must be made when working with explicit types. For any other case, use the Int class */ let thousand: UInt16 = 1_000 let one: UInt8 = 1 let thousandAndOne = thousand + UInt16(one) } //: [Next](@next)
mit
49d250c601853cbc0d860d77d9940d27
36.675127
312
0.695769
3.804203
false
false
false
false
lanjing99/iOSByTutorials
iOS 8 by tutorials/Chapter 11 - Extensions - Action/Quick-Bit-Starter/Quick Bit/ViewController.swift
1
6660
/* * Copyright (c) 2014 Razeware LLC * * 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 import QuartzCore import BitlyKit class ViewController: UIViewController { enum ActionButtonState { case Shorten case Copy } let bitlyService: BitlyService @IBOutlet var longUrlTextField: UITextField! @IBOutlet var domainSegmentedControl: UISegmentedControl! @IBOutlet var actionButton: UIButton! @IBOutlet var copiedLabel: UILabel! var actionButtonState: ActionButtonState = .Shorten var shortenedUrl: BitlyShortenedUrlModel! required init(coder aDecoder: NSCoder) { bitlyService = BitlyService(accessToken: "19febc3999253ad2227019c933a224bb0d6f8480") super.init(coder: aDecoder)! NSNotificationCenter.defaultCenter().addObserver(self, selector: "respondToUIApplicationDidBecomeActiveNotification", name: UIApplicationDidBecomeActiveNotification, object: nil) } override func viewDidLoad() { super.viewDidLoad() actionButton.layer.borderColor = UIColor.whiteColor().CGColor actionButton.layer.borderWidth = 1.0 / UIScreen.mainScreen().scale actionButton.layer.cornerRadius = 15.0 copiedLabel.hidden = true setupLongUrlTextFieldAppearance() } override func viewWillAppear(animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: animated) super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: animated) super.viewWillDisappear(animated) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animateAlongsideTransition(nil) { _ in self.setupLongUrlTextFieldAppearance() } } func respondToUIApplicationDidBecomeActiveNotification() { resetView() askToUseClipboardIfUrlPresent(); } func askToUseClipboardIfUrlPresent() { if let pasteBoardUrl = UIPasteboard.generalPasteboard().URL { if pasteBoardUrl.host != "bit.ly" || pasteBoardUrl.host != "bitly.com" || pasteBoardUrl.host != "j.mp" { // don't ask to shorten urls we know are already shortened let alertController = UIAlertController(title: "Shorten clipboard item?", message: pasteBoardUrl.absoluteString, preferredStyle: .Alert) let yesAction = UIAlertAction(title: "Yes", style: .Default) { action in self.addPasteboardUrlToLongUrlTextField() self.dismissViewControllerAnimated(true, completion: nil) } let noAction = UIAlertAction(title: "No", style: .Cancel) { action in self.dismissViewControllerAnimated(true, completion: nil) } alertController.addAction(yesAction) alertController.addAction(noAction) presentViewController(alertController, animated: true, completion: nil) } } } func addPasteboardUrlToLongUrlTextField() { if let url = UIPasteboard.generalPasteboard().URL { longUrlTextField.text = url.absoluteString } } @IBAction func longUrlTextFieldChanged(sender: UIButton) { actionButtonState = .Shorten actionButton.setTitle("Shorten", forState: .Normal) copiedLabel.hidden = true } @IBAction func actionButtonPressed(sender: UIButton) { longUrlTextField.resignFirstResponder() switch (actionButtonState) { case .Shorten: shortenUrl() case .Copy: UIPasteboard.generalPasteboard().URL = shortenedUrl.shortUrl copiedLabel.hidden = false } } func shortenUrl() { var domain: String switch (domainSegmentedControl.selectedSegmentIndex) { case 1: domain = "j.mp" case 2: domain = "bitly.com" default: domain = "bit.ly" } var longUrlOpt: NSURL? = NSURL(string: self.longUrlTextField.text!) if let longUrl = longUrlOpt { bitlyService.shortenUrl(longUrl, domain: domain) { shortenedUrlResult, error in if error != nil { self.presentError() } else { dispatch_async(dispatch_get_main_queue()) { self.shortenedUrl = shortenedUrlResult! self.actionButton.setTitle(self.shortenedUrl.shortUrl?.absoluteString, forState: .Normal) self.actionButtonState = .Copy BitlyHistoryService.sharedService.addItem(self.shortenedUrl) } } } } } func presentError() { let alertController = UIAlertController(title: "Unable to Shorten", message: "Check your entered URL's format and try again", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default) { action in self.dismissViewControllerAnimated(true, completion: nil) } alertController.addAction(okAction) self.presentViewController(alertController, animated: true, completion: nil) } func setupLongUrlTextFieldAppearance() { let attributedPlaceHolderString = NSAttributedString(string: "URL", attributes: [NSForegroundColorAttributeName : UIColor.whiteColor()]) longUrlTextField.attributedPlaceholder = attributedPlaceHolderString let bottomBorder = CALayer() bottomBorder.frame = CGRectMake(0.0, CGRectGetHeight(longUrlTextField.frame)-2, CGRectGetWidth(longUrlTextField.frame), 2.0); bottomBorder.backgroundColor = UIColor.whiteColor().CGColor longUrlTextField.layer.addSublayer(bottomBorder) } func resetView() { longUrlTextField?.text = "" actionButtonState = .Shorten actionButton?.setTitle("Shorten", forState: .Normal) copiedLabel?.hidden = true } }
mit
41d2857c3df73c952e559a3a2d1a7b9b
35.593407
182
0.724775
4.774194
false
false
false
false
DaftMobile/ios4beginners_2017
Class 1/Swift Basics.playground/Pages/Collections.xcplaygroundpage/Contents.swift
1
1295
import Foundation //: [Previous](@previous) //: # Arrays /// The type is Array<String>. It could be described as [String] as well var names: [String] = ["Piotr", "Marcin", "Anna"] print(names) // ["Piotr", "Marcin", "Anna"] var primes = [2, 3, 5, 7] // Inferred as Array<Int>, or [Int] print(primes) // [2, 3, 5, 7] //: ## Modyfing Arrays names.append("Krystian") print(names) // ["Piotr", "Marcin", "Anna", "Krystian"] primes.append(8) print(primes) // [2, 3, 5, 7, 8] primes.append(11) print(primes) // [2, 3, 5, 7, 8, 11] primes.remove(at: 4) print(primes) // [2, 3, 5, 7, 11] //: ### Arrays are typed //names.append(11) // You cannot do that, `names` is an Array of Strings! //primes.append(UIButton()) //: # Dictionaries // Type is inferred as [String: Int] // Dictionary with String keys and Int values var numberOfLegs = ["ant": 6, "snake": 0, "dog": 4] print(numberOfLegs) // ["ant": 6, "snake": 0, "dog": 4] //: ## Modyfing Dictionaries numberOfLegs["fish"] = 421 print(numberOfLegs) // ["ant": 6, "fish": 421, "snake": 0, "dog": 4] numberOfLegs["fish"] = 0 print(numberOfLegs) // ["ant": 6, "fish": 0, "snake": 0, "dog": 4] //: ## Accessing values of a dictionary print(numberOfLegs["ant"]) // Optional(6) print(numberOfLegs["spider"]) // nil //: [Next](@next)
apache-2.0
3eebd9e50564c39b099d0a418626f066
18.328358
75
0.612355
2.726316
false
false
false
false
Explora-codepath/explora
Explora/Credentials.swift
1
1004
// // Credentials.swift // Explora // // Created by admin on 10/18/15. // Copyright © 2015 explora-codepath. All rights reserved. // import UIKit struct Credentials { static let defaultCredentialsFile = "Credentials" static let defaultCredentials = Credentials.loadFromPropertyListNamed(defaultCredentialsFile) let parseID: String let parseKey: String let mapboxKey: String private static func loadFromPropertyListNamed(name: String) -> Credentials { // You must add a Credentials.plist file let path = NSBundle.mainBundle().pathForResource(name, ofType: "plist")! let dictionary = NSDictionary(contentsOfFile: path)! let parseID = dictionary["ParseID"] as! String let parseKey = dictionary["ParseClientKey"] as! String let mapboxKey = dictionary["MGLMapboxAccessToken"] as! String return Credentials(parseID: parseID, parseKey: parseKey, mapboxKey: mapboxKey) } }
mit
2a20c0e2e56959230ade9c682311e01a
32.466667
101
0.678963
4.497758
false
false
false
false
SwiftKit/Torch
Source/Database/UnsafeDatabase.swift
1
3628
// // UnsafeDatabase.swift // Torch // // Created by Filip Dolnik on 20.07.16. // Copyright © 2016 Brightify. All rights reserved. // /// Wrapper for Database that is crashing with fatalError instead of throwing errors. public class UnsafeDatabase { private let database: Database internal init(database: Database) { self.database = database } } // MARK: - Load extension UnsafeDatabase { public func load<T: TorchEntity>(type: T.Type, sortBy sortDescriptors: SortDescriptor<T>...) -> [T] { return load(type, sortBy: sortDescriptors) } public func load<T: TorchEntity>(type: T.Type, sortBy sortDescriptors: [SortDescriptor<T>]) -> [T] { do { return try database.load(type, sortBy: sortDescriptors) } catch { fatalError(String(error)) } } public func load<T: TorchEntity, P: PredicateConvertible where P.ParentType == T>(type: T.Type, where predicate: P, sortBy sortDescriptors: SortDescriptor<T>...) -> [T] { return load(type, where: predicate, sortBy: sortDescriptors) } public func load<T: TorchEntity, P: PredicateConvertible where P.ParentType == T>(type: T.Type, where predicate: P, sortBy sortDescriptors: [SortDescriptor<T>]) -> [T] { do { return try database.load(type, where: predicate, sortBy: sortDescriptors) } catch { fatalError(String(error)) } } } // MARK: - Save extension UnsafeDatabase { /// See `Database.save` public func save<T: TorchEntity>(entities: T...) -> UnsafeDatabase { return save(entities) } public func save<T: TorchEntity>(entities: [T]) -> UnsafeDatabase { do { try database.save(entities) } catch { fatalError(String(error)) } return self } /// See `Database.create` public func create<T: TorchEntity>(inout entity: T) -> UnsafeDatabase { do { try database.create(&entity) } catch { fatalError(String(error)) } return self } public func create<T: TorchEntity>(inout entities: [T]) -> UnsafeDatabase { do { try database.create(&entities) } catch { fatalError(String(error)) } return self } } // MARK: - Delete extension UnsafeDatabase { public func delete<T: TorchEntity>(entities: T...) -> UnsafeDatabase { delete(entities) return self } public func delete<T: TorchEntity>(entities: [T]) -> UnsafeDatabase { do { try database.delete(entities) } catch { fatalError(String(error)) } return self } public func delete<T: TorchEntity, P: PredicateConvertible where P.ParentType == T>(type: T.Type, where predicate: P) -> UnsafeDatabase { do { try database.delete(type, where: predicate) } catch { fatalError(String(error)) } return self } public func deleteAll<T: TorchEntity>(type: T.Type) -> UnsafeDatabase { do { try database.deleteAll(type) } catch { fatalError(String(error)) } return self } } // MARK: - Transaction extension UnsafeDatabase { public func rollback() -> UnsafeDatabase { database.rollback() return self } public func write(@noescape closure: () -> () = {}) -> UnsafeDatabase { do { try database.write(closure) } catch { fatalError(String(error)) } return self } }
mit
a130c6f298b3a555277d4752010590e8
25.093525
174
0.584505
4.328162
false
false
false
false
nissivm/DemoShopPayPal
DemoShop-PayPal/Objects/Auxiliar.swift
1
2586
// // Auxiliar.swift // DemoShop-PayPal // // Copyright © 2016 Nissi Vieira Miranda. All rights reserved. // import Foundation class Auxiliar { static var currentUserId = "" //-------------------------------------------------------------------------// // MARK: MBProgressHUD //-------------------------------------------------------------------------// static func showLoadingHUDWithText(labelText : String, forView view : UIView) { dispatch_async(dispatch_get_main_queue()) { let progressHud = MBProgressHUD.showHUDAddedTo(view, animated: true) progressHud.labelText = labelText } } static func hideLoadingHUDInView(view : UIView) { dispatch_async(dispatch_get_main_queue()) { MBProgressHUD.hideAllHUDsForView(view, animated: true) } } //-------------------------------------------------------------------------// // MARK: "Ok" Alert Controller //-------------------------------------------------------------------------// static func presentAlertControllerWithTitle(title : String, andMessage message : String, forViewController vc : UIViewController) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) let alertAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(alertAction) dispatch_async(dispatch_get_main_queue()) { vc.presentViewController(alert, animated: true, completion: nil) } } //-------------------------------------------------------------------------// // MARK: Format price for Pay Pal //-------------------------------------------------------------------------// static func formatPrice(price: CGFloat) -> NSDecimalNumber { let roundingBehavior = NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundUp, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) var decimal = NSDecimalNumber(float: Float(price)) decimal = decimal.decimalNumberByRoundingAccordingToBehavior(roundingBehavior) return decimal } }
mit
53799a92a566689939b77fecac469be1
33.48
91
0.470019
6.645244
false
false
false
false
wj2061/ios7ptl-swift3.0
ch19-UIDynamics/CollectionDrag/CollectionDrag/DragLayout.swift
1
2174
// // DragLayout.swift // CollectionDrag // // Created by WJ on 15/11/19. // Copyright © 2015年 wj. All rights reserved. // import UIKit class DragLayout: UICollectionViewFlowLayout { var indexPath:IndexPath? lazy var animatar: UIDynamicAnimator? = { return UIDynamicAnimator(collectionViewLayout: self) }() var behaivor:UIAttachmentBehavior? func startDraggingIndexPath(_ indexpath:IndexPath,fromPoint:CGPoint){ animatar?.removeAllBehaviors() self.indexPath = indexpath let attributes = super.layoutAttributesForItem(at: indexpath) attributes!.zIndex += 1 behaivor = UIAttachmentBehavior(item: attributes!, attachedToAnchor: fromPoint) behaivor?.length = 0 behaivor?.frequency = 10 animatar?.addBehavior(behaivor!) let dynamicItem = UIDynamicItemBehavior(items: [attributes!]) dynamicItem.resistance = 10 animatar?.addBehavior(dynamicItem) updateDragLocation(fromPoint) } func updateDragLocation(_ point:CGPoint){ behaivor?.anchorPoint = point } func stopDraging(){ if let index = indexPath{ let attributes = super.layoutAttributesForItem(at: index) updateDragLocation(attributes!.center) indexPath = nil behaivor = nil } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let existingAttributes = super.layoutAttributesForElements(in: rect) var allAttributes = [UICollectionViewLayoutAttributes]() for attribute in existingAttributes!{ if attribute.indexPath != indexPath{ allAttributes.append(attribute) } // else{ // allAttributes.appendContentsOf( [animatar!.layoutAttributesForCellAtIndexPath(indexPath!)!]) // } } // animatar!.layoutAttributesForCellAtIndexPath(indexPath!) allAttributes.append(contentsOf: animatar!.items(in: rect) as! [UICollectionViewLayoutAttributes]) return allAttributes } }
mit
afd6b12ea13ea83d8d3513434819e98a
30.463768
110
0.649931
5.15677
false
false
false
false
cozkurt/coframework
COFramework/COFramework/Swift/Components/GeoLocation/GeoModel.swift
1
2008
// // GeoModel.swift // COLibrary // // Created by Cenker Ozkurt on 07/14/16. // Copyright (c) 2015 Cenker Ozkurt. All rights reserved. // import UIKit import MapKit import CloudKit import CoreLocation // GeoModel conforms MKAnnotation protocol // To make model work with MKMapView delegates public class GeoModel: NSObject, MKAnnotation { // Following properties are reqired for MKAnnotation // for callouts public var coordinate: CLLocationCoordinate2D public var title: String? public var subtitle: String? // Custom properties used in model to store // more information public var nibName: String? public var data: AnyObject? public init(nibName: String?, coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?, data: AnyObject?) { self.nibName = nibName self.coordinate = coordinate self.title = title self.subtitle = subtitle self.data = data } } public struct ReversedGeoLocation { public let name: String // eg. Apple Inc. public let streetName: String // eg. Infinite Loop public let streetNumber: String // eg. 1 public let city: String // eg. Cupertino public let state: String // eg. CA public let zipCode: String // eg. 95014 public let country: String // eg. United States public let isoCountryCode: String // eg. US // Handle optionals as needed public init(with placemark: CLPlacemark) { self.name = placemark.name ?? "" self.streetName = placemark.thoroughfare ?? "" self.streetNumber = placemark.subThoroughfare ?? "" self.city = placemark.locality ?? "" self.state = placemark.administrativeArea ?? "" self.zipCode = placemark.postalCode ?? "" self.country = placemark.country ?? "" self.isoCountryCode = placemark.isoCountryCode ?? "" } }
gpl-3.0
67eb04dc6bdf99689d3e2b6d4821cc80
30.375
124
0.630976
4.724706
false
false
false
false
ytakzk/Hokusai
Classes/Hokusai.swift
1
20220
// // Hokusai.swift // Hokusai // // Created by Yuta Akizuki on 2015/07/07. // Copyright (c) 2015年 ytakzk. All rights reserved. // import UIKit private struct HOKConsts { let animationDuration:TimeInterval = 0.8 let hokusaiTag = 9999 } // Action Types public enum HOKAcitonType { case none, selector, closure } // Color Types public enum HOKColorScheme { case hokusai, asagi, matcha, tsubaki, inari, karasu, enshu func getColors() -> HOKColors { switch self { case .asagi: return HOKColors( backGroundColor: UIColorHex(0x0bada8), buttonColor: UIColorHex(0x08827e), cancelButtonColor: UIColorHex(0x6dcecb), fontColor: UIColorHex(0xffffff) ) case .matcha: return HOKColors( backGroundColor: UIColorHex(0x314631), buttonColor: UIColorHex(0x618c61), cancelButtonColor: UIColorHex(0x496949), fontColor: UIColorHex(0xffffff) ) case .tsubaki: return HOKColors( backGroundColor: UIColorHex(0xe5384c), buttonColor: UIColorHex(0xac2a39), cancelButtonColor: UIColorHex(0xc75764), fontColor: UIColorHex(0xffffff) ) case .inari: return HOKColors( backGroundColor: UIColorHex(0xdd4d05), buttonColor: UIColorHex(0xa63a04), cancelButtonColor: UIColorHex(0xb24312), fontColor: UIColorHex(0x231e1c) ) case .karasu: return HOKColors( backGroundColor: UIColorHex(0x180614), buttonColor: UIColorHex(0x3d303d), cancelButtonColor: UIColorHex(0x261d26), fontColor: UIColorHex(0x9b9981) ) case .enshu: return HOKColors( backGroundColor: UIColorHex(0xccccbe), buttonColor: UIColorHex(0xffffff), cancelButtonColor: UIColorHex(0xe5e5d8), fontColor: UIColorHex(0x9b9981) ) default: // Hokusai return HOKColors( backGroundColor: UIColorHex(0x00AFF0), buttonColor: UIColorHex(0x197EAD), cancelButtonColor: UIColorHex(0x1D94CA), fontColor: UIColorHex(0xffffff) ) } } fileprivate func UIColorHex(_ hex: UInt) -> UIColor { return UIColor( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hex & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } } final public class HOKColors: NSObject { var backgroundColor: UIColor var buttonColor: UIColor var cancelButtonColor: UIColor var fontColor: UIColor required public init(backGroundColor: UIColor, buttonColor: UIColor, cancelButtonColor: UIColor, fontColor: UIColor) { self.backgroundColor = backGroundColor self.buttonColor = buttonColor self.cancelButtonColor = cancelButtonColor self.fontColor = fontColor } } final public class HOKButton: UIButton { var target:AnyObject! var selector:Selector! var action:(()->Void)! var actionType = HOKAcitonType.none var isCancelButton = false // Font let kDefaultFont = "AvenirNext-DemiBold" let kFontSize:CGFloat = 16.0 func setColor(_ colors: HOKColors) { self.setTitleColor(colors.fontColor, for: UIControlState()) self.backgroundColor = (isCancelButton) ? colors.cancelButtonColor : colors.buttonColor } func setFontName(_ fontName: String?) { let name:String if let fontName = fontName , !fontName.isEmpty { name = fontName } else { name = kDefaultFont } self.titleLabel?.font = UIFont(name: name, size:kFontSize) } } final public class HOKLabel: UILabel { var isTitle = true // Font var kDefaultFont:String { return isTitle ? "AvenirNext-DemiBold" : "AvenirNext-Light" } let kFontSize:CGFloat = 16.0 func setColor(_ colors: HOKColors) { self.textColor = colors.fontColor self.backgroundColor = UIColor.clear } func setFontName(_ fontName: String?) { let name:String if let fontName = fontName , !fontName.isEmpty { name = fontName } else { name = kDefaultFont } self.font = UIFont(name: name, size:kFontSize) } } final public class HOKMenuView: UIView { var colorScheme = HOKColorScheme.hokusai public let kDamping: CGFloat = 0.7 public let kInitialSpringVelocity: CGFloat = 0.8 fileprivate var displayLink: CADisplayLink? fileprivate let shapeLayer = CAShapeLayer() fileprivate var bendableOffset = UIOffset.zero override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func layoutSubviews() { super.layoutSubviews() } func setShapeLayer(_ colors: HOKColors) { self.backgroundColor = UIColor.clear shapeLayer.fillColor = colors.backgroundColor.cgColor shapeLayer.frame = frame self.layer.insertSublayer(shapeLayer, at: 0) } func positionAnimationWillStart() { if displayLink == nil { displayLink = CADisplayLink(target: self, selector: #selector(HOKMenuView.tick(_:))) displayLink!.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode) } shapeLayer.frame = CGRect(origin: CGPoint.zero, size: frame.size) } func updatePath() { let width = shapeLayer.bounds.width let height = shapeLayer.bounds.height let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 0)) path.addQuadCurve(to: CGPoint(x: width, y: 0), controlPoint:CGPoint(x: width * 0.5, y: 0 + bendableOffset.vertical)) path.addQuadCurve(to: CGPoint(x: width, y: height + 100.0), controlPoint:CGPoint(x: width + bendableOffset.horizontal, y: height * 0.5)) path.addQuadCurve(to: CGPoint(x: 0, y: height + 100.0), controlPoint: CGPoint(x: width * 0.5, y: height + 100.0)) path.addQuadCurve(to: CGPoint(x: 0, y: 0), controlPoint: CGPoint(x: bendableOffset.horizontal, y: height * 0.5)) path.close() shapeLayer.path = path.cgPath } @objc func tick(_ displayLink: CADisplayLink) { if let presentationLayer = layer.presentation() as CALayer? { var verticalOffset = self.layer.frame.origin.y - presentationLayer.frame.origin.y // On dismissing, the offset should not be offended on the buttons. if verticalOffset > 0 { verticalOffset *= 0.2 } bendableOffset = UIOffset( horizontal: 0.0, vertical: verticalOffset ) updatePath() if verticalOffset == 0 { self.displayLink!.invalidate() self.displayLink = nil } } } } final public class Hokusai: UIViewController, UIGestureRecognizerDelegate { // Views fileprivate var menuView = HOKMenuView() fileprivate var buttons = [HOKButton]() fileprivate var labels = [HOKLabel]() fileprivate var instance:Hokusai! = nil fileprivate var kButtonWidth:CGFloat = 250 fileprivate let kButtonHeight:CGFloat = 48.0 fileprivate let kElementInterval:CGFloat = 16.0 fileprivate var kLabelWidth:CGFloat { return kButtonWidth } fileprivate let kLabelHeight:CGFloat = 30.0 fileprivate var bgColor = UIColor(white: 1.0, alpha: 0.7) // Variables users can change public var colorScheme = HOKColorScheme.hokusai public var fontName = "" public var lightFontName = "" public var colors:HOKColors! = nil public var cancelButtonTitle = "Cancel" public var cancelButtonAction : (()->Void)? public var headline: String = "" public var message:String = "" required public init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } required public init() { super.init(nibName:nil, bundle:nil) view.frame = UIScreen.main.bounds view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] view.backgroundColor = UIColor.clear menuView.frame = view.frame view.addSubview(menuView) kButtonWidth = view.frame.width * 0.8 // Gesture Recognizer for outside the menu let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Hokusai.dismissHokusai)) tapGesture.numberOfTapsRequired = 1 tapGesture.delegate = self self.view.addGestureRecognizer(tapGesture) NotificationCenter.default.addObserver(self, selector: #selector(Hokusai.onOrientationChange(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } /// Convenience initializer to allow a title and optional message convenience public init(headline: String, message: String = "") { self.init() self.headline = headline self.message = message } @objc func onOrientationChange(_ notification: Notification) { self.updateFrames() self.view.layoutIfNeeded() } func updateFrames() { kButtonWidth = view.frame.width * 0.8 var yPrevious:CGFloat = 0 for label in labels { label.frame = CGRect(x: 0.0, y: 0.0, width: kLabelWidth, height: kLabelHeight) label.sizeToFit() label.center = CGPoint(x: view.center.x, y: label.frame.size.height * 0.5 + yPrevious + kElementInterval) yPrevious = label.frame.maxY } for btn in buttons { btn.frame = CGRect(x: 0.0, y: 0.0, width: kButtonWidth, height: kButtonHeight) btn.center = CGPoint(x: view.center.x, y: kButtonHeight * 0.5 + yPrevious + kElementInterval) yPrevious = btn.frame.maxY } let labelHeights = labels.flatMap { $0.frame.height }.reduce(0, +) let buttonHeights = buttons.flatMap { $0.frame.height }.reduce(0, +) let menuHeight = CGFloat(buttons.count + labels.count + 1) * kElementInterval + labelHeights + buttonHeights menuView.frame = CGRect( x: 0, y: view.frame.height - menuHeight, width: view.frame.width, height: menuHeight ) menuView.shapeLayer.frame = CGRect(origin: CGPoint.zero, size: menuView.frame.size) menuView.updatePath() menuView.layoutIfNeeded() } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if touch.view != gestureRecognizer.view { return false } return true } // Add a button with a closure public func addButton(_ title:String, action:@escaping ()->Void) -> HOKButton { let btn = addButton(title) btn.action = action btn.actionType = HOKAcitonType.closure btn.addTarget(self, action:#selector(Hokusai.buttonTapped(_:)), for:.touchUpInside) return btn } // Add a button with a selector public func addButton(_ title:String, target:AnyObject, selector:Selector) -> HOKButton { let btn = addButton(title) btn.target = target btn.selector = selector btn.actionType = HOKAcitonType.selector btn.addTarget(self, action:#selector(Hokusai.buttonTapped(_:)), for:.touchUpInside) btn.addTarget(self, action:#selector(Hokusai.buttonDarker(_:)), for:.touchDown) btn.addTarget(self, action:#selector(Hokusai.buttonLighter(_:)), for:.touchUpOutside) return btn } // Add a cancel button public func addCancelButton(_ title:String) -> HOKButton { if let cancelButtonAction = cancelButtonAction { let btn = addButton(title, action: cancelButtonAction) btn.isCancelButton = true return btn } else { let btn = addButton(title) btn.addTarget(self, action:#selector(Hokusai.buttonTapped(_:)), for:.touchUpInside) btn.addTarget(self, action:#selector(Hokusai.buttonDarker(_:)), for:.touchDown) btn.addTarget(self, action:#selector(Hokusai.buttonLighter(_:)), for:.touchUpOutside) btn.isCancelButton = true return btn } } // Add a button just with a title fileprivate func addButton(_ title:String) -> HOKButton { let btn = HOKButton() btn.layer.masksToBounds = true btn.setTitle(title, for: UIControlState()) menuView.addSubview(btn) buttons.append(btn) return btn } // Add a multi-lined message label fileprivate func addMessageLabel(_ text: String) -> HOKLabel { let label = addLabel(text) label.isTitle = false return label } // Add a multi-lined label just with a text fileprivate func addLabel(_ text: String) -> HOKLabel { let label = HOKLabel() label.layer.masksToBounds = true label.textAlignment = .center label.text = text label.numberOfLines = 0 menuView.addSubview(label) labels.append(label) return label } // Show the menu public func show() { if let rv = UIApplication.shared.keyWindow { if rv.viewWithTag(HOKConsts().hokusaiTag) == nil { view.tag = HOKConsts().hokusaiTag.hashValue rv.addSubview(view) } } else { print("Hokusai:: You have to call show() after the controller has appeared.") return } // This is needed to retain this instance. instance = self guard let colors = self.colors == nil ? colorScheme.getColors() : self.colors else { return } // Set a background color of Menuview menuView.setShapeLayer(colors) // Add a cancel button let _ = self.addCancelButton(cancelButtonTitle) // Add a title label when title is set if !headline.isEmpty { let _ = self.addLabel(headline) } // Add a message label when message is set if !message.isEmpty { let _ = self.addMessageLabel(message) } // Style buttons for btn in buttons { btn.layer.cornerRadius = kButtonHeight * 0.5 btn.setFontName(fontName) btn.setColor(colors) } // Style labels for label in labels { label.setFontName(label.isTitle ? fontName : lightFontName) label.setColor(colors) } // Set frames self.updateFrames() // Animations animationWillStart() // Debug if (buttons.count == 0) { print("Hokusai:: The menu has no item yet.") } else if (buttons.count > 6) { print("Hokusai:: The menu has lots of items.") } } // Add an animation when showing the menu fileprivate func animationWillStart() { // Background self.view.backgroundColor = UIColor.clear UIView.animate(withDuration: HOKConsts().animationDuration * 0.4, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.view.backgroundColor = self.bgColor }, completion: nil ) // Menuview menuView.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.frame.height), size: menuView.frame.size) UIView.animate(withDuration: HOKConsts().animationDuration, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.6, options: [.beginFromCurrentState, .allowUserInteraction, .overrideInheritedOptions], animations: { self.menuView.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.frame.height-self.menuView.frame.height), size: self.menuView.frame.size) }, completion: {(finished) in }) menuView.positionAnimationWillStart() } // Dismiss the menuview @objc public func dismissHokusai() { // Background and Menuview UIView.animate(withDuration: HOKConsts().animationDuration, delay: 0.0, usingSpringWithDamping: 100.0, initialSpringVelocity: 0.6, options: [.beginFromCurrentState, .allowUserInteraction, .overrideInheritedOptions, .curveEaseOut], animations: { self.view.backgroundColor = UIColor.clear self.menuView.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.frame.height), size: self.menuView.frame.size) }, completion: {(finished) in self.view.removeFromSuperview() }) menuView.positionAnimationWillStart() } // When a button is tapped, this method is called. @objc func buttonTapped(_ btn:HOKButton) { switch btn.actionType { case .closure: btn.action() case .selector: let control = UIControl() control.sendAction(btn.selector, to:btn.target, for:nil) case .none: if !btn.isCancelButton { print("Unknow action type for button") } } dismissHokusai() } // Make the buttons darker when user tapping. @objc func buttonDarker(_ btn:HOKButton) { btn.backgroundColor = btn.backgroundColor!.darkerColorWithPercentage(0.2) } // Make the buttons lighter when user release finger. @objc func buttonLighter(_ btn:HOKButton) { btn.backgroundColor = btn.backgroundColor!.lighterColorWithPercentage(0.2) } } extension UIColor { func lighterColorWithPercentage(_ percent : Double) -> UIColor { return colorWithBrightness(CGFloat(1 + percent)) } func darkerColorWithPercentage(_ percent : Double) -> UIColor { return colorWithBrightness(CGFloat(1 - percent)) } func colorWithBrightness(_ factor: CGFloat) -> UIColor { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: saturation, brightness: brightness * factor, alpha: alpha) } else { return self } } }
mit
1d126b08448b5eacc1446da709617cde
31.557166
175
0.577406
4.957822
false
false
false
false
mlilback/rc2SwiftClient
ClientCore/Parsing/Rc2RmdParser.swift
1
4953
// // Rc2RmdParser.swift // ClientCore // // Created by Mark Lilback on 12/17/19. // Copyright © 2019 Rc2. All rights reserved. // import Foundation import Parsing import ReactiveSwift import Rc2Common import MJLLogger /// a callback that recieves a parsed keyword. returns true if a help URL should be included for it public typealias HelpCallback = (String) -> Bool /// allows subscribing to the parsedDocument without knowing anything about the parser public protocol ParserContext: class { var parsedDocument: Property<RmdDocument?> { get } } /// A wrapper around parsing so users of ClientCore do not need to know about Rc2Parser public class Rc2RmdParser: RmdParser, ParserContext { private let equationHighLigther = EquationHighlighter() var helpCallback: HelpCallback? private var contents: NSTextStorage // offers read-only version of _parsedDocument public let parsedDocument: Property<RmdDocument?> private let _parsedDocument = MutableProperty<RmdDocument?>(nil) public init(contents: NSTextStorage, help: @escaping HelpCallback) { self.contents = contents helpCallback = help parsedDocument = Property<RmdDocument?>(_parsedDocument) super.init() } /// Reparses the contents and updates parsedDocument, syntax highlighting any R code public func reparse() throws { guard contents.length > 0 else { _parsedDocument.value = nil; return } _parsedDocument.value = try RmdDocument(contents: contents.string, parser: self) // highlight code chunks _parsedDocument.value?.chunks.forEach { chunk in contents.addAttribute(ChunkKey, value: chunk.chunkType, range: chunk.innerRange) chunk.children.forEach { contents.addAttribute(ChunkKey, value: $0.chunkType, range: $0.innerRange) } // mark nested chunks if chunk.isEquation { equationHighLigther.highlight(string: contents, range: chunk.innerRange) return } guard chunk.chunkType == .code else { return } do { let highLighter = try RHighlighter(contents, range: chunk.innerRange) try highLighter.start() } catch { Log.error("error highlighting R code \(error.localizedDescription)", .parser) Log.debug("code=\(contents.attributedSubstring(from: chunk.innerRange).string)", .parser) } } } public func highlightEquation(contents: NSMutableAttributedString, range: NSRange) { equationHighLigther.highlight(string: contents, range: range) } /// Highlights the code/equations of text in range synchronously /// - Note: only currently called for R documents, so does not need to handle latex code /// - Parameters: /// - text: The mutable attributed string to update highlight of /// - range: The range to update, niil updates the entire text /// - timeout: How long until the parser should abort // TODO: implement as a signal handler that cancels oldest highlight job public func highlight(text: NSMutableAttributedString, range: NSRange? = nil, timeout: TimeInterval) { let rng = range ?? NSRange(location: 0, length: text.length) do { let highLighter = try RHighlighter(text, range: rng, timeout: timeout) try highLighter.start() } catch { Log.warn("error message highlighting R code", .app) } } /// Highlights the code/equations of text in range synchronously /// - Note: only currently called for R documents, so does not need to handle latex code /// - Parameters: /// - text: The mutable attributed string to update highlight of /// - range: The range to update, niil updates the entire text /// - timeout: How long until the parser should abort /// - Returns: a signal producer to highlight asynchronously public func highlightR(text: NSMutableAttributedString, range: NSRange? = nil, timeout: TimeInterval) -> SignalProducer<Bool, RParserError> { let rng = range ?? NSRange(location: 0, length: text.length) let producer = SignalProducer<Bool, RParserError> { (observer, _) in do { let hlighter = try RHighlighter(text, range: rng, timeout: timeout) try hlighter.start() observer.send(value: true) observer.sendCompleted() } catch RParserError.unknown { observer.send(error: RParserError.unknown) } catch RParserError.canceled { observer.send(error: RParserError.canceled) } catch RParserError.timeout { observer.send(error: RParserError.timeout) } catch { observer.send(error: .unknown) } } return producer } public func selectionChanged(range: NSRange) { // swiftlint:disable:next force_try try! reparse() } /// Called when the contents of the editor have changed due to user action. By default, this parses and highlights the entire contents /// /// - Parameters: /// - contents: The contents of the editor that was changed /// - range: the range of the original text that changed /// - delta: the length delta for the edited change // public func contentsChanged(range: NSRange, changeLength delta: Int) { // highlight(text: contents, range: range) // } }
isc
fb6863f8ef92136254d9f27124c417d8
38.301587
142
0.732229
3.847708
false
false
false
false
MyBar/MyBarMusic
MyBarMusic/MyBarMusic/Classes/Main/View/MBMiniPlayerView.swift
1
13648
// // MBMiniPlayerView.swift // MyBarMusic // // Created by lijingui2010 on 2017/7/6. // Copyright © 2017年 MyBar. All rights reserved. // import UIKit import Kingfisher class MBMiniPlayerView: UIView, UIScrollViewDelegate { @IBOutlet weak var separatorView: UIView! @IBOutlet weak var playlistButton: UIButton! @IBOutlet weak var playOrPauseButton: UIButton! @IBOutlet weak var nonePlaylistLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! var preMiniPlayerAlbumCoverView: MBMiniPlayerAlbumCoverView? var currentMiniPlayerAlbumCoverView: MBMiniPlayerAlbumCoverView? var nextMiniPlayerAlbumCoverView: MBMiniPlayerAlbumCoverView? lazy var playerManager: MBPlayerManager = AppDelegate.delegate.playerManager private static var miniPlayerView: MBMiniPlayerView? class var shared: MBMiniPlayerView { guard self.miniPlayerView == nil else { return self.miniPlayerView! } self.miniPlayerView = Bundle.main.loadNibNamed("MBMiniPlayerView", owner: nil, options: nil)?.last as? MBMiniPlayerView self.miniPlayerView?.backgroundColor = UIColor(patternImage: UIImage(named: "vc_bg")!) let miniPlayerViewHeight: CGFloat = 57.0 let navigationBarAndStatusBarHeight: CGFloat = (UIApplication.shared.keyWindow!.rootViewController?.slideMenuController()?.mainViewController as! UINavigationController).navigationBar.frame.height + UIApplication.shared.statusBarFrame.height self.miniPlayerView?.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - miniPlayerViewHeight - navigationBarAndStatusBarHeight, width: UIScreen.main.bounds.width, height: miniPlayerViewHeight) self.miniPlayerView?.setupButtons() self.miniPlayerView?.setupScrollView() //监听状态变化 NotificationCenter.default.addObserver(self.miniPlayerView!, selector: #selector(self.miniPlayerView!.observePlayerManagerStatus(_:)), name: NSNotification.Name("playerManagerStatus"), object: nil) return self.miniPlayerView! } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name("playerManagerStatus"), object: nil) self.currentMiniPlayerAlbumCoverView?.pauseAnimation() } var isEnable: Bool = false { didSet { self.nonePlaylistLabel.isHidden = isEnable self.scrollView.isHidden = !isEnable self.playOrPauseButton.isEnabled = isEnable self.playlistButton.isEnabled = isEnable if isEnable == false { self.currentMiniPlayerAlbumCoverView?.removeAnimation() self.playerManager.endPlay() } } } private func setupButtons() { self.updatePlayOrPauseButton() self.playlistButton.setImage(UIImage(named: "miniplayer_btn_playlist_normal"), for: UIControlState.normal) self.playlistButton.setImage(UIImage(named: "miniplayer_btn_playlist_highlight"), for: UIControlState.highlighted) self.playlistButton.setImage(UIImage(named: "miniplayer_btn_playlist_disable"), for: UIControlState.disabled) } func updatePlayOrPauseButton() { if self.isEnable { if self.playerManager.isPlaying == true { self.playOrPauseButton.setImage(UIImage(named: "miniplayer_btn_pause_normal"), for: UIControlState.normal) self.playOrPauseButton.setBackgroundImage(UIImage(named: "channel_song_list_play_btn"), for: UIControlState.normal) self.playOrPauseButton.setImage(UIImage(named: "miniplayer_btn_pause_highlight"), for: UIControlState.highlighted) self.playOrPauseButton.setBackgroundImage(UIImage(named: "channel_song_list_play_btn_h"), for: UIControlState.highlighted) } else { self.playOrPauseButton.setImage(UIImage(named: "miniplayer_btn_play_normal"), for: UIControlState.normal) self.playOrPauseButton.setBackgroundImage(UIImage(named: "channel_song_list_play_btn"), for: UIControlState.normal) self.playOrPauseButton.setImage(UIImage(named: "miniplayer_btn_play_highlight"), for: UIControlState.highlighted) self.playOrPauseButton.setBackgroundImage(UIImage(named: "channel_song_list_play_btn_h"), for: UIControlState.highlighted) } } else { self.playOrPauseButton.setImage(UIImage(named: "miniplayer_btn_play_disable"), for: UIControlState.disabled) self.playOrPauseButton.setBackgroundImage(UIImage(), for: UIControlState.disabled) } } @IBAction func clickPlayOrPauseButtonAction(_ sender: UIButton) { if self.isEnable { if self.playerManager.isPlaying == true { self.playerManager.pausePlay() } else if self.playerManager.isPlaying == false { self.playerManager.startPlay() } else if self.playerManager.playerManagerStatus == .readyToPlay { self.playerManager.startPlay() } } } private func setupScrollView() { self.scrollView.backgroundColor = self.backgroundColor let margin: CGFloat = 8.0 let scrollViewWidth = UIScreen.main.bounds.width - self.playOrPauseButton.frame.width - self.playlistButton.frame.width - margin * 3 let scrollViewHeight = self.frame.height - self.separatorView.frame.maxY self.scrollView.frame = CGRect(x: 0, y: self.separatorView.frame.maxY, width: scrollViewWidth, height: scrollViewHeight) self.scrollView.contentSize = CGSize(width: self.scrollView.frame.width * 3, height: self.scrollView.frame.height) self.scrollView.delegate = self self.preMiniPlayerAlbumCoverView = MBMiniPlayerAlbumCoverView.miniPlayerAlbumCoverView self.preMiniPlayerAlbumCoverView?.frame = CGRect(x: 0, y: self.scrollView.frame.origin.y, width: self.scrollView.frame.width, height: self.scrollView.frame.height) self.scrollView.addSubview(self.preMiniPlayerAlbumCoverView!) self.currentMiniPlayerAlbumCoverView = MBMiniPlayerAlbumCoverView.miniPlayerAlbumCoverView self.currentMiniPlayerAlbumCoverView?.frame = CGRect(x: self.scrollView.frame.width, y: self.scrollView.frame.origin.y, width: self.scrollView.frame.width, height: self.scrollView.frame.height) self.scrollView.addSubview(self.currentMiniPlayerAlbumCoverView!) self.nextMiniPlayerAlbumCoverView = MBMiniPlayerAlbumCoverView.miniPlayerAlbumCoverView self.nextMiniPlayerAlbumCoverView?.frame = CGRect(x: self.scrollView.frame.width * CGFloat(2), y: self.scrollView.frame.origin.y, width: self.scrollView.frame.width, height: self.scrollView.frame.height) self.scrollView.addSubview(self.nextMiniPlayerAlbumCoverView!) self.scrollView.contentOffset = CGPoint(x: self.scrollView.frame.width, y: 0) } /** UIScrollViewDelegate */ func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { //关于设置一个范围因为调试的时候发现contentOffset.x有时候不是0,self.scrollView.frame.width, self.scrollView.frame.width * CGFloat(2) if scrollView.contentOffset.x >= 0 && scrollView.contentOffset.x <= 10 { for miniPlayerAlbumCoverView in self.scrollView.subviews { miniPlayerAlbumCoverView.removeFromSuperview() } self.setupScrollView() self.playerManager.playPrevious() } if scrollView.contentOffset.x >= scrollView.frame.width * CGFloat(2) - 10 && scrollView.contentOffset.x <= scrollView.frame.width * CGFloat(2) + 10 { for miniPlayerAlbumCoverView in self.scrollView.subviews { miniPlayerAlbumCoverView.removeFromSuperview() } self.setupScrollView() self.playerManager.playNext() } } } extension MBMiniPlayerView { func observePlayerManagerStatus(_ notification: Notification) { let rotationAngle = (notification.object as? CGFloat) ?? self.currentMiniPlayerAlbumCoverView!.rotationAngle switch self.playerManager.playerManagerStatus { case .playing: print("MBMiniPlayerView.playerManager.playerManagerStatus = playing") self.updatePlayOrPauseButton() self.currentMiniPlayerAlbumCoverView!.initAnimation(with: rotationAngle) self.currentMiniPlayerAlbumCoverView!.resumeAnimation() case .paused: print("MBMiniPlayerView.playerManager.playerManagerStatus = paused") self.updatePlayOrPauseButton() self.currentMiniPlayerAlbumCoverView!.initAnimation(with: rotationAngle) self.currentMiniPlayerAlbumCoverView!.pauseAnimation() case .stopped: print("MBMiniPlayerView.playerManager.playerManagerStatus = stopped") self.currentMiniPlayerAlbumCoverView!.removeAnimation() case .loadSongModel: print("MBMiniPlayerView.playerManager.playerManagerStatus = loadSongModel") self.updateContentOfScrollView() case .unknown: print("MBMiniPlayerView.playerManager.playerManagerStatus = unknown") case .readyToPlay: print("MBMiniPlayerView.playerManager.playerManagerStatus = readyToPlay") self.currentMiniPlayerAlbumCoverView!.initAnimation(with: rotationAngle) case .failed: print("MBMiniPlayerView.playerManager.playerManagerStatus = failed") case .none: print("MBMiniPlayerView.playerManager.playerManagerStatus = none") } } func updateContentOfScrollView() { var preSongInfoModelIndex = self.playerManager.currentSongInfoModelIndex! - 1 let currentSongInfoModelIndex = self.playerManager.currentSongInfoModelIndex! var nextSongInfoModelIndex = self.playerManager.currentSongInfoModelIndex! + 1 switch self.playerManager.playingSortType! { case MBPlayingSortType.SingleLoop: fallthrough case MBPlayingSortType.Sequence: if (preSongInfoModelIndex < 0) { preSongInfoModelIndex = self.playerManager.songInfoList!.count - 1 } if (nextSongInfoModelIndex >= self.playerManager.songInfoList!.count) { nextSongInfoModelIndex = 0 } case MBPlayingSortType.Random: if (preSongInfoModelIndex < 0) { preSongInfoModelIndex = self.playerManager.songInfoList!.count - 1 } if (nextSongInfoModelIndex >= self.playerManager.songInfoList!.count) { nextSongInfoModelIndex = 0 } } self.preMiniPlayerAlbumCoverView?.musicNameLabel.text = self.playerManager.songInfoList![preSongInfoModelIndex].title self.currentMiniPlayerAlbumCoverView?.musicNameLabel.text = self.playerManager.songInfoList![currentSongInfoModelIndex].title self.nextMiniPlayerAlbumCoverView?.musicNameLabel.text = self.playerManager.songInfoList![nextSongInfoModelIndex].title self.preMiniPlayerAlbumCoverView?.lyricLabel.text = self.playerManager.songInfoList![preSongInfoModelIndex].artist_name self.currentMiniPlayerAlbumCoverView?.lyricLabel.text = self.playerManager.songInfoList![currentSongInfoModelIndex].artist_name self.nextMiniPlayerAlbumCoverView?.lyricLabel.text = self.playerManager.songInfoList![nextSongInfoModelIndex].artist_name if let urlStr = self.playerManager.songInfoList?[preSongInfoModelIndex].pic_small { self.preMiniPlayerAlbumCoverView?.albumImageView.kf.setImage(with: URL(string: urlStr), placeholder: UIImage(named: "player_albumcover_minidefault"), options: nil, progressBlock: nil, completionHandler: nil) } else { self.preMiniPlayerAlbumCoverView?.albumImageView.image = UIImage(named: "player_albumcover_minidefault") } if let urlStr = self.playerManager.songInfoList?[currentSongInfoModelIndex].pic_small { self.currentMiniPlayerAlbumCoverView?.albumImageView.kf.setImage(with: URL(string: urlStr), placeholder: UIImage(named: "player_albumcover_minidefault"), options: nil, progressBlock: nil, completionHandler: nil) } else { self.currentMiniPlayerAlbumCoverView?.albumImageView.image = UIImage(named: "player_albumcover_minidefault") } if let urlStr = self.playerManager.songInfoList?[nextSongInfoModelIndex].pic_small { self.nextMiniPlayerAlbumCoverView?.albumImageView.kf.setImage(with: URL(string: urlStr), placeholder: UIImage(named: "player_albumcover_minidefault"), options: nil, progressBlock: nil, completionHandler: nil) } else { self.nextMiniPlayerAlbumCoverView?.albumImageView.image = UIImage(named: "player_albumcover_minidefault") } } }
mit
cb7645c0d0d359f4c0fe157959283736
45.530822
249
0.67226
5.006264
false
false
false
false
ben-ng/swift
stdlib/public/core/WriteBackMutableSlice.swift
1
1729
//===--- WriteBackMutableSlice.swift --------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// internal func _writeBackMutableSlice<C, Slice_>( _ self_: inout C, bounds: Range<C.Index>, slice: Slice_ ) where C : MutableCollection, Slice_ : Collection, C._Element == Slice_.Iterator.Element, C.Index == Slice_.Index { self_._failEarlyRangeCheck(bounds, bounds: self_.startIndex..<self_.endIndex) // FIXME(performance): can we use // _withUnsafeMutableBufferPointerIfSupported? Would that create inout // aliasing violations if the newValue points to the same buffer? var selfElementIndex = bounds.lowerBound let selfElementsEndIndex = bounds.upperBound var newElementIndex = slice.startIndex let newElementsEndIndex = slice.endIndex while selfElementIndex != selfElementsEndIndex && newElementIndex != newElementsEndIndex { self_[selfElementIndex] = slice[newElementIndex] self_.formIndex(after: &selfElementIndex) slice.formIndex(after: &newElementIndex) } _precondition( selfElementIndex == selfElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a smaller size") _precondition( newElementIndex == newElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a larger size") }
apache-2.0
c2024bc72c3de3cc9df56f51c27d6120
35.787234
83
0.689416
4.829609
false
false
false
false
OatmealDome/dolphin
Source/iOS/DolphiniOS/DolphiniOS/UI/Emulation/TouchController/TCButtonType.swift
1
6195
// Copyright 2019 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. import Foundation // ButtonManager::ButtonType @objc enum TCButtonType: Int { // GameCube case BUTTON_A = 0 case BUTTON_B = 1 case BUTTON_START = 2 case BUTTON_X = 3 case BUTTON_Y = 4 case BUTTON_Z = 5 case BUTTON_UP = 6 case BUTTON_DOWN = 7 case BUTTON_LEFT = 8 case BUTTON_RIGHT = 9 case STICK_MAIN = 10 case STICK_C = 15 case TRIGGER_L = 20 case TRIGGER_R = 21 // Wiimote case WIIMOTE_BUTTON_A = 100 case WIIMOTE_BUTTON_B = 101 case WIIMOTE_BUTTON_MINUS = 102 case WIIMOTE_BUTTON_PLUS = 103 case WIIMOTE_BUTTON_HOME = 104 case WIIMOTE_BUTTON_1 = 105 case WIIMOTE_BUTTON_2 = 106 case WIIMOTE_UP = 107 case WIIMOTE_DOWN = 108 case WIIMOTE_LEFT = 109 case WIIMOTE_RIGHT = 110 case WIIMOTE_IR = 111 case WIIMOTE_IR_UP = 112 case WIIMOTE_IR_DOWN = 113 case WIIMOTE_IR_LEFT = 114 case WIIMOTE_IR_RIGHT = 115 case WIIMOTE_IR_FORWARD = 116 case WIIMOTE_IR_BACKWARD = 117 case WIIMOTE_IR_HIDE = 118 case WIIMOTE_SWING = 119 case WIIMOTE_SWING_UP = 120 case WIIMOTE_SWING_DOWN = 121 case WIIMOTE_SWING_LEFT = 122 case WIIMOTE_SWING_RIGHT = 123 case WIIMOTE_SWING_FORWARD = 124 case WIIMOTE_SWING_BACKWARD = 125 case WIIMOTE_TILT = 126 case WIIMOTE_TILT_FORWARD = 127 case WIIMOTE_TILT_BACKWARD = 128 case WIIMOTE_TILT_LEFT = 129 case WIIMOTE_TILT_RIGHT = 130 case WIIMOTE_TILT_MODIFIER = 131 case WIIMOTE_SHAKE_X = 132 case WIIMOTE_SHAKE_Y = 133 case WIIMOTE_SHAKE_Z = 134 // Nunchuk case NUNCHUK_BUTTON_C = 200 case NUNCHUK_BUTTON_Z = 201 case NUNCHUK_STICK = 202 case NUNCHUK_SWING = 207 case NUNCHUK_SWING_UP = 208 case NUNCHUK_SWING_DOWN = 209 case NUNCHUK_SWING_LEFT = 210 case NUNCHUK_SWING_RIGHT = 211 case NUNCHUK_SWING_FORWARD = 212 case NUNCHUK_SWING_BACKWARD = 213 case NUNCHUK_TILT = 214 case NUNCHUK_TILT_FORWARD = 215 case NUNCHUK_TILT_BACKWARD = 216 case NUNCHUK_TILT_LEFT = 217 case NUNCHUK_TILT_RIGHT = 218 case NUNCHUK_TILT_MODIFIER = 219 case NUNCHUK_SHAKE_X = 220 case NUNCHUK_SHAKE_Y = 221 case NUNCHUK_SHAKE_Z = 222 // Classic Controller case CLASSIC_BUTTON_A = 300 case CLASSIC_BUTTON_B = 301 case CLASSIC_BUTTON_X = 302 case CLASSIC_BUTTON_Y = 303 case CLASSIC_BUTTON_MINUS = 304 case CLASSIC_BUTTON_PLUS = 305 case CLASSIC_BUTTON_HOME = 306 case CLASSIC_BUTTON_ZL = 307 case CLASSIC_BUTTON_ZR = 308 case CLASSIC_DPAD_UP = 309 case CLASSIC_DPAD_DOWN = 310 case CLASSIC_DPAD_LEFT = 311 case CLASSIC_DPAD_RIGHT = 312 case CLASSIC_STICK_LEFT = 313 case CLASSIC_STICK_LEFT_UP = 314 case CLASSIC_STICK_LEFT_DOWN = 315 case CLASSIC_STICK_LEFT_LEFT = 316 case CLASSIC_STICK_LEFT_RIGHT = 317 case CLASSIC_STICK_RIGHT = 318 case CLASSIC_STICK_RIGHT_UP = 319 case CLASSIC_STICK_RIGHT_DOWN = 320 case CLASSIC_STICK_RIGHT_LEFT = 321 case CLASSIC_STICK_RIGHT_RIGHT = 322 case CLASSIC_TRIGGER_L = 323 case CLASSIC_TRIGGER_R = 324 // Wiimote IMU case WIIMOTE_ACCEL_LEFT = 625 case WIIMOTE_ACCEL_RIGHT = 626 case WIIMOTE_ACCEL_FORWARD = 627 case WIIMOTE_ACCEL_BACKWARD = 628 case WIIMOTE_ACCEL_UP = 629 case WIIMOTE_ACCEL_DOWN = 630 case WIIMOTE_GYRO_PITCH_UP = 631 case WIIMOTE_GYRO_PITCH_DOWN = 632 case WIIMOTE_GYRO_ROLL_LEFT = 633 case WIIMOTE_GYRO_ROLL_RIGHT = 634 case WIIMOTE_GYRO_YAW_LEFT = 635 case WIIMOTE_GYRO_YAW_RIGHT = 636 // Wiimote IMU IR case WIIMOTE_IR_RECENTER = 800 // TODO: Guitar, Drums, Turntable, Rumble func getImageName() -> String { switch self { case .BUTTON_A: return "gcpad_a" case .BUTTON_B: return "gcpad_b" case .BUTTON_START: return "gcpad_start" case .BUTTON_X: return "gcpad_x" case .BUTTON_Y: return "gcpad_y" case .BUTTON_Z: return "gcpad_z" case .BUTTON_UP, .BUTTON_DOWN, .BUTTON_LEFT, .BUTTON_RIGHT, .WIIMOTE_UP, .WIIMOTE_DOWN, .WIIMOTE_LEFT, .WIIMOTE_RIGHT, .CLASSIC_DPAD_UP, .CLASSIC_DPAD_DOWN, .CLASSIC_DPAD_LEFT, .CLASSIC_DPAD_RIGHT: return "gcwii_dpad" case .STICK_MAIN, .WIIMOTE_IR, .NUNCHUK_STICK, .CLASSIC_STICK_LEFT, .CLASSIC_STICK_RIGHT: return "gcwii_joystick" case .STICK_C: return "gcpad_c" case .TRIGGER_L: return "gcpad_l" case .TRIGGER_R: return "gcpad_r" case .WIIMOTE_BUTTON_A: return "wiimote_a" case .WIIMOTE_BUTTON_B: return "wiimote_b" case .WIIMOTE_BUTTON_MINUS, .CLASSIC_BUTTON_MINUS: return "wiimote_minus" case .WIIMOTE_BUTTON_PLUS, .CLASSIC_BUTTON_PLUS: return "wiimote_plus" case .WIIMOTE_BUTTON_HOME, .CLASSIC_BUTTON_HOME: return "wiimote_home" case .WIIMOTE_BUTTON_1: return "wiimote_one" case .WIIMOTE_BUTTON_2: return "wiimote_two" case .NUNCHUK_BUTTON_C: return "nunchuk_c" case .NUNCHUK_BUTTON_Z: return "nunchuk_z" case .CLASSIC_BUTTON_A: return "classic_a" case .CLASSIC_BUTTON_B: return "classic_b" case .CLASSIC_BUTTON_X: return "classic_x" case .CLASSIC_BUTTON_Y: return "classic_y" case .CLASSIC_BUTTON_ZL: return "classic_zl" case .CLASSIC_BUTTON_ZR: return "classic_zr" case .CLASSIC_TRIGGER_L: return "classic_l" case .CLASSIC_TRIGGER_R: return "classic_r" default: return "gcpad_a" } } func getButtonScale() -> CGFloat { switch self { case .BUTTON_A, .BUTTON_Z, .TRIGGER_L, .TRIGGER_R, .WIIMOTE_BUTTON_B, .NUNCHUK_BUTTON_Z, .CLASSIC_BUTTON_ZL, .CLASSIC_BUTTON_ZR, .CLASSIC_TRIGGER_L, .CLASSIC_TRIGGER_R: return 0.6 case .BUTTON_B, .BUTTON_START, .WIIMOTE_BUTTON_1, .WIIMOTE_BUTTON_2, .WIIMOTE_BUTTON_A, .CLASSIC_BUTTON_A, .CLASSIC_BUTTON_B, .CLASSIC_BUTTON_X, .CLASSIC_BUTTON_Y: return 0.33 case .BUTTON_X, .BUTTON_Y: return 0.5 case .WIIMOTE_BUTTON_PLUS, .WIIMOTE_BUTTON_MINUS, .CLASSIC_BUTTON_MINUS, .CLASSIC_BUTTON_PLUS: return 0.2 case .WIIMOTE_BUTTON_HOME, .CLASSIC_BUTTON_HOME: return 0.25 case .NUNCHUK_BUTTON_C: return 0.4 default: return 1.0 } } }
gpl-2.0
92bf1056e0aba4e13d50ace4bf998e51
28.221698
172
0.670702
2.738727
false
false
false
false
cathandnya/Pixitail
pixiViewer/Classes/Widget/CatHand/CHImageCache.swift
1
4411
// // CHImageCache.swift // // Created by nya on 2014/06/07. // Copyright (c) 2014年 CatHand.org. All rights reserved. // import Foundation class CHImageCache { static let sharedInstance = { () -> CHImageCache in let path: String = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String return CHImageCache(path: (path as NSString).appendingPathComponent("CHImageCache")) }() init(path: String, cacheSize: UInt64 = 100 * 1000 * 1000) { self.basePath = path; self.cacheSize = cacheSize; self.totalCacheSize = 0; if !FileManager.default.fileExists(atPath: self.basePath) { do { try FileManager.default.createDirectory(atPath: self.basePath, withIntermediateDirectories:true, attributes: nil) } catch _ { } } DispatchQueue.global().async { self.calculateCacheSizeAndFillUsageMap() } } class func keyForURL(_ url: URL) -> String { return "\(url.absoluteString.hash)" } func contains(_ key: String) -> Bool { let path = pathForKey(key) return FileManager.default.fileExists(atPath: path) } func data(_ key: String) -> Data? { let path = pathForKey(key) let data = try? Data(contentsOf: URL(fileURLWithPath: path)) if var info = filesDic[path] { info.date = Date() } return data } func setData(_ data: Data, key: String) -> Bool { let path = pathForKey(key) let b = (try? data.write(to: URL(fileURLWithPath: path), options: [.atomic])) != nil if !b { return false } else { let len: UInt64 = UInt64(data.count) filesDic[path] = FileInfo(size: len, date: Date(), path: path) self.totalCacheSize += len; if self.totalCacheSize > self.cacheSize { var mary = Array(self.filesDic.values) mary.sort { (obj1 : FileInfo, obj2 : FileInfo) -> Bool in return obj1.date.timeIntervalSinceReferenceDate < obj2.date.timeIntervalSinceReferenceDate } while self.totalCacheSize > self.cacheSize { let obj = mary[0] do { try FileManager.default.removeItem(atPath: obj.path) self.totalCacheSize -= obj.size self.filesDic.removeValue(forKey: obj.path) mary.remove(at: 0) } catch _ { break; } } } return true; } } func removeData(_ key: String) { let path = pathForKey(key) if FileManager.default.fileExists(atPath: path) { do { try FileManager.default.removeItem(atPath: path) } catch _ { } } } func removeAll() { do { try FileManager.default.removeItem(atPath: self.basePath) } catch _ { } } // private var basePath: String var cacheSize: UInt64 var totalCacheSize: UInt64 var filesDic = Dictionary<String, FileInfo>() struct FileInfo { var size: UInt64 var date: Date var path: String } func pathForKey(_ key: String) -> String { return (self.basePath as NSString).appendingPathComponent(key) } func calculateCacheSizeAndFillUsageMap() { var total: UInt64 = 0; var mary = Array<FileInfo>() do { let contents = try FileManager.default.contentsOfDirectory(atPath: basePath); for name in contents { let path = URL(fileURLWithPath: basePath).appendingPathComponent(name).path do { let a = try FileManager.default.attributesOfItem(atPath: path) let size = (a[FileAttributeKey.size] as! NSNumber).uint64Value let date = a[FileAttributeKey.modificationDate] as! Date? if let d = date { let info = FileInfo(size: size, date: d, path: path) mary.append(info) total += size; } } catch { } } } catch { } mary.sort { (obj1 : FileInfo, obj2 : FileInfo) -> Bool in return obj1.date.timeIntervalSinceReferenceDate < obj2.date.timeIntervalSinceReferenceDate } // 古いのけしとく while total > self.cacheSize { let obj = mary[0] do { try FileManager.default.removeItem(atPath: obj.path) total -= obj.size mary.remove(at: 0); } catch _ { // 削除失敗 break } } DispatchQueue.main.async { for obj in mary { self.filesDic[obj.path] = obj; } self.totalCacheSize = total } } }
mit
5be76bcd0592e0354e5016f2e4673a7c
24.95858
179
0.626852
3.6107
false
false
false
false
adrfer/swift
test/Generics/generic_types.swift
2
8301
// RUN: %target-parse-verify-swift protocol MyFormattedPrintable { func myFormat() -> String } func myPrintf(format: String, _ args: MyFormattedPrintable...) {} extension Int : MyFormattedPrintable { func myFormat() -> String { return "" } } struct S<T : MyFormattedPrintable> { var c : T static func f(a: T) -> T { return a } func f(a: T, b: Int) { return myPrintf("%v %v %v", a, b, c) } } func makeSInt() -> S<Int> {} typealias SInt = S<Int> var a : S<Int> = makeSInt() a.f(1,b: 2) var b : Int = SInt.f(1) struct S2<T> { static func f() -> T { S2.f() } } struct X { } var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}} enum Optional<T> { case Element(T) case None init() { self = .None } init(_ t: T) { self = .Element(t) } } typealias OptionalInt = Optional<Int> var uniontest1 : (Int) -> Optional<Int> = OptionalInt.Element var uniontest2 : Optional<Int> = OptionalInt.None var uniontest3 = OptionalInt(1) // FIXME: Stuff that should work, but doesn't yet. // var uniontest4 : OptInt = .None // var uniontest5 : OptInt = .Some(1) func formattedTest<T : MyFormattedPrintable>(a: T) { myPrintf("%v", a) } struct formattedTestS<T : MyFormattedPrintable> { func f(a: T) { formattedTest(a) } } struct GenericReq< T : GeneratorType, U : GeneratorType where T.Element == U.Element > {} func getFirst<R : GeneratorType>(r: R) -> R.Element { var r = r return r.next()! } func testGetFirst(ir: Range<Int>) { _ = getFirst(ir.generate()) as Int } struct XT<T> { init(t : T) { prop = (t, t) } static func f() -> T {} func g() -> T {} var prop : (T, T) } class YT<T> { init(_ t : T) { prop = (t, t) } deinit {} class func f() -> T {} func g() -> T {} var prop : (T, T) } struct ZT<T> { var x : T, f : Float } struct Dict<K, V> { subscript(key: K) -> V { get {} set {} } } class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}} subscript(key: K) -> V { get {} set {} } } typealias XI = XT<Int> typealias YI = YT<Int> typealias ZI = ZT<Int> var xi = XI(t: 17) var yi = YI(17) var zi = ZI(x: 1, f: 3.0) var i : Int = XI.f() i = XI.f() i = xi.g() i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}} i = yi.g() var xif : (XI) -> () -> Int = XI.g var gif : (YI) -> () -> Int = YI.g var ii : (Int, Int) = xi.prop ii = yi.prop xi.prop = ii yi.prop = ii var d1 : Dict<String, Int> var d2 : Dictionary<String, Int> d1["hello"] = d2["world"] i = d2["blarg"] struct RangeOfPrintables<R : SequenceType where R.Generator.Element : MyFormattedPrintable> { var r : R func format() -> String { var s : String for e in r { s = s + e.myFormat() + " " } return s } } struct Y {} struct SequenceY : SequenceType, GeneratorType { typealias Generator = SequenceY typealias Element = Y func next() -> Element? { return Y() } func generate() -> Generator { return self } } func useRangeOfPrintables(roi : RangeOfPrintables<[Int]>) { var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'SequenceType'}} var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}} } struct HasNested<T> { init<U>(_ t: T, _ u: U) {} func f<U>(t: T, u: U) -> (T, U) {} struct InnerGeneric<U> { // expected-error{{generic type 'InnerGeneric' nested}} init() {} func g<V>(t: T, u: U, v: V) -> (T, U, V) {} } struct Inner { // expected-error{{nested in generic type}} init (_ x: T) {} func identity(x: T) -> T { return x } } } func useNested(ii: Int, hni: HasNested<Int>, xisi : HasNested<Int>.InnerGeneric<String>, xfs: HasNested<Float>.InnerGeneric<String>) { var i = ii, xis = xisi typealias InnerI = HasNested<Int>.Inner var innerI = InnerI(5) typealias InnerF = HasNested<Float>.Inner var innerF : InnerF = innerI // expected-error{{cannot convert value of type 'InnerI' (aka 'HasNested<Int>.Inner') to specified type 'InnerF' (aka 'HasNested<Float>.Inner')}} innerI.identity(i) i = innerI.identity(i) // Generic function in a generic class typealias HNI = HasNested<Int> var id = hni.f(1, u: 3.14159) id = (2, 3.14159) hni.f(1.5, 3.14159) // expected-error{{missing argument label 'u:' in call}} hni.f(1.5, u: 3.14159) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Int'}} // Generic constructor of a generic struct HNI(1, 2.71828) // expected-warning{{unused}} // FIXME: Should report this error: {{cannot convert the expression's type 'HNI' to type 'Int'}} HNI(1.5, 2.71828) // expected-error{{cannot invoke initializer for type 'HNI' with an argument list of type '(Double, Double)'}} expected-note{{expected an argument list of type '(T, U)'}} // Generic function in a nested generic struct var ids = xis.g(1, u: "Hello", v: 3.14159) ids = (2, "world", 2.71828) xis = xfs // expected-error{{cannot assign value of type 'HasNested<Float>.InnerGeneric<String>' to type 'HasNested<Int>.InnerGeneric<String>'}} } var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}} var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}{{21-28=}} // Check unqualified lookup of inherited types. class Foo<T> { typealias Nested = T } class Bar : Foo<Int> { func f(x: Int) -> Nested { return x } struct Inner { func g(x: Int) -> Nested { return x } func withLocal() { struct Local { func h(x: Int) -> Nested { return x } } } } } extension Bar { func g(x: Int) -> Nested { return x } /* This crashes for unrelated reasons: <rdar://problem/14376418> struct Inner2 { func f(x: Int) -> Nested { return x } } */ } // Make sure that redundant typealiases (that map to the same // underlying type) don't break protocol conformance or use. class XArray : ArrayLiteralConvertible { typealias Element = Int init() { } required init(arrayLiteral elements: Int...) { } } class YArray : XArray { typealias Element = Int required init(arrayLiteral elements: Int...) { super.init() } } var yarray : YArray = [1, 2, 3] var xarray : XArray = [1, 2, 3] // Type parameters can be referenced only via unqualified name lookup struct XParam<T> { func foo(x: T) { _ = x as T } static func bar(x: T) { _ = x as T } } var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of 'XParam<Int>'}} // Diagnose failure to meet a superclass requirement. class X1 { } class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}} class X3 { } var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}} protocol P { associatedtype AssocP } protocol Q { associatedtype AssocQ } struct X4 : P, Q { typealias AssocP = Int typealias AssocQ = String } struct X5<T, U where T: P, T: Q, T.AssocP == T.AssocQ> { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}} var y: X5<X4, Int> // expected-error{{'X5' requires the types 'AssocP' (aka 'Int') and 'AssocQ' (aka 'String') be equivalent}} // Recursive generic signature validation. class Top {} class Bottom<T : Bottom<Top>> {} // expected-error 2{{type may not reference itself as a requirement}} // expected-error@-1{{Bottom' requires that 'Top' inherit from 'Bottom<Top>'}} // expected-note@-2{{requirement specified as 'T' : 'Bottom<Top>' [with T = Top]}} class X6<T> { let d: D<T> init(_ value: T) { d = D(value) } class D<T2> { // expected-error{{generic type 'D' nested in type 'X6' is not allowed}} init(_ value: T2) {} } } // Invalid inheritance clause struct UnsolvableInheritance1<T : T.A> {} // expected-error@-1 {{inheritance from non-protocol, non-class type 'T.A'}} struct UnsolvableInheritance2<T : U.A, U : T.A> {} // expected-error@-1 {{inheritance from non-protocol, non-class type 'U.A'}} // expected-error@-2 {{inheritance from non-protocol, non-class type 'T.A'}}
apache-2.0
06f652b6053ea83f540dad43ad5b05a5
23.853293
190
0.62619
3.08817
false
false
false
false
rankun203/SwiftGround
FoodPin/FoodPin/DetailViewController.swift
1
3002
// // DetailViewController.swift // FoodPin // // Created by Kun on 10/17/15. // Copyright © 2015 Kun. All rights reserved. // import UIKit class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var detailsTableView: UITableView! @IBOutlet weak var restaurantImageView: UIImageView! let detailCellName = "detailCell" var restaurant: Restaurant! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. restaurantImageView.image = UIImage(named: restaurant.image) detailsTableView.backgroundColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.2) detailsTableView.separatorColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.8) detailsTableView.tableFooterView = UIView(frame: CGRectZero) title = restaurant.name } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.hidesBarsOnSwipe = false self.navigationController?.setNavigationBarHidden(false, animated: true) } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(detailCellName, forIndexPath: indexPath) as! DetailTableViewCell cell.backgroundColor = UIColor.clearColor() switch indexPath.row { case 0: cell.fieldLabel.text = "Name" cell.valueLabel.text = restaurant.name case 1: cell.fieldLabel.text = "Type" cell.valueLabel.text = restaurant.type case 2: cell.fieldLabel.text = "Location" cell.valueLabel.text = restaurant.location case 3: cell.fieldLabel.text = "Been Here" cell.valueLabel.text = restaurant.isVisited ? "Yes, I've been here before" : "No" default: cell.fieldLabel.text = "" cell.valueLabel.text = "" } return cell } }
mit
d9ba7a827bc679630432feecf6876a24
33.895349
127
0.663112
4.863857
false
false
false
false
orj/Manoeuvre
Manoeuvre/Vector.swift
1
8756
// Copyright (c) 2014 Oliver Jones. All rights reserved. // import UIKit import CoreGraphics /** Defines the basic arithmetic functions of vector types. */ public protocol VectorArithmeticType { typealias FactorType func +(lhs: Self, rhs: Self) -> Self func -(lhs: Self, rhs: Self) -> Self func *(lhs: Self, rhs: FactorType) -> Self func /(lhs: Self, rhs: FactorType) -> Self prefix func -(rhs: Self) -> Self func +=(inout lhs: Self, rhs: Self) -> Self func -=(inout lhs: Self, rhs: Self) -> Self func *=(inout lhs: Self, rhs: FactorType) -> Self func /=(inout lhs: Self, rhs: FactorType) -> Self } public protocol VectorType : VectorArithmeticType { typealias ElementType typealias LengthType var length: LengthType { get } var lengthSquared: LengthType { get } var normalized: Self { get } class var zeroVector: Self { get } } /** Defines a two dimensional vector type */ public protocol Vector2Type : VectorType { var x:ElementType { get set } var y:ElementType { get set } init(_ x:ElementType, _ y:ElementType) } /** Defines a three dimensional vector type */ public protocol Vector3Type : VectorType { var x:ElementType { get set } var y:ElementType { get set } var z:ElementType { get set } init(_ x:ElementType, _ y:ElementType, _ z:ElementType) } public struct Vector2 : Vector2Type { public typealias ElementType = CGFloat public typealias FactorType = ElementType public typealias LengthType = ElementType public var x: ElementType public var y: ElementType public init(_ x: ElementType, _ y: ElementType) { self.x = x self.y = y } public var length: LengthType { return Manoeuvre.length(self) } public var lengthSquared: LengthType { return Manoeuvre.lengthSquared(self) } public var normalized: Vector2 { return Manoeuvre.normalize(self) } public static var zeroVector: Vector2 { return Vector2(0, 0) } } extension Vector2 { init(_ value: CGVector) { self.init(value.dx, value.dy) } init(_ value: CGPoint) { self.init(value.x, value.y) } } extension CGVector { init(_ value: Vector2) { self.init(value.x, value.y) } } extension CGPoint { init(_ value: Vector2) { self.init(x:value.x, y:value.y) } } // TODO: Is there a way of doing this without defining generic functions for every possible T.ElementType type? Float, Double, etc? public func lengthSquared<T: Vector2Type where T.ElementType == T.LengthType, T.ElementType == T.FactorType, T.ElementType == CGFloat>(vector: T) -> T.LengthType { var xSquared = vector.x * vector.x var ySquared = vector.y * vector.y return xSquared + ySquared } public func lengthSquared<T: Vector3Type where T.ElementType == T.LengthType, T.ElementType == T.FactorType, T.ElementType == CGFloat>(vector: T) -> T.LengthType { var xSquared = vector.x * vector.x var ySquared = vector.y * vector.y var zSquared = vector.z * vector.z return xSquared + ySquared + zSquared } public func length<T: Vector2Type where T.ElementType == T.LengthType, T.ElementType == T.FactorType, T.ElementType == CGFloat>(vector: T) -> T.LengthType { return 0 // sqrt(lengthSquared(vector)) } public func length<T: Vector3Type where T.ElementType == T.LengthType, T.ElementType == T.FactorType, T.ElementType == CGFloat>(vector: T) -> T.LengthType { return 0 //sqrt(lengthSquared(vector)) } /// Returns a normalized copy of the specified vector. public func normalize<T: VectorType where T.ElementType == T.LengthType, T.ElementType == T.FactorType, T.ElementType == CGFloat>(vector: T) -> T { var len = vector.length if (len > CGFloat(DBL_EPSILON)) { return vector / len } return vector } /// Returns the vector perpendicular to the specified 2 dimensional vector. public func perpendicular<T: Vector2Type where T.ElementType == CGFloat>(vector: T) -> T { return T(-vector.y, vector.x); } /// Returns a copy of the vector truncated so that its length does not exceed the specified maxLength. public func truncate<T: VectorType where T.LengthType == T.ElementType, T.FactorType == T.ElementType, T.ElementType == CGFloat>(vector: T, maxLength: T.LengthType) -> T { if (vector.length > maxLength) { return vector.normalized * maxLength } return vector } /// Returns the squared euclidean distance between the specified vectors. public func distanceSquared<T:VectorType>(vector1: T, vector2: T) -> T.LengthType { var separation = vector2 - vector1 return separation.lengthSquared } public func distance<T:VectorType>(vector1: T, vector2: T) -> T.LengthType { var separation = vector2 - vector1 return separation.length } /// Calculates the dot product of two 2 dimensional vectors. public func dot<T: Vector2Type where T.ElementType == T.FactorType, T.ElementType == CGFloat>(vector1:T, vector2:T) -> T.FactorType { var x = vector1.x * vector2.x var y = vector1.y * vector2.y return x + y } /// Calculates the dot product of two 3 dimensional vectors. public func dot<T: Vector3Type where T.ElementType == T.FactorType, T.ElementType == CGFloat>(vector1:T, vector2:T) -> T.FactorType { var x = vector1.x * vector2.x var y = vector1.y * vector2.y var z = vector1.z * vector2.z return x + y + z } /// Returns the vector that is the result of adding two vectors to each other. public func +(lhs:Vector2, rhs:Vector2) -> Vector2 { var x = lhs.x + rhs.x var y = lhs.y + rhs.y return Vector2(x, y) } /// Returns the vector that is the result of subtracting two vectors from each other. public func -<T:Vector2Type where T.ElementType == CGFloat>(lhs:T, rhs:T) -> T { var x = lhs.x - rhs.x var y = lhs.y - rhs.y return T(x, y) } /// Returns the reverse vector of the specified vector. public prefix func -<T:Vector2Type where T.ElementType == CGFloat>(rhs:T) -> T { var x = -rhs.x var y = -rhs.y return T(x, y) } /// Returns a vector multiplied by the specfied factor. public func *<T:Vector2Type where T.FactorType == T.ElementType, T.ElementType == CGFloat>(lhs:T, rhs:T.FactorType) -> T { var x = lhs.x * rhs var y = lhs.y * rhs return T(x, y) } /// Returns a vector divided by the specfied factor. public func /<T:Vector2Type where T.FactorType == T.ElementType, T.ElementType == CGFloat>(lhs:T, rhs:T.FactorType) -> T { var x = lhs.x / rhs var y = lhs.y / rhs return T(x, y) } public func +=<T:Vector2Type where T.ElementType == CGFloat>(inout lhs:T, rhs:T) -> T { lhs.x += rhs.x lhs.y += rhs.y return lhs } public func -=<T:Vector2Type where T.ElementType == CGFloat>(inout lhs:T, rhs:T) -> T { lhs.x -= rhs.x lhs.y -= rhs.y return lhs } public func *=<T:Vector2Type where T.FactorType == T.ElementType, T.ElementType == CGFloat>(inout lhs:T, rhs:T.FactorType) -> T { lhs.x *= rhs lhs.y *= rhs return lhs } public func /=<T:Vector2Type where T.FactorType == T.ElementType, T.ElementType == CGFloat>(inout lhs:T, rhs:T.FactorType) -> T { lhs.x /= rhs lhs.y /= rhs return lhs } /// Returns the vector that is the result of adding two vectors to each other. public func add<T: VectorArithmeticType>(lhs:T, rhs:T) -> T { return lhs + rhs; } /// Returns the vector that is the result of subtracting two vectors from each other. public func subtract<T: VectorArithmeticType>(lhs:T, rhs:T) -> T { return lhs - rhs; } /// Returns a vector multiplied by the specfied factor. public func multiply<T: VectorArithmeticType>(vector:T, factor:T.FactorType) -> T { return vector * factor; } /// Returns a vector divided by the specfied factor. public func divide<T: VectorArithmeticType>(vector:T, factor:T.FactorType) -> T { return vector / factor; } /// Returns the reverse vector of the specified vector. public func reverse<T: VectorArithmeticType>(vector:T) -> T { return -vector; } /** Given a normalized wall normal vector reflect (bounce) the specified vector off it. :param: wallNormal The normalized normal vector of the wall. i.e, a unit vector perpendicular to the wall. */ public func reflect<T: Vector2Type where T.FactorType == T.ElementType, T.FactorType == CGFloat>(vector: T, wallNormal:T) -> T { return vector + (-wallNormal * (2.0 * dot(vector, wallNormal))) } extension CGVector : Printable { public var description: String { return "{\(dx), \(dy)}" } } extension CGPoint : Printable { public var description: String { return "{\(x), \(y)}" } }
mit
502effee30853287238e3e647af3cac4
29.508711
171
0.665144
3.582651
false
false
false
false
wulkano/aperture
Sources/Aperture/Aperture.swift
1
6379
import Foundation import AVFoundation public final class Aperture: NSObject { public enum Error: Swift.Error { case invalidScreen case invalidAudioDevice case couldNotAddScreen case couldNotAddMic case couldNotAddOutput } private let destination: URL private let session: AVCaptureSession private let output: AVCaptureMovieFileOutput private var activity: NSObjectProtocol? public var onStart: (() -> Void)? public var onFinish: ((Swift.Error?) -> Void)? public var onPause: (() -> Void)? public var onResume: (() -> Void)? public var isRecording: Bool { output.isRecording } public var isPaused: Bool { output.isRecordingPaused } private init( destination: URL, input: AVCaptureInput, output: AVCaptureMovieFileOutput, audioDevice: AVCaptureDevice?, videoCodec: String? ) throws { self.destination = destination session = AVCaptureSession() self.output = output // Needed because otherwise there is no audio on videos longer than 10 seconds. // https://stackoverflow.com/a/26769529/64949 output.movieFragmentInterval = .invalid if let audioDevice = audioDevice { if !audioDevice.hasMediaType(.audio) { throw Error.invalidAudioDevice } let audioInput = try AVCaptureDeviceInput(device: audioDevice) if session.canAddInput(audioInput) { session.addInput(audioInput) } else { throw Error.couldNotAddMic } } if session.canAddInput(input) { session.addInput(input) } else { throw Error.couldNotAddScreen } if session.canAddOutput(output) { session.addOutput(output) } else { throw Error.couldNotAddOutput } // TODO: Default to HEVC when on 10.13 or newer and encoding is hardware supported. Without hardware encoding I got 3 FPS full screen recording. // TODO: Find a way to detect hardware encoding support. // Hardware encoding is supported on 6th gen Intel processor or newer. if let videoCodec = videoCodec { output.setOutputSettings([AVVideoCodecKey: videoCodec], for: output.connection(with: .video)!) } super.init() } // TODO: When targeting macOS 10.13, make the `videoCodec` option the type `AVVideoCodecType`. /** Start a capture session with the given screen ID. Use `Aperture.Devices.screen()` to get a list of available screens. - Parameter destination: The destination URL where the captured video will be saved. Needs to be writable by current user. - Parameter framesPerSecond: The frames per second to be used for this capture. - Parameter cropRect: Optionally the screen capture can be cropped. Pass a `CGRect` to this initializer representing the crop area. - Parameter showCursor: Whether to show the cursor in the captured video. - Parameter highlightClicks: Whether to highlight clicks in the captured video. - Parameter screenId: The ID of the screen to be captured. - Parameter audioDevice: An optional audio device to capture. - Parameter videoCodec: The video codec to use when capturing. */ public convenience init( destination: URL, framesPerSecond: Int = 60, cropRect: CGRect? = nil, showCursor: Bool = true, highlightClicks: Bool = false, screenId: CGDirectDisplayID = .main, audioDevice: AVCaptureDevice? = .default(for: .audio), videoCodec: String? = nil ) throws { let input = try AVCaptureScreenInput(displayID: screenId).unwrapOrThrow(Error.invalidScreen) input.minFrameDuration = CMTime(videoFramesPerSecond: framesPerSecond) if let cropRect = cropRect { input.cropRect = cropRect } input.capturesCursor = showCursor input.capturesMouseClicks = highlightClicks try self.init( destination: destination, input: input, output: AVCaptureMovieFileOutput(), audioDevice: audioDevice, videoCodec: videoCodec ) } /** Start a capture session with the given iOS device. Use `Aperture.Devices.iOS()` to get a list of connected iOS devices and use the `.id` property to create an `AVCaptureDevice`: ``` AVCaptureDevice(uniqueID: id) ``` The frame rate is 60 frames per second. - Parameter destination: The destination URL where the captured video will be saved. Needs to be writable by current user. - Parameter iosDevice: The iOS device to capture. - Parameter audioDevice: An optional audio device to capture. - Parameter videoCodec: The video codec to use when capturing. */ public convenience init( destination: URL, iosDevice: AVCaptureDevice, audioDevice: AVCaptureDevice? = nil, videoCodec: String? = nil ) throws { let input = try AVCaptureDeviceInput(device: iosDevice) try self.init( destination: destination, input: input, output: AVCaptureMovieFileOutput(), audioDevice: audioDevice, videoCodec: videoCodec ) } public func start() { session.startRunning() output.startRecording(to: destination, recordingDelegate: self) } public func stop() { output.stopRecording() // This prevents a race condition in Apple's APIs with the above and below calls. sleep(for: 0.1) self.session.stopRunning() } public func pause() { output.pauseRecording() } public func resume() { output.resumeRecording() } } extension Aperture: AVCaptureFileOutputRecordingDelegate { private var shouldPreventSleep: Bool { get { activity != nil } set { if newValue { activity = ProcessInfo.processInfo.beginActivity(options: .idleSystemSleepDisabled, reason: "Recording screen") } else if let activity = activity { ProcessInfo.processInfo.endActivity(activity) self.activity = nil } } } public func fileOutput(_ captureOutput: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { shouldPreventSleep = true onStart?() } public func fileOutput(_ captureOutput: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Swift.Error?) { shouldPreventSleep = false onFinish?(error) } public func fileOutput(_ output: AVCaptureFileOutput, didPauseRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { shouldPreventSleep = false onPause?() } public func fileOutput(_ output: AVCaptureFileOutput, didResumeRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { shouldPreventSleep = true onResume?() } public func fileOutputShouldProvideSampleAccurateRecordingStart(_ output: AVCaptureFileOutput) -> Bool { true } }
mit
f4f5ea60e5321d0009fe6a2b423d601f
29.089623
166
0.746669
4.02969
false
false
false
false
shintarogit/wcsession_rx
Demo/Demo WatchKit Extension/InterfaceController.swift
1
2854
// // InterfaceController.swift // Demo WatchKit Extension // // Created by Inomoto Shintaro on 2017/03/08. // Copyright © 2017年 Shintaro Inomoto. All rights reserved. // import WatchKit import Foundation import RxSwift import WatchConnectivity class InterfaceController: WKInterfaceController { @IBOutlet var parentDeviceLabel: WKInterfaceLabel! @IBOutlet private var connectivityLabel: WKInterfaceLabel! @IBOutlet private var sayHelloButton: WKInterfaceButton! private var disposer: Disposable? private var disposer2: Disposable? override func awake(withContext context: Any?) { super.awake(withContext: context) self.parentDeviceLabel.setText(nil) disposer = WCSession.default .rx.activationState .do(onNext: { self.sayHelloButton.setHidden(!($0 == .activated)) }, onError: nil, onCompleted: nil, onSubscribe: nil, onDispose: nil) .subscribe(onNext: { switch($0){ case .activated: self.connectivityLabel.setText("Active.") case .inactive: self.connectivityLabel.setText("Inactive.") case .notActivated: self.connectivityLabel.setText("Not activated.") } }, onError: { self.connectivityLabel.setText("Error !! \($0.localizedDescription)") }, onCompleted: { }) { self.connectivityLabel.setText("Canceled.") } disposer2 = WCSession.default .rx.didReceiveMessage .subscribe(onNext: { guard let message = MessageConverter.message(from: $0) else { return } self.parentDeviceLabel.setText(message + " @" + Date().description) }, onError: { self.parentDeviceLabel.setText("Error !! \($0.localizedDescription)") }, onCompleted: { }) { self.parentDeviceLabel.setText("Canceled.") } } @IBAction func sayHelloButtonDidTouchUp() { WCSession.default .sendMessage(MessageConverter.userInfo(from: "Hello !!"), replyHandler: { _ in }, errorHandler: { _ in }) } override func willActivate() { super.willActivate() WCSession.default.activate() } deinit { disposer?.dispose() disposer2?.dispose() } }
mit
09e0de40b068a6f44c94584d047f778f
28.091837
85
0.507541
5.866255
false
false
false
false
JKapanke/worldvisitor
WorldVisitor/Dice.swift
2
756
// // Dice.swift // WorldTraveler // // Created by Jason Kapanke on 12/2/14. // Copyright (c) 2014 Better Things. All rights reserved. // import Foundation import AVFoundation class Dice { let minValue = 1 let maxValue = 6 var audioPlayer = AVAudioPlayer() var currentValue = 1 func rollDice() -> Int { currentValue = Int(arc4random_uniform(6) + 1) return currentValue } func getCurrentValue() -> Int { return currentValue } func playRollingDiceSound() { let soundURL = NSBundle.mainBundle().URLForResource("diceShake", withExtension: "wav") audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil) audioPlayer.play() } }
gpl-2.0
8d26332d4775518d7287d895cd5a37eb
19.432432
94
0.621693
4.295455
false
false
false
false
sunfei/RxSwift
RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift
12
6043
// // RecursiveScheduler.swift // RxSwift // // Created by Krunoslav Zaher on 6/7/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class RecursiveScheduler<State, S: Scheduler>: RecursiveSchedulerOf<State, S.TimeInterval> { let scheduler: S init(scheduler: S, action: Action) { self.scheduler = scheduler super.init(action: action) } override func scheduleRelativeAdapter(state: State, dueTime: S.TimeInterval, action: (State) -> RxResult<Disposable>) -> RxResult<Disposable> { return scheduler.scheduleRelative(state, dueTime: dueTime, action: action) } override func scheduleAdapter(state: State, action: (State) -> RxResult<Disposable>) -> RxResult<Disposable> { return scheduler.schedule(state, action: action) } } public class RecursiveSchedulerOf<State, TimeInterval> : Disposable { public typealias ScheduleRelative = (State, TimeInterval) -> Void public typealias ScheduleImmediate = (State) -> Void typealias Action = (state: State, scheduler: RecursiveSchedulerOf<State, TimeInterval>) -> Void let lock = NSRecursiveLock() let group = CompositeDisposable() var action: Action? init(action: Action) { self.action = action } // abstract methods func scheduleRelativeAdapter(state: State, dueTime: TimeInterval, action: (State) -> RxResult<Disposable>) -> RxResult<Disposable> { return abstractMethod() } func scheduleAdapter(state: State, action: (State) -> RxResult<Disposable>) -> RxResult<Disposable> { return abstractMethod() } // relative scheduling public func schedule(state: State, dueTime: TimeInterval) { var isAdded = false var isDone = false var removeKey: CompositeDisposable.DisposeKey? = nil let d = scheduleRelativeAdapter(state, dueTime: dueTime) { (state) -> RxResult<Disposable> in // best effort if self.group.disposed { return NopDisposableResult } let action = self.lock.calculateLocked { () -> Action? in if isAdded { self.group.removeDisposable(removeKey!) } else { isDone = true } return self.action } if let action = action { action(state: state, scheduler: self) } return NopDisposableResult } ensureScheduledSuccessfully(d.map { disposable in lock.performLocked { if !isDone { removeKey = group.addDisposable(d.get()) isAdded = true } } return () }) } // immediate scheduling public func schedule(state: State) { var isAdded = false var isDone = false var removeKey: CompositeDisposable.DisposeKey? = nil let d = scheduleAdapter(state) { (state) -> RxResult<Disposable> in // best effort if self.group.disposed { return NopDisposableResult } let action = self.lock.calculateLocked { () -> Action? in if isAdded { self.group.removeDisposable(removeKey!) } else { isDone = true } return self.action } if let action = action { action(state: state, scheduler: self) } return NopDisposableResult } ensureScheduledSuccessfully(d.map { disposable in lock.performLocked { if !isDone { removeKey = group.addDisposable(d.get()) isAdded = true } } return () }) } public func dispose() { self.lock.performLocked { self.action = nil } self.group.dispose() } } class RecursiveImmediateSchedulerOf<State> : Disposable { typealias Action = (state: State, recurse: State -> Void) -> Void var lock = SpinLock() let group = CompositeDisposable() var action: Action? let scheduler: ImmediateScheduler init(action: Action, scheduler: ImmediateScheduler) { self.action = action self.scheduler = scheduler } // immediate scheduling func schedule(state: State) { var isAdded = false var isDone = false var removeKey: CompositeDisposable.DisposeKey? = nil let d = self.scheduler.schedule(state) { (state) -> RxResult<Disposable> in // best effort if self.group.disposed { return NopDisposableResult } let action = self.lock.calculateLocked { () -> Action? in if isAdded { self.group.removeDisposable(removeKey!) } else { isDone = true } return self.action } if let action = action { action(state: state, recurse: self.schedule) } return NopDisposableResult } ensureScheduledSuccessfully(d.map { disposable in lock.performLocked { if !isDone { removeKey = group.addDisposable(d.get()) isAdded = true } } return () }) } func dispose() { self.lock.performLocked { self.action = nil } self.group.dispose() } }
mit
9fc6ff04c13f76cd7aab573ae7b5ad6a
27.780952
147
0.519113
5.473732
false
false
false
false
albertjo/FitbitSwift
FitbitSwift/Classes/FitbitAuthManager.swift
1
8513
// // SwiftBit.swift // Pods // // Created by Albert Jo on 5/12/16. // // import Locksmith import SwiftyJSON import Alamofire let ACCOUNT = "authentiated user" let SERVICE = "Fitbit" public enum FitbitScope: String { case activity, heartrate, location, nutrition, profile, settings, sleep, social, weight public static func all() -> [FitbitScope] { return [FitbitScope.activity, FitbitScope.heartrate, FitbitScope.location, FitbitScope.nutrition, FitbitScope.profile, FitbitScope.settings, FitbitScope.sleep, FitbitScope.social, FitbitScope.weight] } public static func generateUrlString(scopes: Array<FitbitScope>) -> String { return getStringArray(scopes).joinWithSeparator("%20") } public static func getStringArray(scopes: Array<FitbitScope>) -> [String] { var array = [String]() for scope in scopes { array.append(scope.rawValue) } return array } } struct FitbitOAuthKeys: CreateableSecureStorable, GenericPasswordSecureStorable, DeleteableSecureStorable, ReadableSecureStorable { let accessToken : String let refreshToken : String let expiresIn : Int let dateCreated : NSDate static var sharedInstance : FitbitOAuthKeys? { if let data = Locksmith.loadDataForUserAccount(ACCOUNT, inService: SERVICE) { return FitbitOAuthKeys(accessToken: data["access_token"] as! String, refreshToken: data["refresh_token"] as! String, expiresIn: data["expires_in"] as! Int, dateCreated: data["date_created"] as! NSDate) } return nil } // Required by GenericPasswordSecureStorable let service = SERVICE let account = ACCOUNT // Required by CreateableSecureStorable var data: [String: AnyObject] { return ["access_token": accessToken, "refresh_token": refreshToken, "expires_in": expiresIn, "date_created": dateCreated] } } public class FitbitAuthManager { var OAuthTokenCompletionHandler:(NSError? -> Void)? var clientID: String var clientSecret: String var redirectUrl: String var authorizeUrl = "https://www.fitbit.com/oauth2/authorize" var accessTokenUrl = "https://api.fitbit.com/oauth2/token" var scope : [FitbitScope] = FitbitScope.all() var oauthKeys : FitbitOAuthKeys? { return FitbitOAuthKeys.sharedInstance } var authorizationHeader : [String : String] { return [ "Authorization": "Bearer \(oauthKeys!.accessToken))" ] } var authorizationCode : String { return convertToBase64("\(clientID):\(clientSecret)") } // MARK: Initializer public init(clientID: String, clientSecret: String, redirectUrl: String, scope : [FitbitScope]?) { self.clientID = clientID self.clientSecret = clientSecret self.redirectUrl = redirectUrl if let _scope = scope { self.scope = _scope } } // MARK: Authentication func beginOAuthRequest() { let escapedCallbackURL = escapedString(redirectUrl) let authPath = "https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=\(clientID)&redirect_uri=\(escapedCallbackURL)&scope=\(FitbitScope.generateUrlString(scope))&expires_in=604800" if let authURL:NSURL = NSURL(string: authPath) { UIApplication.sharedApplication().openURL(authURL) } } func processOAuthResponse(url: NSURL) { let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) guard components != nil else { return } guard let code = components!.code else { return } let headers = [ "Authorization": "Basic \(authorizationCode)", "Content-Type": "application/x-www-form-urlencoded" ] let parameters = [ "grant_type":"authorization_code", "client_id":clientID, "redirect_uri":redirectUrl, "code":code ] Alamofire.request(.POST, accessTokenUrl, parameters: parameters, headers: headers) .validate() .responseJSON { response in var requestError : NSError? switch response.result { case .Success: if let value = response.result.value { self.saveOAuthKeys(JSON(value)) } case .Failure(let error): requestError = error } // Execute completion handler if let completionHandler = self.OAuthTokenCompletionHandler { completionHandler(requestError) } } } func isAuthenticated() -> Bool { return oauthKeys != nil } public func deleteOAuthToken() -> Bool { if oauthKeys != nil { do { if Locksmith.loadDataForUserAccount(ACCOUNT, inService: SERVICE) != nil { try Locksmith.deleteDataForUserAccount(ACCOUNT, inService: SERVICE) return true } } catch { handleKeychainError(error) } } return false } public func refreshAccessToken(callbackFunction: ((NSError?) -> Void)?) { let headers = [ "Authorization": "Basic \(authorizationCode)", "Content-Type": "application/x-www-form-urlencoded" ] let parameters = [ "grant_type":"refresh_token", "refresh_token":"\(oauthKeys!.refreshToken)" ] Alamofire.request(.POST, accessTokenUrl, parameters: parameters, headers: headers) .validate() .responseJSON { response in var requestError : NSError? switch response.result { case .Success: if let value = response.result.value { self.saveOAuthKeys(JSON(value)) } case .Failure(let error): requestError = error } // if callback function is provided, call it if let callback = callbackFunction { callback(requestError) } } } private func handleOAuthError(error : ErrorType) { } private func saveOAuthKeys(json : JSON) { let accessToken = json["access_token"].string! let refreshToken = json["refresh_token"].string! let expiresIn = json["expires_in"].int! let oauthKeys = FitbitOAuthKeys(accessToken: accessToken, refreshToken: refreshToken, expiresIn: expiresIn, dateCreated: NSDate()) do { /// first, check if OAuth keys have already been stored, and delete old keys if Locksmith.loadDataForUserAccount(ACCOUNT, inService: SERVICE) != nil{ try Locksmith.deleteDataForUserAccount(ACCOUNT, inService: SERVICE) } /// save new keys try oauthKeys.createInSecureStore() } catch { handleKeychainError(error) } } // TODO: private func handleKeychainError(error: ErrorType) { } // MARK: Helper methods private func escapedString(str : String) -> String { return str.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! } private func convertToBase64(str : String) -> String { let data = str.dataUsingEncoding(NSUTF8StringEncoding) return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) } } extension NSURLComponents { var queryItemDictionary: [String : String] { var results = [String: String]() if queryItems != nil { for queryItem in queryItems! { results[queryItem.name.lowercaseString] = queryItem.value } } return results } var code: String? { if let _code = queryItemDictionary["code"] { return _code } return nil } }
mit
40f14d7cd79814480c406d045b64ffc9
32.388235
204
0.57559
5.175076
false
false
false
false
ffont/BBC6Music
BBC 6Music/ViewController-iOS.swift
1
1527
// // ViewController-iOS.swift // BBC 6 Music // // Created by Frederic Font Corbera on 30/12/15. // Copyright © 2015 Frederic Font Corbera. All rights reserved. // import Foundation import UIKit class BBC6MusicViewController_iOS: BBC6MusicViewController { @IBOutlet weak var label: UITextView! @IBOutlet weak var logo: UIImageView! @IBOutlet weak var programNameLabel: UITextView! override func setLogoAlpha(_ alpha: CGFloat) { self.logo.alpha = alpha } override func setLabelText(_ text: String) { self.label.text = text } override func setProgrameNameLabelText(_ text: String) { self.programNameLabel.text = text } override func adaptSizes(){ // Also reduce logo size //let screenSize: CGRect = UIScreen.mainScreen().bounds //self.logo.frame = CGRectMake(0,0, screenSize.height * 0.2, 50) //self.logo.setNeedsLayout() //self.logo.setNeedsDisplay() switch UIDevice.current.userInterfaceIdiom { case .phone: // If device is iPhone, reduce label and programNameLabel font sizes self.label.font = UIFont.systemFont(ofSize: 18) self.programNameLabel.font = UIFont.systemFont(ofSize: 24) case .pad: break default: break } } // MARK: UI actions @IBAction func onPressLogo(_ sender: UIButton) { self.togglePlayPause() } }
cc0-1.0
2634f865175244b38bd564f3266ae9ac
27.792453
84
0.610092
4.461988
false
false
false
false
kingcos/Swift-X-Algorithms
LeetCode/101-Symmetric-Tree/101-Symmetric-Tree.playground/Contents.swift
1
988
import UIKit /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } class Solution { // 20 ms func isSymmetric(_ root: TreeNode?) -> Bool { func isSymmetricNodes(_ a: TreeNode?, _ b: TreeNode?) -> Bool { if a == nil && b == nil { return true } if a == nil || b == nil { return false } return a?.val == b?.val && isSymmetricNodes(a?.left, b?.right) && isSymmetricNodes(a?.right, b?.left) } return isSymmetricNodes(root, root) } }
mit
7556bcd74db42970f7dfc76edc709265
24.333333
113
0.526316
3.756654
false
false
false
false
openHPI/xikolo-ios
Common/Data/Helper/FetchRequests/CourseItemHelper+FetchRequests.swift
1
2664
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import CoreData extension CourseItemHelper { public enum FetchRequest { static func courseItems(forCourse course: Course) -> NSFetchRequest<CourseItem> { let request: NSFetchRequest<CourseItem> = CourseItem.fetchRequest() request.predicate = NSPredicate(format: "section.course = %@", course) return request } public static func orderedCourseItems(forCourse course: Course) -> NSFetchRequest<CourseItem> { let request = self.courseItems(forCourse: course) let sectionSort = NSSortDescriptor(keyPath: \CourseItem.section?.position, ascending: true) let positionSort = NSSortDescriptor(keyPath: \CourseItem.position, ascending: true) request.sortDescriptors = [sectionSort, positionSort] return request } static func orderedCourseItems(forSection section: CourseSection) -> NSFetchRequest<CourseItem> { let request: NSFetchRequest<CourseItem> = CourseItem.fetchRequest() request.predicate = NSPredicate(format: "section = %@", section) let titleSort = NSSortDescriptor(keyPath: \CourseItem.position, ascending: true) request.sortDescriptors = [titleSort] return request } public static func courseItem(withId courseItemId: String) -> NSFetchRequest<CourseItem> { let request: NSFetchRequest<CourseItem> = CourseItem.fetchRequest() request.predicate = NSPredicate(format: "id == %@", courseItemId) request.fetchLimit = 1 return request } static func courseItems(forCourse course: Course, withContentType type: String) -> NSFetchRequest<CourseItem> { let request: NSFetchRequest<CourseItem> = CourseItem.fetchRequest() request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [ NSPredicate(format: "section.course = %@", course), NSPredicate(format: "contentType = %@", type), ]) return request } static func courseItems(forSection section: CourseSection, withContentType type: String) -> NSFetchRequest<CourseItem> { let request: NSFetchRequest<CourseItem> = CourseItem.fetchRequest() request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [ NSPredicate(format: "section = %@", section), NSPredicate(format: "contentType = %@", type), ]) return request } } }
gpl-3.0
cd331de61075a7fd64b88b1b0044e413
42.655738
128
0.647766
5.315369
false
false
false
false
codeOfRobin/Components-Personal
Sources/AgentPickerDataSource.swift
1
2122
// // AgentPickerDataSource.swift // BuildingBlocks-iOS // // Created by Robin Malhotra on 07/09/17. // Copyright © 2017 BuildingBlocks. All rights reserved. // import AsyncDisplayKit import RxSwift import Dwifft class AgentPickerDataSource: NSObject, ASTableDataSource { var agents: [AgentViewModel] = [] { didSet { let (inserts, deletes) = Dwifft.destructuredDiff(oldValue, agents, section: 1) tableNode?.performBatchUpdates({ tableNode?.insertRows(at: inserts, with: .fade) tableNode?.deleteRows(at: deletes, with: .fade) }, completion: nil) } } var team: TeamViewModel? = nil { didSet { switch (oldValue, team) { case (nil, .some(_)): tableNode?.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .fade) case (.some(_), nil): tableNode?.deleteRows(at: [IndexPath.init(row: 0, section: 0)], with: .fade) case (.some(_), .some(_)): tableNode?.reloadRows(at: [IndexPath.init(row: 0, section: 0)], with: .fade) default: break } } } let disposeBag = DisposeBag() weak var tableNode: ASTableNode? init(teamObservable: Observable<TeamViewModel?>, agentsObservable: Observable<[AgentViewModel]>, tableNode: ASTableNode?) { super.init() self.tableNode = tableNode teamObservable.subscribe(onNext: { [weak self] (team) in self?.team = team }).disposed(by: disposeBag) agentsObservable.subscribe(onNext: { [weak self] (agents) in self?.agents = agents }).disposed(by: disposeBag) } func numberOfSections(in tableNode: ASTableNode) -> Int { return 2 } func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return team == nil ? 0 : 1 case 1: return agents.count default: return 0 } } func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode { switch indexPath.section { case 0: return OptionNode(contentNode: DefaultTextNode(text: team?.label ?? "-")) case 1: return OptionNode(contentNode: AgentCellNode(agentViewModel: agents[indexPath.row])) default: return ASCellNode() } } }
mit
990010f6a7a1bfc7dbe90762c670280e
25.848101
124
0.685997
3.460033
false
false
false
false
JoMo1970/cordova-plugin-qrcode-reader
src/ios/QrCodeReader.swift
1
5989
import Foundation import AVFoundation import UIKit @objc(QrCodeReader) class QrCodeReader : CDVPlugin, QRCodeReaderViewControllerDelegate { //private variables var newCommand : CDVInvokedUrlCommand? = CDVInvokedUrlCommand() lazy var reader: QRCodeReaderApp = QRCodeReaderApp() lazy var readerVC: QRCodeReaderViewController = { let builder = QRCodeReaderViewControllerBuilder { $0.reader = QRCodeReaderApp(metadataObjectTypes: [AVMetadataObjectTypeQRCode], captureDevicePosition: .back) $0.showTorchButton = false $0.showSwitchCameraButton = false $0.showOverlayView = false } return QRCodeReaderViewController(builder: builder) }() //this function will validate if a certificate is installed within the app file structure or in the keychain of the device @objc(launchqrreader:) func launchqrreader(command: CDVInvokedUrlCommand) { //set the local command variable self.newCommand = command //init scan modal self.scanInModalAction() } func resizeView(rawView: UIView) { let rect: CGRect = CGRect(x: 0, y: 0, width: rawView.bounds.width, height: rawView.bounds.height) var innerRect = rect.insetBy(dx: 50, dy: 50) let minSize = min(innerRect.width, innerRect.height) if innerRect.width != minSize { innerRect.origin.x += (innerRect.width - minSize) / 2 innerRect.size.width = minSize } else if innerRect.height != minSize { innerRect.origin.y += (innerRect.height - minSize) / 2 innerRect.size.height = minSize } //resize the current view controller rawView.frame = innerRect } //this function will check camera permissions private func checkScanPermissions() -> Bool { do { return try QRCodeReaderApp.supportsMetadataObjectTypes() } catch let error as NSError { let alert: UIAlertController? switch error.code { case -11852: alert = UIAlertController(title: "Error", message: "This app is not authorized to use Back Camera.", preferredStyle: .alert) alert?.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (_) in DispatchQueue.main.async { if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(settingsURL) } } })) alert?.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) case -11814: alert = UIAlertController(title: "Error", message: "Reader not supported by the current device", preferredStyle: .alert) alert?.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) default: alert = nil } guard let vc = alert else { return false } self.viewController.present(vc, animated: true, completion: nil) return false } } func scanInModalAction() { //check permissions, then add reader view controller guard checkScanPermissions() else { return } //init readerVC presentation options readerVC.view.backgroundColor = UIColor.clear; readerVC.view.isOpaque = false readerVC.modalPresentationStyle = .overCurrentContext readerVC.delegate = self //init completion callback readerVC.completionBlock = { (result: QRCodeReaderResult?) in if let result = result { print("Completion with result: \(result.value) of type \(result.metadataType)") //init plugin result var response: Dictionary = ["success" : true, "secret" : result.value ] as [String : Any] var pluginResult = CDVPluginResult( status: CDVCommandStatus_OK, messageAs: response ) //send the callback object back print("Sending back cordova response") self.commandDelegate!.send( pluginResult, callbackId: self.newCommand?.callbackId ) } } self.viewController.present(readerVC, animated: true, completion: nil) } func scanInPreviewAction() { guard checkScanPermissions(), !reader.isRunning else { return } /*previewView.setupComponents(showCancelButton: false, showSwitchCameraButton: false, showTorchButton: false, showOverlayView: true, reader: reader) reader.startScanning() reader.didFindCode = { result in let alert = UIAlertController( title: "QRCodeReader", message: String (format:"%@ (of type %@)", result.value, result.metadataType), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) }*/ } func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) { reader.stopScanning() self.viewController.dismiss(animated: true) { [weak self] in print("The camera view has dismissed") /*let alert = UIAlertController( title: "QRCodeReader", message: String (format:"%@ (of type %@)", result.value, result.metadataType), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self?.viewController.present(alert, animated: true, completion: nil)*/ } } func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) { if let cameraName = newCaptureDevice.device.localizedName { print("Switching capturing to: \(cameraName)") } } func readerDidCancel(_ reader: QRCodeReaderViewController) { reader.stopScanning() self.viewController.dismiss(animated: true, completion: nil) } }
mit
3be2002433753241d33e320fb13e0718
35.078313
154
0.636667
5.062553
false
false
false
false
SPECURE/rmbt-ios-client
Sources/RMBTZeroMeasurementSynchronizer.swift
1
3704
// // RMBTZeroMeasurementSynchronizer.swift // Pods // // Created by Sergey Glushchenko on 10/4/17. // import Alamofire open class RMBTZeroMeasurementSynchronizer: NSObject { public static let shared = RMBTZeroMeasurementSynchronizer() var timer: Timer? private let worker = DispatchQueue(label: "RMBTZeroMeasurementSynchronizer worker") private let duration: TimeInterval = 60.0 //seconds private var isSynchronizating = false private var reachabilityManager = NetworkReachabilityManager() deinit { defer { if timer?.isValid == true { timer?.invalidate() } } } override init() { super.init() } open func startSynchronization() { if timer?.isValid == true { timer?.invalidate() } reachabilityManager?.startListening(onUpdatePerforming: { [weak self] (status) in guard let self = self else { return } if (status != .notReachable) { self.tick(timer: self.timer) } }) timer = Timer.scheduledTimer(timeInterval: self.duration, target: self, selector: #selector(tick(timer:)), userInfo: nil, repeats: true) self.tick(timer: timer) } open func stopSynchronization() { if timer?.isValid == true { timer?.invalidate() } reachabilityManager?.stopListening() } @objc func tick(timer: Timer?) { if (isSynchronizating == false) { self.isSynchronizating = true if let zeroMeasurements = StoredZeroMeasurement.loadObjects() { var measurements: [ZeroMeasurementRequest] = [] var measurementsForDelete: [StoredZeroMeasurement] = [] for zeroMeasurement in zeroMeasurements { if let _ = zeroMeasurement.speedMeasurementResult() { measurements.append(ZeroMeasurementRequest(measurement: zeroMeasurement)) } else { measurementsForDelete.append(zeroMeasurement) } } if measurements.count > 0 { ZeroMeasurementRequest.submit(zeroMeasurements: measurements, success: { [weak self] (response) in DispatchQueue.main.async { for measurement in zeroMeasurements { measurement.deleteObject() } self?.isSynchronizating = false self?.tick(timer: self?.timer) } }, error: { [weak self] (error) in self?.isSynchronizating = false }) } else { if measurementsForDelete.count > 0 { DispatchQueue.main.async { for measurement in measurementsForDelete { measurement.deleteObject() self.isSynchronizating = false DispatchQueue.main.async { self.tick(timer: self.timer) } } } } else { self.isSynchronizating = false } } } else { self.isSynchronizating = true } } } }
apache-2.0
6ccffef955cf6bcf43134ecd9e6cef58
32.672727
144
0.482451
5.898089
false
false
false
false
kinetic-fit/sensors-swift-trainers
Sources/SwiftySensorsTrainers/CycleOpsSerializer.swift
1
2777
// // CycleOpsSerializer.swift // SwiftySensorsTrainers // // https://github.com/kinetic-fit/sensors-swift-trainers // // Copyright © 2017 Kinetic. All rights reserved. // import Foundation import SwiftySensors /// :nodoc: open class CycleOpsSerializer { public class Response { fileprivate(set) var mode: ControlMode = .headless fileprivate(set) var status: ControlStatus = .speedOkay fileprivate(set) var parameter1: Int16 = 0 fileprivate(set) var parameter2: Int16 = 0 } public enum ControlMode: UInt8 { case headless = 0x00 case manualPower = 0x01 case manualSlope = 0x02 case powerRange = 0x03 case warmUp = 0x04 case rollDown = 0x05 } public enum ControlStatus: UInt8 { case speedOkay = 0x00 case speedUp = 0x01 case speedDown = 0x02 case rollDownInitializing = 0x03 case rollDownInProcess = 0x04 case rollDownPassed = 0x05 case rollDownFailed = 0x06 } public static func setControlMode(_ mode: ControlMode, parameter1: Int16 = 0, parameter2: Int16 = 0) -> [UInt8] { return [ 0x00, 0x10, mode.rawValue, UInt8(parameter1 & 0xFF), UInt8(parameter1 >> 8 & 0xFF), UInt8(parameter2 & 0xFF), UInt8(parameter2 >> 8 & 0xFF), 0x00, 0x00, 0x00 ] } public static func readReponse(_ data: Data) -> Response? { let bytes = data.map { $0 } var index: Int = 0 if bytes.count > 9 { let _ = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 // response code let commandIdRaw = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 if commandIdRaw == 0x1000 { let controlRaw = bytes[index++=] let parameter1 = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8 let parameter2 = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8 let statusRaw = bytes[index++=] if let controlMode = CycleOpsSerializer.ControlMode(rawValue: controlRaw) { if let status = CycleOpsSerializer.ControlStatus(rawValue: statusRaw) { let response = Response() response.mode = controlMode response.status = status response.parameter1 = parameter1 response.parameter2 = parameter2 return response } } } } return nil } }
mit
d88f8d9b896b5052e82c254c12ab6c91
33.7
117
0.525216
4.212443
false
false
false
false
hinoppy/MappingJSON
MappingJSON/MappingJSON.swift
1
3973
// // MappingJSON.swift // MappingJSON // // Created by Shinya Hino on 12/24/15. // Copyright © 2015 Shinya Hino. All rights reserved. // import Foundation public class MappingJSON { enum Error: ErrorType { case ValueForKeyNotFound(key: String) case TypeMismatch(key: String, value: AnyObject, actualType: AnyObject.Type) case UnwrapNil } private var raw: [String: AnyObject] public init(raw: [String: AnyObject]) { self.raw = raw } public init(raw: [String: AnyObject], keyPath: [String]) throws { self.raw = raw if keyPath.isEmpty { return } for key in keyPath { self.raw = try self.value(key) } } public func value<T>(key: String) throws -> T { // get and unwrap value for key guard let rawValue = self.raw[key] else { throw Error.ValueForKeyNotFound(key: key) } if rawValue is NSNull { throw Error.ValueForKeyNotFound(key: key) } // cast value to T guard let value = rawValue as? T else { throw Error.TypeMismatch(key: key, value: rawValue, actualType: rawValue.dynamicType) } return value } public func optionalValue<T>(key: String) throws -> T? { do { let value: T = try self.value(key) return value } catch Error.ValueForKeyNotFound(_) { return nil } } public func value<T: Object where T.ObjectType == T>(key: String) throws -> T { guard let rawValue = self.raw[key] else { throw Error.ValueForKeyNotFound(key: key) } if rawValue is NSNull { throw Error.ValueForKeyNotFound(key: key) } guard let value = rawValue as? [String: AnyObject] else { throw Error.TypeMismatch(key: key, value: rawValue, actualType: rawValue.dynamicType) } return try MappingJSON(raw: value).map(T) } public func value<T: Object where T.ObjectType == T>(key: String) throws -> [T] { guard let rawValue = self.raw[key] else { throw Error.ValueForKeyNotFound(key: key) } if rawValue is NSNull { throw Error.ValueForKeyNotFound(key: key) } guard let values = rawValue as? [[String: AnyObject]] else { throw Error.TypeMismatch(key: key, value: rawValue, actualType: rawValue.dynamicType) } return try values.map { (value) -> T in try MappingJSON(raw: value).map(T) } } public func optionalValue<T: Object where T.ObjectType == T>(key: String) throws -> T? { do { let value: T = try self.value(key) return value } catch Error.ValueForKeyNotFound(_) { return nil } } public func optionalValue<T: Object where T.ObjectType == T>(key: String) throws -> [T]? { do { let values: [[String: AnyObject]] = try self.value(key) return try values.map { (value) -> T in try MappingJSON(raw: value).map(T) } } catch Error.ValueForKeyNotFound(_) { return nil } } public func map<T: Object where T.ObjectType == T>(type: T.Type) throws -> T { return try T.map(self) } public func value<T, U>(key: String, transform: (U) -> T?) throws -> T { let rawValue: U = try self.value(key) guard let value = transform(rawValue) else { throw Error.UnwrapNil } return value } public func optionalValue<T, U>(key: String, transform: (U) -> T?) throws -> T? { do { let value = try self.value(key, transform: transform) return value } catch Error.ValueForKeyNotFound(_) { return nil } catch Error.UnwrapNil { return nil } } }
mit
e25832e7c2bbb067f6c9994d8026c058
30.531746
97
0.556898
4.275565
false
false
false
false
Moliholy/devslopes-smack-animation
Smack/View/GradientView.swift
1
960
// // GradientView.swift // Smack // // Created by Jonny B on 7/14/17. // Copyright © 2017 Jonny B. All rights reserved. // import UIKit @IBDesignable class GradientView: UIView { @IBInspectable var topColor: UIColor = #colorLiteral(red: 0.3631127477, green: 0.4045833051, blue: 0.8775706887, alpha: 1) { didSet { self.setNeedsLayout() } } @IBInspectable var bottomColor: UIColor = #colorLiteral(red: 0.1725490196, green: 0.831372549, blue: 0.8470588235, alpha: 1) { didSet { self.setNeedsLayout() } } override func layoutSubviews() { let gradientLayer = CAGradientLayer() gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor] gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 1) gradientLayer.frame = self.bounds self.layer.insertSublayer(gradientLayer, at: 0) } }
bsd-2-clause
2d4bc6744f5d7064b912451434720864
27.205882
130
0.631908
3.866935
false
false
false
false
zhangzichen/Pontus
Pontus/UIKit+Pontus/UIScrollView+Pontus.swift
1
4059
import UIKit public extension UIScrollView { var offsetX : CGFloat { get { return contentOffset.x } set { contentOffset.x = newValue } } var offsetY : CGFloat { get { return contentOffset.y } set { contentOffset.y = newValue } } var contentSizeHeight : CGFloat { get { return contentSize.height } set { contentSize.height = newValue } } var contentSizeWidth : CGFloat { get { return contentSize.width } set { contentSize.width = newValue } } var insetTop : CGFloat { get { return contentInset.top } set { contentInset.top = newValue scrollIndicatorInsets.top = newValue } } var insetBottom : CGFloat { get { return contentInset.bottom } set { contentInset.bottom = newValue scrollIndicatorInsets.bottom = newValue } } func delegate(_ delegate: UIScrollViewDelegate) -> Self { self.delegate = delegate return self } func contentInsetTop(_ top:CGFloat) -> Self { insetTop = top return self } func contentInsetBottom(_ bottom:CGFloat) -> Self { insetBottom = bottom return self } func contentInsetLeft(_ left:CGFloat) -> Self { self.contentInset.left = left return self } func contentInsetRight(_ right:CGFloat) -> Self { self.contentInset.right = right return self } func insetBottom(_ bottom : CGFloat) -> Self { insetBottom = bottom scrollIndicatorInsets.bottom = bottom return self } func offsetX(_ offsetX:CGFloat) -> Self { self.offsetX = offsetX return self } func offsetY(_ offsetY : CGFloat) -> Self { self.offsetY = offsetY return self } func insetTop(_ top : CGFloat) -> Self { insetTop = top scrollIndicatorInsets.top = top return self } func bounces(_ bounces : Bool) -> Self { self.bounces = bounces return self } func contentSize(_ size : CGSize) -> Self { contentSize = size return self } func contentSize(_ width:CGFloat, height:CGFloat) -> Self { contentSize = CGSize(width: width, height: height) return self } func contentInset(_ contentInset : UIEdgeInsets) -> Self { self.contentInset = contentInset return self } func scrollIndicatorInsets(_ scrollIndicatorInsets : UIEdgeInsets) -> Self { self.scrollIndicatorInsets = scrollIndicatorInsets return self } func contentOffset(_ contentOffset : CGPoint) -> Self { self.contentOffset = contentOffset return self } func alwaysBounceHorizontal(_ alwaysBounceHorizontal : Bool) -> Self { self.alwaysBounceHorizontal = alwaysBounceHorizontal return self } func alwaysBounceVertical(_ alwaysBounceVertical : Bool) -> Self { self.alwaysBounceVertical = alwaysBounceVertical return self } func scrollEnabled(_ scrollEnabled : Bool) -> Self { self.isScrollEnabled = scrollEnabled return self } func pagingEnabled(_ pagingEnabled : Bool) -> Self { self.isPagingEnabled = pagingEnabled return self } func showsVerticalScrollIndicator(_ showsVerticalScrollIndicator:Bool) -> Self { self.showsVerticalScrollIndicator = showsVerticalScrollIndicator return self } func showsHorizontalScrollIndicator(_ showsHorizontalScrollIndicator: Bool) -> Self { self.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator return self } }
mit
60b6a6316a2eb57166f5f2c54e9b4383
22.876471
89
0.566888
5.798571
false
false
false
false
paulsumit1993/DailyFeed
DailyFeed/📦Model/DailyFeedRealmModel.swift
1
1350
// // DailyFeedRealmModel.swift // DailyFeed // // Created by Sumit Paul on 22/02/17. // import Foundation import RealmSwift final class DailyFeedRealmModel: Object { @objc dynamic var title: String = "" @objc dynamic var author: String = "" @objc dynamic var publishedAt: String = "" @objc dynamic var urlToImage: String = "" @objc dynamic var articleDescription: String = "" @objc dynamic var url: String = "" override static func primaryKey() -> String? { return "title" } //Helper to convert DailyFeedModel to DailyFeedRealmModel class func toDailyFeedRealmModel(from: DailyFeedModel) -> DailyFeedRealmModel { let item = DailyFeedRealmModel() item.title = from.title if let artDescription = from.articleDescription { item.articleDescription = artDescription } if let writer = from.author { item.author = writer } if let publishedTime = from.publishedAt { item.publishedAt = publishedTime } if let url = from.url { item.url = url } if let imageFromUrl = from.urlToImage { item.urlToImage = imageFromUrl } return item } }
gpl-3.0
3ac08d8cf46759ce0b66b191ee22e774
23.545455
83
0.571852
4.736842
false
false
false
false
sandrinodimattia/webtask-telco-sample
osx/SwiftSample/CompleteProfileController.swift
1
2139
// // CompleteProfileController.swift // TelcoMobile // // Created by Sandrino Di Mattia on 18/03/15. // Copyright (c) 2015 Auth0. All rights reserved. // import UIKit class CompleteProfileController: UIViewController, UIWebViewDelegate { var url: String = "" var loaded: Bool = false; @IBOutlet weak var webView: UIWebView! @IBOutlet weak var spinner: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Complete Profile" self.navigationItem.setHidesBackButton(true, animated: true) spinner.hidesWhenStopped = true webView.delegate = self } override func viewWillAppear(animated: Bool) { let requestURL = NSURL(string: url) let request = NSURLRequest(URL: requestURL!) webView.loadRequest(request) } override func viewDidLayoutSubviews() { self.webView?.frame = self.view.bounds } func webViewDidStartLoad(webView: UIWebView!) { if (!loaded) { spinner.startAnimating() } } func webViewDidFinishLoad(webView: UIWebView!) { loaded = true spinner.stopAnimating() } func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) { spinner.stopAnimating() } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { println("Navigating to: " + request.URL.host!) if (request.URL.host == "webview.close"){ self.performSegueWithIdentifier("updatedProfile", sender: self) self.dismissViewControllerAnimated(true, completion: nil) spinner.stopAnimating() return false } if (request.URL.host == "webview.cancel"){ navigationController?.popViewControllerAnimated(true) self.dismissViewControllerAnimated(true, completion: nil) spinner.stopAnimating() return false } return true } }
mit
2b5e9ca3f0521b2bc7a38744d6ad5b2f
27.905405
137
0.630201
5.268473
false
false
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/Controller/Layout/ViewController.swift
1
2110
// // ViewController.swift // WechatArticle // // Created by hwh on 15/11/8. // Copyright © 2015年 hwh. All rights reserved. // import UIKit import PushKit //import SnapKit class ViewController: UIViewController,MenuItemSelectDelegate{ @IBOutlet weak var containerView: UIView! @IBOutlet weak var hotButton: UIButton! @IBOutlet weak var settingButton: UIButton! var hotController: HotCategoryController! var settingController : SettingController! var currentController : UIViewController? static var token :dispatch_once_t = 0 let model = HotViewModel() override func viewDidLoad() { super.viewDidLoad() hotController = HotCategoryController.Nib() settingController = SettingController.Nib() self.addChildViewController(hotController) self.addChildViewController(settingController) showHotController(hotButton) setUpViews() } // 切换到 热点视图 @IBAction func showHotController(sender:UIButton) { hotButton.selected = true settingButton.selected = false settingController.view.removeFromSuperview() containerView.addSubview(hotController.view) hotController.view.frame = containerView.bounds currentController = hotController } // 切换到 设置视图 @IBAction func showCategoryController(sender:UIButton) { hotButton.selected = false settingButton.selected = true hotController.view.removeFromSuperview() containerView.addSubview(settingController.view) settingController.view.frame = containerView.bounds currentController = settingController settingController.didMoveToParentViewController(self) } /** 创建视图 */ func setUpViews() { print(model, terminator: "") } /** 打开左侧菜单 - parameter sender: 按钮 */ @IBAction func click(sender: AnyObject) { self.slideMenuController()?.openLeft() } }
apache-2.0
caff806ec8c68c7d35cdbf1fd40f3b77
25.688312
61
0.658394
5.150376
false
false
false
false
kostiakoval/WatchKit-Apps
1- Counter/Counter WatchKit Extension/Counter.swift
1
596
// // Counter.swift // Counter // // Created by Konstantin Koval on 13/12/14. // Copyright (c) 2014 Konstantin Koval. All rights reserved. // import Foundation private let counterKey = "counter" struct Counter { private (set) var count = 0 mutating func increase() { count += 1 } func save() { let defaults = NSUserDefaults.standardUserDefaults() defaults.setInteger(count, forKey: counterKey) } mutating func load() { count = NSUserDefaults.standardUserDefaults().integerForKey(counterKey) } mutating func reset() { count = 0 save() } }
mit
57a9b7e2944ec5da102fcff0eaa151af
17.65625
74
0.662752
4.054422
false
false
false
false
jopamer/swift
test/Constraints/tuple.swift
1
6563
// RUN: %target-typecheck-verify-swift // Test various tuple constraints. func f0(x: Int, y: Float) {} var i : Int var j : Int var f : Float func f1(y: Float, rest: Int...) {} func f2(_: (_ x: Int, _ y: Int) -> Int) {} func f2xy(x: Int, y: Int) -> Int {} func f2ab(a: Int, b: Int) -> Int {} func f2yx(y: Int, x: Int) -> Int {} func f3(_ x: (_ x: Int, _ y: Int) -> ()) {} func f3a(_ x: Int, y: Int) {} func f3b(_: Int) {} func f4(_ rest: Int...) {} func f5(_ x: (Int, Int)) {} func f6(_: (i: Int, j: Int), k: Int = 15) {} //===----------------------------------------------------------------------===// // Conversions and shuffles //===----------------------------------------------------------------------===// // Variadic functions. f4() f4(1) f4(1, 2, 3) f2(f2xy) f2(f2ab) f2(f2yx) f3(f3a) f3(f3b) // expected-error{{cannot convert value of type '(Int) -> ()' to expected argument type '(Int, Int) -> ()'}} func getIntFloat() -> (int: Int, float: Float) {} var values = getIntFloat() func wantFloat(_: Float) {} wantFloat(values.float) var e : (x: Int..., y: Int) // expected-error{{cannot create a variadic tuple}} typealias Interval = (a:Int, b:Int) func takeInterval(_ x: Interval) {} takeInterval(Interval(1, 2)) f5((1,1)) // Tuples with existentials var any : Any = () any = (1, 2) any = (label: 4) // Scalars don't have .0/.1/etc i = j.0 // expected-error{{value of type 'Int' has no member '0'}} any.1 // expected-error{{value of type 'Any' has no member '1'}} // expected-note@-1{{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} any = (5.0, 6.0) as (Float, Float) _ = (any as! (Float, Float)).1 // Fun with tuples protocol PosixErrorReturn { static func errorReturnValue() -> Self } extension Int : PosixErrorReturn { static func errorReturnValue() -> Int { return -1 } } func posixCantFail<A, T : Comparable & PosixErrorReturn> (_ f: @escaping (A) -> T) -> (_ args:A) -> T { return { args in let result = f(args) assert(result != T.errorReturnValue()) return result } } func open(_ name: String, oflag: Int) -> Int { } var foo: Int = 0 var fd = posixCantFail(open)(("foo", 0)) // Tuples and lvalues class C { init() {} func f(_: C) {} } func testLValue(_ c: C) { var c = c c.f(c) let x = c c = x } // <rdar://problem/21444509> Crash in TypeChecker::coercePatternToType func invalidPatternCrash(_ k : Int) { switch k { case (k, cph_: k) as UInt8: // expected-error {{tuple pattern cannot match values of the non-tuple type 'UInt8'}} expected-warning {{cast from 'Int' to unrelated type 'UInt8' always fails}} break } } // <rdar://problem/21875219> Tuple to tuple conversion with IdentityExpr / AnyTryExpr hang class Paws { init() throws {} } func scruff() -> (AnyObject?, Error?) { do { return try (Paws(), nil) } catch { return (nil, error) } } // Test variadics with trailing closures. func variadicWithTrailingClosure(_ x: Int..., y: Int = 2, fn: (Int, Int) -> Int) { } variadicWithTrailingClosure(1, 2, 3) { $0 + $1 } variadicWithTrailingClosure(1) { $0 + $1 } variadicWithTrailingClosure() { $0 + $1 } variadicWithTrailingClosure { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0) { $0 + $1 } variadicWithTrailingClosure(1, y: 0) { $0 + $1 } variadicWithTrailingClosure(y: 0) { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0, fn: +) variadicWithTrailingClosure(1, y: 0, fn: +) variadicWithTrailingClosure(y: 0, fn: +) variadicWithTrailingClosure(1, 2, 3, fn: +) variadicWithTrailingClosure(1, fn: +) variadicWithTrailingClosure(fn: +) // <rdar://problem/23700031> QoI: Terrible diagnostic in tuple assignment func gcd_23700031<T>(_ a: T, b: T) { var a = a var b = b (a, b) = (b, a % b) // expected-error {{binary operator '%' cannot be applied to two 'T' operands}} // expected-note @-1 {{overloads for '%' exist with these partially matching parameter lists: (UInt8, UInt8), (Int8, Int8), (UInt16, UInt16), (Int16, Int16), (UInt32, UInt32), (Int32, Int32), (UInt64, UInt64), (Int64, Int64), (UInt, UInt), (Int, Int)}} } // <rdar://problem/24210190> // Don't ignore tuple labels in same-type constraints or stronger. protocol Kingdom { associatedtype King } struct Victory<General> { init<K: Kingdom>(_ king: K) where K.King == General {} } struct MagicKingdom<K> : Kingdom { typealias King = K } func magify<T>(_ t: T) -> MagicKingdom<T> { return MagicKingdom() } func foo(_ pair: (Int, Int)) -> Victory<(x: Int, y: Int)> { return Victory(magify(pair)) // expected-error {{cannot convert return expression of type 'Victory<(Int, Int)>' to return type 'Victory<(x: Int, y: Int)>'}} } // https://bugs.swift.org/browse/SR-596 // Compiler crashes when accessing a non-existent property of a closure parameter func call(_ f: (C) -> Void) {} func makeRequest() { call { obj in print(obj.invalidProperty) // expected-error {{value of type 'C' has no member 'invalidProperty'}} } } // <rdar://problem/25271859> QoI: Misleading error message when expression result can't be inferred from closure struct r25271859<T> { } extension r25271859 { func map<U>(f: (T) -> U) -> r25271859<U> { } func andThen<U>(f: (T) -> r25271859<U>) { } } func f(a : r25271859<(Float, Int)>) { a.map { $0.0 } .andThen { _ in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{18-18=-> r25271859<String> }} print("hello") // comment this out and it runs, leave any form of print in and it doesn't return r25271859<String>() } } // LValue to rvalue conversions. func takesRValue(_: (Int, (Int, Int))) {} func takesAny(_: Any) {} var x = 0 var y = 0 let _ = (x, (y, 0)) takesRValue((x, (y, 0))) takesAny((x, (y, 0))) // SR-2600 - Closure cannot infer tuple parameter names typealias Closure<A, B> = ((a: A, b: B)) -> String func invoke<A, B>(a: A, b: B, _ closure: Closure<A,B>) { print(closure((a, b))) } invoke(a: 1, b: "B") { $0.b } invoke(a: 1, b: "B") { $0.1 } invoke(a: 1, b: "B") { (c: (a: Int, b: String)) in return c.b } invoke(a: 1, b: "B") { c in return c.b } // Crash with one-element tuple with labeled element class Dinner {} func microwave() -> Dinner? { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner?'}} } func microwave() -> Dinner { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner'}} }
apache-2.0
d2b635fc8b4ad2c4b13af5439f4c0b38
25.57085
254
0.616029
3.052558
false
false
false
false
nhatlee/MyWebsite-SwiftVapor
Sources/App/Controllers/UserController.swift
1
1643
// // UserController.swift // MyWebsite // // Created by nhatlee on 9/24/17. // //import App import Vapor import HTTP final class UserController: ResourceRepresentable { var users: [User] = [] func index(req: Request) throws -> ResponseRepresentable { let user = User(userName: "coding", email: "[email protected]", password: "1234") return try JSON(node: [ "name": user.userName, "email": user.email ]) } //This is the function the figure out what method that should be called depending on the HTTP request type. We will here start with the get. func makeResource() -> Resource<User> { return Resource( index: index, store: createUser ) } //This is where the 'post' request gets redirected to //This function has grouped: api and resource is: user //URL: http://localhost:8080/api/user func createUser(req: Request) throws -> ResponseRepresentable { let user = try User(request: req) if !(try Ultility.isExist(user)) { //Save to local database try user.save() users.append(user) var listJson: [JSON] = [] for u in users { let json = try JSON(node: [ "name": u.userName, "email": u.email, "Pass" : u.password ]) listJson.append(json) } return JSON(listJson) } else { return "User with email:\(user.email) has exist in database" } } }
mit
8c9944619281fda4269923bbc3811e5d
29.425926
145
0.539866
4.452575
false
false
false
false
benjamincongdon/TubeSync
TubeSync/YoutubeClient.swift
1
12791
// // YoutubeClient.swift // Playlist Sync // // Created by Benjamin Congdon on 1/11/16. // Copyright © 2016 Benjamin Congdon. All rights reserved. // import Cocoa import CocoaLumberjack class YoutubeClient: NSObject { static let defaultClient = YoutubeClient() var options:NSMutableDictionary internal private(set) var authenticated:Bool = false //var busy = false var downloadQueue = Array<(String,String)>() var handlesForPlaylists = Dictionary<Playlist,[NSFileHandle]>() var partialLogResponse:String = "" var partialErrResponse:String = "" override init(){ //Initializes Client options = NSMutableDictionary() super.init() } //Tries to authenticate with cookie func authenticate() -> YoutubeResponse{ return authYoutubeDL([]) } //Tries to authenticate with username + password + (optional) 2fa key func authenticate(username:String, password: String, twoFA:String) -> YoutubeResponse{ return authYoutubeDL([username, password, twoFA]) } //Runs YoutubeDL with current options and returns output private func authYoutubeDL(options:Array<String>) -> YoutubeResponse { let response = runYTDLTask(options, scriptName: "Authenticate") let str = response.errResult DDLogInfo(response.errResult) //No credentials provided if str.containsString("The playlist doesn't exist or is private, use --username or --netrc"){ DDLogWarn("Need account credentials to authenticate.") return YoutubeResponse.NeedCredentials } //Credential check failed else if str.containsString("Please use your account password"){ DDLogWarn("Provided credentials incorrect.") return YoutubeResponse.IncorrectCredentials } //Able to login else{ authenticated = true DDLogInfo("Authentication successful.") return YoutubeResponse.AuthSuccess } } private func runYTDLTask(options:Array<String>, scriptName:String) -> (logResult:String, errResult:String){ if !partialErrResponse.isEmpty || !partialLogResponse.isEmpty { DDLogError("Tried to start YTDL task when one hasn't completed yet.") return ("","") } partialLogResponse = "" partialErrResponse = "" if scriptName != "Authenticate" { DDLogVerbose("Running task with options \(options) and script name \(scriptName)") } else{ DDLogVerbose("Running authentication task.") } let task = NSTask() task.launchPath = NSBundle.mainBundle().pathForResource(scriptName, ofType: "py")! as String task.arguments = options let logOut = NSPipe() let errOut = NSPipe() let logFileHandle = logOut.fileHandleForReading let errFileHandle = errOut.fileHandleForReading task.standardOutput = logOut task.standardError = errOut NSNotificationCenter.defaultCenter().addObserver(self, selector: "receivedData:", name: NSFileHandleDataAvailableNotification, object: logFileHandle) NSNotificationCenter.defaultCenter().addObserver(self, selector: "terminated:", name: NSTaskDidTerminateNotification, object: task) NSNotificationCenter.defaultCenter().addObserver(self, selector: "receivedError:", name: NSFileHandleDataAvailableNotification, object: errFileHandle) logFileHandle.waitForDataInBackgroundAndNotify() errFileHandle.waitForDataInBackgroundAndNotify() task.launch() task.waitUntilExit() let logResponse = partialLogResponse let errResponse = partialErrResponse dispatch_async(GlobalMainQueue){ print(logResponse, errResponse) } DDLogVerbose("StdOut of Task: " + logResponse) if !errResponse.isEmpty{ DDLogVerbose("ErrOut of Task: " + errResponse) } partialLogResponse = "" partialErrResponse = "" return (logResponse, errResponse) } func receivedData(notification:NSNotification){ let handle = notification.object as! NSFileHandle let data = handle.availableData if data.length != 0 { let newData = String(data: data, encoding: NSUTF8StringEncoding)! partialLogResponse += newData if let fileName = extractFileName(newData){ NSNotificationCenter.defaultCenter().postNotificationName(CurrentDownloadFileName, object: fileName) } } handle.waitForDataInBackgroundAndNotify() } func terminated(notification:NSNotification){ NSNotificationCenter.defaultCenter().removeObserver(self) } func receivedError(notification:NSNotification){ let handle = notification.object as! NSFileHandle let data = handle.availableData if data.length != 0 { let newData = String(data: data, encoding: NSUTF8StringEncoding)! partialErrResponse += newData } handle.waitForDataInBackgroundAndNotify() } func deauthenticate(){ authenticated = false deleteCookie() } func deleteCookie(){ let fileManager = NSFileManager.defaultManager() do { try fileManager.removeItemAtPath(".cookie.txt") } catch let error as NSError { print("Ooops! Something went wrong: \(error)") } } func isValidPlaylist(url:String) -> YoutubeResponse { let result = runYTDLTask([url], scriptName: "Playlist") if result.errResult == "" { //No error in getting result let jsonResult = JSON(string:result.logResult) for(k,v) in jsonResult{ if k as! String == "_type" && v.asString == "playlist"{ DDLogInfo("Valid playlist found for url: " + url) return YoutubeResponse.ValidPlaylist } } return YoutubeResponse.NotPlaylist } else if result.errResult.containsString("Error 404"){ DDLogWarn("404 Error encountered while checking playlist at url: " + url) return YoutubeResponse.InvalidPlaylist } else if result.errResult.containsString("playlist doesn't exist or is private") { DDLogWarn("Playlist at url is either private or nonexistant: " + url) return YoutubeResponse.NeedCredentials } return YoutubeResponse.InvalidPlaylist } func youtubeInfo(url:String) throws -> JSON?{ let result = runYTDLTask([url], scriptName: "Playlist") if result.errResult != "" { print("ERROR:") print(result.errResult) if result.errResult.containsString("[Errno 8] nodename nor servname provided"){ throw YoutubeError.NetworkFailure } } return JSON(string:result.logResult) } func playlistInfo(url:String) throws -> (title:String?, entries:Array<String>){ let optionalResult = try youtubeInfo(url) if let jsonResult = optionalResult { guard let title = jsonResult["title"].asString else{ print(jsonResult["title"].asError) return(nil,[""]) } guard let entries = jsonResult["entries"].asArray else{ print(jsonResult["entries"].asError) return(nil,[""]) } return(title,extractIDs(entries)) } return (nil,[""]) } func makeFoldersToPath(path:String){ do { print("path to " + path) try NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { print("ERROR: " + error.localizedDescription) DDLogError("Could not make folders to path: " + path) DDLogError(error.description) } } func extractFileName(data:String) -> String?{ //Extract file name from output let logResultArray = data.characters.split{$0 == "\n"}.map(String.init) for line in logResultArray { let beginString = "[download] Destination: " let endString = " has already been downloaded" var fileName:String = "" if line.hasPrefix(beginString){ fileName = line.substringFromIndex(line.startIndex.advancedBy(beginString.characters.count)) } else if line.hasSuffix(endString) { fileName = line.substringFromIndex(line.startIndex.advancedBy("[download] ".characters.count)) fileName = fileName.substringToIndex(fileName.endIndex.advancedBy(-1 * endString.characters.count)) } if fileName != ""{ print("returning file name: " + fileName) DDLogInfo("Found video with filename: " + fileName) return fileName } } return nil } func downloadVideo(url:String, path:String) -> String { makeFoldersToPath(path) //Actually download video let result = runYTDLTask([url,path], scriptName: "Download") NSNotificationCenter.defaultCenter().postNotificationName("videoFinished", object: result.logResult) if let fileName = extractFileName(result.logResult){ return fileName } print("ERROR: Returning null filename:") print(result.logResult) print(result.errResult) DDLogError("Returning null filename for download from url: " + url) DDLogError("Download Logs: " + result.logResult) DDLogError("Error Logs: " + result.errResult) return "" } //NOTE: Should only be called *AFTER* a sync func deleteStaleFiles(playlist:Playlist, path:String){ let playlistPath = NSString(string: path).stringByAppendingPathComponent(playlist.title) let folderList = SyncHelper.listFolder(playlistPath) for file in folderList{ if file.hasSuffix(".mp4") && !playlist.entries.values.contains(file){ let filePath = NSString(string: playlistPath).stringByAppendingPathComponent(file) deleteFile(filePath) } //Any file that has a ".part" extension *AFTER* a sync must be stale. else if file.hasSuffix(".part"){ let filePath = NSString(string: playlistPath).stringByAppendingPathComponent(file) deleteFile(filePath) } } } func deleteFile(path:String){ let fileManager = NSFileManager.defaultManager() do { try fileManager.removeItemAtPath(path) print("DELETE: Removed file: " + path) DDLogInfo("Deleting file at path: " + path) } catch let error as NSError { print("Something went wrong deleting file: \(error)") DDLogError("Unable to delete file at path: " + path) DDLogError(error.description) } } func refreshPlaylist(playlist:Playlist) throws { let info = try YoutubeClient.defaultClient.playlistInfo(playlist.url) if info.title == nil{ print("playlist no longer valid") throw YoutubeError.CannotRefreshError } var entryDict = Dictionary<String,String>() for entry in info.entries { entryDict[entry] = "" } //Add new videos to entry for newEntry in entryDict { if !playlist.entries.keys.contains(newEntry.0){ playlist.entries[newEntry.0] = "" } } //Delete stale videos from dictionary for oldEntry in playlist.entries { if !entryDict.keys.contains(oldEntry.0) { playlist.entries.removeValueForKey(oldEntry.0) } } } func extractIDs(entries:[JSON]) -> Array<String>{ var entryIDList = Array<String>() for jsonEntry in entries{ guard let title = jsonEntry["id"].asString else{ continue } entryIDList.append(title) } return entryIDList } } enum YoutubeResponse{ case AuthSuccess, NeedCredentials, IncorrectCredentials, ValidPlaylist, InvalidPlaylist, NotPlaylist, DuplicatePlaylist } enum YoutubeError: ErrorType{ case CannotRefreshError, NetworkFailure }
mit
326ad57068078a7cd64a23866dd3a572
36.731563
158
0.611728
5.207655
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/ExperimentsListViewController.swift
1
32914
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 third_party_objective_c_material_components_ios_components_Buttons_Buttons import third_party_objective_c_material_components_ios_components_Dialogs_Dialogs import third_party_objective_c_material_components_ios_components_FeatureHighlight_ColorThemer import third_party_objective_c_material_components_ios_components_FeatureHighlight_FeatureHighlight import third_party_objective_c_material_components_ios_components_Palettes_Palettes import third_party_objective_c_material_components_ios_components_Snackbar_Snackbar protocol ExperimentsListViewControllerDelegate: class { /// Informs the delegate the sidebar should be shown. func experimentsListShowSidebar() /// Informs the delegate that Drive sync status should be refreshed. func experimentsListManualSync() /// Informs the delegate the experiment with the given ID should be shown. /// /// - Parameter experimentID: An experiment ID. func experimentsListShowExperiment(withID experimentID: String) /// Informs the delegate a new experiment should be created and shown. func experimentsListShowNewExperiment() /// Informs the delegate the archive state for an experiment should be toggled. /// /// - Parameter experimentID: An experiment ID. func experimentsListToggleArchiveStateForExperiment(withID experimentID: String) /// Informs the delegate the user has deleted the experiment. /// /// - Parameter experimentID: An experiment ID. func experimentsListDeleteExperiment(withID experimentID: String) /// Informs the delegate the deletion was completed and not undone. /// /// - Parameter deletedExperiment: A deleted experiment. func experimentsListDeleteExperimentCompleted(_ deletedExperiment: DeletedExperiment) /// Informs the delegate the claim experiments view controller should be shown. func experimentsListShowClaimExperiments() /// Informs the delegate the experiments list appeared. func experimentsListDidAppear() /// Informs the delegate the experiment title changed. /// /// - Parameters: /// - title: The experiment title. /// - experimentID: The ID of the experiment that changed. func experimentsListDidSetTitle(_ title: String?, forExperimentID experimentID: String) /// Informs the delegate the experiment cover image changed. /// /// - Parameters: /// - imageData: The cover image data. /// - metadata: The metadata associated with the image. /// - experiment: The ID of the experiment whose cover image was set. func experimentsListDidSetCoverImageData(_ imageData: Data?, metadata: NSDictionary?, forExperimentID experimentID: String) /// Informs the delegate the experiment should be exported as a PDF. /// /// - Parameters: /// - experiment: The experiment to export. /// - completionHandler: The completion handler to call when export is complete. func experimentsListExportExperimentPDF( _ experiment: Experiment, completionHandler: @escaping PDFExportController.CompletionHandler) /// Asks the delegate for a pop up menu action to initiate export flow. /// /// - Parameters: /// - experiment: The experiment to be exported. /// - presentingViewController: The presenting view controller. /// - sourceView: View to anchor a popover to display. func experimentsListExportFlowAction(for experiment: Experiment, from presentingViewController: UIViewController, sourceView: UIView) -> PopUpMenuAction } // swiftlint:disable type_body_length /// A list of the user's experiments. This is the view the user sees on launch. class ExperimentsListViewController: MaterialHeaderViewController, ExperimentStateListener, ExperimentsListItemsDelegate, ExperimentsListCellDelegate { // MARK: - Constants private let createExperimentHighlightTimeInterval: TimeInterval = 10 private let fabPadding: CGFloat = 16.0 // MARK: - Properties weak var delegate: ExperimentsListViewControllerDelegate? /// The menu bar button. Exposed for testing. let menuBarButton = MaterialMenuBarButtonItem() /// The no connection bar button. Exposed for testing. let noConnectionBarButton = MaterialBarButtonItem() private let accountsManager: AccountsManager private let commonUIComponents: CommonUIComponents private let createExperimentFAB = MDCFloatingButton() private var createExperimentHighlightTimer: Timer? private let documentManager: DocumentManager private let emptyView = EmptyView(title: String.emptyProject, imageName: "empty_experiment_list") private var highlightController: MDCFeatureHighlightViewController? private let metadataManager: MetadataManager private let networkAvailability: NetworkAvailability private var pullToRefreshController: PullToRefreshController? private var pullToRefreshControllerForEmptyView: PullToRefreshController? private let sensorDataManager: SensorDataManager private let exportType: UserExportType private let shouldAllowManualSync: Bool private let snackbarCategoryArchivedExperiment = "snackbarCategoryArchivedExperiment" private let snackbarCategoryDeletedExperiment = "snackbarCategoryDeletedExperiment" private let preferenceManager: PreferenceManager private let experimentsListItemsViewController: ExperimentsListItemsViewController private let existingDataMigrationManager: ExistingDataMigrationManager? private let saveToFilesHandler = SaveToFilesHandler() override var trackedScrollView: UIScrollView? { return experimentsListItemsViewController.collectionView } /// Sets the number of unclaimed experiments that exist. When the count is greater than one, the /// claim experiments view will be shown as a collection view header and in the empty view. private var numberOfUnclaimedExperiments: Int = 0 { didSet { guard numberOfUnclaimedExperiments != oldValue else { return } let shouldShowClaimExperimentsView = numberOfUnclaimedExperiments > 0 // Empty view emptyView.emptyViewDelegate = self emptyView.isClaimExperimentsViewHidden = !shouldShowClaimExperimentsView if shouldShowClaimExperimentsView { emptyView.claimExperimentsView.setNumberOfUnclaimedExperiments(numberOfUnclaimedExperiments) } if shouldShowClaimExperimentsView { // Collection view header. let headerConfigurationBlock: ExperimentsListHeaderConfigurationBlock = { [weak self] in if let strongSelf = self, let header = $0 as? ClaimExperimentsHeaderView { header.claimExperimentsView.delegate = strongSelf header.claimExperimentsView.setNumberOfUnclaimedExperiments( strongSelf.numberOfUnclaimedExperiments) } } let headerSizeBlock: ExperimentsListHeaderSizeBlock = { (width) in return CGSize(width: width, height: ClaimExperimentsHeaderView.Metrics.height) } experimentsListItemsViewController.setCollectionViewHeader( configurationBlock: headerConfigurationBlock, headerSizeBlock: headerSizeBlock, class: ClaimExperimentsHeaderView.self) } else { experimentsListItemsViewController.removeCollectionViewHeader() } } } // MARK: - Public /// Designated initializer. /// /// - Parameters: /// - accountsManager: The accounts manager. /// - analyticsReporter: The analytics reporter. /// - commonUIComponents: Common UI components. /// - existingDataMigrationManager: The existing data migration manager. /// - metadataManager: The metadata manager. /// - networkAvailability: Network availability. /// - preferenceManager: The preference manager. /// - sensorDataManager: The sensor data manager. /// - documentManager: The document manager. /// - exportType: The export option type to show. /// - shouldAllowManualSync: Whether to allow manual syncing. init(accountsManager: AccountsManager, analyticsReporter: AnalyticsReporter, commonUIComponents: CommonUIComponents, existingDataMigrationManager: ExistingDataMigrationManager?, metadataManager: MetadataManager, networkAvailability: NetworkAvailability, preferenceManager: PreferenceManager, sensorDataManager: SensorDataManager, documentManager: DocumentManager, exportType: UserExportType, shouldAllowManualSync: Bool) { self.accountsManager = accountsManager self.commonUIComponents = commonUIComponents self.existingDataMigrationManager = existingDataMigrationManager self.metadataManager = metadataManager self.networkAvailability = networkAvailability self.preferenceManager = preferenceManager self.sensorDataManager = sensorDataManager self.documentManager = documentManager self.exportType = exportType self.shouldAllowManualSync = shouldAllowManualSync experimentsListItemsViewController = ExperimentsListItemsViewController(cellClass: ExperimentsListCell.self, metadataManager: metadataManager, preferenceManager: preferenceManager) super.init(analyticsReporter: analyticsReporter) experimentsListItemsViewController.delegate = self experimentsListItemsViewController.cellConfigurationBlock = { [weak self] (cell, overview, image) in if let strongSelf = self, let cell = cell as? ExperimentsListCell, let overview = overview { cell.configureForExperimentOverview(overview, delegate: strongSelf, image: image) } } experimentsListItemsViewController.cellSizeBlock = { (width) in return ExperimentsListCell.itemSize(inWidth: width) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override func viewDidLoad() { super.viewDidLoad() title = String.appName // Experiments list items view controller. experimentsListItemsViewController.scrollDelegate = self experimentsListItemsViewController.view.translatesAutoresizingMaskIntoConstraints = false addChild(experimentsListItemsViewController) view.addSubview(experimentsListItemsViewController.view) experimentsListItemsViewController.view.pinToEdgesOfView(view) let sidebarMenuButton = UIBarButtonItem(image: UIImage(named: "ic_menu"), style: .plain, target: self, action: #selector(sidebarMenuButtonPressed)) sidebarMenuButton.tintColor = .white sidebarMenuButton.accessibilityLabel = String.sidebarMenuContentDescription sidebarMenuButton.accessibilityHint = String.sidebarMenuContentDetails navigationItem.leftBarButtonItem = sidebarMenuButton menuBarButton.button.addTarget(self, action: #selector(menuButtonPressed), for: .touchUpInside) menuBarButton.button.setImage(UIImage(named: "ic_more_horiz"), for: .normal) noConnectionBarButton.button.addTarget(self, action: #selector(noConnectionButtonPressed), for: .touchUpInside) let noConnectionImage = UIImage(named: "ic_signal_wifi_statusbar_connected_no_internet") noConnectionBarButton.button.setImage(noConnectionImage, for: .normal) noConnectionBarButton.button.accessibilityHint = String.driveErrorNoConnection noConnectionBarButton.button.accessibilityLabel = String.driveErrorNoConnectionContentDescription noConnectionBarButton.button.accessibilityTraits = .staticText noConnectionBarButton.button.tintColor = .white updateRightBarButtonItems() // Configure the empty view. emptyView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(emptyView) emptyView.topAnchor.constraint(equalTo: appBar.navigationBar.bottomAnchor).isActive = true emptyView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true emptyView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true emptyView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true // Add the FAB. view.addSubview(createExperimentFAB) createExperimentFAB.accessibilityLabel = String.btnNewExperimentContentDescription createExperimentFAB.setImage(UIImage(named: "ic_add"), for: .normal) createExperimentFAB.tintColor = .white createExperimentFAB.setBackgroundColor(appBar.headerViewController.headerView.backgroundColor, for: .normal) createExperimentFAB.addTarget(self, action: #selector(addExperimentButtonPressed), for: .touchUpInside) createExperimentFAB.translatesAutoresizingMaskIntoConstraints = false createExperimentFAB.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -fabPadding).isActive = true createExperimentFAB.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -fabPadding).isActive = true experimentsListItemsViewController.collectionView.contentInset = UIEdgeInsets(top: experimentsListItemsViewController.collectionView.contentInset.top, left: 0, bottom: MDCFloatingButton.defaultDimension(), right: 0) // Pull to refresh. if shouldAllowManualSync { pullToRefreshController = commonUIComponents.pullToRefreshController( forScrollView: experimentsListItemsViewController.collectionView) { [weak self] in self?.performPullToRefresh() } if pullToRefreshController != nil { // Pull to refresh is not visible when allowing the header to expand past its max height. appBar.headerViewController.headerView.canOverExtend = false // Collection view needs to bounce vertical for pull to refresh. experimentsListItemsViewController.collectionView.alwaysBounceVertical = true } pullToRefreshControllerForEmptyView = commonUIComponents.pullToRefreshController(forScrollView: emptyView) { [weak self] in self?.performPullToRefresh() } if pullToRefreshControllerForEmptyView != nil { // Empty view needs to bounce vertical for pull to refresh. emptyView.alwaysBounceVertical = true } } // Listen to notifications of newly imported experiments. NotificationCenter.default.addObserver(self, selector: #selector(experimentImported), name: .documentManagerDidImportExperiment, object: nil) // Listen to notifications of newly downloaded assets. NotificationCenter.default.addObserver(self, selector: #selector(downloadedImages), name: .driveSyncManagerDownloadedImages, object: nil) // Listen to notifications of network availability changing. NotificationCenter.default.addObserver(self, selector: #selector(networkAvailabilityChanged), name: .NetworkAvailabilityChanged, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Recreate sections in case experiments were created or modified while view was off screen. experimentsListItemsViewController.updateExperiments() updateEmptyView(animated: false) refreshUnclaimedExperiments() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Invalidate the feature highlight timer on viewDidAppear to prevent an older timer from // firing before creating a new timer. createExperimentHighlightTimer?.invalidate() createExperimentHighlightTimer = nil // After some time, if user has no experiments and hasn't been shown the feature highlight // before, give them a nudge if necessary. if !preferenceManager.hasUserSeenExperimentHighlight { createExperimentHighlightTimer = Timer.scheduledTimer(timeInterval: createExperimentHighlightTimeInterval, target: self, selector: #selector(highlightCreateActionIfNeeded), userInfo: nil, repeats: false) RunLoop.main.add(createExperimentHighlightTimer!, forMode: .common) } delegate?.experimentsListDidAppear() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Unoding an archive or delete is unstable when this view is off screen so dismiss snackbars. [snackbarCategoryArchivedExperiment, snackbarCategoryDeletedExperiment].forEach { MDCSnackbarManager.dismissAndCallCompletionBlocks(withCategory: $0) } // Make sure the highlight doesn't appear when off screen. createExperimentHighlightTimer?.invalidate() createExperimentHighlightTimer = nil dismissFeatureHighlightIfNecessary() highlightController = nil } /// Handles the event that an experiment fails to load. func handleExperimentLoadingFailure() { experimentsListItemsViewController.handleExperimentLoadingFailure() } /// Inserts an experiment overview. /// /// - Parameters: /// - overview: An experiment overview. /// - atBeginning: Whether to insert the overview at the beginning. func insertOverview(_ overview: ExperimentOverview, atBeginning: Bool = false) { experimentsListItemsViewController.insertOverview(overview, atBeginning: atBeginning) } /// Refreshes the number of unclaimed experiments shown in the header. func refreshUnclaimedExperiments() { if let existingDataMigrationManager = existingDataMigrationManager { numberOfUnclaimedExperiments = existingDataMigrationManager.numberOfExistingExperiments } } /// Reloads the experiments and refreshes the view. func reloadExperiments() { // If view isn't visible it will automatically be reloaded when the view appears. if isViewVisible { experimentsListItemsViewController.updateExperiments() updateEmptyView(animated: false) } } /// Updates the nav item's right bar button items. Exposed for testing. func updateRightBarButtonItems() { var rightBarButtonItems: [UIBarButtonItem] = [menuBarButton] if accountsManager.supportsAccounts && networkAvailability.isAvailable == false { rightBarButtonItems.append(noConnectionBarButton) } navigationItem.rightBarButtonItems = rightBarButtonItems } /// Starts the pull to refresh animation. func startPullToRefreshAnimation() { pullToRefreshController?.startRefreshing() pullToRefreshControllerForEmptyView?.startRefreshing() } /// Ends the pull to refresh animation. func endPullToRefreshAnimation() { pullToRefreshController?.endRefreshing() pullToRefreshControllerForEmptyView?.endRefreshing() } // MARK: - Private // Feature highlight that nudges the user to create an experiment if they have one or fewer // experiments. @objc private func highlightCreateActionIfNeeded() { guard !preferenceManager.hasUserSeenExperimentHighlight else { return } guard metadataManager.experimentOverviews.count <= 1 else { preferenceManager.hasUserSeenExperimentHighlight = true return } // Set up a fake button to display a highlighted state and have a nice shadow. let fakeFAB = MDCFloatingButton() fakeFAB.accessibilityLabel = String.btnNewExperimentContentDescription fakeFAB.setImage(UIImage(named: "ic_add"), for: .normal) fakeFAB.tintColor = .white fakeFAB.setBackgroundColor(.appBarDefaultStatusBarBackgroundColor, for: .normal) fakeFAB.sizeToFit() // Show the highlight. let highlight = MDCFeatureHighlightViewController(highlightedView: createExperimentFAB, andShow: fakeFAB) { (accepted) in if accepted { self.addExperimentButtonPressed() } } fakeFAB.addTarget(highlight, action: #selector(highlight.acceptFeature), for: .touchUpInside) highlight.titleText = String.experimentsTutorialTitle highlight.bodyText = String.experimentsTutorialMessage highlight.outerHighlightColor = MDCPalette.blue.tint700 MDCFeatureHighlightColorThemer.applySemanticColorScheme( ViewConstants.featureHighlightColorScheme, to: highlight) present(highlight, animated: true) highlightController = highlight preferenceManager.hasUserSeenExperimentHighlight = true } /// Dismisses the feature highlight if it's on screen, without animation. func dismissFeatureHighlightIfNecessary() { highlightController?.dismiss(animated: false) } private func updateEmptyView(animated: Bool) { UIView.animate(withDuration: animated ? 0.5 : 0) { self.emptyView.alpha = self.experimentsListItemsViewController.isEmpty ? 1 : 0 } } private func performPullToRefresh() { delegate?.experimentsListManualSync() analyticsReporter.track(.syncManualRefresh) } // MARK: - Accessibility override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool { let isEmptyViewShowing = emptyView.alpha == 1 guard let pullToRefreshController = isEmptyViewShowing ? pullToRefreshControllerForEmptyView : pullToRefreshController, direction == .up else { return super.accessibilityScroll(direction) } let scrollView = isEmptyViewShowing ? emptyView : experimentsListItemsViewController.collectionView let shouldPullToRefresh = scrollView.contentOffset.y <= -scrollView.contentInset.top guard shouldPullToRefresh else { return super.accessibilityScroll(direction) } UIAccessibility.post(notification: .announcement, argument: String.pullToRefreshContentDescription) pullToRefreshController.startRefreshing() performPullToRefresh() return true } // MARK: - User Actions @objc private func sidebarMenuButtonPressed() { delegate?.experimentsListShowSidebar() } @objc private func menuButtonPressed() { let currentlyShowingArchived = preferenceManager.shouldShowArchivedExperiments let icon = UIImage(named: currentlyShowingArchived ? "ic_check_box" : "ic_check_box_outline_blank") let popUpMenu = PopUpMenuViewController() popUpMenu.addAction(PopUpMenuAction(title: String.actionIncludeArchivedExperiments, icon: icon) { _ -> Void in self.preferenceManager.shouldShowArchivedExperiments = !currentlyShowingArchived self.experimentsListItemsViewController.shouldIncludeArchivedExperiments = !currentlyShowingArchived self.updateEmptyView(animated: true) }) popUpMenu.present(from: self, position: .sourceView(menuBarButton.button)) } @objc private func addExperimentButtonPressed() { // User is taking the featured action, so ensure that they never see the feature highlight. preferenceManager.hasUserSeenExperimentHighlight = true delegate?.experimentsListShowNewExperiment() } @objc private func noConnectionButtonPressed() { showSnackbar(withMessage: String.driveErrorNoConnection) } // MARK: - Notifications @objc private func experimentImported() { guard Thread.isMainThread else { DispatchQueue.main.async { self.experimentImported() } return } // Update the overviews. reloadExperiments() } @objc private func downloadedImages(notification: Notification) { guard Thread.isMainThread else { DispatchQueue.main.async { self.downloadedImages(notification: notification) } return } guard isViewVisible, let imagePaths = notification.userInfo?[DriveSyncUserInfoConstants.downloadedImagePathsKey] as? [String] else { return } experimentsListItemsViewController.reloadCells(forDownloadedImagePaths: imagePaths) } @objc private func networkAvailabilityChanged() { updateRightBarButtonItems() } // MARK: - ExperimentStateListener func experimentStateArchiveStateChanged(forExperiment experiment: Experiment, overview: ExperimentOverview, undoBlock: @escaping () -> Void) { let didCollectionViewChange = experimentsListItemsViewController.experimentArchivedStateChanged( forExperimentOverview: overview, updateCollectionView: isViewVisible) // Only show the snackbar and update the empty view if the view is visible. guard isViewVisible else { return } if didCollectionViewChange { updateEmptyView(animated: true) } if overview.isArchived { // Only show the snack bar if the experiment is now archived. showUndoSnackbar(withMessage: String.archivedExperimentMessage, category: snackbarCategoryArchivedExperiment, undoBlock: undoBlock) } else { // If the user is unarchiving, hide any archived state undo snackbars. MDCSnackbarManager.dismissAndCallCompletionBlocks( withCategory: snackbarCategoryArchivedExperiment) } } func experimentStateDeleted(_ deletedExperiment: DeletedExperiment, undoBlock: (() -> Void)?) { let didCollectionViewChange = experimentsListItemsViewController.experimentWasRemoved( withID: deletedExperiment.experimentID, updateCollectionView: isViewVisible) // Only update the empty view if the view is visible. if isViewVisible && didCollectionViewChange { updateEmptyView(animated: true) } // Not all delete actions can be undone. guard let undoBlock = undoBlock else { delegate?.experimentsListDeleteExperimentCompleted(deletedExperiment) return } var didUndo = false showUndoSnackbar(withMessage: String.deletedExperimentMessage, category: snackbarCategoryDeletedExperiment, undoBlock: { didUndo = true undoBlock() }) { (_) in if !didUndo { self.delegate?.experimentsListDeleteExperimentCompleted(deletedExperiment) } } } func experimentStateRestored(_ experiment: Experiment, overview: ExperimentOverview) { let didCollectionViewChange = experimentsListItemsViewController.experimentWasRestored( forExperimentOverview: overview, updateCollectionView: isViewVisible) if didCollectionViewChange { updateEmptyView(animated: true) } } // MARK: - ExperimentsListItemsDelegate func experimentsListItemsViewControllerDidSelectExperiment(withID experimentID: String) { delegate?.experimentsListShowExperiment(withID: experimentID) } // MARK: - ExperimentsListCellDelegate func menuButtonPressedForCell(_ cell: ExperimentsListCell, attachmentButton: UIButton) { guard let overview = experimentsListItemsViewController.overview(forCell: cell) else { return } let archiveTitle = overview.isArchived ? String.actionUnarchive : String.actionArchive let archiveAccessibilityLabel = overview.isArchived ? String.actionUnarchiveExperimentContentDescription : String.actionArchiveExperimentContentDescription let popUpMenu = PopUpMenuViewController() // Edit. popUpMenu.addAction(PopUpMenuAction(title: String.actionEdit, icon: UIImage(named: "ic_edit")) { _ -> Void in guard let experiment = self.metadataManager.experiment(withID: overview.experimentID) else { return } let editExperimentVC = EditExperimentViewController(experiment: experiment, analyticsReporter: self.analyticsReporter, metadataManager: self.metadataManager) editExperimentVC.delegate = self self.present(editExperimentVC, animated: true) }) // Archive. popUpMenu.addAction(PopUpMenuAction( title: archiveTitle, icon: UIImage(named: "ic_archive"), accessibilityLabel: archiveAccessibilityLabel) { _ -> Void in self.delegate?.experimentsListToggleArchiveStateForExperiment(withID: overview.experimentID) }) // Export if !RecordingState.isRecording, let experiment = metadataManager.experiment(withID: overview.experimentID), !experiment.isEmpty { if let action = delegate?.experimentsListExportFlowAction(for: experiment, from: self, sourceView: attachmentButton) { popUpMenu.addAction(action) } } // Delete. popUpMenu.addAction(PopUpMenuAction( title: String.actionDelete, icon: UIImage(named: "ic_delete"), accessibilityLabel: String.actionDeleteExperimentContentDescription) { _ -> Void in // Prompt the user to confirm deletion. let alertController = MDCAlertController(title: String.deleteExperimentDialogTitle, message: String.deleteExperimentDialogMessage) let cancelAction = MDCAlertAction(title: String.btnDeleteObjectCancel) let deleteAction = MDCAlertAction(title: String.btnDeleteObjectConfirm) { _ in // Delete the experiment and update the collection view. self.delegate?.experimentsListDeleteExperiment(withID: overview.experimentID) } alertController.addAction(cancelAction) alertController.addAction(deleteAction) alertController.accessibilityViewIsModal = true self.present(alertController, animated: true) }) popUpMenu.present(from: self, position: .sourceView(attachmentButton)) } // MARK: - UIGestureRecognizerDelegate override func interactivePopGestureShouldBegin() -> Bool { // The MaterialHeaderCollectionViewController overrides interactive pop gestures and defaults // to allowing the gesture, but ExperimentsListViewController is the root view for the nav // stack and allowing it to attempt to pop back breaks the nav controller. Instead, disable this // behavior in this VC. return false } } // swiftlint:enable type_body_length // MARK: - EditExperimentViewControllerDelegate extension ExperimentsListViewController: EditExperimentViewControllerDelegate { func editExperimentViewControllerDidSetTitle(_ title: String?, forExperimentID experimentID: String) { delegate?.experimentsListDidSetTitle(title, forExperimentID: experimentID) experimentsListItemsViewController.collectionView.reloadData() } func editExperimentViewControllerDidSetCoverImageData(_ imageData: Data?, metadata: NSDictionary?, forExperimentID experimentID: String) { delegate?.experimentsListDidSetCoverImageData(imageData, metadata: metadata, forExperimentID: experimentID) experimentsListItemsViewController.collectionView.reloadData() } } // MARK: - ClaimExperimentsViewDelegate extension ExperimentsListViewController: ClaimExperimentsViewDelegate { func claimExperimentsViewDidPressClaimExperiments() { delegate?.experimentsListShowClaimExperiments() } } // MARK: - EmptyViewDelegate extension ExperimentsListViewController: EmptyViewDelegate { func emptyViewDidPressClaimExperiments() { delegate?.experimentsListShowClaimExperiments() } }
apache-2.0
0cd0f0fec0999c0b4bfbcb9cab47c127
40.928662
100
0.713526
5.60811
false
false
false
false
googlearchive/science-journal-ios
ScienceJournalTests/SensorData/PreferenceManagerTest.swift
1
22071
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 XCTest @testable import third_party_sciencejournal_ios_ScienceJournalOpen class PreferenceManagerTest: XCTestCase { func testShowArchivedExperiments() { // Set up a root preference manager and two for specific accounts, and reset each. let rootPrefsManager = PreferenceManager() let prefsManagerForAccount1 = PreferenceManager(accountID: "1") let prefsManagerForAccount2 = PreferenceManager(accountID: "2") [rootPrefsManager, prefsManagerForAccount1, prefsManagerForAccount2].forEach { $0.resetAll() } // Root preference manager. XCTAssertFalse(rootPrefsManager.shouldShowArchivedExperiments, "Should not show archived experiments.") rootPrefsManager.shouldShowArchivedExperiments = true XCTAssertTrue(rootPrefsManager.shouldShowArchivedExperiments, "Should show archived experiments.") rootPrefsManager.shouldShowArchivedExperiments = false XCTAssertFalse(rootPrefsManager.shouldShowArchivedExperiments, "Should not show archived experiments.") // The preference manager for account 1 should not be affected by the root preference manager. XCTAssertFalse(prefsManagerForAccount1.shouldShowArchivedExperiments, "Should not show archived experiments for account 1.") prefsManagerForAccount1.shouldShowArchivedExperiments = true XCTAssertTrue(prefsManagerForAccount1.shouldShowArchivedExperiments, "Should show archived experiments for account 1.") // The preference manager for account 2 should not be affected by the root preference manager or // the one for account 1. XCTAssertFalse(prefsManagerForAccount2.shouldShowArchivedExperiments, "Should not show archived experiments for account 2.") prefsManagerForAccount2.shouldShowArchivedExperiments = true XCTAssertTrue(prefsManagerForAccount2.shouldShowArchivedExperiments, "Should show archived experiments for account 2.") } func testShowArchivedRecordings() { // Set up a root preference manager and two for specific accounts, and reset each. let rootPrefsManager = PreferenceManager() let prefsManagerForAccount1 = PreferenceManager(accountID: "1") let prefsManagerForAccount2 = PreferenceManager(accountID: "2") [rootPrefsManager, prefsManagerForAccount1, prefsManagerForAccount2].forEach { $0.resetAll() } // Root preference manager. XCTAssertFalse(rootPrefsManager.shouldShowArchivedRecordings, "Should not show archived recordings.") rootPrefsManager.shouldShowArchivedRecordings = true XCTAssertTrue(rootPrefsManager.shouldShowArchivedRecordings, "Should show archived recordings.") rootPrefsManager.shouldShowArchivedRecordings = false XCTAssertFalse(rootPrefsManager.shouldShowArchivedRecordings, "Should not show archived recordings.") // The preference manager for account 1 should not be affected by the root preference manager. XCTAssertFalse(prefsManagerForAccount1.shouldShowArchivedRecordings, "Should not show archived recordings for account 1.") prefsManagerForAccount1.shouldShowArchivedRecordings = true XCTAssertTrue(prefsManagerForAccount1.shouldShowArchivedRecordings, "Should show archived recordings for account 1.") // The preference manager for account 2 should not be affected by the root preference manager or // the one for account 1. XCTAssertFalse(prefsManagerForAccount2.shouldShowArchivedRecordings, "Should not show archived recordings for account 2.") prefsManagerForAccount2.shouldShowArchivedRecordings = true XCTAssertTrue(prefsManagerForAccount2.shouldShowArchivedRecordings, "Should show archived recordings for account 2.") } func testUserHasSeenExperimentHighlight() { // Set up a root preference manager and two for specific accounts, and reset each. let rootPrefsManager = PreferenceManager() let prefsManagerForAccount1 = PreferenceManager(accountID: "1") let prefsManagerForAccount2 = PreferenceManager(accountID: "2") [rootPrefsManager, prefsManagerForAccount1, prefsManagerForAccount2].forEach { $0.resetAll() } // Root preference manager. XCTAssertFalse(rootPrefsManager.hasUserSeenExperimentHighlight, "User has not seen experiment highlight yet.") rootPrefsManager.hasUserSeenExperimentHighlight = true XCTAssertTrue(rootPrefsManager.hasUserSeenExperimentHighlight, "User has seen experiment highlight.") // The preference manager for account 1 should not be affected by the root preference manager. XCTAssertFalse(prefsManagerForAccount1.hasUserSeenExperimentHighlight, "User has not seen experiment highlight yet for account 1.") prefsManagerForAccount1.hasUserSeenExperimentHighlight = true XCTAssertTrue(prefsManagerForAccount1.hasUserSeenExperimentHighlight, "User has seen experiment highlight for account 1.") // The preference manager for account 2 should not be affected by the root preference manager or // the one for account 1. XCTAssertFalse(prefsManagerForAccount2.hasUserSeenExperimentHighlight, "User has not seen experiment highlight yet for account 2.") prefsManagerForAccount2.hasUserSeenExperimentHighlight = true XCTAssertTrue(prefsManagerForAccount2.hasUserSeenExperimentHighlight, "User has seen experiment highlight for account 2.") } func testDefaultExperiment() { // Set up a root preference manager and two for specific accounts, and reset each. let rootPrefsManager = PreferenceManager() let prefsManagerForAccount1 = PreferenceManager(accountID: "1") let prefsManagerForAccount2 = PreferenceManager(accountID: "2") [rootPrefsManager, prefsManagerForAccount1, prefsManagerForAccount2].forEach { $0.resetAll() } // Root preference manager. XCTAssertFalse(rootPrefsManager.defaultExperimentWasCreated, "Default experiment has not been created yet.") rootPrefsManager.defaultExperimentWasCreated = true XCTAssertTrue(rootPrefsManager.defaultExperimentWasCreated, "Default experiment was created.") // The preference manager for account 1 should not be affected by the root preference manager. XCTAssertFalse(prefsManagerForAccount1.defaultExperimentWasCreated, "Default experiment has not been created yet for account 1.") prefsManagerForAccount1.defaultExperimentWasCreated = true XCTAssertTrue(prefsManagerForAccount1.defaultExperimentWasCreated, "Default experiment was created for account 1.") // The preference manager for account 2 should not be affected by the root preference manager or // the one for account 1. XCTAssertFalse(prefsManagerForAccount2.defaultExperimentWasCreated, "Default experiment has not been created yet for account 2.") prefsManagerForAccount2.defaultExperimentWasCreated = true XCTAssertTrue(prefsManagerForAccount2.defaultExperimentWasCreated, "Default experiment was created for account 2.") } func testUserHasOptedOutOfUsageTracking() { // Set up a root preference manager and two for specific accounts, and reset each. let rootPrefsManager = PreferenceManager() let prefsManagerForAccount1 = PreferenceManager(accountID: "1") let prefsManagerForAccount2 = PreferenceManager(accountID: "2") [rootPrefsManager, prefsManagerForAccount1, prefsManagerForAccount2].forEach { $0.resetAll() } // Root preference manager. XCTAssertFalse(rootPrefsManager.hasUserOptedOutOfUsageTracking, "User has not opted out of usage tracking.") rootPrefsManager.hasUserOptedOutOfUsageTracking = true XCTAssertTrue(rootPrefsManager.hasUserOptedOutOfUsageTracking, "User has opted out of usage tracking.") // The preference manager for account 1 should not be affected by the root preference manager. XCTAssertFalse(prefsManagerForAccount1.hasUserOptedOutOfUsageTracking, "User has not opted out of usage tracking for account 1.") prefsManagerForAccount1.hasUserOptedOutOfUsageTracking = true XCTAssertTrue(prefsManagerForAccount1.hasUserOptedOutOfUsageTracking, "User has opted out of usage tracking for account 1.") // The preference manager for account 2 should not be affected by the root preference manager or // the one for account 1. XCTAssertFalse(prefsManagerForAccount2.hasUserOptedOutOfUsageTracking, "User has not opted out of usage tracking for account 2.") prefsManagerForAccount2.hasUserOptedOutOfUsageTracking = true XCTAssertTrue(prefsManagerForAccount2.hasUserOptedOutOfUsageTracking, "User has opted out of usage tracking for account 2.") } func testHasUserSeenAudioAndBrightnessSensorBackgroundMessage() { // Set up a root preference manager and two for specific accounts, and reset each. let rootPrefsManager = PreferenceManager() let prefsManagerForAccount1 = PreferenceManager(accountID: "1") let prefsManagerForAccount2 = PreferenceManager(accountID: "2") [rootPrefsManager, prefsManagerForAccount1, prefsManagerForAccount2].forEach { $0.resetAll() } // Root preference manager. XCTAssertFalse(rootPrefsManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has not seen the audio and brightness sensor background message yet.") rootPrefsManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage = true XCTAssertTrue(rootPrefsManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has seen the audio and brightness sensor background message.") // The preference manager for account 1 should not be affected by the root preference manager. XCTAssertFalse(prefsManagerForAccount1.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has not seen the audio and brightness sensor background message yet for " + "account 1.") prefsManagerForAccount1.hasUserSeenAudioAndBrightnessSensorBackgroundMessage = true XCTAssertTrue(prefsManagerForAccount1.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has seen the audio and brightness sensor background message for account 1.") // The preference manager for account 2 should not be affected by the root preference manager or // the one for account 1. XCTAssertFalse(prefsManagerForAccount2.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has not seen the audio and brightness sensor background message yet for " + "account 2.") prefsManagerForAccount2.hasUserSeenAudioAndBrightnessSensorBackgroundMessage = true XCTAssertTrue(prefsManagerForAccount2.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has seen the audio and brightness sensor background message for account 2.") } func testResetAll() { // Set up a root preference manager and two for specific accounts. let rootPrefsManager = PreferenceManager() let prefsManagerForAccount1 = PreferenceManager(accountID: "1") let prefsManagerForAccount2 = PreferenceManager(accountID: "2") // Set everything to true for each preference manager. rootPrefsManager.shouldShowArchivedExperiments = true rootPrefsManager.shouldShowArchivedRecordings = true rootPrefsManager.hasUserSeenExperimentHighlight = true rootPrefsManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage = true rootPrefsManager.defaultExperimentWasCreated = true rootPrefsManager.hasUserOptedOutOfUsageTracking = true prefsManagerForAccount1.shouldShowArchivedExperiments = true prefsManagerForAccount1.shouldShowArchivedRecordings = true prefsManagerForAccount1.hasUserSeenExperimentHighlight = true prefsManagerForAccount1.hasUserSeenAudioAndBrightnessSensorBackgroundMessage = true prefsManagerForAccount1.defaultExperimentWasCreated = true prefsManagerForAccount1.hasUserOptedOutOfUsageTracking = true prefsManagerForAccount2.shouldShowArchivedExperiments = true prefsManagerForAccount2.shouldShowArchivedRecordings = true prefsManagerForAccount2.hasUserSeenExperimentHighlight = true prefsManagerForAccount2.hasUserSeenAudioAndBrightnessSensorBackgroundMessage = true prefsManagerForAccount2.defaultExperimentWasCreated = true prefsManagerForAccount2.hasUserOptedOutOfUsageTracking = true // Everything in the root preference manager should be true. XCTAssertTrue(rootPrefsManager.shouldShowArchivedExperiments, "Should show archived experiments.") XCTAssertTrue(rootPrefsManager.shouldShowArchivedRecordings, "Should show archived recordings.") XCTAssertTrue(rootPrefsManager.hasUserSeenExperimentHighlight, "User has seen experiment highlight.") XCTAssertTrue(rootPrefsManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has seen audio and brightness sensor background message.") XCTAssertTrue(rootPrefsManager.defaultExperimentWasCreated, "Default experiment was created.") XCTAssertTrue(rootPrefsManager.hasUserOptedOutOfUsageTracking, "User has opted out of usage tracking.") // Reset the root preference manager, and everything should be false (or nil). rootPrefsManager.resetAll() XCTAssertFalse(rootPrefsManager.shouldShowArchivedExperiments, "Should not show archived experiments.") XCTAssertFalse(rootPrefsManager.shouldShowArchivedRecordings, "Should not show archived recordings.") XCTAssertFalse(rootPrefsManager.hasUserSeenExperimentHighlight, "User has not seen experiment highlight.") XCTAssertFalse(rootPrefsManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has not seen audio and brightness sensor background message.") XCTAssertFalse(rootPrefsManager.defaultExperimentWasCreated, "Default experiment was not created.") XCTAssertFalse(rootPrefsManager.hasUserOptedOutOfUsageTracking, "User has not opted out of usage tracking.") // Everything in the preference manager for account 1 should be true, despite resetting the root // preference manager. XCTAssertTrue(prefsManagerForAccount1.shouldShowArchivedExperiments, "Should show archived experiments for account 1.") XCTAssertTrue(prefsManagerForAccount1.shouldShowArchivedRecordings, "Should show archived recordings for account 1.") XCTAssertTrue(prefsManagerForAccount1.hasUserSeenExperimentHighlight, "User has seen experiment highlight for account 1.") XCTAssertTrue(prefsManagerForAccount1.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has seen audio and brightness sensor background message for account 1.") XCTAssertTrue(prefsManagerForAccount1.defaultExperimentWasCreated, "Default experiment was created for account 1.") XCTAssertTrue(prefsManagerForAccount1.hasUserOptedOutOfUsageTracking, "User has opted out of usage tracking for account 1.") // Reset the preference manager for account 1, and everything should be false (or nil). prefsManagerForAccount1.resetAll() XCTAssertFalse(prefsManagerForAccount1.shouldShowArchivedExperiments, "Should not show archived experiments for account 1.") XCTAssertFalse(prefsManagerForAccount1.shouldShowArchivedRecordings, "Should not show archived recordings for account 1.") XCTAssertFalse(prefsManagerForAccount1.hasUserSeenExperimentHighlight, "User has not seen experiment highlight for account 1.") XCTAssertFalse(prefsManagerForAccount1.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has not seen audio and brightness sensor background message for account " + "1.") XCTAssertFalse(prefsManagerForAccount1.defaultExperimentWasCreated, "Default experiment was not created for account 1.") XCTAssertFalse(prefsManagerForAccount1.hasUserOptedOutOfUsageTracking, "User has not opted out of usage tracking for account 1.") // Everything in the preference manager for account 2 should be true, despite resetting the root // preference manager and the one for account 1. XCTAssertTrue(prefsManagerForAccount2.shouldShowArchivedExperiments, "Should show archived experiments for account 2.") XCTAssertTrue(prefsManagerForAccount2.shouldShowArchivedRecordings, "Should show archived recordings for account 2.") XCTAssertTrue(prefsManagerForAccount2.hasUserSeenExperimentHighlight, "User has seen experiment highlight for account 2.") XCTAssertTrue(prefsManagerForAccount2.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has seen audio and brightness sensor background message for account 2.") XCTAssertTrue(prefsManagerForAccount2.defaultExperimentWasCreated, "Default experiment was created for account 2.") XCTAssertTrue(prefsManagerForAccount2.hasUserOptedOutOfUsageTracking, "User has opted out of usage tracking for account 2.") // Reset the preference manager for account 2, and everything should be false (or nil). prefsManagerForAccount2.resetAll() XCTAssertFalse(prefsManagerForAccount2.shouldShowArchivedExperiments, "Should not show archived experiments for account 2.") XCTAssertFalse(prefsManagerForAccount2.shouldShowArchivedRecordings, "Should not show archived recordings for account 2.") XCTAssertFalse(prefsManagerForAccount2.hasUserSeenExperimentHighlight, "User has not seen experiment highlight for account 2.") XCTAssertFalse(prefsManagerForAccount2.hasUserSeenAudioAndBrightnessSensorBackgroundMessage, "User has not seen audio and brightness sensor background message for account " + "2.") XCTAssertFalse(prefsManagerForAccount2.defaultExperimentWasCreated, "Default experiment was not created for account 2.") XCTAssertFalse(prefsManagerForAccount2.hasUserOptedOutOfUsageTracking, "User has not opted out of usage tracking for account 2.") } func testMigratePreferencesFromManager() { let preferenceManagerToCopy = PreferenceManager() let preferenceManager = PreferenceManager(accountID: "test") preferenceManager.resetAll() // Set preferences to true. preferenceManagerToCopy.shouldShowArchivedExperiments = true preferenceManagerToCopy.shouldShowArchivedRecordings = true preferenceManagerToCopy.hasUserSeenExperimentHighlight = true preferenceManagerToCopy.hasUserSeenAudioAndBrightnessSensorBackgroundMessage = true preferenceManagerToCopy.defaultExperimentWasCreated = true preferenceManagerToCopy.hasUserOptedOutOfUsageTracking = true // Migrate preferences. preferenceManager.migratePreferences(fromManager: preferenceManagerToCopy) // Assert the preference that should be migrated is true. XCTAssertTrue(preferenceManager.hasUserOptedOutOfUsageTracking) // The rest should be the default value. XCTAssertFalse(preferenceManager.shouldShowArchivedExperiments) XCTAssertFalse(preferenceManager.shouldShowArchivedRecordings) XCTAssertFalse(preferenceManager.hasUserSeenExperimentHighlight) XCTAssertFalse(preferenceManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage) XCTAssertFalse(preferenceManager.defaultExperimentWasCreated) // Set the preference that migrates to false. preferenceManagerToCopy.hasUserOptedOutOfUsageTracking = false // Migrate preferences. preferenceManager.migratePreferences(fromManager: preferenceManagerToCopy) // Assert the preference that should be migrated is false. XCTAssertFalse(preferenceManager.hasUserOptedOutOfUsageTracking) // The rest should still be the default value. XCTAssertFalse(preferenceManager.shouldShowArchivedExperiments) XCTAssertFalse(preferenceManager.shouldShowArchivedRecordings) XCTAssertFalse(preferenceManager.hasUserSeenExperimentHighlight) XCTAssertFalse(preferenceManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage) XCTAssertFalse(preferenceManager.defaultExperimentWasCreated) } func testMigrateRemoveUserBirthdate() { // Build the birthdate key to match what preference manager uses. let accountID = "accountID" let birthdateKey = "GSJ_UserBirthdate_\(accountID)" // Set a date in user defaults the user, then create a preference manager. It should // remove the birthdate. UserDefaults.standard.set(Date(), forKey: birthdateKey) let _ = PreferenceManager(accountID: accountID) XCTAssertNil(UserDefaults.standard.object(forKey: birthdateKey), "The birthdate should be removed from user defaults.") } }
apache-2.0
f90460bfd0072bfc0164b7ebf5239f3b
56.476563
100
0.759458
5.538519
false
false
false
false
ldt25290/MyInstaMap
ThirdParty/ObjectMapper/Tests/ObjectMapperTests/ImmutableTests.swift
3
18860
// // ImmutableTests.swift // ObjectMapper // // Created by Suyeol Jeon on 23/09/2016. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import XCTest import ObjectMapper class ImmutableObjectTests: XCTestCase { let JSON: [String: Any] = [ // Basic types "prop1": "Immutable!", "prop2": 255, "prop3": true, // prop4 has a default value // String "prop5": "prop5", "prop6": "prop6", "prop7": "prop7", // [String] "prop8": ["prop8"], "prop9": ["prop9"], "prop10": ["prop10"], // [String: String] "prop11": ["key": "prop11"], "prop12": ["key": "prop12"], "prop13": ["key": "prop13"], // Base "prop14": ["base": "prop14"], "prop15": ["base": "prop15"], "prop16": ["base": "prop16"], // [Base] "prop17": [["base": "prop17"]], "prop18": [["base": "prop18"]], "prop19": [["base": "prop19"]], // [String: Base] "prop20": ["key": ["base": "prop20"]], "prop21": ["key": ["base": "prop21"]], "prop22": ["key": ["base": "prop22"]], // Optional with immutables "prop23": "Optional", "prop24": 255, "prop25": true, "prop26": 255.0, // RawRepresentable "prop27a": NSNumber(value: 0), "prop27b": NSNumber(value: 1000), "prop27c": [NSNumber(value: 0), NSNumber(value: 1000)], "prop28a": Int(0), "prop28b": Int(255), "prop28c": [Int(0), Int(255)], "prop29a": Double(0), "prop29b": Double(100), "prop29c": [Double(0), Double(100)], "prop30a": Float(0), "prop30b": Float(100), "prop30c": [Float(0), Float(100)], "prop31a": "String A", "prop31b": "String B", "prop31c": ["String A", "String B"], // [[String]] "prop32": [["prop32"]], "prop33": [["prop33"]], "prop34": [["prop34"]], // [[Base]] "prop35": [[["base": "prop35"]]], "prop36": [[["base": "prop36"]]], "prop37": [[["base": "prop37"]]], "non.nested->key": "string", "nested": [ "int": 123, "string": "hello", "array": ["a", "b", "c"], "dictionary": ["a": 10, "b": 20, "c": 30], ], "com.hearst.ObjectMapper.nested": [ "com.hearst.ObjectMapper.int": 123, "com.hearst.ObjectMapper.string": "hello", "array": ["a", "b", "c"], "dictionary": ["a": 10, "b": 20, "c": 30], ] ] func testImmutableMappable() { let mapper = Mapper<Struct>() let immutable: Struct = try! mapper.map(JSON: JSON) XCTAssertNotNil(immutable) XCTAssertEqual(immutable.prop1, "Immutable!") XCTAssertEqual(immutable.prop2, 255) XCTAssertEqual(immutable.prop3, true) XCTAssertEqual(immutable.prop4, .greatestFiniteMagnitude) XCTAssertEqual(immutable.prop5, "prop5_TRANSFORMED") XCTAssertEqual(immutable.prop6, "prop6_TRANSFORMED") XCTAssertEqual(immutable.prop7, "prop7_TRANSFORMED") XCTAssertEqual(immutable.prop8, ["prop8_TRANSFORMED"]) XCTAssertEqual(immutable.prop9!, ["prop9_TRANSFORMED"]) XCTAssertEqual(immutable.prop10, ["prop10_TRANSFORMED"]) XCTAssertEqual(immutable.prop11, ["key": "prop11_TRANSFORMED"]) XCTAssertEqual(immutable.prop12!, ["key": "prop12_TRANSFORMED"]) XCTAssertEqual(immutable.prop13, ["key": "prop13_TRANSFORMED"]) XCTAssertEqual(immutable.prop14.base, "prop14") XCTAssertEqual(immutable.prop15?.base, "prop15") XCTAssertEqual(immutable.prop16.base, "prop16") XCTAssertEqual(immutable.prop17[0].base, "prop17") XCTAssertEqual(immutable.prop18![0].base, "prop18") XCTAssertEqual(immutable.prop19[0].base, "prop19") XCTAssertEqual(immutable.prop20["key"]!.base, "prop20") XCTAssertEqual(immutable.prop21!["key"]!.base, "prop21") XCTAssertEqual(immutable.prop22["key"]!.base, "prop22") XCTAssertEqual(immutable.prop23!, "Optional") XCTAssertEqual(immutable.prop24!, 255) XCTAssertEqual(immutable.prop25!, true) XCTAssertEqual(immutable.prop26!, 255.0) XCTAssertEqual(immutable.prop27a.rawValue, Int64Enum.a.rawValue) XCTAssertEqual(immutable.prop27b.rawValue, Int64Enum.b.rawValue) XCTAssertEqual(immutable.prop27c, [Int64Enum.a, Int64Enum.b]) XCTAssertEqual(immutable.prop28a.rawValue, IntEnum.a.rawValue) XCTAssertEqual(immutable.prop28b.rawValue, IntEnum.b.rawValue) XCTAssertEqual(immutable.prop28c, [IntEnum.a, IntEnum.b]) XCTAssertEqual(immutable.prop29a.rawValue, DoubleEnum.a.rawValue) XCTAssertEqual(immutable.prop29b.rawValue, DoubleEnum.b.rawValue) XCTAssertEqual(immutable.prop29c, [DoubleEnum.a, DoubleEnum.b]) XCTAssertEqual(immutable.prop30a.rawValue, FloatEnum.a.rawValue) XCTAssertEqual(immutable.prop30b.rawValue, FloatEnum.b.rawValue) XCTAssertEqual(immutable.prop30c, [FloatEnum.a, FloatEnum.b]) XCTAssertEqual(immutable.prop31a.rawValue, StringEnum.A.rawValue) XCTAssertEqual(immutable.prop31b.rawValue, StringEnum.B.rawValue) XCTAssertEqual(immutable.prop31c, [StringEnum.A, StringEnum.B]) XCTAssertEqual(immutable.prop32[0][0], "prop32_TRANSFORMED") XCTAssertEqual(immutable.prop33![0][0], "prop33_TRANSFORMED") XCTAssertEqual(immutable.prop34[0][0], "prop34_TRANSFORMED") XCTAssertEqual(immutable.prop35[0][0].base, "prop35") XCTAssertEqual(immutable.prop36![0][0].base, "prop36") XCTAssertEqual(immutable.prop37[0][0].base, "prop37") XCTAssertEqual(immutable.nonnestedString, "string") XCTAssertEqual(immutable.nestedInt, 123) XCTAssertEqual(immutable.nestedString, "hello") XCTAssertEqual(immutable.nestedArray, ["a", "b", "c"]) XCTAssertEqual(immutable.nestedDictionary, ["a": 10, "b": 20, "c": 30]) XCTAssertEqual(immutable.delimiterNestedInt, 123) XCTAssertEqual(immutable.delimiterNestedString, "hello") XCTAssertEqual(immutable.delimiterNestedArray, ["a", "b", "c"]) XCTAssertEqual(immutable.delimiterNestedDictionary, ["a": 10, "b": 20, "c": 30]) let JSON2: [String: Any] = [ "prop1": "prop1", "prop2": NSNull() ] let immutable2 = try? mapper.map(JSON: JSON2) XCTAssertNil(immutable2) // TODO: ImmutableMappable to JSON let JSONFromObject = mapper.toJSON(immutable) let objectFromJSON = try? mapper.map(JSON: JSONFromObject) XCTAssertNotNil(objectFromJSON) assertImmutableObjectsEqual(objectFromJSON!, immutable) } func testMappingFromArray() { let JSONArray: [[String: Any]] = [JSON] let array: [Struct] = try! Mapper<Struct>().mapArray(JSONArray: JSONArray) XCTAssertNotNil(array.first) } func testMappingFromDictionary() { let JSONDictionary: [String: [String: Any]] = [ "key1": JSON, "key2": JSON, ] let dictionary: [String: Struct] = try! Mapper<Struct>().mapDictionary(JSON: JSONDictionary) XCTAssertNotNil(dictionary.first) XCTAssertEqual(dictionary.count, 2) XCTAssertEqual(Set(dictionary.keys), Set(["key1", "key2"])) } func testMappingFromDictionary_empty() { let JSONDictionary: [String: [String: Any]] = [:] let dictionary: [String: Struct] = try! Mapper<Struct>().mapDictionary(JSON: JSONDictionary) XCTAssertTrue(dictionary.isEmpty) } func testMappingFromDictionary_throws() { let JSONDictionary: [String: [String: Any]] = [ "key1": JSON, "key2": ["invalid": "dictionary"], ] XCTAssertThrowsError(try Mapper<Struct>().mapDictionary(JSON: JSONDictionary)) } func testMappingFromDictionaryOfArrays() { let JSONDictionary: [String: [[String: Any]]] = [ "key1": [JSON, JSON], "key2": [JSON], "key3": [], ] let dictionary: [String: [Struct]] = try! Mapper<Struct>().mapDictionaryOfArrays(JSON: JSONDictionary) XCTAssertNotNil(dictionary.first) XCTAssertEqual(dictionary.count, 3) XCTAssertEqual(Set(dictionary.keys), Set(["key1", "key2", "key3"])) XCTAssertEqual(dictionary["key1"]?.count, 2) XCTAssertEqual(dictionary["key2"]?.count, 1) XCTAssertEqual(dictionary["key3"]?.count, 0) } func testMappingFromDictionaryOfArrays_empty() { let JSONDictionary: [String: [[String: Any]]] = [:] let dictionary: [String: [Struct]] = try! Mapper<Struct>().mapDictionaryOfArrays(JSON: JSONDictionary) XCTAssertTrue(dictionary.isEmpty) } func testMappingFromDictionaryOfArrays_throws() { let JSONDictionary: [String: [[String: Any]]] = [ "key1": [JSON], "key2": [["invalid": "dictionary"]], ] XCTAssertThrowsError(try Mapper<Struct>().mapDictionaryOfArrays(JSON: JSONDictionary)) } func testMappingArrayOfArrays() { let JSONArray: [[[String: Any]]] = [ [JSON, JSON], [JSON], [], ] let array: [[Struct]] = try! Mapper<Struct>().mapArrayOfArrays(JSONObject: JSONArray) XCTAssertNotNil(array.first) XCTAssertEqual(array.count, 3) XCTAssertEqual(array[0].count, 2) XCTAssertEqual(array[1].count, 1) XCTAssertEqual(array[2].count, 0) } func testMappingArrayOfArrays_empty() { let JSONArray: [[[String: Any]]] = [] let array: [[Struct]] = try! Mapper<Struct>().mapArrayOfArrays(JSONObject: JSONArray) XCTAssertTrue(array.isEmpty) } func testMappingArrayOfArrays_throws() { let JSONArray: [[[String: Any]]] = [ [JSON], [["invalid": "dictionary"]], ] XCTAssertThrowsError(try Mapper<Struct>().mapArrayOfArrays(JSONObject: JSONArray)) } func testAsPropertyOfMappable() { struct ImmutableObject: ImmutableMappable { let value: String init(map: Map) throws { self.value = try map.value("value") } } struct Object: Mappable { var immutable: ImmutableObject! init?(map: Map) {} mutating func mapping(map: Map) { self.immutable <- map["immutable"] } } let json: [String: Any] = [ "immutable": [ "value": "Hello" ] ] let object = Mapper<Object>().map(JSON: json) XCTAssertEqual(object?.immutable?.value, "Hello") } } struct Struct { let prop1: String let prop2: Int let prop3: Bool let prop4: Double let prop5: String let prop6: String? let prop7: String! let prop8: [String] let prop9: [String]? let prop10: [String]! let prop11: [String: String] let prop12: [String: String]? let prop13: [String: String]! let prop14: Base let prop15: Base? let prop16: Base! let prop17: [Base] let prop18: [Base]? let prop19: [Base]! let prop20: [String: Base] let prop21: [String: Base]? let prop22: [String: Base]! // Optionals var prop23: String? var prop24: Int? var prop25: Bool? var prop26: Double? // RawRepresentable let prop27a: Int64Enum let prop27b: Int64Enum let prop27c: [Int64Enum] let prop28a: IntEnum let prop28b: IntEnum let prop28c: [IntEnum] let prop29a: DoubleEnum let prop29b: DoubleEnum let prop29c: [DoubleEnum] let prop30a: FloatEnum let prop30b: FloatEnum let prop30c: [FloatEnum] let prop31a: StringEnum let prop31b: StringEnum let prop31c: [StringEnum] let prop32: [[String]] let prop33: [[String]]? let prop34: [[String]]! let prop35: [[Base]] let prop36: [[Base]]? let prop37: [[Base]]! var nonnestedString: String var nestedInt: Int var nestedString: String var nestedArray: [String] var nestedDictionary: [String: Int] var delimiterNestedInt: Int var delimiterNestedString: String var delimiterNestedArray: [String] var delimiterNestedDictionary: [String: Int] } extension Struct: ImmutableMappable { init(map: Map) throws { prop1 = try map.value("prop1") prop2 = try map.value("prop2") prop3 = try map.value("prop3") prop4 = (try? map.value("prop4")) ?? .greatestFiniteMagnitude prop5 = try map.value("prop5", using: stringTransform) prop6 = try? map.value("prop6", using: stringTransform) prop7 = try? map.value("prop7", using: stringTransform) prop8 = try map.value("prop8", using: stringTransform) prop9 = try? map.value("prop9", using: stringTransform) prop10 = try? map.value("prop10", using: stringTransform) prop11 = try map.value("prop11", using: stringTransform) prop12 = try? map.value("prop12", using: stringTransform) prop13 = try? map.value("prop13", using: stringTransform) prop14 = try map.value("prop14") prop15 = try? map.value("prop15") prop16 = try? map.value("prop16") prop17 = try map.value("prop17") prop18 = try? map.value("prop18") prop19 = try? map.value("prop19") prop20 = try map.value("prop20") prop21 = try? map.value("prop21") prop22 = try? map.value("prop22") prop27a = try map.value("prop27a") prop27b = try map.value("prop27b") prop27c = try map.value("prop27c") prop28a = try map.value("prop28a") prop28b = try map.value("prop28b") prop28c = try map.value("prop28c") prop29a = try map.value("prop29a") prop29b = try map.value("prop29b") prop29c = try map.value("prop29c") prop30a = try map.value("prop30a") prop30b = try map.value("prop30b") prop30c = try map.value("prop30c") prop31a = try map.value("prop31a") prop31b = try map.value("prop31b") prop31c = try map.value("prop31c") prop32 = try map.value("prop32", using: stringTransform) prop33 = try? map.value("prop33", using: stringTransform) prop34 = try? map.value("prop34", using: stringTransform) prop35 = try map.value("prop35") prop36 = try? map.value("prop36") prop37 = try? map.value("prop37") nonnestedString = try map.value("non.nested->key", nested: false) nestedInt = try map.value("nested.int") nestedString = try map.value("nested.string") nestedArray = try map.value("nested.array") nestedDictionary = try map.value("nested.dictionary") delimiterNestedInt = try map.value("com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.int", delimiter: "->") delimiterNestedString = try map.value("com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.string", delimiter: "->") delimiterNestedArray = try map.value("com.hearst.ObjectMapper.nested->array", delimiter: "->") delimiterNestedDictionary = try map.value("com.hearst.ObjectMapper.nested->dictionary", delimiter: "->") } mutating func mapping(map: Map) { prop23 <- map["prop23"] prop24 <- map["prop24"] prop25 <- map["prop25"] prop26 <- map["prop26"] prop1 >>> map["prop1"] prop2 >>> map["prop2"] prop3 >>> map["prop3"] prop4 >>> map["prop4"] prop5 >>> (map["prop5"], stringTransform) prop6 >>> (map["prop6"], stringTransform) prop7 >>> (map["prop7"], stringTransform) prop8 >>> (map["prop8"], stringTransform) prop9 >>> (map["prop9"], stringTransform) prop10 >>> (map["prop10"], stringTransform) prop11 >>> (map["prop11"], stringTransform) prop12 >>> (map["prop12"], stringTransform) prop13 >>> (map["prop13"], stringTransform) prop14 >>> map["prop14"] prop15 >>> map["prop15"] prop16 >>> map["prop16"] prop17 >>> map["prop17"] prop18 >>> map["prop18"] prop19 >>> map["prop19"] prop20 >>> map["prop20"] prop21 >>> map["prop21"] prop22 >>> map["prop22"] prop27a >>> map["prop27a"] prop27b >>> map["prop27b"] prop27c >>> map["prop27c"] prop28a >>> map["prop28a"] prop28b >>> map["prop28b"] prop28c >>> map["prop28c"] prop29a >>> map["prop29a"] prop29b >>> map["prop29b"] prop29c >>> map["prop29c"] prop30a >>> map["prop30a"] prop30b >>> map["prop30b"] prop30c >>> map["prop30c"] prop31a >>> map["prop31a"] prop31b >>> map["prop31b"] prop31c >>> map["prop31c"] prop32 >>> (map["prop32"], stringTransform) prop33 >>> (map["prop33"], stringTransform) prop34 >>> (map["prop34"], stringTransform) prop35 >>> map["prop35"] prop36 >>> map["prop36"] prop37 >>> map["prop37"] nonnestedString >>> map["non.nested->key", nested: false] nestedInt >>> map["nested.int"] nestedString >>> map["nested.string"] nestedArray >>> map["nested.array"] nestedDictionary >>> map["nested.dictionary"] delimiterNestedInt >>> map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.int", delimiter: "->"] delimiterNestedString >>> map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.string", delimiter: "->"] delimiterNestedArray >>> map["com.hearst.ObjectMapper.nested->array", delimiter: "->"] delimiterNestedDictionary >>> map["com.hearst.ObjectMapper.nested->dictionary", delimiter: "->"] } } let stringTransform = TransformOf<String, String>( fromJSON: { (str: String?) -> String? in guard let str = str else { return nil } return "\(str)_TRANSFORMED" }, toJSON: { (str: String?) -> String? in return str?.replacingOccurrences(of: "_TRANSFORMED", with: "") } ) private func assertImmutableObjectsEqual(_ lhs: Struct, _ rhs: Struct) { XCTAssertEqual(lhs.prop1, rhs.prop1) XCTAssertEqual(lhs.prop2, rhs.prop2) XCTAssertEqual(lhs.prop3, rhs.prop3) XCTAssertEqual(lhs.prop4, rhs.prop4) XCTAssertEqual(lhs.prop5, rhs.prop5) XCTAssertEqual(lhs.prop6, rhs.prop6) XCTAssertEqual(lhs.prop7, rhs.prop7) XCTAssertEqual(lhs.prop8, rhs.prop8) XCTAssertEqual(lhs.prop23, rhs.prop23) // @hack: compare arrays and objects with their string representation. XCTAssertEqual("\(lhs.prop9 as Optional)", "\(rhs.prop9 as Optional)") XCTAssertEqual("\(lhs.prop10)", "\(rhs.prop10)") XCTAssertEqual("\(lhs.prop11)", "\(rhs.prop11)") XCTAssertEqual("\(lhs.prop12 as Optional)", "\(rhs.prop12 as Optional)") XCTAssertEqual("\(lhs.prop13)", "\(rhs.prop13)") XCTAssertEqual("\(lhs.prop14)", "\(rhs.prop14)") XCTAssertEqual("\(lhs.prop15 as Optional)", "\(rhs.prop15 as Optional)") XCTAssertEqual("\(lhs.prop16)", "\(rhs.prop16)") XCTAssertEqual("\(lhs.prop17)", "\(rhs.prop17)") XCTAssertEqual("\(lhs.prop18 as Optional)", "\(rhs.prop18 as Optional)") XCTAssertEqual("\(lhs.prop19)", "\(rhs.prop19)") XCTAssertEqual("\(lhs.prop20)", "\(rhs.prop20)") XCTAssertEqual("\(lhs.prop21 as Optional)", "\(rhs.prop21 as Optional)") XCTAssertEqual("\(lhs.prop22)", "\(rhs.prop22)") XCTAssertEqual("\(lhs.prop32)", "\(rhs.prop32)") XCTAssertEqual("\(lhs.prop33 as Optional)", "\(rhs.prop33 as Optional)") XCTAssertEqual("\(lhs.prop34)", "\(rhs.prop34)") XCTAssertEqual("\(lhs.prop35)", "\(rhs.prop35)") XCTAssertEqual("\(lhs.prop36 as Optional)", "\(rhs.prop36 as Optional)") XCTAssertEqual("\(lhs.prop37)", "\(rhs.prop37)") }
mit
954f6fe13dd70051beb2f8a363116a88
30.07084
122
0.68176
3.187965
false
false
false
false
nnsnodnb/nowplaying-ios
NowPlayingTests/Tests/ViewModels/Play/TestPlayViewModelArtworkScale.swift
1
3220
// // TestPlayViewModelArtworkScale.swift // NowPlayingTests // // Created by Yuya Oka on 2022/05/04. // @testable import NowPlaying import RxSwift import RxTest import XCTest final class TestPlayViewModelArtworkScale: XCTestCase { // MARK: - Properties var router: PlayerRoutable! var disposeBag: DisposeBag! var testScheduler: TestScheduler! // MARK: - Life Cycle override func setUp() { super.setUp() router = PlayerRouter() disposeBag = .init() testScheduler = .init(initialClock: 0) } override func tearDown() { super.tearDown() router = nil disposeBag = nil testScheduler = nil } func test再生されていないので0_9() { let mediaItem = StubMediaItem(title: "タイトル", artist: "アーティスト", artwork: nil) let musicPlayerController = StubMusicPlayerController(mediaItem: mediaItem, playbackState: .paused) let viewModel = PlayViewModel(router: router, musicPlayerController: musicPlayerController) let observer = testScheduler.createObserver(CGFloat.self) viewModel.outputs.artworkScale.drive(observer).disposed(by: disposeBag) XCTAssertEqual(observer.events, [.next(0, 0.9)]) } func test再生されているので1_0() { let mediaItem = StubMediaItem(title: "タイトル", artist: "アーティスト", artwork: nil) let musicPlayerController = StubMusicPlayerController(mediaItem: mediaItem, playbackState: .playing) let viewModel = PlayViewModel(router: router, musicPlayerController: musicPlayerController) let observer = testScheduler.createObserver(CGFloat.self) viewModel.outputs.artworkScale.drive(observer).disposed(by: disposeBag) XCTAssertEqual(observer.events, [.next(0, 1.0)]) } func test一時停止から再生が始まったので1_0() { let mediaItem = StubMediaItem(title: "タイトル", artist: "アーティスト", artwork: nil) let musicPlayerController = StubMusicPlayerController(mediaItem: mediaItem, playbackState: .paused) let viewModel = PlayViewModel(router: router, musicPlayerController: musicPlayerController) let observer = testScheduler.createObserver(CGFloat.self) viewModel.outputs.artworkScale.drive(observer).disposed(by: disposeBag) testScheduler.advanceTo(1) viewModel.inputs.playPause.accept(()) XCTAssertEqual(observer.events, [.next(0, 0.9), .next(1, 1.0)]) } func test再生中から一時停止になったので0_9() { let mediaItem = StubMediaItem(title: "タイトル", artist: "アーティスト", artwork: nil) let musicPlayerController = StubMusicPlayerController(mediaItem: mediaItem, playbackState: .playing) let viewModel = PlayViewModel(router: router, musicPlayerController: musicPlayerController) let observer = testScheduler.createObserver(CGFloat.self) viewModel.outputs.artworkScale.drive(observer).disposed(by: disposeBag) testScheduler.advanceTo(1) viewModel.inputs.playPause.accept(()) XCTAssertEqual(observer.events, [.next(0, 1.0), .next(1, 0.9)]) } }
mit
fa4060392eff09182bdd6f83480af5ba
36.555556
108
0.697567
4.345714
false
true
false
false
haawa799/WaniKit2
Sources/WaniKit/Model/UserInfo.swift
3
1634
// // User.swift // Pods // // Created by Andriy K. on 12/10/15. // // import Foundation public struct UserInfo { // Dictionary keys private static let keyUsername = "username" private static let keyGravatar = "gravatar" private static let keyLevel = "level" private static let keyTitle = "title" private static let keyAbout = "about" private static let keyWebsite = "website" private static let keyTwitter = "twitter" private static let keyTopicsCount = "topics_count" private static let keyPostsCount = "posts_count" private static let keyCreationDate = "creation_date" public var username: String public var gravatar: String? public var level: Int? public var title: String? public var about: String? public var website: String? public var twitter: String? public var topicsCount: Int? public var postsCount: Int? public var creationDate: NSDate? } extension UserInfo: DictionaryInitialization { public init(dict: NSDictionary) { username = dict[UserInfo.keyUsername] as! String if let creation = dict[UserInfo.keyCreationDate] as? Int { creationDate = NSDate(timeIntervalSince1970: NSTimeInterval(creation)) } gravatar = (dict[UserInfo.keyGravatar] as? String) level = (dict[UserInfo.keyLevel] as? Int) title = (dict[UserInfo.keyTitle] as? String) about = (dict[UserInfo.keyAbout] as? String) website = (dict[UserInfo.keyWebsite] as? String) twitter = (dict[UserInfo.keyTwitter] as? String) topicsCount = (dict[UserInfo.keyTopicsCount] as? Int) postsCount = (dict[UserInfo.keyPostsCount] as? Int) } }
mit
150b68de6314898a35b24fac57c0a34f
27.666667
76
0.706854
3.937349
false
false
false
false
meteochu/HanekeSwift
Haneke/Haneke.swift
1
1360
// // Haneke.swift // Haneke // // Created by Hermes Pique on 9/9/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit public struct HanekeGlobals { public static let Domain = "io.haneke" } public struct Shared { public static var imageCache : Cache<UIImage> { struct Static { static let name = "shared-images" static let cache = Cache<UIImage>(name: name) } return Static.cache } public static var dataCache : Cache<Data> { struct Static { static let name = "shared-data" static let cache = Cache<Data>(name: name) } return Static.cache } public static var stringCache : Cache<String> { struct Static { static let name = "shared-strings" static let cache = Cache<String>(name: name) } return Static.cache } public static var JSONCache : Cache<JSON> { struct Static { static let name = "shared-json" static let cache = Cache<JSON>(name: name) } return Static.cache } } func errorWithCode(code: Int, description: String) -> NSError { let userInfo = [NSLocalizedDescriptionKey: description] return NSError(domain: HanekeGlobals.Domain, code: code, userInfo: userInfo) }
apache-2.0
362c4112103679b6b5d7208938c3a060
23.727273
80
0.589706
4.37299
false
false
false
false
liuxuan30/OJProblems
OCOJ/OCOJ/HeapSolution.swift
1
1621
// // HeapSolution.swift // OCOJ // // Created by Xuan on 3/21/16. // Copyright © 2016 Wingzero. All rights reserved. // import Foundation public class HeapSolution: Solution { func buildHeap(inout nums: [Int]) { guard nums.count > 0 else { return } let count = nums.count for i in (1 ... count / 2).reverse() { adjustHeap(&nums, i, nums.count) } } /** I use 0...count-1 version right now. Revert to commit 13ad2eccb0d35e940d0fbdb075510f1f4a7c41f7 for 1...count version */ func adjustHeap(inout nums: [Int], _ position: Int, _ size: Int) { var i = position while i <= size { let left = 2 * i let right = left + 1 var largest = i - 1 if left - 1 < size && nums[largest] < nums[left - 1] { largest = left - 1 } if right - 1 < size && nums[largest] < nums[right - 1] { largest = right - 1 } if largest != i - 1 { swap(&nums[i - 1], &nums[largest]) i = largest + 1 } else { break } } } func heapSort(inout nums: [Int]) { buildHeap(&nums) for i in (2 ... nums.count).reverse() { swap(&nums[i - 1], &nums[1 - 1]) adjustHeap(&nums, 1, i - 1) } } func testSort() { var nums = [3,1,2,5,7,4,11,13,10,8,9,15] heapSort(&nums) print(nums) } }
mit
c1f49211710e2e91e140a7235ffa6966
23.560606
121
0.445062
3.681818
false
false
false
false
maximveksler/Developing-iOS-8-Apps-with-Swift
lesson-017/Autolayout Localized/Autolayout/ViewController.swift
5
6738
// // ViewController.swift // Autolayout // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit class ViewController: UIViewController { // after the demo, appropriate things were private-ized. // including outlets and actions. @IBOutlet private weak var loginField: UITextField! @IBOutlet private weak var passwordField: UITextField! @IBOutlet private weak var passwordLabel: UILabel! @IBOutlet private weak var companyLabel: UILabel! @IBOutlet private weak var nameLabel: UILabel! @IBOutlet private weak var imageView: UIImageView! @IBOutlet weak var lastLoginLabel: UILabel! // our Model, the logged in user var loggedInUser: User? { didSet { updateUI() } } // sets whether the password field is secure or not var secure: Bool = false { didSet { updateUI() } } // update the user-interface // by transferring information from the Model to our View // and setting up security in the password fields // // NOTE: After the demo, this method was protected against // crashing if it is called before our outlets are set. // This is nice to do since setting our Model calls this // and our Model might get set while we are being prepared. // It was easy too. Just added ? after outlets. // private func updateUI() { passwordField?.secureTextEntry = secure let password = NSLocalizedString("Password", comment: "Prompt for the user's password when it is not secure (i.e. plain text)") let securedPassword = NSLocalizedString("Secured Password", comment: "Prompt for an obscured (not plain text) password") passwordLabel?.text = secure ? securedPassword : password nameLabel?.text = loggedInUser?.name companyLabel?.text = loggedInUser?.company image = loggedInUser?.image if let lastLogin = loggedInUser?.lastLogin { let dateFormatter = NSDateFormatter() dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle let time = dateFormatter.stringFromDate(lastLogin) let numberFormatter = NSNumberFormatter() numberFormatter.maximumFractionDigits = 1 let daysAgo = numberFormatter.stringFromNumber(-lastLogin.timeIntervalSinceNow/(60*60*24))! let lastLoginFormatString = NSLocalizedString("Last Login %@ days ago at %@", comment: "Reports the number of days ago and time that the user last logged in") lastLoginLabel.text = String.localizedStringWithFormat(lastLoginFormatString, daysAgo, time) } else { lastLoginLabel.text = "" } } // once we're loaded (outlets set, etc.), update the UI override func viewDidLoad() { super.viewDidLoad() updateUI() } private struct AlertStrings { struct LoginError { static let Title = NSLocalizedString("Login Error", comment: "Title of alert when user types in an incorrect user name or password") static let Message = NSLocalizedString("Invalid user name or password", comment: "Message in an alert when the user types in an incorrect user name or password") static let DismissButton = NSLocalizedString("Try Again", comment: "The only button available in an alert presented when the user types incorrect user name or password") } } // log in (set our Model) @IBAction private func login() { loggedInUser = User.login(loginField.text ?? "", password: passwordField.text ?? "") if loggedInUser == nil { let alert = UIAlertController(title: AlertStrings.LoginError.Title, message: AlertStrings.LoginError.Message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: AlertStrings.LoginError.DismissButton, style: UIAlertActionStyle.Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } } // toggle whether passwords are secure or not @IBAction private func toggleSecurity() { secure = !secure } // a convenience property // so that we can easily intervene // when an image is set in our imageView // whenever the image is set in our imageView // we add a constraint that the imageView // must maintain the aspect ratio of its image private var image: UIImage? { get { return imageView?.image } set { imageView?.image = newValue if let constrainedView = imageView { if let newImage = newValue { aspectRatioConstraint = NSLayoutConstraint( item: constrainedView, attribute: .Width, relatedBy: .Equal, toItem: constrainedView, attribute: .Height, multiplier: newImage.aspectRatio, constant: 0) } else { aspectRatioConstraint = nil } } } } // the imageView aspect ratio constraint // when it is set here, // we'll remove any existing aspect ratio constraint // and then add the new one to our view private var aspectRatioConstraint: NSLayoutConstraint? { willSet { if let existingConstraint = aspectRatioConstraint { view.removeConstraint(existingConstraint) } } didSet { if let newConstraint = aspectRatioConstraint { view.addConstraint(newConstraint) } } } } // User is our Model, // so it can't itself have anything UI-related // but we can add a UI-specific property // just for us to use // because we are the Controller // note this extension is private private extension User { var image: UIImage? { if let image = UIImage(named: login) { return image } else { return UIImage(named: "unknown_user") } } } // wouldn't it be convenient // to have an aspectRatio property in UIImage? // yes, it would, so let's add one! // why is this not already in UIImage? // probably because the semantic of returning zero // if the height is zero is not perfect // (nil might be better, but annoying) extension UIImage { var aspectRatio: CGFloat { return size.height != 0 ? size.width / size.height : 0 } }
apache-2.0
cfef0eb3e9ccd452338a0d46af707ca5
37.067797
167
0.629267
5.276429
false
false
false
false
iCrany/iOSExample
iOSExample/Module/LockExample/LockExampleTableViewController.swift
1
6293
// // LockExampleTableViewController.swift // iOSExample // // Created by iCrany on 2017/10/19. // Copyright © 2017 iCrany. All rights reserved. // import Foundation import UIKit class LockExampleTableViewController: UIViewController { struct Constant { static let kLockBenchMarkExample = "Lock Bench Mark"//性能测试 static let kNSLockExample = "NSLock Example" static let kSynchronizedLockExample = "Synchronized Lock Example" static let kPthreadMutexTExample = "pthread_mutex_t Lock Example" static let kSemaphoreExample = "semaphore Lock Example" static let kNSLockDeadLockExample = "NSLock dead Lock Example" static let kRecursiveLockExample = "Recursive Lock Example" static let kGCDLockExample = "GCD Lock Example" static let kPthreadMutexTDeadLockExample = "pthread_mutex_t dead Lock Example" static let kPthreadMutexTRecursiveLockExample = "pthread_mutex_t recursive Lock Example" static let kOSSpinLockExample = "OSSpinLock Lock Example" static let kNSConditionExample = "NSCondition Lock Example" static let kOSUnfairLockExample = "os_unfair_lock_t Lock Example" } private lazy var tableView: UITableView = { let tableView = UITableView.init(frame: .zero, style: .plain) tableView.tableFooterView = UIView.init() tableView.delegate = self tableView.dataSource = self return tableView }() fileprivate var dataSource: [String] = [] init() { super.init(nibName: nil, bundle: nil) self.prepareDataSource() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "Lock Example" self.setupUI() } private func setupUI() { self.view.addSubview(self.tableView) self.tableView.snp.makeConstraints { maker in maker.edges.equalTo(self.view) } self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self)) } private func prepareDataSource() { self.dataSource.append(Constant.kLockBenchMarkExample) self.dataSource.append(Constant.kNSLockExample) self.dataSource.append(Constant.kSynchronizedLockExample) self.dataSource.append(Constant.kPthreadMutexTExample) self.dataSource.append(Constant.kSemaphoreExample) self.dataSource.append(Constant.kNSLockDeadLockExample) self.dataSource.append(Constant.kRecursiveLockExample) self.dataSource.append(Constant.kGCDLockExample) self.dataSource.append(Constant.kPthreadMutexTDeadLockExample) self.dataSource.append(Constant.kPthreadMutexTRecursiveLockExample) self.dataSource.append(Constant.kOSSpinLockExample) self.dataSource.append(Constant.kNSConditionExample) self.dataSource.append(Constant.kOSUnfairLockExample) } fileprivate func getLockTypeFromDataSourceStr(str: String) -> LockExampleConstant.LockType { switch str { case Constant.kNSLockExample: return LockExampleConstant.LockType.nsLock case Constant.kSynchronizedLockExample: return LockExampleConstant.LockType.synchronized case Constant.kPthreadMutexTExample: return LockExampleConstant.LockType.pthreadMutexT case Constant.kSemaphoreExample: return LockExampleConstant.LockType.semaphore case Constant.kNSLockDeadLockExample: return LockExampleConstant.LockType.nsLockDeadLock case Constant.kRecursiveLockExample: return LockExampleConstant.LockType.nsRecursiveLock case Constant.kGCDLockExample: return LockExampleConstant.LockType.gcdLock case Constant.kPthreadMutexTDeadLockExample: return LockExampleConstant.LockType.pthreadMutexTDeadLock case Constant.kPthreadMutexTRecursiveLockExample: return LockExampleConstant.LockType.pthreadMutexTRecursiveLock case Constant.kOSSpinLockExample: return LockExampleConstant.LockType.osspinLock case Constant.kNSConditionExample: return LockExampleConstant.LockType.nscondition case Constant.kOSUnfairLockExample: return LockExampleConstant.LockType.os_unfair_lock default: return LockExampleConstant.LockType.undefined } } } extension LockExampleTableViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedDataSourceStr = self.dataSource[indexPath.row] switch selectedDataSourceStr { case Constant.kLockBenchMarkExample: let vc: LockBenchMarkViewController = LockBenchMarkViewController.init(nibName: nil, bundle: nil) self.navigationController?.pushViewController(vc, animated: true) default: let lockType: LockExampleConstant.LockType = self.getLockTypeFromDataSourceStr(str: selectedDataSourceStr) let vc: LockExampleViewController = LockExampleViewController.init(lockType: lockType) self.navigationController?.pushViewController(vc, animated: true) } } } extension LockExampleTableViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let dataSourceStr: String = self.dataSource[indexPath.row] let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self)) if let cell = tableViewCell { cell.textLabel?.text = dataSourceStr cell.textLabel?.textColor = UIColor.black return cell } else { return UITableViewCell.init(style: .default, reuseIdentifier: "error") } } }
mit
f548435eca653d9df130f782780c8620
36.855422
132
0.711489
4.88647
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift
25
2265
// // SerialDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 3/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. public final class SerialDisposable : DisposeBase, Cancelable { private var _lock = SpinLock() // state private var _current = nil as Disposable? private var _isDisposed = false /// - returns: Was resource disposed. public var isDisposed: Bool { return self._isDisposed } /// Initializes a new instance of the `SerialDisposable`. override public init() { super.init() } /** Gets or sets the underlying disposable. Assigning this property disposes the previous disposable object. If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. */ public var disposable: Disposable { get { return self._lock.calculateLocked { return self._current ?? Disposables.create() } } set (newDisposable) { let disposable: Disposable? = self._lock.calculateLocked { if self._isDisposed { return newDisposable } else { let toDispose = self._current self._current = newDisposable return toDispose } } if let disposable = disposable { disposable.dispose() } } } /// Disposes the underlying disposable as well as all future replacements. public func dispose() { self._dispose()?.dispose() } private func _dispose() -> Disposable? { self._lock.lock(); defer { self._lock.unlock() } if self._isDisposed { return nil } else { self._isDisposed = true let current = self._current self._current = nil return current } } }
mit
b907a436d66c229b4c0240a646927edb
29.186667
196
0.574205
5.535452
false
false
false
false
TotalDigital/People-iOS
People at Total/profileViewController.swift
1
154927
// // profileViewController.swift // People at Total // // Created by Florian Letellier on 01/02/2017. // Copyright © 2017 Florian Letellier. All rights reserved. // import UIKit import SwiftyJSON import SafariServices import MessageUI import AddressBook import Contacts import ContactsUI import SVProgressHUD extension UIImageView { func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) { contentMode = mode print("call downloaded image") URLSession.shared.dataTask(with: url) { (data, response, error) in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let image = UIImage(data: data) else { print("error downloaded image") return } DispatchQueue.main.async() { () -> Void in self.image = image.circleMasked print("done downloaded image") } }.resume() } func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) { print("call downloaded image") if link.contains("placeholdit.imgix.net") { return } guard let url = URL(string: link) else { return } downloadedFrom(url: url, contentMode: mode) } } extension CALayer { func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) { let border = CALayer() switch edge { case UIRectEdge.top: border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: thickness) break case UIRectEdge.bottom: border.frame = CGRect(x: 0, y: self.frame.height - thickness, width: self.frame.width, height: thickness) break case UIRectEdge.left: border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.frame.height) break case UIRectEdge.right: border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: self.frame.height) break default: break } border.backgroundColor = color.cgColor; self.addSublayer(border) } } class jobTableViewCell: UITableViewCell { @IBOutlet weak var jobTitle: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var location: UILabel! // @IBOutlet weak var descJob: UILabel! } class jobExpandTableViewCell: UITableViewCell { @IBOutlet weak var jobTitle: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var location: UILabel! @IBOutlet weak var descLabel: UILabel! } class EducationTableViewCell: UITableViewCell { @IBOutlet weak var jobTitle: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var location: UILabel! } class projectTableViewCell: UITableViewCell { @IBOutlet weak var projectTitle: UILabel! @IBOutlet weak var projectDate: UILabel! @IBOutlet weak var projectLocation: UILabel! @IBOutlet weak var detailProject: UILabel! } class projectExpandTableViewCell: UITableViewCell { @IBOutlet weak var projectTitle: UILabel! @IBOutlet weak var projectLocation: UILabel! @IBOutlet weak var projectDate: UILabel! @IBOutlet weak var detailProject: UILabel! @IBOutlet weak var bottomSpaceLocationConstraint: NSLayoutConstraint! @IBOutlet weak var projectMembersLabel: UILabel! } class memberTableViewCell: UITableViewCell { @IBOutlet weak var memberName: UILabel! @IBOutlet weak var pictureMember: UIImageView! @IBOutlet weak var jobTitleLabel: UILabel! } protocol relationsMemberTableViewCellDelegate{ func closeFriendsTapped(at index:IndexPath, sender: AnyObject, user_id : Int) } class relationsMemberTableViewCell: UITableViewCell { @IBOutlet weak var relationMemberName: UILabel! @IBOutlet weak var relationMemberPicture: UIImageView! @IBOutlet weak var relationMemberJob: UILabel! var delegate:relationsMemberTableViewCellDelegate! @IBOutlet weak var closeFriendsBtn: UIButton! var indexPath:IndexPath! var user_id:Int = 0 @IBAction func closeFriendsAction(_ sender: Any) { self.delegate?.closeFriendsTapped(at: indexPath, sender: sender as AnyObject, user_id : user_id) } } class relationTableViewCell: UITableViewCell { @IBOutlet weak var relationType: UILabel! } class skillTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var sizingCell: CustomCollectionCell? @IBOutlet var flowLayout: UICollectionViewFlowLayout! @IBOutlet var infoLabel: UILabel! @IBOutlet var collectionView: UICollectionView! var gameNames:[String] = [] override func awakeFromNib() { super.awakeFromNib() // Initialization code let cellNib = UINib(nibName: "CollectionCell", bundle: nil) self.collectionView.register(cellNib, forCellWithReuseIdentifier: "CollectionCell") self.collectionView.backgroundColor = UIColor.clear self.sizingCell = (cellNib.instantiate(withOwner: nil, options: nil) as NSArray).firstObject as! CustomCollectionCell? // self.flowLayout.sectionInset = UIEdgeInsetsMake(8, 8, 8, 8) collectionView.delegate = self collectionView.dataSource = self } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { self.configureCell(self.sizingCell!, forIndexPath: indexPath) return self.sizingCell!.systemLayoutSizeFitting(UILayoutFittingCompressedSize) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameNames.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CustomCollectionCell self.configureCell(cell, forIndexPath: indexPath) return cell } func configureCell(_ cell: CustomCollectionCell, forIndexPath indexPath: IndexPath) { let tag = gameNames[indexPath.row] cell.tagName.text = tag cell.crossButton.isHidden = true // cell.trailingLabelConstraint.constant = 6 } } class CustomCollectionCell: UICollectionViewCell { @IBOutlet weak var tagName: UILabel! // @IBOutlet weak var maxWidthConstraint: NSLayoutConstraint! @IBOutlet weak var crossButton: UIButton! // @IBOutlet weak var trailingLabelConstraint: NSLayoutConstraint! override func awakeFromNib() { //self.backgroundColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1) //self.tagName.textColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1) self.layer.cornerRadius = 4 // self.maxWidthConstraint.constant = UIScreen.main.bounds.width - 8 * 2 - 8 * 2 } } class languageTableViewCell: UITableViewCell { } class profileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,UISearchBarDelegate, UISearchDisplayDelegate, relationsMemberTableViewCellDelegate, UIGestureRecognizerDelegate, MFMailComposeViewControllerDelegate, CNContactViewControllerDelegate, OptionButtonsDelegate { internal func closeFriendsTapped(at index: IndexPath, sender: AnyObject) { if(searchActive){ if filtered.count>0 { let row = index.row self.toConnect(profile: self.filtered[row],sender: sender,index: index) } } } internal func closeFriendsTapped(at index: IndexPath, sender: AnyObject, user_id : Int) { getUserFromIDForRelationship(user_id: user_id,sender:sender) } @IBOutlet weak var imageProfile: UIImageView! @IBOutlet weak var nameProfile: UILabel! @IBOutlet weak var jobLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var entitiesLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableViewMember: UITableView! @IBOutlet var tableViewManager: UITableView! @IBOutlet var tableViewColleague: UITableView! @IBOutlet var tableViewRelationMember: UITableView! @IBOutlet var tableViewTeam: UITableView! @IBOutlet var tableViewAssitant: UITableView! @IBOutlet weak var contentView: UIView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var contentInformationView: UIView! @IBOutlet weak var connectButton: UIButton! @IBOutlet weak var addToContactButton: UIButton! @IBOutlet weak var lblEmail: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var lblPhonenumber: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var imgLinkedin: UIImageView! @IBOutlet weak var lblLinkedin: UILabel! @IBOutlet weak var stackLinkedin: UIView! @IBOutlet weak var imgTwitter: UIImageView! @IBOutlet weak var lblTwitter: UILabel! @IBOutlet weak var stackTwitter: UIView! @IBOutlet weak var stackTwitterLeading: NSLayoutConstraint! @IBOutlet weak var viewProfileInformation: UIView! @IBOutlet weak var contactInformationHeight: NSLayoutConstraint! @IBOutlet weak var otherServicesHeight: NSLayoutConstraint! @IBOutlet weak var viewContactInformation: UIView! @IBOutlet weak var viewOtherServices: UIView! @IBOutlet weak var stackEmail: UIView! @IBOutlet weak var stackPhoneNumber: UIView! @IBOutlet weak var stackPhoneNumberTop: NSLayoutConstraint! @IBOutlet weak var stackEmailHeight: NSLayoutConstraint! @IBOutlet weak var stackPhoneNumberHeight: NSLayoutConstraint! @IBOutlet var is_external: UILabel! var isExpand: Bool = false var profile: Profile = Profile() var callbackLatestProfile : ((Profile) -> Void)? var searchBar: UISearchBar = UISearchBar() var relations: [String: [Profile]] = [:] var selectedCellIndexPath: IndexPath? var currentRelation: String = "" var rowSection2: CGFloat = 0.0 var access_token: String = "" var profile_id: Int = 0 var isFromNavigationNotAvailable: Bool = false @IBOutlet weak var tblSearch: UITableView! var searchActive : Bool = false var filtered:[Profile] = [] var usersSearchPageNo: Int = 0 var collectionViewHeightSkill: CGFloat = 0.0 var collectionViewHeightLangue: CGFloat = 0.0 let pagingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) @IBAction func toConnect(_ sender: Any) { if(profile.relations.isRelationAvailable) { let actionSheetController: UIAlertController = UIAlertController(title: "Confirm", message: "Do you want to remove your relationship?", preferredStyle: .alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in //Just dismiss the action sheet } let removeAction: UIAlertAction = UIAlertAction(title: "Remove", style: .destructive) { action -> Void in //Just dismiss the action sheet self.removeRelationShipWithID(relationship_id: self.profile.relations.relationshipID) } actionSheetController.addAction(cancelAction) actionSheetController.addAction(removeAction) self.present(actionSheetController, animated: true, completion: nil) } else { let myActionSheet = UIAlertController(title: "Confirm new relationship", message: "Add", preferredStyle: UIAlertControllerStyle.actionSheet) // blue action button let blueAction = UIAlertAction(title: "as colleague", style: UIAlertActionStyle.default) { (action) in print("As colleague") self.addRelationShip(kind: "is_colleague_of") } // red action button let redAction = UIAlertAction(title: "as manager", style: UIAlertActionStyle.default) { (action) in print("as Manager") self.addRelationShip(kind: "is_managed_by") } // yellow action button let yellowAction = UIAlertAction(title: "as team member", style: UIAlertActionStyle.default) { (action) in print("as Team member") self.addRelationShip(kind: "is_manager_of") } let purpleAction = UIAlertAction(title: "as assistant", style: UIAlertActionStyle.default) { (action) in print("as assistant") self.addRelationShip(kind: "is_assisted_by") } // cancel action button let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (action) in print("Cancel action button tapped") } // add action buttons to action sheet myActionSheet.addAction(blueAction) myActionSheet.addAction(redAction) myActionSheet.addAction(yellowAction) myActionSheet.addAction(purpleAction) myActionSheet.addAction(cancelAction) // support iPads (popover view) myActionSheet.popoverPresentationController?.sourceView = self.connectButton myActionSheet.popoverPresentationController?.sourceRect = self.connectButton.bounds // present the action sheet self.present(myActionSheet, animated: true, completion: nil) } } @IBAction func btn_clkAddToContacts(_ sender: Any) { if URL(string: (profile.user?.image!)!) != nil { self.downloadedFrom(link: (profile.user?.image!)!) } else { if #available(iOS 9.0, *) { let store = CNContactStore() let contact = CNMutableContact() let homePhone = CNLabeledValue(label: CNLabelHome, value: CNPhoneNumber(stringValue :profile.contact.phone_number!)) contact.givenName = (profile.user?.first_name)! contact.familyName = (profile.user?.last_name)! if (profile.contact.email!.contains("total.com")) { contact.organizationName = "Total" } contact.phoneNumbers = [homePhone] let workEmail = CNLabeledValue(label:CNLabelWork, value:profile.contact.email! as NSString) contact.emailAddresses = [workEmail] let controller = CNContactViewController(forNewContact : contact)// .viewControllerForUnknownContact(contact) controller.contactStore = store controller.delegate = self self.navigationController?.setNavigationBarHidden(false, animated: true) let navController = UINavigationController(rootViewController: controller) // Creating a navigation controller with VC1 at the root of the navigation stack. self.present(navController, animated:true, completion: nil) } } } func contactViewController(_ vc: CNContactViewController, didCompleteWith con: CNContact?) { self.dismiss(animated: true, completion: nil) } func contactViewController(_ vc: CNContactViewController, shouldPerformDefaultActionFor prop: CNContactProperty) -> Bool { return false } override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tblSearch.delegate = self tblSearch.dataSource = self tblSearch.reloadData() tableViewManager.separatorStyle = .none tableViewColleague.separatorStyle = .none tableViewAssitant.separatorStyle = .none tableViewTeam.separatorStyle = .none tableViewMember.separatorStyle = .none searchBar.delegate = self searchBar.placeholder = "Search on people..." tableView.estimatedRowHeight = 116.0 pagingSpinner.color = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0) pagingSpinner.hidesWhenStopped = true tblSearch.tableFooterView = pagingSpinner let tapKeyboard: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) //Uncomment the line below if you want the tap not not interfere and cancel other interactions. tapKeyboard.cancelsTouchesInView = false view.addGestureRecognizer(tapKeyboard) let screenSize: CGRect = UIScreen.main.bounds if profile.id != 0 { if (self.profile.user.is_external == true) { self.is_external.isHidden = false } if (profile.contact.linkedin_profile?.characters.count)! > 0 { stackLinkedin.isHidden = false } else { stackLinkedin.isHidden = true } if (profile.contact.twitter_profile?.characters.count)! > 0 { stackTwitter.isHidden = false } else { stackTwitter.isHidden = true } if (profile.contact.linkedin_profile?.characters.count)! <= 0 && (profile.contact.twitter_profile?.characters.count)! > 0 { stackTwitterLeading.constant = 0 self.contentView.layoutIfNeeded() } if (profile.contact.linkedin_profile?.characters.count)! <= 0 && (profile.contact.twitter_profile?.characters.count)! <= 0 { // contentView.frame = CGRect(x:0,y: 0,width: screenSize.width,height: contentView.frame.size.height - otherServicesHeight.constant) otherServicesHeight.constant = 0 self.contentView.layoutIfNeeded() } if (profile.contact.email?.characters.count)! <= 0 || (profile.contact.phone_number?.characters.count)! <= 0 { contactInformationHeight.constant = stackEmailHeight.constant + 40 self.contentView.layoutIfNeeded() } if (profile.contact.email?.characters.count)! <= 0 && (profile.contact.phone_number?.characters.count)! <= 0 { contactInformationHeight.constant = 0 self.contentView.layoutIfNeeded() } if (profile.contact.email?.characters.count)! <= 0 { stackEmailHeight.constant = 0 stackPhoneNumberTop.constant = 0 self.contentView.layoutIfNeeded() } if (profile.contact.phone_number?.characters.count)! <= 0 { stackPhoneNumberHeight.constant = 0 self.contentView.layoutIfNeeded() } contentInformationView.frame = CGRect(x:0,y: viewProfileInformation.frame.origin.y + viewProfileInformation.frame.size.height ,width: screenSize.width,height: viewOtherServices.frame.size.height + contactInformationHeight.constant + viewContactInformation.frame.origin.y) contentView.frame = CGRect(x:0,y: 0,width: screenSize.width,height: contentInformationView.frame.size.height + contentInformationView.frame.origin.y + 10) if ((profile.user?.image!) != nil) { imageProfile.downloadedFrom(link: (profile.user?.image!)!) } imageProfile.setImageForName(string: "\((profile.user?.first_name)!) \((profile.user?.last_name)!)", backgroundColor: nil, circular: true, textAttributes: nil) //imageProfile.image?.circleMasked //UIImage(named: (profile.user?.image)!)?.circleMasked nameProfile.text = "\((profile.user?.first_name)!) \((profile.user?.last_name)!)" jobLabel.text = profile.user?.job locationLabel.text = profile.user?.location entitiesLabel.text = profile.user?.entities } else { profile.id = self.profile_id self.getCurrentUpdatedUser() } contentInformationView.layer.addBorder(edge: UIRectEdge.top, color: UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 1.0), thickness: 1.0) connectButton.layer.cornerRadius = 2 addToContactButton.layer.cornerRadius = 2 let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField textFieldInsideSearchBar?.textColor = UIColor.white textFieldInsideSearchBar?.backgroundColor = UIColor(red: 58/255 ,green: 131/255, blue: 202/255, alpha:1.0) if (textFieldInsideSearchBar!.value(forKey:"attributedPlaceholder") != nil) { let attributeDict = [NSForegroundColorAttributeName: UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.75)] textFieldInsideSearchBar!.attributedPlaceholder = NSAttributedString(string: "Search on People...", attributes: attributeDict) if let imageView = textFieldInsideSearchBar?.leftView as? UIImageView { imageView.image = imageView.image?.transform(withNewColor: UIColor(red: 255/255, green: 255/255, blue: 255, alpha: 0.75)) } } navigationItem.titleView = searchBar self.navigationController?.navigationBar.tintColor = UIColor.white self.navigationController?.navigationBar.barTintColor = UIColor(red: 22/255, green: 108/255, blue: 193/255, alpha: 1.0) self.navigationController?.navigationBar.isTranslucent = false let contentSize = screenSize.height - UIApplication.shared.statusBarFrame.height - (self.navigationController?.navigationBar.frame.size.height)! - (self.tabBarController?.tabBar.frame.height)! // contentView.frame = CGRect(x:0,y: 0,width: screenSize.width,height: contentSize * 0.95) tableView.frame = CGRect(x:0, y: contentView.frame.size.height, width: screenSize.width, height: contentSize * 5.0) //self.tableView.addSubview(tableViewMember) self.scrollView.addSubview(contentView) self.scrollView.addSubview(tableView) view.addSubview(scrollView) //Contact emailLabel.text = profile.contact.email phoneLabel.text = profile.contact.phone_number if(profile.relations.isRelationAvailable) { connectButton.setTitle("Remove",for: .normal) } let tap = UITapGestureRecognizer(target: self, action: #selector(myProfileViewController.handleLinkedinImage(sender:))) tap.delegate = myProfileViewController() as UIGestureRecognizerDelegate self.imgLinkedin.addGestureRecognizer(tap) self.imgLinkedin.isUserInteractionEnabled = true let tap2 = UITapGestureRecognizer(target: self, action: #selector(myProfileViewController.handleTwitterImage(sender:))) tap2.delegate = myProfileViewController() as UIGestureRecognizerDelegate self.imgTwitter.addGestureRecognizer(tap2) self.imgTwitter.isUserInteractionEnabled = true let tap3 = UITapGestureRecognizer(target: self, action: #selector(myProfileViewController.handleEmailID(sender:))) tap3.delegate = myProfileViewController() as UIGestureRecognizerDelegate self.emailLabel.addGestureRecognizer(tap3) self.emailLabel.isUserInteractionEnabled = true let tap4 = UITapGestureRecognizer(target: self, action: #selector(myProfileViewController.handlePhoneNumber(sender:))) tap4.delegate = myProfileViewController() as UIGestureRecognizerDelegate self.phoneLabel.addGestureRecognizer(tap4) self.phoneLabel.isUserInteractionEnabled = true let tap5 = UITapGestureRecognizer(target: self, action: #selector(myProfileViewController.handleEmailID(sender:))) tap5.delegate = myProfileViewController() as UIGestureRecognizerDelegate self.lblEmail.addGestureRecognizer(tap5) self.lblEmail.isUserInteractionEnabled = true let tap6 = UITapGestureRecognizer(target: self, action: #selector(myProfileViewController.handlePhoneNumber(sender:))) tap6.delegate = myProfileViewController() as UIGestureRecognizerDelegate self.lblPhonenumber.addGestureRecognizer(tap6) self.lblPhonenumber.isUserInteractionEnabled = true self.view.bringSubview(toFront: tblSearch) tblSearch.isHidden = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("viewWillAppear") if isFromNavigationNotAvailable { navigationController?.setNavigationBarHidden(false, animated: true) } } override func viewWillDisappear(_ animated: Bool) { if isFromNavigationNotAvailable { navigationController?.setNavigationBarHidden(true, animated: true) } } override func viewDidAppear(_ animated: Bool) { self.scrollView.contentSize = CGSize(width: self.tableViewContentSize().width, height: self.tableViewContentSize().height + contentView.frame.size.height) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // let screenSize: CGRect = UIScreen.main.bounds // scrollView.contentSize = CGSize(width: screenSize.width, height: (screenSize.height - UIApplication.shared.statusBarFrame.height - (self.navigationController?.navigationBar.frame.size.height)! - (self.tabBarController?.tabBar.frame.height)!) * 5.0) self.scrollView.contentSize = CGSize(width: self.tableViewContentSize().width, height: self.tableViewContentSize().height + contentView.frame.size.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections if tableView == tableViewMember { return 1 } else if tableView == self.tableView{ return 6 } else { return 1 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == self.tblSearch { if(searchActive) { return filtered.count } return 0 } // #warning Incomplete implementation, return the number of rows if tableView == tableViewMember { print("row : \(selectedCellIndexPath?.row)") //print("profile count : \(profile.projects[(selectedCellIndexPath?.row)!].members_profile.count)") if selectedCellIndexPath?.row == -1 { return 0 } else { return profile.projects[(selectedCellIndexPath?.row)!].members_profile.count } } else if tableView == self.tableView { if section == 0 { return profile.jobs.count } else if section == 1 { return profile.projects.count } else if section == 2 { return profile.degree.count } else if section == 3 { // return self.relations.count if relations.count > 0 { return 4 } return 0 } else if section == 4 { return 2 } } else if tableView == tableViewManager { return (relations["Managers"]?.count)! } else if tableView == tableViewAssitant { return (relations["Assistant"]?.count)! } else if tableView == tableViewTeam { return (relations["Team Members"]?.count)! } else if tableView == tableViewColleague { return (relations["Colleagues"]?.count)! } return 0 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if tableView == self.tblSearch { return 57.0 } if tableView == self.tableView { return 55.0 } else if tableView == self.tableViewMember { return 0 } return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, viewForHeaderInSection section:Int) -> UIView? { if tableView == self.tblSearch { let headerView = UILabel(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: self.view.frame.width, height: 57))) let label = NewLabel(frame: CGRect(x: 0, y: 0, width: headerView.frame.width, height: headerView.frame.height)) label.font = UIFont(name: "HelveticaNeue-bold", size: 14)! label.textColor = UIColor(red: 112/255, green: 113/255, blue: 115/255, alpha: 1.0) label.text = "SEARCH RESULT" label.backgroundColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1.0) headerView.addSubview(label) //headerView.bringSubview(toFront: label) // headerView.backgroundColor = UIColor.red/*(red: 250/255, green: 250/255, blue: 250/255, alpha: 1.0)*/ print("label.text :") print(label.frame) return headerView } let headerView = UILabel(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: self.view.frame.width, height: 55))) if tableView == self.tableView { let label = NewLabel2(frame: CGRect(x: 0, y: 0, width: headerView.frame.width, height: headerView.frame.height)) label.font = UIFont(name: "HelveticaNeue-bold", size: 14)! label.textColor = UIColor(red: 112/255, green: 113/255, blue: 115/255, alpha: 1.0) label.backgroundColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1.0) label.layer.addBorder(edge: UIRectEdge.top, color: UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 1.0), thickness: 1.0) label.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 1.0), thickness: 1.0) //headerView.bringSubview(toFront: label) // headerView.backgroundColor = UIColor.red/*(red: 250/255, green: 250/255, blue: 250/255, alpha: 1.0)*/ switch (section) { case 0: label.text = "JOBS" case 1: label.text = "PROJECTS" case 2: label.text = "EDUCATION" case 3: label.text = "RELATIONS" case 4: label.text = "MORE INFOS" default: break } headerView.addSubview(label) headerView.layoutIfNeeded() } return headerView } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if tableView == tableViewMember && profile.projects[(selectedCellIndexPath?.row)!].members_profile.count > 0{ return "Project members" } else if tableView == self.tableView { if section == 0 { return "JOBS" } else if section == 1 { return "PROJECTS" } else if section == 2 { return "EDUCATION" } else if section == 3 { return "RELATIONS" } else if section == 4 { return "MORE INFOS" } return "" } else { return "" } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didSelectRowAtIndexPath 222") if tableView == self.tblSearch { if let profileVC = UIStoryboard(name: "Storyboard", bundle: nil).instantiateViewController(withIdentifier: "profileViewController") as? profileViewController { if self.searchBar.isFirstResponder == true { self.searchBar.resignFirstResponder() } profileVC.profile = filtered[indexPath.row] print("relationsArray : ") dump(relationsArray(relations: filtered[indexPath.row].relations)) let profile = filtered[indexPath.row] profileVC.access_token = self.access_token profileVC.relations = relationsArray(relations: profile.relations) profileVC.callbackLatestProfile = {(newProfile:Profile) in self.filtered[indexPath.row] = newProfile self.tableView.reloadData() } if let navigator = self.navigationController { navigator.pushViewController(profileVC, animated: true) } } } if tableView == tableViewMember && profile.projects[(selectedCellIndexPath?.row)!].members_profile.count > 0{ pushUserFromID(user_id: profile.projects[(selectedCellIndexPath?.row)!].members_profile[indexPath.row].user.user_id) } if tableView == self.tableView && (indexPath.section == 0 || indexPath.section == 1) { if (self.isExpand) { self.isExpand = false } if (indexPath==self.selectedCellIndexPath) { self.isExpand = false self.selectedCellIndexPath = IndexPath(row: -1, section: indexPath.section) }else{ self.isExpand = true self.selectedCellIndexPath = indexPath } // self.selectedCellIndexPath = indexPath // self.isExpand = !self.isExpand tableView.reloadData() if indexPath.section == 1{ tableViewMember.reloadData() } print("data reloaded : \(self.selectedCellIndexPath)") self.scrollView.contentSize = CGSize(width: self.tableViewContentSize().width, height: self.tableViewContentSize().height + contentView.frame.size.height) } else if tableView == tableViewManager { if let user_id = relations["Managers"]?[indexPath.row].user?.user_id { //in value you will get non optional value pushUserFromID(user_id: user_id) } } else if tableView == tableViewAssitant { if let user_id = relations["Assistant"]?[indexPath.row].user?.user_id { //in value you will get non optional value pushUserFromID(user_id: user_id) } } else if tableView == tableViewTeam { if let user_id = relations["Team Members"]?[indexPath.row].user?.user_id { //in value you will get non optional value pushUserFromID(user_id: user_id) } } else if tableView == tableViewColleague { if let user_id = relations["Colleagues"]?[indexPath.row].user?.user_id { //in value you will get non optional value pushUserFromID(user_id: user_id) } // return (relations["Colleagues"]?.count)! } tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if tableView == self.tblSearch { return 80 } if tableView == self.tableView && indexPath.section == 4 { // return 140 if indexPath.row == 0 { let cell: skillTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "skillCell") as? skillTableViewCell let skill = profile.skills.skills cell.infoLabel.text = "Skills" cell.gameNames = skill cell.collectionView.reloadData() return 50 + cell.collectionView.collectionViewLayout.collectionViewContentSize.height } else { let cell: skillTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "skillCell") as? skillTableViewCell let language = profile.langues.langues cell.infoLabel.text = "Language" cell.gameNames = language cell.collectionView.reloadData() return 140 + cell.collectionView.collectionViewLayout.collectionViewContentSize.height } // if indexPath.row == 0 { // return 50 + collectionViewHeightSkill // } // else { // return 50 + collectionViewHeightLangue // } } if isExpand == true && indexPath.section == 1 && indexPath == selectedCellIndexPath { let row = (selectedCellIndexPath?.row)! let memberCount = profile.projects[(selectedCellIndexPath?.row)!].members_profile.count return 170.0 + calculateHeight(inString: profile.projects[(selectedCellIndexPath?.row)!].objDescription!) + 40.0 * CGFloat(memberCount) } if tableView == self.tableView && indexPath.section == 1 { return 140.0 } rowSection2 = 0 if tableView == self.tableViewColleague { return 50 /*+ 20.0 * CGFloat(relations["Colleagues"]!.count)*/ } if tableView == self.tableViewManager { return 50 /*+ 20.0 * CGFloat(relations["Managers"]!.count)*/ } if tableView == self.tableViewTeam { return 50 /*+ 20.0 * CGFloat(relations["Team Members"]!.count)*/ } if tableView == self.tableViewAssitant { return 50 /*+ 20.0 * CGFloat(relations["Assistant"]!.count)*/ } if tableView == self.tableView && indexPath.section == 3 { // switch Array(relations.keys)[indexPath.row] { // case "Managers": // return 40 + CGFloat(relations["Managers"]!.count) * 50.0 // case "Assistant": // return 40 + CGFloat(relations["Assistant"]!.count) * 50.0 // case "Colleagues": // return 40 + CGFloat(relations["Colleagues"]!.count) * 50.0 // case "Team Members": // return 40 + CGFloat(relations["Team Members"]!.count) * 50.0 // default: break // } if relations.count > 0 { if indexPath.row == 0 { if (relations["Managers"] != nil) { return 40 + CGFloat(relations["Managers"]!.count) * 50.0 } } else if indexPath.row == 1 { if (relations["Assistant"] != nil) { return 40 + CGFloat(relations["Assistant"]!.count) * 50.0 } } else if indexPath.row == 2 { if (relations["Team Members"] != nil) { return 40 + CGFloat(relations["Team Members"]!.count) * 50.0 } } else if indexPath.row == 3 { if (relations["Colleagues"] != nil) { return 40 + CGFloat(relations["Colleagues"]!.count) * 50.0 } } } return 0 } if tableView == self.tableView && indexPath.section == 2 { return 127.0 } if isExpand == true && indexPath.section == 0 && indexPath == selectedCellIndexPath { print("calculateHeight : \(calculateHeight(inString: profile.jobs[(selectedCellIndexPath?.row)!].objDescription!))") return 135 + calculateHeight(inString: profile.jobs[(selectedCellIndexPath?.row)!].objDescription!) } if tableView == self.tableView && indexPath.section == 0 { return 140.0 } return UITableViewAutomaticDimension } func calculateHeight(inString:String) -> CGFloat { let messageString = inString let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 14.0)] let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes) let screenSize: CGRect = UIScreen.main.bounds let rect : CGRect = attributedString.boundingRect(with: CGSize(width: screenSize.width - 32, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil) let requredSize:CGRect = rect return requredSize.height } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //var cell = UITableViewCell() if tableView == self.tblSearch { let cell = tableView.dequeueReusableCell(withIdentifier: "profileCell")! as! profileTableViewCell; if indexPath.row == 0 { cell.addTopSeparator(tableView: tableView) } cell.indexPath = indexPath cell.delegate = self if(searchActive){ if filtered.count>0 { let row = indexPath.row print("row : \(row)") let name:String! = "\((self.filtered[row].user?.first_name)!) \((self.filtered[row].user?.last_name)!)" cell.nameLabel?.text = name if ((filtered[row].user?.image) != nil) { cell.avatarImageView.downloadedFrom(link: (filtered[row].user?.image)!) } cell.avatarImageView.setImageForName(string: name, backgroundColor: nil, circular: true, textAttributes: nil) cell.jobTitleLabel?.text = filtered[row].user?.job! cell.entitiesLabel?.text = filtered[row].user?.entities! if self.filtered[row].relations.isRelationAvailable == true { print("name : \(name) true") cell.closeFriendsBtn?.isHidden = true } else { cell.closeFriendsBtn?.isHidden = false print("false") } } } return cell; } else if tableView == self.tableView { switch indexPath.section { case 0: if isExpand == false || selectedCellIndexPath != indexPath{ let cell = tableView.dequeueReusableCell(withIdentifier: "jobCell", for: indexPath as IndexPath) as! jobTableViewCell cell.jobTitle.text = profile.jobs[indexPath.row].title if let start_date = profile.jobs[indexPath.row].start_date { if let end_date = profile.jobs[indexPath.row].end_date { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date: Date? = dateFormatterGet.date(from: start_date) let date1: Date? = dateFormatterGet.date(from: end_date) cell.date.text = "\(dateFormatter.string(from: date!)) - \(dateFormatter.string(from: date1!))" } else { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date: Date? = dateFormatterGet.date(from: start_date) cell.date.text = "\(dateFormatter.string(from: date!))" } } else { if let end_date = profile.jobs[indexPath.row].end_date { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date1: Date? = dateFormatterGet.date(from: end_date) cell.date.text = "\(dateFormatter.string(from: date1!))" } } cell.location.text = profile.jobs[indexPath.row].location return cell } else{ let cell = tableView.dequeueReusableCell(withIdentifier: "jobCellExpand", for: indexPath as IndexPath) as! jobExpandTableViewCell cell.jobTitle.text = profile.jobs[indexPath.row].title if let start_date = profile.jobs[indexPath.row].start_date { if let end_date = profile.jobs[indexPath.row].end_date { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date: Date? = dateFormatterGet.date(from: start_date) let date1: Date? = dateFormatterGet.date(from: end_date) cell.date.text = "\(dateFormatter.string(from: date!)) - \(dateFormatter.string(from: date1!))" } else { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date: Date? = dateFormatterGet.date(from: start_date) cell.date.text = "\(dateFormatter.string(from: date!))" } } else { if let end_date = profile.jobs[indexPath.row].end_date { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date1: Date? = dateFormatterGet.date(from: end_date) cell.date.text = "\(dateFormatter.string(from: date1!))" } } cell.location.text = profile.jobs[indexPath.row].location cell.descLabel.text = profile.jobs[indexPath.row].objDescription return cell } case 1: if isExpand == false || selectedCellIndexPath != indexPath{ let cell = tableView.dequeueReusableCell(withIdentifier: "projectCell", for: indexPath as IndexPath) as! projectTableViewCell cell.projectTitle.text = profile.projects[indexPath.row].title let project = profile.projects[indexPath.row] if project.end_date == "" { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date: Date? = dateFormatterGet.date(from: profile.projects[indexPath.row].start_date!) cell.projectDate.text = "From \(dateFormatter.string(from: date!))" } else { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date: Date? = dateFormatterGet.date(from: profile.projects[indexPath.row].start_date!) let date1: Date? = dateFormatterGet.date(from: profile.projects[indexPath.row].end_date!) cell.projectDate.text = "\(dateFormatter.string(from: date!)) - \(dateFormatter.string(from: date1!))" } cell.projectLocation.text = profile.projects[indexPath.row].location return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "projectExpandCell", for: indexPath as IndexPath) as! projectExpandTableViewCell cell.projectTitle.text = profile.projects[indexPath.row].title let project = profile.projects[indexPath.row] if project.end_date == "" { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date: Date? = dateFormatterGet.date(from: profile.projects[indexPath.row].start_date!) cell.projectDate.text = "From \(dateFormatter.string(from: date!))" } else { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date: Date? = dateFormatterGet.date(from: profile.projects[indexPath.row].start_date!) let date1: Date? = dateFormatterGet.date(from: profile.projects[indexPath.row].end_date!) cell.projectDate.text = "\(dateFormatter.string(from: date!)) - \(dateFormatter.string(from: date1!))" } cell.projectLocation.text = profile.projects[indexPath.row].location cell.detailProject.text = profile.projects[indexPath.row].objDescription let screenSize: CGRect = UIScreen.main.bounds let memberCount = profile.projects[(selectedCellIndexPath?.row)!].members_profile.count let description = profile.projects[(selectedCellIndexPath?.row)!].objDescription tableViewMember.removeFromSuperview() if memberCount > 0 && description != nil { cell.projectMembersLabel.text = "Project members (\(memberCount))" tableViewMember.frame = CGRect(x:0,y: Int(140 + calculateHeight(inString: description!)) ,width: Int(screenSize.width),height: 20 + 50 * profile.projects[(selectedCellIndexPath?.row)!].members_profile.count) cell.addSubview(tableViewMember) } return cell } case 2: if isExpand == false || selectedCellIndexPath != indexPath{ let cell = tableView.dequeueReusableCell(withIdentifier: "EducationTableViewCell", for: indexPath as IndexPath) as! EducationTableViewCell cell.jobTitle.text = profile.degree[indexPath.row].title if let start_date = profile.degree[indexPath.row].entry_year { if let end_date = profile.degree[indexPath.row].graduation_year { cell.date.text = "\(profile.degree[indexPath.row].entry_year!) - \(profile.degree[indexPath.row].graduation_year!)" } else { cell.date.text = "\(profile.degree[indexPath.row].entry_year!)" } } else { cell.date.text = "\(profile.degree[indexPath.row].graduation_year!)" } cell.location.text = profile.degree[indexPath.row].school return cell } else{ let cell = tableView.dequeueReusableCell(withIdentifier: "jobCellExpand", for: indexPath as IndexPath) as! jobExpandTableViewCell cell.jobTitle.text = profile.jobs[indexPath.row].title if let start_date = profile.jobs[indexPath.row].start_date { if let end_date = profile.jobs[indexPath.row].end_date { cell.date.text = "\(profile.jobs[indexPath.row].start_date!) - \(profile.jobs[indexPath.row].end_date!)" } } cell.location.text = profile.jobs[indexPath.row].location cell.descLabel.text = profile.jobs[indexPath.row].objDescription return cell } case 3: let cell = tableView.dequeueReusableCell(withIdentifier: "relationCell", for: indexPath as IndexPath) as! relationTableViewCell switch (indexPath.row) { case 0: if (relations["Managers"] != nil) { var tableViewRelation: UITableView = UITableView() var height: CGFloat = 0 // switch Array(relations.keys)[indexPath.row] { // case "Managers": tableViewRelation = tableViewManager height = CGFloat(relations["Managers"]!.count) * 50.0 // case "Assistant": // tableViewRelation = tableViewAssitant // height = CGFloat(relations["Assistant"]!.count) * 50.0 // case "Colleagues": // tableViewRelation = tableViewColleague // height = CGFloat(relations["Colleagues"]!.count) * 50.0 // case "Team Members": // tableViewRelation = tableViewTeam // height = CGFloat(relations["Team Members"]!.count) * 50.0 // default: break // } tableViewRelation.frame = CGRect(x:0,y: 40,width: Int(UIScreen.main.bounds.width),height: Int(height)) // cell.relationType.text = Array(relations.keys)[indexPath.row] // self.currentRelation = Array(relations.keys)[indexPath.row] cell.relationType.text = "Managers" self.currentRelation = "Managers" cell.removeSeparator(width: 0.0) cell.addSubview(tableViewRelation) } case 1: if (relations["Assistant"] != nil) { var tableViewRelation1: UITableView = UITableView() var height: CGFloat = 0.0 // switch Array(relations.keys)[indexPath.row] { // case "Managers": // tableViewRelation1 = tableViewManager // height = CGFloat(relations["Managers"]!.count) * 50.0 // case "Assistant": tableViewRelation1 = tableViewAssitant height = CGFloat(relations["Assistant"]!.count) * 50.0 // case "Colleagues": // tableViewRelation1 = tableViewColleague // height = CGFloat(relations["Colleagues"]!.count) * 50.0 // case "Team Members": // tableViewRelation1 = tableViewTeam // height = CGFloat((relations["Team Members"]?.count)!) * 50.0 // default: break // } tableViewRelation1.frame = CGRect(x:0,y: 40,width: Int(UIScreen.main.bounds.width),height: Int(height)) cell.relationType.text = "Assistant" self.currentRelation = "Assistant" cell.removeSeparator(width: 0.0) cell.addSubview(tableViewRelation1) } case 2: if (relations["Team Members"] != nil) { var tableViewRelation2: UITableView = UITableView() var height: CGFloat = 0.0 // switch Array(relations.keys)[indexPath.row] { // case "Managers": // tableViewRelation2 = tableViewManager // height = CGFloat(relations["Managers"]!.count) * 50.0 // case "Assistant": // tableViewRelation2 = tableViewAssitant // height = CGFloat(relations["Assistant"]!.count) * 50.0 // case "Colleagues": // tableViewRelation2 = tableViewColleague // height = CGFloat(relations["Colleagues"]!.count) * 50.0 // case "Team Members": tableViewRelation2 = tableViewTeam height = CGFloat(relations["Team Members"]!.count) * 50.0 // default: break // } tableViewRelation2.frame = CGRect(x:0,y: 40,width: Int(UIScreen.main.bounds.width),height: Int(height)) cell.relationType.text = "Team Members" self.currentRelation = "Team Members" cell.removeSeparator(width: 0.0) cell.addSubview(tableViewRelation2) } case 3: if (relations["Colleagues"] != nil) { var tableViewRelation3: UITableView = UITableView() var height: CGFloat = 0.0 // switch Array(relations.keys)[indexPath.row] { // case "Managers": // tableViewRelation3 = tableViewManager // height = CGFloat(relations["Managers"]!.count) * 50.0 // case "Assistant": // tableViewRelation3 = tableViewAssitant // height = CGFloat(relations["Assistant"]!.count) * 50.0 // case "Colleagues": tableViewRelation3 = tableViewColleague height = CGFloat(relations["Colleagues"]!.count) * 50.0 // case "Team Members": // tableViewRelation3 = tableViewTeam // height = CGFloat(relations["Team Members"]!.count) * 50.0 // default: break // } tableViewRelation3.frame = CGRect(x:0,y: 40,width: Int(UIScreen.main.bounds.width),height: Int(height)) cell.relationType.text = "Colleagues" self.currentRelation = "Colleagues" cell.removeSeparator(width: 0.0) cell.addSubview(tableViewRelation3) } default: return cell } return cell case 4: if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "skillCell", for: indexPath as IndexPath) as! skillTableViewCell let skill = profile.skills.skills cell.infoLabel.text = "Skills" cell.gameNames = skill cell.collectionView.reloadData() self.collectionViewHeightSkill = cell.collectionView.collectionViewLayout.collectionViewContentSize.height return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "skillCell", for: indexPath as IndexPath) as! skillTableViewCell let language = profile.langues.langues cell.infoLabel.text = "Language" cell.gameNames = language cell.collectionView.reloadData() self.collectionViewHeightLangue = cell.collectionView.collectionViewLayout.collectionViewContentSize.height return cell } default: let cell = UITableViewCell() return cell } } else if tableView == self.tableViewMember { let cell = tableView.dequeueReusableCell(withIdentifier: "memberCell", for: indexPath as IndexPath) as! memberTableViewCell let row = (selectedCellIndexPath?.row)! if let first_name = profile.projects[row].members_profile[indexPath.row].user?.first_name { if let last_name = profile.projects[row].members_profile[indexPath.row].user?.last_name { cell.memberName.text = "\(first_name) \(last_name)" } else { cell.memberName.text = "\(first_name)" } } //cell.pictureMember.image = UIImage(named: (profile.projects[row].members_profile[indexPath.row].user?.image!)!)?.circleMasked cell.pictureMember.downloadedFrom(link: (profile.projects[row].members_profile[indexPath.row].user?.image!)!) cell.pictureMember.setImageForName(string: cell.memberName.text!, backgroundColor: nil, circular: true, textAttributes: nil) //cell.jobTitleLabel.text = profile.projects[row].members_profile[indexPath.row].user?.job return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "relationMemberCell", for: indexPath as IndexPath) as! relationsMemberTableViewCell cell.delegate = self cell.indexPath = indexPath if let user_id = relations[self.currentRelation]?[indexPath.row].user?.user_id { cell.user_id = user_id } cell.relationMemberJob.text = relations[self.currentRelation]?[indexPath.row].user?.job cell.relationMemberName.text = "\((relations[self.currentRelation]?[indexPath.row].user?.first_name)!) \((relations[self.currentRelation]?[indexPath.row].user?.last_name)!)" //cell.relationMemberPicture.image = UIImage(named: (relations[self.currentRelation]?[indexPath.row].user?.image!)!)?.circleMasked cell.relationMemberPicture.downloadedFrom(link: (relations[self.currentRelation]?[indexPath.row].user?.image!)!) cell.relationMemberPicture.setImageForName(string: cell.relationMemberName.text!, backgroundColor: nil, circular: true, textAttributes: nil) return cell } } func getCurrentUpdatedUser() { let param: NSDictionary = [:] let url = "users/" + "\(profile.id)" var profiles:[Profile] = [] APIUtility.sharedInstance.getAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() if (error == nil) { //let status : Int = response?.value(forKey: "status") as! Int dump(response) let json = JSON(response)[0] //dump(response) //dump("json : \(json)") var users: [User] //Do something you want var projects: [Project] = [] var jobs: [Job] = [] var degrees: [Degree] = [] var user = User() var isRelationAvailable: Bool = false var relationshipID: Int = 0 if let first_name = json["first_name"].stringValue as? String, let last_name = json["last_name"].stringValue as? String { user.first_name = "\(first_name)" user.last_name = "\(last_name)" } if let job = json["job_title"].stringValue as? String { user.job = "\(job)" } if let location = json["office_address"].stringValue as? String { user.location = "\(location)" } if let image = json["picture_url"].stringValue as? String { user.image = image } if let entity = json["entity"].stringValue as? String { user.entities = "\(entity)" } if let external = json["external"].boolValue as? Bool { user.is_external = external } var skill = Skill() for j in 0..<json["skills"].count { print("s : \(json["skills"][j]["name"].stringValue)") if let s = json["skills"][j]["name"].stringValue as? String { skill.skills.append(s) } } print("skills : \(skill.skills)") var language = Language() for j in 0..<json["languages"].count { if let l = json["languages"][j]["name"].stringValue as? String { language.langues.append(l) } } var relations = Relation() for j in 0..<json["relationships"].count { if let relation = json["relationships"][j].dictionaryObject{ //let id = relation["target"]?["user_id"].int let profile = Profile() let user = User() if let target = relation["target"] as? Dictionary<String, AnyObject> { user.first_name = target["first_name"] as? String user.last_name = target["last_name"] as? String user.image = target["picture_url"] as? String user.job = target["job_title"] as? String user.user_id = (target["id"] as? Int)! } if(user.user_id == AppData.sharedInstance.currentUser.id) { isRelationAvailable = true relationshipID = relation["id"] as! Int } profile.user = user switch (relation["kind"] as! String) { case "is_manager_of": print("kind : \(relation["kind"] as! String)") relations.teamMembers_profile.append(profile) case "is_managed_by": relations.managers_profile.append(profile) case "is_colleague_of": relations.colleagues_profile.append(profile) case "is_assisted_by": relations.assistants_profile.append(profile) default: break } } } dump("relations : \(relations)") let profile_id = json["id"].intValue for j in 0..<json["projects"].count { let project = Project() let proj = (json["projects"][j]) project.title = proj["name"].stringValue project.location = proj["location"].stringValue project.objDescription = proj["project_participations"][0]["role_description"].stringValue project.id = proj["id"].intValue project.start_date = proj["project_participations"][0]["start_date"].stringValue project.end_date = proj["project_participations"][0]["end_date"].stringValue project.participation_id = proj["project_participations"][0]["id"].intValue //print("project.participation_id : \(project.participation_id)") for k in 0..<proj["project_participations"].count { let participants = proj["project_participations"].arrayValue print("k : \(k)") dump("participants : \(participants)") let participant = participants[k].dictionaryValue var profile = Profile() var user = User() profile.id = (participant["user_id"]?.intValue)! user.user_id = (participant["user_id"]?.intValue)! user.first_name = participant["user_first_name"]?.stringValue user.last_name = participant["user_last_name"]?.stringValue user.image = participant["user_picture_url"]?.stringValue profile.user = user project.members_profile.append(profile) } dump("project members : \(project.members_profile)") projects.append(project) } for j in 0..<json["jobs"].count { var job = Job() if let j = json["jobs"][j].dictionaryObject { job.title = j["title"] as? String job.location = j["location"] as? String job.id = j["id"] as? Int job.start_date = j["start_date"]as? String job.objDescription = j["description"] as? String jobs.append(job) } } for j in 0..<json["degrees"].count { var degree = Degree() if let j = json["degrees"][j].dictionaryObject { degree.title = j["title"] as? String if let objEntry_Year = j["entry_year"] { if !(objEntry_Year is NSNull) { degree.entry_year = "\(objEntry_Year as! Int)" } } if let objGraduation_year = j["graduation_year"] { if !(objGraduation_year is NSNull) { degree.graduation_year = "\(objGraduation_year as! Int)" } } degree.user_id = j["user_id"]as? Int let school : NSDictionary = (j["school"]) as! NSDictionary degree.school_id = school["id"] as? Int degree.school = school["name"] as? String degrees.append(degree) } } var contact = Contact() if let email = json["email"].stringValue as? String { contact.email = email } if let phone = json["phone"].stringValue as? String { contact.phone_number = json["phone"].stringValue } if let linkedin = json["linkedin"].stringValue as? String { contact.linkedin_profile = linkedin } if let wat = json["wat_link"].stringValue as? String { contact.wat_profile = wat } if let twitter = json["twitter"].stringValue as? String { contact.twitter_profile = twitter } if let agil = json["agil"].stringValue as? String { contact.agil_profile = agil } if let skype = json["skype"].stringValue as? String { contact.skipe = skype } let objprofile = Profile() objprofile.user = user objprofile.jobs = jobs.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) objprofile.contact = contact objprofile.projects = projects.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) objprofile.langues = language objprofile.skills = skill objprofile.relations = relations objprofile.relations.isRelationAvailable = isRelationAvailable objprofile.relations.relationshipID = relationshipID objprofile.degree = degrees.sorted(by: { $0.entry_year?.compare($1.entry_year!) == .orderedDescending }) self.relations = relationsArray(relations: relations) if let id = json["id"].intValue as? Int { objprofile.id = id } dump(objprofile) profiles.append(objprofile) var objProfile = Profile() objProfile = profiles[0] self.profile = objProfile if let cb = self.callbackLatestProfile { cb(self.profile) } self.updatedCurrentUserView() } else { let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func updatedCurrentUserView() { let screenSize: CGRect = UIScreen.main.bounds if profile.id != 0 { if (self.profile.user.is_external == true) { self.is_external.isHidden = false } if (profile.contact.linkedin_profile?.characters.count)! > 0 { stackLinkedin.isHidden = false } else { stackLinkedin.isHidden = true } if (profile.contact.twitter_profile?.characters.count)! > 0 { stackTwitter.isHidden = false } else { stackTwitter.isHidden = true } if (profile.contact.linkedin_profile?.characters.count)! <= 0 && (profile.contact.twitter_profile?.characters.count)! > 0 { stackTwitterLeading.constant = 0 self.contentView.layoutIfNeeded() } if (profile.contact.linkedin_profile?.characters.count)! <= 0 && (profile.contact.twitter_profile?.characters.count)! <= 0 { // contentView.frame = CGRect(x:0,y: 0,width: screenSize.width,height: contentView.frame.size.height - otherServicesHeight.constant) otherServicesHeight.constant = 0 self.contentView.layoutIfNeeded() } if (profile.contact.email?.characters.count)! <= 0 || (profile.contact.phone_number?.characters.count)! <= 0 { contactInformationHeight.constant = stackEmailHeight.constant + 40 self.contentView.layoutIfNeeded() } if (profile.contact.email?.characters.count)! <= 0 && (profile.contact.phone_number?.characters.count)! <= 0 { contactInformationHeight.constant = 0 self.contentView.layoutIfNeeded() } if (profile.contact.email?.characters.count)! <= 0 { stackEmailHeight.constant = 0 stackPhoneNumberTop.constant = 0 self.contentView.layoutIfNeeded() } if (profile.contact.phone_number?.characters.count)! <= 0 { stackPhoneNumberHeight.constant = 0 self.contentView.layoutIfNeeded() } contentInformationView.frame = CGRect(x:0,y: viewProfileInformation.frame.origin.y + viewProfileInformation.frame.size.height ,width: screenSize.width,height: viewOtherServices.frame.size.height + contactInformationHeight.constant + viewContactInformation.frame.origin.y) contentView.frame = CGRect(x:0,y: 0,width: screenSize.width,height: contentInformationView.frame.size.height + contentInformationView.frame.origin.y + 10) imageProfile.downloadedFrom(link: (profile.user?.image!)!) imageProfile.setImageForName(string: "\((profile.user?.first_name)!) \((profile.user?.last_name)!)", backgroundColor: nil, circular: true, textAttributes: nil) //imageProfile.image?.circleMasked //UIImage(named: (profile.user?.image)!)?.circleMasked nameProfile.text = "\((profile.user?.first_name)!) \((profile.user?.last_name)!)" jobLabel.text = profile.user?.job locationLabel.text = profile.user?.location entitiesLabel.text = profile.user?.entities } imageProfile.downloadedFrom(link: (profile.user?.image!)!) imageProfile.setImageForName(string: "\((profile.user?.first_name)!) \((profile.user?.last_name)!)", backgroundColor: nil, circular: true, textAttributes: nil) //imageProfile.image?.circleMasked //UIImage(named: (profile.user?.image)!)?.circleMasked nameProfile.text = "\((profile.user?.first_name)!) \((profile.user?.last_name)!)" jobLabel.text = profile.user?.job locationLabel.text = profile.user?.location entitiesLabel.text = profile.user?.entities //Contact emailLabel.text = profile.contact.email phoneLabel.text = profile.contact.phone_number if(profile.relations.isRelationAvailable) { connectButton.setTitle("Remove",for: .normal) } else { connectButton.setTitle("Connect",for: .normal) } self.tableView.reloadData() self.scrollView.contentSize = CGSize(width: self.tableViewContentSize().width, height: self.tableViewContentSize().height + contentView.frame.size.height) } func pushUserFromID(user_id : Int) { if let profileVC = UIStoryboard(name: "Storyboard", bundle: nil).instantiateViewController(withIdentifier: "profileViewController") as? profileViewController { if self.searchBar.isFirstResponder == true { self.searchBar.resignFirstResponder() } profileVC.profile_id = user_id profileVC.access_token = self.access_token if let navigator = self.navigationController { navigator.pushViewController(profileVC, animated: true) } } } func getUserFromID(user_id : Int) { let param: NSDictionary = [:] let url = "users/" + "\(user_id)" var profiles:[Profile] = [] APIUtility.sharedInstance.getAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() if (error == nil) { //let status : Int = response?.value(forKey: "status") as! Int dump(response) let json = JSON(response)[0] //dump(response) //dump("json : \(json)") var users: [User] //Do something you want var projects: [Project] = [] var jobs: [Job] = [] var degrees: [Degree] = [] var user = User() var isRelationAvailable: Bool = false var relationshipID: Int = 0 if let first_name = json["first_name"].stringValue as? String, let last_name = json["last_name"].stringValue as? String { user.first_name = "\(first_name)" user.last_name = "\(last_name)" } if let job = json["job_title"].stringValue as? String { user.job = "\(job)" } if let location = json["office_address"].stringValue as? String { user.location = "\(location)" } if let image = json["picture_url"].stringValue as? String { user.image = image } if let entity = json["entity"].stringValue as? String { user.entities = "\(entity)" } var skill = Skill() for j in 0..<json["skills"].count { print("s : \(json["skills"][j]["name"].stringValue)") if let s = json["skills"][j]["name"].stringValue as? String { skill.skills.append(s) } } print("skills : \(skill.skills)") var language = Language() for j in 0..<json["languages"].count { if let l = json["languages"][j]["name"].stringValue as? String { language.langues.append(l) } } var relations = Relation() for j in 0..<json["relationships"].count { if let relation = json["relationships"][j].dictionaryObject{ //let id = relation["target"]?["user_id"].int let profile = Profile() let user = User() if let target = relation["target"] as? Dictionary<String, AnyObject> { user.first_name = target["first_name"] as? String user.last_name = target["last_name"] as? String user.image = target["picture_url"] as? String user.job = target["job_title"] as? String user.user_id = (target["id"] as? Int)! } if(user.user_id == AppData.sharedInstance.currentUser.id) { isRelationAvailable = true relationshipID = relation["id"] as! Int } profile.user = user switch (relation["kind"] as! String) { case "is_manager_of": print("kind : \(relation["kind"] as! String)") relations.teamMembers_profile.append(profile) case "is_managed_by": relations.managers_profile.append(profile) case "is_colleague_of": relations.colleagues_profile.append(profile) case "is_assisted_by": relations.assistants_profile.append(profile) default: break } } } dump("relations : \(relations)") let profile_id = json["id"].intValue for j in 0..<json["projects"].count { let project = Project() let proj = (json["projects"][j]) project.title = proj["name"].stringValue project.location = proj["location"].stringValue project.objDescription = proj["project_participations"][0]["role_description"].stringValue project.id = proj["id"].intValue project.start_date = proj["project_participations"][0]["start_date"].stringValue project.end_date = proj["project_participations"][0]["end_date"].stringValue project.participation_id = proj["project_participations"][0]["id"].intValue //print("project.participation_id : \(project.participation_id)") for k in 0..<proj["project_participations"].count { let participants = proj["project_participations"].arrayValue print("k : \(k)") dump("participants : \(participants)") let participant = participants[k].dictionaryValue var profile = Profile() var user = User() profile.id = (participant["user_id"]?.intValue)! user.user_id = (participant["user_id"]?.intValue)! user.first_name = participant["user_first_name"]?.stringValue user.last_name = participant["user_last_name"]?.stringValue user.image = participant["user_picture_url"]?.stringValue profile.user = user project.members_profile.append(profile) } dump("project members : \(project.members_profile)") projects.append(project) } for j in 0..<json["jobs"].count { var job = Job() if let j = json["jobs"][j].dictionaryObject { job.title = j["title"] as? String job.location = j["location"] as? String job.id = j["id"] as? Int job.start_date = j["start_date"]as? String job.objDescription = j["description"] as? String jobs.append(job) } } for j in 0..<json["degrees"].count { var degree = Degree() if let j = json["degrees"][j].dictionaryObject { degree.title = j["title"] as? String if let objEntry_Year = j["entry_year"] { if !(objEntry_Year is NSNull) { degree.entry_year = "\(objEntry_Year as! Int)" } } if let objGraduation_year = j["graduation_year"] { if !(objGraduation_year is NSNull) { degree.graduation_year = "\(objGraduation_year as! Int)" } } degree.user_id = j["user_id"]as? Int let school : NSDictionary = (j["school"]) as! NSDictionary degree.school_id = school["id"] as? Int degree.school = school["name"] as? String degrees.append(degree) } } var contact = Contact() if let email = json["email"].stringValue as? String { contact.email = email } if let phone = json["phone"].stringValue as? String { contact.phone_number = json["phone"].stringValue } if let linkedin = json["linkedin"].stringValue as? String { contact.linkedin_profile = linkedin } if let wat = json["wat_link"].stringValue as? String { contact.wat_profile = wat } if let twitter = json["twitter"].stringValue as? String { contact.twitter_profile = twitter } if let agil = json["agil"].stringValue as? String { contact.agil_profile = agil } if let skype = json["skype"].stringValue as? String { contact.skipe = skype } let profile = Profile() profile.user = user profile.jobs = jobs.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) profile.contact = contact profile.projects = projects.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) profile.langues = language profile.skills = skill profile.relations = relations profile.relations.isRelationAvailable = isRelationAvailable profile.relations.relationshipID = relationshipID profile.degree = degrees.sorted(by: { $0.entry_year?.compare($1.entry_year!) == .orderedDescending }) if let id = json["id"].intValue as? Int { profile.id = id } dump(profile) profiles.append(profile) var objProfile = Profile() objProfile = profiles[0] if let profileVC = UIStoryboard(name: "Storyboard", bundle: nil).instantiateViewController(withIdentifier: "profileViewController") as? profileViewController { if self.searchBar.isFirstResponder == true { self.searchBar.resignFirstResponder() } profileVC.profile = objProfile profileVC.relations = relationsArray(relations: relations) profileVC.access_token = self.access_token if let navigator = self.navigationController { navigator.pushViewController(profileVC, animated: true) } } } else { let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func getUserFromIDForRelationship(user_id : Int,sender: AnyObject) { if user_id == AppData.sharedInstance.currentUser.id{ return } let param: NSDictionary = [:] let url = "users/" + "\(user_id)" var profiles:[Profile] = [] APIUtility.sharedInstance.getAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() if (error == nil) { //let status : Int = response?.value(forKey: "status") as! Int dump(response) let json = JSON(response)[0] //dump(response) //dump("json : \(json)") var users: [User] //Do something you want var projects: [Project] = [] var jobs: [Job] = [] var degrees: [Degree] = [] var user = User() var isRelationAvailable: Bool = false var relationshipID: Int = 0 if let first_name = json["first_name"].stringValue as? String, let last_name = json["last_name"].stringValue as? String { user.first_name = "\(first_name)" user.last_name = "\(last_name)" } if let job = json["job_title"].stringValue as? String { user.job = "\(job)" } if let location = json["office_address"].stringValue as? String { user.location = "\(location)" } if let image = json["picture_url"].stringValue as? String { user.image = image } if let entity = json["entity"].stringValue as? String { user.entities = "\(entity)" } var skill = Skill() for j in 0..<json["skills"].count { print("s : \(json["skills"][j]["name"].stringValue)") if let s = json["skills"][j]["name"].stringValue as? String { skill.skills.append(s) } } print("skills : \(skill.skills)") var language = Language() for j in 0..<json["languages"].count { if let l = json["languages"][j]["name"].stringValue as? String { language.langues.append(l) } } var relations = Relation() for j in 0..<json["relationships"].count { if let relation = json["relationships"][j].dictionaryObject{ //let id = relation["target"]?["user_id"].int let profile = Profile() let user = User() if let target = relation["target"] as? Dictionary<String, AnyObject> { user.first_name = target["first_name"] as? String user.last_name = target["last_name"] as? String user.image = target["picture_url"] as? String user.job = target["job_title"] as? String user.user_id = (target["id"] as? Int)! } if(user.user_id == AppData.sharedInstance.currentUser.id) { isRelationAvailable = true relationshipID = relation["id"] as! Int } profile.user = user switch (relation["kind"] as! String) { case "is_manager_of": print("kind : \(relation["kind"] as! String)") relations.teamMembers_profile.append(profile) case "is_managed_by": relations.managers_profile.append(profile) case "is_colleague_of": relations.colleagues_profile.append(profile) case "is_assisted_by": relations.assistants_profile.append(profile) default: break } } } dump("relations : \(relations)") let profile_id = json["id"].intValue for j in 0..<json["projects"].count { let project = Project() let proj = (json["projects"][j]) project.title = proj["name"].stringValue project.location = proj["location"].stringValue project.objDescription = proj["project_participations"][0]["role_description"].stringValue project.id = proj["id"].intValue project.start_date = proj["project_participations"][0]["start_date"].stringValue project.end_date = proj["project_participations"][0]["end_date"].stringValue project.participation_id = proj["project_participations"][0]["id"].intValue //print("project.participation_id : \(project.participation_id)") for k in 0..<proj["project_participations"].count { let participants = proj["project_participations"].arrayValue print("k : \(k)") dump("participants : \(participants)") let participant = participants[k].dictionaryValue var profile = Profile() var user = User() profile.id = (participant["user_id"]?.intValue)! user.user_id = (participant["user_id"]?.intValue)! user.first_name = participant["user_first_name"]?.stringValue user.last_name = participant["user_last_name"]?.stringValue user.image = participant["user_picture_url"]?.stringValue profile.user = user project.members_profile.append(profile) } dump("project members : \(project.members_profile)") projects.append(project) } for j in 0..<json["jobs"].count { var job = Job() if let j = json["jobs"][j].dictionaryObject { job.title = j["title"] as? String job.location = j["location"] as? String job.id = j["id"] as? Int job.start_date = j["start_date"]as? String job.objDescription = j["description"] as? String jobs.append(job) } } for j in 0..<json["degrees"].count { var degree = Degree() if let j = json["degrees"][j].dictionaryObject { degree.title = j["title"] as? String if let objEntry_Year = j["entry_year"] { if !(objEntry_Year is NSNull) { degree.entry_year = "\(objEntry_Year as! Int)" } } if let objGraduation_year = j["graduation_year"] { if !(objGraduation_year is NSNull) { degree.graduation_year = "\(objGraduation_year as! Int)" } } degree.user_id = j["user_id"]as? Int let school : NSDictionary = (j["school"]) as! NSDictionary degree.school_id = school["id"] as? Int degree.school = school["name"] as? String degrees.append(degree) } } var contact = Contact() if let email = json["email"].stringValue as? String { contact.email = email } if let phone = json["phone"].stringValue as? String { contact.phone_number = json["phone"].stringValue } if let linkedin = json["linkedin"].stringValue as? String { contact.linkedin_profile = linkedin } if let wat = json["wat_link"].stringValue as? String { contact.wat_profile = wat } if let twitter = json["twitter"].stringValue as? String { contact.twitter_profile = twitter } if let agil = json["agil"].stringValue as? String { contact.agil_profile = agil } if let skype = json["skype"].stringValue as? String { contact.skipe = skype } let profile = Profile() profile.user = user profile.jobs = jobs.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) profile.contact = contact profile.projects = projects.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) profile.langues = language profile.skills = skill profile.relations = relations profile.relations.isRelationAvailable = isRelationAvailable profile.relations.relationshipID = relationshipID profile.degree = degrees.sorted(by: { $0.entry_year?.compare($1.entry_year!) == .orderedDescending }) if let id = json["id"].intValue as? Int { profile.id = id } dump(profile) profiles.append(profile) var objProfile = Profile() objProfile = profiles[0] self.toConnect(profile: objProfile, sender: sender) } else { let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func addRelationShip(kind: String) { // POST /api/v1/relationships let url = "relationships" let param: NSDictionary = ["relationship": ["user_id": AppData.sharedInstance.currentUser.id,"target_id": profile.id,"kind": kind]] APIUtility.sharedInstance.postAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() self.getCurrentUpdatedUser() if (error == nil) { let json = JSON(response) print("response edit profile") dump(json) } else { let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func removeRelationShipWithID(relationship_id: Int) { // DELETE /api/v1/relationships/{relationship_id} let url = "relationships/" + "\(relationship_id)" let param: NSDictionary = ["relationship_id": relationship_id] APIUtility.sharedInstance.deleteAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() self.getCurrentUpdatedUser() if (error == nil) { let json = JSON(response) print("response edit profile") dump(json) } else { let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func toConnect(profile: Profile, sender: AnyObject) { if(profile.relations.isRelationAvailable) { let actionSheetController: UIAlertController = UIAlertController(title: "Confirm", message: "Do you want to remove your relationship?", preferredStyle: .alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in //Just dismiss the action sheet } let removeAction: UIAlertAction = UIAlertAction(title: "Remove", style: .destructive) { action -> Void in //Just dismiss the action sheet self.removeRelationShipWithID(relationship_id: profile.relations.relationshipID) } actionSheetController.addAction(cancelAction) actionSheetController.addAction(removeAction) self.present(actionSheetController, animated: true, completion: nil) } else { let myActionSheet = UIAlertController(title: "Confirm new relationship", message: "Add", preferredStyle: UIAlertControllerStyle.actionSheet) // blue action button let blueAction = UIAlertAction(title: "as colleague", style: UIAlertActionStyle.default) { (action) in print("As colleague") self.addRelationShip(kind: "is_colleague_of", profile: profile) } // red action button let redAction = UIAlertAction(title: "as manager", style: UIAlertActionStyle.default) { (action) in print("as Manager") self.addRelationShip(kind: "is_managed_by", profile: profile) } // yellow action button let yellowAction = UIAlertAction(title: "as team member", style: UIAlertActionStyle.default) { (action) in print("as Team member") self.addRelationShip(kind: "is_manager_of", profile: profile) } let purpleAction = UIAlertAction(title: "as assistant", style: UIAlertActionStyle.default) { (action) in print("as assistant") self.addRelationShip(kind: "is_assisted_by", profile: profile) } // cancel action button let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (action) in print("Cancel action button tapped") } // add action buttons to action sheet myActionSheet.addAction(blueAction) myActionSheet.addAction(redAction) myActionSheet.addAction(yellowAction) myActionSheet.addAction(purpleAction) myActionSheet.addAction(cancelAction) // support iPads (popover view) myActionSheet.popoverPresentationController?.sourceView = sender as! UIButton myActionSheet.popoverPresentationController?.sourceRect = sender.bounds // present the action sheet self.present(myActionSheet, animated: true, completion: nil) } } func addRelationShip(kind: String,profile: Profile) { // POST /api/v1/relationships let url = "relationships" let param: NSDictionary = ["relationship": ["user_id": AppData.sharedInstance.currentUser.id,"target_id": profile.id,"kind": kind]] APIUtility.sharedInstance.postAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() // self.getCurrentUpdatedUser() if (error == nil) { let json = JSON(response) print("response edit profile") dump(json) } else { let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func handleLinkedinImage(sender: UITapGestureRecognizer? = nil) { // handling code if (profile.contact.linkedin_profile?.characters.count)! > 0 { guard var url = NSURL(string: profile.contact.linkedin_profile!) else { print("INVALID URL") return } /// Test for valid scheme & append "http" if needed if !["http", "https"].contains(url.scheme?.lowercased() ?? "") { let appendedLink = "http://" + profile.contact.linkedin_profile! url = NSURL(string: appendedLink)! } let svc = SFSafariViewController(url: url as URL, entersReaderIfAvailable: true) self.present(svc, animated: true, completion: nil) } } func handleTwitterImage(sender: UITapGestureRecognizer? = nil) { // handling code if (profile.contact.twitter_profile?.characters.count)! > 0 { guard var url = NSURL(string: profile.contact.twitter_profile!) else { print("INVALID URL") return } /// Test for valid scheme & append "http" if needed if !["http", "https"].contains(url.scheme?.lowercased() ?? "") { let appendedLink = "https://twitter.com/" + profile.contact.twitter_profile! url = NSURL(string: appendedLink)! } let svc = SFSafariViewController(url: url as URL, entersReaderIfAvailable: true) self.present(svc, animated: true, completion: nil) } } func handleEmailID(sender: UITapGestureRecognizer? = nil) { // handling code if (profile.contact.email != nil) { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setToRecipients([profile.contact.email!]) // mail.setSubject("Bla") // mail.setMessageBody("<b>Blabla</b>", isHTML: true) present(mail, animated: true, completion: nil) } else { print("Cannot send mail") // give feedback to the user } } } func handlePhoneNumber(sender: UITapGestureRecognizer? = nil) { // handling code if (profile.contact.phone_number != nil) { callNumber(phoneNumber: profile.contact.phone_number!) } } private func callNumber(phoneNumber:String) { let scanner = Scanner(string: phoneNumber) let validCharacters = CharacterSet.decimalDigits let startCharacters = validCharacters.union(CharacterSet(charactersIn: "+#")) var digits: NSString? var validNumber = "" while !scanner.isAtEnd { if scanner.scanLocation == 0 { scanner.scanCharacters(from: startCharacters, into: &digits) } else { scanner.scanCharacters(from: validCharacters, into: &digits) } scanner.scanUpToCharacters(from: validCharacters, into: nil) if let digits = digits as? String { validNumber.append(digits) } } print(validNumber) if let phoneCallURL = URL(string: "tel://\(validNumber)") { let application:UIApplication = UIApplication.shared if (application.canOpenURL(phoneCallURL)) { if #available(iOS 10.0, *) { application.open(phoneCallURL, options: [:], completionHandler: nil) } else { // Fallback on earlier versions UIApplication.shared.openURL(phoneCallURL) } } } } // MARK: - MFMailComposeViewControllerDelegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { switch result.rawValue { case MFMailComposeResult.cancelled.rawValue: print("Cancelled") case MFMailComposeResult.saved.rawValue: print("Saved") case MFMailComposeResult.sent.rawValue: print("Sent") case MFMailComposeResult.failed.rawValue: print("Error: \(error?.localizedDescription)") default: break } controller.dismiss(animated: true, completion: nil) } /* // 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. } */ func tableViewContentSize() -> CGSize { tableView.layoutIfNeeded() let screenSize: CGRect = UIScreen.main.bounds tableView.frame = CGRect(x:0, y: contentView.frame.size.height, width: screenSize.width, height: tableView.contentSize.height) tableView.layoutIfNeeded() return tableView.contentSize } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { print("coucou1") // searchActive = true; } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { // searchActive = false; print("coucou2") } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchActive = false; // Clear any search criteria searchBar.text = "" // Dismiss the keyboard searchBar.resignFirstResponder() // Reload of table data //->> your search result table self.tableView.reloadData() print("coucou3") } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() if searchBar.text! != "" { usersSearchPageNo = 0; self.filtered = [] getDataWithSearch(txtSearch: searchBar.text!) } // searchActive = false; print("coucou4") } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText == "" { searchActive = false; tblSearch.isHidden = true filtered.removeAll() } else { searchActive = true; tblSearch.isHidden = false // getDataWithSearch(txtSearch: searchText) } self.tblSearch.reloadData() } func toConnect(profile: Profile, sender: AnyObject, index: IndexPath) { if(profile.relations.isRelationAvailable) { let actionSheetController: UIAlertController = UIAlertController(title: "Confirm", message: "Do you want to remove your relationship?", preferredStyle: .alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in //Just dismiss the action sheet } let removeAction: UIAlertAction = UIAlertAction(title: "Remove", style: .destructive) { action -> Void in //Just dismiss the action sheet self.removeRelationShipWithID(relationship_id: profile.relations.relationshipID, profile: profile, index: index) } actionSheetController.addAction(cancelAction) actionSheetController.addAction(removeAction) self.present(actionSheetController, animated: true, completion: nil) } else { let myActionSheet = UIAlertController(title: "Confirm new relationship", message: "Add", preferredStyle: UIAlertControllerStyle.actionSheet) // blue action button let blueAction = UIAlertAction(title: "as colleague", style: UIAlertActionStyle.default) { (action) in print("As colleague") self.addRelationShip(kind: "is_colleague_of", profile: profile, index: index) } // red action button let redAction = UIAlertAction(title: "as manager", style: UIAlertActionStyle.default) { (action) in print("as Manager") self.addRelationShip(kind: "is_managed_by", profile: profile, index: index) } // yellow action button let yellowAction = UIAlertAction(title: "as team member", style: UIAlertActionStyle.default) { (action) in print("as Team member") self.addRelationShip(kind: "is_manager_of", profile: profile, index: index) } let purpleAction = UIAlertAction(title: "as assistant", style: UIAlertActionStyle.default) { (action) in print("as assistant") self.addRelationShip(kind: "is_assisted_by", profile: profile, index: index) } // cancel action button let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (action) in print("Cancel action button tapped") } // add action buttons to action sheet myActionSheet.addAction(blueAction) myActionSheet.addAction(redAction) myActionSheet.addAction(yellowAction) myActionSheet.addAction(purpleAction) myActionSheet.addAction(cancelAction) // support iPads (popover view) myActionSheet.popoverPresentationController?.sourceView = sender as! UIButton myActionSheet.popoverPresentationController?.sourceRect = sender.bounds // present the action sheet self.present(myActionSheet, animated: true, completion: nil) } } func addRelationShip(kind: String,profile: Profile, index: IndexPath) { // POST /api/v1/relationships let url = "relationships" let param: NSDictionary = ["relationship": ["user_id": AppData.sharedInstance.currentUser.id,"target_id": profile.id,"kind": kind]] APIUtility.sharedInstance.postAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() self.getUserFromID(user_id: profile.id,index:index) if (error == nil) { let json = JSON(response) print("response edit profile") dump(json) } else { let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func removeRelationShipWithID(relationship_id: Int,profile: Profile, index: IndexPath) { // DELETE /api/v1/relationships/{relationship_id} let url = "relationships/" + "\(relationship_id)" let param: NSDictionary = ["relationship_id": relationship_id] APIUtility.sharedInstance.deleteAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() self.getUserFromID(user_id: profile.id,index:index) if (error == nil) { let json = JSON(response) print("response edit profile") dump(json) } else { let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func getUserFromID(user_id : Int, index: IndexPath) { let param: NSDictionary = [:] let url = "users/" + "\(user_id)" var profiles:[Profile] = [] APIUtility.sharedInstance.getAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() if (error == nil) { //let status : Int = response?.value(forKey: "status") as! Int dump(response) let json = JSON(response)[0] //dump(response) //dump("json : \(json)") var users: [User] //Do something you want var projects: [Project] = [] var jobs: [Job] = [] var degrees: [Degree] = [] var user = User() var isRelationAvailable: Bool = false var relationshipID: Int = 0 if let first_name = json["first_name"].stringValue as? String, let last_name = json["last_name"].stringValue as? String { user.first_name = "\(first_name)" user.last_name = "\(last_name)" } if let job = json["job_title"].stringValue as? String { user.job = "\(job)" } if let location = json["office_address"].stringValue as? String { user.location = "\(location)" } if let image = json["picture_url"].stringValue as? String { user.image = image } if let entity = json["entity"].stringValue as? String { user.entities = "\(entity)" } var skill = Skill() for j in 0..<json["skills"].count { print("s : \(json["skills"][j]["name"].stringValue)") if let s = json["skills"][j]["name"].stringValue as? String { skill.skills.append(s) } } print("skills : \(skill.skills)") var language = Language() for j in 0..<json["languages"].count { if let l = json["languages"][j]["name"].stringValue as? String { language.langues.append(l) } } var relations = Relation() for j in 0..<json["relationships"].count { if let relation = json["relationships"][j].dictionaryObject{ //let id = relation["target"]?["user_id"].int let profile = Profile() let user = User() if let target = relation["target"] as? Dictionary<String, AnyObject> { user.first_name = target["first_name"] as? String user.last_name = target["last_name"] as? String user.image = target["picture_url"] as? String user.job = target["job_title"] as? String user.user_id = (target["id"] as? Int)! } if(user.user_id == AppData.sharedInstance.currentUser.id) { isRelationAvailable = true relationshipID = relation["id"] as! Int } profile.user = user switch (relation["kind"] as! String) { case "is_manager_of": print("kind : \(relation["kind"] as! String)") relations.teamMembers_profile.append(profile) case "is_managed_by": relations.managers_profile.append(profile) case "is_colleague_of": relations.colleagues_profile.append(profile) case "is_assisted_by": relations.assistants_profile.append(profile) default: break } } } dump("relations : \(relations)") let profile_id = json["id"].intValue for j in 0..<json["projects"].count { let project = Project() let proj = (json["projects"][j]) project.title = proj["name"].stringValue project.location = proj["location"].stringValue project.objDescription = proj["project_participations"][0]["role_description"].stringValue project.id = proj["id"].intValue project.start_date = proj["project_participations"][0]["start_date"].stringValue project.end_date = proj["project_participations"][0]["end_date"].stringValue project.participation_id = proj["project_participations"][0]["id"].intValue //print("project.participation_id : \(project.participation_id)") for k in 0..<proj["project_participations"].count { let participants = proj["project_participations"].arrayValue print("k : \(k)") dump("participants : \(participants)") let participant = participants[k].dictionaryValue var profile = Profile() var user = User() profile.id = (participant["user_id"]?.intValue)! user.user_id = (participant["user_id"]?.intValue)! user.first_name = participant["user_first_name"]?.stringValue user.last_name = participant["user_last_name"]?.stringValue user.image = participant["user_picture_url"]?.stringValue profile.user = user project.members_profile.append(profile) } dump("project members : \(project.members_profile)") projects.append(project) } for j in 0..<json["jobs"].count { var job = Job() if let j = json["jobs"][j].dictionaryObject { job.title = j["title"] as? String job.location = j["location"] as? String job.id = j["id"] as? Int job.start_date = j["start_date"]as? String job.objDescription = j["description"] as? String jobs.append(job) } } for j in 0..<json["degrees"].count { var degree = Degree() if let j = json["degrees"][j].dictionaryObject { degree.title = j["title"] as? String if let objEntry_Year = j["entry_year"] { if !(objEntry_Year is NSNull) { degree.entry_year = "\(objEntry_Year as! Int)" } } if let objGraduation_year = j["graduation_year"] { if !(objGraduation_year is NSNull) { degree.graduation_year = "\(objGraduation_year as! Int)" } } degree.user_id = j["user_id"]as? Int let school : NSDictionary = (j["school"]) as! NSDictionary degree.school_id = school["id"] as? Int degree.school = school["name"] as? String degrees.append(degree) } } var contact = Contact() if let email = json["email"].stringValue as? String { contact.email = email } if let phone = json["phone"].stringValue as? String { contact.phone_number = json["phone"].stringValue } if let linkedin = json["linkedin"].stringValue as? String { contact.linkedin_profile = linkedin } if let wat = json["wat_link"].stringValue as? String { contact.wat_profile = wat } if let twitter = json["twitter"].stringValue as? String { contact.twitter_profile = twitter } if let agil = json["agil"].stringValue as? String { contact.agil_profile = agil } if let skype = json["skype"].stringValue as? String { contact.skipe = skype } let profile = Profile() profile.user = user profile.jobs = jobs.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) profile.contact = contact profile.projects = projects.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) profile.langues = language profile.skills = skill profile.relations = relations profile.relations.isRelationAvailable = isRelationAvailable profile.relations.relationshipID = relationshipID profile.degree = degrees.sorted(by: { $0.entry_year?.compare($1.entry_year!) == .orderedDescending }) if let id = json["id"].intValue as? Int { profile.id = id } dump(profile) profiles.append(profile) var objProfile = Profile() objProfile = profiles[0] if(self.searchActive){ if self.filtered.count>0 { self.filtered[index.row] = objProfile } } self.tblSearch.reloadData() } else { let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // Find collectionview cell nearest to the center of collectionView // Arbitrarily start with the last cell (as a default) if (self.tableView.contentOffset.y >= (self.tableView.contentSize.height - self.tableView.bounds.size.height)-200) { // Don't animate if(searchActive) { getDataWithSearch(txtSearch: searchBar.text!) } else { // getData() } } } func getDataWithSearch(txtSearch: String) { if Reachability.isConnectedToNetwork() == false { return } //SVProgressHUD.show() self.pagingSpinner.startAnimating() // Next page usersSearchPageNo += 1 let param: NSDictionary = ["page": usersSearchPageNo,"per_page": 15] print("getData called : \(self.access_token)") // GET /api/v1/users/search/{search_term} let url : String! = "users/search/" + txtSearch.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! APIUtility.sharedInstance.getAPICall(token: self.access_token, url: url, parameters: param) { (response, error) in // SVProgressHUD.dismiss() if (error == nil) { if(self.filtered.count>0) { } else { self.filtered = [] } //let status : Int = response?.value(forKey: "status") as! Int let json = JSON(response) //dump(json) var users: [User] for i in 0..<json.count { //Do something you want var projects: [Project] = [] var jobs: [Job] = [] var degrees: [Degree] = [] var user = User() var isRelationAvailable: Bool = false var relationshipID: Int = 0 if let first_name = json[i]["first_name"].stringValue as? String, let last_name = json[i]["last_name"].stringValue as? String { user.first_name = first_name user.last_name = last_name } if let job = json[i]["job_title"].stringValue as? String { user.job = "\(job)" } if let location = json[i]["office_address"].stringValue as? String { user.location = "\(location)" } if var image = json[i]["picture_url"].stringValue as? String { if image == "http://placehold.it/180x180" { image = "https://placeholdit.imgix.net/~text?txtsize=17&txt=180%C3%97180&w=180&h=180" } user.image = image //print("image : \(image)") } if let entity = json[i]["entity"].stringValue as? String { user.entities = "\(entity)" } if let external = json[i]["external"].boolValue as? Bool { user.is_external = external } var skill = Skill() for j in 0..<json[i]["skills"].count { //print("s : \(json[i]["skills"][j]["name"].stringValue)") if let s = json[i]["skills"][j]["name"].stringValue as? String { skill.skills.append(s) } } //print("skills : \(skill.skills)") var language = Language() for j in 0..<json[i]["languages"].count { if let l = json[i]["languages"][j]["name"].stringValue as? String { language.langues.append(l) } } var relations = Relation() for j in 0..<json[i]["relationships"].count { if let relation = json[i]["relationships"][j].dictionaryObject{ //let id = relation["target"]?["user_id"].int let profile = Profile() let user = User() if let target = relation["target"] as? Dictionary<String, AnyObject> { user.first_name = target["first_name"] as? String user.last_name = target["last_name"] as? String user.image = target["picture_url"] as? String user.job = target["job_title"] as? String user.user_id = (target["id"] as? Int)! } if(user.user_id == AppData.sharedInstance.currentUser.id) { isRelationAvailable = true relationshipID = relation["id"] as! Int } profile.user = user switch (relation["kind"] as! String) { case "is_manager_of": print("kind : \(relation["kind"] as! String)") relations.teamMembers_profile.append(profile) case "is_managed_by": relations.managers_profile.append(profile) case "is_colleague_of": relations.colleagues_profile.append(profile) case "is_assisted_by": relations.assistants_profile.append(profile) default: break } } } dump("relations : \(relations)") for j in 0..<json[i]["projects"].count { var project = Project() let proj = (json[i]["projects"][j]) //dump("proj : \(proj["id"])") // project = self.projects.first {$0.id! == proj["id"].intValue}! project.title = proj["name"].stringValue project.location = proj["location"].stringValue project.objDescription = proj["project_participations"][0]["role_description"].stringValue project.id = proj["id"].intValue project.start_date = proj["project_participations"][0]["start_date"].stringValue project.end_date = proj["project_participations"][0]["end_date"].stringValue project.participation_id = proj["project_participations"][0]["id"].intValue //print("project.participation_id : \(project.participation_id)") for k in 0..<proj["project_participations"].count { let participants = proj["project_participations"].arrayValue print("k : \(k)") dump("participants : \(participants)") let participant = participants[k].dictionaryValue var profile = Profile() var user = User() profile.id = (participant["user_id"]?.intValue)! user.user_id = (participant["user_id"]?.intValue)! user.first_name = participant["user_first_name"]?.stringValue user.last_name = participant["user_last_name"]?.stringValue user.image = participant["user_picture_url"]?.stringValue profile.user = user project.members_profile.append(profile) } dump("project members : \(project.members_profile)") projects.append(project) } for j in 0..<json[i]["jobs"].count { if let newj = json[i]["jobs"][j].dictionaryObject{ let job = Job() job.title = newj["title"] as? String job.location = newj["location"] as? String job.id = newj["id"] as? Int job.start_date = newj["start_date"] as? String job.end_date = newj["end_date"] as? String job.objDescription = newj["description"] as? String jobs.append(job) } } for j in 0..<json[i]["degrees"].count { if let j = json[i]["degrees"][j].dictionaryObject { let degree = Degree() degree.title = j["title"] as? String if let objEntry_Year = j["entry_year"] { if !(objEntry_Year is NSNull) { degree.entry_year = "\(objEntry_Year as! Int)" } } if let objGraduation_year = j["graduation_year"] { if !(objGraduation_year is NSNull) { degree.graduation_year = "\(objGraduation_year as! Int)" } } degree.user_id = j["user_id"]as? Int let school : NSDictionary = (j["school"]) as! NSDictionary degree.school_id = school["id"] as? Int degree.school = school["name"] as? String degrees.append(degree) } } var contact = Contact() if let email = json[i]["email"].stringValue as? String { contact.email = email } if let phone = json[i]["phone"].stringValue as? String { contact.phone_number = json[i]["phone"].stringValue } if let linkedin = json[i]["linkedin"].stringValue as? String { contact.linkedin_profile = linkedin } if let wat = json[i]["wat_link"].stringValue as? String { contact.wat_profile = wat } if let twitter = json[i]["twitter"].stringValue as? String { contact.twitter_profile = twitter } if let agil = json[i]["agil"].stringValue as? String { contact.agil_profile = agil } if let skype = json[i]["skype"].stringValue as? String { contact.skipe = skype } let profile = Profile() profile.user = user profile.jobs = jobs.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) profile.contact = contact profile.projects = projects.sorted(by: { $0.start_date?.compare($1.start_date!) == .orderedDescending }) profile.langues = language profile.skills = skill profile.relations = relations profile.relations.isRelationAvailable = isRelationAvailable profile.relations.relationshipID = relationshipID profile.degree = degrees.sorted(by: { $0.entry_year?.compare($1.entry_year!) == .orderedDescending }) //dump("relations : \(profile.relations)") if let id = json[i]["id"].intValue as? Int { profile.id = id print("id profile : \(profile.id)") } //dump(profile) self.filtered.append(profile) //defaults.set(self.profiles, forKey: "profiles") print("coucou") } //self.getRelation() //self.matchRelationMember() //self.matchProjectMemberId() self.tblSearch.reloadData() self.pagingSpinner.stopAnimating() } else { self.pagingSpinner.stopAnimating() let alert = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } //Calls this function when the tap is recognized. override func dismissKeyboard() { if searchBar.isFirstResponder == true && searchBar.text == ""{ searchBar.resignFirstResponder() } } func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) { print("call downloaded image") URLSession.shared.dataTask(with: url) { (data, response, error) in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let image = UIImage(data: data) else { print("error downloaded image") return } DispatchQueue.main.async() { () -> Void in // self.image = image.circleMasked do { let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let fileURL = documentsURL.appendingPathComponent("profile_pic.png") if let pngImageData = UIImagePNGRepresentation(image) { try pngImageData.write(to: fileURL, options: .atomic) } } catch { } if #available(iOS 9.0, *) { let store = CNContactStore() let contact = CNMutableContact() let homePhone = CNLabeledValue(label: CNLabelHome, value: CNPhoneNumber(stringValue :self.profile.contact.self.phone_number!)) contact.givenName = (self.profile.user?.first_name)! contact.familyName = (self.profile.user?.last_name)! if (self.profile.contact.email!.contains("total.com")) { contact.organizationName = "Total" } contact.phoneNumbers = [homePhone] let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let filePath = documentsURL.appendingPathComponent("profile_pic.png").path if FileManager.default.fileExists(atPath: filePath) { let img = UIImage(contentsOfFile: filePath) contact.imageData = UIImagePNGRepresentation(img!) as Data? } // contact.imageData = data as Data? let workEmail = CNLabeledValue(label:CNLabelWork, value:self.profile.contact.email! as NSString) contact.emailAddresses = [workEmail] let controller = CNContactViewController(forNewContact : contact)// .viewControllerForUnknownContact(contact) controller.contactStore = store controller.delegate = self self.navigationController?.setNavigationBarHidden(false, animated: true) let navController = UINavigationController(rootViewController: controller) // Creating a navigation controller with VC1 at the root of the navigation stack. self.present(navController, animated:true, completion: nil) } print("done downloaded image") } }.resume() } func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) { print("call downloaded image") if link.contains("placeholdit.imgix.net") { return } guard let url = URL(string: link) else { return } downloadedFrom(url: url, contentMode: mode) } }
apache-2.0
f8052c930dd0d024079ca73d64d60935
44.754873
296
0.50954
5.525967
false
false
false
false
ianyh/Highball
Highball/PostPhoto.swift
1
1451
// // PostPhoto.swift // Highball // // Created by Ian Ynda-Hummel on 8/29/14. // Copyright (c) 2014 ianynda. All rights reserved. // import Mapper import SwiftyJSON import UIKit internal struct Size: Mappable { let width: Double let url: NSURL init(map: Mapper) throws { width = try map.from("width") url = try map.from("url") } } public struct PostPhoto: Mappable { public let width: CGFloat public let height: CGFloat private let sizes: [Size] public let widthToHeightRatio: Double? public init(map: Mapper) throws { let width: Double = map.optionalFrom("original_size.width") ?? 0 let height: Double = map.optionalFrom("original_size.height") ?? 0 self.width = CGFloat(width) self.height = CGFloat(height) if width > 0 && height > 0 { widthToHeightRatio = width / height } else { widthToHeightRatio = 1.0 } let originalSize: Size = try map.from("original_size") let alternateSizes: [Size] = try map.from("alt_sizes") sizes = ([originalSize] + alternateSizes).sort { $0.width > $1.width } } public func urlWithWidth(width: CGFloat) -> NSURL { let appDelegate = UIApplication.sharedApplication().delegate if let delegate = appDelegate as? AppDelegate, reachability = delegate.reachability { if reachability.isReachableViaWiFi() { return sizes.first!.url } } let largerSizes = sizes.filter { $0.width > Double(width) } return largerSizes.last?.url ?? sizes.first!.url } }
mit
d90204cd83ee81390d2e31c34ed722fd
23.183333
87
0.694693
3.358796
false
false
false
false
Rapid-SDK/ios
Examples/RapiDO - ToDo list/RapiDO iOS/FilterViewController.swift
1
4825
// // FilterViewController.swift // ExampleApp // // Created by Jan on 05/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import UIKit import Rapid protocol FilterViewControllerDelegate: class { func filterViewControllerDidCancel(_ controller: FilterViewController) func filterViewControllerDidFinish(_ controller: FilterViewController, withFilter filter: RapidFilter?) } class FilterViewController: UIViewController { weak var delegate: FilterViewControllerDelegate? var filter: RapidFilter? @IBOutlet weak var segmentedControl: UISegmentedControl! { didSet { segmentedControl.tintColor = .appRed } } @IBOutlet weak var tagsTableView: TagsTableView! @IBOutlet weak var doneButton: UIButton! { didSet { doneButton.setTitleColor(.white, for: .normal) doneButton.backgroundColor = .appRed doneButton.titleLabel?.font = UIFont.systemFont(ofSize: 15) } } @IBOutlet weak var cancelButton: UIButton! { didSet { cancelButton.setTitleColor(.appRed, for: .normal) cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: 15) } } @IBOutlet weak var separatorView: UIView! { didSet { separatorView.backgroundColor = .appRed } } override func viewDidLoad() { super.viewDidLoad() setupUI() } // MARK: Actions @IBAction func cancel(_ sender: Any) { delegate?.filterViewControllerDidCancel(self) } @IBAction func done(_ sender: Any) { var operands = [RapidFilter]() // Segmented control selected index equal to 1 means "show all tasks regardless completion state", so no filter is needed // Otherwise, create filter for either completed or incompleted tasks if segmentedControl.selectedSegmentIndex != 1 { let completed = segmentedControl.selectedSegmentIndex == 0 operands.append(RapidFilter.equal(keyPath: Task.completedAttributeName, value: completed)) } // Create filter for selected tags let selectedTags = tagsTableView.selectedTags if selectedTags.count > 0 { var tagFilters = [RapidFilter]() for tag in selectedTags { tagFilters.append(RapidFilter.arrayContains(keyPath: Task.tagsAttributeName, value: tag.rawValue)) } // Combine single tag filters with logical "OR" operator operands.append(RapidFilter.or(tagFilters)) } // If there are any filters combine them with logical "AND" let filter: RapidFilter? if operands.count > 0 { filter = RapidFilter.and(operands) } else { filter = nil } delegate?.filterViewControllerDidFinish(self, withFilter: filter) } } fileprivate extension FilterViewController { /// Setup UI according to filter func setupUI() { if let expression = filter?.expression, case .compound(_, let operands) = expression { var tagsSet = false var completionSet = false for operand in operands { switch operand { case .simple(_, _, let value): completionSet = true let done = value as? Bool ?? false let index = done ? 0 : 2 segmentedControl.selectedSegmentIndex = index case .compound(_, let operands): tagsSet = true var tags = [Tag]() for case .simple(_, _, let value) in operands { switch value as? String { case .some(Tag.home.rawValue): tags.append(.home) case .some(Tag.work.rawValue): tags.append(.work) case .some(Tag.other.rawValue): tags.append(.other) default: break } } tagsTableView.selectTags(tags) } } if !tagsSet { tagsTableView.selectTags([]) } if !completionSet { segmentedControl.selectedSegmentIndex = 1 } } else { segmentedControl.selectedSegmentIndex = 1 tagsTableView.selectTags([]) } } }
mit
852de92f34ecb122cd23aa9d46b2473a
31.594595
129
0.534826
5.868613
false
false
false
false
alblue/swift
test/SILGen/assignment.swift
1
1976
// RUN: %target-swift-emit-silgen -enable-sil-ownership -enforce-exclusivity=checked %s | %FileCheck %s class C {} struct A {} struct B { var owner: C } var a = A() // CHECK-LABEL: sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { // CHECK: assign {{%.*}} to {{%.*}} : $*A // CHECK: destroy_value {{%.*}} : $B // CHECK: } // end sil function 'main' (a, _) = (A(), B(owner: C())) class D { var child: C = C() } // Verify that the LHS is formally evaluated before the RHS. // CHECK-LABEL: sil hidden @$s10assignment5test1yyF : $@convention(thin) () -> () { func test1() { // CHECK: [[T0:%.*]] = metatype $@thick D.Type // CHECK: [[CTOR:%.*]] = function_ref @$s10assignment1DC{{[_0-9a-zA-Z]*}}fC // CHECK: [[D:%.*]] = apply [[CTOR]]([[T0]]) // CHECK: [[T0:%.*]] = metatype $@thick C.Type // CHECK: [[CTOR:%.*]] = function_ref @$s10assignment1CC{{[_0-9a-zA-Z]*}}fC // CHECK: [[C:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(method) (@thick C.Type) -> @owned C // CHECK: [[SETTER:%.*]] = class_method [[D]] : $D, #D.child!setter.1 // CHECK: apply [[SETTER]]([[C]], [[D]]) // CHECK: destroy_value [[D]] D().child = C() } // rdar://32039566 protocol P { var left: Int {get set} var right: Int {get set} } // Verify that the access to the LHS does not begin until after the // RHS is formally evaluated. // CHECK-LABEL: sil hidden @$s10assignment15copyRightToLeft1pyAA1P_pz_tF : $@convention(thin) (@inout P) -> () { func copyRightToLeft(p: inout P) { // CHECK: bb0(%0 : @trivial $*P): // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*P // CHECK: [[READ_OPEN:%.*]] = open_existential_addr immutable_access [[READ]] // CHECK: end_access [[READ]] : $*P // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*P // CHECK: [[WRITE_OPEN:%.*]] = open_existential_addr mutable_access [[WRITE]] // CHECK: end_access [[WRITE]] : $*P p.left = p.right }
apache-2.0
bbc31ac774f2df7d9d5741b53d93eda0
37.745098
122
0.581478
3.106918
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/App Lista (7.0)/Lista Core Data/Lista/ListaTableViewController.swift
1
3600
// // ListaTableViewController.swift // Lista // // Created by Fabio Santos on 11/3/14. // Copyright (c) 2014 Fabio Santos. All rights reserved. // import UIKit import CoreData class ListaTableViewController: UITableViewController { var itens: [Item] = [] override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let moc = appDelegate.managedObjectContext! let fetchRequest = NSFetchRequest(entityName: "Item") var erro: NSError do { itens = try moc.executeFetchRequest(fetchRequest) as! [Item] } catch { erro = error as NSError print("O fetch não foi possível. \(erro), \(erro.userInfo)") } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itens.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ListaPrototypeCell", forIndexPath: indexPath) let itemDaLista = itens[indexPath.row] cell.textLabel?.text = itemDaLista.nome cell.accessoryType = itemDaLista.foiConcluido ? UITableViewCellAccessoryType.Checkmark :UITableViewCellAccessoryType.None return cell } // MARK: - Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) let itemTocado = itens[indexPath.row] itemTocado.foiConcluido = !itemTocado.foiConcluido do { try itemTocado.managedObjectContext?.save() } catch _ { } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None) } // MARK: - Actions @IBAction func voltaParaLista(segue: UIStoryboardSegue!) { let sourceVC = segue.sourceViewController as! AdicionarItemViewController if let nomeDoItem = sourceVC.novoNomeParaItem { // itens.append(nomeDoItem) armazenarItem(nomeDoItem) tableView.reloadData() } } func armazenarItem(nome: String, concluido: Bool = false, criadoEm: NSDate = NSDate()) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let moc = appDelegate.managedObjectContext! let entity = NSEntityDescription.entityForName("Item", inManagedObjectContext: moc) let item = Item(entity: entity!, insertIntoManagedObjectContext: moc) item.nome = nome item.foiConcluido = concluido item.criadoEm = criadoEm var erro: NSError? do { try moc.save() } catch let error as NSError { erro = error print("Não foi possível armazenar. \(erro), \(erro?.userInfo)") } itens.append(item) } }
mit
3645d110b78ef1befc5f275439b70246
27.09375
129
0.596496
5.383234
false
false
false
false
phakphumi/Chula-Expo-iOS-Application
Chula Expo 2017/Chula Expo 2017/Modal_EventDetails/GalleryTableViewCell.swift
1
5057
// // GalleryTableViewCell.swift // Chula Expo 2017 // // Created by Pakpoom on 1/16/2560 BE. // Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved. // import UIKit extension UIView { var parentViewController: UIViewController? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.next if let viewController = parentResponder as? UIViewController { return viewController } } return nil } } class GalleryTableViewCell: UITableViewCell, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { @IBOutlet var galleryCollectionView: UICollectionView! @IBOutlet var galleryView: UIView! var images = [String]() /* @IBOutlet var image1: UIImageView! @IBOutlet var image2: UIImageView! @IBOutlet var image3: UIImageView! @IBOutlet var image4: UIImageView! @IBOutlet var image5: UIImageView! @IBOutlet var image6: UIImageView! */ /*private func setImageTag() { image1.tag = 0 image2.tag = 1 image3.tag = 2 image4.tag = 3 image5.tag = 4 image6.tag = 5 } private func clearImage() { for image in imageAlbum { image.image = nil } }*/ func wasTap() { let parentVC = self.parentViewController! if images.count > 0 { parentVC.performSegue(withIdentifier: "presentGallery", sender: parentVC) } else { let confirm = UIAlertController(title: "เกิดข้อผิดพลาด", message: "กิจกรรมนี้ไม่มีรูปภาพประกอบ", preferredStyle: UIAlertControllerStyle.alert) confirm.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.destructive, handler: nil)) parentVC.present(confirm, animated: true, completion: nil) } } override func awakeFromNib() { super.awakeFromNib() // Initialization code galleryCollectionView.delegate = self galleryCollectionView.dataSource = self // // let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() // let width = UIScreen.main.bounds.width // layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) // layout.itemSize = CGSize(width: width / 2, height: width / 2) // layout.minimumInteritemSpacing = 0 // layout.minimumLineSpacing = 0 // galleryCollectionView.collectionViewLayout = layout // let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(GalleryTableViewCell.wasTap)) // galleryCollectionView.addGestureRecognizer(tapGestureRecognizer) galleryCollectionView.isUserInteractionEnabled = true /* imageAlbum = [image1, image2, image3, image4, image5, image6] setImageTag() clearImage() */ } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as UICollectionViewCell // let view = cell.viewWithTag(0) as! UIImageView if let imageView = cell.viewWithTag(1) as? UIImageView { // let tapGestureRecognizer = UITapGestureRecognizer(target: imageView, action: #selector(GalleryTableViewCell.wasTap)) // imageView.addGestureRecognizer(tapGestureRecognizer) imageView.imageFromServerURL(urlString: images[indexPath.row]) cell.backgroundView = UIView() cell.backgroundView?.tag = indexPath.row } // let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(GalleryTableViewCell.wasTap)) // cell.addGestureRecognizer(tapGestureRecognizer) return cell } // func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // // return CGSize(width: UIScreen.main.bounds.width * 0.133333333, height: UIScreen.main.bounds.width * 0.133333333) // // } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
058158ce8d992accc8786a2e1a4c534f
29.703704
162
0.61158
5.319786
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Media/ImageCropViewController.swift
2
5524
import Foundation import WordPressShared import UIKit /// This ViewController allows the user to resize and crop any given UIImage. /// class ImageCropViewController: UIViewController, UIScrollViewDelegate { // MARK: - Public Properties /// Will be invoked with the cropped and scaled image and a boolean indicating /// whether or not the original image was modified @objc var onCompletion: ((UIImage, Bool) -> Void)? @objc var onCancel: (() -> Void)? @objc var maskShape: ImageCropOverlayMaskShape = .circle @objc var shouldShowCancelButton = false // MARK: - Public Initializers @objc convenience init(image: UIImage) { let nibName = ImageCropViewController.classNameWithoutNamespaces() self.init(nibName: nibName, bundle: nil) rawImage = image } // MARK: - UIViewController Methods override func viewDidLoad() { super.viewDidLoad() // Title title = NSLocalizedString("Resize & Crop", comment: "Screen title. Resize and crop an image.") view.backgroundColor = .basicBackground // Setup: NavigationItem let useButtonTitle = NSLocalizedString("Use", comment: "Use the current image") navigationItem.rightBarButtonItem = UIBarButtonItem(title: useButtonTitle, style: .plain, target: self, action: #selector(cropWasPressed)) if shouldShowCancelButton { let cancelButtonTitle = NSLocalizedString("Cancel", comment: "Cancel the crop") navigationItem.leftBarButtonItem = UIBarButtonItem(title: cancelButtonTitle, style: .plain, target: self, action: #selector(cancelWasPressed)) } // Setup: ImageView imageView.image = rawImage // Setup: ScrollView let minimumScale = max(scrollView.frame.width / rawImage.size.width, scrollView.frame.height / rawImage.size.height) scrollView.minimumZoomScale = minimumScale scrollView.maximumZoomScale = minimumScale * maximumScaleFactor scrollView.zoomScale = minimumScale // Setup: Overlay overlayView.borderColor = .primary(.shade40) overlayView.outerColor = overlayColor overlayView.maskShape = maskShape } // MARK: - UIScrollViewDelegate Methods func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { // NO-OP: // Required to enable scrollView Zooming } // MARK: - Action Handlers @IBAction func cropWasPressed() { // Calculations! let screenScale = UIScreen.main.scale let zoomScale = scrollView.zoomScale let oldSize = rawImage.size let resizeRect = CGRect(x: 0, y: 0, width: oldSize.width * zoomScale, height: oldSize.height * zoomScale) let clippingRect = CGRect(x: scrollView.contentOffset.x * screenScale, y: scrollView.contentOffset.y * screenScale, width: scrollView.frame.width * screenScale, height: scrollView.frame.height * screenScale) if scrollView.contentOffset.x == 0 && scrollView.contentOffset.y == 0 && oldSize.width == clippingRect.width && oldSize.height == clippingRect.height { onCompletion?(rawImage, false) return } // Resize UIGraphicsBeginImageContextWithOptions(resizeRect.size, false, screenScale) rawImage?.draw(in: resizeRect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // Crop guard let clippedImageRef = scaledImage!.cgImage!.cropping(to: clippingRect.integral) else { return } let clippedImage = UIImage(cgImage: clippedImageRef, scale: screenScale, orientation: .up) onCompletion?(clippedImage, true) } @IBAction func cancelWasPressed() { onCancel?() } private let overlayColor = UIColor.basicBackground.withAlphaComponent(0.78) // MARK: - Private Constants private let maximumScaleFactor = CGFloat(3) // MARK: - Private Properties private var rawImage: UIImage! // MARK: - IBOutlets @IBOutlet private var scrollView: UIScrollView! { didSet { scrollView.backgroundColor = .basicBackground } } @IBOutlet private var imageView: UIImageView! @IBOutlet private var overlayView: ImageCropOverlayView! @IBOutlet private var topView: UIView! { didSet { topView.backgroundColor = overlayColor } } @IBOutlet private var bottomView: UIView! { didSet { bottomView.backgroundColor = overlayColor } } @IBOutlet private var rightView: UIView! { didSet { rightView.backgroundColor = overlayColor } } @IBOutlet private var leftView: UIView! { didSet { leftView.backgroundColor = overlayColor } } }
gpl-2.0
bf0a199b69d0729be47a8726e8b9e6e8
34.87013
124
0.602462
5.784293
false
false
false
false
Raizlabs/FreshAir
Breeze/Conditions.swift
1
2393
// // Conditions.swift // FreshAir // // Created by Brian King on 2/3/16. // Copyright © 2016 Raizlabs. All rights reserved. // import Foundation import FreshAirUtility typealias DetectCondition = (String) -> RZFCondition? extension Platform { func localeCondition(path: String) -> RZFCondition? { let nsPath = path as NSString if let dir = nsPath.componentsSeparatedByString("/").first { switch self { case .Apple: let splitDir = dir.componentsSeparatedByString(".") if splitDir.count == 2 && splitDir[1] == "lproj" { return RZFCondition(key: "locale", comparison: "eq", value: splitDir[0]) } case .Android: let splitDir = dir.componentsSeparatedByString("-") if splitDir.count > 2 && splitDir[0] == "drawable" && NSLocale.availableLocaleIdentifiers().contains(splitDir[1]) { return RZFCondition(key: "locale", comparison: "eq", value: splitDir[1]) } } } return nil } func resolutionCondition() throws -> DetectCondition { switch self { case .Apple: return AppleResolution.resolutionCondition case .Android: throw ExpansionError.AndroidUnsupported } } func deviceCondition() throws -> DetectCondition { switch self { case .Apple: return AppleDevice.deviceCondition case .Android: throw ExpansionError.AndroidUnsupported } } } extension AppleResolution { static func resolutionCondition(path: String) -> RZFCondition? { for key in ["1", "2", "3"] { if path.containsString("@\(key)x") { // RZFEnvironmentDisplayScaleKey isn't linking >< return RZFCondition(key: "displayScale", comparison: "eq", value: key) } } return nil; } } extension AppleDevice { static func deviceCondition(path: String) -> RZFCondition? { for key in ["ipad", "iphone"] { if path.containsString("~\(key).") { // RZFEnvironmentDeviceKey isn't linking >< return RZFCondition(key: "device", comparison: "eq", value: key) } } return nil; } }
mit
5c82412abd5b48d5fba283fe30fe6b5f
30.077922
96
0.556856
4.699411
false
false
false
false