repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Vluxe/AnimationSeries
login/libs/Jazz/LoadingView.swift
1
5845
// // LoadingView.swift // // Created by Dalton Cherry on 3/11/15. // Copyright (c) 2015 Vluxe. All rights reserved. // import UIKit public class LoadingView: UIView, AnimationProtocol { public var lineWidth: CGFloat = 0.0 //the width of the ring public var color: UIColor? //the color of the ring public var progress: CGFloat = 0.0 //the progress of the loading. This can be between 0 and 1 public var shapeLayer: CAShapeLayer! //the layer that represents the view's shape layer public var clockwise = true //if the loading should go clockwise or counterclockwise private var point:CGFloat = 0 public var startPoint: CGFloat { set{ point = newValue Jazz.rotateView(self, degrees: newValue) } get{return point} } private var stopped = false private let startKey = "startKey" private let endKey = "endKey" override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } //setup the properties func commonInit() { self.userInteractionEnabled = false self.startPoint = 270 self.shapeLayer = self.layer as CAShapeLayer self.backgroundColor = UIColor.clearColor() } //start the loading animation public func start(speed: Double = 1.2) { //drawPath() runLoading(speed) } //run the loading animation private func runLoading(speed: Double) { shapeLayer.removeAnimationForKey(startKey) shapeLayer.removeAnimationForKey(endKey) if stopped { stopped = false self.progress = 0 drawPath() return } var startAnim = Jazz.createAnimation(speed, delay: speed/1.7, type: .EaseInOut, key: "strokeStart") startAnim.fromValue = self.shapeLayer.strokeStart startAnim.toValue = 1 var animation = Jazz.createAnimation(speed, delay: 0, type: .EaseInOut, key: "strokeEnd") animation.fromValue = self.progress animation.toValue = 1 CATransaction.begin() CATransaction.setCompletionBlock { self.shapeLayer.strokeEnd = 1 self.progress = 0 self.start(speed: speed) } shapeLayer.addAnimation(startAnim, forKey: startKey) shapeLayer.addAnimation(animation, forKey: endKey) CATransaction.commit() } //stop the loading public func stop() { stopped = true } //animate the progress public func animateProgress(speed: Double = 1.2,progress: CGFloat) { var animation = Jazz.createAnimation(speed, delay: 0, type: .EaseInOut, key: "strokeEnd") animation.fromValue = self.progress animation.toValue = progress CATransaction.begin() CATransaction.setCompletionBlock { self.progress = progress self.shapeLayer.removeAnimationForKey(self.endKey) self.drawPath() } shapeLayer.addAnimation(animation, forKey: endKey) CATransaction.commit() } //implement the animations public func doAnimations(duration: Double, delay: Double, type: CurveType) { var animation = Jazz.createAnimation(duration, delay: delay, type: type, key: "path") animation.fromValue = shapeLayer.path animation.toValue = buildPath(self.bounds, width: self.lineWidth, progress: self.progress).CGPath shapeLayer.addAnimation(animation, forKey: Jazz.oneShotKey()) var bColor = Jazz.createAnimation(duration, delay: delay, type: type, key: "fillColor") bColor.fromValue = shapeLayer.fillColor bColor.toValue = self.color?.CGColor shapeLayer.addAnimation(bColor, forKey: Jazz.oneShotKey()) var bWidth = Jazz.createAnimation(duration, delay: delay, type: type, key: "lineWidth") bWidth.fromValue = shapeLayer.lineWidth bWidth.toValue = self.lineWidth shapeLayer.addAnimation(bWidth, forKey: Jazz.oneShotKey()) } //finished the animation and set the shape into its final state public func finishAnimation(Void) { drawPath() let keys = self.shapeLayer.animationKeys() for key in keys { if let k = key as? String { if k.hasPrefix(Jazz.animPrefix()) { self.shapeLayer.removeAnimationForKey(k) } } } } //creates the shapes path func buildPath(rect: CGRect, width: CGFloat, progress: CGFloat) -> UIBezierPath { var pro = progress if pro > 1 { pro = 1 } else if pro < 0 { pro = 0 } let pad: CGFloat = 1 var fr = rect fr.size.width = floor(rect.size.width-(pad*2)) fr.size.height = floor(rect.size.height-(pad*2)) fr.origin.x = pad fr.origin.y = pad var path = UIBezierPath(ovalInRect: fr) shapeLayer.strokeEnd = pro return path } //update the shape from the properties func drawPath() { shapeLayer.lineCap = kCALineCapRound shapeLayer.fillColor = UIColor.clearColor().CGColor shapeLayer.strokeColor = self.color?.CGColor shapeLayer.lineWidth = self.lineWidth shapeLayer.path = buildPath(self.bounds, width: self.lineWidth, progress: self.progress).CGPath } //draw the path public override func drawRect(rect: CGRect) { super.drawRect(rect) drawPath() } //set the layer of this view to be a shape public override class func layerClass() -> AnyClass { return CAShapeLayer.self } }
apache-2.0
c9985120a55d715b3d2aefabcee7f1a0
33.187135
107
0.620017
4.683494
false
false
false
false
liuchuo/Book-sales-management-system
BSMS2/BSMS2/ViewController.swift
1
10352
// // ViewController.swift // BSMS2 // // Created by ChenXin on 16/4/28. // Copyright © 2016年 ChenXin. All rights reserved. // import UIKit //bookcells means the information of books in top7 chart var bookcells: [myModel] = [] //bookshoppingcart means the information of books in shopping cart var bookShoppingCart: [myModel] = [] class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! // MARK:- Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. bookcells = [ myModel(id: "1", image: "se", rank: "Top1:", title: "《软件工程》", intro: "机械工业出版社/69.00元", price: 69, descriptions: "----------内容简介:----------\n本书第7版包含了很多新的内容,而且调整了全书的结构,以改进教学顺序,同时更加强调一些新的、重要的软件工程过程和软件工程实践知识。全书分软件过程、建模、质量管理、软件项目管理和软件工程高级课题五个部分,系统地论述了软件工程领域最新的基础知识,包括新的概念、原则、技术、方法和工具,同时提供了大量供读者进一步研究探索的参考信息。 本书适合作为本科生和研究生的软件工程及相关课程的教材,新版中五个部分的划分有利于教师根据学时和教学要求安排教学,同时也适合作为软件专业人员的工作指南,即使是资深专业人员,阅读本书也能获益匪浅。"), myModel(id: "2", image: "linux", rank: "Top2:", title: "《鸟哥的Linux私房菜》", intro: "人民邮电出版社/88.00元", price: 88, descriptions: "----------内容简介:----------\n本书是全面而详细地介绍了Linux操作系统。全书分为5个部分:第一部分着重说明Linux的起源及功能,如何规划和安装Linux主机;第二部分介绍Linux的文件系统、文件、目录与磁盘的管理;第三部分介绍文字模式接口 shell和管理系统的好帮手shell脚本,另外还介绍了文字编辑器vi和vim的使用方法;第四部分介绍了对于系统安全非常重要的Linux账号的管理,以及主机系统与程序的管理,如查看进程、任务分配和作业管理;第五部分介绍了系统管理员(root)的管理事项,如了解系统运行状况、系统服务,针对登录文件进行解析,对系统进行备份以及核心的管理等。"), myModel(id: "3", image: "algorithm", rank: "Top3:", title: "《算法导论》", intro: "机械工业出版社/128.00元", price: 128, descriptions: "----------内容简介:----------\n在有关算法的书中,有一些叙述非常严谨,但不够全面;另一些涉及了大量的题材,但又缺乏严谨性。本书将严谨性和全面性融为一体,深入讨论各类算法,并着力使这些算法的设计和分析能为各个层次的读者接受。全书各章自成体系,可以作为独立的学习单元;算法以英语和伪代码的形式描述,具备初步程序设计经验的人就能看懂;说明和解释力求浅显易懂,不失深度和数学严谨性。\n全书选材经典、内容丰富、结构合理、逻辑清晰,对本科生的数据结构课程和研究生的算法课程都是非常实用的教材,在IT专业人员的职业生涯中,本书也是一本案头必备的参考书或工程实践手册。"), myModel(id: "4", image: "html", rank: "Top4:", title: "《深入浅出HTML与CSS、XHTML》", intro: "东南大学出版社/98.00元", price: 98, descriptions: "----------内容简介:----------\n《深入浅出HTML与CSS XHTML》(影印版)能让你避免认为Web-safe颜色还是紧要问题的尴尬,以及不明智地把标记放入你的页面。最大的好处是,你将毫无睡意地学习HTML、XHTML 和CSS。如果你曾经读过深入浅出(Head First)系列图书中的任一本,就会知道书中展现的是什么:一个按人脑思维方式设计的丰富的可视化学习模式。《深入浅出HTML与CSS XHTML》的编写采用了许多最新的研究,包括神经生物学、认知科学以及学习理论,这使得《深入浅出HTML与CSS XHTML》能让HTML和CSS深深地烙印在你的脑海里。"), myModel(id: "5", image: "java", rank: "Top5:", title: "《Java核心技术·卷1:基础知识》", intro: "机械工业出版社/88.00元",price: 88, descriptions: "----------内容简介:----------\n《Java核心技术·卷1:基础知识》共14章。第1章概述了Java语言与其他程序设计语言不同的性能;第2章讲解了如何下载和安装JDK及本书的程序示例;第3章介绍了变量、循环和简单的函数;第4章讲解了类和封装;第5章介绍了继承;第6章解释了接口和内部类;第7章概述了图形用户界面程序设计知识;第8章讨论AWT的事件模型;第9章探讨了SwingGUI工具箱;第10章讲解如何部署自己的应用程序或applet;第11章讨论异常处理;第12章概要介绍泛型程序设计;第13章讲解Java平台的集合框架;第14章介绍了多线程。本书最后还有一个附录,其中列出了Java语言的保留字。"), myModel(id: "6", image: "ios", rank: "Top6:", title: "《Hacking and Securing iOS Applications》", intro: "McGraw-Hill Osborne Media/98.00元",price: 98, descriptions: "----------内容简介:----------\nBased on unique and previously undocumented research, this book by noted iOS expert Jonathan Zdziarski shows the numerous weaknesses that exist in typical iPhone and iPad apps. Zdziarski shows finance companies, large institutions and others where the exploitable flaws lie in their code, and in this book he will show you as well, in a clear, direct, and immediately applicable style. More importantly. Topics cover manipulating the Objective-C runtime, debugger abuse, hijacking network traffic, testing and class validation, jailbreak detection, and much more."), myModel(id: "7", image: "oc", rank: "Top7:", title: "《Programming in Objective-C》", intro: "Addison-Wesley Professional/70.00元", price: 70, descriptions: "----------内容简介:----------\nUpdated for OS X 10.9 Mavericks, iOS 7, and Xcode 5 Programming in Objective-C is a concise, carefully written tutorial on the basics of Objective-C and object-oriented programming for Apple's iOS and OS X platforms. The book makes no assumptions about prior experience with object-oriented programming languages or with the C language. Because of this, both beginners and experienced programmers alike can use this book to quickly and effectively learn the fundamentals of Objective-C.") ] //the left bar button item of navigation self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "本月图书销量排行榜:",style: .plain ,target: self, action: nil) //the right bar button item of navigation self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "查看购物车",style: .plain ,target: self, action: #selector(callMe)) } //show in shopping cart - jump to the shoppingcartviewcontroller @objc fileprivate func callMe() { let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "shoppingCart") vc.navigationItem.title = self.navigationItem.rightBarButtonItem?.title self.navigationController?.pushViewController(vc, animated: true) } // MARK: - table view data source internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bookcells.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let book : myModel = bookcells[indexPath.row] bookShoppingCart.append(book) let titleaddprice : String = book.title + " \(book.price).00元" let alertView : UIAlertController = UIAlertController(title: "~~您已成功加入购物车耶耶~~", message: titleaddprice, preferredStyle: .alert) let okaction : UIAlertAction = UIAlertAction(title: "嗯,本宝宝知道了~", style: .default, handler: nil) alertView.addAction(okaction) self .present(alertView, animated: true, completion: nil) } internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "bookcells")! as UITableViewCell let bookcell = bookcells[indexPath.row] as myModel let image = cell.viewWithTag(101) as! UIImageView let rank = cell.viewWithTag(102) as! UILabel let title = cell.viewWithTag(103) as! UILabel let intro = cell.viewWithTag(104) as! UILabel image.image = UIImage(named: bookcell.image) rank.text = bookcell.rank title.text = bookcell.title intro.text = bookcell.intro return cell } //MARK: - tableView deleagte func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let book : myModel = bookcells[indexPath.row] let detalVc : DetailViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController detalVc.book = book self.navigationController?.pushViewController(detalVc, animated: true) } // override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // // let cell : UITableViewCell = sender as! UITableViewCell // let index : NSIndexPath = self.tableView.indexPathForCell(cell)! // let book : myModel = bookcells[index.row] // // let detailVc : DetailViewController = segue.destinationViewController as! DetailViewController // detailVc.book = book // // } }
gpl-3.0
52832ba8f597c846276a4284730a2aea
63.89916
770
0.704648
3.000389
false
false
false
false
apple/swift-driver
Sources/SwiftDriver/Driver/LinkKind.swift
1
1034
//===--------------- LinkKind.swift - Swift Linking Kind ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// /// Describes the kind of linker output we expect to produce. public enum LinkOutputType { /// An executable file. case executable /// A shared library (e.g., .dylib or .so) case dynamicLibrary /// A static library (e.g., .a or .lib) case staticLibrary } /// Describes the kind of link-time-optimization we expect to perform. public enum LTOKind: String, Hashable, CaseIterable { /// Perform LLVM ThinLTO. case llvmThin = "llvm-thin" /// Perform LLVM full LTO. case llvmFull = "llvm-full" }
apache-2.0
0a8fc22e2281e0e9e0530be429a35a52
32.354839
80
0.630561
4.290456
false
false
false
false
PSSWD/psswd-ios
psswd/Fields.swift
1
1265
// // Fields.swift // psswd // // Created by Daniil on 11.01.15. // Copyright (c) 2015 kirick. All rights reserved. // class Fields { struct classVar { static var defaultFields: [String: AnyObject] = [:] } class func uniteFields(srv_fields: [[String: AnyObject]], data_fields: [[String: AnyObject]]) -> [[String: AnyObject]] { var _fields: [[String: AnyObject]] = [] for v in srv_fields { var _v = v let v_type = v["type"] as! String if "_" != Array(v_type)[0] { var def = classVar.defaultFields[v_type] as! [String: AnyObject] for (k2, v2) in v { def[k2] = v2 } _v = def } var existsFields = getByType(data_fields, type: v_type) if (nil != existsFields && v["editable"] as? Bool != false) { _v["value"] = existsFields!["value"] } _v["default"] = true _fields.append(_v) } for v in data_fields { if nil == getByType(_fields, type: v["type"] as! String) { _fields.append(v) } } return _fields } class func getByType(list: [ [String: AnyObject] ], type: String) -> [String: AnyObject]? { var _field: [String: AnyObject]? = nil for v in list { if v["type"] as! String == type { _field = v break } } return _field } }
gpl-2.0
79e6fd24766d2e4e99c85ebe95e9df0c
17.880597
119
0.565217
2.786344
false
false
false
false
4jchc/4jchc-BaiSiBuDeJie
4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Me-我/View/XMGSqaureButton.swift
1
1762
// // XMGSqaureself.swift // 4jchc-BaiSiBuDeJie // // Created by 蒋进 on 16/3/3. // Copyright © 2016年 蒋进. All rights reserved. // import UIKit class XMGSqaureButton: UIButton { func setup(){ self.titleLabel!.textAlignment = NSTextAlignment.Center; self.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) self.titleLabel?.font = UIFont.systemFontOfSize(15) self.setBackgroundImage(UIImage(named: "mainCellBackground"), forState: .Normal) } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { setup() } override func layoutSubviews() { super.layoutSubviews() // 调整图片 self.imageView!.y = self.height * 0.15; self.imageView!.width = self.width * 0.5; self.imageView!.height = self.imageView!.width; self.imageView!.centerX = self.width * 0.5; // 调整文字 self.titleLabel!.x = 0; self.titleLabel!.y = CGRectGetMaxY(self.imageView!.frame); self.titleLabel!.width = self.width; self.titleLabel!.height = self.height - self.titleLabel!.y; } // 通过模型赋值 var square:XMGSquare?{ didSet{ self.setTitle(square?.name, forState: .Normal) // 利用SDWebImage给按钮设置image self.sd_setImageWithURL(NSURL(string: square!.icon!), forState: .Normal) } } }
apache-2.0
6781d8676de8711d60ee7f9a1d1b1364
24.132353
88
0.571679
4.304786
false
false
false
false
martinschilliger/SwissGrid
Pods/Alamofire/Source/ServerTrustPolicy.swift
2
14068
// // ServerTrustPolicy.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. open class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. open let policies: [String: ServerTrustPolicy] /// Initializes the `ServerTrustPolicyManager` instance with the given policies. /// /// Since different servers and web services can have different leaf certificates, intermediate and even root /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key /// pinning for host3 and disabling evaluation for host4. /// /// - parameter policies: A dictionary of all policies mapped to a particular host. /// /// - returns: The new `ServerTrustPolicyManager` instance. public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /// Returns the `ServerTrustPolicy` for the given host if applicable. /// /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override /// this method and implement more complex mapping implementations such as wildcards. /// /// - parameter host: The host to use when searching for a matching policy. /// /// - returns: The server trust policy for the given host if found. open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension URLSession { private struct AssociatedKeys { static var managerKey = "URLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager } set(manager) { objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - ServerTrustPolicy /// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when /// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust /// with a given set of criteria to determine whether the server trust is valid and the connection should be made. /// /// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other /// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged /// to route all communication over an HTTPS connection with pinning enabled. /// /// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to /// validate the host provided by the challenge. Applications are encouraged to always /// validate the host in production environments to guarantee the validity of the server's /// certificate chain. /// /// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to /// validate the host provided by the challenge as well as specify the revocation flags for /// testing for revoked certificates. Apple platforms did not start testing for revoked /// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is /// demonstrated in our TLS tests. Applications are encouraged to always validate the host /// in production environments to guarantee the validity of the server's certificate chain. /// /// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is /// considered valid if one of the pinned certificates match one of the server certificates. /// By validating both the certificate chain and host, certificate pinning provides a very /// secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate /// chain in production environments. /// /// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered /// valid if one of the pinned public keys match one of the server certificate public keys. /// By validating both the certificate chain and host, public key pinning provides a very /// secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate /// chain in production environments. /// /// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. /// /// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. public enum ServerTrustPolicy { case performDefaultEvaluation(validateHost: Bool) case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case disableEvaluation case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) // MARK: - Bundle Location /// Returns all certificates within the given bundle with a `.cer` file extension. /// /// - parameter bundle: The bundle to search for all `.cer` files. /// /// - returns: All certificates within the given bundle. public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { var certificates: [SecCertificate] = [] let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) }.joined()) for path in paths { if let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, let certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } } return certificates } /// Returns all public keys within the given bundle with a `.cer` file extension. /// /// - parameter bundle: The bundle to search for all `*.cer` files. /// /// - returns: All public keys within the given bundle. public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificates(in: bundle) { if let publicKey = publicKey(for: certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /// Evaluates whether the server trust is valid for the given host. /// /// - parameter serverTrust: The server trust to evaluate. /// - parameter host: The host of the challenge protection space. /// /// - returns: Whether the server trust is valid. public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .performDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) serverTrustIsValid = trustIsValid(serverTrust) case let .performRevokedEvaluation(validateHost, revocationFlags): let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) serverTrustIsValid = trustIsValid(serverTrust) case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateData(for: serverTrust) let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData == pinnedCertificateData { serverTrustIsValid = true break outerLoop } } } } case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .disableEvaluation: serverTrustIsValid = true case let .customEvaluation(closure): serverTrustIsValid = closure(serverTrust, host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(_ trust: SecTrust) -> Bool { var isValid = false var result = SecTrustResultType.invalid let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { let unspecified = SecTrustResultType.unspecified let proceed = SecTrustResultType.proceed isValid = result == unspecified || result == proceed } return isValid } // MARK: - Private - Certificate Data private func certificateData(for trust: SecTrust) -> [Data] { var certificates: [SecCertificate] = [] for index in 0 ..< SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index) { certificates.append(certificate) } } return certificateData(for: certificates) } private func certificateData(for certificates: [SecCertificate]) -> [Data] { return certificates.map { SecCertificateCopyData($0) as Data } } // MARK: - Private - Public Key Extraction private static func publicKeys(for trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0 ..< SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index), let publicKey = publicKey(for: certificate) { publicKeys.append(publicKey) } } return publicKeys } private static func publicKey(for certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust, trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } }
mit
c4427670b0b20827a50bd27087584ee5
45.276316
120
0.656881
5.801237
false
false
false
false
huangboju/Moots
UICollectionViewLayout/MagazineLayout-master/Tests/ModelStateEmptySectionLayoutTests.swift
1
4940
// Created by bryankeller on 11/13/18. // Copyright © 2018 Airbnb, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 MagazineLayout final class ModelStateEmptySectionLayoutTests: XCTestCase { // MARK: Internal override func setUp() { modelState = ModelState(currentVisibleBoundsProvider: { return .zero }) } override func tearDown() { modelState = nil } func testEmptySectionsLayout() { var metrics0 = MagazineLayoutSectionMetrics.defaultSectionMetrics(forCollectionViewWidth: 320) metrics0.sectionInsets = .zero metrics0.itemInsets = UIEdgeInsets(top: 10, left: 0, bottom: 20, right: 0) var metrics1 = MagazineLayoutSectionMetrics.defaultSectionMetrics(forCollectionViewWidth: 320) metrics1.sectionInsets = UIEdgeInsets(top: -25, left: 0, bottom: 20, right: 10) metrics1.itemInsets = UIEdgeInsets(top: 50, left: 0, bottom: 100, right: 0) let initialSections = [ SectionModel( itemModels: [], headerModel: nil, footerModel: nil, backgroundModel: nil, metrics: metrics0), SectionModel( itemModels: [], headerModel: nil, footerModel: nil, backgroundModel: nil, metrics: metrics1), ] modelState.setSections(initialSections) let expectedHeightOfSection0 = metrics0.sectionInsets.top + metrics0.sectionInsets.bottom let expectedHeightOfSection1 = metrics1.sectionInsets.top + metrics1.sectionInsets.bottom XCTAssert( (modelState.sectionMaxY(forSectionAtIndex: 0, .afterUpdates) == expectedHeightOfSection0 && modelState.sectionMaxY(forSectionAtIndex: 1, .afterUpdates) == expectedHeightOfSection1), "The layout has incorrect heights for its sections") } func testEmptySectionsWithHeadersFootersAndBackgroundsLayout() { var metrics0 = MagazineLayoutSectionMetrics.defaultSectionMetrics(forCollectionViewWidth: 320) metrics0.sectionInsets = UIEdgeInsets(top: 10, left: 5, bottom: 20, right: 5) metrics0.itemInsets = UIEdgeInsets(top: 10, left: 10, bottom: 20, right: 10) var metrics1 = MagazineLayoutSectionMetrics.defaultSectionMetrics(forCollectionViewWidth: 320) metrics1.sectionInsets = .zero metrics1.itemInsets = UIEdgeInsets(top: 50, left: 10, bottom: 100, right: 10) let initialSections = [ SectionModel( itemModels: [], headerModel: HeaderModel( heightMode: .static(height: 45), height: 45, pinToVisibleBounds: false), footerModel: FooterModel( heightMode: .static(height: 45), height: 45, pinToVisibleBounds: false), backgroundModel: BackgroundModel(), metrics: metrics0), SectionModel( itemModels: [], headerModel: HeaderModel( heightMode: .static(height: 65), height: 65, pinToVisibleBounds: false), footerModel: FooterModel( heightMode: .static(height: 65), height: 65, pinToVisibleBounds: false), backgroundModel: BackgroundModel(), metrics: metrics1), ] modelState.setSections(initialSections) let expectedHeaderFrames = [ CGRect(x: 5, y: 10, width: 310, height: 45), CGRect(x: 0, y: 120, width: 320, height: 65), ] XCTAssert( FrameHelpers.expectedFrames( expectedHeaderFrames, matchHeaderFramesInSectionIndexRange: 0..<modelState.numberOfSections(.afterUpdates), modelState: modelState), "Header frames are incorrect") let expectedFooterFrames = [ CGRect(x: 5, y: 55, width: 310, height: 45), CGRect(x: 0, y: 185, width: 320, height: 65) ] XCTAssert( FrameHelpers.expectedFrames( expectedFooterFrames, matchFooterFramesInSectionIndexRange: 0..<modelState.numberOfSections(.afterUpdates), modelState: modelState), "Footer frames are incorrect") let expectedBackgroundFrames = [ CGRect(x: 5, y: 10, width: 310, height: 90), CGRect(x: 0, y: 120, width: 320, height: 130), ] XCTAssert( FrameHelpers.expectedFrames( expectedBackgroundFrames, matchBackgroundFramesInSectionIndexRange: 0..<modelState.numberOfSections(.afterUpdates), modelState: modelState), "Background frames are incorrect") } // MARK: Private private var modelState: ModelState! }
mit
e9510c2908369be61d9746c9ac8f1150
34.028369
98
0.684147
4.386323
false
false
false
false
or9/iOS-Tutorials
food-tracker-tutorial/MealTableViewController.swift
1
5591
import UIKit class MealTableViewController: UITableViewController { // MARK: Properties var meals = [Meal]() override func viewDidLoad() { super.viewDidLoad() // Use edit button provided by table view controller navigationItem.leftBarButtonItem = editButtonItem() if let savedMeals = loadMeals() { meals += savedMeals } else { loadSampleMeals() } } func loadSampleMeals () { let photo1 = UIImage(named: "finn")! let meal1 = Meal(name: "Finn The Human", photo: photo1, rating: 4)! let photo2 = UIImage(named: "jake")! let meal2 = Meal(name: "Jake the Spider", photo: photo2, rating: 3)! let photo3 = UIImage(named: "marcelene")! let meal3 = Meal(name: "Marcelene", photo: photo3, rating: 5)! meals += [meal1, meal2, meal3] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Table view cells are reused and should be dequeued using a cell identifier let cellIdentifier = "MealTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MealTableViewCell let meal = meals[indexPath.row] // Configure the cell cell.nameLabel.text = meal.name cell.photoImageView.image = meal.photo cell.ratingControl.rating = meal.rating return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source meals.removeAtIndex(indexPath.row) saveMeals() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // 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?) { if segue.identifier == "ShowDetail" { let mealDetailViewController = segue.destinationViewController as! MealViewController if let selectedMealCell = sender as? MealTableViewCell { let indexPath = tableView.indexPathForCell(selectedMealCell)! let selectedMeal = meals[indexPath.row] mealDetailViewController.meal = selectedMeal } } else if segue.identifier == "AddItem" { print("Adding new meal…") } } @IBAction func unwindMealList (sender: UIStoryboardSegue) { if let sourceViewController = sender.sourceViewController as? MealViewController, meal = sourceViewController.meal { if let selectedIndexPath = tableView.indexPathForSelectedRow { meals[selectedIndexPath.row] = meal tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) } else { let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0) meals.append(meal) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) } saveMeals() } } // MARK: NSCoding func saveMeals() { let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path!) if !isSuccessfulSave { print("save failed!") } } func loadMeals() -> [Meal]? { // May return array of meals or nothing (nil) // use as? so it can return nil when appropriate return NSKeyedUnarchiver.unarchiveObjectWithFile(Meal.ArchiveURL.path!) as? [Meal] } }
mit
bbe549b1723630af70502df1d254fee3
32.668675
157
0.614421
5.662614
false
false
false
false
Jnosh/swift
stdlib/public/SDK/Foundation/PlistEncoder.swift
2
70555
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Plist Encoder //===----------------------------------------------------------------------===// /// `PropertyListEncoder` facilitates the encoding of `Encodable` values into property lists. open class PropertyListEncoder { // MARK: - Options /// The output format to write the property list data in. Defaults to `.binary`. open var outputFormat: PropertyListSerialization.PropertyListFormat = .binary /// Contextual user-provided information for use during encoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the encoding hierarchy. fileprivate struct _Options { let outputFormat: PropertyListSerialization.PropertyListFormat let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level encoder. fileprivate var options: _Options { return _Options(outputFormat: outputFormat, userInfo: userInfo) } // MARK: - Constructing a Property List Encoder /// Initializes `self` with default strategies. public init() {} // MARK: - Encoding Values /// Encodes the given top-level value and returns its property list representation. /// /// - parameter value: The value to encode. /// - returns: A new `Data` value containing the encoded property list data. /// - throws: `EncodingError.invalidValue` if a non-comforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`. /// - throws: An error if any value throws an error during encoding. open func encode<Value : Encodable>(_ value: Value) throws -> Data { let encoder = _PlistEncoder(options: self.options) try value.encode(to: encoder) guard encoder.storage.count > 0 else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(Value.self) did not encode any values.")) } let topLevel = encoder.storage.popContainer() if topLevel is NSNumber { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(Value.self) encoded as number property list fragment.")) } else if topLevel is NSString { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(Value.self) encoded as string property list fragment.")) } else if topLevel is NSDate { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(Value.self) encoded as date property list fragment.")) } return try PropertyListSerialization.data(fromPropertyList: topLevel, format: self.outputFormat, options: 0) } } // MARK: - _PlistEncoder fileprivate class _PlistEncoder : Encoder { // MARK: Properties /// The encoder's storage. var storage: _PlistEncodingStorage /// Options set on the top-level encoder. let options: PropertyListEncoder._Options /// The path to the current point in encoding. var codingPath: [CodingKey?] /// Contextual user-provided information for use during encoding. var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level encoder options. init(options: PropertyListEncoder._Options, codingPath: [CodingKey?] = []) { self.options = options self.storage = _PlistEncodingStorage() self.codingPath = codingPath } // MARK: - Coding Path Operations /// Performs the given closure with the given key pushed onto the end of the current coding path. /// /// - parameter key: The key to push. May be nil for unkeyed containers. /// - parameter work: The work to perform with the key in the path. func with<T>(pushedKey key: CodingKey?, _ work: () throws -> T) rethrows -> T { self.codingPath.append(key) let ret: T = try work() self.codingPath.removeLast() return ret } /// Returns whether a new element can be encoded at this coding path. /// /// `true` if an element has not yet been encoded at this coding path; `false` otherwise. var canEncodeNewElement: Bool { // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container). // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition. // // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here). return self.storage.count == self.codingPath.count } /// Asserts that a new container can be requested at this coding path. /// `preconditionFailure()`s if one cannot be requested. func assertCanRequestNewContainer() { guard self.canEncodeNewElement else { let previousContainerType: String if self.storage.containers.last is NSDictionary { previousContainerType = "keyed" } else if self.storage.containers.last is NSArray { previousContainerType = "unkeyed" } else { previousContainerType = "single value" } preconditionFailure("Attempt to encode with new container when already encoded with \(previousContainerType) container.") } } // MARK: - Encoder Methods func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> { assertCanRequestNewContainer() let topContainer = self.storage.pushKeyedContainer() let container = _PlistKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer) return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { assertCanRequestNewContainer() let topContainer = self.storage.pushUnkeyedContainer() return _PlistUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer) } func singleValueContainer() -> SingleValueEncodingContainer { assertCanRequestNewContainer() return self } } // MARK: - Encoding Storage and Containers fileprivate struct _PlistEncodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the plist types (NSNumber, NSString, NSDate, NSArray, NSDictionary). private(set) var containers: [NSObject] = [] // MARK: - Initialization /// Initializes `self` with no containers. init() {} // MARK: - Modifying the Stack var count: Int { return self.containers.count } mutating func pushKeyedContainer() -> NSMutableDictionary { let dictionary = NSMutableDictionary() self.containers.append(dictionary) return dictionary } mutating func pushUnkeyedContainer() -> NSMutableArray { let array = NSMutableArray() self.containers.append(array) return array } mutating func push(container: NSObject) { self.containers.append(container) } mutating func popContainer() -> NSObject { precondition(self.containers.count > 0, "Empty container stack.") return self.containers.popLast()! } } // MARK: - Encoding Containers fileprivate struct _PlistKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the encoder we're writing to. let encoder: _PlistEncoder /// A reference to the container we're writing to. let container: NSMutableDictionary /// The path of coding keys taken to get to this point in encoding. var codingPath: [CodingKey?] // MARK: - Initialization /// Initializes `self` with the given references. init(referencing encoder: _PlistEncoder, codingPath: [CodingKey?], wrapping container: NSMutableDictionary) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - Coding Path Operations /// Performs the given closure with the given key pushed onto the end of the current coding path. /// /// - parameter key: The key to push. May be nil for unkeyed containers. /// - parameter work: The work to perform with the key in the path. mutating func with<T>(pushedKey key: CodingKey?, _ work: () throws -> T) rethrows -> T { self.codingPath.append(key) let ret: T = try work() self.codingPath.removeLast() return ret } // MARK: - KeyedEncodingContainerProtocol Methods mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: Int, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: String, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: Float, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode(_ value: Double, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) } mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws { try self.encoder.with(pushedKey: key) { self.container[key.stringValue] = try self.encoder.box(value) } } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { let dictionary = NSMutableDictionary() self.container[key.stringValue] = dictionary return self.with(pushedKey: key) { let container = _PlistKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } } mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let array = NSMutableArray() self.container[key.stringValue] = array return self.with(pushedKey: key) { return _PlistUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } } mutating func superEncoder() -> Encoder { return _PlistReferencingEncoder(referencing: self.encoder, at: _PlistSuperKey.super, wrapping: self.container) } mutating func superEncoder(forKey key: Key) -> Encoder { return _PlistReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container) } } fileprivate struct _PlistUnkeyedEncodingContainer : UnkeyedEncodingContainer { // MARK: Properties /// A reference to the encoder we're writing to. let encoder: _PlistEncoder /// A reference to the container we're writing to. let container: NSMutableArray /// The path of coding keys taken to get to this point in encoding. var codingPath: [CodingKey?] // MARK: - Initialization /// Initializes `self` with the given references. init(referencing encoder: _PlistEncoder, codingPath: [CodingKey?], wrapping container: NSMutableArray) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - Coding Path Operations /// Performs the given closure with the given key pushed onto the end of the current coding path. /// /// - parameter key: The key to push. May be nil for unkeyed containers. /// - parameter work: The work to perform with the key in the path. mutating func with<T>(pushedKey key: CodingKey?, _ work: () throws -> T) rethrows -> T { self.codingPath.append(key) let ret: T = try work() self.codingPath.removeLast() return ret } // MARK: - UnkeyedEncodingContainer Methods mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: Float) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: Double) throws { self.container.add(self.encoder.box(value)) } mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) } mutating func encode<T : Encodable>(_ value: T) throws { try self.encoder.with(pushedKey: nil) { self.container.add(try self.encoder.box(value)) } } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { let dictionary = NSMutableDictionary() self.container.add(dictionary) return self.with(pushedKey: nil) { let container = _PlistKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } } mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { let array = NSMutableArray() self.container.add(array) return self.with(pushedKey: nil) { return _PlistUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } } mutating func superEncoder() -> Encoder { return _PlistReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container) } } extension _PlistEncoder : SingleValueEncodingContainer { // MARK: - Utility Methods /// Asserts that a single value can be encoded at the current coding path (i.e. that one has not already been encoded through this container). /// `preconditionFailure()`s if one cannot be encoded. /// /// This is similar to assertCanRequestNewContainer above. func assertCanEncodeSingleValue() { guard self.canEncodeNewElement else { let previousContainerType: String if self.storage.containers.last is NSDictionary { previousContainerType = "keyed" } else if self.storage.containers.last is NSArray { previousContainerType = "unkeyed" } else { preconditionFailure("Attempt to encode multiple values in a single value container.") } preconditionFailure("Attempt to encode with new container when already encoded with \(previousContainerType) container.") } } // MARK: - SingleValueEncodingContainer Methods func encodeNil() throws { assertCanEncodeSingleValue() self.storage.push(container: _plistNullNSString) } func encode(_ value: Bool) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: Int) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: Int8) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: Int16) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: Int32) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: Int64) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: UInt) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: UInt8) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: UInt16) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: UInt32) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: UInt64) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: String) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: Float) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode(_ value: Double) throws { assertCanEncodeSingleValue() self.storage.push(container: box(value)) } func encode<T : Encodable>(_ value: T) throws { assertCanEncodeSingleValue() try self.storage.push(container: box(value)) } } // MARK: - Concrete Value Representations extension _PlistEncoder { /// Returns the given value boxed in a container appropriate for pushing onto the container stack. fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Float) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Double) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) } fileprivate func box(_ value: Data) -> NSObject { return NSData(data: value) } fileprivate func box<T : Encodable>(_ value: T) throws -> NSObject { if T.self == Date.self { // PropertyListSerialization handles Date directly. return NSDate(timeIntervalSinceReferenceDate: (value as! Date).timeIntervalSinceReferenceDate) } else if T.self == Data.self { // PropertyListSerialization handles Data directly. return NSData(data: (value as! Data)) } // The value should request a container from the _PlistEncoder. let currentTopContainer = self.storage.containers.last try value.encode(to: self) // The top container should be a new container. guard self.storage.containers.last! !== currentTopContainer else { // If the value didn't request a container at all, encode the default container instead. return NSDictionary() } return self.storage.popContainer() } } // MARK: - _PlistReferencingEncoder /// _PlistReferencingEncoder is a special subclass of _PlistEncoder which has its own storage, but references the contents of a different encoder. /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container). fileprivate class _PlistReferencingEncoder : _PlistEncoder { // MARK: Reference types. /// The type of container we're referencing. enum Reference { /// Referencing a specific index in an array container. case array(NSMutableArray, Int) /// Referencing a specific key in a dictionary container. case dictionary(NSMutableDictionary, String) } // MARK: - Properties /// The encoder we're referencing. let encoder: _PlistEncoder /// The container reference itself. let reference: Reference // MARK: - Initialization /// Initializes `self` by referencing the given array container in the given encoder. init(referencing encoder: _PlistEncoder, at index: Int, wrapping array: NSMutableArray) { self.encoder = encoder self.reference = .array(array, index) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(nil) } /// Initializes `self` by referencing the given dictionary container in the given encoder. init(referencing encoder: _PlistEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) { self.encoder = encoder self.reference = .dictionary(dictionary, key.stringValue) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(key) } // MARK: - Coding Path Operations override var canEncodeNewElement: Bool { // With a regular encoder, the storage and coding path grow together. // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. // We have to take this into account. return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1 } // MARK: - Deinitialization // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage. deinit { let value: Any switch self.storage.count { case 0: value = NSDictionary() case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } switch self.reference { case .array(let array, let index): array.insert(value, at: index) case .dictionary(let dictionary, let key): dictionary[NSString(string: key)] = value } } } //===----------------------------------------------------------------------===// // Plist Decoder //===----------------------------------------------------------------------===// /// `PropertyListDecoder` facilitates the decoding of property list values into semantic `Decodable` types. open class PropertyListDecoder { // MARK: Options /// Contextual user-provided information for use during decoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the decoding hierarchy. fileprivate struct _Options { let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level decoder. fileprivate var options: _Options { return _Options(userInfo: userInfo) } // MARK: - Constructing a Property List Decoder /// Initializes `self` with default strategies. public init() {} // MARK: - Decoding Values /// Decodes a top-level value of the given type from the given property list representation. /// /// - parameter type: The type of the value to decode. /// - parameter data: The data to decode from. /// - returns: A value of the requested type. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not a valid property list. /// - throws: An error if any value throws an error during decoding. open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T { var format: PropertyListSerialization.PropertyListFormat = .binary return try decode(T.self, from: data, format: &format) } /// Decodes a top-level value of the given type from the given property list representation. /// /// - parameter type: The type of the value to decode. /// - parameter data: The data to decode from. /// - parameter format: The parsed property list format. /// - returns: A value of the requested type along with the detected format of the property list. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not a valid property list. /// - throws: An error if any value throws an error during decoding. open func decode<T : Decodable>(_ type: T.Type, from data: Data, format: inout PropertyListSerialization.PropertyListFormat) throws -> T { let topLevel = try PropertyListSerialization.propertyList(from: data, options: [], format: &format) let decoder = _PlistDecoder(referencing: topLevel, options: self.options) return try T(from: decoder) } } // MARK: - _PlistDecoder fileprivate class _PlistDecoder : Decoder { // MARK: Properties /// The decoder's storage. var storage: _PlistDecodingStorage /// Options set on the top-level decoder. let options: PropertyListDecoder._Options /// The path to the current point in encoding. var codingPath: [CodingKey?] /// Contextual user-provided information for use during encoding. var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level container and options. init(referencing container: Any, at codingPath: [CodingKey?] = [], options: PropertyListDecoder._Options) { self.storage = _PlistDecodingStorage() self.storage.push(container: container) self.codingPath = codingPath self.options = options } // MARK: - Coding Path Operations /// Performs the given closure with the given key pushed onto the end of the current coding path. /// /// - parameter key: The key to push. May be nil for unkeyed containers. /// - parameter work: The work to perform with the key in the path. func with<T>(pushedKey key: CodingKey?, _ work: () throws -> T) rethrows -> T { self.codingPath.append(key) let ret: T = try work() self.codingPath.removeLast() return ret } // MARK: - Decoder Methods func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer) } let container = _PlistKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer) return KeyedDecodingContainer(container) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get unkeyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer) } return _PlistUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) } func singleValueContainer() throws -> SingleValueDecodingContainer { guard !(self.storage.topContainer is [String : Any]) else { throw DecodingError.typeMismatch(SingleValueDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get single value decoding container -- found keyed container instead.")) } guard !(self.storage.topContainer is [Any]) else { throw DecodingError.typeMismatch(SingleValueDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get single value decoding container -- found unkeyed container instead.")) } return self } } // MARK: - Decoding Storage fileprivate struct _PlistDecodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the plist types (NSNumber, Date, String, Array, [String : Any]). private(set) var containers: [Any] = [] // MARK: - Initialization /// Initializes `self` with no containers. init() {} // MARK: - Modifying the Stack var count: Int { return self.containers.count } var topContainer: Any { precondition(self.containers.count > 0, "Empty container stack.") return self.containers.last! } mutating func push(container: Any) { self.containers.append(container) } mutating func popContainer() { precondition(self.containers.count > 0, "Empty container stack.") self.containers.removeLast() } } // MARK: Decoding Containers fileprivate struct _PlistKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the decoder we're reading from. let decoder: _PlistDecoder /// A reference to the container we're reading from. let container: [String : Any] /// The path of coding keys taken to get to this point in decoding. var codingPath: [CodingKey?] // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. init(referencing decoder: _PlistDecoder, wrapping container: [String : Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath } // MARK: - KeyedDecodingContainerProtocol Methods var allKeys: [Key] { return self.container.keys.flatMap { Key(stringValue: $0) } } func contains(_ key: Key) -> Bool { return self.container[key.stringValue] != nil } func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: Bool.self) } } func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: Int.self) } } func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: Int8.self) } } func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: Int16.self) } } func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: Int32.self) } } func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: Int64.self) } } func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: UInt.self) } } func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: UInt8.self) } } func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: UInt16.self) } } func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: UInt32.self) } } func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: UInt64.self) } } func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: Float.self) } } func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: Double.self) } } func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: String.self) } } func decodeIfPresent(_ type: Data.Type, forKey key: Key) throws -> Data? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: Data.self) } } func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? { return try self.decoder.with(pushedKey: key) { return try self.decoder.unbox(self.container[key.stringValue], as: T.self) } } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { return try self.decoder.with(pushedKey: key) { guard let value = self.container[key.stringValue] else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- no value found for key \"\(key.stringValue)\"")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } let container = _PlistKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { return try self.decoder.with(pushedKey: key) { guard let value = self.container[key.stringValue] else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested unkeyed container -- no value found for key \"\(key.stringValue)\"")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } return _PlistUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } } func _superDecoder(forKey key: CodingKey) throws -> Decoder { return try self.decoder.with(pushedKey: key) { guard let value = self.container[key.stringValue] else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- no value found for key \"\(key.stringValue)\"")) } return _PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } } func superDecoder() throws -> Decoder { return try _superDecoder(forKey: _PlistSuperKey.super) } func superDecoder(forKey key: Key) throws -> Decoder { return try _superDecoder(forKey: key) } } fileprivate struct _PlistUnkeyedDecodingContainer : UnkeyedDecodingContainer { // MARK: Properties /// A reference to the decoder we're reading from. let decoder: _PlistDecoder /// A reference to the container we're reading from. let container: [Any] /// The path of coding keys taken to get to this point in decoding. var codingPath: [CodingKey?] /// The index of the element we're about to decode. var currentIndex: Int // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. init(referencing decoder: _PlistDecoder, wrapping container: [Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath self.currentIndex = 0 } // MARK: - UnkeyedDecodingContainer Methods var count: Int? { return self.container.count } var isAtEnd: Bool { return self.currentIndex >= self.count! } mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: Int.Type) throws -> Int? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: Float.Type) throws -> Float? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: Double.Type) throws -> Double? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: String.Type) throws -> String? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent(_ type: Data.Type) throws -> Data? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Data.self) self.currentIndex += 1 return decoded } } mutating func decodeIfPresent<T : Decodable>(_ type: T.Type) throws -> T? { guard !self.isAtEnd else { return nil } return try self.decoder.with(pushedKey: nil) { let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: T.self) self.currentIndex += 1 return decoded } } mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> { return try self.decoder.with(pushedKey: nil) { guard !self.isAtEnd else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } self.currentIndex += 1 let container = _PlistKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } } mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { return try self.decoder.with(pushedKey: nil) { guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested unkeyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } self.currentIndex += 1 return _PlistUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } } mutating func superDecoder() throws -> Decoder { return try self.decoder.with(pushedKey: nil) { guard !self.isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- found null value instead.")) } self.currentIndex += 1 return _PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } } } extension _PlistDecoder : SingleValueDecodingContainer { // MARK: SingleValueDecodingContainer Methods func decodeNil() -> Bool { guard let string = self.storage.topContainer as? String else { return false } return string == _plistNull } // These all unwrap the result, since we couldn't have gotten a single value container if the topContainer was null. func decode(_ type: Bool.Type) throws -> Bool { guard let value = try self.unbox(self.storage.topContainer, as: Bool.self) else { throw DecodingError.valueNotFound(Bool.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected Bool but found null value instead.")) } return value } func decode(_ type: Int.Type) throws -> Int { guard let value = try self.unbox(self.storage.topContainer, as: Int.self) else { throw DecodingError.valueNotFound(Int.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected Int but found null value instead.")) } return value } func decode(_ type: Int8.Type) throws -> Int8 { guard let value = try self.unbox(self.storage.topContainer, as: Int8.self) else { throw DecodingError.valueNotFound(Int8.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected Int8 but found null value instead.")) } return value } func decode(_ type: Int16.Type) throws -> Int16 { guard let value = try self.unbox(self.storage.topContainer, as: Int16.self) else { throw DecodingError.valueNotFound(Int16.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected Int16 but found null value instead.")) } return value } func decode(_ type: Int32.Type) throws -> Int32 { guard let value = try self.unbox(self.storage.topContainer, as: Int32.self) else { throw DecodingError.valueNotFound(Int32.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected Int32 but found null value instead.")) } return value } func decode(_ type: Int64.Type) throws -> Int64 { guard let value = try self.unbox(self.storage.topContainer, as: Int64.self) else { throw DecodingError.valueNotFound(Int64.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected Int64 but found null value instead.")) } return value } func decode(_ type: UInt.Type) throws -> UInt { guard let value = try self.unbox(self.storage.topContainer, as: UInt.self) else { throw DecodingError.valueNotFound(UInt.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected UInt but found null value instead.")) } return value } func decode(_ type: UInt8.Type) throws -> UInt8 { guard let value = try self.unbox(self.storage.topContainer, as: UInt8.self) else { throw DecodingError.valueNotFound(UInt8.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected UInt8 but found null value instead.")) } return value } func decode(_ type: UInt16.Type) throws -> UInt16 { guard let value = try self.unbox(self.storage.topContainer, as: UInt16.self) else { throw DecodingError.valueNotFound(UInt16.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected UInt16 but found null value instead.")) } return value } func decode(_ type: UInt32.Type) throws -> UInt32 { guard let value = try self.unbox(self.storage.topContainer, as: UInt32.self) else { throw DecodingError.valueNotFound(UInt32.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected UInt32 but found null value instead.")) } return value } func decode(_ type: UInt64.Type) throws -> UInt64 { guard let value = try self.unbox(self.storage.topContainer, as: UInt64.self) else { throw DecodingError.valueNotFound(UInt64.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected UInt64 but found null value instead.")) } return value } func decode(_ type: Float.Type) throws -> Float { guard let value = try self.unbox(self.storage.topContainer, as: Float.self) else { throw DecodingError.valueNotFound(Float.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected Float but found null value instead.")) } return value } func decode(_ type: Double.Type) throws -> Double { guard let value = try self.unbox(self.storage.topContainer, as: Double.self) else { throw DecodingError.valueNotFound(Double.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected Double but found null value instead.")) } return value } func decode(_ type: String.Type) throws -> String { guard let value = try self.unbox(self.storage.topContainer, as: String.self) else { throw DecodingError.valueNotFound(String.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected String but found null value instead.")) } return value } func decode<T : Decodable>(_ type: T.Type) throws -> T { guard let value = try self.unbox(self.storage.topContainer, as: T.self) else { throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(T.self) but found null value instead.")) } return value } } // MARK: - Concrete Value Representations extension _PlistDecoder { /// Returns the given value unboxed from a container. fileprivate func unbox(_ value: Any?, as type: Bool.Type) throws -> Bool? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } if let number = value as? NSNumber { // TODO: Add a flag to coerce non-boolean numbers into Bools? if number === kCFBooleanTrue as NSNumber { return true } else if number === kCFBooleanFalse as NSNumber { return false } /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let bool = value as? Bool { return bool */ } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any?, as type: Int.Type) throws -> Int? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int = number.intValue guard NSNumber(value: int) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return int } fileprivate func unbox(_ value: Any?, as type: Int8.Type) throws -> Int8? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int8 = number.int8Value guard NSNumber(value: int8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return int8 } fileprivate func unbox(_ value: Any?, as type: Int16.Type) throws -> Int16? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int16 = number.int16Value guard NSNumber(value: int16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return int16 } fileprivate func unbox(_ value: Any?, as type: Int32.Type) throws -> Int32? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int32 = number.int32Value guard NSNumber(value: int32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return int32 } fileprivate func unbox(_ value: Any?, as type: Int64.Type) throws -> Int64? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int64 = number.int64Value guard NSNumber(value: int64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return int64 } fileprivate func unbox(_ value: Any?, as type: UInt.Type) throws -> UInt? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint = number.uintValue guard NSNumber(value: uint) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return uint } fileprivate func unbox(_ value: Any?, as type: UInt8.Type) throws -> UInt8? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint8 = number.uint8Value guard NSNumber(value: uint8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return uint8 } fileprivate func unbox(_ value: Any?, as type: UInt16.Type) throws -> UInt16? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint16 = number.uint16Value guard NSNumber(value: uint16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return uint16 } fileprivate func unbox(_ value: Any?, as type: UInt32.Type) throws -> UInt32? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint32 = number.uint32Value guard NSNumber(value: uint32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return uint32 } fileprivate func unbox(_ value: Any?, as type: UInt64.Type) throws -> UInt64? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint64 = number.uint64Value guard NSNumber(value: uint64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return uint64 } fileprivate func unbox(_ value: Any?, as type: Float.Type) throws -> Float? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let float = number.floatValue guard NSNumber(value: float) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return float } func unbox(_ value: Any?, as type: Double.Type) throws -> Double? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let double = number.doubleValue guard NSNumber(value: double) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type).")) } return double } func unbox(_ value: Any?, as type: String.Type) throws -> String? { guard let value = value else { return nil } guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return string == _plistNull ? nil : string } func unbox(_ value: Any?, as type: Date.Type) throws -> Date? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let date = value as? Date else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return date } func unbox(_ value: Any?, as type: Data.Type) throws -> Data? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } guard let data = value as? Data else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return data } func unbox<T : Decodable>(_ value: Any?, as type: T.Type) throws -> T? { guard let value = value else { return nil } if let string = value as? String, string == _plistNull { return nil } let decoded: T if T.self == Date.self { decoded = (try self.unbox(value, as: Date.self) as! T) } else if T.self == Data.self { decoded = (try self.unbox(value, as: Data.self) as! T) } else { self.storage.push(container: value) decoded = try T(from: self) self.storage.popContainer() } return decoded } } //===----------------------------------------------------------------------===// // Shared Plist Null Representation //===----------------------------------------------------------------------===// // Since plists do not support null values by default, we will encode them as "$null". fileprivate let _plistNull = "$null" fileprivate let _plistNullNSString = NSString(string: _plistNull) //===----------------------------------------------------------------------===// // Shared Super Key //===----------------------------------------------------------------------===// fileprivate enum _PlistSuperKey : String, CodingKey { case `super` }
apache-2.0
13c4f4aa35e2943fb2d615a540d2b118
40.947087
258
0.619956
4.915355
false
false
false
false
tapglue/snaasSdk-iOS
Sources/Internal/UIDevice+Tapglue.swift
2
2530
// // UIDevice+Tapglue.swift // Tapglue // // Created by John Nilsen on 7/11/16. // Copyright © 2016 Tapglue. All rights reserved. // import UIKit extension UIDevice { var tapglueModelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8 , value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone8,4": return "iPhone SE" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro" case "AppleTV5,3": return "Apple TV" case "i386", "x86_64": return "Simulator" default: return identifier } } }
apache-2.0
eba46a5f8438dfcb4426fc0b5f105cd1
50.612245
92
0.470146
3.878834
false
false
false
false
SmallElephant/FEAlgorithm-Swift
4-ListNode/4-ListNode/RandomListClone.swift
1
1514
// // RandomListClone.swift // 4-ListNode // // Created by FlyElephant on 16/12/17. // Copyright © 2016年 FlyElephant. All rights reserved. // import Foundation class RandomListClone { // 复杂链表的复制 // 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点). func randomListNodeClone(headNode:inout RandomListNode?) { var pHead:RandomListNode? = headNode // A->B->C 拷贝 A->A1->B->B2->C->C1 while pHead != nil { let cloneNode:RandomListNode = RandomListNode() cloneNode.data = (pHead?.data)! + "1" cloneNode.next = pHead?.next pHead?.next = cloneNode pHead = cloneNode.next } // sibling 拷贝 var sHead:RandomListNode? = headNode while sHead != nil { let nextNode:RandomListNode? = sHead?.next if nextNode != nil { nextNode!.sibling = sHead?.sibling?.next } sHead = sHead?.next?.next } // 拆分链表 let cloneHead:RandomListNode? = headNode?.next headNode = cloneHead var beginNode:RandomListNode? = cloneHead while beginNode != nil { let temp = beginNode?.next?.next if beginNode?.next != nil { beginNode?.next = temp } beginNode = temp } } }
mit
b36b84a6d1e4508d5aa347a3f209ed4a
27.142857
62
0.542422
3.851955
false
false
false
false
natestedman/ReactiveCocoa
Sources/ReactiveCocoa/Swift/SignalProducer.swift
1
53198
import Foundation import Result /// A SignalProducer creates Signals that can produce values of type `Value` and/or /// fail with errors of type `Error`. If no failure should be possible, NoError /// can be specified for `Error`. /// /// SignalProducers can be used to represent operations or tasks, like network /// requests, where each invocation of start() will create a new underlying /// operation. This ensures that consumers will receive the results, versus a /// plain Signal, where the results might be sent before any observers are /// attached. /// /// Because of the behavior of start(), different Signals created from the /// producer may see a different version of Events. The Events may arrive in a /// different order between Signals, or the stream might be completely /// different! public struct SignalProducer<Value, Error: ErrorType> { public typealias ProducedSignal = Signal<Value, Error> private let startHandler: (Signal<Value, Error>.Observer, CompositeDisposable) -> () /// Initializes a SignalProducer that will emit the same events as the given signal. /// /// If the Disposable returned from start() is disposed or a terminating /// event is sent to the observer, the given signal will be /// disposed. public init<S: SignalType where S.Value == Value, S.Error == Error>(signal: S) { self.init { observer, disposable in disposable += signal.observe(observer) } } /// Initializes a SignalProducer that will invoke the given closure once /// for each invocation of start(). /// /// The events that the closure puts into the given observer will become /// the events sent by the started Signal to its observers. /// /// If the Disposable returned from start() is disposed or a terminating /// event is sent to the observer, the given CompositeDisposable will be /// disposed, at which point work should be interrupted and any temporary /// resources cleaned up. public init(_ startHandler: (Signal<Value, Error>.Observer, CompositeDisposable) -> ()) { self.startHandler = startHandler } /// Creates a producer for a Signal that will immediately send one value /// then complete. public init(value: Value) { self.init { observer, disposable in observer.sendNext(value) observer.sendCompleted() } } /// Creates a producer for a Signal that will immediately fail with the /// given error. public init(error: Error) { self.init { observer, disposable in observer.sendFailed(error) } } /// Creates a producer for a Signal that will immediately send one value /// then complete, or immediately fail, depending on the given Result. public init(result: Result<Value, Error>) { switch result { case let .Success(value): self.init(value: value) case let .Failure(error): self.init(error: error) } } /// Creates a producer for a Signal that will immediately send the values /// from the given sequence, then complete. public init<S: SequenceType where S.Generator.Element == Value>(values: S) { self.init { observer, disposable in for value in values { observer.sendNext(value) if disposable.disposed { break } } observer.sendCompleted() } } /// A producer for a Signal that will immediately complete without sending /// any values. public static var empty: SignalProducer { return self.init { observer, disposable in observer.sendCompleted() } } /// A producer for a Signal that never sends any events to its observers. public static var never: SignalProducer { return self.init { _ in return } } /// Creates a queue for events that replays them when new signals are /// created from the returned producer. /// /// When values are put into the returned observer (observer), they will be /// added to an internal buffer. If the buffer is already at capacity, /// the earliest (oldest) value will be dropped to make room for the new /// value. /// /// Signals created from the returned producer will stay alive until a /// terminating event is added to the queue. If the queue does not contain /// such an event when the Signal is started, all values sent to the /// returned observer will be automatically forwarded to the Signal’s /// observers until a terminating event is received. /// /// After a terminating event has been added to the queue, the observer /// will not add any further events. This _does not_ count against the /// value capacity so no buffered values will be dropped on termination. public static func buffer(capacity: Int = Int.max) -> (SignalProducer, Signal<Value, Error>.Observer) { precondition(capacity >= 0) // This is effectively used as a synchronous mutex, but permitting // limited recursive locking (see below). // // The queue is a "variable" just so we can use its address as the key // and the value for dispatch_queue_set_specific(). var queue = dispatch_queue_create("org.reactivecocoa.ReactiveCocoa.SignalProducer.buffer", DISPATCH_QUEUE_SERIAL) dispatch_queue_set_specific(queue, &queue, &queue, nil) // Used as an atomic variable so we can remove observers without needing // to run on the queue. let state: Atomic<BufferState<Value, Error>> = Atomic(BufferState()) let producer = self.init { observer, disposable in // Assigned to when replay() is invoked synchronously below. var token: RemovalToken? let replay: () -> () = { let originalState = state.modify { state in var mutableState = state token = mutableState.observers?.insert(observer) return mutableState } for value in originalState.values { observer.sendNext(value) } if let terminationEvent = originalState.terminationEvent { observer.action(terminationEvent) } } // Prevent other threads from sending events while we're replaying, // but don't deadlock if we're replaying in response to a buffer // event observed elsewhere. // // In other words, this permits limited signal recursion for the // specific case of replaying past events. if dispatch_get_specific(&queue) != nil { replay() } else { dispatch_sync(queue, replay) } if let token = token { disposable.addDisposable { state.modify { state in var mutableState = state mutableState.observers?.removeValueForToken(token) return mutableState } } } } let bufferingObserver: Signal<Value, Error>.Observer = Observer { event in // Send serially with respect to other senders, and never while // another thread is in the process of replaying. dispatch_sync(queue) { let originalState = state.modify { state in var mutableState = state if let value = event.value { mutableState.addValue(value, upToCapacity: capacity) } else { // Disconnect all observers and prevent future // attachments. mutableState.terminationEvent = event mutableState.observers = nil } return mutableState } if let observers = originalState.observers { for observer in observers { observer.action(event) } } } } return (producer, bufferingObserver) } /// Creates a SignalProducer that will attempt the given operation once for /// each invocation of start(). /// /// Upon success, the started signal will send the resulting value then /// complete. Upon failure, the started signal will fail with the error that /// occurred. public static func attempt(operation: () -> Result<Value, Error>) -> SignalProducer { return self.init { observer, disposable in operation().analysis(ifSuccess: { value in observer.sendNext(value) observer.sendCompleted() }, ifFailure: { error in observer.sendFailed(error) }) } } /// Creates a Signal from the producer, passes it into the given closure, /// then starts sending events on the Signal when the closure has returned. /// /// The closure will also receive a disposable which can be used to /// interrupt the work associated with the signal and immediately send an /// `Interrupted` event. public func startWithSignal(@noescape setUp: (Signal<Value, Error>, Disposable) -> ()) { let (signal, observer) = Signal<Value, Error>.pipe() // Disposes of the work associated with the SignalProducer and any // upstream producers. let producerDisposable = CompositeDisposable() // Directly disposed of when start() or startWithSignal() is disposed. let cancelDisposable = ActionDisposable { observer.sendInterrupted() producerDisposable.dispose() } setUp(signal, cancelDisposable) if cancelDisposable.disposed { return } let wrapperObserver: Signal<Value, Error>.Observer = Observer { event in observer.action(event) if event.isTerminating { // Dispose only after notifying the Signal, so disposal // logic is consistently the last thing to run. producerDisposable.dispose() } } startHandler(wrapperObserver, producerDisposable) } } private struct BufferState<Value, Error: ErrorType> { // All values in the buffer. var values: [Value] = [] // Any terminating event sent to the buffer. // // This will be nil if termination has not occurred. var terminationEvent: Event<Value, Error>? // The observers currently attached to the buffered producer, or nil if the // producer was terminated. var observers: Bag<Signal<Value, Error>.Observer>? = Bag() // Appends a new value to the buffer, trimming it down to the given capacity // if necessary. mutating func addValue(value: Value, upToCapacity capacity: Int) { values.append(value) let overflow = values.count - capacity if overflow > 0 { values.removeRange(0..<overflow) } } } public protocol SignalProducerType { /// The type of values being sent on the producer typealias Value /// The type of error that can occur on the producer. If errors aren't possible /// then `NoError` can be used. typealias Error: ErrorType /// Extracts a signal producer from the receiver. var producer: SignalProducer<Value, Error> { get } /// Creates a Signal from the producer, passes it into the given closure, /// then starts sending events on the Signal when the closure has returned. func startWithSignal(@noescape setUp: (Signal<Value, Error>, Disposable) -> ()) } extension SignalProducer: SignalProducerType { public var producer: SignalProducer { return self } } extension SignalProducerType { /// Creates a Signal from the producer, then attaches the given observer to /// the Signal as an observer. /// /// Returns a Disposable which can be used to interrupt the work associated /// with the signal and immediately send an `Interrupted` event. public func start(observer: Signal<Value, Error>.Observer = Signal<Value, Error>.Observer()) -> Disposable { var disposable: Disposable! startWithSignal { signal, innerDisposable in signal.observe(observer) disposable = innerDisposable } return disposable } /// Convenience override for start(_:) to allow trailing-closure style /// invocations. public func start(observerAction: Signal<Value, Error>.Observer.Action) -> Disposable { return start(Observer(observerAction)) } /// Creates a Signal from the producer, then adds exactly one observer to /// the Signal, which will invoke the given callback when `next` events are /// received. /// /// Returns a Disposable which can be used to interrupt the work associated /// with the Signal, and prevent any future callbacks from being invoked. public func startWithNext(next: Value -> ()) -> Disposable { return start(Observer(next: next)) } /// Creates a Signal from the producer, then adds exactly one observer to /// the Signal, which will invoke the given callback when a `completed` event is /// received. /// /// Returns a Disposable which can be used to interrupt the work associated /// with the Signal. public func startWithCompleted(completed: () -> ()) -> Disposable { return start(Observer(completed: completed)) } /// Creates a Signal from the producer, then adds exactly one observer to /// the Signal, which will invoke the given callback when a `failed` event is /// received. /// /// Returns a Disposable which can be used to interrupt the work associated /// with the Signal. public func startWithFailed(failed: Error -> ()) -> Disposable { return start(Observer(failed: failed)) } /// Creates a Signal from the producer, then adds exactly one observer to /// the Signal, which will invoke the given callback when an `interrupted` event is /// received. /// /// Returns a Disposable which can be used to interrupt the work associated /// with the Signal. public func startWithInterrupted(interrupted: () -> ()) -> Disposable { return start(Observer(interrupted: interrupted)) } /// Lifts an unary Signal operator to operate upon SignalProducers instead. /// /// In other words, this will create a new SignalProducer which will apply /// the given Signal operator to _every_ created Signal, just as if the /// operator had been applied to each Signal yielded from start(). @warn_unused_result(message="Did you forget to call `start` on the producer?") public func lift<U, F>(transform: Signal<Value, Error> -> Signal<U, F>) -> SignalProducer<U, F> { return SignalProducer { observer, outerDisposable in self.startWithSignal { signal, innerDisposable in outerDisposable.addDisposable(innerDisposable) transform(signal).observe(observer) } } } /// Lifts a binary Signal operator to operate upon SignalProducers instead. /// /// In other words, this will create a new SignalProducer which will apply /// the given Signal operator to _every_ Signal created from the two /// producers, just as if the operator had been applied to each Signal /// yielded from start(). /// /// Note: starting the returned producer will start the receiver of the operator, /// which may not be adviseable for some operators. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func lift<U, F, V, G>(transform: Signal<Value, Error> -> Signal<U, F> -> Signal<V, G>) -> SignalProducer<U, F> -> SignalProducer<V, G> { return liftRight(transform) } /// Right-associative lifting of a binary signal operator over producers. That /// is, the argument producer will be started before the receiver. When both /// producers are synchronous this order can be important depending on the operator /// to generate correct results. @warn_unused_result(message="Did you forget to call `start` on the producer?") private func liftRight<U, F, V, G>(transform: Signal<Value, Error> -> Signal<U, F> -> Signal<V, G>) -> SignalProducer<U, F> -> SignalProducer<V, G> { return { otherProducer in return SignalProducer { observer, outerDisposable in self.startWithSignal { signal, disposable in outerDisposable.addDisposable(disposable) otherProducer.startWithSignal { otherSignal, otherDisposable in outerDisposable.addDisposable(otherDisposable) transform(signal)(otherSignal).observe(observer) } } } } } /// Left-associative lifting of a binary signal operator over producers. That /// is, the receiver will be started before the argument producer. When both /// producers are synchronous this order can be important depending on the operator /// to generate correct results. @warn_unused_result(message="Did you forget to call `start` on the producer?") private func liftLeft<U, F, V, G>(transform: Signal<Value, Error> -> Signal<U, F> -> Signal<V, G>) -> SignalProducer<U, F> -> SignalProducer<V, G> { return { otherProducer in return SignalProducer { observer, outerDisposable in otherProducer.startWithSignal { otherSignal, otherDisposable in outerDisposable.addDisposable(otherDisposable) self.startWithSignal { signal, disposable in outerDisposable.addDisposable(disposable) transform(signal)(otherSignal).observe(observer) } } } } } /// Lifts a binary Signal operator to operate upon a Signal and a SignalProducer instead. /// /// In other words, this will create a new SignalProducer which will apply /// the given Signal operator to _every_ Signal created from the two /// producers, just as if the operator had been applied to each Signal /// yielded from start(). @warn_unused_result(message="Did you forget to call `start` on the producer?") public func lift<U, F, V, G>(transform: Signal<Value, Error> -> Signal<U, F> -> Signal<V, G>) -> Signal<U, F> -> SignalProducer<V, G> { return { otherSignal in return SignalProducer { observer, outerDisposable in self.startWithSignal { signal, disposable in outerDisposable += disposable outerDisposable += transform(signal)(otherSignal).observe(observer) } } } } /// Maps each value in the producer to a new value. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func map<U>(transform: Value -> U) -> SignalProducer<U, Error> { return lift { $0.map(transform) } } /// Maps errors in the producer to a new error. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func mapError<F>(transform: Error -> F) -> SignalProducer<Value, F> { return lift { $0.mapError(transform) } } /// Preserves only the values of the producer that pass the given predicate. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func filter(predicate: Value -> Bool) -> SignalProducer<Value, Error> { return lift { $0.filter(predicate) } } /// Returns a producer that will yield the first `count` values from the /// input producer. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func take(count: Int) -> SignalProducer<Value, Error> { return lift { $0.take(count) } } /// Returns a signal that will yield an array of values when `signal` completes. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func collect() -> SignalProducer<[Value], Error> { return lift { $0.collect() } } /// Forwards all events onto the given scheduler, instead of whichever /// scheduler they originally arrived upon. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func observeOn(scheduler: SchedulerType) -> SignalProducer<Value, Error> { return lift { $0.observeOn(scheduler) } } /// Combines the latest value of the receiver with the latest value from /// the given producer. /// /// The returned producer will not send a value until both inputs have sent at /// least one value each. If either producer is interrupted, the returned producer /// will also be interrupted. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatestWith<U>(otherProducer: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> { return liftRight(Signal.combineLatestWith)(otherProducer) } /// Combines the latest value of the receiver with the latest value from /// the given signal. /// /// The returned producer will not send a value until both inputs have sent at /// least one value each. If either input is interrupted, the returned producer /// will also be interrupted. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatestWith<U>(otherSignal: Signal<U, Error>) -> SignalProducer<(Value, U), Error> { return lift(Signal.combineLatestWith)(otherSignal) } /// Delays `Next` and `Completed` events by the given interval, forwarding /// them on the given scheduler. /// /// `Failed` and `Interrupted` events are always scheduled immediately. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func delay(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<Value, Error> { return lift { $0.delay(interval, onScheduler: scheduler) } } /// Returns a producer that will skip the first `count` values, then forward /// everything afterward. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func skip(count: Int) -> SignalProducer<Value, Error> { return lift { $0.skip(count) } } /// Treats all Events from the input producer as plain values, allowing them to be /// manipulated just like any other value. /// /// In other words, this brings Events “into the monad.” /// /// When a Completed or Failed event is received, the resulting producer will send /// the Event itself and then complete. When an Interrupted event is received, /// the resulting producer will send the Event itself and then interrupt. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func materialize() -> SignalProducer<Event<Value, Error>, NoError> { return lift { $0.materialize() } } /// Forwards the latest value from `self` whenever `sampler` sends a Next /// event. /// /// If `sampler` fires before a value has been observed on `self`, nothing /// happens. /// /// Returns a producer that will send values from `self`, sampled (possibly /// multiple times) by `sampler`, then complete once both input producers have /// completed, or interrupt if either input producer is interrupted. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func sampleOn(sampler: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> { return liftLeft(Signal.sampleOn)(sampler) } /// Forwards the latest value from `self` whenever `sampler` sends a Next /// event. /// /// If `sampler` fires before a value has been observed on `self`, nothing /// happens. /// /// Returns a producer that will send values from `self`, sampled (possibly /// multiple times) by `sampler`, then complete once both inputs have /// completed, or interrupt if either input is interrupted. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func sampleOn(sampler: Signal<(), NoError>) -> SignalProducer<Value, Error> { return lift(Signal.sampleOn)(sampler) } /// Forwards events from `self` until `trigger` sends a Next or Completed /// event, at which point the returned producer will complete. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func takeUntil(trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> { return liftRight(Signal.takeUntil)(trigger) } /// Forwards events from `self` until `trigger` sends a Next or Completed /// event, at which point the returned producer will complete. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func takeUntil(trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> { return lift(Signal.takeUntil)(trigger) } /// Does not forward any values from `self` until `trigger` sends a Next or /// Completed, at which point the returned signal behaves exactly like `signal`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func skipUntil(trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> { return liftRight(Signal.skipUntil)(trigger) } /// Does not forward any values from `self` until `trigger` sends a Next or /// Completed, at which point the returned signal behaves exactly like `signal`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func skipUntil(trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> { return lift(Signal.skipUntil)(trigger) } /// Forwards events from `self` with history: values of the returned producer /// are a tuple whose first member is the previous value and whose second member /// is the current value. `initial` is supplied as the first member when `self` /// sends its first value. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combinePrevious(initial: Value) -> SignalProducer<(Value, Value), Error> { return lift { $0.combinePrevious(initial) } } /// Like `scan`, but sends only the final value and then immediately completes. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func reduce<U>(initial: U, _ combine: (U, Value) -> U) -> SignalProducer<U, Error> { return lift { $0.reduce(initial, combine) } } /// Aggregates `self`'s values into a single combined value. When `self` emits /// its first value, `combine` is invoked with `initial` as the first argument and /// that emitted value as the second argument. The result is emitted from the /// producer returned from `scan`. That result is then passed to `combine` as the /// first argument when the next value is emitted, and so on. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func scan<U>(initial: U, _ combine: (U, Value) -> U) -> SignalProducer<U, Error> { return lift { $0.scan(initial, combine) } } /// Forwards only those values from `self` which do not pass `isRepeat` with /// respect to the previous value. The first value is always forwarded. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func skipRepeats(isRepeat: (Value, Value) -> Bool) -> SignalProducer<Value, Error> { return lift { $0.skipRepeats(isRepeat) } } /// Does not forward any values from `self` until `predicate` returns false, /// at which point the returned signal behaves exactly like `self`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func skipWhile(predicate: Value -> Bool) -> SignalProducer<Value, Error> { return lift { $0.skipWhile(predicate) } } /// Forwards events from `self` until `replacement` begins sending events. /// /// Returns a producer which passes through `Next`, `Failed`, and `Interrupted` /// events from `self` until `replacement` sends an event, at which point the /// returned producer will send that event and switch to passing through events /// from `replacement` instead, regardless of whether `self` has sent events /// already. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func takeUntilReplacement(replacement: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> { return liftRight(Signal.takeUntilReplacement)(replacement) } /// Forwards events from `self` until `replacement` begins sending events. /// /// Returns a producer which passes through `Next`, `Error`, and `Interrupted` /// events from `self` until `replacement` sends an event, at which point the /// returned producer will send that event and switch to passing through events /// from `replacement` instead, regardless of whether `self` has sent events /// already. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func takeUntilReplacement(replacement: Signal<Value, Error>) -> SignalProducer<Value, Error> { return lift(Signal.takeUntilReplacement)(replacement) } /// Waits until `self` completes and then forwards the final `count` values /// on the returned producer. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func takeLast(count: Int) -> SignalProducer<Value, Error> { return lift { $0.takeLast(count) } } /// Forwards any values from `self` until `predicate` returns false, /// at which point the returned producer will complete. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func takeWhile(predicate: Value -> Bool) -> SignalProducer<Value, Error> { return lift { $0.takeWhile(predicate) } } /// Zips elements of two producers into pairs. The elements of any Nth pair /// are the Nth elements of the two input producers. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zipWith<U>(otherProducer: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> { return liftRight(Signal.zipWith)(otherProducer) } /// Zips elements of this producer and a signal into pairs. The elements of /// any Nth pair are the Nth elements of the two. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zipWith<U>(otherSignal: Signal<U, Error>) -> SignalProducer<(Value, U), Error> { return lift(Signal.zipWith)(otherSignal) } /// Applies `operation` to values from `self` with `Success`ful results /// forwarded on the returned producer and `Failure`s sent as `Failed` events. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func attempt(operation: Value -> Result<(), Error>) -> SignalProducer<Value, Error> { return lift { $0.attempt(operation) } } /// Applies `operation` to values from `self` with `Success`ful results mapped /// on the returned producer and `Failure`s sent as `Failed` events. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func attemptMap<U>(operation: Value -> Result<U, Error>) -> SignalProducer<U, Error> { return lift { $0.attemptMap(operation) } } /// Throttle values sent by the receiver, so that at least `interval` /// seconds pass between each, then forwards them on the given scheduler. /// /// If multiple values are received before the interval has elapsed, the /// latest value is the one that will be passed on. /// /// If `self` terminates while a value is being throttled, that value /// will be discarded and the returned producer will terminate immediately. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func throttle(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<Value, Error> { return lift { $0.throttle(interval, onScheduler: scheduler) } } /// Forwards events from `self` until `interval`. Then if producer isn't completed yet, /// fails with `error` on `scheduler`. /// /// If the interval is 0, the timeout will be scheduled immediately. The producer /// must complete synchronously (or on a faster scheduler) to avoid the timeout. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func timeoutWithError(error: Error, afterInterval interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<Value, Error> { return lift { $0.timeoutWithError(error, afterInterval: interval, onScheduler: scheduler) } } } extension SignalProducerType where Value: OptionalType { /// Unwraps non-`nil` values and forwards them on the returned signal, `nil` /// values are dropped. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func ignoreNil() -> SignalProducer<Value.Wrapped, Error> { return lift { $0.ignoreNil() } } } extension SignalProducerType where Value: EventType, Error == NoError { /// The inverse of materialize(), this will translate a signal of `Event` /// _values_ into a signal of those events themselves. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func dematerialize() -> SignalProducer<Value.Value, Value.Error> { return lift { $0.dematerialize() } } } extension SignalProducerType where Error == NoError { /// Promotes a producer that does not generate failures into one that can. /// /// This does not actually cause failers to be generated for the given producer, /// but makes it easier to combine with other producers that may fail; for /// example, with operators like `combineLatestWith`, `zipWith`, `flatten`, etc. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func promoteErrors<F: ErrorType>(_: F.Type) -> SignalProducer<Value, F> { return lift { $0.promoteErrors(F) } } } extension SignalProducerType where Value: Equatable { /// Forwards only those values from `self` which are not duplicates of the /// immedately preceding value. The first value is always forwarded. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func skipRepeats() -> SignalProducer<Value, Error> { return lift { $0.skipRepeats() } } } /// Creates a repeating timer of the given interval, with a reasonable /// default leeway, sending updates on the given scheduler. /// /// This timer will never complete naturally, so all invocations of start() must /// be disposed to avoid leaks. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func timer(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<NSDate, NoError> { // Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of // at least 10% of the timer interval. return timer(interval, onScheduler: scheduler, withLeeway: interval * 0.1) } /// Creates a repeating timer of the given interval, sending updates on the /// given scheduler. /// /// This timer will never complete naturally, so all invocations of start() must /// be disposed to avoid leaks. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func timer(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType, withLeeway leeway: NSTimeInterval) -> SignalProducer<NSDate, NoError> { precondition(interval >= 0) precondition(leeway >= 0) return SignalProducer { observer, compositeDisposable in compositeDisposable += scheduler.scheduleAfter(scheduler.currentDate.dateByAddingTimeInterval(interval), repeatingEvery: interval, withLeeway: leeway) { observer.sendNext(scheduler.currentDate) } } } extension SignalProducerType { /// Injects side effects to be performed upon the specified signal events. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func on(started started: (() -> ())? = nil, event: (Event<Value, Error> -> ())? = nil, failed: (Error -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, terminated: (() -> ())? = nil, disposed: (() -> ())? = nil, next: (Value -> ())? = nil) -> SignalProducer<Value, Error> { return SignalProducer { observer, compositeDisposable in started?() self.startWithSignal { signal, disposable in compositeDisposable += disposable compositeDisposable += signal .on( event: event, failed: failed, completed: completed, interrupted: interrupted, terminated: terminated, disposed: disposed, next: next ) .observe(observer) } } } /// Starts the returned signal on the given Scheduler. /// /// This implies that any side effects embedded in the producer will be /// performed on the given scheduler as well. /// /// Events may still be sent upon other schedulers—this merely affects where /// the `start()` method is run. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func startOn(scheduler: SchedulerType) -> SignalProducer<Value, Error> { return SignalProducer { observer, compositeDisposable in compositeDisposable += scheduler.schedule { self.startWithSignal { signal, signalDisposable in compositeDisposable.addDisposable(signalDisposable) signal.observe(observer) } } } } } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<A, B, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(A, B), Error> { return a.combineLatestWith(b) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<A, B, C, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(A, B, C), Error> { return combineLatest(a, b) .combineLatestWith(c) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<A, B, C, D, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(A, B, C, D), Error> { return combineLatest(a, b, c) .combineLatestWith(d) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<A, B, C, D, E, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(A, B, C, D, E), Error> { return combineLatest(a, b, c, d) .combineLatestWith(e) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<A, B, C, D, E, F, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(A, B, C, D, E, F), Error> { return combineLatest(a, b, c, d, e) .combineLatestWith(f) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<A, B, C, D, E, F, G, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(A, B, C, D, E, F, G), Error> { return combineLatest(a, b, c, d, e, f) .combineLatestWith(g) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<A, B, C, D, E, F, G, H, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H), Error> { return combineLatest(a, b, c, d, e, f, g) .combineLatestWith(h) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<A, B, C, D, E, F, G, H, I, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I), Error> { return combineLatest(a, b, c, d, e, f, g, h) .combineLatestWith(i) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<A, B, C, D, E, F, G, H, I, J, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I, J), Error> { return combineLatest(a, b, c, d, e, f, g, h, i) .combineLatestWith(j) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. Will return an empty `SignalProducer` if the sequence is empty. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func combineLatest<S: SequenceType, Value, Error where S.Generator.Element == SignalProducer<Value, Error>>(producers: S) -> SignalProducer<[Value], Error> { var generator = producers.generate() if let first = generator.next() { let initial = first.map { [$0] } return GeneratorSequence(generator).reduce(initial) { producer, next in producer.combineLatestWith(next).map { $0.0 + [$0.1] } } } return .empty } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<A, B, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(A, B), Error> { return a.zipWith(b) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<A, B, C, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(A, B, C), Error> { return zip(a, b) .zipWith(c) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<A, B, C, D, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(A, B, C, D), Error> { return zip(a, b, c) .zipWith(d) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<A, B, C, D, E, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(A, B, C, D, E), Error> { return zip(a, b, c, d) .zipWith(e) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<A, B, C, D, E, F, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(A, B, C, D, E, F), Error> { return zip(a, b, c, d, e) .zipWith(f) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<A, B, C, D, E, F, G, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(A, B, C, D, E, F, G), Error> { return zip(a, b, c, d, e, f) .zipWith(g) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<A, B, C, D, E, F, G, H, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H), Error> { return zip(a, b, c, d, e, f, g) .zipWith(h) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<A, B, C, D, E, F, G, H, I, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I), Error> { return zip(a, b, c, d, e, f, g, h) .zipWith(i) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<A, B, C, D, E, F, G, H, I, J, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I, J), Error> { return zip(a, b, c, d, e, f, g, h, i) .zipWith(j) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. Will return an empty `SignalProducer` if the sequence is empty. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func zip<S: SequenceType, Value, Error where S.Generator.Element == SignalProducer<Value, Error>>(producers: S) -> SignalProducer<[Value], Error> { var generator = producers.generate() if let first = generator.next() { let initial = first.map { [$0] } return GeneratorSequence(generator).reduce(initial) { producer, next in producer.zipWith(next).map { $0.0 + [$0.1] } } } return .empty } extension SignalProducerType where Value: SignalProducerType, Error == Value.Error { /// Flattens the inner producers sent upon `producer` (into a single producer of /// values), according to the semantics of the given strategy. /// /// If `producer` or an active inner producer fails, the returned /// producer will forward that failure immediately. /// /// `Interrupted` events on inner producers will be treated like `Completed` /// events on inner producers. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { return lift { (signal: Signal<Value, Error>) -> Signal<Value.Value, Error> in return signal.flatten(strategy) } } } extension SignalProducerType where Value: SignalType, Error == Value.Error { /// Flattens the inner signals sent upon `producer` (into a single producer of /// values), according to the semantics of the given strategy. /// /// If `producer` or an active inner signal emits an error, the returned /// producer will forward that error immediately. /// /// `Interrupted` events on inner signals will be treated like `Completed` /// events on inner signals. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { return self.lift { $0.flatten(strategy) } } } extension SignalProducerType { /// Maps each event from `producer` to a new producer, then flattens the /// resulting producers (into a single producer of values), according to the /// semantics of the given strategy. /// /// If `producer` or any of the created producers fail, the returned /// producer will forward that failure immediately. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> SignalProducer<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `producer` to a new signal, then flattens the /// resulting signals (into a single producer of values), according to the /// semantics of the given strategy. /// /// If `producer` or any of the created signals emit an error, the returned /// producer will forward that error immediately. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> SignalProducer<U, Error> { return map(transform).flatten(strategy) } /// Catches any failure that may occur on the input producer, mapping to a new producer /// that starts in its place. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> SignalProducer<Value, F> { return self.lift { $0.flatMapError(handler) } } /// `concat`s `next` onto `self`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func concat(next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> { return SignalProducer<SignalProducer<Value, Error>, Error>(values: [self.producer, next]).flatten(.Concat) } } extension SignalProducerType { /// Repeats `self` a total of `count` times. Repeating `1` times results in /// an equivalent signal producer. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func times(count: Int) -> SignalProducer<Value, Error> { precondition(count >= 0) if count == 0 { return .empty } else if count == 1 { return producer } return SignalProducer { observer, disposable in let serialDisposable = SerialDisposable() disposable.addDisposable(serialDisposable) func iterate(current: Int) { self.startWithSignal { signal, signalDisposable in serialDisposable.innerDisposable = signalDisposable signal.observe { event in if case .Completed = event { let remainingTimes = current - 1 if remainingTimes > 0 { iterate(remainingTimes) } else { observer.sendCompleted() } } else { observer.action(event) } } } } iterate(count) } } /// Ignores failures up to `count` times. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func retry(count: Int) -> SignalProducer<Value, Error> { precondition(count >= 0) if count == 0 { return producer } else { return flatMapError { _ in self.retry(count - 1) } } } /// Waits for completion of `producer`, *then* forwards all events from /// `replacement`. Any failure sent from `producer` is forwarded immediately, in /// which case `replacement` will not be started, and none of its events will be /// be forwarded. All values sent from `producer` are ignored. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func then<U>(replacement: SignalProducer<U, Error>) -> SignalProducer<U, Error> { let relay = SignalProducer<U, Error> { observer, observerDisposable in self.startWithSignal { signal, signalDisposable in observerDisposable.addDisposable(signalDisposable) signal.observe { event in switch event { case let .Failed(error): observer.sendFailed(error) case .Completed: observer.sendCompleted() case .Interrupted: observer.sendInterrupted() case .Next: break } } } } return relay.concat(replacement) } /// Starts the producer, then blocks, waiting for the first value. @warn_unused_result(message="Did you forget to check the result?") public func first() -> Result<Value, Error>? { return take(1).single() } /// Starts the producer, then blocks, waiting for events: Next and Completed. /// When a single value or error is sent, the returned `Result` will represent /// those cases. However, when no values are sent, or when more than one value /// is sent, `nil` will be returned. @warn_unused_result(message="Did you forget to check the result?") public func single() -> Result<Value, Error>? { let semaphore = dispatch_semaphore_create(0) var result: Result<Value, Error>? take(2).start { event in switch event { case let .Next(value): if result != nil { // Move into failure state after recieving another value. result = nil return } result = .Success(value) case let .Failed(error): result = .Failure(error) dispatch_semaphore_signal(semaphore) case .Completed, .Interrupted: dispatch_semaphore_signal(semaphore) } } dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) return result } /// Starts the producer, then blocks, waiting for the last value. @warn_unused_result(message="Did you forget to check the result?") public func last() -> Result<Value, Error>? { return takeLast(1).single() } /// Starts the producer, then blocks, waiting for completion. @warn_unused_result(message="Did you forget to check the result?") public func wait() -> Result<(), Error> { return then(SignalProducer<(), Error>(value: ())).last() ?? .Success(()) } }
mit
f36cf73cd499c4af3f8d3a28cf228e3a
41.895161
429
0.70972
3.817555
false
false
false
false
gcharita/XMLMapper
XMLMapper/Classes/Requests/SOAPEnvelope.swift
1
1273
// // SOAPEnvelope.swift // XMLMapper // // Created by Giorgos Charitakis on 02/10/2017. // import Foundation public class SOAPEnvelope: XMLMappable { public var nodeName: String! = "soap:Envelope" var soapEncodingStyle: String = "http://schemas.xmlsoap.org/soap/encoding/" var xmlnsSOAP: String = "http://schemas.xmlsoap.org/soap/envelope/" var soapBody: SOAPBody! var soapHeader: SOAPHeader? var nodesOrder: [String] = [ "soap:Header", "soap:Body", ] public init(soapMessage: SOAPMessage, soapInformation: SOAPInformation? = nil, soapVersion: SOAPVersion = .version1point1) { xmlnsSOAP = soapVersion.namespace soapEncodingStyle = soapVersion.encodingStyle self.soapBody = SOAPBody(soapMessage: soapMessage) if let soapInformation = soapInformation { self.soapHeader = SOAPHeader(soapInformation: soapInformation) } } required public init?(map: XMLMap) {} public func mapping(map: XMLMap) { soapEncodingStyle <- map.attributes["soap:encodingStyle"] xmlnsSOAP <- map.attributes["xmlns:soap"] soapHeader <- map["soap:Header"] soapBody <- map["soap:Body"] nodesOrder <- map.nodesOrder } }
mit
fee4e3b13fb77303728ac895c558919b
30.04878
128
0.655145
4.028481
false
false
false
false
alobanov/ALFormBuilder
Sources/FormBuilder/FomModelBuilder/sections/SectionItemBuilder.swift
1
982
// // SectionItemBuilder.swift // ALFormBuilder // // Created by Lobanov Aleksey on 29/10/2017. // Copyright © 2017 Lobanov Aleksey. All rights reserved. // import Foundation public protocol SectionItemBuilderProtocol { func define(identifier: String, header: String?, footer: String?) func result() -> FormItemCompositeProtocol } public class SectionItemBuilder: SectionItemBuilderProtocol { private var header: String? private var footer: String? private var identifier: String = "" private var cellType: FBUniversalCellProtocol = ALFB.Cells.emptyField public init() {} public func define(identifier: String, header: String?, footer: String?) { self.identifier = identifier self.header = header self.footer = footer } public func result() -> FormItemCompositeProtocol { let base = BaseFormComposite(identifier: identifier, level: .section) return SectionFormComposite(composite: base, header: header, footer: footer) } }
mit
b14951a4bc2cfd10c35dc5b0b96a968b
27.852941
80
0.734964
4.36
false
false
false
false
eckama11/air_quality
iOS/air_Quality/air_Quality/ViewController.swift
1
2333
// // ViewController.swift // Air_Quality // // Created by Amanda Eckhardt on 12/9/14. // Copyright (c) 2014 Amanda Eckhardt. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var dateLabel: UILabel! @IBOutlet var datePicker: UIDatePicker! @IBOutlet var usernameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged) var dateFormatterA = NSDateFormatter() dateFormatterA.dateFormat = "yyyy/MM/dd" var strDate = dateFormatterA.stringFromDate(datePicker.date) dateLabel.text = strDate prefs.setObject(strDate, forKey: "date") NSLog("d: %@",strDate); // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int NSLog("%i",isLoggedIn as Int) if (isLoggedIn != 1) { self.performSegueWithIdentifier("goto_login", sender: self) } else { //self.usernameLabel.text = prefs.objectForKey("deviceId") as NSString } } @IBAction func logouTapped(sender: UIButton) { let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() prefs.setInteger(0, forKey: "ISLOGGEDIN") self.performSegueWithIdentifier("goto_login", sender: self) } func datePickerChanged(datePicker:UIDatePicker) { let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy/MM/dd" dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") var strDate = dateFormatter.stringFromDate(datePicker.date) dateLabel.text = strDate prefs.setObject(strDate, forKey: "date") } }
gpl-3.0
c8040c88908650cbbfac88a6e6e6773f
35.453125
122
0.671667
4.96383
false
false
false
false
Reality-Virtually-Hackathon/Team-2
WorkspaceAR/VirtualNode.swift
1
3644
// // VirtualNode.swift // WorkspaceAR // // Created by Kenneth Friedman on 10/7/17. // Copyright © 2017 Apple. All rights reserved. // import Foundation import SceneKit import ARKit class VirtualNode: SCNNode { /// Use average of recent virtual object distances to avoid rapid changes in object scale. private var recentVirtualObjectDistances = [Float]() /// Resets the objects poisition smoothing. func reset() { recentVirtualObjectDistances.removeAll() } /** Set the object's position based on the provided position relative to the `cameraTransform`. If `smoothMovement` is true, the new position will be averaged with previous position to avoid large jumps. - Tag: VirtualObjectSetPosition */ func setPosition(_ newPosition: float3, relativeTo cameraTransform: matrix_float4x4, smoothMovement: Bool) { let cameraWorldPosition = cameraTransform.translation var positionOffsetFromCamera = newPosition - cameraWorldPosition // Limit the distance of the object from the camera to a maximum of 10 meters. if simd_length(positionOffsetFromCamera) > 10 { positionOffsetFromCamera = simd_normalize(positionOffsetFromCamera) positionOffsetFromCamera *= 10 } /* Compute the average distance of the object from the camera over the last ten updates. Notice that the distance is applied to the vector from the camera to the content, so it affects only the percieved distance to the object. Averaging does _not_ make the content "lag". */ if smoothMovement { let hitTestResultDistance = simd_length(positionOffsetFromCamera) // Add the latest position and keep up to 10 recent distances to smooth with. recentVirtualObjectDistances.append(hitTestResultDistance) recentVirtualObjectDistances = Array(recentVirtualObjectDistances.suffix(10)) let averageDistance = recentVirtualObjectDistances.average! let averagedDistancePosition = simd_normalize(positionOffsetFromCamera) * averageDistance simdPosition = cameraWorldPosition + averagedDistancePosition } else { simdPosition = cameraWorldPosition + positionOffsetFromCamera } } /// - Tag: AdjustOntoPlaneAnchor func adjustOntoPlaneAnchor(_ anchor: ARPlaneAnchor, using node: SCNNode) { // Get the object's position in the plane's coordinate system. let planePosition = node.convertPosition(position, from: parent) // Check that the object is not already on the plane. guard planePosition.y != 0 else { return } // Add 10% tolerance to the corners of the plane. let tolerance: Float = 0.1 let minX: Float = anchor.center.x - anchor.extent.x / 2 - anchor.extent.x * tolerance let maxX: Float = anchor.center.x + anchor.extent.x / 2 + anchor.extent.x * tolerance let minZ: Float = anchor.center.z - anchor.extent.z / 2 - anchor.extent.z * tolerance let maxZ: Float = anchor.center.z + anchor.extent.z / 2 + anchor.extent.z * tolerance guard (minX...maxX).contains(planePosition.x) && (minZ...maxZ).contains(planePosition.z) else { return } // Move onto the plane if it is near it (within 5 centimeters). let verticalAllowance: Float = 0.05 let epsilon: Float = 0.001 // Do not update if the difference is less than 1 mm. let distanceToPlane = abs(planePosition.y) if distanceToPlane > epsilon && distanceToPlane < verticalAllowance { SCNTransaction.begin() SCNTransaction.animationDuration = CFTimeInterval(distanceToPlane * 500) // Move 2 mm per second. SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) position.y = anchor.transform.columns.3.y SCNTransaction.commit() } } }
mit
4ae16312bdf7cfcc033d793e076d583b
38.182796
109
0.751853
4.05228
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/Tab Navigation/ReaderTabViewController.swift
1
5744
import UIKit import Gridicons class ReaderTabViewController: UIViewController { private let viewModel: ReaderTabViewModel private let makeReaderTabView: (ReaderTabViewModel) -> ReaderTabView private lazy var readerTabView: ReaderTabView = { return makeReaderTabView(viewModel) }() private let searchButton: SpotlightableButton = SpotlightableButton(type: .custom) init(viewModel: ReaderTabViewModel, readerTabViewFactory: @escaping (ReaderTabViewModel) -> ReaderTabView) { self.viewModel = viewModel self.makeReaderTabView = readerTabViewFactory super.init(nibName: nil, bundle: nil) title = ReaderTabConstants.title setupNavigationButtons() ReaderTabViewController.configureRestoration(on: self) ReaderCardService().clean() viewModel.filterTapped = { [weak self] (fromView, completion) in guard let self = self else { return } self.viewModel.presentFilter(from: self, sourceView: fromView, completion: { [weak self] topic in self?.dismiss(animated: true, completion: nil) completion(topic) }) } NotificationCenter.default.addObserver(self, selector: #selector(defaultAccountDidChange(_:)), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil) } required init?(coder: NSCoder) { fatalError(ReaderTabConstants.storyBoardInitError) } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) ReaderTracker.shared.start(.main) if AppConfiguration.showsWhatIsNew { WPTabBarController.sharedInstance()?.presentWhatIsNew(on: self) } searchButton.shouldShowSpotlight = QuickStartTourGuide.shared.isCurrentElement(.readerSearch) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) ReaderTracker.shared.stop(.main) } func setupNavigationButtons() { // Settings Button let settingsButton = UIBarButtonItem(image: UIImage.gridicon(.cog), style: .plain, target: self, action: #selector(didTapSettingsButton)) settingsButton.accessibilityIdentifier = ReaderTabConstants.settingsButtonIdentifier // Search Button searchButton.spotlightOffset = UIOffset(horizontal: 20, vertical: -10) searchButton.setImage(.gridicon(.search), for: .normal) searchButton.addTarget(self, action: #selector(didTapSearchButton), for: .touchUpInside) searchButton.accessibilityIdentifier = ReaderTabConstants.searchButtonAccessibilityIdentifier let searchBarButton = UIBarButtonItem(customView: searchButton) navigationItem.rightBarButtonItems = [searchBarButton, settingsButton] } override func loadView() { view = readerTabView navigationItem.largeTitleDisplayMode = .always navigationController?.navigationBar.prefersLargeTitles = true } @objc func willEnterForeground() { guard isViewOnScreen() else { return } ReaderTracker.shared.start(.main) } } // MARK: - Navigation Buttons extension ReaderTabViewController { @objc private func didTapSettingsButton() { viewModel.presentManage(from: self) } @objc private func didTapSearchButton() { viewModel.navigateToSearch() } } // MARK: - State Restoration extension ReaderTabViewController: UIViewControllerRestoration { static func configureRestoration(on instance: ReaderTabViewController) { instance.restorationIdentifier = ReaderTabConstants.restorationIdentifier instance.restorationClass = ReaderTabViewController.self } static let encodedIndexKey = ReaderTabConstants.encodedIndexKey static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { let index = Int(coder.decodeInt32(forKey: ReaderTabViewController.encodedIndexKey)) let controller = WPTabBarController.sharedInstance().readerTabViewController controller?.setStartIndex(index) return controller } override func encodeRestorableState(with coder: NSCoder) { coder.encode(viewModel.selectedIndex, forKey: ReaderTabViewController.encodedIndexKey) } func setStartIndex(_ index: Int) { viewModel.selectedIndex = index } } // MARK: - Notifications extension ReaderTabViewController { // Ensure that topics and sites are synced when account changes @objc private func defaultAccountDidChange(_ notification: Foundation.Notification) { loadView() } } // MARK: - Constants extension ReaderTabViewController { private enum ReaderTabConstants { static let title = NSLocalizedString("Reader", comment: "The default title of the Reader") static let settingsButtonIdentifier = "ReaderSettingsButton" static let searchButtonAccessibilityIdentifier = "ReaderSearchBarButton" static let storyBoardInitError = "Storyboard instantiation not supported" static let restorationIdentifier = "WPReaderTabControllerRestorationID" static let encodedIndexKey = "WPReaderTabControllerIndexRestorationKey" } }
gpl-2.0
09b7f3be666011bb4ff346e47e32739d
33.812121
185
0.697249
5.620352
false
false
false
false
kenada/advent-of-code
src/2015/day 13.swift
1
4491
// // day 13.swift // Advent of Code 2015 // // Copyright © 2017 Randy Eckenrode // // 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 AdventSupport import Foundation typealias Person = String func happiness(of people: [Person], withRelationships lookup: [Pair<Person>: Int]) -> Int { let pairings = pairs(of: people) return pairings.reduce(0) { $0 + (lookup[$1] ?? 0) } } func pairs(of people: [Person]) -> [Pair<Person>] { guard people.count > 1 else { return [] } var result = zip(people, people[1..<people.count]).map { Pair.init($0.0, $0.1) } result.append(Pair(people.last!, people.first!)) result.append(contentsOf: result.lazy.map { Pair($0.second, $0.first) }) return result } private let regex = try! NSRegularExpression(pattern: "([^ ]+) would (gain|lose) ([\\d]+) happiness units by sitting next to ([^.]+)\\.") func parsed(ofDay13 input: String) -> (Pair<Person>, Int)? { let nsInput = input as NSString guard let match = regex.firstMatch(in: input, options: [], range: NSMakeRange(0, nsInput.length)) else { return nil } let gainOrLose = nsInput.substring(with: match.range(at: 2)) guard gainOrLose == "gain" || gainOrLose == "lose" else { return nil } guard let happiness = Int(nsInput.substring(with: match.range(at: 3))) else { return nil } return (Pair(nsInput.substring(with: match.range(at: 1)), nsInput.substring(with: match.range(at: 4))), happiness * (gainOrLose == "gain" ? 1 : -1)) } // MARK: - Solution class Day13: Solution { required init() {} var name = "Day 13" func part1(input: String) { let (people, mapping) = Day13.reading(input: input) Day13.solution(withTable: people, dispositions: mapping, label: "part 1") } func part2(input: String) { var (people, mapping) = Day13.reading(input: input) people.forEach { person in mapping[Pair("Me", person)] = 0 mapping[Pair(person, "Me")] = 0 } people.append("Me") Day13.solution(withTable: people, dispositions: mapping, label: "part 2") } private static func reading(input: String) -> ([Person], [Pair<Person>: Int]) { let lines = input.lines var people: Set<Person> = [] var mapping: [Pair<Person>: Int] = [:] do { let parsedLines = lines.flatMap { line -> (Pair<Person>, Int)? in let parsedLine = parsed(ofDay13: line) _ = parsedLine.map { people.insert($0.0.first) people.insert($0.0.second) } return parsedLine } parsedLines.forEach { let (pairing, happiness) = $0; return mapping[pairing] = happiness } } return (Array(people), mapping) } private static func solution(withTable people: [Person], dispositions mapping: [Pair<Person>: Int], label: String) { let permutations = people.permutations var totalHappiness = Int.min permutations.forEach { permutation in let permHappiness = happiness(of: permutation, withRelationships: mapping) if permHappiness > totalHappiness { totalHappiness = permHappiness } } print("The total change in happiness for the best seating arrangement in \(label) is: \(totalHappiness)") } }
mit
443db2a6052ce51c88334e36b049aabd
34.634921
121
0.634298
4.0161
false
false
false
false
zmeyc/GRDB.swift
Tests/GRDBTests/FTS5CustomTokenizerTests.swift
1
17590
#if SQLITE_ENABLE_FTS5 import XCTest import Foundation #if USING_SQLCIPHER import GRDBCipher #elseif USING_CUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif // A custom tokenizer that ignores some tokens private final class StopWordsTokenizer : FTS5CustomTokenizer { static let name = "stopWords" let wrappedTokenizer: FTS5Tokenizer let ignoredTokens: [String] init(db: Database, arguments: [String]) throws { if arguments.isEmpty { wrappedTokenizer = try db.makeTokenizer(.unicode61()) } else { wrappedTokenizer = try db.makeTokenizer(FTS5TokenizerDescriptor(components: arguments)) } // TODO: find a way to provide stop words through arguments ignoredTokens = ["bar"] } deinit { // TODO: test that deinit is called } func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { // The way we implement stop words is by letting wrappedTokenizer do its // job but intercepting its tokens before they feed SQLite. // // `tokenCallback` is @convention(c). This requires a little setup in // order to transfer context. struct CustomContext { let ignoredTokens: [String] let context: UnsafeMutableRawPointer let tokenCallback: FTS5TokenCallback } var customContext = CustomContext(ignoredTokens: ignoredTokens, context: context!, tokenCallback: tokenCallback) return withUnsafeMutablePointer(to: &customContext) { customContextPointer in // Invoke wrappedTokenizer, but intercept raw tokens return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in // Extract context let customContext = customContextPointer!.assumingMemoryBound(to: CustomContext.self).pointee // Extract token guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else { return 0 // SQLITE_OK } // Ignore stop words if customContext.ignoredTokens.contains(token) { return 0 // SQLITE_OK } // Notify token return customContext.tokenCallback(customContext.context, flags, pToken, nToken, iStart, iEnd) } } } } // A custom tokenizer that converts tokens to NFKC so that "fi" can match "fi" (U+FB01: LATIN SMALL LIGATURE FI) private final class NFKCTokenizer : FTS5CustomTokenizer { static let name = "nfkc" let wrappedTokenizer: FTS5Tokenizer init(db: Database, arguments: [String]) throws { if arguments.isEmpty { wrappedTokenizer = try db.makeTokenizer(.unicode61()) } else { wrappedTokenizer = try db.makeTokenizer(FTS5TokenizerDescriptor(components: arguments)) } } deinit { // TODO: test that deinit is called } func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { // The way we implement NFKC conversion is by letting wrappedTokenizer // do its job, but intercepting its tokens before they feed SQLite. // // `tokenCallback` is @convention(c). This requires a little setup in // order to transfer context. struct CustomContext { let context: UnsafeMutableRawPointer let tokenCallback: FTS5TokenCallback } var customContext = CustomContext(context: context!, tokenCallback: tokenCallback) return withUnsafeMutablePointer(to: &customContext) { customContextPointer in // Invoke wrappedTokenizer, but intercept raw tokens return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in // Extract context let customContext = customContextPointer!.assumingMemoryBound(to: CustomContext.self).pointee // Extract token guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else { return 0 // SQLITE_OK } // Convert to NFKC let nfkc = token.precomposedStringWithCompatibilityMapping // Notify NFKC token return ContiguousArray(nfkc.utf8).withUnsafeBufferPointer { buffer in guard let addr = buffer.baseAddress else { return 0 // SQLITE_OK } let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) let nToken = Int32(buffer.count) return customContext.tokenCallback(customContext.context, flags, pToken, nToken, iStart, iEnd) } } } } } // A custom tokenizer that defines synonyms private final class SynonymsTokenizer : FTS5CustomTokenizer { static let name = "synonyms" let wrappedTokenizer: FTS5Tokenizer let synonyms: [Set<String>] init(db: Database, arguments: [String]) throws { if arguments.isEmpty { wrappedTokenizer = try db.makeTokenizer(.unicode61()) } else { wrappedTokenizer = try db.makeTokenizer(FTS5TokenizerDescriptor(components: arguments)) } synonyms = [["first", "1st"]] } deinit { // TODO: test that deinit is called } func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { // Don't look for synonyms when tokenizing queries, as advised by // https://www.sqlite.org/fts5.html#synonym_support if tokenization.contains(.query) { return wrappedTokenizer.tokenize(context: context, tokenization: tokenization, pText: pText, nText: nText, tokenCallback: tokenCallback) } // The way we implement synonyms support is by letting wrappedTokenizer // do its job, but intercepting its tokens before they feed SQLite. // // `tokenCallback` is @convention(c). This requires a little setup in // order to transfer context. struct CustomContext { let synonyms: [Set<String>] let context: UnsafeMutableRawPointer let tokenCallback: FTS5TokenCallback } var customContext = CustomContext(synonyms: synonyms, context: context!, tokenCallback: tokenCallback) return withUnsafeMutablePointer(to: &customContext) { customContextPointer in // Invoke wrappedTokenizer, but intercept raw tokens return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in // Extract context let customContext = customContextPointer!.assumingMemoryBound(to: CustomContext.self).pointee // Extract token guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else { return 0 // SQLITE_OK } guard let synonyms = customContext.synonyms.first(where: { $0.contains(token) }) else { // No synonym return customContext.tokenCallback(customContext.context, flags, pToken, nToken, iStart, iEnd) } // Notify each synonym for (index, synonym) in synonyms.enumerated() { let code = ContiguousArray(synonym.utf8).withUnsafeBufferPointer { buffer -> Int32 in guard let addr = buffer.baseAddress else { return 0 // SQLITE_OK } let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) let nToken = Int32(buffer.count) // Set FTS5_TOKEN_COLOCATED for all but first token let synonymFlags = (index == 0) ? flags : flags | 1 // 1: FTS5_TOKEN_COLOCATED return customContext.tokenCallback(customContext.context, synonymFlags, pToken, nToken, iStart, iEnd) } if code != 0 { // SQLITE_OK return code } } return 0 // SQLITE_OK } } } } class FTS5CustomTokenizerTests: GRDBTestCase { func testStopWordsTokenizerDatabaseQueue() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(tokenizer: StopWordsTokenizer.self) try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS5()) { t in t.tokenizer = StopWordsTokenizer.tokenizerDescriptor() t.column("content") } try db.execute("INSERT INTO documents VALUES (?)", arguments: ["foo bar"]) try db.execute("INSERT INTO documents VALUES (?)", arguments: ["foo baz"]) // foo is not ignored XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["foo"]), 2) // bar is ignored XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["bar"]), 0) // bar is ignored in queries too: the "foo bar baz" phrase matches the "foo baz" content XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["\"foo bar baz\""]), 1) } } func testStopWordsTokenizerDatabasePool() throws { let dbPool = try makeDatabaseQueue() dbPool.add(tokenizer: StopWordsTokenizer.self) try dbPool.write { db in try db.create(virtualTable: "documents", using: FTS5()) { t in t.tokenizer = StopWordsTokenizer.tokenizerDescriptor() t.column("content") } try db.execute("INSERT INTO documents VALUES (?)", arguments: ["foo bar"]) try db.execute("INSERT INTO documents VALUES (?)", arguments: ["foo baz"]) // foo is not ignored XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["foo"]), 2) // bar is ignored XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["bar"]), 0) // bar is ignored in queries too: the "foo bar baz" phrase matches the "foo baz" content XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["\"foo bar baz\""]), 1) } try dbPool.read { db in // foo is not ignored XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["foo"]), 2) // bar is ignored XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["bar"]), 0) // bar is ignored in queries too: the "foo bar baz" phrase matches the "foo baz" content XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["\"foo bar baz\""]), 1) } } func testNFKCTokenizer() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(tokenizer: NFKCTokenizer.self) // Without NFKC conversion try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS5()) { t in t.tokenizer = .unicode61() t.column("content") } try db.execute("INSERT INTO documents VALUES (?)", arguments: ["aimé\u{FB01}"]) // U+FB01: LATIN SMALL LIGATURE FI XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aimé\u{FB01}"]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aimefi"]), 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aim\u{00E9}fi"]), 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aime\u{0301}\u{FB01}"]), 1) try db.drop(table: "documents") } // With NFKC conversion wrapping unicode61 (the default) try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS5()) { t in t.tokenizer = NFKCTokenizer.tokenizerDescriptor() t.column("content") } try db.execute("INSERT INTO documents VALUES (?)", arguments: ["aimé\u{FB01}"]) // U+FB01: LATIN SMALL LIGATURE FI XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aimé\u{FB01}"]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aimefi"]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aim\u{00E9}fi"]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aime\u{0301}\u{FB01}"]), 1) try db.drop(table: "documents") } // With NFKC conversion wrapping ascii try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS5()) { t in let ascii = FTS5TokenizerDescriptor.ascii() t.tokenizer = NFKCTokenizer.tokenizerDescriptor(arguments: ascii.components) t.column("content") } try db.execute("INSERT INTO documents VALUES (?)", arguments: ["aimé\u{FB01}"]) // U+FB01: LATIN SMALL LIGATURE FI XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aimé\u{FB01}"]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aimefi"]), 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aim\u{00E9}fi"]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["aime\u{0301}\u{FB01}"]), 1) try db.drop(table: "documents") } } func testSynonymTokenizer() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(tokenizer: SynonymsTokenizer.self) try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS5()) { t in t.tokenizer = SynonymsTokenizer.tokenizerDescriptor() t.column("content") } try db.execute("INSERT INTO documents VALUES (?)", arguments: ["first foo"]) try db.execute("INSERT INTO documents VALUES (?)", arguments: ["1st bar"]) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["first"]), 2) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["1st"]), 2) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["\"first foo\""]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["\"1st foo\""]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["\"first bar\""]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["\"1st bar\""]), 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["fi*"]), 2) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["1s*"]), 2) } } } #endif
mit
688bc0da17c6f1ac382fa5b5f2d5e0cb
51.172107
196
0.607724
4.842192
false
false
false
false
tylerbrockett/cse394-principles-of-mobile-applications
final-project/Appa/NearbyFoodEntryViewController.swift
1
2191
/* * @authors Tyler Brockett, Shikha Mehta, Tam Le * @course ASU CSE 394 * @project Group Project * @version April 15, 2016 * @project-description Allows users to track Geocaches * @class-name NearbyFoodEntryViewController.swift * @class-description Displays MapView with annotations for the Geocache and the restaurant */ import MapKit import UIKit import Foundation class NearbyFoodEntryViewController: UIViewController { var restaurant:Restaurant = Restaurant() var geocacheLocation:CLLocation = CLLocation() @IBOutlet weak var restaurantName: UILabel! @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { restaurantName.text = restaurant.name let restLat:Double = restaurant.latitude let restLon:Double = restaurant.longitude let geoLat:Double = geocacheLocation.coordinate.latitude let geoLon:Double = geocacheLocation.coordinate.longitude let distance:Double = geocacheLocation.distanceFromLocation(CLLocation(latitude: restaurant.latitude, longitude: restaurant.longitude)) let middlePoint = CLLocationCoordinate2D(latitude: ((restLat + geoLat)/2.0), longitude: ((restLon + geoLon)/2.0)) let region: MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(middlePoint, 0.5 * distance, 0.5 * distance) mapView.setRegion(region, animated: true) // Set annotations let restCoord = CLLocationCoordinate2D(latitude: restLat, longitude: restLon) let geoCoord = CLLocationCoordinate2D(latitude: geoLat, longitude: geoLon) // Add Restaurant Annotation let restAnnotation = MKPointAnnotation() restAnnotation.coordinate = restCoord restAnnotation.title = restaurant.name self.mapView.addAnnotation(restAnnotation) // Add Geocache Annotation let geoAnnotation = MKPointAnnotation() geoAnnotation.coordinate = geoCoord geoAnnotation.title = "Geocache" self.mapView.addAnnotation(geoAnnotation) } }
mit
2d4fc631528ca81b38cfc9236b4aad66
38.836364
143
0.675034
5.002283
false
false
false
false
powerytg/Accented
Accented/UI/Details/DetailFullScreenImageViewController.swift
1
3006
// // DetailFullScreenImageViewController.swift // Accented // // Detail page full screen image view controller // This page allows zooming and pinching on the image // // Created by You, Tiangong on 6/1/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class DetailFullScreenImageViewController: UIViewController, DetailLightBoxAnimation { // Image view private var imageView : InteractiveImageView? // Photo model var photo : PhotoModel // Back button private var backButton = UIButton(type: .custom) init(photo : PhotoModel) { self.photo = photo super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Image view if let imageUrl = PhotoRenderer.preferredImageUrl(photo) { imageView = InteractiveImageView(imageUrl: imageUrl, frame: view.bounds) self.view.addSubview(imageView!) } // Back button self.view.addSubview(backButton) backButton.setImage(UIImage(named: "DetailBackButton"), for: UIControlState()) backButton.addTarget(self, action: #selector(backButtonDidTap(_:)), for: .touchUpInside) backButton.sizeToFit() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() imageView?.frame = self.view.bounds var f = backButton.frame f.origin.x = 10 f.origin.y = 30 backButton.frame = f } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { [weak self] (context) in self?.imageView?.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) self?.imageView?.transitionToSize(size) }, completion: nil) } // MARK: - Events @objc private func backButtonDidTap(_ sender : UIButton) { self.presentingViewController?.dismiss(animated: true, completion: nil) } // MARK: - UIScrollViewDelegate func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } // MARK: - Lightbox animation func lightBoxTransitionWillBegin() { // Initially hide all the conent view.isHidden = true } func lightboxTransitionDidFinish() { view.isHidden = false self.view.backgroundColor = UIColor.black } func performLightBoxTransition() { // Do nothing } func desitinationRectForSelectedLightBoxPhoto(_ photo: PhotoModel) -> CGRect { return self.view.bounds } }
mit
41ae74af250061bebef459e133f85ee4
28.174757
112
0.638602
4.92623
false
false
false
false
Dhvl-Golakiya/ImageAdjusts
Example/ImageAdjusts/ImageAdjustView.swift
1
25647
// // AdjustEditorView.swift // Flippy // // Created by Infyom on 05/08/17. // Copyright © 2017 Infyom. All rights reserved. // import UIKit class ImageAdjustView : UIView, UIGestureRecognizerDelegate { @IBOutlet var screenSortView: UIView! @IBOutlet var mainView: UIView! @IBOutlet var sliderView: UIView! @IBOutlet var backImageView: UIImageView! @IBOutlet var colorImageView: UIImageView! @IBOutlet var layoutStackView: UIStackView! @IBOutlet var effectSlider: UISlider! var selectedShade : Shades? var viewFrame : CGRect! var mainImage : UIImage! var tempImage : UIImage! var selectSaveImageCallback : ((UIImage) -> Void)? var selectCancleImageCallback : ((Bool) -> Void)? var brightnessValue : CGFloat = 0 var saturationVlue : CGFloat = 1.0 var contrastValue : CGFloat = 1.0 var sharpnessValue : CGFloat = 0.40 var warmthValue : CGFloat = 157.67 var exposureValue : CGFloat = 0.50 var highlightValue : CGFloat = 1.0 var shadowsValue : CGFloat = 0.0 var vibranceValue : CGFloat = 0.0 var tintValue : CGFloat = 1.0 var fadeValue : CGFloat = 0.0 var shadesArray = [Shades.Brightness, Shades.Saturation, Shades.Contrast, Shades.Sharpness, Shades.Warmth, Shades.Exposure, Shades.Vibrance, Shades.Highlights, Shades.Shadows, Shades.Tint, Shades.Fade] override func awakeFromNib() { super.awakeFromNib() self.sliderView.transform = CGAffineTransform(scaleX: 0.0, y: 0.0) self.addGestures() } static func create(image : UIImage) -> ImageAdjustView { let selectView = Bundle.main.loadNibNamed("ImageAdjustView", owner: self, options: nil)?[0] as! ImageAdjustView let window = UIApplication.shared.keyWindow if #available(iOS 11.0, *) { let topPadding = window?.safeAreaInsets.top let bottomPadding = window?.safeAreaInsets.bottom selectView.viewFrame = CGRect(x: 0, y: topPadding!, width: getScreenWidth(), height: getScreenHeight() - (topPadding! + bottomPadding!)) } else { selectView.viewFrame = CGRect(x: 0, y: 0, width: getScreenWidth(), height: getScreenHeight()) } selectView.mainImage = image selectView.didInit() if #available(iOS 11.0, *) { let topPadding = window?.safeAreaInsets.top let bottomPadding = window?.safeAreaInsets.bottom selectView.frame = CGRect(x: 0, y: getScreenHeight(), width: getScreenWidth(), height: getScreenHeight() - (topPadding! + bottomPadding!)) } else { selectView.frame = CGRect(x: 0, y: getScreenHeight(), width: getScreenWidth(), height: getScreenHeight()) } window!.addSubview(selectView) UIView.animate(withDuration: 0.35) { if #available(iOS 11.0, *) { let topPadding = window?.safeAreaInsets.top let bottomPadding = window?.safeAreaInsets.bottom selectView.frame = CGRect(x: 0, y: topPadding!, width: getScreenWidth(), height: getScreenHeight() - (topPadding! + bottomPadding!)) } else { selectView.frame = CGRect(x: 0, y: 0, width: getScreenWidth(), height: getScreenHeight()) } selectView.setAllData() } return selectView } func didInit() { self.frame = self.viewFrame } func addGestures() { let taptouchGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGesture)) taptouchGesture.minimumPressDuration = 0.0 taptouchGesture.delegate = self self.backImageView.addGestureRecognizer(taptouchGesture) } @objc func longPressGesture(pinchGesture: UILongPressGestureRecognizer) { if(pinchGesture.state == .began) { self.colorImageView.isHidden = false } if (pinchGesture.state == .changed) { self.colorImageView.isHidden = false } if pinchGesture.state == .ended { self.colorImageView.isHidden = true } } func setAllData() { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(400)) { UIView.animate(withDuration: 0.35, animations: { self.backImageView.image = self.mainImage self.tempImage = self.mainImage print(self.mainView.frame) print(self.mainView.bounds) let frame = self.getSize(imageSize : self.mainImage.size , frameSize: self.mainView.frame.size) print(frame) self.screenSortView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) self.screenSortView.center = CGPoint(x : self.mainView.getWidth / 2 , y: self.mainView.getHeight / 2) self.backImageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) self.colorImageView.frame = CGRect(x: 0, y: 0, width: frame.width , height: frame.height) self.colorImageView.image = self.mainImage }, completion: { finished in self.setEffecList() }) } } func setEffecList() { UIView.animate(withDuration: 0.35, animations: { var count = -1 for layoutData in self.shadesArray { count += 1 let layoutView = AdjustImageView.create(frame : CGRect(x: 0, y: 0, width: self.layoutStackView.getHeight , height: self.layoutStackView.getHeight), effectCase: layoutData) layoutView.tag = count layoutView.frame = CGRect(x: 0, y: 0, width: self.layoutStackView.getHeight , height: self.layoutStackView.getHeight) layoutView.selectEffectCallback = { effect in self.setSlider(effecName : effect) } self.layoutStackView.addArrangedSubview(layoutView) layoutView.setLayoutView() } }, completion: { finished in }) } func getSize(imageSize: CGSize, frameSize: CGSize) -> CGSize { if imageSize.width >= frameSize.width{ let newWidth = frameSize.width / imageSize.width let newSize = CGSize(width: imageSize.width * newWidth , height: imageSize.height * newWidth) if newSize.height >= frameSize.height{ let newHeight = frameSize.height / newSize.height return CGSize(width: newSize.width * newHeight , height: newSize.height * newHeight) }else{ return newSize } } else { let newHeight = frameSize.height / imageSize.height let newSize = CGSize(width: imageSize.width * newHeight , height: imageSize.height * newHeight) if newSize.width >= frameSize.width { let newWidth = frameSize.width / newSize.width return CGSize(width: newSize.width * newWidth , height: newSize.height * newWidth) }else{ return newSize } } } func setSliderValue(float: Float) { if self.selectedShade == .Brightness { let ciContext = CIContext(options: nil) brightnessValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil{ coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let filter = CIFilter(name: "CIColorControls") filter?.setValue(float, forKey: kCIInputBrightnessKey) filter?.setValue(coreImage, forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Saturation { let ciContext = CIContext(options: nil) saturationVlue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil{ coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let filter = CIFilter(name: "CIColorControls") filter?.setValue(float, forKey: kCIInputSaturationKey) filter?.setValue(coreImage, forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Contrast { let ciContext = CIContext(options: nil) contrastValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil{ coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let filter = CIFilter(name: "CIColorControls") filter?.setValue(float, forKey: kCIInputContrastKey) filter?.setValue(coreImage, forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage{ let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Sharpness { let ciContext = CIContext(options: nil) sharpnessValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil { coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let filter = CIFilter(name: "CISharpenLuminance") filter?.setValue(float, forKey: kCIInputSharpnessKey) filter?.setValue(coreImage, forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage{ let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Warmth { let ciContext = CIContext(options: nil) warmthValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil { coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } var number = CGFloat(float) if number > 157.9 { let minus = 172 - number number = 165 + minus } else { let minus = 157.9 - number number = 130 + minus } let vector0 = CIVector(x: 4000, y: number) let vector1 = CIVector(x: 5000, y: number) let filter = CIFilter(name: "CITemperatureAndTint") filter?.setValue(coreImage, forKey: kCIInputImageKey) filter?.setValue(vector0, forKey: "inputNeutral") filter?.setValue(vector1, forKey: "inputTargetNeutral") if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Exposure { let ciContext = CIContext(options: nil) exposureValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil { coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let filter = CIFilter(name: "CIExposureAdjust") filter?.setValue(float, forKey: kCIInputEVKey) filter?.setValue(coreImage, forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Vibrance { let ciContext = CIContext(options: nil) vibranceValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil { coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let filter = CIFilter(name: "CIVibrance") filter?.setValue(float, forKey: "inputAmount") filter?.setValue(coreImage, forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Highlights { let ciContext = CIContext(options: nil) highlightValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil { coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let filter = CIFilter(name: "CIHighlightShadowAdjust") filter?.setValue(float, forKey: "inputHighlightAmount") filter?.setValue(coreImage, forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Shadows { let ciContext = CIContext(options: nil) shadowsValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil{ coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let filter = CIFilter(name: "CIHighlightShadowAdjust") filter?.setValue(float, forKey: "inputShadowAmount") filter?.setValue(coreImage, forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage{ let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Tint { let ciContext = CIContext(options: nil) tintValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil { coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let vector0 = CIVector(x: 4000, y: CGFloat(float)) let filter = CIFilter(name: "CITemperatureAndTint") filter?.setValue(coreImage, forKey: kCIInputImageKey) filter?.setValue(vector0, forKey: "inputNeutral") if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } else { print("image filtering failed") } } if self.selectedShade == .Fade { let ciContext = CIContext(options: nil) fadeValue = CGFloat(float) print(float) var coreImage = CIImage() if mainImage.cgImage != nil { coreImage = CIImage(cgImage: mainImage.cgImage!) } else { coreImage = mainImage.ciImage! } let filter = CIFilter(name: "CIPhotoEffectFade") filter?.setValue(float, forKey: "inputImage") filter?.setValue(coreImage, forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { let cgimgresult = ciContext.createCGImage(output, from: output.extent) let image = UIImage(cgImage: cgimgresult!) let filter = CIFilter(name: "CIHighlightShadowAdjust") filter?.setValue(float, forKey: "inputShadowAmount") filter?.setValue(CIImage(cgImage: image.cgImage!), forKey: kCIInputImageKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { let cgimgresult = ciContext.createCGImage(output, from: output.extent) self.backImageView.image = UIImage(cgImage: cgimgresult!) } } else { print("image filtering failed") } } } func setSlider(effecName : Shades) { self.sliderView.transform = CGAffineTransform(scaleX: 0.0, y: 0.0) self.backImageView.image = tempImage UIView.animate(withDuration: 0.35) { self.sliderView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) if effecName == .Brightness { self.effectSlider.isHidden = false self.effectSlider.minimumValue = -0.5 self.effectSlider.maximumValue = 0.5 self.effectSlider.value = Float(self.brightnessValue) self.selectedShade = .Brightness self.setSliderValue(float : Float(self.brightnessValue)) } if effecName == .Saturation { self.effectSlider.isHidden = false self.effectSlider.minimumValue = 0 self.effectSlider.maximumValue = 2 self.effectSlider.value = Float(self.saturationVlue) self.selectedShade = .Saturation self.setSliderValue(float : Float(self.saturationVlue)) } if effecName == .Contrast { self.effectSlider.isHidden = false self.effectSlider.minimumValue = 0.5 self.effectSlider.maximumValue = 1.5 self.effectSlider.value = Float(self.contrastValue) self.selectedShade = .Contrast self.setSliderValue(float : Float(self.contrastValue)) } if effecName == .Sharpness { self.effectSlider.isHidden = false self.effectSlider.minimumValue = -1.2 self.effectSlider.maximumValue = 2.0 self.effectSlider.value = Float(self.sharpnessValue) self.selectedShade = .Sharpness self.setSliderValue(float : Float(self.sharpnessValue)) } if effecName == .Warmth { self.effectSlider.isHidden = false self.effectSlider.minimumValue = 145 self.effectSlider.maximumValue = 172 self.effectSlider.value = Float(self.warmthValue) self.selectedShade = .Warmth self.setSliderValue(float : Float(self.warmthValue)) } if effecName == .Exposure { self.effectSlider.isHidden = false self.effectSlider.minimumValue = -2 self.effectSlider.maximumValue = 2 self.effectSlider.value = Float(self.exposureValue) self.selectedShade = .Exposure self.setSliderValue(float : Float(self.exposureValue)) } if effecName == .Vibrance { self.effectSlider.isHidden = false self.effectSlider.minimumValue = -1 self.effectSlider.maximumValue = 1 self.effectSlider.value = Float(self.vibranceValue) self.selectedShade = .Vibrance self.setSliderValue(float : Float(self.vibranceValue)) } if effecName == .Highlights { self.effectSlider.isHidden = false self.effectSlider.minimumValue = 0 self.effectSlider.maximumValue = 2 self.effectSlider.value = Float(self.highlightValue) self.selectedShade = .Highlights self.setSliderValue(float : Float(self.highlightValue)) } if effecName == .Shadows { self.effectSlider.isHidden = false self.effectSlider.minimumValue = -1 self.effectSlider.maximumValue = 1 self.effectSlider.value = Float(self.shadowsValue) self.selectedShade = .Shadows self.setSliderValue(float : Float(self.shadowsValue)) } if effecName == .Tint { self.effectSlider.isHidden = false self.effectSlider.minimumValue = -170 self.effectSlider.maximumValue = 95 self.effectSlider.value = Float(self.tintValue) self.selectedShade = .Tint self.setSliderValue(float : Float(self.tintValue)) } if effecName == .Fade { self.effectSlider.isHidden = false self.effectSlider.minimumValue = -1 self.effectSlider.maximumValue = 1 self.effectSlider.value = Float(self.fadeValue) self.selectedShade = .Fade self.setSliderValue(float : Float(self.fadeValue)) } } } @IBAction func onEffectApply(_ sender: Any) { for view in layoutStackView.subviews{ if let View = view as? AdjustImageView { View.setDefaultView() } } UIView.animate(withDuration: 0.35, animations: { self.sliderView.alpha = 0.0 }, completion: { finished in self.sliderView.transform = CGAffineTransform(scaleX: 0.0, y: 0.0) self.sliderView.alpha = 1.0 }) self.mainImage = self.backImageView.image } @IBAction func onCancleClick(_ sender: Any) { UIView.animate(withDuration: 0.35, animations: { self.frame = CGRect(x: 0, y: getScreenHeight(), width: getScreenWidth(), height: getScreenHeight()) }, completion: { finished in self.removeFromSuperview() }) } @IBAction func onSaveClick(_ sender: Any) { selectSaveImageCallback!(self.backImageView.image!) UIView.animate(withDuration: 0.35, animations: { self.frame = CGRect(x: 0, y: getScreenHeight(), width: getScreenWidth(), height: getScreenHeight()) }, completion: { finished in self.removeFromSuperview() }) } @IBAction func slider(_ sender: UISlider) { self.setSliderValue(float : sender.value) } } enum Shades : String { case Brightness = "Brightness" case Saturation = "Saturation" case Contrast = "Contrast" case Sharpness = "Sharpness" case Warmth = "Warmth" case Exposure = "Exposure" case Vibrance = "Vibrance" case Highlights = "Highlights" case Shadows = "Shadows" case Tint = "Tint" case Fade = "Fade" } extension UIView { // Get width of View public var getWidth : CGFloat { return frame.width } // Get height of view public var getHeight : CGFloat { return frame.height } // Get Origin.x public var startX : CGFloat { return frame.origin.x } // Get Origin.y public var startY : CGFloat { return frame.origin.y } }
mit
746cb87f75c13ceebb06d2ec662e3aa6
40.0336
205
0.563012
4.93762
false
false
false
false
forgot/FAAlertController
Example/BaseViewController.swift
1
12874
// // ViewController.swift // FAAlertController // // Created by Jesse Cox on 9/24/16. // Copyright © 2016 Apprhythmia LLC. All rights reserved. // import UIKit import FAAlertController class BaseViewController: UIViewController, FAAlertControllerDelegate { var _title: String { return "Hello! This is where the title goes! Amazing, right?" } var _message: String { return "This is a message. You can put lots of words here, and then show them to your users. Its really exciting." } var _numberOfActions = 4 var _numberOfTextFields = 2 var _preferredActionIndex = 1 var alertTitle: String? var alertMessage: String? var appearanceStyle: FAAlertControllerAppearanceStyle { return .default } var faControllerAppearanceDelegate: FAAlertControllerAppearanceDelegate? var action1Title = "Awesome" var action2Title = "Radical" var action3Title = "Cancel" var action4Title = "Destroy" var action5Title = "Foo" var action6Title = "Bar" var uiAlertAction1: UIAlertAction! var uiAlertAction2: UIAlertAction! var uiAlertAction3: UIAlertAction! var uiAlertAction4: UIAlertAction! var uiAlertAction5: UIAlertAction! var uiAlertAction6: UIAlertAction! var faAlertAction1: FAAlertAction! var faAlertAction2: FAAlertAction! var faAlertAction3: FAAlertAction! var faAlertAction4: FAAlertAction! var faAlertAction5: FAAlertAction! var faAlertAction6: FAAlertAction! let segmentedControl = UISegmentedControl(items: ["Alert", "ActionSheet", "Picker"]) var alertButtons: [UIBarButtonItem]! var actionSheetButtons: [UIBarButtonItem]! var pickerButtons: [UIBarButtonItem]! override func viewDidLoad() { super.viewDidLoad() setupButtonArrays() segmentedControl.addTarget(self, action: #selector(togglePreferredType(sender:)), for: .valueChanged) navigationItem.titleView = segmentedControl segmentedControl.selectedSegmentIndex = 0 navigationController?.isNavigationBarHidden = false navigationController?.isToolbarHidden = false alertTitle = _title alertMessage = _message uiAlertAction1 = UIAlertAction(title: action1Title, style: .default, handler: { (action) in print("Doing something \(self.action1Title.lowercased())....") }) uiAlertAction2 = UIAlertAction(title: action2Title, style: .default, handler: { (action) in print("Doing something \(self.action2Title.lowercased())....") }) uiAlertAction3 = UIAlertAction(title: action3Title, style: .cancel, handler: { action in print("Canceling the thing.....") }) uiAlertAction4 = UIAlertAction(title: action4Title, style: .destructive, handler: { (action) in print("Destroying the thing....") }) uiAlertAction5 = UIAlertAction(title: action5Title, style: .default, handler: { (action) in print("Doing \(self.action5Title.lowercased()) things....") }) uiAlertAction6 = UIAlertAction(title: action6Title, style: .default, handler: { (action) in print("Doing \(self.action6Title.lowercased()) things....") }) faAlertAction1 = FAAlertAction(title: action1Title, style: .default, handler: { (action) in print("Doing something \(self.action1Title.lowercased())....") }) faAlertAction2 = FAAlertAction(title: action2Title, style: .default, handler: { (action) in print("Doing something \(self.action2Title.lowercased())....") }) faAlertAction3 = FAAlertAction(title: action3Title, style: .cancel) faAlertAction4 = FAAlertAction(title: action4Title, style: .destructive, handler: { (action) in print("Doing \(self.action4Title.lowercased()) things....") }) faAlertAction5 = FAAlertAction(title: action5Title, style: .default, handler: { (action) in print("Doing \(self.action5Title.lowercased()) things....") }) faAlertAction6 = FAAlertAction(title: action6Title, style: .default, handler: { (action) in print("Doing \(self.action6Title.lowercased()) things....") }) } func setupButtonArrays() { let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let uiAlertButton = UIBarButtonItem(title: "UIAlert", style: .plain, target: self, action: #selector(showUIAlert)) let uiActionSheet = UIBarButtonItem(title: "UIActionSheet", style: .plain, target: self, action: #selector(showUIActionSheet)) let faAlertButton = UIBarButtonItem(title: "FAAlert", style: .plain, target: self, action: #selector(showFAAlert)) let faActionSheet = UIBarButtonItem(title: "FAActionSheet", style: .plain, target: self, action: #selector(showFAActionSheet)) let picker = UIBarButtonItem(title: "FAPicker", style: .plain, target: self, action: #selector(showPicker)) alertButtons = [flexSpace, uiAlertButton, flexSpace, faAlertButton, flexSpace] actionSheetButtons = [flexSpace, uiActionSheet, flexSpace, faActionSheet, flexSpace] pickerButtons = [flexSpace, picker, flexSpace] setToolbarItems(alertButtons, animated: false) } @IBAction func togglePreferredType(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: setToolbarItems(alertButtons, animated: true) case 1: setToolbarItems(actionSheetButtons, animated: true) case 2: setToolbarItems(pickerButtons, animated: true) default: print("We shouldn't ever get here") } } func showUIAlert() { let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) if _numberOfActions >= 1 { alert.addAction(uiAlertAction1) } if _numberOfActions >= 2 { alert.addAction(uiAlertAction2) } if _numberOfActions >= 3 { alert.addAction(uiAlertAction3) } if _numberOfActions >= 4 { alert.addAction(uiAlertAction4) } if _numberOfActions >= 5 { alert.addAction(uiAlertAction5) } if _numberOfActions >= 6 { alert.addAction(uiAlertAction6) } if _numberOfActions >= _preferredActionIndex + 1 { alert.preferredAction = alert.actions[_preferredActionIndex] } if _numberOfTextFields >= 1 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field One" } } if _numberOfTextFields >= 2 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Two" } } if _numberOfTextFields >= 3 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Three" } } if _numberOfTextFields >= 4 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Four" } } if _numberOfTextFields >= 5 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Five" } } if _numberOfTextFields >= 6 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Five" } } present(alert, animated: true, completion: nil) } func showUIActionSheet() { let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .actionSheet) if _numberOfActions >= 1 { alert.addAction(uiAlertAction1) } if _numberOfActions >= 2 { alert.addAction(uiAlertAction2) } if _numberOfActions >= 3 { alert.addAction(uiAlertAction3) } if _numberOfActions >= 4 { alert.addAction(uiAlertAction4) } if _numberOfActions >= 5 { alert.addAction(uiAlertAction5) } if _numberOfActions >= 6 { alert.addAction(uiAlertAction6) } if _numberOfActions >= 2 { alert.preferredAction = uiAlertAction2 } present(alert, animated: true, completion: nil) } func showFAAlert() { let alert = FAAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert, appearance: appearanceStyle) alert.appearanceDelegate = faControllerAppearanceDelegate if _numberOfActions >= 1 { alert.addAction(faAlertAction1) } if _numberOfActions >= 2 { alert.addAction(faAlertAction2) } if _numberOfActions >= 3 { alert.addAction(faAlertAction3) } if _numberOfActions >= 4 { alert.addAction(faAlertAction4) } if _numberOfActions >= 5 { alert.addAction(faAlertAction5) } if _numberOfActions >= 6 { alert.addAction(faAlertAction6) } if _numberOfActions >= _preferredActionIndex + 1 { alert.preferredAction = alert.actions[_preferredActionIndex] } if _numberOfTextFields >= 1 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field One" } } if _numberOfTextFields >= 2 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Two" } } if _numberOfTextFields >= 3 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Three" } } if _numberOfTextFields >= 4 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Four" } } if _numberOfTextFields >= 5 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Five" } } if _numberOfTextFields >= 6 { alert.addTextField { (textfield) in textfield.placeholder = "Text Field Five" } } present(alert, animated: true, completion: nil) } func showFAActionSheet() { let alert = FAAlertController(title: alertTitle, message: alertMessage, preferredStyle: .actionSheet, appearance: appearanceStyle) alert.appearanceDelegate = faControllerAppearanceDelegate if _numberOfActions >= 1 { alert.addAction(faAlertAction1) } if _numberOfActions >= 2 { alert.addAction(faAlertAction2) } if _numberOfActions >= 3 { alert.addAction(faAlertAction3) } if _numberOfActions >= 4 { alert.addAction(faAlertAction4) } if _numberOfActions >= 5 { alert.addAction(faAlertAction5) } if _numberOfActions >= 6 { alert.addAction(faAlertAction6) } if _numberOfActions >= 2 { alert.preferredAction = faAlertAction2 } present(alert, animated: true, completion: nil) } func showPicker() { // Create items let itemOne = PickableItem(title: "Network One", subtitle: "A pretty good network") let itemTwo = PickableItem(title: "Network Two", subtitle: "Almost as good as Network One") let itemThree = PickableItem(title: "Network Three", subtitle: "Don't pick this one") let items = [itemOne, itemTwo, itemThree] // Create Cancel Action let cancel = FAAlertAction(title: "Cancel", style: .cancel) // Setup Alert let title = "Select A Wireless Network" let message = "This is a message" let alert = FAAlertController(title: title, message: message, preferredStyle: .picker, appearance: appearanceStyle, items: items) alert.addAction(cancel) alert.delegate = self present(alert, animated: true, completion: nil) } func didSelectItem(_ item: Pickable) { print("Selected \(item)") } @IBAction func unwindToMainViewController(segue: UIStoryboardSegue) {} } class PickableItem: Pickable { let title: String let subtitle: String? init(title: String, subtitle: String?) { self.title = title self.subtitle = subtitle } }
mit
81963c59aef6030ea8c04d914d77a1d7
35.160112
138
0.600948
4.892816
false
false
false
false
chenchangqing/learniosanimation
example03/example03/ViewController.swift
1
9780
// // ViewController.swift // example03 // // Created by green on 15/8/13. // Copyright (c) 2015年 com.chenchangqing. All rights reserved. // import UIKit class ViewController: UIViewController { private var starShapeLayer : CAShapeLayer! // 五角星 private var starPath01 : UIBezierPath! // 五角星曲线01 private var starPath02 : UIBezierPath! // 五角星曲线02 private var timer : NSTimer! // 时间控制 private var i = 0 private var ovalLayer : CAShapeLayer! // 椭圆 private var rectLayer : CAShapeLayer! // 矩形 private var circleLayer : CAShapeLayer! // 圆形 private var progressLayer : CAShapeLayer! // 圆形进度条 private var timer2 : NSTimer! // 时间控制 private var progressView : ProgressCircleView! // 圆形进度条控件 // MARK: - override func viewDidLoad() { super.viewDidLoad() setup() // 五角星定时执行动画 timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("pathAnimation"), userInfo: nil, repeats: true) // 圆形进度条定制执行动画 timer2 = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("animationEventTypeOne"), userInfo: nil, repeats: true) timer2 = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("animationEventTypeTwo"), userInfo: nil, repeats: true) // 延时1秒 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(NSEC_PER_SEC * 1)), dispatch_get_main_queue()) { () -> Void in self.progressView.value = 1 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - setup private func setup() { view.backgroundColor = UIColor(red: 0.878, green: 0.878, blue: 0.878, alpha: 1) // 配置五角星 setup01() // 设置椭圆、正圆、矩形 setup02() // 设置圆形进度条 setup03() // 设置圆形进度条(使用ProgressCircleView) setup04() } // MARK: - 五角星相关 /** * 五角星相关设置 */ private func setup01() { // 创建bezierPath setupStarBezierPath01() setupStarBezierPath02() // 创建shapeLayer starShapeLayer = CAShapeLayer() starShapeLayer.frame = CGRectMake(16, 36, 45, 45) starShapeLayer.path = starPath01.CGPath starShapeLayer.fillColor = UIColor.clearColor().CGColor starShapeLayer.strokeColor = UIColor.redColor().CGColor starShapeLayer.lineWidth = 2 starShapeLayer.backgroundColor = UIColor.purpleColor().CGColor view.layer.addSublayer(starShapeLayer) } /** * 五角星动画 */ func pathAnimation() { if (i++ % 2) == 0 { let circleAnim = CABasicAnimation(keyPath: "path") circleAnim.removedOnCompletion = false circleAnim.duration = 1 circleAnim.fromValue = starPath01.CGPath circleAnim.toValue = starPath02.CGPath starShapeLayer.path = starPath02.CGPath starShapeLayer.addAnimation(circleAnim, forKey: "animateCirclePath") } else { let circleAnim = CABasicAnimation(keyPath: "path") circleAnim.removedOnCompletion = false circleAnim.duration = 1 circleAnim.fromValue = starPath02.CGPath circleAnim.toValue = starPath01.CGPath starShapeLayer.path = starPath01.CGPath starShapeLayer.addAnimation(circleAnim, forKey: "animateCirclePath") } } /** * 贝塞尔曲线01 */ private func setupStarBezierPath01() { starPath01 = UIBezierPath() starPath01.moveToPoint(CGPointMake(22.5, 2.5)) starPath01.addLineToPoint(CGPointMake(28.32, 14.49)) starPath01.addLineToPoint(CGPointMake(41.52, 16.32)) starPath01.addLineToPoint(CGPointMake(31.92, 25.56)) starPath01.addLineToPoint(CGPointMake(34.26, 38.68)) starPath01.addLineToPoint(CGPointMake(22.5, 32.4)) starPath01.addLineToPoint(CGPointMake(10.74, 38.68)) starPath01.addLineToPoint(CGPointMake(13.08, 25.56)) starPath01.addLineToPoint(CGPointMake(3.48, 16.32)) starPath01.addLineToPoint(CGPointMake(16.68, 14.49)) starPath01.closePath() } /** * 贝塞尔曲线02 */ private func setupStarBezierPath02() { starPath02 = UIBezierPath() starPath02.moveToPoint(CGPointMake(22.5, 2.5)) starPath02.addLineToPoint(CGPointMake(32.15, 9.21)) starPath02.addLineToPoint(CGPointMake(41.52, 16.32)) starPath02.addLineToPoint(CGPointMake(38.12, 27.57)) starPath02.addLineToPoint(CGPointMake(34.26, 38.68)) starPath02.addLineToPoint(CGPointMake(22.5, 38.92)) starPath02.addLineToPoint(CGPointMake(10.74, 38.68)) starPath02.addLineToPoint(CGPointMake(6.88, 27.57)) starPath02.addLineToPoint(CGPointMake(3.48, 16.32)) starPath02.addLineToPoint(CGPointMake(12.85, 9.21)) starPath02.closePath() } // MARK: - UIBezierPath /** * 设置椭圆、矩形、正圆的层 */ private func setup02() { // 创建椭圆层 创建矩形层 创建正圆层 ovalLayer = CAShapeLayer() ovalLayer.frame = CGRectMake(16, CGRectGetMaxY(starShapeLayer.frame) + 16, CGRectGetWidth(view.bounds) - 32, 50) rectLayer = CAShapeLayer() rectLayer.frame = CGRectMake(16, CGRectGetMaxY(ovalLayer.frame) + 16, CGRectGetWidth(view.bounds) - 32, 50) circleLayer = CAShapeLayer() circleLayer.frame = CGRectMake(16, CGRectGetMaxY(rectLayer.frame) + 16, CGRectGetWidth(view.bounds) - 32, 50) // 分别创建塞尔曲线 let oval = UIBezierPath(ovalInRect: CGRectMake(0, 0, 100, 50)) let rect = UIBezierPath(rect: rectLayer.bounds) let circle = UIBezierPath(ovalInRect: CGRectMake(0, 0, CGRectGetHeight(circleLayer.bounds), CGRectGetHeight(circleLayer.bounds))) // 分别显示CAShapeLayer的边界 ovalLayer.borderWidth = 1 rectLayer.borderWidth = 1 circleLayer.borderWidth = 1 // 分别禁止内容显示超出CAShapeLayer的frame值 ovalLayer.masksToBounds = true rectLayer.masksToBounds = true circleLayer.masksToBounds = true // 分别修改贝塞尔曲线的填充颜色 ovalLayer.fillColor = UIColor.redColor().CGColor rectLayer.fillColor = UIColor.redColor().CGColor circleLayer.fillColor = UIColor.redColor().CGColor // 分别建立贝塞尔曲线与CAShapeLayer之间的关联 ovalLayer.path = oval.CGPath rectLayer.path = rect.CGPath circleLayer.path = circle.CGPath // 分别添加并显示 view.layer.addSublayer(ovalLayer) view.layer.addSublayer(rectLayer) view.layer.addSublayer(circleLayer) } // MARK: - 圆形进度条动画 /** * 设置圆形进度条 */ private func setup03() { // 创建CAShapeLayer progressLayer = CAShapeLayer() progressLayer.frame = CGRectMake(16, CGRectGetMaxY(circleLayer.frame) + 16, CGRectGetWidth(view.bounds) - 32, 100) // 创建圆形贝塞尔曲线 let oval = UIBezierPath(ovalInRect: CGRectMake(0, 0, 100, 100)) // 修改CAShapeLayer的线条相关值 progressLayer.fillColor = UIColor.clearColor().CGColor progressLayer.strokeColor = UIColor.redColor().CGColor progressLayer.lineWidth = 2 progressLayer.strokeStart = 0 progressLayer.strokeEnd = 0 // 建立贝塞尔曲线与CAShapeLayer之间的关联 progressLayer.path = oval.CGPath // 添加并显示 view.layer.addSublayer(progressLayer) } /** * 动画01 */ func animationEventTypeOne() { progressLayer.strokeEnd = CGFloat(arc4random() % 100) / 100 } /** * 动画02 */ func animationEventTypeTwo() { let valueOne = CGFloat(arc4random() % 100) / 100 let valuTwo = CGFloat(arc4random() % 100) / 100 progressLayer.strokeStart = valueOne < valuTwo ? valueOne : valuTwo progressLayer.strokeEnd = valueOne > valuTwo ? valueOne : valuTwo } // MARK: - 圆形进度条控件 /** * 设置圆形进度条控件 */ private func setup04() { progressView = ProgressCircleView(frame: CGRectMake(16, CGRectGetMaxY(progressLayer.frame) + 16, 100, 100)) progressView.value = 0.75 progressView.lineWidth = 2 progressView.lineColor = UIColor.purpleColor() view.addSubview(progressView) } }
apache-2.0
e3aee89bf57916da4a0bcedc8b1e53bb
31.408451
147
0.574207
4.588235
false
false
false
false
irshadqureshi/IQCacheResources
IQCacheResources/Classes/UIImageViewExtension.swift
1
1783
// // UIImageViewExtension.swift // Pods // // Created by Irshad on 15/07/17. // // import Foundation import UIKit // Mark:- Image View Extension to check if image exsist in cache or not. If not then download it from server. public extension UIImageView { public func iq_setImageWithUrl(url: NSURL, completion: @escaping (_ error : NSError?) -> Void) { self.iq_setImageWithUrl(url: url, placeholderImage: nil, completion: completion) } public func iq_setImageWithUrl(url: NSURL) { self.iq_setImageWithUrl(url: url, placeholderImage: nil, completion: nil) } public func iq_setImageWithUrl(url: NSURL, placeholderImage: UIImage? = nil, completion: ((_ error : NSError?) -> Void)?) { self.image = nil if let _ = placeholderImage { self.image = placeholderImage } if let cachedImage = CacheManager.sharedCache.unarchiveImage(url: url.absoluteString!) { self.image = cachedImage if let _ = completion { completion!(nil) } return } download(url: url).getImage { (url, image, error) -> Void in if error == nil , let _ = image { self.image = image! CacheManager.sharedCache.archiveImage(image: image!, url: url.absoluteString!) if let _ = completion { completion!(nil) } } else { if let _ = completion { completion!(error) } } } } }
mit
dae7f54caba58be7d7419dfbfbef62c0
24.112676
127
0.498598
5.138329
false
false
false
false
shajrawi/swift
test/ParseableInterface/Inputs/enums-layout-helper.swift
1
932
// CHECK-LABEL: public enum FutureproofEnum : Int public enum FutureproofEnum: Int { // CHECK-NEXT: case a{{$}} case a = 1 // CHECK-NEXT: case b{{$}} case b = 10 // CHECK-NEXT: case c{{$}} case c = 100 } // CHECK-LABEL: public enum FrozenEnum : Int @_frozen public enum FrozenEnum: Int { // CHECK-NEXT: case a{{$}} case a = 1 // CHECK-NEXT: case b{{$}} case b = 10 // CHECK-NEXT: case c{{$}} case c = 100 } // CHECK-LABEL: public enum FutureproofObjCEnum : Int32 @objc public enum FutureproofObjCEnum: Int32 { // CHECK-NEXT: case a = 1{{$}} case a = 1 // CHECK-NEXT: case b = 10{{$}} case b = 10 // CHECK-NEXT: case c = 100{{$}} case c = 100 } // CHECK-LABEL: public enum FrozenObjCEnum : Int32 @_frozen @objc public enum FrozenObjCEnum: Int32 { // CHECK-NEXT: case a = 1{{$}} case a = 1 // CHECK-NEXT: case b = 10{{$}} case b = 10 // CHECK-NEXT: case c = 100{{$}} case c = 100 }
apache-2.0
f0c39d70fc05cc8f84d796e777d17d97
22.3
55
0.592275
3.159322
false
false
false
false
viWiD/Persist
Sources/Persist/ContextMerger.swift
1
2137
// // ContextMerger.swift // Pods // // Created by Nils Fischer on 01.04.16. // // import Foundation import CoreData import Evergreen // Currently unused class ContextMerger: NSObject { let logger = Evergreen.getLogger("Persist.ContextMerger") weak var context: NSManagedObjectContext? weak var mainContext: NSManagedObjectContext? let entityType: Identifyable.Type init(observing context: NSManagedObjectContext, toMergeInto mainContext: NSManagedObjectContext, deduplicatingEntity entityType: Identifyable.Type) { self.context = context self.mainContext = mainContext self.entityType = entityType super.init() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func contextDidSave(notification: NSNotification) { guard let mainContext = self.mainContext else { logger.warning("Main context was released before changes could be merged into it.") return } mainContext.performBlock { // merge changes into main context self.logger.debug("Merging changes into main context...") mainContext.mergeChangesFromContextDidSaveNotification(notification) // save if mainContext.hasChanges { do { self.logger.debug("Saving main context with merged changes.") try mainContext.save() } catch { self.logger.error("Failed saving context.", error: error) } } else { self.logger.debug("No need to save main context.") } } } func beginObserving() { guard let context = self.context else { logger.warning("Observed context was released before observing began.") return } NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ContextMerger.contextDidSave(_:)), name: NSManagedObjectContextDidSaveNotification, object: context) } }
mit
edd32deeca51c2b4ca1662ae8b649848
29.971014
183
0.615817
5.653439
false
false
false
false
ListFranz/VPNOn
VPNOnKit/VPNKeychainWrapper.swift
23
3123
// // VPNKeychainWrapper.swift // VPNOn // // Created by Lex Tang on 12/12/14. // Copyright (c) 2014 LexTang.com. All rights reserved. // import Foundation //let kKeychainServiceName = NSBundle.mainBundle().bundleIdentifier! let kKeychainServiceName = "com.LexTang.VPNOn" final public class VPNKeychainWrapper { public class func setPassword(password: String, forVPNID VPNID: String) -> Bool { let key = NSURL(string: VPNID)!.lastPathComponent! KeychainWrapper.serviceName = kKeychainServiceName KeychainWrapper.removeObjectForKey(key) if password.isEmpty { return true } return KeychainWrapper.setString(password, forKey: key) } public class func setSecret(secret: String, forVPNID VPNID: String) -> Bool { let key = NSURL(string: VPNID)!.lastPathComponent! KeychainWrapper.serviceName = kKeychainServiceName KeychainWrapper.removeObjectForKey("\(key)psk") if secret.isEmpty { return true } return KeychainWrapper.setString(secret, forKey: "\(key)psk") } public class func setCertificate(certificate: NSData?, forVPNID VPNID: String) -> Bool { let key = NSURL(string: VPNID)!.lastPathComponent! KeychainWrapper.serviceName = kKeychainServiceName KeychainWrapper.removeObjectForKey("\(key)cert") if let data = certificate { KeychainWrapper.setData(data, forKey: "\(key)cert") } return true } public class func passwordForVPNID(VPNID: String) -> NSData? { let key = NSURL(string: VPNID)!.lastPathComponent! KeychainWrapper.serviceName = kKeychainServiceName return KeychainWrapper.dataRefForKey(key) } public class func secretForVPNID(VPNID: String) -> NSData? { let key = NSURL(string: VPNID)!.lastPathComponent! KeychainWrapper.serviceName = kKeychainServiceName return KeychainWrapper.dataRefForKey("\(key)psk") } public class func destoryKeyForVPNID(VPNID: String) { let key = NSURL(string: VPNID)!.lastPathComponent! KeychainWrapper.serviceName = kKeychainServiceName KeychainWrapper.removeObjectForKey(key) KeychainWrapper.removeObjectForKey("\(key)psk") KeychainWrapper.removeObjectForKey("\(key)cert") } public class func passwordStringForVPNID(VPNID: String) -> String? { let key = NSURL(string: VPNID)!.lastPathComponent! KeychainWrapper.serviceName = kKeychainServiceName return KeychainWrapper.stringForKey(key) } public class func secretStringForVPNID(VPNID: String) -> String? { let key = NSURL(string: VPNID)!.lastPathComponent! KeychainWrapper.serviceName = kKeychainServiceName return KeychainWrapper.stringForKey("\(key)psk") } public class func certificateForVPNID(VPNID: String) -> NSData? { let key = NSURL(string: VPNID)!.lastPathComponent! KeychainWrapper.serviceName = kKeychainServiceName return KeychainWrapper.dataForKey("\(key)cert") } }
mit
ae775145ad5b3ac5479a0b5f532c4e9a
36.638554
92
0.680435
5.266442
false
false
false
false
MadArkitekt/Swift_Tutorials_And_Demos
Websockets/EmojiTransmitter/CollectionViewController.swift
1
2647
/** * Copyright (c) 2016 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 final class CollectionViewController: UICollectionViewController { // MARK: - Properties let emoji = ["😀", "😬", "😁", "😂", "😃", "😄", "😅", "😆", "😇", "😉", "😊", "🙂", "🙃", "☺️", "😋", "😌", "😍", "😘", "😗", "😙", "😚", "😜", "😝", "😛", "🤑", "🤓", "😎", "🤗", "😏", "😶", "😐", "😑", "😒", "🙄", "🤔", "😳", "😞", "😟", "😠", "😡", "😔", "😕", "🙁", "☹️", "😣", "😖", "😫", "😩", "😤", "😮", "😱", "😨", "😰", "😯", "😦", "😧", "😢", "😥", "😪", "😓", "😭", "😵", "😲", "🤐", "😷", "🤒", "🤕", "😴", "💩"] } // MARK: - Internal extension CollectionViewController { func selectedEmoji() -> String? { guard let selectedIndexPaths = collectionView?.indexPathsForSelectedItems, let item = selectedIndexPaths.first?.item else { return nil } return emoji[item] } } // MARK: - UICollectionViewDataSource extension CollectionViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return emoji.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "emoji", for: indexPath) let label = cell.viewWithTag(100) as? UILabel label?.text = emoji[indexPath.item] return cell } }
gpl-2.0
1dd0df3d69bb4af257ab80c544b06d58
38.967213
361
0.64192
4.016474
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/SVideoController.swift
1
19564
// // VideoStreamingTestModalController.swift // Telegram // // Created by Mikhail Filimonov on 12/11/2018. // Copyright © 2018 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import SwiftSignalKit import Postbox import RangeSet import IOKit.pwr_mgt extension MediaPlayerStatus { func withUpdatedVolume(_ volume: Float) -> MediaPlayerStatus { return MediaPlayerStatus(generationTimestamp: self.generationTimestamp, duration: self.duration, dimensions: self.dimensions, timestamp: self.timestamp, baseRate: self.baseRate, volume: volume, seekId: self.seekId, status: self.status) } func withUpdatedTimestamp(_ timestamp: Double) -> MediaPlayerStatus { return MediaPlayerStatus(generationTimestamp: self.generationTimestamp, duration: self.duration, dimensions: self.dimensions, timestamp: timestamp, baseRate: self.baseRate, volume: self.volume, seekId: self.seekId, status: self.status) } func withUpdatedDuration(_ duration: Double) -> MediaPlayerStatus { return MediaPlayerStatus(generationTimestamp: self.generationTimestamp, duration: duration, dimensions: self.dimensions, timestamp: self.timestamp, baseRate: self.baseRate, volume: self.volume, seekId: self.seekId, status: self.status) } } enum SVideoStyle { case regular case pictureInPicture } class SVideoController: GenericViewController<SVideoView>, PictureInPictureControl { var style: SVideoStyle = .regular private var fullScreenWindow: Window? private var fullScreenRestoreState: (rect: NSRect, view: NSView)? private let mediaPlayer: MediaPlayer private let reference: FileMediaReference private let statusDisposable = MetaDisposable() private let bufferingDisposable = MetaDisposable() private let hideOnIdleDisposable = MetaDisposable() private let hideControlsDisposable = MetaDisposable() private let postbox: Postbox private var pictureInPicture: Bool = false private var hideControls: ValuePromise<Bool> = ValuePromise(true, ignoreRepeated: true) private var controlsIsHidden: Bool = false var togglePictureInPictureImpl:((Bool, PictureInPictureControl)->Void)? private var isPaused: Bool = true private var forceHiddenControls: Bool = false private var _videoFramePreview: MediaPlayerFramePreview? private var mode: PictureInPictureControlMode = .normal private var updateControls: SwiftSignalKit.Timer? private var videoFramePreview: MediaPlayerFramePreview { if let videoFramePreview = _videoFramePreview { return videoFramePreview } else { self._videoFramePreview = MediaPlayerFramePreview(postbox: postbox, fileReference: reference) } return _videoFramePreview! } func setMode(_ mode: PictureInPictureControlMode, animated: Bool) { genericView.setMode(mode, animated: animated) self.mode = mode } private var scrubbingFrame = Promise<MediaPlayerFramePreviewResult?>(nil) private var scrubbingFrames = false private var scrubbingFrameDisposable: Disposable? init(postbox: Postbox, reference: FileMediaReference, fetchAutomatically: Bool = false) { self.reference = reference self.postbox = postbox mediaPlayer = MediaPlayer(postbox: postbox, reference: reference.resourceReference(reference.media.resource), streamable: reference.media.isStreamable, video: true, preferSoftwareDecoding: false, enableSound: true, baseRate: FastSettings.playingVideoRate, volume: FastSettings.volumeRate, fetchAutomatically: fetchAutomatically) super.init() bar = .init(height: 0) } var status: Signal<MediaPlayerStatus, NoError> { return mediaPlayer.status } func play(_ startTime: TimeInterval? = nil) { mediaPlayer.play() self.isPaused = false if let startTime = startTime, startTime > 0 { mediaPlayer.seek(timestamp: startTime) } } func setBaseRate(_ baseRate: Double) { mediaPlayer.setBaseRate(baseRate) FastSettings.setPlayingVideoRate(baseRate) } func playOrPause() { self.isPaused = !self.isPaused mediaPlayer.togglePlayPause() if let status = genericView.status { switch status.status { case .buffering: mediaPlayer.seek(timestamp: status.timestamp / status.duration) default: break } } } func pause() { self.isPaused = true mediaPlayer.pause() } func play() { self.isPaused = false self.play(nil) } func didEnter() { } func didExit() { } private func updateIdleTimer() { NSCursor.unhide() hideOnIdleDisposable.set((Signal<NoValue, NoError>.complete() |> delay(1.0, queue: Queue.mainQueue())).start(completed: { [weak self] in guard let `self` = self else {return} let hide = !self.genericView.isInMenu self.hideControls.set(hide) if !self.pictureInPicture, !self.isPaused, hide { NSCursor.hide() } })) } private func updateControlVisibility(_ isMouseUpOrDown: Bool = false) { updateIdleTimer() if let rootView = genericView.superview?.superview { var hide = !genericView._mouseInside() && !rootView.isHidden && (NSEvent.pressedMouseButtons & (1 << 0)) == 0 if !hide, (NSEvent.pressedMouseButtons & (1 << 0)) != 0 { hide = genericView.controlsStyle.isPip } if self.fullScreenWindow != nil && isMouseUpOrDown, !genericView.insideControls { hide = true if !self.isPaused { NSCursor.hide() } } hideControls.set(hide || forceHiddenControls) } else { hideControls.set(forceHiddenControls) } } private func setHandlersOn(window: Window) { updateIdleTimer() let mouseInsidePlayer = genericView.mediaPlayer.mouseInside() hideControls.set(!mouseInsidePlayer || forceHiddenControls) window.set(mouseHandler: { [weak self] (event) -> KeyHandlerResult in if let window = self?.genericView.window, let contentView = window.contentView { let point = contentView.convert(window.mouseLocationOutsideOfEventStream, from: nil) if contentView.hitTest(point) != nil { self?.updateControlVisibility() } } return .rejected }, with: self, for: .mouseMoved, priority: .modal) window.set(mouseHandler: { [weak self] (event) -> KeyHandlerResult in if let window = self?.genericView.window, let contentView = window.contentView { let point = contentView.convert(window.mouseLocationOutsideOfEventStream, from: nil) if contentView.hitTest(point) != nil { self?.updateControlVisibility() } } return .rejected }, with: self, for: .mouseExited, priority: .modal) window.set(mouseHandler: { [weak self] (event) -> KeyHandlerResult in self?.updateIdleTimer() return .rejected }, with: self, for: .leftMouseDragged, priority: .modal) window.set(mouseHandler: { [weak self] (event) -> KeyHandlerResult in if let window = self?.genericView.window, let contentView = window.contentView { let point = contentView.convert(window.mouseLocationOutsideOfEventStream, from: nil) if contentView.hitTest(point) != nil { self?.updateControlVisibility() } } return .rejected }, with: self, for: .mouseEntered, priority: .modal) window.set(mouseHandler: { [weak self] (event) -> KeyHandlerResult in if self?.genericView.mediaPlayer.mouseInside() == true { self?.updateControlVisibility(true) } return .rejected }, with: self, for: .leftMouseDown, priority: .modal) window.set(mouseHandler: { [weak self] (event) -> KeyHandlerResult in guard let `self` = self else {return .rejected} if let window = self.genericView.window, let contentView = window.contentView { let point = contentView.convert(window.mouseLocationOutsideOfEventStream, from: nil) if contentView.hitTest(point) != nil { self.updateControlVisibility(true) } } self.genericView.subviews.last?.mouseUp(with: event) return .rejected }, with: self, for: .leftMouseUp, priority: .modal) // self.updateControls = SwiftSignalKit.Timer(timeout: 2.0, repeat: true, completion: { [weak self] in // self?.updateControlVisibility() // }, queue: .mainQueue()) // // self.updateControls?.start() } private var assertionID: IOPMAssertionID = 0 private var success: IOReturn? private func disableScreenSleep() -> Bool? { guard success == nil else { return nil } success = IOPMAssertionCreateWithName( kIOPMAssertionTypeNoDisplaySleep as CFString, IOPMAssertionLevel(kIOPMAssertionLevelOn), "Video Playing" as CFString, &assertionID ) return success == kIOReturnSuccess } private func enableScreenSleep() -> Bool { if success != nil { success = IOPMAssertionRelease(assertionID) success = nil return true } return false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let window = window { setHandlersOn(window: window) } } override func viewDidDisappear(_ animated: Bool) { super.viewWillDisappear(animated) hideOnIdleDisposable.set(nil) _ = enableScreenSleep() NSCursor.unhide() window?.removeAllHandlers(for: self) } var isPictureInPicture: Bool { return self.pictureInPicture } func hideControlsIfNeeded(_ forceHideControls: Bool = false) -> Bool { self.forceHiddenControls = forceHideControls if !controlsIsHidden { hideControls.set(true) return true } return false } func unhideControlsIfNeeded(_ forceUnhideControls: Bool = true) -> Bool { forceHiddenControls = !forceUnhideControls if controlsIsHidden { hideControls.set(forceUnhideControls) return true } return false } override func viewDidLoad() { super.viewDidLoad() genericView.layerContentsRedrawPolicy = .duringViewResize mediaPlayer.attachPlayerView(genericView.mediaPlayer) genericView.isStreamable = reference.media.isStreamable hideControlsDisposable.set(hideControls.get().start(next: { [weak self] hide in self?.genericView.hideControls(hide, animated: true) self?.controlsIsHidden = hide })) let statusValue:Atomic<MediaPlayerStatus?> = Atomic(value: nil) let updateTemporaryStatus:(_ f: (MediaPlayerStatus?)->MediaPlayerStatus?) -> Void = { [weak self] f in self?.genericView.status = statusValue.modify(f) } let duration = Double(reference.media.duration ?? 0) statusDisposable.set((mediaPlayer.status |> deliverOnMainQueue).start(next: { [weak self] status in let status = status.withUpdatedDuration(status.duration != 0 ? status.duration : duration) switch status.status { case .playing: _ = self?.disableScreenSleep() case let .buffering(_, whilePlaying): if whilePlaying { _ = self?.disableScreenSleep() } else { _ = self?.enableScreenSleep() } case .paused: _ = self?.enableScreenSleep() } _ = statusValue.swap(status) self?.genericView.status = status })) let size = reference.media.resource.size ?? 0 let bufferingStatus = postbox.mediaBox.resourceRangesStatus(reference.media.resource) |> map { ranges -> (RangeSet<Int64>, Int64) in return (ranges, size) } |> deliverOnMainQueue bufferingDisposable.set(bufferingStatus.start(next: { [weak self] bufferingStatus in self?.genericView.bufferingStatus = bufferingStatus })) self.scrubbingFrameDisposable = (self.scrubbingFrame.get() |> deliverOnMainQueue).start(next: { [weak self] result in guard let `self` = self else { return } if let result = result { self.genericView.showScrubblerPreviewIfNeeded() self.genericView.setCurrentScrubblingState(result) } else { self.genericView.hideScrubblerPreviewIfNeeded() // empty image } }) genericView.interactions = SVideoInteractions(playOrPause: { [weak self] in self?.playOrPause() }, rewind: { [weak self] timestamp in guard let `self` = self else { return } self.mediaPlayer.seek(timestamp: timestamp) }, scrobbling: { [weak self] timecode in guard let `self` = self else { return } if let timecode = timecode { if !self.scrubbingFrames { self.scrubbingFrames = true self.scrubbingFrame.set(self.videoFramePreview.generatedFrames |> map(Optional.init)) } self.videoFramePreview.generateFrame(at: timecode) } else { self.scrubbingFrame.set(.single(nil)) self.videoFramePreview.cancelPendingFrames() self.scrubbingFrames = false } }, volume: { [weak self] value in self?.mediaPlayer.setVolume(value) FastSettings.setVolumeRate(value) updateTemporaryStatus { status in return status?.withUpdatedVolume(value) } }, toggleFullScreen: { [weak self] in self?.toggleFullScreen() }, togglePictureInPicture: { [weak self] in self?.togglePictureInPicture() }, closePictureInPicture: { closePipVideo() }, setBaseRate: { [weak self] rate in self?.setBaseRate(rate) }) if let duration = reference.media.duration, duration < 30 { mediaPlayer.actionAtEnd = .loop({ [weak self] in Queue.mainQueue().async { self?.updateIdleTimer() } }) } else { mediaPlayer.actionAtEnd = .action { [weak self] in Queue.mainQueue().async { self?.mediaPlayer.seek(timestamp: 0) self?.mediaPlayer.pause() self?.updateIdleTimer() self?.hideControls.set(false) } } } readyOnce() } func togglePictureInPicture() { if let function = togglePictureInPictureImpl { if fullScreenRestoreState != nil { toggleFullScreen() } self.pictureInPicture = !pictureInPicture window?.removeAllHandlers(for: self) function(pictureInPicture, self) if let window = view.window?.contentView?.window as? Window { setHandlersOn(window: window) } genericView.set(isInPictureInPicture: pictureInPicture) } } func togglePlayerOrPause() { playOrPause() } func rewindBackward() { genericView.rewindBackward() } func rewindForward() { genericView.rewindForward() } var isFullscreen: Bool { return self.fullScreenRestoreState != nil } func toggleFullScreen() { if let screen = NSScreen.main { if let window = fullScreenWindow, let state = fullScreenRestoreState { var topInset: CGFloat = 0 if #available(macOS 12.0, *) { topInset = screen.safeAreaInsets.top } window.setFrame(NSMakeRect(screen.frame.minX + state.rect.minX, screen.frame.minY + screen.frame.height - state.rect.maxY - topInset, state.rect.width, state.rect.height), display: true, animate: true) window.orderOut(nil) view.frame = state.rect state.view.addSubview(view) genericView.set(isInFullScreen: false) genericView.mediaPlayer.setVideoLayerGravity(.resizeAspectFill) window.removeAllHandlers(for: self) if let window = self.window { setHandlersOn(window: window) } self.fullScreenWindow = nil self.fullScreenRestoreState = nil } else { genericView.mediaPlayer.setVideoLayerGravity(.resizeAspect) fullScreenRestoreState = (rect: view.frame, view: view.superview!) fullScreenWindow = Window(contentRect: NSMakeRect(view.frame.minX, screen.frame.height - view.frame.maxY, view.frame.width, view.frame.height), styleMask: [.fullSizeContentView, .borderless], backing: .buffered, defer: true, screen: screen) setHandlersOn(window: fullScreenWindow!) window?.removeAllHandlers(for: self) fullScreenWindow?.isOpaque = true fullScreenWindow?.hasShadow = false fullScreenWindow?.level = .screenSaver self.view.frame = self.view.bounds fullScreenWindow?.contentView?.addSubview(self.view) fullScreenWindow?.orderFront(nil) genericView.set(isInFullScreen: true) fullScreenWindow?.becomeKey() fullScreenWindow?.setFrame(screen.frame, display: true, animate: true) } } } deinit { statusDisposable.dispose() bufferingDisposable.dispose() hideOnIdleDisposable.dispose() hideControlsDisposable.dispose() updateControls?.invalidate() _ = IOPMAssertionRelease(assertionID) NSCursor.unhide() } }
gpl-2.0
018fe9575a079f927fbe139f375abee3
36.051136
336
0.585442
5.222371
false
false
false
false
MTTHWBSH/Gaggle
Gaggle/Controllers/Posts/EditPostViewController.swift
1
7451
// // EditPostViewController.swift // Gaggle // // Created by Matthew Bush on 1/12/16. // Copyright © 2016 Matthew Bush. All rights reserved. // import UIKit import Parse import SVProgressHUD class EditPostViewController: ViewController, UITextFieldDelegate, UIScrollViewDelegate { @IBOutlet var imageView: UIImageView! @IBOutlet var submitButton: PrimaryButton! @IBOutlet var maskView: UIView! @IBOutlet var titleTextField: UITextField! @IBOutlet var subtitleTextField: UITextField! @IBOutlet var scrollView: UIScrollView! @IBOutlet var imageViewTopMargin: NSLayoutConstraint! var image: UIImage? var photoFile: PFFile? deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewDidLoad() { super.viewDidLoad() setup() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Analytics.logScreen("Edit Post") } func setup() { title = "Share" imageView.image = image titleTextField.delegate = self subtitleTextField.delegate = self titleTextField.autocapitalizationType = .none titleTextField.autocorrectionType = .no subtitleTextField.autocapitalizationType = .none subtitleTextField.autocorrectionType = .no scrollView.delegate = self let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) view.addGestureRecognizer(tap) if let image = image { shouldUploadImage(image, width: 550.0) } } override func styleView() { view.backgroundColor = Style.whiteColor if UIScreen.main.nativeBounds.height <= 960 { imageViewTopMargin.constant = 0 } maskView.backgroundColor = Style.randomBrandColor(withOpacity: 0.85) titleTextField.tintColor = Style.whiteColor titleTextField.textColor = Style.whiteColor titleTextField.font = Style.regularFontWithSize(32.0) subtitleTextField.tintColor = Style.whiteColor subtitleTextField.textColor = Style.whiteColor subtitleTextField.font = Style.regularFontWithSize(32.0) } // MARK: Text Field func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == titleTextField { subtitleTextField.becomeFirstResponder() } else if textField == subtitleTextField { subtitleTextField.resignFirstResponder() } return true } func dismissKeyboard() { view.endEditing(true) } // MARK: Post Upload func shouldUploadImage(_ image: UIImage, width: CGFloat) { let scale = width / image.size.width let height = image.size.height * scale UIGraphicsBeginImageContext(CGSize(width: width, height: height)) image.draw(in: CGRect(x: 0, y: 0, width: width, height: height)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let imageData: Data = UIImageJPEGRepresentation(resizedImage!, 1.0) else { return } photoFile = PFFile(data: imageData) if let photoFile = photoFile { photoFile.saveInBackground { (completion, error) in if completion { print("Photo file save in background completed") } else { print(error?.localizedDescription ?? "Error saving file in background") } } } } func uploadPost() { SVProgressHUD.showProgress(0.1, status: "Uploading") guard let currentUserID = PFUser.current()?.objectId, let photoFile = photoFile else { let alertText = "An error occured while uploading your photo. Please try again." SVProgressHUD.showError(withStatus: alertText) return } let post = PFObject(className: Constants.PostClassKey) post.setObject(currentUserID, forKey: Constants.PostUserIDKey) post.setObject(photoFile, forKey: Constants.PostImageKey) if let title = titleTextField.text, let subtitle = subtitleTextField.text { post.setObject(title, forKey: Constants.PostTitleKey) post.setObject(subtitle, forKey: Constants.PostSubtitleKey) } post.saveInBackground { (completion, error) in SVProgressHUD.dismiss() if completion { SVProgressHUD.showProgress(1.0, status: "Complete") } else { print("Post failed to save: \(error)") let alertText = "An error occured while uploading your photo" SVProgressHUD.showError(withStatus: alertText) return } } guard let parentVC = parent as? NavigationController, let presentingVC = presentingViewController as? TabBarController else { return } presentingVC.selectedIndex = 0 guard let selectedVC = presentingVC.selectedViewController as? NavigationController, let vc = selectedVC.topViewController as? MainFeedViewController else { return } vc.setup() parentVC.dismiss(animated: true, completion: nil) } func submitPost() { Analytics.logEvent("Post", action: "Submit", Label: "Submit Button Pressed", key: "") if titleTextField.text != "" && subtitleTextField.text != "" { uploadPost() } else { let alertText = "Looks like there are some empty fields, please fill them out and try again." SVProgressHUD.showError(withStatus: alertText) } } // MARK: Keyboard Avoidance func keyboardWillShow(_ note: Notification) { var keyboardFrame = (note.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue keyboardFrame = view.convert(keyboardFrame, from: nil) var contentInset:UIEdgeInsets = scrollView.contentInset contentInset.bottom = keyboardFrame.size.height + 20 scrollView.contentInset = contentInset if let activeView = activeView() { scrollView.scrollRectToVisible(activeView.frame, animated: false) } } func activeView() -> UIView? { return [titleTextField, subtitleTextField].filter { return $0.isFirstResponder }.first } func keyboardWillHide(_ note: Notification) { let contentInset:UIEdgeInsets = UIEdgeInsets.zero scrollView.contentInset = contentInset } // MARK: IBActions @IBAction func submitButtonPressed(_ sender: AnyObject) { submitPost() } @IBAction func closeButtonPressed(_ sender: AnyObject) { dismiss(animated: true, completion: nil) } }
gpl-2.0
aaf0bf1dd1d05fd38d49487ed3d287fa
36.25
173
0.645638
5.445906
false
false
false
false
ffried/FFFoundation
Sources/FFFoundation/Extensions/OperationQueue+FFAdditions.swift
1
1718
// // OperationQueue+FFAdditions.swift // FFFoundation // // Created by Florian Friedrich on 10.12.14. // Copyright 2014 Florian Friedrich // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import class Foundation.OperationQueue import class Foundation.BlockOperation extension OperationQueue { public var isMain: Bool { self === type(of: self).main } public var isCurrent: Bool { type(of: self).current.flatMap { $0 === self } ?? false } public func addOperation(with block: @escaping () -> (), completion: @escaping () -> ()) { let operation = BlockOperation(block: block) operation.completionBlock = completion addOperation(operation) } public func addOperationWithBlockAndWait(block: @escaping () -> ()) { addOperation(with: block, andWait: true) } public func addOperationWithBlockAndWaitIfNotCurrentQueue(block: @escaping () -> ()) { addOperation(with: block, andWait: !isCurrent) } private final func addOperation(with block: @escaping () -> (), andWait wait: Bool) { let operation = BlockOperation(block: block) addOperations([operation], waitUntilFinished: wait) } }
apache-2.0
6d2eb8c69d8923182b58eaf40ae3dafe
35.553191
94
0.687427
4.393862
false
false
false
false
pluralsight/PSOperations
PSOperationsLocation/Location+OSX.swift
1
2526
#if os(OSX) import CoreLocation import Foundation import PSOperations public struct Location: CapabilityType { public static let name = "Location" public init() { } public func requestStatus(_ completion: @escaping (CapabilityStatus) -> Void) { guard CLLocationManager.locationServicesEnabled() else { completion(.notAvailable) return } let actual = CLLocationManager.authorizationStatus() switch actual { case .notDetermined: completion(.notDetermined) case .restricted: completion(.notAvailable) case .denied: completion(.denied) case .authorized: completion(.authorized) default: completion(.authorized) } } public func authorize(_ completion: @escaping (CapabilityStatus) -> Void) { Authorizer.authorize(completion: completion) } } private let Authorizer = LocationAuthorizer() private class LocationAuthorizer: NSObject, CLLocationManagerDelegate { private let manager = CLLocationManager() private var completion: ((CapabilityStatus) -> Void)? override init() { super.init() manager.delegate = self } func authorize(completion: @escaping (CapabilityStatus) -> Void) { guard self.completion == nil else { fatalError("Attempting to authorize location when a request is already in-flight") } self.completion = completion let key = "NSLocationUsageDescription" manager.startUpdatingLocation() // This is helpful when developing an app. assert(Bundle.main.object(forInfoDictionaryKey: key) != nil, "Requesting location permission requires the \(key) key in your Info.plist") } @objc func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if let completion = self.completion, manager == self.manager { self.completion = nil switch status { case .authorized: completion(.authorized) case .denied: completion(.denied) case .restricted: completion(.notAvailable) case .notDetermined: self.completion = completion manager.startUpdatingLocation() manager.stopUpdatingLocation() default: completion(.authorized) } } } } #endif
apache-2.0
079e2945eacae357bf06eb6c0d869145
28.372093
145
0.619161
5.689189
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Room/ViewModel/RoomAnchorVM.swift
1
1631
// // RoomAnchorVM.swift // DYZB // // Created by xiudou on 16/10/30. // Copyright © 2016年 xiudo. All rights reserved. // import UIKit class RoomAnchorVM: NSObject { fileprivate let urlS = "http://live.9158.com/Fans/GetHotLive?page=" // lazy var roomAnchor : RoomAnchorModel = RoomAnchorModel() lazy var roomYKModelArray : [RoomYKModel] = [RoomYKModel]() func getRoomAnchorData(_ page : Int,finishCallBack : @escaping ()->(),noDataCallBack:@escaping ()->()){ // 此处用的是YK/MB的链接 let urlString = urlS + String(page) print(urlString) NetworkTools.requestData(.get ,URLString: urlString, parameters: nil) { (result) -> () in // print("page==\(page)",result) guard let resultDict = result as? [String : NSObject] else {return} guard let dict = resultDict["data"] as? [String : NSObject] else { return } guard let dictArray = dict["list"] as? [[String : NSObject]] else { return } if dictArray.count == 0{ noDataCallBack() return } if page == 1{ self.roomYKModelArray.removeAll() } for dic in dictArray{ let roomYkM = RoomYKModel(dic: dic) // print(roomYkM.myname) self.roomYKModelArray.append(roomYkM) } // let roomModel = RoomAnchorModel(dict: dict) // self.roomAnchor = roomModel finishCallBack() } } }
mit
1bbff71ad7d09a85ea3f480a28a1f387
29.415094
107
0.533499
4.392371
false
false
false
false
nerdycat/Cupcake
Cupcake/AttStr.swift
1
14004
// // AttStr.swift // Cupcake // // Created by nerdycat on 2017/3/17. // Copyright © 2017 nerdycat. All rights reserved. // import UIKit /** * Create NSMutableAttributedString with String or UIImage. * Usages: AttStr("hello world").select("world").color("red") AttStr("A big smile ", Img("smile"), " !!") //insert image attachment */ public func AttStr(_ objects: Any?...) -> NSMutableAttributedString { let result = NSMutableAttributedString() for object in objects { var subAtt: NSAttributedString? = nil if object is NSAttributedString { subAtt = object as? NSAttributedString } else if object is String { subAtt = NSAttributedString(string: object as! String) } else if object is UIImage { let attachment = NSTextAttachment() attachment.image = object as? UIImage subAtt = NSAttributedString(attachment: attachment) } if subAtt != nil { result.append(subAtt!) } } result.cpk_select(range: NSMakeRange(0, result.length), setFlag: false) return result } public extension NSMutableAttributedString { /** * NSFontAttributeName * font use Font() internally, so it can take any kind of values that Font() supported. * See Font.siwft for more information. * Usages: .font(15) .font("20") .font("body") .font(someLabel.font) ... */ @discardableResult func font(_ style: Any) -> Self { cpk_addAttribute(name: "NSFont", value: Font(style)) return self } /** * NSForegroundColorAttributeName * color use Color() internally, so it can take any kind of values that Color() supported. * See Color.swift for more information. * Usages: .color(@"red") .color(@"#F00") .color(@"255,0,0") .color(someView.backgroundColor) ... */ @discardableResult func color(_ any: Any) -> Self { cpk_addAttribute(name: "NSColor", value: Color(any)!) return self } /** * NSBackgroundColorAttributeName * bg use Color() internally, so it can take any kind of values that Color() supported. * See Color.swift for more information. * Usages: .bg(@"red") .bg(@"#F00") .bg(@"255,0,0") .bg(someView.backgroundColor) .bg("cat") //using image ... */ @discardableResult func bg(_ any: Any) -> Self { cpk_addAttribute(name: "NSBackgroundColor", value: Color(any) ?? Color(Img(any))!) return self } /** * NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName * underline's second argument use Color() internally, so it can take any kind of values that Color() supported. * See Color.swift for more information. * Usages: .underline() //single underline with the same color of text .underline(.patternDash) //dash underline with the same color of text .underline("red") //single underline with red color .underline(.styleDouble, "red") //double underline with red color ... */ #if swift(>=4.2) @discardableResult func underline(_ style: NSUnderlineStyle = .single, _ color: Any? = nil) -> Self { var styles = NSNumber(value: style.rawValue) let lineStyle: NSUnderlineStyle = [.single, .thick, .double] if style.rawValue != 0 && (style.rawValue & lineStyle.rawValue == 0) { styles = NSNumber(value: style.rawValue | NSUnderlineStyle.single.rawValue) } cpk_addAttribute(name: "NSUnderline", value: styles) if let underlineColor = Color(color) { cpk_addAttribute(name: "NSUnderlineColor", value: underlineColor) } return self } #else @discardableResult public func underline(_ style: NSUnderlineStyle = .styleSingle, _ color: Any? = nil) -> Self { var styles = NSNumber(value: style.rawValue) if style != .styleNone && style != .styleSingle && style != .styleThick && style != .styleDouble { styles = NSNumber(value: style.rawValue | NSUnderlineStyle.styleSingle.rawValue) } cpk_addAttribute(name: "NSUnderline", value: styles) if let underlineColor = Color(color) { cpk_addAttribute(name: "NSUnderlineColor", value: underlineColor) } return self } #endif @discardableResult func underline(_ color: Any) -> Self { #if swift(>=4.2) return underline(.single, color) #else return underline(.styleSingle, color) #endif } /** * NSStrikethroughStyleAttributeName, NSStrikethroughColorAttributeName * strikethrough's second argument use Color() internally, so it can take any kind of values that Color() supported. * See Color.swift for more information. * Usages: .strikethrough() //single strikethrough with the same color of text .strikethrough(.patternDash) //dash strikethrough with the same color of text .strikethrough("red") //single strikethrough with red color .strikethrough(.styleDouble, "red") //double strikethrough with red color ... */ #if swift(>=4.2) @discardableResult func strikethrough(_ style: NSUnderlineStyle = .single, _ color: Any? = nil) -> Self { var styles = NSNumber(value: style.rawValue) let lineStyle: NSUnderlineStyle = [.single, .thick, .double] if style.rawValue != 0 && (style.rawValue & lineStyle.rawValue == 0) { styles = NSNumber(value: style.rawValue | NSUnderlineStyle.single.rawValue) } cpk_addAttribute(name: "NSStrikethrough", value: styles) if let strikethroughColor = Color(color) { cpk_addAttribute(name: "NSStrikethroughColor", value: strikethroughColor) } return self } #else @discardableResult public func strikethrough(_ style: NSUnderlineStyle = .styleSingle, _ color: Any? = nil) -> Self { var styles = NSNumber(value: style.rawValue) if style != .styleNone && style != .styleSingle && style != .styleThick && style != .styleDouble { styles = NSNumber(value: style.rawValue | NSUnderlineStyle.styleSingle.rawValue) } cpk_addAttribute(name: "NSStrikethrough", value: styles) if let strikethroughColor = Color(color) { cpk_addAttribute(name: "NSStrikethroughColor", value: strikethroughColor) } return self } #endif @discardableResult func strikethrough(_ color: Any) -> Self { #if swift(>=4.2) return strikethrough(.single, color) #else return strikethrough(.styleSingle, color) #endif } /** * NSStrokeWidthAttributeName, NSStrokeColorAttributeName * stroke's second argument use Color() internally, so it can take any kind of values that Color() supported. * See Color.swift for more information. * Usages: .stroke(1) .stroke(-4, "red") */ @discardableResult func stroke(_ width: CGFloat, _ color: Any? = nil) -> Self { cpk_addAttribute(name: "NSStrokeWidth", value: width) if let strokeColor = Color(color) { cpk_addAttribute(name: "NSStrokeColor", value: strokeColor) } return self } /** * NSObliquenessAttributeName * Usages: .oblique(0.3) .oblique(-0.3) */ @discardableResult func oblique(_ value: CGFloat) -> Self { cpk_addAttribute(name: "NSObliqueness", value: value) return self } /** * NSBaselineOffsetAttributeName * Usages: .offset(20) .offset(-20) */ @discardableResult func offset(_ offset: CGFloat) -> Self { cpk_addAttribute(name: "NSBaselineOffset", value: offset) return self } /** * NSLinkAttributeName * Also can be used to add clickable link for UILabel. * Usages: .link("http://www.google.com") .link() //mark as link for UILabel */ @discardableResult func link(_ url: String? = nil) -> Self { if let urlString = url { cpk_addAttribute(name: "NSLink", value: urlString) } else { cpk_addAttribute(name: CPKLabelLinkAttributeName, value: CPKLabelLinkAttributeValue) } return self } /** * Line spacing * Usages: .lineGap(10) */ @discardableResult func lineGap(_ spacing: CGFloat) -> Self { cpk_addParagraphAttribute(key: "lineSpacing", value: spacing) return self } /** * First line head indent * Usages: .indent(20) */ @discardableResult func indent(_ headIntent: CGFloat) -> Self { cpk_addParagraphAttribute(key: "firstLineHeadIndent", value: headIntent) return self } /** * TextAlignment * Usages: .align(.center) .align(.justified) ... */ @discardableResult func align(_ alignment: NSTextAlignment) -> Self { cpk_addParagraphAttribute(key: "alignment", value: NSNumber(value: alignment.rawValue)) return self } /** * Select substrings * By default Attributes are applied to the whole string. You can make them only affect some parts of them by selecting substrings with regular expression or range. * You can pass multiply options at the same time. * See AttStrSelectionOptions for more information. * Usages: AttStr("hello world").select("world").color("red") //only "world" are red AttStr("abc123").select("[a-z]+").color("red") //only "abc" are red AttStr("abc123").select(.number).color("red") //only "123" are red AttStr("@Tim at #Apple").select(.nameTag, .hashTag).color("red") //@Tim" and "#Apple" are red AttStr("@Tim at #apple").select(.range(5, 2)).color("red") //only "@at" are red ... * .select("pattern") is just the shorthand of .select(.match("pattern")) */ @discardableResult func select(_ optionOrStringLiterals: AttStrSelectionOptions...) -> Self { for option in optionOrStringLiterals { var regExp: NSRegularExpression? var patternString: String? var selectedRange = false switch option { case .all: cpk_select(range: NSMakeRange(0, self.length)) case .url: regExp = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) case .date: regExp = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue) case .phoneNumber: regExp = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue) case .hashTag: patternString = "(?<!\\w)#([\\w\\_]+)?" case .nameTag: patternString = "(?<!\\w)@([\\w\\_]+)?" case .number: patternString = "\\d+(\\.\\d+)?" case let .match(value): if let regExpObject = value as? NSRegularExpression { regExp = regExpObject } else { patternString = String(describing: value) } case let .range(location, length): cpk_select(range: NSMakeRange(location >= 0 ? location : self.length + location, length)) return self } if patternString != nil { regExp = try? NSRegularExpression(pattern: patternString!, options: NSRegularExpression.Options(rawValue: 0)) } if regExp != nil { let matches = regExp!.matches(in: self.string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.length)) for result in matches { cpk_select(range: result.range) selectedRange = true } } if !selectedRange { cpk_select(range: nil) } } return self } /** * Prevent overriding attribute. * By default, the attribute value applied later will override the previous one if they are the same attributes. * Usages: AttStr(@"hello").color(@"red").color(@"green") //green color AttStr(@"hello").color(@"red").preventOverride.color(@"green") //red color */ @discardableResult func preventOverride(_ flag: Bool = true) -> Self { self.cpkPreventOverrideAttribute = flag return self } } public enum AttStrSelectionOptions { case all //select whole string case url //select all urls case date //select all dates case number //select all numbers case phoneNumber //select all phone numbers case hashTag //select all hash tags case nameTag //select all name tags case match(Any) //select substrings with regExp pattern or regExp Object case range(Int, Int) //select substring with range }
mit
f38269651364a2eff3156b2f23835cfb
35.371429
121
0.56495
4.828621
false
false
false
false
sharath-cliqz/browser-ios
Sync/Synchronizers/Bookmarks/BookmarksSynchronizer.swift
2
17397
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger typealias UploadFunction = ([Record<BookmarkBasePayload>], _ lastTimestamp: Timestamp?, _ onUpload: @escaping (POSTResult, Timestamp?) -> DeferredTimestamp) -> DeferredTimestamp class TrivialBookmarkStorer: BookmarkStorer { let uploader: UploadFunction init(uploader: @escaping UploadFunction) { self.uploader = uploader } func applyUpstreamCompletionOp(_ op: UpstreamCompletionOp, itemSources: ItemSources, trackingTimesInto local: LocalOverrideCompletionOp) -> Deferred<Maybe<POSTResult>> { log.debug("Uploading \(op.records.count) modified records.") log.debug("Uploading \(op.amendChildrenFromBuffer.count) amended buffer records.") log.debug("Uploading \(op.amendChildrenFromMirror.count) amended mirror records.") log.debug("Uploading \(op.amendChildrenFromLocal.count) amended local records.") var records: [Record<BookmarkBasePayload>] = [] records.reserveCapacity(op.records.count + op.amendChildrenFromBuffer.count + op.amendChildrenFromLocal.count + op.amendChildrenFromMirror.count) records.append(contentsOf: op.records) func accumulateFromAmendMap(_ itemsWithNewChildren: [GUID: [GUID]], fetch: ([GUID: [GUID]]) -> Maybe<[GUID: BookmarkMirrorItem]>) throws /* MaybeErrorType */ { if itemsWithNewChildren.isEmpty { return } let fetched = fetch(itemsWithNewChildren) guard let items = fetched.successValue else { log.warning("Couldn't fetch items to amend.") throw fetched.failureValue! } items.forEach { (guid, item) in let payload = item.asPayloadWithChildren(itemsWithNewChildren[guid]) let mappedGUID = payload["id"].string ?? guid let record = Record<BookmarkBasePayload>(id: mappedGUID, payload: payload) records.append(record) } } do { try accumulateFromAmendMap(op.amendChildrenFromBuffer, fetch: { itemSources.buffer.getBufferItemsWithGUIDs($0.keys).value }) try accumulateFromAmendMap(op.amendChildrenFromMirror, fetch: { itemSources.mirror.getMirrorItemsWithGUIDs($0.keys).value }) try accumulateFromAmendMap(op.amendChildrenFromLocal, fetch: { itemSources.local.getLocalItemsWithGUIDs($0.keys).value }) } catch { return deferMaybe(error as! MaybeErrorType) } var success: [GUID] = [] var failed: [GUID: String] = [:] func onUpload(_ result: POSTResult, lastModified: Timestamp?) -> DeferredTimestamp { success.append(contentsOf: result.success) result.failed.forEach { guid, message in failed[guid] = message } log.debug("Uploaded records got timestamp \(lastModified).") let modified = lastModified ?? 0 local.setModifiedTime(modified, guids: result.success) return deferMaybe(modified) } // Chain the last upload timestamp right into our lastFetched timestamp. // This is what Sync clients tend to do, but we can probably do better. return uploader(records, op.ifUnmodifiedSince, onUpload) // As if we uploaded everything in one go. >>> { deferMaybe(POSTResult(success: success, failed: failed)) } } } // MARK: - External synchronizer interface. open class BufferingBookmarksSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "bookmarks") } override var storageVersion: Int { return BookmarksStorageVersion } open func synchronizeBookmarksToStorage(_ storage: SyncableBookmarks & LocalItemSource & MirrorItemSource, usingBuffer buffer: BookmarkBufferStorage & BufferItemSource, withServer storageClient: Sync15StorageClient, info: InfoCollections, greenLight: @escaping () -> Bool) -> SyncResult { if let reason = self.reasonToNotSync(storageClient) { return deferMaybe(.notStarted(reason)) } let encoder = RecordEncoder<BookmarkBasePayload>(decode: BookmarkType.somePayloadFromJSON, encode: { $0.json }) guard let bookmarksClient = self.collectionClient(encoder, storageClient: storageClient) else { log.error("Couldn't make bookmarks factory.") return deferMaybe(FatalError(message: "Couldn't make bookmarks factory.")) } let start = Date.nowMicroseconds() let mirrorer = BookmarksMirrorer(storage: buffer, client: bookmarksClient, basePrefs: self.prefs, collection: "bookmarks") let storer = TrivialBookmarkStorer(uploader: { records, lastTimestamp, onUpload in // Default to our last fetch time for If-Unmodified-Since. let timestamp = lastTimestamp ?? self.lastFetched return self.uploadRecords(records, lastTimestamp: timestamp, storageClient: bookmarksClient, onUpload: onUpload) >>== effect { timestamp in // We need to advance our batching downloader timestamp to match. See Bug 1253458. self.setTimestamp(timestamp) mirrorer.advanceNextDownloadTimestampTo(timestamp: timestamp) } }) let doMirror = mirrorer.go(info: info, greenLight: greenLight) let run: SyncResult if !AppConstants.shouldMergeBookmarks { if case .Release = AppConstants.BuildChannel { // On release, just mirror; don't validate. run = doMirror } else { run = doMirror >>== effect({ result in // Just validate to report statistics. if case .completed = result { log.debug("Validating completed buffer download.") let _ = buffer.validate() } }) } } else { run = doMirror >>== { result in // Only bother trying to sync if the mirror operation wasn't interrupted or partial. if case .completed = result { let applier = MergeApplier(buffer: buffer, storage: storage, client: storer, greenLight: greenLight) return applier.go() } return deferMaybe(result) } } run.upon { result in let end = Date.nowMicroseconds() let duration = end - start log.info("Bookmark \(AppConstants.shouldMergeBookmarks ? "sync" : "mirroring") took \(duration)µs. Result was \(result.successValue?.description ?? result.failureValue?.description ?? "failure")") } return run } } class MergeApplier { let greenLight: () -> Bool let buffer: BookmarkBufferStorage let storage: SyncableBookmarks let client: BookmarkStorer let merger: BookmarksStorageMerger init(buffer: BookmarkBufferStorage & BufferItemSource, storage: SyncableBookmarks & LocalItemSource & MirrorItemSource, client: BookmarkStorer, greenLight: @escaping () -> Bool) { self.greenLight = greenLight self.buffer = buffer self.storage = storage self.merger = ThreeWayBookmarksStorageMerger(buffer: buffer, storage: storage) self.client = client } // Exposed for use from tests. func applyResult(_ result: BookmarksMergeResult) -> Success { return result.applyToClient(self.client, storage: self.storage, buffer: self.buffer) } func go() -> SyncResult { guard self.greenLight() else { log.info("Green light turned red; not merging bookmarks.") return deferMaybe(SyncStatus.completed) } return self.merger.merge() >>== self.applyResult >>> always(SyncStatus.completed) } } /** * The merger takes as input an existing storage state (mirror and local override), * a buffer of new incoming records that relate to the mirror, and performs a three-way * merge. * * The merge itself does not mutate storage. The result of the merge is conceptually a * tuple: a new mirror state, a set of reconciled + locally changed records to upload, * and two checklists of buffer and local state to discard. * * Typically the merge will be complete, resulting in a new mirror state, records to * upload, and completely emptied buffer and local. In the case of partial inconsistency * this will not be the case; incomplete subtrees will remain in the buffer. (We don't * expect local subtrees to ever be incomplete.) * * It is expected that the caller will immediately apply the result in this order: * * 1. Upload the remote changes, if any. If this fails we can retry the entire process. * * 2(a). Apply the local changes, if any. If this fails we will re-download the records * we just uploaded, and should reach the same end state. * This step takes a timestamp key from (1), because pushing a record into the mirror * requires a server timestamp. * * 2(b). Switch to the new mirror state. If this fails, we should find that our reconciled * server contents apply neatly to our mirror and empty local, and we'll reach the * same end state. * * Mirror state is applied in a sane order to respect relational constraints, even though * we configure sqlite to defer constraint validation until the transaction is committed. * That means: * * - Add any new records in the value table. * - Change any existing records in the value table. * - Update structure. * - Remove records from the value table. * * 3. Apply buffer changes. We only do this after the mirror has advanced; if we fail to * clean up the buffer, it'll reconcile neatly with the mirror on a subsequent try. * * 4. Update bookkeeping timestamps. If this fails we will download uploaded records, * find they match, and have no repeat merging work to do. * * The goal of merging is that the buffer is empty (because we reconciled conflicts and * updated the server), our local overlay is empty (because we reconciled conflicts and * applied our changes to the server), and the mirror matches the server. * * Note that upstream application is robust: we can use XIUS to ensure that writes don't * race. Buffer application is similarly robust, because this code owns all writes to the * buffer. Local and mirror application, however, is not: the user's actions can cause * changes to write to the database before we're done applying the results of a sync. * We mitigate this a little by being explicit about the local changes that we're flushing * (rather than, say, `DELETE FROM local`), but to do better we'd need change detection * (e.g., an in-memory monotonic counter) or locking to prevent bookmark operations from * racing. Later! */ protocol BookmarksStorageMerger: class { init(buffer: BookmarkBufferStorage & BufferItemSource, storage: SyncableBookmarks & LocalItemSource & MirrorItemSource) func merge() -> Deferred<Maybe<BookmarksMergeResult>> } class NoOpBookmarksMerger: BookmarksStorageMerger { let buffer: BookmarkBufferStorage & BufferItemSource let storage: SyncableBookmarks & LocalItemSource & MirrorItemSource required init(buffer: BookmarkBufferStorage & BufferItemSource, storage: SyncableBookmarks & LocalItemSource & MirrorItemSource) { self.buffer = buffer self.storage = storage } func merge() -> Deferred<Maybe<BookmarksMergeResult>> { return deferMaybe(BookmarksMergeResult.NoOp(ItemSources(local: self.storage, mirror: self.storage, buffer: self.buffer))) } } class ThreeWayBookmarksStorageMerger: BookmarksStorageMerger { let buffer: BookmarkBufferStorage & BufferItemSource let storage: SyncableBookmarks & LocalItemSource & MirrorItemSource required init(buffer: BookmarkBufferStorage & BufferItemSource, storage: SyncableBookmarks & LocalItemSource & MirrorItemSource) { self.buffer = buffer self.storage = storage } // MARK: - BookmarksStorageMerger. // Trivial one-way sync. fileprivate func applyLocalDirectlyToMirror() -> Deferred<Maybe<BookmarksMergeResult>> { // Theoretically, we do the following: // * Construct a virtual bookmark tree overlaying local on the mirror. // * Walk the tree to produce Sync records. // * Upload those records. // * Flatten that tree into the mirror, clearing local. // // This is simpler than a full three-way merge: it's tree delta then flatten. // // But we are confident that our local changes, when overlaid on the mirror, are // consistent. So we can take a little bit of a shortcut: process records // directly, rather than building a tree. // // So do the following: // * Take everything in `local` and turn it into a Sync record. This means pulling // folder hierarchies out of localStructure, values out of local, and turning // them into records. Do so in hierarchical order if we can, and set sortindex // attributes to put folders first. // * Upload those records in as few batches as possible. Ensure that each batch // is consistent, if at all possible, though we're hoping for server support for // atomic writes. // * Take everything in local that was successfully uploaded and move it into the // mirror, using the timestamps we tracked from the upload. // // Optionally, set 'again' to true in our response, and do this work only for a // particular subtree (e.g., a single root, or a single branch of changes). This // allows us to make incremental progress. // TODO log.debug("No special-case local-only merging yet. Falling back to three-way merge.") return self.threeWayMerge() } fileprivate func applyIncomingDirectlyToMirror() -> Deferred<Maybe<BookmarksMergeResult>> { // If the incoming buffer is consistent -- and the result of the mirrorer // gives us a hint about that! -- then we can move the buffer records into // the mirror directly. // // Note that this is also true for entire subtrees: if none of the children // of, say, 'menu________' are modified locally, then we can apply it without // merging. // // TODO log.debug("No special-case remote-only merging yet. Falling back to three-way merge.") return self.threeWayMerge() } // This is exposed for testing. func getMerger() -> Deferred<Maybe<ThreeWayTreeMerger>> { return self.storage.treesForEdges() >>== { (local, remote) in // At this point *might* have two empty trees. This should only be the case if // there are value-only changes (e.g., a renamed bookmark). // We don't fail in that case, but we could optimize here. // Find the mirror tree so we can compare. return self.storage.treeForMirror() >>== { mirror in // At this point we know that there have been changes both locally and remotely. // (Or, in the general case, changes either locally or remotely.) let itemSources = ItemSources(local: CachingLocalItemSource(source: self.storage), mirror: CachingMirrorItemSource(source: self.storage), buffer: CachingBufferItemSource(source: self.buffer)) return deferMaybe(ThreeWayTreeMerger(local: local, mirror: mirror, remote: remote, itemSources: itemSources)) } } } func getMergedTree() -> Deferred<Maybe<MergedTree>> { return self.getMerger() >>== { $0.produceMergedTree() } } func threeWayMerge() -> Deferred<Maybe<BookmarksMergeResult>> { return self.getMerger() >>== { $0.produceMergedTree() >>== $0.produceMergeResultFromMergedTree } } func merge() -> Deferred<Maybe<BookmarksMergeResult>> { return self.buffer.isEmpty() >>== { noIncoming in // TODO: the presence of empty desktop roots in local storage // isn't something we really need to worry about. Can we skip it here? return self.storage.isUnchanged() >>== { noOutgoing in switch (noIncoming, noOutgoing) { case (true, true): // Nothing to do! log.debug("No incoming and no outgoing records: no-op.") return deferMaybe(BookmarksMergeResult.NoOp(ItemSources(local: self.storage, mirror: self.storage, buffer: self.buffer))) case (true, false): // No incoming records to apply. Unilaterally apply local changes. return self.applyLocalDirectlyToMirror() case (false, true): // No outgoing changes. Unilaterally apply remote changes if they're consistent. return self.buffer.validate() >>> self.applyIncomingDirectlyToMirror default: // Changes on both sides. Merge. return self.buffer.validate() >>> self.threeWayMerge } } } } }
mpl-2.0
9ecb5b8333fd87713ca1ecc79dddb0f2
46.016216
292
0.677397
4.705437
false
false
false
false
DaveWoodCom/XCGLogger
DemoApps/macOSDemo/macOSDemo/AppDelegate.swift
1
9429
// // AppDelegate.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2014-06-06. // Copyright © 2014 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // import Cocoa import XCGLogger let appDelegate = NSApplication.shared.delegate as! AppDelegate let log: XCGLogger = { // Setup XCGLogger (Advanced/Recommended Usage) // Create a logger object with no destinations let log = XCGLogger(identifier: "advancedLogger", includeDefaultDestinations: false) // Create a destination for the system console log (via NSLog) let systemDestination = AppleSystemLogDestination(identifier: "advancedLogger.appleSystemLogDestination") // Optionally set some configuration options systemDestination.outputLevel = .debug systemDestination.showLogIdentifier = false systemDestination.showFunctionName = true systemDestination.showThreadName = true systemDestination.showLevel = true systemDestination.showFileName = true systemDestination.showLineNumber = true // Add the destination to the logger log.add(destination: systemDestination) // Create a file log destination let logPath: String = "/tmp/XCGLogger_macOSDemo.log" let autoRotatingFileDestination = AutoRotatingFileDestination(writeToFile: logPath, identifier: "advancedLogger.fileDestination", shouldAppend: true, maxFileSize: 1024 * 5, // 5k, not a good size for production (default is 1 megabyte) maxTimeInterval: 60, // 1 minute, also not good for production (default is 10 minutes) targetMaxLogFiles: 20) // Default is 10, max is 255 // Optionally set some configuration options autoRotatingFileDestination.outputLevel = .debug autoRotatingFileDestination.showLogIdentifier = false autoRotatingFileDestination.showFunctionName = true autoRotatingFileDestination.showThreadName = true autoRotatingFileDestination.showLevel = true autoRotatingFileDestination.showFileName = true autoRotatingFileDestination.showLineNumber = true autoRotatingFileDestination.showDate = true // Process this destination in the background autoRotatingFileDestination.logQueue = XCGLogger.logQueue // Add colour (using the ANSI format) to our file log, you can see the colour when `cat`ing or `tail`ing the file in Terminal on macOS let ansiColorLogFormatter: ANSIColorLogFormatter = ANSIColorLogFormatter() ansiColorLogFormatter.colorize(level: .verbose, with: .colorIndex(number: 244), options: [.faint]) ansiColorLogFormatter.colorize(level: .debug, with: .black) ansiColorLogFormatter.colorize(level: .info, with: .blue, options: [.underline]) ansiColorLogFormatter.colorize(level: .notice, with: .green, options: [.italic]) ansiColorLogFormatter.colorize(level: .warning, with: .red, options: [.faint]) ansiColorLogFormatter.colorize(level: .error, with: .red, options: [.bold]) ansiColorLogFormatter.colorize(level: .severe, with: .white, on: .red) ansiColorLogFormatter.colorize(level: .alert, with: .white, on: .red, options: [.bold]) ansiColorLogFormatter.colorize(level: .emergency, with: .white, on: .red, options: [.bold, .blink]) autoRotatingFileDestination.formatters = [ansiColorLogFormatter] // Add the destination to the logger log.add(destination: autoRotatingFileDestination) // Add basic app info, version info etc, to the start of the logs log.logAppDetails() return log }() let dateHashFormatter: DateFormatter = { let dateHashFormatter = DateFormatter() dateHashFormatter.locale = NSLocale.current dateHashFormatter.dateFormat = "yyyy-MM-dd_HHmmss_SSS" return dateHashFormatter }() @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Properties @IBOutlet var window: NSWindow! @IBOutlet var logLevelTextField: NSTextField! @IBOutlet var currentLogLevelTextField: NSTextField! @IBOutlet var generateTestLogTextField: NSTextField! @IBOutlet var logLevelSlider: NSSlider! // MARK: - Life cycle methods func applicationDidFinishLaunching(_ notification: Notification) { // Insert code here to initialize your application updateView() } func applicationWillTerminate(_ notification: Notification) { // Insert code here to tear down your application } // MARK: - Main View @IBAction func verboseButtonTouchUpInside(_ sender: AnyObject) { log.verbose("Verbose button tapped") log.verbose { // add expensive code required only for logging, then return an optional String return "Executed verbose code block" // or nil } } @IBAction func debugButtonTouchUpInside(_ sender: AnyObject) { log.debug("Debug button tapped") log.debug { // add expensive code required only for logging, then return an optional String return "Executed debug code block" // or nil } } @IBAction func infoButtonTouchUpInside(_ sender: AnyObject) { log.info("Info button tapped") log.info { // add expensive code required only for logging, then return an optional String return "Executed info code block" // or nil } } @IBAction func noticeButtonTouchUpInside(_ sender: AnyObject) { log.notice("Notice button tapped") log.notice { // add expensive code required only for logging, then return an optional String return "Executed notice code block" // or nil } } @IBAction func warningButtonTouchUpInside(_ sender: AnyObject) { log.warning("Warning button tapped") log.warning { // add expensive code required only for logging, then return an optional String return "Executed warning code block" // or nil } } @IBAction func errorButtonTouchUpInside(_ sender: AnyObject) { log.error("Error button tapped") log.error { // add expensive code required only for logging, then return an optional String return "Executed error code block" // or nil } } @IBAction func severeButtonTouchUpInside(_ sender: AnyObject) { log.severe("Severe button tapped") log.severe { // add expensive code required only for logging, then return an optional String return "Executed severe code block" // or nil } } @IBAction func alertButtonTouchUpInside(_ sender: AnyObject) { log.alert("Alert button tapped") log.alert { // add expensive code required only for logging, then return an optional String return "Executed alert code block" // or nil } } @IBAction func emergencyButtonTouchUpInside(_ sender: AnyObject) { log.emergency("Emergency button tapped") log.emergency { // add expensive code required only for logging, then return an optional String return "Executed emergency code block" // or nil } } @IBAction func rotateLogFileButtonTouchUpInside(_ sender: AnyObject) { guard let fileDestination = log.destination(withIdentifier: "advancedLogger.fileDestination") as? FileDestination else { log.error("File destination not found, unable to rotate the log") return } let dateHash: String = dateHashFormatter.string(from: Date()) let archiveFilePath: String = ("~/Desktop/XCGLogger_Log_\(dateHash).txt" as NSString).expandingTildeInPath fileDestination.rotateFile(to: archiveFilePath) } @IBAction func logLevelSliderValueChanged(_ sender: AnyObject) { var logLevel: XCGLogger.Level = .verbose if (0 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 1) { logLevel = .verbose } else if (1 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 2) { logLevel = .debug } else if (2 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 3) { logLevel = .info } else if (3 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 4) { logLevel = .notice } else if (4 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 5) { logLevel = .warning } else if (5 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 6) { logLevel = .error } else if (6 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 7) { logLevel = .severe } else if (7 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 8) { logLevel = .alert } else if (8 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 9) { logLevel = .emergency } else { logLevel = .none } log.outputLevel = logLevel updateView() } func updateView() { logLevelSlider.floatValue = Float(log.outputLevel.rawValue) currentLogLevelTextField.stringValue = "\(log.outputLevel)" } }
mit
ed78d3dac04b282a55abe1552288a354
39.813853
153
0.666525
5.08248
false
false
false
false
whitepixelstudios/Material
Sources/iOS/Bar.swift
1
8231
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(ContentViewAlignment) public enum ContentViewAlignment: Int { case full case center } open class Bar: View { /// Will layout the view. open var willLayout: Bool { return 0 < bounds.width && 0 < bounds.height && nil != superview && !grid.deferred } open override var intrinsicContentSize: CGSize { return bounds.size } /// Should center the contentView. open var contentViewAlignment = ContentViewAlignment.full { didSet { layoutSubviews() } } /// A preset wrapper around contentEdgeInsets. open var contentEdgeInsetsPreset: EdgeInsetsPreset { get { return grid.contentEdgeInsetsPreset } set(value) { grid.contentEdgeInsetsPreset = value } } /// A reference to EdgeInsets. @IBInspectable open var contentEdgeInsets: EdgeInsets { get { return grid.contentEdgeInsets } set(value) { grid.contentEdgeInsets = value } } /// A preset wrapper around interimSpace. open var interimSpacePreset: InterimSpacePreset { get { return grid.interimSpacePreset } set(value) { grid.interimSpacePreset = value } } /// A wrapper around grid.interimSpace. @IBInspectable open var interimSpace: InterimSpace { get { return grid.interimSpace } set(value) { grid.interimSpace = value } } /// Grid cell factor. @IBInspectable open var gridFactor: CGFloat = 12 { didSet { assert(0 < gridFactor, "[Material Error: gridFactor must be greater than 0.]") layoutSubviews() } } /// ContentView that holds the any desired subviews. open let contentView = UIView() /// Left side UIViews. open var leftViews = [UIView]() { didSet { for v in oldValue { v.removeFromSuperview() } layoutSubviews() } } /// Right side UIViews. open var rightViews = [UIView]() { didSet { for v in oldValue { v.removeFromSuperview() } layoutSubviews() } } /// Center UIViews. open var centerViews: [UIView] { get { return contentView.grid.views } set(value) { contentView.grid.views = value } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { super.init(frame: frame) } /// Convenience initializer. public convenience init() { self.init(frame: .zero) } /** A convenience initializer with parameter settings. - Parameter leftViews: An Array of UIViews that go on the left side. - Parameter rightViews: An Array of UIViews that go on the right side. - Parameter centerViews: An Array of UIViews that go in the center. */ public convenience init(leftViews: [UIView]? = nil, rightViews: [UIView]? = nil, centerViews: [UIView]? = nil) { self.init() self.leftViews = leftViews ?? [] self.rightViews = rightViews ?? [] self.centerViews = centerViews ?? [] } open override func layoutSubviews() { super.layoutSubviews() guard willLayout else { return } var lc = 0 var rc = 0 grid.begin() grid.views.removeAll() for v in leftViews { if let b = v as? UIButton { b.contentEdgeInsets = .zero b.titleEdgeInsets = .zero } v.frame.size.width = v.intrinsicContentSize.width v.sizeToFit() v.grid.columns = Int(ceil(v.bounds.width / gridFactor)) + 2 lc += v.grid.columns grid.views.append(v) } grid.views.append(contentView) for v in rightViews { if let b = v as? UIButton { b.contentEdgeInsets = .zero b.titleEdgeInsets = .zero } v.frame.size.width = v.intrinsicContentSize.width v.sizeToFit() v.grid.columns = Int(ceil(v.bounds.width / gridFactor)) + 2 rc += v.grid.columns grid.views.append(v) } contentView.grid.begin() contentView.grid.offset.columns = 0 var l: CGFloat = 0 var r: CGFloat = 0 if .center == contentViewAlignment { if leftViews.count < rightViews.count { r = CGFloat(rightViews.count) * interimSpace l = r } else { l = CGFloat(leftViews.count) * interimSpace r = l } } let p = bounds.width - l - r - contentEdgeInsets.left - contentEdgeInsets.right let columns = Int(ceil(p / gridFactor)) if .center == contentViewAlignment { if lc < rc { contentView.grid.columns = columns - 2 * rc contentView.grid.offset.columns = rc - lc } else { contentView.grid.columns = columns - 2 * lc rightViews.first?.grid.offset.columns = lc - rc } } else { contentView.grid.columns = columns - lc - rc } grid.axis.columns = columns grid.commit() contentView.grid.commit() layoutDivider() } open override func prepare() { super.prepare() heightPreset = .normal autoresizingMask = .flexibleWidth interimSpacePreset = .interimSpace3 contentEdgeInsetsPreset = .square1 prepareContentView() } } extension Bar { /// Prepares the contentView. fileprivate func prepareContentView() { contentView.contentScaleFactor = Screen.scale } }
bsd-3-clause
5cab53f96d67347e198f400a65266b62
29.040146
116
0.580002
5.062116
false
false
false
false
zmeyc/telegram-bot-swift
Sources/TelegramBotSDK/Utils.swift
1
1696
// // Utils.swift // // This source file is part of the Telegram Bot SDK for Swift (unofficial). // // Copyright (c) 2015 - 2020 Andrey Fidrya and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information // See AUTHORS.txt for the list of the project authors // import Foundation /// Reads token from environment variable or from a file. /// /// - Returns: token. public func readToken(from name: String) -> String { guard let token: String = readConfigurationValue(name) else { print("\n" + "-----\n" + "ERROR\n" + "-----\n" + "Please create either:\n" + " - an environment variable named \(name)\n" + " - a file named \(name)\n" + "containing your bot's token.\n\n") exit(1) } return token } /// Reads value from environment variable or from a file. /// /// - Returns: `String`. public func readConfigurationValue(_ name: String) -> String? { let environment = ProcessInfo.processInfo.environment var value = environment[name] if value == nil { do { value = try String(contentsOfFile: name, encoding: String.Encoding.utf8) } catch { } } if let value = value { return value.trimmed() } return nil } /// Reads value from environment variable or from a file. /// /// - Returns: `Int64`. public func readConfigurationValue(_ name: String) -> Int64? { if let v: String = readConfigurationValue(name) { return Int64(v) } return nil } /// Reads value from environment variable or from a file. /// /// - Returns: `Int`. public func readConfigurationValue(_ name: String) -> Int? { if let v: String = readConfigurationValue(name) { return Int(v) } return nil }
apache-2.0
98ec22c928ff876ee0e9088d3505a2f4
23.228571
75
0.67158
3.358416
false
true
false
false
keithbhunter/KBHAnimatedLabels
KBHAnimatedLabels/AnimationsTableViewController.swift
1
1872
// // AnimationsTableViewController.swift // KBHAnimatedLabels // // Created by Keith Hunter on 11/2/15. // Copyright © 2015 Keith Hunter. All rights reserved. // import UIKit final class AnimationsTableViewController: UITableViewController { enum Animations: Int { case Flip case Spin case Spring case Wave case Total func stringValue() -> String { switch self { case Flip: return "Flip" case Spin: return "Spin" case Wave: return "Wave" case Spring: return "Spring" default: return "Total" } } } // MARK: UI Lifecycle override func viewDidLoad() { super.viewDidLoad() title = "Animations" } // MARK: Table View DataSource and Delegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Animations.Total.rawValue } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let animation = Animations(rawValue: indexPath.row) else { fatalError("Unexpected index path: \(indexPath.row)") } let cell = tableView.dequeueReusableCellWithIdentifier("Basic", forIndexPath: indexPath) cell.textLabel?.text = animation.stringValue() return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard let animation = Animations(rawValue: indexPath.row) else { fatalError("Unexpected index path: \(indexPath.row)") } performSegueWithIdentifier(animation.stringValue(), sender: nil) } }
mit
d3b279d356db50f0c8ba5632a813e074
29.177419
128
0.637627
5.423188
false
false
false
false
hejunbinlan/Operations
OperationsTests/LocationConditionTests.swift
1
5821
// // LocationConditionTests.swift // Operations // // Created by Daniel Thorpe on 26/07/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import XCTest import CoreLocation @testable import Operations class TestableLocationManager: NSObject, LocationManager { let fakeLocationManager = CLLocationManager() var serviceEnabled: Bool var authorizationStatus: CLAuthorizationStatus var returnedStatus = CLAuthorizationStatus.AuthorizedAlways var returnedLocation: CLLocation! var didSetDelegate = false var didSetDesiredAccuracy: CLLocationAccuracy? = .None var didRequestWhenInUseAuthorization = false var didRequestAlwaysAuthorization = false var didStartUpdatingLocation = false var didStopLocationUpdates = false weak var delegate: CLLocationManagerDelegate! init(enabled: Bool, status: CLAuthorizationStatus) { serviceEnabled = enabled authorizationStatus = status } func opr_setDesiredAccuracy(accuracy: CLLocationAccuracy) { didSetDesiredAccuracy = accuracy } func opr_setDelegate(aDelegate: CLLocationManagerDelegate) { didSetDelegate = true delegate = aDelegate } func opr_requestWhenInUseAuthorization() { didRequestWhenInUseAuthorization = true changeStatus() } func opr_requestAlwaysAuthorization() { didRequestAlwaysAuthorization = true changeStatus() } func opr_startUpdatingLocation() { didStartUpdatingLocation = true delegate.locationManager!(fakeLocationManager, didUpdateLocations: [returnedLocation]) } func opr_stopLocationUpdates() { didStopLocationUpdates = true } private func changeStatus() { authorizationStatus = returnedStatus switch authorizationStatus { case .AuthorizedAlways, .AuthorizedWhenInUse: serviceEnabled = true default: serviceEnabled = false } delegate.locationManager!(fakeLocationManager, didChangeAuthorizationStatus: returnedStatus) } } class LocationConditionTests: OperationTests { func test__service_enabled_with_always__then__permission_not_requested() { let locationManager = TestableLocationManager(enabled: true, status: .AuthorizedAlways) let operation = TestOperation() operation.addCondition(LocationCondition(usage: .Always, manager: locationManager)) addCompletionBlockToTestOperation(operation, withExpectation: expectationWithDescription("Test: \(__FUNCTION__)")) runOperation(operation) waitForExpectationsWithTimeout(3, handler: nil) XCTAssertTrue(operation.finished) XCTAssertFalse(locationManager.didRequestAlwaysAuthorization) XCTAssertFalse(locationManager.didRequestWhenInUseAuthorization) } func test__service_enabled_with_when_in_use__then__permission_not_requested() { let locationManager = TestableLocationManager(enabled: true, status: .AuthorizedWhenInUse) let operation = TestOperation() operation.addCondition(LocationCondition(usage: .WhenInUse, manager: locationManager)) addCompletionBlockToTestOperation(operation, withExpectation: expectationWithDescription("Test: \(__FUNCTION__)")) runOperation(operation) waitForExpectationsWithTimeout(3, handler: nil) XCTAssertTrue(operation.finished) XCTAssertFalse(locationManager.didRequestAlwaysAuthorization) XCTAssertFalse(locationManager.didRequestWhenInUseAuthorization) } func test__service_enabled_with_in_user_but_always_required_then__always_permissions_requested() { let locationManager = TestableLocationManager(enabled: true, status: .AuthorizedWhenInUse) let operation = TestOperation() operation.addCondition(LocationCondition(usage: .Always, manager: locationManager)) addCompletionBlockToTestOperation(operation, withExpectation: expectationWithDescription("Test: \(__FUNCTION__)")) runOperation(operation) waitForExpectationsWithTimeout(3, handler: nil) XCTAssertTrue(operation.finished) XCTAssertTrue(locationManager.didRequestAlwaysAuthorization) XCTAssertFalse(locationManager.didRequestWhenInUseAuthorization) } func test__service_disabled__then__always_permissions_requested() { let locationManager = TestableLocationManager(enabled: false, status: .NotDetermined) let operation = TestOperation() operation.addCondition(LocationCondition(usage: .Always, manager: locationManager)) addCompletionBlockToTestOperation(operation, withExpectation: expectationWithDescription("Test: \(__FUNCTION__)")) runOperation(operation) waitForExpectationsWithTimeout(3, handler: nil) XCTAssertTrue(operation.finished) XCTAssertTrue(locationManager.didRequestAlwaysAuthorization) XCTAssertFalse(locationManager.didRequestWhenInUseAuthorization) } func test__service_disabled_when_is_use_required_then__when_in_use_permissions_requested() { let locationManager = TestableLocationManager(enabled: false, status: .NotDetermined) locationManager.returnedStatus = .AuthorizedWhenInUse let operation = TestOperation() operation.addCondition(LocationCondition(usage: .WhenInUse, manager: locationManager)) addCompletionBlockToTestOperation(operation, withExpectation: expectationWithDescription("Test: \(__FUNCTION__)")) runOperation(operation) waitForExpectationsWithTimeout(3, handler: nil) XCTAssertTrue(operation.finished) XCTAssertFalse(locationManager.didRequestAlwaysAuthorization) XCTAssertTrue(locationManager.didRequestWhenInUseAuthorization) } }
mit
c4629bcaf3772d0f6c4763c99dace209
35.603774
122
0.737973
6.024845
false
true
false
false
semonchan/LearningSwift
Project/Project - 01 - StopWatch/Project 01 - StopWatch/ViewController.swift
1
1755
// // ViewController.swift // Project 01 - StopWatch // // Created by 程超 on 2017/11/20. // Copyright © 2017年 程超. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var beginButton: UIButton! @IBOutlet weak var pauseButton: UIButton! var timeCounter = 0.0 var isBegining = false var timer = Timer() // lazy var timer: Timer = { // let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) // return timer // }(); override func viewDidLoad() { super.viewDidLoad() timeLabel.text = String(timeCounter); } @IBAction func beginButtonAction(_ sender: Any) { if isBegining { return } beginButton.isEnabled = false pauseButton.isEnabled = true timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) // timer.fire() } @IBAction func resetButtonAction(_ sender: Any) { timer.invalidate() isBegining = false timeCounter = 0.0 timeLabel.text = String(timeCounter) beginButton.isEnabled = true pauseButton.isEnabled = true } @IBAction func pauseButtonAction(_ sender: Any) { beginButton.isEnabled = true pauseButton.isEnabled = false // 计时器停止 timer.invalidate() isBegining = false } // 更新时间显示 @objc func updateTimer() { timeCounter = timeCounter + 0.1 timeLabel.text = String(format: "%.1f", timeCounter) } }
mit
28f7fc8fad39df95d9f9c09a33d8485c
25.90625
139
0.614983
4.337531
false
false
false
false
almazrafi/Metatron
Tests/MetatronTests/ID3v2/FrameStuffs/ID3v2TimeValueTest.swift
1
5684
// // ID3v2TimeValueTest.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 XCTest @testable import Metatron class ID3v2TimeValueTest: XCTestCase { // MARK: Instance Methods func test() { let stuff = ID3v2TextInformation() do { stuff.timeValue = TagTime(hour: -1) XCTAssert(stuff.timeValue == TagTime()) XCTAssert(stuff.fields == []) } do { stuff.timeValue = TagTime(hour: 24) XCTAssert(stuff.timeValue == TagTime()) XCTAssert(stuff.fields == []) } do { stuff.timeValue = TagTime(hour: 12, minute: -1) XCTAssert(stuff.timeValue == TagTime()) XCTAssert(stuff.fields == []) } do { stuff.timeValue = TagTime(hour: 12, minute: 60) XCTAssert(stuff.timeValue == TagTime()) XCTAssert(stuff.fields == []) } do { stuff.timeValue = TagTime(hour: 12, second: -1) XCTAssert(stuff.timeValue == TagTime()) XCTAssert(stuff.fields == []) } do { stuff.timeValue = TagTime(hour: 12, second: 60) XCTAssert(stuff.timeValue == TagTime()) XCTAssert(stuff.fields == []) } for hour in 0..<24 { for minute in 0..<60 { for second in 0..<60 { stuff.timeValue = TagTime(hour: hour, minute: minute, second: second) XCTAssert(stuff.timeValue == TagTime(hour: hour, minute: minute)) } } } do { stuff.fields = [] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["1"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12:3"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12:34:5"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = [":2:34:56"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12::4:56"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12:34::6"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["-2:34:56"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12:-4:56"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12:34:-6"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12-34:56"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12:34-56"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12-34-56"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12:34"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12:34:56"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["123"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["12345"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["123456"] XCTAssert(stuff.timeValue == TagTime()) } do { stuff.fields = ["1234"] let value = stuff.timeValue XCTAssert((value.hour == 12) && (value.minute == 34) && (value.second == 0)) } do { stuff.fields = ["9934"] let value = stuff.timeValue XCTAssert((value.hour == 99) && (value.minute == 34) && (value.second == 0)) } do { stuff.fields = ["1299"] let value = stuff.timeValue XCTAssert((value.hour == 12) && (value.minute == 99) && (value.second == 0)) } do { stuff.fields = ["9999"] let value = stuff.timeValue XCTAssert((value.hour == 99) && (value.minute == 99) && (value.second == 0)) } } }
mit
7f4d66814187f7214d9dedc7df86c567
22.983122
89
0.508269
4.309325
false
false
false
false
alexnaldo/themoviedbapi
Sources/Core/Commands/TheMovieDbDiscoverCommand.swift
1
2809
// // TheMovieDbConfiguration.swift // TheMovieDbApi // // Created by Alexnaldo Santos on 04/08/16. // Copyright © 2016 Alexnaldo Santos. All rights reserved. // import Foundation import SwiftyJSON public typealias TheMovieDbDiscoverListModel = TheMovieDbListModel<TheMovieDbDiscoverModel> public class TheMovieDbDiscoverModel: TheMovieDbModel { public var poster_path: String! public var adult = false public var overview: String! public var release_date: NSDate? public var genre_ids:[Int]! public var id:Int! public var original_title:String! public var original_language:String! public var title:String! public var backdrop_path:String! public var popularity:Double! public var vote_count:UInt! public var video = false public var vote_average:Double! /* tv properties */ public var name: String! public var original_name: String! public var origin_country:[String]! public var first_air_date: NSDate? public var discoveryType: TheMovieDbType { if let _ = self.name { return .tv } else { return .movie } } public override func loadFromJSON( json: JSON ) { super.loadFromJSON(json) self.poster_path = json["poster_path"].stringValue self.adult = json["adult"].boolValue self.overview = json["overview"].stringValue self.release_date = json["release_date"].string?.fromYearMonthDay() self.genre_ids = json["genre_ids"].map { $1.intValue } self.id = json["id"].intValue self.original_title = json["original_title"].stringValue self.original_language = json["original_language"].stringValue self.title = json["title"].stringValue self.backdrop_path = json["backdrop_path"].stringValue self.popularity = json["popularity"].doubleValue self.vote_count = json["vote_count"].uIntValue self.video = json["video"].boolValue self.vote_average = json["vote_average"].doubleValue //tv properties self.name = json["name"].string self.original_name = json["original_name"].string self.origin_country = json["origin_country"].map { $1.stringValue } self.first_air_date = json["first_air_date"].string?.fromYearMonthDay() //copy tv properties to movie properties to make access easy if self.discoveryType == .tv { self.title = self.name self.original_title = self.original_name self.release_date = self.first_air_date } } } public extension TheMovieDbCommands { public func discover(type: TheMovieDbType)-> TheMovieDbListCommand { return TheMovieDbListCommand(commandRoute:"/discover/\(type)", api: self.api!) } }
mit
3f355f52c0283745cc2a994b886df462
34.556962
91
0.65812
4.178571
false
false
false
false
onekiloparsec/KPCJumpBarControl
KPCJumpBarControlDemoTreeController/ItemOutlineViewDelegate.swift
1
2336
// // ItemOutlineViewDelegate.swift // iObserve2 // // Created by Cédric Foellmi on 03/01/2017. // Copyright © 2017 onekiloparsec. All rights reserved. // import AppKit typealias OutlineViewSelectionDidChangeBlock = (Notification) -> () class ItemOutlineViewDelegate: NSObject, NSOutlineViewDelegate { let selectionDidChangeBlock: OutlineViewSelectionDidChangeBlock init(_ block: @escaping OutlineViewSelectionDidChangeBlock) { self.selectionDidChangeBlock = block } func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { let node = (item is OutlineNode) ? item as! OutlineNode : (item as! NSTreeNode).representedObject as! OutlineNode var cellView: NSTableCellView? = nil if (node.isRoot) { cellView = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "MainOutlineSectionCellViewIdentifier"), owner: nil) as! NSTableCellView? } else { cellView = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "MainOutlineSingleLineCellViewIdentifier"), owner: nil) as! NSTableCellView? } cellView?.objectValue = node return cellView } func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool { // Sometimes it happens, on quit??? let node = (item is OutlineNode) ? item as! OutlineNode : (item as! NSTreeNode).representedObject as! OutlineNode return node.isRoot } func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool { let node = (item is OutlineNode) ? item as! OutlineNode : (item as! NSTreeNode).representedObject as! OutlineNode return !node.isRoot } func outlineView(_ outlineView: NSOutlineView, shouldShowOutlineCellForItem item: Any) -> Bool { let node = (item is OutlineNode) ? item as! OutlineNode : (item as! NSTreeNode).representedObject as! OutlineNode return node.isRoot || !node.isLeaf } func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat { return 24.0 } func outlineViewSelectionDidChange(_ notification: Notification) { self.selectionDidChangeBlock(notification) } }
mit
b846a3d18891f8593d7c730b60ad8467
40.678571
176
0.700514
4.944915
false
false
false
false
DianQK/rx-sample-code
YepRecord/Utils/SafeCollection.swift
1
2067
// // SafeCollection.swift // Expandable // // Created by DianQK on 8/18/16. // Copyright © 2016 T. All rights reserved. // import Foundation public struct SafeCollection<Base: Collection> { //: Collection { /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the sequence. public typealias SubSequence = Base.SubSequence public func dropFirst(_ n: Int) -> SubSequence { return _base.dropFirst(n) } fileprivate var _base: Base public init(_ base: Base) { _base = base } public typealias Index = Base.Index public var startIndex: Index { return _base.startIndex } public var endIndex: Index { return _base.endIndex } public subscript(index: Base.Index) -> Base.Iterator.Element? { if startIndex <= index && index < endIndex { return _base[index] } return nil } public subscript(bounds: Range<Base.Index>) -> Base.SubSequence? { if startIndex <= bounds.lowerBound && bounds.upperBound < endIndex { return _base[bounds] } return nil } var safe: SafeCollection<Base> { //Allows to chain ".safe" without side effects return self } } public extension Collection { var safe: SafeCollection<Self> { return SafeCollection(self) } }
mit
4a186ccd98d630681009204bce1994ce
27.30137
83
0.601162
4.251029
false
false
false
false
JudoPay/JudoKit
Source/JudoPayViewController.swift
1
17841
// // JudoPayViewController.swift // JudoKit // // Copyright (c) 2016 Alternative Payments Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } /** the JudoPayViewController is the one solution build to guide a user through the journey of entering their card details. */ open class JudoPayViewController: UIViewController { // MARK: Transaction variables /// the current JudoKit Session open var judoKitSession: JudoKit /// The amount and currency to process, amount to two decimal places and currency in string open fileprivate (set) var amount: Amount? /// The number (e.g. "123-456" or "654321") identifying the Merchant you wish to pay open fileprivate (set) var judoId: String? /// Your reference for this consumer, this payment and an object containing any additional data you wish to tag this payment with. The property name and value are both limited to 50 characters, and the whole object cannot be more than 1024 characters open fileprivate (set) var reference: Reference? /// Card token and Consumer token open fileprivate (set) var paymentToken: PaymentToken? /// Customer address to use when AVS is turned off open private(set) var address: Address? /// The current transaction public let transaction: Transaction // MARK: 3DS variables fileprivate var pending3DSTransaction: Transaction? fileprivate var pending3DSReceiptID: String? // MARK: completion blocks fileprivate var completionBlock: JudoCompletionBlock? /// The overridden view object forwarding to a JudoPayView override open var view: UIView! { get { return self.myView as UIView } set { if newValue is JudoPayView { myView = newValue as? JudoPayView } } } /// The main JudoPayView of this ViewController var myView: JudoPayView! /** Initializer to start a payment journey - parameter judoId: The judoId of the recipient - parameter amount: An amount and currency for the transaction - parameter reference: A Reference for the transaction - parameter transactionType: The type of the transaction - parameter completion: Completion block called when transaction has been finished - parameter currentSession: The current judo apiSession - parameter cardDetails: An object containing all card information - default: nil - parameter paymentToken: A payment token if a payment by token is to be made - default: nil - returns: a JPayViewController object for presentation on a view stack */ public init(judoId: String, amount: Amount, reference: Reference, transactionType: TransactionType = .payment, completion: @escaping JudoCompletionBlock, currentSession: JudoKit, cardDetails: CardDetails? = nil, address: Address? = nil, paymentToken: PaymentToken? = nil) throws { self.judoId = judoId self.amount = amount self.reference = reference self.paymentToken = paymentToken self.address = address self.completionBlock = completion self.judoKitSession = currentSession self.myView = JudoPayView(type: transactionType, currentTheme: currentSession.theme, cardDetails: cardDetails, isTokenPayment: paymentToken != nil) self.transaction = try self.judoKitSession.transaction(self.myView.transactionType, judoId: judoId, amount: amount, reference: reference) super.init(nibName: nil, bundle: nil) } /** Designated initializer that will fail if called - parameter nibNameOrNil: Nib name or nil - parameter nibBundleOrNil: Bundle or nil - returns: will crash if executed */ override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { fatalError("This class should not be initialised with initWithNibName:Bundle:") } /** Designated initializer that will fail if called - parameter aDecoder: A decoder - returns: will crash if executed */ convenience required public init?(coder aDecoder: NSCoder) { fatalError("This class should not be initialised with initWithCoder:") } // MARK: View Lifecycle /** viewDidLoad */ override open func viewDidLoad() { super.viewDidLoad() self.judoKitSession.apiSession.uiClientMode = true switch self.myView.transactionType { case .payment, .preAuth: self.title = self.judoKitSession.theme.paymentTitle case .registerCard: self.title = self.judoKitSession.theme.registerCardTitle case .refund: self.title = self.judoKitSession.theme.refundTitle default: self.title = "Invalid" } self.myView.threeDSecureWebView.delegate = self // Button actions let payButtonTitle = myView.transactionType == .registerCard ? judoKitSession.theme.registerCardNavBarButtonTitle : judoKitSession.theme.paymentButtonTitle self.myView.paymentButton.addTarget(self, action: #selector(JudoPayViewController.payButtonAction(_:)), for: .touchUpInside) self.myView.paymentNavBarButton = UIBarButtonItem(title: payButtonTitle, style: .done, target: self, action: #selector(JudoPayViewController.payButtonAction(_:))) self.myView.paymentNavBarButton!.isEnabled = false self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: self.judoKitSession.theme.backButtonTitle, style: .plain, target: self, action: #selector(JudoPayViewController.doneButtonAction(_:))) self.navigationItem.rightBarButtonItem = self.myView.paymentNavBarButton self.navigationController?.navigationBar.tintColor = self.judoKitSession.theme.getTextColor() self.navigationController?.navigationBar.barTintColor = self.judoKitSession.theme.getNavigationBarBackgroundColor() if !self.judoKitSession.theme.colorMode() { self.navigationController?.navigationBar.barStyle = UIBarStyle.black } navigationController?.navigationBar.setBottomBorderColor(color: judoKitSession.theme.getNavigationBarBottomColor(), height: 1.0) navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: judoKitSession.theme.getNavigationBarTitleColor()] self.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] } /** viewWillAppear - parameter animated: Animated */ open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.myView.paymentEnabled(false) self.myView.layoutIfNeeded() if self.myView.cardDetails == nil && self.myView.cardInputField.textField.text != nil { self.myView.cardInputField.textFieldDidChangeValue(self.myView.cardInputField.textField) self.myView.expiryDateInputField.textFieldDidChangeValue(self.myView.expiryDateInputField.textField) } } /** viewDidAppear - parameter animated: Animated */ open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.myView.cardInputField.textField.text?.count > 0 { self.myView.secureCodeInputField.textField.becomeFirstResponder() } else { self.myView.cardInputField.textField.becomeFirstResponder() } } // MARK: Button Actions /** When the user hits the pay button, the information is collected from the fields and passed to the backend. The transaction will then be executed. - parameter sender: The payment button */ @objc func payButtonAction(_ sender: AnyObject) { guard let reference = self.reference, let amount = self.amount, let judoId = self.judoId else { self.completionBlock?(nil, JudoError(.parameterError)) return // BAIL } self.myView.secureCodeInputField.textField.resignFirstResponder() self.myView.postCodeInputField.textField.resignFirstResponder() self.myView.loadingView.startAnimating() do { let transaction = try self.judoKitSession.transaction(self.myView.transactionType, judoId: judoId, amount: amount, reference: reference) if var payToken = self.paymentToken { payToken.cv2 = self.myView.secureCodeInputField.textField.text transaction.paymentToken(payToken) } else { // I expect that all the texts are available because the Pay Button would not be active otherwise if self.judoKitSession.theme.avsEnabled { guard let postCode = self.myView.postCodeInputField.textField.text else { return } address = Address(postCode: postCode, country: self.myView.billingCountryInputField.selectedCountry) } var issueNumber: String? = nil var startDate: String? = nil if self.myView.cardInputField.textField.text?.cardNetwork() == .maestro { issueNumber = self.myView.issueNumberInputField.textField.text startDate = self.myView.startDateInputField.textField.text } var cardNumberString = self.myView.cardDetails?._cardNumber if cardNumberString == nil { cardNumberString = self.myView.cardInputField.textField.text!.strippedWhitespaces } transaction.card(Card(number: cardNumberString!, expiryDate: self.myView.expiryDateInputField.textField.text!, securityCode: self.myView.secureCodeInputField.textField.text!, address: address, startDate: startDate, issueNumber: issueNumber)) } try self.judoKitSession.completion(transaction, block: { [weak self] (response, error) -> () in if let error = error { if error.domain == JudoErrorDomain && error.code == .threeDSAuthRequest { guard let payload = error.payload else { self?.completionBlock?(nil, JudoError(.responseParseError)) return // BAIL } do { self?.pending3DSTransaction = transaction self?.pending3DSReceiptID = try self?.myView.threeDSecureWebView.load3DSWithPayload(payload) } catch { self?.myView.loadingView.stopAnimating() self?.completionBlock?(nil, error as? JudoError) } self?.myView.loadingView.actionLabel.text = self?.judoKitSession.theme.redirecting3DSTitle self?.title = self?.judoKitSession.theme.authenticationTitle self?.myView.paymentEnabled(false) } else { self?.completionBlock?(nil, error) self?.myView.loadingView.stopAnimating() } } else if let response = response { self?.completionBlock?(response, nil) self?.myView.loadingView.stopAnimating() } }) } catch let error as JudoError { self.completionBlock?(nil, error) self.myView.loadingView.stopAnimating() } catch { self.completionBlock?(nil, JudoError(.unknown)) self.myView.loadingView.stopAnimating() } } /** executed if the user hits the "Back" button - parameter sender: the button */ @objc func doneButtonAction(_ sender: UIBarButtonItem) { self.completionBlock?(nil, JudoError(.userDidCancel)) } } // MARK: UIWebViewDelegate extension JudoPayViewController: UIWebViewDelegate { /** webView delegate method - parameter webView: The web view - parameter request: The request that was called - parameter navigationType: The navigation Type - returns: return whether webView should start loading the request */ public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { let urlString = request.url?.absoluteString if let urlString = urlString , urlString.range(of: "Parse3DS") != nil { guard let body = request.httpBody, let bodyString = NSString(data: body, encoding: String.Encoding.utf8.rawValue) else { self.completionBlock?(nil, JudoError(.failed3DSError)) return false } var results = JSONDictionary() let pairs = bodyString.components(separatedBy: "&") for pair in pairs { if pair.range(of: "=") != nil { let components = pair.components(separatedBy: "=") let value = components[1] let escapedVal = value.removingPercentEncoding results[components[0]] = escapedVal as AnyObject? } } if let receiptId = self.pending3DSReceiptID { if self.myView.transactionType == .registerCard { self.myView.loadingView.actionLabel.text = self.judoKitSession.theme.verifying3DSRegisterCardTitle } else { self.myView.loadingView.actionLabel.text = self.judoKitSession.theme.verifying3DSPaymentTitle } self.myView.loadingView.startAnimating() self.title = self.judoKitSession.theme.authenticationTitle self.pending3DSTransaction?.threeDSecure(results, receiptId: receiptId, block: { [weak self] (resp, error) -> () in self?.myView.loadingView.stopAnimating() if let error = error { self?.completionBlock?(nil, error) } else if let resp = resp { self?.completionBlock?(resp, nil) } else { self?.completionBlock?(nil, JudoError(.unknown)) } }) } else { self.completionBlock?(nil, JudoError(.unknown)) } UIView.animate(withDuration: 0.3, animations: { () -> Void in self.myView.threeDSecureWebView.alpha = 0.0 }, completion: { (didFinish) -> Void in self.myView.threeDSecureWebView.loadRequest(URLRequest(url: URL(string: "about:blank")!)) }) return false } return true } /** webView delegate method that indicates the webView has finished loading - parameter webView: The web view */ public func webViewDidFinishLoad(_ webView: UIWebView) { var alphaVal: CGFloat = 1.0 if webView.request?.url?.absoluteString == "about:blank" { alphaVal = 0.0 } UIView.animate(withDuration: 0.5, animations: { () -> Void in self.myView.threeDSecureWebView.alpha = alphaVal self.myView.loadingView.stopAnimating() }) } /** webView delegate method that indicates the webView has failed with an error - parameter webView: The web view - parameter error: The error */ public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { UIView.animate(withDuration: 0.5, animations: { () -> Void in self.myView.threeDSecureWebView.alpha = 0.0 self.myView.loadingView.stopAnimating() }) self.completionBlock?(nil, JudoError(.failed3DSError, bridgedError: error as NSError?)) } }
mit
edaced770c940808b8784badd1e52025
40.203233
284
0.624124
5.207531
false
false
false
false
tudou152/QQZone
QQZone/QQZone/Classes/Home/HomeViewController.swift
1
5287
// // HomeViewController.swift // QQZone // // Created by 君哥 on 2016/11/22. // Copyright © 2016年 fistBlood. All rights reserved. // import UIKit extension Selector { static let iconBtnClick = #selector(HomeViewController().iconBtnClick) } class HomeViewController: UIViewController { // MARK: 属性 /// 当前选中的索引 var currrentIndex: Int = 0 /// 容器视图 lazy var containerView: UIView = { // 设置尺寸 let width = min(self.view.frame.width, self.view.frame.height) - kDockItemWH let y: CGFloat = 20 let height: CGFloat = self.view.frame.height - y let x = self.dockView.frame.maxX let containerView = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) return containerView }() /// 导航栏 lazy var dockView: DockView = { // 设置尺寸 let isLandscape = self.view.frame.width > self.view.frame.height let w = isLandscape ? kDockLandscapeWidth : kDockPortraitWidth let dockView = DockView(frame: CGRect(x: 0, y: 0, width: w, height: self.view.bounds.height)) dockView.iconView.addTarget(self, action: .iconBtnClick, for: .touchUpInside) // 设置代理 dockView.tabBarView.delegate = self return dockView }() override func viewDidLoad() { super.viewDidLoad() // 初始化设置 setup() } // 设置状态栏的颜色 override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } // MARK: 设置子控件 extension HomeViewController { fileprivate func setup() { view.backgroundColor = UIColor(r: 55, g: 55, b: 55) // 添加Dock view.addSubview(dockView) // 添加containerView view.addSubview(containerView) // 添加所有的子控制器 setupChildViewControllers() // 底部菜单栏的点击的回调 dockView.bottomMenuView.didClickBtn = { [weak self] type in switch type { case .mood: let moodVC = MoodViewController() let nav = UINavigationController(rootViewController: moodVC) nav.modalPresentationStyle = .formSheet self?.present(nav, animated: true, completion: nil) case .photo: print("发表图片") case .blog: print("发表日志") } } } /// 添加所有子控制器 fileprivate func setupChildViewControllers() { addOneViewController(AllStatusViewController() , "全部动态", .red) addOneViewController(UIViewController() , "与我相关", .blue) addOneViewController(UIViewController(), "照片墙", .darkGray) addOneViewController(UIViewController(), "电子相框", .yellow) addOneViewController(UIViewController(), "好友", .orange) addOneViewController(UIViewController(), "更多", .white) addOneViewController(CenterViewController(), "个人中心", .gray) } private func addOneViewController(_ viewController: UIViewController, _ title: String,_ bgColor: UIColor) { // 设置控制器属性 viewController.view.backgroundColor = bgColor viewController.title = title // 设置导航控制器属性 let nav = UINavigationController(rootViewController: viewController) nav.navigationBar.isTranslucent = false // 设置导航栏不透明 addChildViewController(nav) } } // MARK: 监听屏幕的旋转 extension HomeViewController { override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { // 将屏幕旋转的时间传递给子控件 self.dockView.viewWillTransiton(to: size, with: coordinator) // 设置子控件的尺寸 let width = min(size.width, size.height) - kDockItemWH let y: CGFloat = 20 let height: CGFloat = size.height - y let x = dockView.frame.maxX containerView.frame = CGRect(x: x, y: y, width: width, height: height) } } // MARK: TabBarViewDelegate extension HomeViewController: TabBarViewDelegate { func tabBarViewSelectIndex(_ tabBarView: TabBarView, from: NSInteger, to: NSInteger) { // 移除旧的View let oldVC = childViewControllers[from] oldVC.view.removeFromSuperview() // 添加新的View let newVC = childViewControllers[to] containerView.addSubview(newVC.view) newVC.view.frame = containerView.bounds // 记录当前选中的索引 currrentIndex = to } } // MARK: 监听按钮点击 extension HomeViewController { /// 取消正在选中的按钮 func iconBtnClick() { // 取消中间菜单栏的选中状态 dockView.tabBarView.selectBtn?.isSelected = false tabBarViewSelectIndex(dockView.tabBarView, from: currrentIndex, to: childViewControllers.count - 1) } }
mit
36f8259259c15c6f6ae287fcd3c7ec07
27.467836
112
0.603328
4.662835
false
false
false
false
alibaba/coobjc
Examples/coSwiftDemo/coSwiftDemo/DataService.swift
1
4556
// // DataService.swift // coSwiftDemo // // Copyright © 2018 Alibaba Group Holding Limited 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 Foundation import coswift import CoreLocation public class RequestResult { var data: Data? var response: URLResponse? init(data: Data?, response: URLResponse?) { self.data = data self.response = response } } func co_fetchSomethingAsynchronous() -> Promise<Data?> { let promise = Promise<Data?>(constructor: { (fulfill, reject) in let data: Data? = nil let error: Error? = nil // fetch the data if error != nil { reject(error!) } else { fulfill(data) } }) promise.onCancel { (promiseObj) in } return promise } let someQueue = DispatchQueue(label: "aa") func co_fetchSomething() -> Chan<String> { let chan = Chan<String>() someQueue.async { // fetch operations chan.send_nonblock(val: "the result") } return chan } func test() { co_launch { let resultStr = try await(channel: co_fetchSomething()) print("result: \(resultStr)") } co_launch { let result = try await(promise: co_fetchSomethingAsynchronous()) switch result { case .fulfilled(let data): print("data: \(String(describing: data))") break case .rejected(let error): print("error: \(error)") } } } extension URLSession { public func dataTask(with url: URL) -> Promise<(Data?, URLResponse?)> { let promise = Promise<(Data?, URLResponse?)>() let task = self.dataTask(with: url) { (data, response, error) in if error != nil { promise.reject(error: error!) } else { promise.fulfill(value: (data, response)) } } promise.onCancel { [weak task] (pro) in task?.cancel() } task.resume() return promise } } public class DataService { fileprivate let urlPath = "http://www.baidu.com" public static let shared = DataService(); public func fetchWeatherData() throws -> String { let sessionConfig = URLSessionConfiguration.default let session = URLSession(configuration: sessionConfig) let location = CLLocation(latitude: 0, longitude: 0) guard var components = URLComponents(string:urlPath) else { throw NSError(domain: "DataService", code: -1, userInfo: [NSLocalizedDescriptionKey : "Invalid URL."]) } // get appId from Info.plist let latitude = String(location.coordinate.latitude) let longitude = String(location.coordinate.longitude) components.queryItems = [URLQueryItem(name:"lat", value:latitude), URLQueryItem(name:"lon", value:longitude), URLQueryItem(name:"appid", value:"796b6557f59a77fa02db756a30803b95")] let url = components.url var ret = "" let result = try await (closure: { session.dataTask(with: url!) }) switch result { case .fulfilled(let (data, response)): if let data1 = data { if let httpResponse = response as? HTTPURLResponse { print("response: \(httpResponse)") } if let str = String(data: data1, encoding: String.Encoding.utf8) { ret = str print("responseString: \(str)") } } case .rejected(let error): print("error: \(error)") } return ret } }
apache-2.0
2579c8250c8c3cbf9662614c154869fd
25.482558
114
0.545554
4.794737
false
false
false
false
eightloops/UICode
Sources/Layout/LayoutConstraintItem.swift
1
18715
// // Copyright (c) 2014-2020 eightloops GmbH (http://www.eightloops.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public protocol LayoutConstraintItem: NSObjectProtocol { var superview: UIView? { get } } extension UIView: LayoutConstraintItem { } extension UILayoutGuide: LayoutConstraintItem { public var superview: UIView? { return owningView } } extension LayoutConstraintItem { // MARK: - // MARK: Pin position @discardableResult public func pin( _ edge: LayoutEdgeAttribute, to: LayoutConstraintItem? = nil, inset: CGFloat, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> NSLayoutConstraint { let first = self let second = to ?? self.superview! let attr = edge.positionAttribute() if edge == .right || edge == .bottom { return second.pin( attr, to: first, constant: inset, multiplier: multiplier, relation: relation, priority: priority, container: container) } else { return first.pin( attr, to: second, constant: inset, multiplier: multiplier, relation: relation, priority: priority, container: container) } } @discardableResult public func pin( _ attr: LayoutPositionAttribute, to: LayoutConstraintItem? = nil, toAttr: NSLayoutConstraint.Attribute? = nil, constant: CGFloat, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> NSLayoutConstraint { let second = to ?? self.superview! let secondAttr = toAttr ?? attr.layoutAttribute() let constraint = NSLayoutConstraint(item: self, attribute: attr.layoutAttribute(), relatedBy: relation, toItem: second, attribute: secondAttr, multiplier: multiplier, constant: constant) constraint.priority = priority constraint.addToView( container) return constraint } @discardableResult public func pin( _ attr: LayoutEdgeAttribute, to: LayoutConstraintItem, spacing: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> NSLayoutConstraint { let toAttr = attr.inverse().layoutAttribute() return pin( attr.positionAttribute(), to: to, toAttr: toAttr, constant: spacing, relation: relation, priority: priority, container: container) } @discardableResult public func pin( _ attr: LayoutPositionAttribute, to: LayoutConstraintItem? = nil, toAttr: NSLayoutConstraint.Attribute? = nil, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> NSLayoutConstraint { if let edge = attr.edgeAttribute() { if toAttr == nil || toAttr == attr.layoutAttribute() && multiplier == 1.0 { return pin( edge, to: to, inset: 0.0, multiplier: multiplier, relation: relation, priority: priority, container: container) } } return pin( attr, to: to, toAttr: toAttr, constant: 0.0, multiplier: multiplier, relation: relation, priority: priority, container: container) } // MARK: - // MARK: Pin multiple positions @discardableResult public func pin( _ edges: [LayoutEdgeAttribute], to: LayoutConstraintItem? = nil, inset: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> [NSLayoutConstraint] { return edges.map() { (edge) in return self.pin( edge, to: to, inset: inset, relation: relation, priority: priority, container: container) } } @discardableResult public func pin( _ attrs: [LayoutPositionAttribute], to: LayoutConstraintItem? = nil, constant: CGFloat, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> [NSLayoutConstraint] { return attrs.map() { (attr) in return self.pin( attr, to: to, toAttr: attr.layoutAttribute(), constant: constant, multiplier: multiplier, relation: relation, priority: priority, container: container) } } @discardableResult public func pin( _ attrs: [LayoutPositionAttribute], to: LayoutConstraintItem? = nil, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> [NSLayoutConstraint] { return attrs.map() { (attr) in return self.pin( attr, to: to, toAttr: attr.layoutAttribute(), multiplier: multiplier, relation: relation, priority: priority, container: container) } } // MARK: - // MARK: Pin fraction @discardableResult public func pin( _ edge: LayoutEdgeAttribute, to: LayoutConstraintItem? = nil, fraction: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> NSLayoutConstraint { var toAttr: NSLayoutConstraint.Attribute = .notAnAttribute switch edge { case .left: toAttr = .centerX case .top: toAttr = .centerY case .right, .bottom: toAttr = edge.layoutAttribute() } var multiplier: CGFloat = 1.0 switch edge { case .left, .top: multiplier = fraction * 2.0 case .right, .bottom: multiplier = 1.0 / (1.0 - fraction) } let first = self let second = to ?? self.superview! let attr = edge.positionAttribute() if edge == .right || edge == .bottom { return second.pin( attr, to: first, toAttr: toAttr, constant: 0.0, multiplier: multiplier, relation: relation, priority: priority, container: container) } else { return first.pin( attr, to: second, toAttr: toAttr, constant: 0.0, multiplier: multiplier, relation: relation, priority: priority, container: container) } } public func pin( _ edges: [LayoutEdgeAttribute], to: UIView? = nil, fraction: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> [NSLayoutConstraint] { return edges.map() { (edge) in return self.pin( edge, to: to, fraction: fraction, relation: relation, priority: priority, container: container) } } } extension UIView { // MARK: - // MARK: Pin size @discardableResult public func pin( _ attr: LayoutSizeAttribute, _ constant: CGFloat, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: self, attribute: attr.layoutAttribute(), relatedBy: relation, toItem: nil, attribute: attr.layoutAttribute(), multiplier: multiplier, constant: constant) constraint.priority = priority constraint.addToView( container) return constraint } @discardableResult public func pin( _ attr: LayoutSizeAttribute, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> NSLayoutConstraint { return pin( attr, to: self.superview!, toAttr: attr.layoutAttribute(), constant: 0.0, multiplier: multiplier, relation: relation, priority: priority, container: container ?? self.superview) } @discardableResult public func pin( _ attr: LayoutSizeAttribute, to: LayoutConstraintItem, toAttr: NSLayoutConstraint.Attribute? = nil, constant: CGFloat = 0.0, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> NSLayoutConstraint { let secondAttr = toAttr ?? attr.layoutAttribute() let constraint = NSLayoutConstraint(item: self, attribute: attr.layoutAttribute(), relatedBy: relation, toItem: to, attribute: secondAttr, multiplier: multiplier, constant: constant) constraint.priority = priority constraint.addToView( container) return constraint } // MARK: - // MARK: Pin multiple sizes @discardableResult public func pin( _ attrs: [LayoutSizeAttribute], _ constant: CGFloat, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> [NSLayoutConstraint] { return attrs.map() { (attr) in return self.pin( attr, constant, multiplier: multiplier, relation: relation, priority: priority, container: container) } } @discardableResult public func pin( _ attrs: [LayoutSizeAttribute], multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> [NSLayoutConstraint] { return attrs.map() { (attr) in return self.pin( attr, multiplier: multiplier, relation: relation, priority: priority, container: container) } } @discardableResult public func pin( _ attrs: [LayoutSizeAttribute], to: LayoutConstraintItem, constant: CGFloat = 0.0, multiplier: CGFloat = 1.0, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required, container: UIView? = nil) -> [NSLayoutConstraint] { return attrs.map() { (attr) in return self.pin( attr, to: to, toAttr: attr.layoutAttribute(), constant: constant, multiplier: multiplier, relation: relation, priority: priority, container: container) } } // MARK: - // MARK: Pin intrinsic size public func pin( _ type: LayoutIntrinsicSizeAttribute, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required) { var axes = [NSLayoutConstraint.Axis]() if type == .intrinsicHeight || type == .intrinsicSize { axes.append( .vertical) } if type == .intrinsicWidth || type == .intrinsicSize { axes.append( .horizontal) } if relation == .equal || relation == .greaterThanOrEqual { for axis in axes { self.setContentCompressionResistancePriority( priority, for: axis) } } if relation == .equal || relation == .lessThanOrEqual { for axis in axes { self.setContentHuggingPriority( priority, for: axis) } } } // MARK: - // MARK: Unpin size @discardableResult public func unpin( _ attr: LayoutSizeAttribute, from: UIView, fromAttr: NSLayoutConstraint.Attribute? = nil, constant: CGFloat? = nil, multiplier: CGFloat? = nil, relation: NSLayoutConstraint.Relation? = nil, priority: UILayoutPriority? = nil, container: UIView? = nil) -> [NSLayoutConstraint] { let firstAttribute = attr.layoutAttribute() let secondAttribute = fromAttr ?? firstAttribute let secondView = from return unpinMultiConstraint( firstAttribute, secondView: secondView, secondAttribute: secondAttribute, constant: constant, multiplier: multiplier, relation: relation, priority: priority, container: container) } @discardableResult public func unpin( _ attr: LayoutSizeAttribute, multiplier: CGFloat? = nil, relation: NSLayoutConstraint.Relation? = nil, priority: UILayoutPriority? = nil, container: UIView? = nil) -> [NSLayoutConstraint] { if let from = self.superview { return unpin( attr, from: from, fromAttr: attr.layoutAttribute(), multiplier: multiplier, relation: relation, priority: priority, container: container ?? self.superview) } else { return [] } } @discardableResult public func unpin( _ attr: LayoutSizeAttribute, constant: CGFloat?, multiplier: CGFloat? = nil, relation: NSLayoutConstraint.Relation? = nil, priority: UILayoutPriority? = nil, container: UIView? = nil) -> [NSLayoutConstraint] { let firstAttribute = attr.layoutAttribute() var constraints = [NSLayoutConstraint]() let container = container ?? self for c in container.constraints { if c.firstItem as! UIView == self && c.firstAttribute == firstAttribute { var match = true if let constant = constant { match = match && (constant == c.constant) } if let multiplier = multiplier { match = match && (multiplier == c.multiplier) } if let relation = relation { match = match && (relation == c.relation) } if let priority = priority { match = match && (priority == c.priority) } if match { constraints.append( c) c.removeFromView( view: container) } } } return constraints } // MARK: - // MARK: Unpin multiple sizes @discardableResult public func unpin( _ attrs: [LayoutSizeAttribute], from: UIView, fromAttr: NSLayoutConstraint.Attribute? = nil, multiplier: CGFloat? = nil, relation: NSLayoutConstraint.Relation? = nil, priority: UILayoutPriority? = nil, container: UIView? = nil) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() for attr in attrs { for constraint in unpin( attr, from: from, fromAttr: fromAttr, multiplier: multiplier, relation: relation, priority: priority, container: container) { constraints.append( constraint) } } return constraints } @discardableResult public func unpin( _ attrs: [LayoutSizeAttribute], multiplier: CGFloat? = nil, relation: NSLayoutConstraint.Relation? = nil, priority: UILayoutPriority? = nil, container: UIView? = nil) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() for attr in attrs { for constraint in unpin( attr, multiplier: multiplier, relation: relation, priority: priority, container: container) { constraints.append( constraint) } } return constraints } @discardableResult public func unpin( _ attrs: [LayoutSizeAttribute], constant: CGFloat?, multiplier: CGFloat? = nil, relation: NSLayoutConstraint.Relation? = nil, priority: UILayoutPriority? = nil, container: UIView? = nil) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() for attr in attrs { for constraint in unpin( attr, constant: constant, multiplier: multiplier, relation: relation, priority: priority, container: container) { constraints.append( constraint) } } return constraints } // MARK: - // MARK: Unpin position @discardableResult public func unpin( _ attr: LayoutPositionAttribute, from: UIView? = nil, fromAttr: NSLayoutConstraint.Attribute? = nil, constant: CGFloat? = nil, multiplier: CGFloat? = nil, relation: NSLayoutConstraint.Relation? = nil, priority: UILayoutPriority? = nil, container: UIView? = nil) -> [NSLayoutConstraint] { let firstAttribute = attr.layoutAttribute() let secondAttribute = fromAttr ?? firstAttribute if let secondView = from ?? self.superview { return unpinMultiConstraint( firstAttribute, secondView: secondView, secondAttribute: secondAttribute, constant: constant, multiplier: multiplier, relation: relation, priority: priority, container: containerForView( from, container: container)) } else { return [] } } // MARK: - // MARK: Unpin multiple positions @discardableResult public func unpin( _ attrs: [LayoutPositionAttribute], from: UIView? = nil, fromAttr: NSLayoutConstraint.Attribute? = nil, constant: CGFloat? = nil, multiplier: CGFloat? = nil, relation: NSLayoutConstraint.Relation? = nil, priority: UILayoutPriority? = nil, container: UIView? = nil) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() for attr in attrs { for constraint in unpin( attr, from: from, fromAttr: fromAttr, constant: constant, multiplier: multiplier, relation: relation, priority: priority, container: container) { constraints.append( constraint) } } return constraints } // MARK: - // MARK: Pin helper methods @discardableResult func containerForView( _ view: UIView?, container: UIView?) -> UIView? { if let container = container { return container } else if view == nil { return self.superview } else { return nil } } @discardableResult func unpinMultiConstraint( _ firstAttribute: NSLayoutConstraint.Attribute, secondView: UIView, secondAttribute: NSLayoutConstraint.Attribute, constant: CGFloat? = nil, multiplier: CGFloat? = nil, relation: NSLayoutConstraint.Relation? = nil, priority: UILayoutPriority? = nil, container: UIView? = nil) -> [NSLayoutConstraint] { let firstView = self var constraints: [NSLayoutConstraint] = [] var container: UIView? = container if container == nil { container = firstView.lowestCommonAncestor( secondView) } if let container = container { for c in container.constraints { let firstItem = c.firstItem as! UIView let secondItem = c.secondItem as! UIView? var match = false if firstItem == firstView && secondItem == secondView { match = c.firstAttribute == firstAttribute && c.secondAttribute == secondAttribute } else if secondItem == firstView && firstItem == secondView { match = c.firstAttribute == secondAttribute && c.secondAttribute == firstAttribute } if match { if let constant = constant { match = match && (constant == c.constant) } if let multiplier = multiplier { match = match && (multiplier == c.multiplier) } if let relation = relation { match = match && (relation == c.relation) } if let priority = priority { match = match && (priority == c.priority) } if match { constraints.append( c) c.removeFromView( view: container) } } } } return constraints } }
mit
953bbf3c0f8f7d6ae669773c185c5fd2
45.209877
330
0.691905
4.631279
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/DAO/BatchFetch/Galleries/MyGalleriesBatchFetchOperation.swift
1
2345
// // MyGalleriesBatchFetchOperation.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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. // class MyGalleriesBatchFetchOperation: ConcurrentOperation { private let requestSender: RequestSender private let filter: GalleriesRequestFilter? let pagingData: PagingData private(set) var galleries: Array<Gallery>? private var requestHandler: RequestHandler? init(requestSender: RequestSender, filter: GalleriesRequestFilter?, pagingData: PagingData, complete: OperationCompleteClosure?) { self.requestSender = requestSender self.filter = filter self.pagingData = pagingData super.init(complete: complete) } override func main() { guard isCancelled == false else { return } let request = MyGalleriesRequest(page: pagingData.page, perPage: pagingData.pageSize, filter: filter) let handler = GalleriesResponseHandler { [weak self](galleries, _, error) -> (Void) in self?.galleries = galleries self?.finish(error) } requestHandler = requestSender.send(request, withResponseHandler: handler) } override func cancel() { requestHandler?.cancel() super.cancel() } }
mit
c55661cf3f5cdf020981be2f32db4670
39.431034
134
0.717271
4.616142
false
false
false
false
jellybeansoup/ios-sherpa
src/Sherpa/Article.swift
1
3045
// // Copyright © 2021 Daniel Farrelly // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation internal struct Article { let key: String? let title: String let body: String let buildMin: Int let buildMax: Int let relatedKeys: [String] internal init?(dictionary: [String: Any]) { // Key if let string = dictionary["key"] as? String, !string.isEmpty { key = string } else { key = nil } // Minimum build if let int = dictionary["build_min"] as? Int { buildMin = int } else if let string = dictionary["build_min"] as? String, let int = Int(string) { buildMin = int } else { buildMin = 1 } // Maximum build if let int = dictionary["build_max"] as? Int { buildMax = int } else if let string = dictionary["build_max"] as? String, let int = Int(string) { buildMax = int } else { buildMax = Int.max } // Related articles if let array = dictionary["related_articles"] as? [String] { relatedKeys = array } else if let string = dictionary["related_articles"] as? String, !string.isEmpty { relatedKeys = [string] } else { relatedKeys = [] } // Title and body title = dictionary["title"] as? String ?? "" body = dictionary["body"] as? String ?? "" if title.isEmpty || body.isEmpty { return nil } } internal func matches(_ query: String) -> Bool { if query.isEmpty { return true } let lowercaseQuery = query.lowercased() if self.title.lowercased().range(of: lowercaseQuery) != nil { return true } else if self.body.lowercased().range(of: lowercaseQuery) != nil { return true } return false } internal func matches(_ buildNumber: Int) -> Bool { return buildNumber >= self.buildMin && buildNumber <= self.buildMax } }
bsd-2-clause
f549b23e1186ad121e888b385d31f94c
25.938053
85
0.690539
3.767327
false
false
false
false
MaxHasADHD/TraktKit
Common/Models/Users/TraktListItem.swift
1
734
// // TraktListItem.swift // TraktKit // // Created by Maximilian Litteral on 6/22/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation public struct TraktListItem: Codable, Hashable { public let rank: Int public let listedAt: Date public let type: String public var show: TraktShow? = nil public var season: TraktSeason? = nil public var episode: TraktEpisode? = nil public var movie: TraktMovie? = nil public var person: Person? = nil enum CodingKeys: String, CodingKey { case rank case listedAt = "listed_at" case type case show case season case episode case movie case person } }
mit
1a1851b2f58cf9c0ad03b57784b165f1
22.645161
62
0.639836
4.311765
false
false
false
false
jolucama/OpenWeatherMapAPIConsumer
OpenWeatherMapAPIConsumer/Classes/CurrentResponseOpenWeatherMap.swift
1
1962
// // ResponseOpenWeatherMap.swift // WhatWearToday // // Created by jlcardosa on 17/11/2016. // Copyright © 2016 Cardosa. All rights reserved. // import Foundation import CoreLocation public class CurrentResponseOpenWeatherMap : ResponseOpenWeatherMap, ResponseOpenWeatherMapProtocol { public func getCoord() -> CLLocationCoordinate2D { let coord = self.rawData["coord"] as! Dictionary<String,Float> return CLLocationCoordinate2D(latitude: CLLocationDegrees(coord["lat"]!), longitude: CLLocationDegrees(coord["long"]!)) } public func getTemperature() -> Float { let main = self.getDictionary(byKey: "main") return main["temp"] as! Float } public func getPressure() -> Float { let main = self.getDictionary(byKey: "main") return main["pressure"] as! Float } public func getHumidity() -> Float { let main = self.getDictionary(byKey: "main") return main["humidity"] as! Float } public func getTempMax() -> Float { let main = self.getDictionary(byKey: "main") return main["temp_max"] as! Float } public func getTempMin() -> Float { let main = self.getDictionary(byKey: "main") return main["temp_min"] as! Float } public func getCityName() -> String { return self.rawData["name"] as! String } public func getIconList() -> IconList { let weather = self.getArrayOfDictionary(byKey: "weather").first let icon = weather?["icon"] as! String return IconList(rawValue: icon)! } public func getDescription() -> String { let weather = self.getArrayOfDictionary(byKey: "weather").first return weather?["description"] as! String } public func getWindSpeed() -> Float { let wind = self.getDictionary(byKey: "wind") return wind["speed"] as! Float } public func getDate() -> Date { return Date(timeIntervalSince1970: self.rawData["dt"] as! TimeInterval) } }
mit
d48a84ae2d7fe2f4e466fcc38bc559b4
27.42029
121
0.658338
4.034979
false
false
false
false
tjhancocks/Pixel
PixelApp/PixelApp/New Document/NewDocumentController.swift
1
2965
// // NewDocumentController.swift // PixelApp // // Created by Tom Hancocks on 03/08/2014. // Copyright (c) 2014 Tom Hancocks. All rights reserved. // import Cocoa class NewDocumentController: NSWindowController { var parentWindow: NSWindow? @IBOutlet var documentNameField: NSTextField? @IBOutlet var baseImageNameField: NSTextField? @IBOutlet var canvasWidthField: NSTextField? @IBOutlet var canvasHeightField: NSTextField? var baseImageURL: NSURL? var canvasSize = CGSize(width: 16, height: 16) var documentName = "My Pixel Art Image" override var windowNibName: String! { return "NewDocumentController" } override func windowDidLoad() { super.windowDidLoad() documentNameField!.stringValue = documentName canvasWidthField!.integerValue = Int(canvasSize.width) canvasHeightField!.integerValue = Int(canvasSize.height) } @IBAction func importBaseImage(sender: AnyObject!) { let openPanel = NSOpenPanel() openPanel.allowedFileTypes = NSImage.imageFileTypes() openPanel.prompt = "Import" if openPanel.runModal() == NSOKButton { baseImageURL = openPanel.URL baseImageNameField!.stringValue = baseImageURL!.lastPathComponent.stringByDeletingPathExtension // Pull in the actual image and then get its dimensions and set them. let image = NSImage(contentsOfURL: openPanel.URL!)! canvasWidthField!.integerValue = Int(image.size.width) canvasHeightField!.integerValue = Int(image.size.height) } } @IBAction func validateCanvasSizeInput(sender: AnyObject!) { let field = sender as NSTextField if field.integerValue < 1 { let alert = NSAlert() alert.addButtonWithTitle("OK") alert.messageText = "Invalid Canvas Size" alert.informativeText = "A canvas can not have a dimension that is less than 1 pixel." alert.alertStyle = .WarningAlertStyle if alert.runModal() == NSOKButton { field.integerValue = 1 } } } @IBAction func cancel(sender: AnyObject!) { if let window = window { if let parent = parentWindow? { parent.endSheet(window, returnCode: NSCancelButton) } window.orderOut(sender) } } @IBAction func createDocument(sender: AnyObject!) { documentName = documentNameField!.stringValue canvasSize.width = CGFloat(canvasWidthField!.integerValue) canvasSize.height = CGFloat(canvasHeightField!.integerValue) if let window = window { if let parent = parentWindow? { parent.endSheet(window, returnCode: NSOKButton) } window.orderOut(sender) } } }
mit
60baa9520245c01dd3f0f93b8c25385c
31.582418
107
0.622934
5.138648
false
false
false
false
zirinisp/PazMapDirections
PazMapDirections/PazMapDirections.swift
1
6908
// // PazMapDirections.swift // PazMapDirections // // Created by Pantelis Zirinis on 08/11/2016. // Copyright © 2016 paz-labs. All rights reserved. // import Foundation import UIKit import CoreLocation import MapKit // enum to hold possible navigation apps on user's device public enum PazNavigationApp { case AppleMaps case GoogleMaps case Navigon case TomTom case Waze // shortcut to access every value of possible navigation app public static let AllValues: [PazNavigationApp] = [.AppleMaps, .GoogleMaps, .Navigon, .TomTom, .Waze] // property that returns only navigation apps that the user has installed public static var AvailableServices: [PazNavigationApp] { return self.AllValues.filter { app in app.available } } // name of each app as it will appear on the Alert's options public var name: String { switch self { case .AppleMaps: return "Apple Maps" case .GoogleMaps: return "Google Maps" case .Navigon: return "Navigon" case .TomTom: return "TomTom" case .Waze: return "Waze" } } // base of URL used to open the navigation app public var urlString: String { switch self { case .AppleMaps: return "http://maps.apple.com" case .GoogleMaps: return "comgooglemaps://" case .Navigon: return "navigon://" case .TomTom: return "tomtomhome://" case .Waze: return "waze://" } } // auxiliar property to transform a string into an URL public var url: URL? { return URL(string: self.urlString) } // property that checks if a given app is installed public var available: Bool { guard let url = self.url else { return false } return UIApplication.shared.canOpenURL(url) } /* func to get the full URL (in string version) necessary to open the navigation app on the desired coordinates */ public func directionsUrlString(coordinate: CLLocationCoordinate2D, name: String = "Destination") -> String { var urlString = self.urlString switch self { case .AppleMaps: urlString.append("?q=\(coordinate.latitude),\(coordinate.longitude)=d&t=h") case .GoogleMaps: urlString.append("?saddr=&daddr=\(coordinate.latitude),\(coordinate.longitude)&directionsmode=driving") case .Navigon: urlString.append("coordinate/\(name)/\(coordinate.longitude)/\(coordinate.latitude)") case .TomTom: urlString.append("geo:action=navigateto&lat=\(coordinate.latitude)&long=\(coordinate.longitude)&name=\(name)") case .Waze: urlString.append("?ll=\(coordinate.latitude),\(coordinate.longitude)&navigate=yes") } let urlwithPercentEscapes = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? urlString return urlwithPercentEscapes } // wrapper func to turn a string into an URL object public func directionsUrl(coordinate: CLLocationCoordinate2D, name: String = "Destination") -> URL? { let urlString = self.directionsUrlString(coordinate: coordinate, name: name) return URL(string: urlString) } /* func that tries to open a navigation app on a specific set of coordinates and informs it's callback if it was successful */ public func openWithDirections(coordinate: CLLocationCoordinate2D, name: String = "Destination", completion: ((Bool) -> Swift.Void)? = nil) { // Apple Maps can be opened differently than other navigation apps if self == .AppleMaps { let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary:nil)) mapItem.name = self.name let success = mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]) completion?(success) } guard let url = self.directionsUrl(coordinate: coordinate, name: name) else { completion?(false) return } // open the app with appropriate method for your target iOS version if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: { (success) in print("Open \(url.absoluteString): \(success)") completion?(success) }) } else { let success = UIApplication.shared.openURL(url) completion?(success) } } /* func to create an Alert where the options are the available navigation apps on the user's device. The callback informs if the operation was successful */ public static func directionsAlertController(coordinate: CLLocationCoordinate2D, name: String = "Destination", title: String = "Directions Using", message: String? = nil, completion: ((Bool) -> ())? = nil) -> UIAlertController { let directionsAlertView = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) for navigationApp in PazNavigationApp.AvailableServices { let action = UIAlertAction(title: navigationApp.name, style: UIAlertActionStyle.default, handler: { action in navigationApp.openWithDirections(coordinate: coordinate, name: name, completion: completion) }) directionsAlertView.addAction(action) } let cancelAction = UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.cancel, handler: { action in completion?(false) }) directionsAlertView.addAction(cancelAction) return directionsAlertView } }
mit
ee07c83b207843cda8e4e36c3ed7ef60
37.160221
122
0.543507
5.647588
false
false
false
false
VadimPavlov/Swifty
Sources/Swifty/ios/IBDesignable/UIGradientView.swift
1
1356
// // UIGradientView.swift // Created by Vadim Pavlov on 19.12.15. import UIKit @IBDesignable public class UIGradientView: UIView { @IBInspectable public var startColor: UIColor = .black { didSet { self.updateColors() } } @IBInspectable public var endColor: UIColor = .white { didSet { self.updateColors() } } @IBInspectable public var startPoint: CGPoint = CGPoint(x: 0.5, y: 0) { willSet { self.gradientLayer.startPoint = newValue } } @IBInspectable public var endPoint: CGPoint = CGPoint(x: 0.5, y: 1) { willSet { self.gradientLayer.endPoint = newValue } } // initialization override public class var layerClass: AnyClass { return CAGradientLayer.self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.updateColors() } override init(frame: CGRect) { super.init(frame: frame) self.updateColors() } // private private func updateColors() { self.gradientLayer.colors = [self.startColor.cgColor, self.endColor.cgColor] self.setNeedsDisplay() } private var gradientLayer: CAGradientLayer { return self.layer as! CAGradientLayer } }
mit
50454b01886334ab986910d0b11c7449
22.789474
84
0.59587
4.724739
false
false
false
false
EndouMari/TabPageViewController
Sources/TabPageViewController.swift
1
12032
// // TabPageViewController.swift // TabPageViewController // // Created by EndouMari on 2016/02/24. // Copyright © 2016年 EndouMari. All rights reserved. // import UIKit open class TabPageViewController: UIPageViewController { open var isInfinity: Bool = false open var option: TabPageOption = TabPageOption() open var tabItems: [(viewController: UIViewController, title: String)] = [] var currentIndex: Int? { guard let viewController = viewControllers?.first else { return nil } return tabItems.map{ $0.viewController }.firstIndex(of: viewController) } fileprivate var beforeIndex: Int = 0 fileprivate var tabItemsCount: Int { return tabItems.count } fileprivate var defaultContentOffsetX: CGFloat { return self.view.bounds.width } fileprivate var shouldScrollCurrentBar: Bool = true lazy fileprivate var tabView: TabView = self.configuredTabView() fileprivate var statusView: UIView? fileprivate var statusViewHeightConstraint: NSLayoutConstraint? fileprivate var tabBarTopConstraint: NSLayoutConstraint? private var appNavigationAppearance: UINavigationBarAppearance? private var appNavigationScrollEdgeAppearance: UINavigationBarAppearance? public init() { super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) } public required init?(coder aDecoder: NSCoder) { super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) } override open func viewDidLoad() { super.viewDidLoad() setupPageViewController() setupScrollView() updateNavigationBar() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if tabView.superview == nil { tabView = configuredTabView() } if let currentIndex = currentIndex , isInfinity { tabView.updateCurrentIndex(currentIndex, shouldScroll: true) } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateNavigationBar() tabView.layouted = true } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if let appearance = appNavigationAppearance { navigationController?.navigationBar.standardAppearance = appearance } navigationController?.navigationBar.scrollEdgeAppearance = appNavigationScrollEdgeAppearance } } // MARK: - Public Interface public extension TabPageViewController { func displayControllerWithIndex(_ index: Int, direction: UIPageViewController.NavigationDirection, animated: Bool) { beforeIndex = index shouldScrollCurrentBar = false let nextViewControllers: [UIViewController] = [tabItems[index].viewController] let completion: ((Bool) -> Void) = { [weak self] _ in self?.shouldScrollCurrentBar = true self?.beforeIndex = index } setViewControllers( nextViewControllers, direction: direction, animated: animated, completion: completion) guard isViewLoaded else { return } tabView.updateCurrentIndex(index, shouldScroll: true) } } // MARK: - View extension TabPageViewController { fileprivate func setupPageViewController() { dataSource = self delegate = self setViewControllers([tabItems[beforeIndex].viewController], direction: .forward, animated: false, completion: nil) } fileprivate func setupScrollView() { // Disable PageViewController's ScrollView bounce let scrollView = view.subviews.compactMap { $0 as? UIScrollView }.first scrollView?.scrollsToTop = false scrollView?.delegate = self scrollView?.backgroundColor = option.pageBackgoundColor scrollView?.contentInsetAdjustmentBehavior = .never } /** Update NavigationBar */ fileprivate func updateNavigationBar() { guard let navigationBar = navigationController?.navigationBar else { return } if appNavigationAppearance == nil { appNavigationAppearance = navigationBar.standardAppearance.copy() appNavigationScrollEdgeAppearance = navigationBar.scrollEdgeAppearance?.copy() } if option.isTranslucent { navigationBar.standardAppearance.configureWithTransparentBackground() } else { navigationBar.standardAppearance.configureWithOpaqueBackground() navigationBar.standardAppearance.shadowColor = .clear } navigationBar.standardAppearance.backgroundColor = option.tabBackgroundColor.withAlphaComponent(option.tabBarAlpha) navigationBar.scrollEdgeAppearance = navigationBar.standardAppearance } fileprivate func configuredTabView() -> TabView { let tabView = TabView(isInfinity: isInfinity, option: option) tabView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(tabView) let top = tabView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor) top.isActive = true tabView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true tabView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true tabView.heightAnchor.constraint(equalToConstant: option.tabHeight).isActive = true tabView.pageTabItems = tabItems.map({ $0.title}) tabView.updateCurrentIndex(beforeIndex, shouldScroll: true) tabView.pageItemPressedBlock = { [weak self] (index: Int, direction: UIPageViewController.NavigationDirection) in self?.displayControllerWithIndex(index, direction: direction, animated: true) } tabBarTopConstraint = top return tabView } private func setupStatusView() { let statusView = UIView() statusView.backgroundColor = option.tabBackgroundColor.withAlphaComponent(option.tabBarAlpha) statusView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(statusView) statusView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true statusView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true statusView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true let height = statusView.heightAnchor.constraint(equalToConstant: view.safeAreaInsets.top) height.isActive = true statusViewHeightConstraint = height self.statusView = statusView } public func updateNavigationBarHidden(_ hidden: Bool, animated: Bool) { guard let navigationController = navigationController else { return } switch option.hidesTopViewOnSwipeType { case .tabBar: updateTabBarOrigin(hidden: hidden) case .navigationBar: if hidden { statusView?.isHidden = false navigationController.setNavigationBarHidden(true, animated: true) } else { showNavigationBar() } case .all: updateTabBarOrigin(hidden: hidden) if hidden { statusView?.isHidden = false navigationController.setNavigationBarHidden(true, animated: true) } else { showNavigationBar() } default: break } if statusView == nil { setupStatusView() } statusViewHeightConstraint!.constant = view.safeAreaInsets.top } public func showNavigationBar() { guard let navigationController = navigationController else { return } guard navigationController.isNavigationBarHidden else { return } guard let tabBarTopConstraint = tabBarTopConstraint else { return } if option.hidesTopViewOnSwipeType != .none { tabBarTopConstraint.constant = 0.0 UIView.animate(withDuration: TimeInterval(UINavigationController.hideShowBarDuration), delay: 0, options: [], animations: { self.view.layoutIfNeeded() }, completion: { finished in self.statusView?.isHidden = true navigationController.setNavigationBarHidden(false, animated: false) }) } } private func updateTabBarOrigin(hidden: Bool) { guard let tabBarTopConstraint = tabBarTopConstraint else { return } tabBarTopConstraint.constant = hidden ? -(20.0 + option.tabHeight) : 0.0 UIView.animate(withDuration: TimeInterval(UINavigationController.hideShowBarDuration)) { self.view.layoutIfNeeded() } } } // MARK: - UIPageViewControllerDataSource extension TabPageViewController: UIPageViewControllerDataSource { fileprivate func nextViewController(_ viewController: UIViewController, isAfter: Bool) -> UIViewController? { guard var index = tabItems.map({$0.viewController}).firstIndex(of: viewController) else { return nil } if isAfter { index += 1 } else { index -= 1 } if isInfinity { if index < 0 { index = tabItems.count - 1 } else if index == tabItems.count { index = 0 } } if index >= 0 && index < tabItems.count { return tabItems[index].viewController } return nil } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { return nextViewController(viewController, isAfter: true) } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { return nextViewController(viewController, isAfter: false) } } // MARK: - UIPageViewControllerDelegate extension TabPageViewController: UIPageViewControllerDelegate { public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { shouldScrollCurrentBar = true tabView.scrollToHorizontalCenter() // Order to prevent the the hit repeatedly during animation tabView.updateCollectionViewUserInteractionEnabled(false) } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if let currentIndex = currentIndex , currentIndex < tabItemsCount { tabView.updateCurrentIndex(currentIndex, shouldScroll: false) beforeIndex = currentIndex } tabView.updateCollectionViewUserInteractionEnabled(true) } } // MARK: - UIScrollViewDelegate extension TabPageViewController: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.x == defaultContentOffsetX || !shouldScrollCurrentBar { return } // (0..<tabItemsCount) var index: Int if scrollView.contentOffset.x > defaultContentOffsetX { index = beforeIndex + 1 } else { index = beforeIndex - 1 } if index == tabItemsCount { index = 0 } else if index < 0 { index = tabItemsCount - 1 } let scrollOffsetX = scrollView.contentOffset.x - view.frame.width tabView.scrollCurrentBarView(index, contentOffsetX: scrollOffsetX) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { tabView.updateCurrentIndex(beforeIndex, shouldScroll: true) } }
mit
941cb85b472f21d6dee5fdf8884181f7
33.566092
197
0.671211
5.885029
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Swift Note/CS193p/iOS11/EmojiArt/EmojiArtView+Gestures.swift
1
3715
// // EmojiArtView+Gestures.swift // EmojiArt // // Created by CS913p Instructor. // Copyright © 2017 Stanford University. All rights reserved. // import UIKit // Gesture Recognition Extension to EmojiArtView extension EmojiArtView { func addEmojiArtGestureRecognizers(to view: UIView) { view.isUserInteractionEnabled = true view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.selectSubview(by:)))) view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.selectAndMoveSubview(by:)))) } var selectedSubview: UIView? { get { return subviews.filter { $0.layer.borderWidth > 0 }.first } set { subviews.forEach { $0.layer.borderWidth = 0 } newValue?.layer.borderWidth = 1 if newValue != nil { enableRecognizers() } else { disableRecognizers() } } } @objc func selectSubview(by recognizer: UITapGestureRecognizer) { if recognizer.state == .ended { selectedSubview = recognizer.view } } @objc func selectAndMoveSubview(by recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: if selectedSubview != nil, recognizer.view != nil { selectedSubview = recognizer.view } case .changed, .ended: if selectedSubview != nil { recognizer.view?.center = recognizer.view!.center.offset(by: recognizer.translation(in: self)) recognizer.setTranslation(CGPoint.zero, in: self) } default: break } } func enableRecognizers() { if let scrollView = superview as? UIScrollView { // if we are in a scroll view, disable its recognizers // so that ours will get the touch events instead scrollView.panGestureRecognizer.isEnabled = false scrollView.pinchGestureRecognizer?.isEnabled = false } if gestureRecognizers == nil || gestureRecognizers!.count == 0 { addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.deselectSubview))) addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: #selector(self.resizeSelectedLabel(by:)))) } else { gestureRecognizers?.forEach { $0.isEnabled = true } } } func disableRecognizers() { if let scrollView = superview as? UIScrollView { // if we are in a scroll view, re-enable its recognizers scrollView.panGestureRecognizer.isEnabled = true scrollView.pinchGestureRecognizer?.isEnabled = true } gestureRecognizers?.forEach { $0.isEnabled = false } } @objc func deselectSubview() { selectedSubview = nil } @objc func resizeSelectedLabel(by recognizer: UIPinchGestureRecognizer) { switch recognizer.state { case .changed, .ended: if let label = selectedSubview as? UILabel { label.attributedText = label.attributedText?.withFontScaled(by: recognizer.scale) label.stretchToFit() recognizer.scale = 1.0 } default: break } } @objc func selectAndSendSubviewToBack(by recognizer: UITapGestureRecognizer) { if recognizer.state == .ended { if let view = recognizer.view, let index = subviews.index(of: view) { selectedSubview = view exchangeSubview(at: 0, withSubviewAt: index) } } } }
mit
164a3b437100061535f7ae1225065ac6
34.371429
122
0.609316
5.208976
false
false
false
false
bartoszj/acextract
acextractTests/Assets.swift
1
1720
// // Assets.swift // acextract // // Created by Bartosz Janda on 25.06.2016. // Copyright © 2016 Bartosz Janda. All rights reserved. // import Foundation enum Asset: String { // MARK: Cases case iOS = "data/assets_ios" case iPhone = "data/assets_iphone" case iPad = "data/assets_ipad" case macOS = "data/assets_mac" case tvOS = "data/assets_tv" case watchOS = "data/assets_watch" case assets = "data/assets" // MARK: Properties var path: String { guard let path = Asset.path(catalog: self) else { fatalError("Missing car file") } return path } // MARK: Static static let bundleIdentifer = "com.bjanda.acextractTests" static let bundle = Bundle(identifier: bundleIdentifer)! static func path(name: String) -> String? { return bundle.path(forResource: name, ofType: "car") } static func path(catalog: Asset) -> String? { return path(name: catalog.rawValue) } } struct AssetsContainer { var iOS: AssetsCatalog! var iPad: AssetsCatalog! var iPhone: AssetsCatalog! var macOS: AssetsCatalog! var tvOS: AssetsCatalog! var watchOS: AssetsCatalog! init() { do { iOS = try AssetsCatalog(path: Asset.iOS.path) iPad = try AssetsCatalog(path: Asset.iPad.path) iPhone = try AssetsCatalog(path: Asset.iPhone.path) macOS = try AssetsCatalog(path: Asset.macOS.path) tvOS = try AssetsCatalog(path: Asset.tvOS.path) watchOS = try AssetsCatalog(path: Asset.watchOS.path) } catch { fatalError("Cannot create assets") } } } let assetsContainer = AssetsContainer()
mit
24e772b599a1bd0421ebc9f3f184bcd8
26.285714
65
0.622455
4.06383
false
false
false
false
srn214/Floral
Floral/Floral/Classes/Expand/Extensions/RxSwift/Cocoa/RxTextFieldDelegateProxy.swift
1
2571
// // RxTextFieldDelegateProxy.swift // RxSwiftX // // Created by Pircate on 2018/6/3. // Copyright © 2018年 Pircate. All rights reserved. // import RxSwift import RxCocoa extension UITextField: HasDelegate { public typealias Delegate = UITextFieldDelegate } open class RxTextFieldDelegateProxy: DelegateProxy<UITextField, UITextFieldDelegate>, DelegateProxyType, UITextFieldDelegate { public weak private(set) var textField: UITextField? public init(textField: ParentObject) { self.textField = textField super.init(parentObject: textField, delegateProxy: RxTextFieldDelegateProxy.self) } public static func registerKnownImplementations() { self.register { RxTextFieldDelegateProxy(textField: $0) } } private var _shouldClearPublishSubject: PublishSubject<UITextField>? private var _shouldReturnPublishSubject: PublishSubject<UITextField>? var shouldClearPublishSubject: PublishSubject<UITextField> { if let subject = _shouldClearPublishSubject { return subject } let subject = PublishSubject<UITextField>() _shouldClearPublishSubject = subject return subject } var shouldReturnPublishSubject: PublishSubject<UITextField> { if let subject = _shouldReturnPublishSubject { return subject } let subject = PublishSubject<UITextField>() _shouldReturnPublishSubject = subject return subject } public typealias ShouldChangeCharacters = (UITextField, NSRange, String) -> Bool public var shouldChangeCharacters: ShouldChangeCharacters = { _, _, _ in true } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return shouldChangeCharacters(textField, range, string) } public func textFieldShouldClear(_ textField: UITextField) -> Bool { if let subject = _shouldClearPublishSubject { subject.onNext(textField) } return true } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let subject = _shouldReturnPublishSubject { subject.onNext(textField) } return true } deinit { if let subject = _shouldClearPublishSubject { subject.onCompleted() } if let subject = _shouldReturnPublishSubject { subject.onCompleted() } } }
mit
c815193b009a74de1b8875f0b4171f05
29.211765
136
0.662773
5.836364
false
false
false
false
michikono/how-tos
swift-using-typealiases-as-generics/swift-using-typealiases-as-generics.playground/Pages/5-0-implementing-patterns.xcplaygroundpage/Contents.swift
1
918
//: Implementing Patterns //: ===================== //: [Previous](@previous) protocol Material {} class Wood: Material {} class Glass: Material {} class Metal: Material {} class Cotton: Material {} protocol HouseholdThing { } protocol Furniture: HouseholdThing { typealias M: Material typealias T: HouseholdThing func mainMaterial() -> M static func factory() -> T } class Chair: Furniture { func mainMaterial() -> Wood { return Wood() } static func factory() -> Chair { return Chair() } } class Lamp: Furniture { func mainMaterial() -> Glass { return Glass() } static func factory() -> Lamp { return Lamp() } } //: This won't work class FurnitureMaker<C: Furniture> { func make() -> C { return C() } func material(furniture: C) -> C.M { return furniture.mainMaterial() } } //: [Next](@next)
mit
2ec9943580e1fbd4f05ed6f3a8c1c88e
17.36
40
0.58061
3.793388
false
false
false
false
cuappdev/podcast-ios
Recast/Discover/MainSearchViewController.swift
1
4418
// // MainSearchViewController.swift // Recast // // Created by Jack Thompson on 9/25/18. // Copyright © 2018 Cornell AppDev. All rights reserved. // import UIKit import SnapKit protocol SearchTableViewDelegate: class { func refreshController() func didPress(_ partialPodcast: PartialPodcast) } class MainSearchViewController: ViewController { // MARK: - Variables var searchController: UISearchController! var searchResultsTableView: UITableView! var tableViewData: MainSearchDataSourceDelegate! var searchDelayTimer: Timer? var searchText: String = "" var discoverContainerView: UIView! var discoverVC: DiscoverViewController! // MARK: - Constants let podcastCellReuseId = PodcastTableViewCell.cellReuseId override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Search" searchController = UISearchController(searchResultsController: nil) searchController.hidesNavigationBarDuringPresentation = false searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.placeholder = "Search" searchController.searchBar.barStyle = .black searchController.searchBar.delegate = self navigationItem.hidesSearchBarWhenScrolling = false definesPresentationContext = true let searchField = searchController?.searchBar.value(forKey: "searchField") as? UITextField searchField?.textColor = .white searchField?.backgroundColor = #colorLiteral(red: 0.09749762056, green: 0.09749762056, blue: 0.09749762056, alpha: 1) searchController?.searchBar.barTintColor = .black searchController?.searchBar.barStyle = .black searchController?.searchBar.tintColor = .white navigationItem.titleView = searchController.searchBar tableViewData = MainSearchDataSourceDelegate() tableViewData.delegate = self searchResultsTableView = UITableView(frame: .zero, style: .plain) searchResultsTableView.dataSource = tableViewData searchResultsTableView.delegate = tableViewData searchResultsTableView.register(PodcastTableViewCell.self, forCellReuseIdentifier: podcastCellReuseId) view.addSubview(searchResultsTableView) discoverContainerView = UIView() discoverContainerView.isUserInteractionEnabled = true view.addSubview(discoverContainerView) discoverVC = DiscoverViewController() addChild(discoverVC) discoverContainerView.addSubview(discoverVC.view) setUpConstraints() } func setUpConstraints() { searchResultsTableView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide) make.leading.trailing.bottom.equalToSuperview() } discoverContainerView.snp.makeConstraints { make in make.edges.equalTo(searchResultsTableView) } discoverVC.view.snp.makeConstraints { make in make.edges.equalToSuperview() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.prefersLargeTitles = false navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) searchController.searchBar.delegate = self } } // MARK: - searchResultsTableView Delegate extension MainSearchViewController: SearchTableViewDelegate { func refreshController() { searchResultsTableView.reloadData() searchResultsTableView.layoutIfNeeded() } func didPress(_ partialPodcast: PartialPodcast) { let podcastDetailVC = PodcastDetailViewController(partialPodcast: partialPodcast) navigationController?.pushViewController(podcastDetailVC, animated: true) } } // MARK: UISearchBarDelegate extension MainSearchViewController: UISearchBarDelegate { func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { discoverContainerView.isHidden = false } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { discoverContainerView.isHidden = true } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard let searchText = searchController.searchBar.text else { return } tableViewData.fetchData(query: searchText) } }
mit
59559087fa583b288604013f45e95e95
34.055556
125
0.723568
5.827177
false
false
false
false
ferdinandurban/HUDini
HUDini/Views/HUDiniImageView.swift
1
808
// // HUDiniImageView.swift // HUDini // // Created by Ferdinand Urban on 15/10/15. // Copyright © 2015 Ferdinand Urban. All rights reserved. // import UIKit public class HUDiniImageView: HUDiniBaseSquareView { public let imageView: UIImageView = { let imageView = UIImageView() imageView.alpha = 0.85 imageView.clipsToBounds = true imageView.contentMode = .Center return imageView }() func imageViewInit(image: UIImage?) { imageView.image = image addSubview(imageView) } public init(image: UIImage?) { super.init() imageViewInit(image) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) imageViewInit(nil) } }
mit
bd03027a3905163a341b91bcc01837d1
20.263158
58
0.60223
4.434066
false
false
false
false
grafiti-io/SwiftCharts
SwiftCharts/Views/ChartAreasView.swift
1
3110
// // ChartAreasView.swift // swift_charts // // Created by ischuetz on 18/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit open class ChartAreasView: UIView { fileprivate let animDuration: Float fileprivate let color: UIColor fileprivate let animDelay: Float public init(points: [CGPoint], frame: CGRect, color: UIColor, animDuration: Float, animDelay: Float) { self.color = color self.animDuration = animDuration self.animDelay = animDelay super.init(frame: frame) backgroundColor = UIColor.clear show(path: generateAreaPath(points: points)) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func generateAreaPath(points: [CGPoint]) -> UIBezierPath { let progressline = UIBezierPath() progressline.lineWidth = 1.0 progressline.lineCapStyle = .round progressline.lineJoinStyle = .round if let p = points.first { progressline.move(to: p) } for i in 1..<points.count { let p = points[i] progressline.addLine(to: p) } progressline.close() return progressline } fileprivate func show(path: UIBezierPath) { let areaLayer = CAShapeLayer() areaLayer.lineJoin = kCALineJoinBevel areaLayer.fillColor = color.cgColor areaLayer.lineWidth = 2.0 areaLayer.strokeEnd = 0.0 layer.addSublayer(areaLayer) areaLayer.path = path.cgPath areaLayer.strokeColor = color.cgColor if animDuration > 0 { let maskLayer = CAGradientLayer() maskLayer.anchorPoint = CGPoint.zero let colors = [ UIColor(white: 0, alpha: 0).cgColor, UIColor(white: 0, alpha: 1).cgColor] maskLayer.colors = colors maskLayer.bounds = CGRect(x: 0, y: 0, width: 0, height: layer.bounds.size.height) maskLayer.startPoint = CGPoint(x: 1, y: 0) maskLayer.endPoint = CGPoint(x: 0, y: 0) layer.mask = maskLayer let revealAnimation = CABasicAnimation(keyPath: "bounds") revealAnimation.fromValue = NSValue(cgRect: CGRect(x: 0, y: 0, width: 0, height: layer.bounds.size.height)) let target = CGRect(x: layer.bounds.origin.x, y: layer.bounds.origin.y, width: layer.bounds.size.width + 2000, height: layer.bounds.size.height) revealAnimation.toValue = NSValue(cgRect: target) revealAnimation.duration = CFTimeInterval(animDuration) revealAnimation.isRemovedOnCompletion = false revealAnimation.fillMode = kCAFillModeForwards revealAnimation.beginTime = CACurrentMediaTime() + CFTimeInterval(animDelay) layer.mask?.add(revealAnimation, forKey: "revealAnimation") } } }
apache-2.0
db3c0afb455360e7fe8709b0327a3409
32.804348
156
0.599035
4.799383
false
false
false
false
sugar2010/Crust
Crust/Model.swift
2
2647
// // Model.swift // Crust // // Created by Justin Spahr-Summers on 2014-06-23. // Copyright (c) 2014 Justin Spahr-Summers. All rights reserved. // import Foundation /// Describes a property's key and type. protocol PropertyDescription: Equatable, Hashable { typealias Value var key: String { get } var type: Any.Type { get } } /// Describes a property of type T. struct PropertyOf<T>: PropertyDescription { typealias Value = T let key: String let type: Any.Type = T.self var hashValue: Int { get { return key.hashValue } } init(_ key: String) { self.key = key } init(_ property: PropertyDescription) { key = property.key type = property.type } } @infix func ==<T>(lhs: PropertyOf<T>, rhs: PropertyOf<T>) -> Bool { return lhs.key == rhs.key } func _reify(properties: PropertyDescription[]) -> PropertyOf<Any>[] { return properties.map { PropertyOf<Any>($0) } } /// The type of dictionary that should be used to store a Model's backing /// properties. typealias PropertyStorage = Dictionary<String, protocol<Equatable>> /// Represents a model object with dynamic property storage. /// /// This should typically be a value type. protocol Model { class func describe() -> PropertyDescription[] var properties: PropertyStorage { get set } init(properties: PropertyStorage) } /// Gets the value of the given property from the given model. func getProperty<M: Model, T: Equatable, P: PropertyDescription where P.Value == T>(model: M, property: P) -> T? { assert(contains(_reify(model.dynamicType.describe()), PropertyOf(property))) return model.properties[property.key] as T? } /// Instantiates a new model that will have the given property set to the given /// new value. func transformProperty<M: Model, T: Equatable, P: PropertyDescription where P.Value == T>(model: M, property: P, value: T) -> M? { assert(contains(_reify(model.dynamicType.describe()), PropertyOf(property))) var properties = model.properties properties[property.key] = value return model.dynamicType(properties: properties) } /// Sets the value of the given property on the given model. func setProperty<M: Model, T: Equatable, P: PropertyDescription where P.Value == T>(inout model: M, property: P, toValue: T) { assert(contains(_reify(model.dynamicType.describe()), PropertyOf(property))) model.properties[property.key] = toValue } /// Clears any existing value for the given property on the given model. func clearProperty<M: Model>(inout model: M, property: PropertyDescription) { assert(contains(_reify(model.dynamicType.describe()), PropertyOf(property))) model.properties.removeValueForKey(property.key) }
mit
fd992ee747754d7454afad345fe21189
26.863158
130
0.722327
3.581867
false
false
false
false
samlaudev/DesignerNews
DesignerNews/CommentCell.swift
1
3386
// // CommentCell.swift // DesignerNews // // Created by Sam Lau on 3/16/15. // Copyright (c) 2015 Sam Lau. All rights reserved. // import UIKit protocol CommonCellDelegate: class { func commonCellDelegateDidTouchUpvote(cell: CommentCell) func commonCellDelegateDidTouchComment(cell: CommentCell) } class CommentCell: UITableViewCell { // MARK: - UI properties @IBOutlet weak var avatarImageView: AsyncImageView! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var upvoteButton: SpringButton! @IBOutlet weak var replyButton: SpringButton! @IBOutlet weak var commentTextView: AutoTextView! @IBOutlet weak var avatarLeftConstraint: NSLayoutConstraint! @IBOutlet weak var indentView: UIView! // MARK: - Delegate weak var delegate: CommonCellDelegate? // MARK: - Respond to action @IBAction func upvoteButtonDidTouch(sender: AnyObject) { upvoteButton.animate() delegate?.commonCellDelegateDidTouchUpvote(self) } @IBAction func replyButtonDidTouch(sender: AnyObject) { replyButton.animate() delegate?.commonCellDelegateDidTouchComment(self) } // MARK: - UI properties func configureCommentCell(comment: JSON) { let userPortraitUrl = comment["user_portrait_url"].string let userDisplayName = comment["user_display_name"].string ?? "" let userJob = comment["user_job"].string ?? "" let createdAt = comment["created_at"].string ?? "" let voteCount = comment["vote_count"].int ?? 0 let body = comment["body"].string ?? "" let bodyHTML = comment["body_html"].string ?? "" timeLabel.text = timeAgoSinceDate(dateFromString(createdAt, "yyyy-MM-dd'T'HH:mm:ssZ"), true) avatarImageView.url = userPortraitUrl?.toURL() avatarImageView.placeholderImage = UIImage(named: "content-avatar-default") authorLabel.text = userDisplayName + ", " + userJob upvoteButton.setTitle("\(voteCount)", forState: UIControlState.Normal) commentTextView.text = body // commentTextView.attributedText = htmlToAttributedString(bodyHTML + "<style>*{font-family:\"Avenir Next\";font-size:16px;line-height:20px}img{max-width:300px}</style>") let commentId = comment["id"].int! if LocalStore.isCommentUpvoted(commentId) { upvoteButton.setImage(UIImage(named: "icon-upvote-active"), forState: UIControlState.Normal) upvoteButton.setTitle(String(comment["vote_count"].int! + 1), forState: UIControlState.Normal) }else { upvoteButton.setImage(UIImage(named: "icon-upvote"), forState: UIControlState.Normal) upvoteButton.setTitle(String(comment["vote_count"].int!), forState: UIControlState.Normal) } let depth = comment["depth"].int! > 4 ? 4 : comment["depth"].int! if depth > 0 { avatarLeftConstraint.constant = CGFloat(depth) * 15 + 25 separatorInset = UIEdgeInsets(top: 0, left: CGFloat(depth) * 20 + 15, bottom: 0, right: 0) indentView.hidden = false } else { avatarLeftConstraint.constant = 7 separatorInset = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 0) indentView.hidden = true } } }
mit
610c2e02b106b8530ed9dec24f10dd1c
40.292683
177
0.657118
4.472919
false
false
false
false
CarlosMChica/swift-dojos
SocialNetworkKata/SocialNetworkKata/model/Post.swift
1
339
struct Post: Equatable { let user: User let message: String let timestamp: CLong init(user: User, message: String, timestamp: CLong) { self.user = user self.message = message self.timestamp = timestamp } } func ==(lhs: Post, rhs: Post) -> Bool { return lhs.message == rhs.message && lhs.user == rhs.user }
apache-2.0
76e5c543278655216ffab662776b5482
18.941176
55
0.637168
3.606383
false
false
false
false
hughbe/swift
stdlib/public/core/Builtin.swift
4
31896
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // Definitions that make elements of Builtin usable in real code // without gobs of boilerplate. @available(*, unavailable, message: "use MemoryLayout<T>.size instead.") public func sizeof<T>(_:T.Type) -> Int { Builtin.unreachable() } @available(*, unavailable, renamed: "MemoryLayout.size(ofValue:)") public func sizeofValue<T>(_:T) -> Int { Builtin.unreachable() } @available(*, unavailable, message: "use MemoryLayout<T>.alignment instead.") public func alignof<T>(_:T.Type) -> Int { Builtin.unreachable() } @available(*, unavailable, renamed: "MemoryLayout.alignment(ofValue:)") public func alignofValue<T>(_:T) -> Int { Builtin.unreachable() } @available(*, unavailable, message: "use MemoryLayout<T>.stride instead.") public func strideof<T>(_:T.Type) -> Int { Builtin.unreachable() } @available(*, unavailable, renamed: "MemoryLayout.stride(ofValue:)") public func strideofValue<T>(_:T) -> Int { Builtin.unreachable() } // This function is the implementation of the `_roundUp` overload set. It is // marked `@inline(__always)` to make primary `_roundUp` entry points seem // cheap enough for the inliner. @_versioned @inline(__always) internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt { _sanityCheck(alignment > 0) _sanityCheck(_isPowerOf2(alignment)) // Note, given that offset is >= 0, and alignment > 0, we don't // need to underflow check the -1, as it can never underflow. let x = offset + UInt(bitPattern: alignment) &- 1 // Note, as alignment is a power of 2, we'll use masking to efficiently // get the aligned value return x & ~(UInt(bitPattern: alignment) &- 1) } @_versioned internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt { return _roundUpImpl(offset, toAlignment: alignment) } @_versioned internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int { _sanityCheck(offset >= 0) return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment)) } /// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe. @_transparent public // @testable func _canBeClass<T>(_: T.Type) -> Int8 { return Int8(Builtin.canBeClass(T.self)) } /// Returns the bits of the given instance, interpreted as having the specified /// type. /// /// Use this function only to convert the instance passed as `x` to a /// layout-compatible type when conversion through other means is not /// possible. Common conversions supported by the Swift standard library /// include the following: /// /// - Value conversion from one integer type to another. Use the destination /// type's initializer or the `numericCast(_:)` function. /// - Bitwise conversion from one integer type to another. Use the destination /// type's `init(extendingOrTruncating:)` or `init(bitPattern:)` /// initializer. /// - Conversion from a pointer to an integer value with the bit pattern of the /// pointer's address in memory, or vice versa. Use the `init(bitPattern:)` /// initializer for the destination type. /// - Casting an instance of a reference type. Use the casting operators (`as`, /// `as!`, or `as?`) or the `unsafeDowncast(_:to:)` function. Do not use /// `unsafeBitCast(_:to:)` with class or pointer types; doing so may /// introduce undefined behavior. /// /// - Warning: Calling this function breaks the guarantees of the Swift type /// system; use with extreme care. /// /// - Parameters: /// - x: The instance to cast to `type`. /// - type: The type to cast `x` to. `type` and the type of `x` must have the /// same size of memory representation and compatible memory layout. /// - Returns: A new instance of type `U`, cast from `x`. @_transparent public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U { _precondition(MemoryLayout<T>.size == MemoryLayout<U>.size, "can't unsafeBitCast between types of different sizes") return Builtin.reinterpretCast(x) } /// Returns `x` as its concrete type `U`. /// /// This cast can be useful for dispatching to specializations of generic /// functions. /// /// - Requires: `x` has type `U`. @_transparent public func _identityCast<T, U>(_ x: T, to expectedType: U.Type) -> U { _precondition(T.self == expectedType, "_identityCast to wrong type") return Builtin.reinterpretCast(x) } /// `unsafeBitCast` something to `AnyObject`. @_transparent internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject { return unsafeBitCast(x, to: AnyObject.self) } @_inlineable @_versioned @_transparent func == (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @_inlineable @_versioned @_transparent func != (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool { return !(lhs == rhs) } @_inlineable @_versioned @_transparent func == (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @_inlineable @_versioned @_transparent func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool { return !(lhs == rhs) } /// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both /// `nil` or they both represent the same type. @_inlineable public func == (t0: Any.Type?, t1: Any.Type?) -> Bool { switch (t0, t1) { case (.none, .none): return true case let (.some(ty0), .some(ty1)): return Bool(Builtin.is_same_metatype(ty0, ty1)) default: return false } } /// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both /// `nil` or they both represent the same type. @_inlineable public func != (t0: Any.Type?, t1: Any.Type?) -> Bool { return !(t0 == t1) } /// Tell the optimizer that this code is unreachable if condition is /// known at compile-time to be true. If condition is false, or true /// but not a compile-time constant, this call has no effect. @_transparent internal func _unreachable(_ condition: Bool = true) { if condition { // FIXME: use a parameterized version of Builtin.unreachable when // <rdar://problem/16806232> is closed. Builtin.unreachable() } } /// Tell the optimizer that this code is unreachable if this builtin is /// reachable after constant folding build configuration builtins. @_versioned @_transparent internal func _conditionallyUnreachable() -> Never { Builtin.conditionallyUnreachable() } @_versioned @_silgen_name("_swift_isClassOrObjCExistentialType") func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool /// Returns `true` iff `T` is a class type or an `@objc` existential such as /// `AnyObject`. @_versioned @inline(__always) internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool { switch _canBeClass(x) { // Is not a class. case 0: return false // Is a class. case 1: return true // Maybe a class. default: return _swift_isClassOrObjCExistentialType(x) } } /// Returns an `UnsafePointer` to the storage used for `object`. There's /// not much you can do with this other than use it to identify the /// object. @available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.") public func unsafeAddress(of object: AnyObject) -> UnsafeRawPointer { Builtin.unreachable() } @available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.") public func unsafeAddressOf(_ object: AnyObject) -> UnsafeRawPointer { Builtin.unreachable() } /// Converts a reference of type `T` to a reference of type `U` after /// unwrapping one level of Optional. /// /// Unwrapped `T` and `U` must be convertible to AnyObject. They may /// be either a class or a class protocol. Either T, U, or both may be /// optional references. @_transparent public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U { return Builtin.castReference(x) } /// - returns: `x as T`. /// /// - Precondition: `x is T`. In particular, in -O builds, no test is /// performed to ensure that `x` actually has dynamic type `T`. /// /// - Warning: Trades safety for performance. Use `unsafeDowncast` /// only when `x as! T` has proven to be a performance problem and you /// are confident that, always, `x is T`. It is better than an /// `unsafeBitCast` because it's more restrictive, and because /// checking is still performed in debug builds. @_transparent public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to: T.Type) -> T { _debugPrecondition(x is T, "invalid unsafeDowncast") return Builtin.castReference(x) } import SwiftShims @inline(__always) public func _getUnsafePointerToStoredProperties(_ x: AnyObject) -> UnsafeMutableRawPointer { let storedPropertyOffset = _roundUp( MemoryLayout<SwiftShims.HeapObject>.size, toAlignment: MemoryLayout<Optional<AnyObject>>.alignment) return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) + storedPropertyOffset } //===----------------------------------------------------------------------===// // Branch hints //===----------------------------------------------------------------------===// // Use @_semantics to indicate that the optimizer recognizes the // semantics of these function calls. This won't be necessary with // mandatory generic inlining. @_versioned @_transparent @_semantics("branchhint") internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool { return Bool(Builtin.int_expect_Int1(actual._value, expected._value)) } /// Optimizer hint that `x` is expected to be `true`. @_transparent @_semantics("fastpath") public func _fastPath(_ x: Bool) -> Bool { return _branchHint(x, expected: true) } /// Optimizer hint that `x` is expected to be `false`. @_transparent @_semantics("slowpath") public func _slowPath(_ x: Bool) -> Bool { return _branchHint(x, expected: false) } /// Optimizer hint that the code where this function is called is on the fast /// path. @_transparent public func _onFastPath() { Builtin.onFastPath() } //===--- Runtime shim wrappers --------------------------------------------===// /// Returns `true` iff the class indicated by `theClass` uses native /// Swift reference-counting. #if _runtime(_ObjC) // Declare it here instead of RuntimeShims.h, because we need to specify // the type of argument to be AnyClass. This is currently not possible // when using RuntimeShims.h @_versioned @_silgen_name("swift_objc_class_usesNativeSwiftReferenceCounting") func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool #else @_versioned @inline(__always) func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool { return true } #endif @_silgen_name("swift_class_getInstanceExtents") func swift_class_getInstanceExtents(_ theClass: AnyClass) -> (negative: UInt, positive: UInt) @_silgen_name("swift_objc_class_unknownGetInstanceExtents") func swift_objc_class_unknownGetInstanceExtents(_ theClass: AnyClass) -> (negative: UInt, positive: UInt) /// - Returns: @inline(__always) internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int { #if _runtime(_ObjC) return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive) #else return Int(swift_class_getInstanceExtents(theClass).positive) #endif } //===--- Builtin.BridgeObject ---------------------------------------------===// #if arch(i386) || arch(arm) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0003 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0002 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #elseif arch(x86_64) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x7F00_0000_0000_0006 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x4000_0000_0000_0000 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 1 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0x8000_0000_0000_0001 } } #elseif arch(arm64) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x7F00_0000_0000_0007 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x4000_0000_0000_0000 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0x8000_0000_0000_0000 } } #elseif arch(powerpc64) || arch(powerpc64le) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0000_0000_0007 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0000_0000_0002 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #elseif arch(s390x) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0000_0000_0007 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0000_0000_0002 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #endif /// Extract the raw bits of `x`. @_versioned @inline(__always) internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt { return UInt(Builtin.castBitPatternFromBridgeObject(x)) } /// Extract the raw spare bits of `x`. @_versioned @inline(__always) internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt { return _bitPattern(x) & _objectPointerSpareBits } @_versioned @inline(__always) internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool { return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0 } /// Create a `BridgeObject` around the given `nativeObject` with the /// given spare bits. /// /// Reference-counting and other operations on this /// object will have access to the knowledge that it is native. /// /// - Precondition: `bits & _objectPointerIsObjCBit == 0`, /// `bits & _objectPointerSpareBits == bits`. @_versioned @inline(__always) internal func _makeNativeBridgeObject( _ nativeObject: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _sanityCheck( (bits & _objectPointerIsObjCBit) == 0, "BridgeObject is treated as non-native when ObjC bit is set" ) return _makeBridgeObject(nativeObject, bits) } /// Create a `BridgeObject` around the given `objCObject`. @inline(__always) public // @testable func _makeObjCBridgeObject( _ objCObject: AnyObject ) -> Builtin.BridgeObject { return _makeBridgeObject( objCObject, _isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit) } /// Create a `BridgeObject` around the given `object` with the /// given spare bits. /// /// - Precondition: /// /// 1. `bits & _objectPointerSpareBits == bits` /// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise, /// `object` is either a native object, or `bits == /// _objectPointerIsObjCBit`. @_versioned @inline(__always) internal func _makeBridgeObject( _ object: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _sanityCheck(!_isObjCTaggedPointer(object) || bits == 0, "Tagged pointers cannot be combined with bits") _sanityCheck( _isObjCTaggedPointer(object) || _usesNativeSwiftReferenceCounting(type(of: object)) || bits == _objectPointerIsObjCBit, "All spare bits must be set in non-native, non-tagged bridge objects" ) _sanityCheck( bits & _objectPointerSpareBits == bits, "Can't store non-spare bits into Builtin.BridgeObject") return Builtin.castToBridgeObject( object, bits._builtinWordValue ) } @_versioned @_silgen_name("_swift_class_getSuperclass") internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass? /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// a root class or class protocol. @inline(__always) public // @testable func _getSuperclass(_ t: AnyClass) -> AnyClass? { return _swift_class_getSuperclass(t) } /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// not a class, is a root class, or is a class protocol. @inline(__always) public // @testable func _getSuperclass(_ t: Any.Type) -> AnyClass? { return (t as? AnyClass).flatMap { _getSuperclass($0) } } //===--- Builtin.IsUnique -------------------------------------------------===// // _isUnique functions must take an inout object because they rely on // Builtin.isUnique which requires an inout reference to preserve // source-level copies in the presence of ARC optimization. // // Taking an inout object makes sense for two additional reasons: // // 1. You should only call it when about to mutate the object. // Doing so otherwise implies a race condition if the buffer is // shared across threads. // // 2. When it is not an inout function, self is passed by // value... thus bumping the reference count and disturbing the // result we are trying to observe, Dr. Heisenberg! // // _isUnique and _isUniquePinned cannot be made public or the compiler // will attempt to generate generic code for the transparent function // and type checking will fail. /// Returns `true` if `object` is uniquely referenced. @_versioned @_transparent internal func _isUnique<T>(_ object: inout T) -> Bool { return Bool(Builtin.isUnique(&object)) } /// Returns `true` if `object` is uniquely referenced or pinned. @_versioned @_transparent internal func _isUniqueOrPinned<T>(_ object: inout T) -> Bool { return Bool(Builtin.isUniqueOrPinned(&object)) } /// Returns `true` if `object` is uniquely referenced. /// This provides sanity checks on top of the Builtin. @_transparent public // @testable func _isUnique_native<T>(_ object: inout T) -> Bool { // This could be a bridge object, single payload enum, or plain old // reference. Any case it's non pointer bits must be zero, so // force cast it to BridgeObject and check the spare bits. _sanityCheck( (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits) == 0) _sanityCheck(_usesNativeSwiftReferenceCounting( type(of: Builtin.reinterpretCast(object) as AnyObject))) return Bool(Builtin.isUnique_native(&object)) } /// Returns `true` if `object` is uniquely referenced or pinned. /// This provides sanity checks on top of the Builtin. @_transparent public // @testable func _isUniqueOrPinned_native<T>(_ object: inout T) -> Bool { // This could be a bridge object, single payload enum, or plain old // reference. Any case it's non pointer bits must be zero. _sanityCheck( (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits) == 0) _sanityCheck(_usesNativeSwiftReferenceCounting( type(of: Builtin.reinterpretCast(object) as AnyObject))) return Bool(Builtin.isUniqueOrPinned_native(&object)) } /// Returns `true` if type is a POD type. A POD type is a type that does not /// require any special handling on copying or destruction. @_transparent public // @testable func _isPOD<T>(_ type: T.Type) -> Bool { return Bool(Builtin.ispod(type)) } /// Returns `true` if type is nominally an Optional type. @_transparent public // @testable func _isOptional<T>(_ type: T.Type) -> Bool { return Bool(Builtin.isOptional(type)) } @available(*, unavailable, message: "Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.") public func unsafeUnwrap<T>(_ nonEmpty: T?) -> T { Builtin.unreachable() } /// Extract an object reference from an Any known to contain an object. internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject { _sanityCheck(type(of: any) is AnyObject.Type || type(of: any) is AnyObject.Protocol, "Any expected to contain object reference") // With a SIL instruction, we could more efficiently grab the object reference // out of the Any's inline storage. // On Linux, bridging isn't supported, so this is a force cast. #if _runtime(_ObjC) return any as AnyObject #else return any as! AnyObject #endif } // Game the SIL diagnostic pipeline by inlining this into the transparent // definitions below after the stdlib's diagnostic passes run, so that the // `staticReport`s don't fire while building the standard library, but do // fire if they ever show up in code that uses the standard library. @inline(__always) public // internal with availability func _trueAfterDiagnostics() -> Builtin.Int1 { return true._value } /// Returns the dynamic type of a value. /// /// You can use the `type(of:)` function to find the dynamic type of a value, /// particularly when the dynamic type is different from the static type. The /// *static type* of a value is the known, compile-time type of the value. The /// *dynamic type* of a value is the value's actual type at run-time, which /// can be nested inside its concrete type. /// /// In the following code, the `count` variable has the same static and dynamic /// type: `Int`. When `count` is passed to the `printInfo(_:)` function, /// however, the `value` parameter has a static type of `Any` (the type /// declared for the parameter) and a dynamic type of `Int`. /// /// func printInfo(_ value: Any) { /// let type = type(of: value) /// print("'\(value)' of type '\(type)'") /// } /// /// let count: Int = 5 /// printInfo(count) /// // '5' of type 'Int' /// /// The dynamic type returned from `type(of:)` is a *concrete metatype* /// (`T.Type`) for a class, structure, enumeration, or other nonprotocol type /// `T`, or an *existential metatype* (`P.Type`) for a protocol or protocol /// composition `P`. When the static type of the value passed to `type(of:)` /// is constrained to a class or protocol, you can use that metatype to access /// initializers or other static members of the class or protocol. /// /// For example, the parameter passed as `value` to the `printSmileyInfo(_:)` /// function in the example below is an instance of the `Smiley` class or one /// of its subclasses. The function uses `type(of:)` to find the dynamic type /// of `value`, which itself is an instance of the `Smiley.Type` metatype. /// /// class Smiley { /// class var text: String { /// return ":)" /// } /// } /// /// class EmojiSmiley : Smiley { /// override class var text: String { /// return "😀" /// } /// } /// /// func printSmileyInfo(_ value: Smiley) { /// let smileyType = type(of: value) /// print("Smile!", smileyType.text) /// } /// /// let emojiSmiley = EmojiSmiley() /// printSmileyInfo(emojiSmiley) /// // Smile! 😀 /// /// In this example, accessing the `text` property of the `smileyType` metatype /// retrieves the overridden value from the `EmojiSmiley` subclass, instead of /// the `Smiley` class's original definition. /// /// Finding the Dynamic Type in a Generic Context /// ============================================= /// /// Normally, you don't need to be aware of the difference between concrete and /// existential metatypes, but calling `type(of:)` can yield unexpected /// results in a generic context with a type parameter bound to a protocol. In /// a case like this, where a generic parameter `T` is bound to a protocol /// `P`, the type parameter is not statically known to be a protocol type in /// the body of the generic function. As a result, `type(of:)` can only /// produce the concrete metatype `P.Protocol`. /// /// The following example defines a `printGenericInfo(_:)` function that takes /// a generic parameter and declares the `String` type's conformance to a new /// protocol `P`. When `printGenericInfo(_:)` is called with a string that has /// `P` as its static type, the call to `type(of:)` returns `P.self` instead /// of `String.self` (the dynamic type inside the parameter). /// /// func printGenericInfo<T>(_ value: T) { /// let type = type(of: value) /// print("'\(value)' of type '\(type)'") /// } /// /// protocol P {} /// extension String: P {} /// /// let stringAsP: P = "Hello!" /// printGenericInfo(stringAsP) /// // 'Hello!' of type 'P' /// /// This unexpected result occurs because the call to `type(of: value)` inside /// `printGenericInfo(_:)` must return a metatype that is an instance of /// `T.Type`, but `String.self` (the expected dynamic type) is not an instance /// of `P.Type` (the concrete metatype of `value`). To get the dynamic type /// inside `value` in this generic context, cast the parameter to `Any` when /// calling `type(of:)`. /// /// func betterPrintGenericInfo<T>(_ value: T) { /// let type = type(of: value as Any) /// print("'\(value)' of type '\(type)'") /// } /// /// betterPrintGenericInfo(stringAsP) /// // 'Hello!' of type 'String' /// /// - Parameter value: The value for which to find the dynamic type. /// - Returns: The dynamic type, which is a metatype instance. @_transparent @_semantics("typechecker.type(of:)") public func type<T, Metatype>(of value: T) -> Metatype { // This implementation is never used, since calls to `Swift.type(of:)` are // resolved as a special case by the type checker. Builtin.staticReport(_trueAfterDiagnostics(), true._value, ("internal consistency error: 'type(of:)' operation failed to resolve" as StaticString).utf8Start._rawValue) Builtin.unreachable() } /// Allows a nonescaping closure to temporarily be used as if it were allowed /// to escape. /// /// You can use this function to call an API that takes an escaping closure in /// a way that doesn't allow the closure to escape in practice. The examples /// below demonstrate how to use `withoutActuallyEscaping(_:do:)` in /// conjunction with two common APIs that use escaping closures: lazy /// collection views and asynchronous operations. /// /// The following code declares an `allValues(in:match:)` function that checks /// whether all the elements in an array match a predicate. The function won't /// compile as written, because a lazy collection's `filter(_:)` method /// requires an escaping closure. The lazy collection isn't persisted, so the /// `predicate` closure won't actually escape the body of the function; /// nevertheless, it can't be used in this way. /// /// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool { /// return array.lazy.filter { !predicate($0) }.isEmpty /// } /// // error: closure use of non-escaping parameter 'predicate'... /// /// `withoutActuallyEscaping(_:do:)` provides a temporarily escapable copy of /// `predicate` that _can_ be used in a call to the lazy view's `filter(_:)` /// method. The second version of `allValues(in:match:)` compiles without /// error, with the compiler guaranteeing that the `escapablePredicate` /// closure doesn't last beyond the call to `withoutActuallyEscaping(_:do:)`. /// /// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool { /// return withoutActuallyEscaping(predicate) { escapablePredicate in /// array.lazy.filter { !escapablePredicate($0) }.isEmpty /// } /// } /// /// Asynchronous calls are another type of API that typically escape their /// closure arguments. The following code declares a /// `perform(_:simultaneouslyWith:)` function that uses a dispatch queue to /// execute two closures concurrently. /// /// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) { /// let queue = DispatchQueue(label: "perform", attributes: .concurrent) /// queue.async(execute: f) /// queue.async(execute: g) /// queue.sync(flags: .barrier) {} /// } /// // error: passing non-escaping parameter 'f'... /// // error: passing non-escaping parameter 'g'... /// /// The `perform(_:simultaneouslyWith:)` function ends with a call to the /// `sync(flags:execute:)` method using the `.barrier` flag, which forces the /// function to wait until both closures have completed running before /// returning. Even though the barrier guarantees that neither closure will /// escape the function, the `async(execute:)` method still requires that the /// closures passed be marked as `@escaping`, so the first version of the /// function does not compile. To resolve these errors, you can use /// `withoutActuallyEscaping(_:do:)` to get copies of `f` and `g` that can be /// passed to `async(execute:)`. /// /// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) { /// withoutActuallyEscaping(f) { escapableF in /// withoutActuallyEscaping(g) { escapableG in /// let queue = DispatchQueue(label: "perform", attributes: .concurrent) /// queue.async(execute: escapableF) /// queue.async(execute: escapableG) /// queue.sync(flags: .barrier) {} /// } /// } /// } /// /// - Important: The escapable copy of `closure` passed to `body` is only valid /// during the call to `withoutActuallyEscaping(_:do:)`. It is undefined /// behavior for the escapable closure to be stored, referenced, or executed /// after the function returns. /// /// - Parameters: /// - closure: A nonescaping closure value that is made escapable for the /// duration of the execution of the `body` closure. If `body` has a /// return value, that value is also used as the return value for the /// `withoutActuallyEscaping(_:do:)` function. /// - body: A closure that is executed immediately with an escapable copy of /// `closure` as its argument. /// - Returns: The return value, if any, of the `body` closure. @_transparent @_semantics("typechecker.withoutActuallyEscaping(_:do:)") public func withoutActuallyEscaping<ClosureType, ResultType>( _ closure: ClosureType, do body: (_ escapingClosure: ClosureType) throws -> ResultType ) rethrows -> ResultType { // This implementation is never used, since calls to // `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by // the type checker. Builtin.staticReport(_trueAfterDiagnostics(), true._value, ("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve" as StaticString).utf8Start._rawValue) Builtin.unreachable() } @_transparent @_semantics("typechecker._openExistential(_:do:)") public func _openExistential<ExistentialType, ContainedType, ResultType>( _ existential: ExistentialType, do body: (_ escapingClosure: ContainedType) throws -> ResultType ) rethrows -> ResultType { // This implementation is never used, since calls to // `Swift._openExistential(_:do:)` are resolved as a special case by // the type checker. Builtin.staticReport(_trueAfterDiagnostics(), true._value, ("internal consistency error: '_openExistential(_:do:)' operation failed to resolve" as StaticString).utf8Start._rawValue) Builtin.unreachable() }
apache-2.0
ca191fc6b1ffab3a502e71810195a6c0
35.238636
110
0.68476
4.05622
false
false
false
false
jeesmon/varamozhi-ios
varamozhi/KeyboardKey.swift
1
19035
// // KeyboardKey.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 6/9/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit // TODO: correct corner radius // TODO: refactor // popup constraints have to be setup with the topmost view in mind; hence these callbacks protocol KeyboardKeyProtocol: class { func frameForPopup(_ key: KeyboardKey, direction: Direction) -> CGRect func willShowPopup(_ key: KeyboardKey, direction: Direction) //may be called multiple times during layout func willHidePopup(_ key: KeyboardKey) } enum VibrancyType { case lightSpecial case darkSpecial case darkRegular } class KeyboardKey: UIControl { weak var delegate: KeyboardKeyProtocol? var vibrancy: VibrancyType? var text: String { didSet { self.label.text = text self.label.frame = CGRect(x: self.labelInset, y: self.labelInset, width: self.bounds.width - self.labelInset * 2, height: self.bounds.height - self.labelInset * 2) self.redrawText() } } var color: UIColor { didSet { updateColors() }} var underColor: UIColor { didSet { updateColors() }} var borderColor: UIColor { didSet { updateColors() }} var popupColor: UIColor { didSet { updateColors() }} var drawUnder: Bool { didSet { updateColors() }} var drawOver: Bool { didSet { updateColors() }} var drawBorder: Bool { didSet { updateColors() }} var underOffset: CGFloat { didSet { updateColors() }} var textColor: UIColor { didSet { updateColors() }} var downColor: UIColor? { didSet { updateColors() }} var downUnderColor: UIColor? { didSet { updateColors() }} var downBorderColor: UIColor? { didSet { updateColors() }} var downTextColor: UIColor? { didSet { updateColors() }} var labelInset: CGFloat = 0 { didSet { if oldValue != labelInset { self.label.frame = CGRect(x: self.labelInset, y: self.labelInset, width: self.bounds.width - self.labelInset * 2, height: self.bounds.height - self.labelInset * 2) } } } var shouldRasterize: Bool = false { didSet { for view in [self.displayView, self.borderView, self.underView] { view?.layer.shouldRasterize = shouldRasterize view?.layer.rasterizationScale = UIScreen.main.scale } } } var popupDirection: Direction? override var isEnabled: Bool { didSet { updateColors() }} override var isSelected: Bool { didSet { updateColors() } } override var isHighlighted: Bool { didSet { updateColors() } } override var frame: CGRect { didSet { self.redrawText() } } var label: UILabel var popupLabel: UILabel? var shape: Shape? { didSet { if oldValue != nil && shape == nil { oldValue?.removeFromSuperview() } self.redrawShape() updateColors() } } var background: KeyboardKeyBackground var popup: KeyboardKeyBackground? var connector: KeyboardConnector? var displayView: ShapeView var borderView: ShapeView? var underView: ShapeView? var shadowView: UIView var shadowLayer: CALayer init(vibrancy optionalVibrancy: VibrancyType?) { self.vibrancy = optionalVibrancy self.displayView = ShapeView() self.underView = ShapeView() self.borderView = ShapeView() self.shadowLayer = CAShapeLayer() self.shadowView = UIView() self.label = UILabel() self.text = "" self.color = UIColor.white self.underColor = UIColor.gray self.borderColor = UIColor.black self.popupColor = UIColor.red self.drawUnder = true self.drawOver = true self.drawBorder = false self.underOffset = 1 self.background = KeyboardKeyBackground(cornerRadius: 4, underOffset: self.underOffset) self.textColor = UIColor.black self.popupDirection = nil super.init(frame: CGRect.zero) self.addSubview(self.shadowView) self.shadowView.layer.addSublayer(self.shadowLayer) self.addSubview(self.displayView) if let underView = self.underView { self.addSubview(underView) } if let borderView = self.borderView { self.addSubview(borderView) } self.addSubview(self.background) self.background.addSubview(self.label) let _: Void = { self.displayView.isOpaque = false self.underView?.isOpaque = false self.borderView?.isOpaque = false self.shadowLayer.shadowOpacity = Float(0.2) self.shadowLayer.shadowRadius = 4 self.shadowLayer.shadowOffset = CGSize(width: 0, height: 3) self.borderView?.lineWidth = CGFloat(0.5) self.borderView?.fillColor = UIColor.clear self.label.textAlignment = NSTextAlignment.center self.label.baselineAdjustment = UIBaselineAdjustment.alignCenters self.label.font = self.label.font.withSize(22) self.label.adjustsFontSizeToFitWidth = true self.label.minimumScaleFactor = CGFloat(0.1) self.label.isUserInteractionEnabled = false self.label.numberOfLines = 2//+201412 }() } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } override func setNeedsLayout() { return super.setNeedsLayout() } var oldBounds: CGRect? override func layoutSubviews() { self.layoutPopupIfNeeded() let boundingBox = (self.popup != nil ? self.bounds.union(self.popup!.frame) : self.bounds) if self.bounds.width == 0 || self.bounds.height == 0 { return } if oldBounds != nil && boundingBox.size.equalTo(oldBounds!.size) { return } oldBounds = boundingBox super.layoutSubviews() CATransaction.begin() CATransaction.setDisableActions(true) self.background.frame = self.bounds self.label.frame = CGRect(x: self.labelInset, y: self.labelInset, width: self.bounds.width - self.labelInset * 2, height: self.bounds.height - self.labelInset * 2) self.displayView.frame = boundingBox self.shadowView.frame = boundingBox self.borderView?.frame = boundingBox self.underView?.frame = boundingBox CATransaction.commit() self.refreshViews() } func refreshViews() { self.refreshShapes() self.redrawText() self.redrawShape() self.updateColors() } func refreshShapes() { // TODO: dunno why this is necessary self.background.setNeedsLayout() self.background.layoutIfNeeded() self.popup?.layoutIfNeeded() self.connector?.layoutIfNeeded() let testPath = UIBezierPath() let edgePath = UIBezierPath() let unitSquare = CGRect(x: 0, y: 0, width: 1, height: 1) // TODO: withUnder let addCurves = { (fromShape: KeyboardKeyBackground?, toPath: UIBezierPath, toEdgePaths: UIBezierPath) -> Void in if let shape = fromShape { let path = shape.fillPath let translatedUnitSquare = self.displayView.convert(unitSquare, from: shape) let transformFromShapeToView = CGAffineTransform(translationX: translatedUnitSquare.origin.x, y: translatedUnitSquare.origin.y) path?.apply(transformFromShapeToView) if path != nil { toPath.append(path!) } if let edgePaths = shape.edgePaths { for (_, anEdgePath) in edgePaths.enumerated() { let editablePath = anEdgePath editablePath.apply(transformFromShapeToView) toEdgePaths.append(editablePath) } } } } addCurves(self.popup, testPath, edgePath) addCurves(self.connector, testPath, edgePath) let shadowPath = UIBezierPath(cgPath: testPath.cgPath) addCurves(self.background, testPath, edgePath) let underPath = self.background.underPath let translatedUnitSquare = self.displayView.convert(unitSquare, from: self.background) let transformFromShapeToView = CGAffineTransform(translationX: translatedUnitSquare.origin.x, y: translatedUnitSquare.origin.y) underPath?.apply(transformFromShapeToView) CATransaction.begin() CATransaction.setDisableActions(true) if let _ = self.popup { self.shadowLayer.shadowPath = shadowPath.cgPath } self.underView?.curve = underPath self.displayView.curve = testPath self.borderView?.curve = edgePath if let borderLayer = self.borderView?.layer as? CAShapeLayer { borderLayer.strokeColor = UIColor.green.cgColor } CATransaction.commit() } func layoutPopupIfNeeded() { if self.popup != nil && self.popupDirection == nil { self.shadowView.isHidden = false self.borderView?.isHidden = false self.popupDirection = Direction.up self.layoutPopup(self.popupDirection!) self.configurePopup(self.popupDirection!) self.delegate?.willShowPopup(self, direction: self.popupDirection!) } else { self.shadowView.isHidden = true self.borderView?.isHidden = true } } func redrawText() { // self.keyView.frame = self.bounds // self.button.frame = self.bounds // // self.button.setTitle(self.text, forState: UIControlState.Normal) } func redrawShape() { if let shape = self.shape { self.text = "" shape.removeFromSuperview() self.addSubview(shape) let pointOffset: CGFloat = 4 let size = CGSize(width: self.bounds.width - pointOffset - pointOffset, height: self.bounds.height - pointOffset - pointOffset) shape.frame = CGRect( x: CGFloat((self.bounds.width - size.width) / 2.0), y: CGFloat((self.bounds.height - size.height) / 2.0), width: size.width, height: size.height) shape.setNeedsLayout() } } func updateColors() { CATransaction.begin() CATransaction.setDisableActions(true) let switchColors = self.isHighlighted || self.isSelected if switchColors { if let downColor = self.downColor { self.displayView.fillColor = downColor } else { self.displayView.fillColor = self.color } if let downUnderColor = self.downUnderColor { self.underView?.fillColor = downUnderColor } else { self.underView?.fillColor = self.underColor } if let downBorderColor = self.downBorderColor { self.borderView?.strokeColor = downBorderColor } else { self.borderView?.strokeColor = self.borderColor } if let downTextColor = self.downTextColor { self.label.textColor = downTextColor self.popupLabel?.textColor = downTextColor self.shape?.color = downTextColor } else { self.label.textColor = self.textColor self.popupLabel?.textColor = self.textColor self.shape?.color = self.textColor } } else { self.displayView.fillColor = self.color self.underView?.fillColor = self.underColor self.borderView?.strokeColor = self.borderColor self.label.textColor = self.textColor self.popupLabel?.textColor = self.textColor self.shape?.color = self.textColor } if self.popup != nil { self.displayView.fillColor = self.popupColor } CATransaction.commit() } func layoutPopup(_ dir: Direction) { assert(self.popup != nil, "popup not found") if let popup = self.popup { if let delegate = self.delegate { let frame = delegate.frameForPopup(self, direction: dir) popup.frame = frame popupLabel?.frame = popup.bounds } else { popup.frame = CGRect.zero popup.center = self.center } } } func configurePopup(_ direction: Direction) { assert(self.popup != nil, "popup not found") self.background.attach(direction) self.popup!.attach(direction.opposite()) let kv = self.background let p = self.popup! self.connector?.removeFromSuperview() self.connector = KeyboardConnector(cornerRadius: 4, underOffset: self.underOffset, start: kv, end: p, startConnectable: kv, endConnectable: p, startDirection: direction, endDirection: direction.opposite()) self.connector!.layer.zPosition = -1 self.addSubview(self.connector!) // self.drawBorder = true if direction == Direction.up { // self.popup!.drawUnder = false // self.connector!.drawUnder = false } } func showPopup() { if self.popup == nil { self.layer.zPosition = 1000 let popup = KeyboardKeyBackground(cornerRadius: 9.0, underOffset: self.underOffset) self.popup = popup self.addSubview(popup) let popupLabel = UILabel() popupLabel.textAlignment = self.label.textAlignment popupLabel.baselineAdjustment = self.label.baselineAdjustment popupLabel.font = self.label.font.withSize(22 * 2) popupLabel.adjustsFontSizeToFitWidth = self.label.adjustsFontSizeToFitWidth popupLabel.minimumScaleFactor = CGFloat(0.1) popupLabel.isUserInteractionEnabled = false popupLabel.numberOfLines = 1 popupLabel.frame = popup.bounds popupLabel.text = self.label.text popup.addSubview(popupLabel) self.popupLabel = popupLabel self.label.isHidden = true } } func hidePopup() { if self.popup != nil { self.delegate?.willHidePopup(self) self.popupLabel?.removeFromSuperview() self.popupLabel = nil self.connector?.removeFromSuperview() self.connector = nil self.popup?.removeFromSuperview() self.popup = nil self.label.isHidden = false self.background.attach(nil) self.layer.zPosition = 0 self.popupDirection = nil } } } /* PERFORMANCE NOTES * CAShapeLayer: convenient and low memory usage, but chunky rotations * drawRect: fast, but high memory usage (looks like there's a backing store for each of the 3 views) * if I set CAShapeLayer to shouldRasterize, perf is *almost* the same as drawRect, while mem usage is the same as before * oddly, 3 CAShapeLayers show the same memory usage as 1 CAShapeLayer — where is the backing store? * might want to move to drawRect with combined draw calls for performance reasons — not clear yet */ class ShapeView: UIView { var shapeLayer: CAShapeLayer? //+roll let +20150421 override class var layerClass : AnyClass { return CAShapeLayer.self } var curve: UIBezierPath? { didSet { if let layer = self.shapeLayer { layer.path = curve?.cgPath } else { self.setNeedsDisplay() } } } var fillColor: UIColor? { didSet { if let layer = self.shapeLayer { layer.fillColor = fillColor?.cgColor } else { self.setNeedsDisplay() } } } var strokeColor: UIColor? { didSet { if let layer = self.shapeLayer { layer.strokeColor = strokeColor?.cgColor } else { self.setNeedsDisplay() } } } var lineWidth: CGFloat? { didSet { if let layer = self.shapeLayer { if let lineWidth = self.lineWidth { layer.lineWidth = lineWidth } } else { self.setNeedsDisplay() } } } convenience init() { self.init(frame: CGRect.zero) } override init(frame: CGRect) { super.init(frame: frame) if let myLayer = self.layer as? CAShapeLayer { self.shapeLayer = myLayer } // optimization: off by default to ensure quick mode transitions; re-enable during rotations //self.layer.shouldRasterize = true //self.layer.rasterizationScale = UIScreen.mainScreen().scale } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func drawCall(_ rect:CGRect) { if self.shapeLayer == nil { if let curve = self.curve { if let lineWidth = self.lineWidth { curve.lineWidth = lineWidth } if let fillColor = self.fillColor { fillColor.setFill() curve.fill() } if let strokeColor = self.strokeColor { strokeColor.setStroke() curve.stroke() } } } } // override func drawRect(rect: CGRect) { // if self.shapeLayer == nil { // self.drawCall(rect) // } // } }
gpl-2.0
f8c0ced80d65f3d4567342ae5fff9368
31.531624
213
0.559981
5.273206
false
false
false
false
Fahrni/YOURLSKit
YOURLSKit/YOURLSError.swift
1
1999
// // YOURLSError.swift // YOURLSKit // // Created by Rob Fahrni on 9/13/17. // Copyright © 2017 hayseed. All rights reserved. // import Foundation protocol YOURLSErrorProtocol: Error { var localizedTitle: String { get } var localizedDescription: String { get } var code: Int { get } } struct YOURLSError: YOURLSErrorProtocol { var localizedTitle: String var localizedDescription: String var code: Int init(urlResponse: URLResponse) { if let response = urlResponse as? HTTPURLResponse { self.localizedTitle = NSLocalizedString("Error", comment: "") self.localizedDescription = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) self.code = response.statusCode } else { self.localizedTitle = NSLocalizedString("Error", comment: "") self.localizedDescription = NSLocalizedString("A network error occured.", comment: "") self.code = -99 } } } /** Helper function to parse YOURLS return values for errors - parameter data: A Data value containing the results of a YOURLS stats call - returns: An instance of YOURLSStats or nil */ func errorFromData(_ data: Data) -> Error? { do { let result = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary guard let statusCode = result[YOURLSClient.Service.statusCode] as? Int, let message = result[YOURLSClient.Service.message] as? String else { NSLog("Parsing failed to get status code or message") return nil } let userInfo = ["message": message] let error = NSError(domain: YOURLSClient.Service.yourlsError, code: statusCode, userInfo: userInfo) return error } catch let error as NSError { NSLog("Parsing stats data object failed: \(error)") return nil } } func errorFromResponse(urlResponse: URLResponse) { }
mit
1e2d177150758a97bfc23fa64359a57b
32.3
140
0.67017
4.646512
false
false
false
false
renxlWin/gege
swiftChuge/Pods/RealmSwift/RealmSwift/ThreadSafeReference.swift
33
5078
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Realm /** Objects of types which conform to `ThreadConfined` can be managed by a Realm, which will make them bound to a thread-specific `Realm` instance. Managed objects must be explicitly exported and imported to be passed between threads. Managed instances of objects conforming to this protocol can be converted to a thread-safe reference for transport between threads by passing to the `ThreadSafeReference(to:)` constructor. Note that only types defined by Realm can meaningfully conform to this protocol, and defining new classes which attempt to conform to it will not make them work with `ThreadSafeReference`. */ public protocol ThreadConfined { // Must also conform to `AssistedObjectiveCBridgeable` /** The Realm which manages the object, or `nil` if the object is unmanaged. Unmanaged objects are not confined to a thread and cannot be passed to methods expecting a `ThreadConfined` object. */ var realm: Realm? { get } /// Indicates if the object can no longer be accessed because it is now invalid. var isInvalidated: Bool { get } } /** An object intended to be passed between threads containing a thread-safe reference to its thread-confined object. To resolve a thread-safe reference on a target Realm on a different thread, pass to `Realm.resolve(_:)`. - warning: A `ThreadSafeReference` object must be resolved at most once. Failing to resolve a `ThreadSafeReference` will result in the source version of the Realm being pinned until the reference is deallocated. - note: Prefer short-lived `ThreadSafeReference`s as the data for the version of the source Realm will be retained until all references have been resolved or deallocated. - see: `ThreadConfined` - see: `Realm.resolve(_:)` */ public class ThreadSafeReference<Confined: ThreadConfined> { private let swiftMetadata: Any? private let type: ThreadConfined.Type /** Indicates if the reference can no longer be resolved because an attempt to resolve it has already occurred. References can only be resolved once. */ public var isInvalidated: Bool { return objectiveCReference.isInvalidated } private let objectiveCReference: RLMThreadSafeReference<RLMThreadConfined> /** Create a thread-safe reference to the thread-confined object. - parameter threadConfined: The thread-confined object to create a thread-safe reference to. - note: You may continue to use and access the thread-confined object after passing it to this constructor. */ public init(to threadConfined: Confined) { let bridged = (threadConfined as! AssistedObjectiveCBridgeable).bridged swiftMetadata = bridged.metadata type = type(of: threadConfined) objectiveCReference = RLMThreadSafeReference(threadConfined: bridged.objectiveCValue as! RLMThreadConfined) } internal func resolve(in realm: Realm) -> Confined? { guard let objectiveCValue = realm.rlmRealm.__resolve(objectiveCReference) else { return nil } return ((Confined.self as! AssistedObjectiveCBridgeable.Type).bridging(from: objectiveCValue, with: swiftMetadata) as! Confined) } } extension Realm { /** Returns the same object as the one referenced when the `ThreadSafeReference` was first created, but resolved for the current Realm for this thread. Returns `nil` if this object was deleted after the reference was created. - parameter reference: The thread-safe reference to the thread-confined object to resolve in this Realm. - warning: A `ThreadSafeReference` object must be resolved at most once. Failing to resolve a `ThreadSafeReference` will result in the source version of the Realm being pinned until the reference is deallocated. An exception will be thrown if a reference is resolved more than once. - warning: Cannot call within a write transaction. - note: Will refresh this Realm if the source Realm was at a later version than this one. - see: `ThreadSafeReference(to:)` */ public func resolve<Confined: ThreadConfined>(_ reference: ThreadSafeReference<Confined>) -> Confined? { return reference.resolve(in: self) } }
mit
8f592da15a25298017514a766fa00877
41.316667
136
0.704805
4.944499
false
false
false
false
panadaW/MyNews
MyWb/MyWb/Class/Controllers/Home/HomeCell/topView.swift
1
2985
// // topView.swift // MyWb // // Created by 王明申 on 15/10/13. // Copyright © 2015年 晨曦的Mac. All rights reserved. // import UIKit import SDWebImage class topView: UIView { var status: Status? { didSet { if let url = status?.user?.imageURL { iconView.sd_setImageWithURL(url) } nameLabel.text = status?.user?.name ?? "" vipIconView.image = status?.user?.vipImage memberIconView.image = status?.user?.memberImage timeLabel.text = "未来" sourceLabel.text = "来自申哥微博.com" } } override init(frame: CGRect) { super.init(frame: frame) // backgroundColor = UIColor.clearColor() setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUpUI() { let sepView = UIView() sepView.backgroundColor = UIColor(white: 0.8, alpha: 1.0) addSubview(sepView) sepView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 10)) // 1. 添加控件 addSubview(iconView) addSubview(nameLabel) addSubview(timeLabel) addSubview(sourceLabel) addSubview(memberIconView) addSubview(vipIconView) // 2. 设置布局 iconView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: sepView, size: CGSize(width: 35, height: 35), offset: CGPoint(x: 8, y: 8)) // nameLabel.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0)) timeLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0)) sourceLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0)) memberIconView.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0)) vipIconView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8)) } // MARK: - 懒加载控件 // 1. 头像图标 private lazy var iconView: UIImageView = UIImageView() // 2. 姓名 private lazy var nameLabel: UILabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14) // 3. 时间标签 private lazy var timeLabel: UILabel = UILabel(color: UIColor.orangeColor(), fontSize: 9) // 4. 来源标签 private lazy var sourceLabel: UILabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 9) // 5. 会员图标 private lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1")) // 6. vip图标 private lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_vip")) }
mit
5ee12613fdd6dcba20a4f36a8f8fc916
39.676056
150
0.642659
3.994467
false
false
false
false
HabitRPG/habitrpg-ios
Habitica API Client/Habitica API Client/Base/StubHolder.swift
1
962
// // StubHolder.swift // Pods // // Created by Elliot Schrock on 9/15/17. // // import Foundation public protocol StubHolderProtocol { var responseCode: Int32 { get } var stubFileName: String? { get } var bundle: Bundle { get } var stubData: Data? { get } var responseHeaders: [String: String] { get } } open class StubHolder: StubHolderProtocol { public let responseCode: Int32 public let stubFileName: String? public let bundle: Bundle public let stubData: Data? public let responseHeaders: [String: String] public init(responseCode: Int32 = 200, stubFileName: String? = nil, stubData: Data? = nil, responseHeaders: [String: String] = ["Content-type": "application/json"], bundle: Bundle = Bundle.main) { self.responseCode = responseCode self.stubFileName = stubFileName self.bundle = bundle self.stubData = stubData self.responseHeaders = responseHeaders } }
gpl-3.0
5fad478e6fb2e86de4f4a2296d40e4f5
28.151515
200
0.672557
4.111111
false
false
false
false
dwestgate/AdScrubber
AdScrubber/StreamReader.swift
1
3807
// // StreamReader.swift // AdScrubber // // Created by David Westgate on 12/31/15. // Copyright © 2016 David Westgate // // 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 // // From: http://stackoverflow.com/questions/24581517/read-a-file-url-line-by-line-in-swift // import Foundation class StreamReader { let encoding : UInt let chunkSize : Int var fileHandle : FileHandle! let buffer : NSMutableData! let delimData : Data! var atEof : Bool = false init?(path: String, delimiter: String = "\n", encoding : UInt = String.Encoding.utf8, chunkSize : Int = 4096) { self.chunkSize = chunkSize self.encoding = encoding if let fileHandle = FileHandle(forReadingAtPath: path), let delimData = delimiter.data(using: String.Encoding(rawValue: encoding)), let buffer = NSMutableData(capacity: chunkSize) { self.fileHandle = fileHandle self.delimData = delimData self.buffer = buffer } else { self.fileHandle = nil self.delimData = nil self.buffer = nil return nil } } deinit { self.close() } /// Return next line, or nil on EOF. func nextLine() -> String? { precondition(fileHandle != nil, "Attempt to read from closed file") if atEof { return nil } // Read data chunks from file until a line delimiter is found: var range = buffer.range(of: delimData, options: [], in: NSMakeRange(0, buffer.length)) while range.location == NSNotFound { let tmpData = fileHandle.readData(ofLength: chunkSize) if tmpData.count == 0 { // EOF or read error. atEof = true if buffer.length > 0 { // Buffer contains last line in file (not terminated by delimiter). let line = NSString(data: buffer as Data, encoding: encoding) buffer.length = 0 return line as String? } // No more lines. return nil } buffer.append(tmpData) range = buffer.range(of: delimData, options: [], in: NSMakeRange(0, buffer.length)) } // Convert complete line (excluding the delimiter) to a string: let line = NSString(data: buffer.subdata(with: NSMakeRange(0, range.location)), encoding: encoding) // Remove line (and the delimiter) from the buffer: buffer.replaceBytes(in: NSMakeRange(0, range.location + range.length), withBytes: nil, length: 0) return line as String? } /// Start reading from the beginning of file. func rewind() -> Void { fileHandle.seek(toFileOffset: 0) buffer.length = 0 atEof = false } /// Close the underlying file. No reading must be done after calling this method. func close() -> Void { fileHandle?.closeFile() fileHandle = nil } }
mit
7a1c9f1faf3fa92ad87529ca4dbf3201
32.681416
113
0.671834
4.295711
false
false
false
false
PuzzleboxIO/orbit-ios
Orbit/Orbit/SynapseManager.swift
1
11995
// // SynapseManager.swift // Orbit // // Created by Steve Castellotti on 9/20/16. // Copyright © 2016 Puzzlebox. All rights reserved. // import Foundation // private let enableSDKLog: Bool = true private let enableSDKLog: Bool = false protocol SynapseDelegate { func updateData() func updateStatus() func updateDevices() func updateDeviceConnection(connected:Bool) } class SynapseManager: NSObject, TGStreamDelegate, MWMDeviceDelegate, TGBleManagerDelegate { var synapseDelegate: SynapseDelegate? // Stream SDK let tgStream:TGStream = TGStream.sharedInstance() var tgConnectionState: ConnectionStates = .STATE_DISCONNECTED // MWM SDK let mDevice:MWMDevice = MWMDevice.sharedInstance() let nTGBleManager:TGBleManager = TGBleManager.sharedTGBleManager(DeviceType.MWM) var devicesArray:[String] = [] var rssiArray:[NSNumber] = [] var devNameArray:[String] = [] var mfgIDArray:[String] = [] // Local var attentionLevel: Int = 0 var meditationLevel: Int = 0 var signalLevel: Int = 0 var powerLevel: Int = 0 // var targetAttention:Float = 0.72 // var targetMeditation:Float = 0.0 var targetAttention:Int = 72 var targetMeditation:Int = 0 // MARK: Shared Instance static let sharedInstance : SynapseManager = { let instance = SynapseManager() return instance }() // MARK: Local Variable var emptyStringArray : [String]? = nil // MARK: Init // private convenience override init() { // print("INFO [SynapseManager]: private convenience override init()") // self.init(array : []) // } // // // MARK: Init Array // // // init( array : [String]) { // private init( array : [String]) { // print("INFO [SynapseManager]: private init( array : [String])") // emptyStringArray = array // // // StreamSDK Delegate // super.init() // self.init() private override init() { super.init() // StreamSDK Delegate tgStream.delegate = self tgStream.enableLog(enableSDKLog) print("INFO [SynapseManager]: Stream SDK version: \(tgStream.getVersion())") // MWM SDK Delegate mDevice.delegate = self // nTGBleManager.enableLogging() // enable enhanced log messages nTGBleManager.setupManager(true) // manualMode enabled nTGBleManager.stopLogging() // disable enhanced log messages nTGBleManager.delegate = self } func test(command: String) { print("INFO [SynapseManager]: test: \(command)") } func updatePowerTargets(attention: Float, meditation: Float) { targetAttention = Int(attention * 100) targetMeditation = Int(meditation * 100) } func updatePowerLevel() { var powerLevel:Int = 0 if (attentionLevel >= targetAttention) && (targetAttention > 0) { powerLevel += attentionLevel } if (meditationLevel >= targetMeditation) && (targetMeditation > 0) { powerLevel += meditationLevel } if powerLevel > 100 { powerLevel = 100 } self.powerLevel = powerLevel print("INFO [updatePowerLevel]: powerLevel: \(powerLevel)") ControlSignalManager.sharedInstance.updatePower(powerLevel: powerLevel) } func connectSynapse() { print("INFO [SynapseManager]: connectSynapse()") resetDevices() switch tgConnectionState { case .STATE_INIT: connectToThinkGearDevice() case .STATE_CONNECTING: break case .STATE_CONNECTED: connectToThinkGearDevice() case .STATE_WORKING: disconnectFromThinkGearDevice() case .STATE_STOPPED: connectToThinkGearDevice() case .STATE_DISCONNECTED: connectToThinkGearDevice() case .STATE_COMPLETE: connectToThinkGearDevice() case .STATE_RECORDING_START: disconnectFromThinkGearDevice() case .STATE_RECORDING_END: disconnectFromThinkGearDevice() case .STATE_FAILED: connectToThinkGearDevice() case .STATE_ERROR: connectToThinkGearDevice() } } func connectToMindWaveMobilePlus() { print ("INFO [SynapseManager]: connectToMindWaveMobilePlus()") let nameList = ["SEAGULL", "Seagull", "WAT Phase 2", "SG DEV", "Pelican", "MindWave Mobile"] nTGBleManager.candidateScan(nameList) } //} // //// MARK: ThinkGear accessory delegate //extension SynapseManager: NSObject, TGStreamDelegate { func onDataReceived(_ datatype: Int, data: Int32, obj: NSObject!, deviceType: DEVICE_TYPE) { // print("INFO [SynapseManager]: onDataReceived") switch datatype { case Int(MindDataType.CODE_POOR_SIGNAL.rawValue): print("INFO [SynapseManager]: onDataReceived: datatype: CODE_POOR_SIGNAL: \(data)") signalLevel = Int(data) if (signalLevel == 0) { signalLevel = 100 } else { if (signalLevel >= 200) { signalLevel = 0 // } else { // signalLevel = 100 - signalLevel } } case Int(MindDataType.CODE_ATTENTION.rawValue): print("INFO [SynapseManager]: onDataReceived: datatype: CODE_ATTENTION: \(data)") attentionLevel = Int(data) case Int(MindDataType.CODE_MEDITATION.rawValue): print("INFO [SynapseManager]: onDataReceived: datatype: CODE_MEDITATION: \(data)") meditationLevel = Int(data) updatePowerLevel() // Update delegates when Meditation value received because it always seems to be issued last from ThinkGear Stream synapseDelegate?.updateData() case Int(MindDataType.CODE_EEGPOWER.rawValue): break case Int(MindDataType.CODE_RAW.rawValue): break default: break } } func onStatesChanged(_ connectionState: ConnectionStates) { print("INFO [SynapseManager]: onStatesChanged") self.tgConnectionState = connectionState switch connectionState { case .STATE_INIT: print("INFO [SynapseManager]: 0 - STATE_INIT") case .STATE_CONNECTING: print("INFO [SynapseManager]: 1 - STATE_CONNECTING") case .STATE_CONNECTED: print("INFO [SynapseManager]: 2 - STATE_CONNECTED") // This will be reached when a legacy MindWave Mobile auto-connects via Bluetooth case .STATE_WORKING: print("INFO [SynapseManager]: 3 - STATE_WORKING") case .STATE_STOPPED: print("INFO [SynapseManager]: 4 - STATE_STOPPED") ControlSignalManager.sharedInstance.stopControlSignal() case .STATE_DISCONNECTED: print("INFO [SynapseManager]: 5 - STATE_DISCONNECTED") ControlSignalManager.sharedInstance.stopControlSignal() case .STATE_COMPLETE: print("INFO [SynapseManager]: 6 - STATE_COMPLETE") case .STATE_RECORDING_START: print("INFO [SynapseManager]: 7 - STATE_RECORDING_START") case .STATE_RECORDING_END: print("INFO [SynapseManager]: 8 - STATE_RECORDING_END") case .STATE_FAILED: print("INFO [SynapseManager]: 100 - STATE_FAILED") case .STATE_ERROR: print("INFO [SynapseManager]: 101 - STATE_ERROR") connectToMindWaveMobilePlus() disconnectFromThinkGearDevice() ControlSignalManager.sharedInstance.stopControlSignal() // print("WARN [FlightViewController]: Re-initializing ThinkGear Stream") // tgStream = TGStream.init() } synapseDelegate?.updateStatus() } func connectToThinkGearDevice() { print("INFO [SynapseManager]: Connecting to ThinkGear device") // tgStream.tearDownAccessorySession() tgStream.initConnectWithAccessorySession() // updateStatusImage(status: STATUS_CONNECTING) // // // let filePath:String = Bundle.main.path(forResource: "sample_data", ofType: "txt")! // // tgStream.initConnect(withFile: filePath) } func disconnectFromThinkGearDevice() { print("INFO [SynapseManager]: Disconnecting from ThinkGear device") tgStream.tearDownAccessorySession() // mDevice.teardownManager() TODO // updateStatusImage(status: STATUS_DEFAULT) // resetViews() // // tgStream.initConnectWithAccessorySession() } // MARK: MWM SDK delegate func eegStarting(_ time: Date!, sampleRate: Int32, realTime rt: Bool, comment: String!) { print("INFO [SynapseManager]: eegStarting: time: \(time) sampleRate: \(sampleRate) realTime: \(rt) comment: \(comment)") } func eegStop(_ result: TGeegResult) { var message:String if (result == TGeegResult.terminatedNormally) { message = "EEG Recording Ended Normally" } else if (result == TGeegResult.terminatedNoData) { message = "No Data Received, Try Again, You must touch the Sensor" } else if (result == TGeegResult.terminatedDataStopped) { message = "Data Stopped, you must maintain contact with the finger Sensor" } else if (result == TGeegResult.terminatedLostConnection) { message = "BLE Connection has been lost" } else { message = "Unexpected result, code: \(result)" } print("INFO [SynapseManager]: eegStop: \(message)") } func eegPowerLowBeta(_ lowBeta: Int32, highBeta: Int32, lowGamma: Int32, midGamma: Int32) { print("INFO [SynapseManager]: eegPowerLowBeta(): lowBeta: \(lowBeta) highBeta: \(highBeta) lowGamma: \(lowGamma) midGamma: \(midGamma)") } func eegPowerDelta(_ delta: Int32, theta: Int32, lowAlpha lowAplpha: Int32, highAlpha: Int32) { print("INFO [SynapseManager]: eegPowerDelta(): \(delta) theta: \(theta) lowAlpha: \(lowAplpha) highAlpha: \(highAlpha)") } func eSense(_ poorSignal: Int32, attention: Int32, meditation: Int32) { print("INFO [SynapseManager]: eSense(): poorSignal: \(eSense) attention: \(attention) meditation: \(meditation)") signalLevel = Int(poorSignal) if (signalLevel == 0) { signalLevel = 100 } else { if (signalLevel >= 200) { signalLevel = 0 } } attentionLevel = Int(attention) meditationLevel = Int(meditation) updatePowerLevel() synapseDelegate?.updateData() } func mwmBaudRate(_ baudRate: Int32, notchFilter: Int32) { print("INFO [SynapseManager]: mwmBaudRate(): baudRate: \(baudRate) notchFilter: \(notchFilter)") } func candidateFound(_ devName: String!, rssi: NSNumber!, mfgID: String!, candidateID: String!) { // print("INFO [SynapseManager]: candidateFound(): devName: \(devName) rssi: \(rssi) mfgID: \(mfgID) rssi: \(rssi)") if mfgID == nil || mfgID == "" { return } if !(devicesArray.contains(candidateID)) { print("INFO [SynapseManager]: candidateFound(): devName: \(devName) rssi: \(rssi) mfgID: \(mfgID) rssi: \(rssi)") devicesArray.append(candidateID) rssiArray.append(rssi) devNameArray.append(devName) mfgIDArray.append(mfgID) synapseDelegate?.updateDevices() } } func bleDidConnect() { print("INFO [SynapseManager]: bleDidConnect()") mDevice.tryStartESense() synapseDelegate?.updateDeviceConnection(connected: true) } func bleDidDisconnect() { print("INFO [SynapseManager]: bleDidDisconnect()") ControlSignalManager.sharedInstance.stopControlSignal() mDevice.tryStopESense() synapseDelegate?.updateDeviceConnection(connected: false) } func bleLostConnect() { print("INFO [SynapseManager]: bleLostConnect()") ControlSignalManager.sharedInstance.stopControlSignal() mDevice.tryStopESense() synapseDelegate?.updateDeviceConnection(connected: false) } func exceptionMessage(_ eventType: TGBleExceptionEvent) { var message:String = "" if (eventType == TGBleExceptionEvent.configurationModeCanNotBeChanged) { message = "Exception Message - Ble Connection Mode CAN NOT be changed" } else if (eventType == TGBleExceptionEvent.failedOtherOperationInProgress) { message = "Exception Message - Another Operation is Already in Progress" } else if (eventType == TGBleExceptionEvent.connectFailedSuspectKeyMismatch) { message = "Exception Message - Device appears to be paired, possible encryption key mismatch, hold side button for 10 seconds to reboot" } else if (eventType == TGBleExceptionEvent.storedConnectionInvalid) //stored connection { // [self onSCandidateClicked:nil]; message = "Exception Detected, code: \(eventType)" } else { message = "Exception Detected, code: \(eventType)" } print("INFO [SynapseManager]: exceptionMessage(): \(message)") } func resetDevices() { print("INFO [SynapseManager]: resetDevices()") devicesArray = [] rssiArray = [] devNameArray = [] mfgIDArray = [] } }
agpl-3.0
a253ffe09dd73c1cfa04c6a44cfa3511
27.69378
139
0.705353
3.363432
false
false
false
false
naoty/qiita-swift
Qiita/Qiita.swift
1
8291
// // Qiita.swift // Qiita // // Created by Naoto Kaneko on 2014/12/11. // Copyright (c) 2014年 Naoto Kaneko. All rights reserved. // public struct Qiita { public class Client { let accessToken: String let session: NSURLSession let baseURLString: String public init(accessToken: String, baseURLString: String = "http://qiita.com/api/v2") { self.accessToken = accessToken self.session = NSURLSession.sharedSession() self.baseURLString = baseURLString } // MARK: - Items public func getItems(parameters: [String:String] = [:]) -> Request<[Item]> { let request = Request<[Item]>() let url = buildURL("/items", parameters: parameters) request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObjects = json as? NSArray { var items: [Item] = [] for jsonObject: AnyObject in jsonObjects { if let item = Item(json: jsonObject) { items.append(item) } } request.resolve(items) } }) return request } public func getItem(id: String, parameters: [String:String] = [:]) -> Request<Item> { let request = Request<Item>() let url = buildURL("/items/\(id)", parameters: parameters) request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObject: AnyObject = json { if let item = Item(json: jsonObject) { request.resolve(item) } } }) return request } public func getUserItems(userID: String, parameters: [String:String] = [:]) -> Request<[Item]> { let request = Request<[Item]>() let url = buildURL("/users/\(userID)/items", parameters: parameters) request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObjects = json as? NSArray { var items: [Item] = [] for jsonObject: AnyObject in jsonObjects { if let item = Item(json: jsonObject) { items.append(item) } } request.resolve(items) } }) return request } public func getUserStocks(userID: String, parameters: [String:String] = [:]) -> Request<[Item]> { let request = Request<[Item]>() let url = buildURL("/users/\(userID)/stocks", parameters: parameters) request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObjects = json as? NSArray { var items: [Item] = [] for jsonObject: AnyObject in jsonObjects { if let item = Item(json: jsonObject) { items.append(item) } } request.resolve(items) } }) return request } // MARK: - Users public func getUsers(parameters: [String:String] = [:]) -> Request<[User]> { let request = Request<[User]>() let url = buildURL("/users", parameters: parameters) request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObjects = json as? NSArray { var users: [User] = [] for jsonObject: AnyObject in jsonObjects { if let user = User(json: jsonObject) { users.append(user) } } request.resolve(users) } }) return request } public func getUser(id: String, parameters: [String:String] = [:]) -> Request<User> { let request = Request<User>() let url = buildURL("/users/\(id)", parameters: parameters) request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObject: AnyObject = json { if let user = User(json: jsonObject) { request.resolve(user) } } }) return request } public func getAuthenticatedUser() -> Request<User> { let request = Request<User>() let url = buildURL("/authenticated_user") request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObject: AnyObject = json { if let user = User(json: jsonObject) { request.resolve(user) } } }) return request } public func getFollowees(id: String, parameters: [String:String] = [:]) -> Request<[User]> { let request = Request<[User]>() let url = buildURL("/users/\(id)/followees", parameters: parameters) request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObjects = json as? NSArray { var users: [User] = [] for jsonObject: AnyObject in jsonObjects { if let user = User(json: jsonObject) { users.append(user) } } request.resolve(users) } }) return request } public func getFollowers(id: String, parameters: [String:String] = [:]) -> Request<[User]> { let request = Request<[User]>() let url = buildURL("/users/\(id)/followers", parameters: parameters) request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObjects = json as? NSArray { var users: [User] = [] for jsonObject: AnyObject in jsonObjects { if let user = User(json: jsonObject) { users.append(user) } } request.resolve(users) } }) return request } public func getItemStockers(itemID: String, parameters: [String:String] = [:]) -> Request<[User]> { let request = Request<[User]>() let url = buildURL("/items/\(itemID)/stockers", parameters: parameters) request.setDataTaskWithSession(session, url: url, completionHandler: { json in if let jsonObjects = json as? NSArray { var users: [User] = [] for jsonObject: AnyObject in jsonObjects { if let user = User(json: jsonObject) { users.append(user) } } request.resolve(users) } }) return request } // MARK: - Private methods private func buildURL(URLString: String, baseURLString: String? = nil, parameters: [String:String] = [:]) -> NSURL { let fullURLString = (baseURLString ?? self.baseURLString) + URLString + buildQuery(parameters) return NSURL(string: fullURLString)! } private func buildQuery(parameters: [String:String]) -> String { if parameters.count == 0 { return "" } var components: [String] = [] for (key, value) in parameters { let component = "=".join([key, value]) components.append(component) } return "?" + "&".join(components) } } }
mit
74d5444f7afb4709a94fb313af55c136
39.837438
124
0.476776
5.474901
false
false
false
false
onevcat/Kingfisher
Sources/Image/Placeholder.swift
7
3402
// // Placeholder.swift // Kingfisher // // Created by Tieme van Veen on 28/08/2017. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !os(watchOS) #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit #endif #if canImport(UIKit) import UIKit #endif /// Represents a placeholder type which could be set while loading as well as /// loading finished without getting an image. public protocol Placeholder { /// How the placeholder should be added to a given image view. func add(to imageView: KFCrossPlatformImageView) /// How the placeholder should be removed from a given image view. func remove(from imageView: KFCrossPlatformImageView) } /// Default implementation of an image placeholder. The image will be set or /// reset directly for `image` property of the image view. extension KFCrossPlatformImage: Placeholder { /// How the placeholder should be added to a given image view. public func add(to imageView: KFCrossPlatformImageView) { imageView.image = self } /// How the placeholder should be removed from a given image view. public func remove(from imageView: KFCrossPlatformImageView) { imageView.image = nil } } /// Default implementation of an arbitrary view as placeholder. The view will be /// added as a subview when adding and be removed from its super view when removing. /// /// To use your customize View type as placeholder, simply let it conforming to /// `Placeholder` by `extension MyView: Placeholder {}`. extension Placeholder where Self: KFCrossPlatformView { /// How the placeholder should be added to a given image view. public func add(to imageView: KFCrossPlatformImageView) { imageView.addSubview(self) translatesAutoresizingMaskIntoConstraints = false centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true centerYAnchor.constraint(equalTo: imageView.centerYAnchor).isActive = true heightAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true widthAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true } /// How the placeholder should be removed from a given image view. public func remove(from imageView: KFCrossPlatformImageView) { removeFromSuperview() } } #endif
mit
78a7eb3d1fec6d9220340518d6ce9eae
40.487805
90
0.74368
4.673077
false
false
false
false
tomomura/TimeSheet
Classes/Utilities/NSDate+DayToTime.swift
1
2005
extension NSDate { enum Week :Int { case Sunday = 1 case Monday = 2 case Tuesday = 3 case Wednesday = 4 case Thursday = 5 case Friday = 6 case Saturday = 7 func name() -> String { switch self { case .Sunday: return "日" case .Monday: return "月" case .Tuesday: return "火" case .Wednesday: return "水" case .Thursday: return "木" case .Friday: return "金" case .Saturday: return "土" } } func color() -> UIColor { switch self { case .Sunday: return UIColor.flatAlizarinColor() case .Saturday: return UIColor.flatPeterRiverColor() default: return UIColor.flatCloudsColor() } } } func timeHuman() -> String? { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" return dateFormatter.stringFromDate(self) } func timeIntervalSinceDateWithRound(date: NSDate) -> Double! { let interval : NSTimeInterval = self.timeIntervalSinceDate(date) return Double(interval / 10 * 10) } func timeIntervalSinceDateHuman(date: NSDate) -> String! { let interval : Double = self.timeIntervalSinceDateWithRound(date) if (interval > 0) { let formatter = NSDateComponentsFormatter() formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Positional formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehavior.allZeros formatter.allowedUnits = NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute return formatter.stringFromTimeInterval(interval) } else { return "0:00" } } func week() -> Week { return Week(rawValue: self.weekday)! } }
mit
059fc5ad16b88d47a6d2ca8445a13407
30.619048
104
0.567554
5.323529
false
false
false
false
chinesemanbobo/PPDemo
Pods/Down/Source/AST/Styling/Helpers/Extensions/UIFont+Traits.swift
3
2169
// // UIFont+Traits.swift // Down // // Created by John Nguyen on 22.06.19. // Copyright © 2016-2019 Down. All rights reserved. // #if !os(watchOS) && !os(Linux) #if canImport(UIKit) import UIKit public typealias DownFontDescriptor = UIFontDescriptor #elseif canImport(AppKit) import AppKit public typealias DownFontDescriptor = NSFontDescriptor #endif extension DownFont { var isStrong: Bool { return contains(.strong) } var isEmphasized: Bool { return contains(.emphasis) } var isMonospace: Bool { return contains(.monoSpace) } var strong: DownFont { return with(.strong) ?? self } var emphasis: DownFont { return with(.emphasis) ?? self } var monospace: DownFont { return with(.monoSpace) ?? self } private func with(_ trait: DownFontDescriptor.SymbolicTraits) -> DownFont? { guard !contains(trait) else { return self } var traits = fontDescriptor.symbolicTraits traits.insert(trait) #if canImport(UIKit) guard let newDescriptor = fontDescriptor.withSymbolicTraits(traits) else { return self } return DownFont(descriptor: newDescriptor, size: pointSize) #elseif canImport(AppKit) let newDescriptor = fontDescriptor.withSymbolicTraits(traits) return DownFont(descriptor: newDescriptor, size: pointSize) #endif } private func contains(_ trait: DownFontDescriptor.SymbolicTraits) -> Bool { return fontDescriptor.symbolicTraits.contains(trait) } } #if canImport(UIKit) private extension DownFontDescriptor.SymbolicTraits { static let strong = DownFontDescriptor.SymbolicTraits.traitBold static let emphasis = DownFontDescriptor.SymbolicTraits.traitItalic static let monoSpace = DownFontDescriptor.SymbolicTraits.traitMonoSpace } #elseif canImport(AppKit) private extension DownFontDescriptor.SymbolicTraits { static let strong = DownFontDescriptor.SymbolicTraits.bold static let emphasis = DownFontDescriptor.SymbolicTraits.italic static let monoSpace = DownFontDescriptor.SymbolicTraits.monoSpace } #endif #endif
mit
8c51030f0a90392ef4b443bc2be9ee89
22.824176
96
0.706642
4.58351
false
false
false
false
sajeel/AutoScout
AutoScout/Assembly/CarsAssembly.swift
1
855
// // CarsAssembly.swift // AutoScout // // Created by Sajjeel Khilji on 5/21/17. // Copyright © 2017 Saj. All rights reserved. // import Foundation import UIKit class CarsAssembly { fileprivate static let mainControllerIdentifier:String = "MainViewControllerID" func createViewController() -> MainViewController { let backEndAPI = AutoScoutAPI(queue: OperationQueue()) let carsViewModel = CarsViewModel(backEndAPI: backEndAPI) let favsViewModel = FavViewModel() let mainController: MainViewController = Utils.controllerFromMainStoryBoardWithId(controllerId: CarsAssembly.mainControllerIdentifier) as! MainViewController mainController.setViewModels(carsViewModel: carsViewModel, favsViewModel: favsViewModel) return mainController } }
gpl-3.0
cfb3a8bc4bc85747dc6c110edcbc5c04
26.548387
165
0.709602
4.88
false
false
false
false
vector-im/riot-ios
Riot/Modules/Common/Buttons/Close/RoundedButton.swift
1
2227
/* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 final class RoundedButton: UIButton, Themable { // MARK: - Constants private enum Constants { static let backgroundColorAlpha: CGFloat = 0.2 static let cornerRadius: CGFloat = 6.0 static let fontSize: CGFloat = 17.0 } // MARK: - Properties // MARK: Private private var theme: Theme? // MARK: Public var actionStyle: UIAlertAction.Style = .default { didSet { self.updateButtonStyle() } } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() self.layer.masksToBounds = true self.titleLabel?.font = UIFont.systemFont(ofSize: Constants.fontSize) self.update(theme: ThemeService.shared().theme) } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = Constants.cornerRadius } // MARK: - Private private func updateButtonStyle() { guard let theme = theme else { return } let backgroundColor: UIColor switch self.actionStyle { case .default: backgroundColor = theme.tintColor default: backgroundColor = theme.noticeColor } self.vc_setBackgroundColor(backgroundColor.withAlphaComponent(Constants.backgroundColorAlpha), for: .normal) self.setTitleColor(backgroundColor, for: .normal) } // MARK: - Themable func update(theme: Theme) { self.theme = theme self.updateButtonStyle() } }
apache-2.0
60924064e0373a0e53cf432ebddc0395
25.2
116
0.626852
5.084475
false
false
false
false
boyXiong/XWSwiftRefresh
XWSwiftRefresh/Header/XWRefreshNormalHeader.swift
7
4572
// // XWRefreshNormalHeader.swift // XWSwiftRefresh // // Created by Xiong Wei on 15/10/5. // Copyright © 2015年 Xiong Wei. All rights reserved. // 简书:猫爪 import UIKit /** headerView 带有状态和指示图片*/ public class XWRefreshNormalHeader: XWRefreshStateHeader { //MARK: 外界接口 /** 菊花样式 */ public var activityIndicatorViewStyle:UIActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray { didSet{ self.activityView.activityIndicatorViewStyle = activityIndicatorViewStyle self.setNeedsLayout() } } /** 指示器的图片[箭头] */ public var arrowImage:UIImage? { didSet{ self.arrowView.image = arrowImage self.placeSubvies() } } //MARK: lazy //图片 /** 指示图片 */ lazy var arrowView:UIImageView = { [unowned self] in var image = UIImage(named:XWIconSrcPath) if image == nil { image = UIImage(named: XWIconLocalPath) } let imageView = UIImageView(image: image) self.addSubview(imageView) return imageView }() //菊花 private lazy var activityView:UIActivityIndicatorView = { [unowned self] in let activityView = UIActivityIndicatorView(activityIndicatorStyle: self.activityIndicatorViewStyle) activityView.bounds = self.arrowView.bounds self.addSubview(activityView) return activityView }() //MARK: 重写父类方法 override func placeSubvies() { super.placeSubvies() //箭头 self.arrowView.xw_size = (self.arrowView.image?.size)! var arrowCenterX = self.xw_width * 0.5 if !self.stateLabel.hidden { arrowCenterX -= 100 } let arrowCenterY = self.xw_height * 0.5 self.arrowView.center = CGPointMake(arrowCenterX, arrowCenterY) //菊花 self.activityView.frame = self.arrowView.frame } //从写观察者属性 /** 辅助记录 旧值 */ private var oldState:XWRefreshState! override var state:XWRefreshState{ didSet{ self.oldState = oldValue if state == oldValue {return} self.switchStateDoSomething(state) } } private func switchStateDoSomething(state:XWRefreshState){ func commonFun(){ self.activityView.stopAnimating() self.arrowView.hidden = false } //4.判断当前的状态 switch state { //4.1如果是刷新状态 case .Idle : //4.1.1 旧值等于 真正刷新的状态 if self.oldState == XWRefreshState.Refreshing { self.arrowView.transform = CGAffineTransformIdentity UIView.animateWithDuration(XWRefreshSlowAnimationDuration, animations: { () -> Void in self.activityView.alpha = 0.0 }, completion: { (flag) -> Void in // 如果执行完动画发现不是idle状态,就直接返回,进入其他状态 if self.state != XWRefreshState.Idle { return } self.activityView.alpha = 1.0 commonFun() }) //4.1.2 不然就反正之前的 }else{ commonFun() UIView.animateWithDuration(XWRefreshSlowAnimationDuration, animations: { () -> Void in self.arrowView.transform = CGAffineTransformIdentity }) } //如果在下拉 case .Pulling: commonFun() UIView.animateWithDuration(XWRefreshSlowAnimationDuration, animations: { () -> Void in let tmp:CGFloat = 0.000001 - CGFloat(M_PI) self.arrowView.transform = CGAffineTransformMakeRotation(tmp); }) case .Refreshing: self.arrowView.hidden = true self.activityView.alpha = 1.0 // 防止refreshing -> idle的动画完毕动作没有被执行 self.activityView.startAnimating() default: break } } }
mit
a2e952dadf4d2d8ae25b4cccc14fbb48
27.045752
108
0.525985
5.151261
false
false
false
false
instacrate/tapcrate-api
Sources/api/Stripe/Models/StripeSubscription.swift
1
3464
// // Subscription.swift // Stripe // // Created by Hakon Hanesand on 12/2/16. // // import Node import Foundation public enum SubscriptionStatus: String, NodeConvertible { case trialing case active case pastDue = "past_due" case canceled case unpaid } public final class StripeSubscription: NodeConvertible { static let type = "subscription" public let id: String public let application_fee_percent: Double? public let cancel_at_period_end: Bool public let canceled_at: Date? public let created: Date public let current_period_end: Date public let current_period_start: Date public let customer: String public let discount: String? public let ended_at: Date? public let livemode: Bool public let plan: Plan public let quantity: Int public let start: Date public let status: SubscriptionStatus public let tax_percent: Double? public let trial_end: Date? public let trial_start: Date? public let metadata: Node? public init(node: Node) throws { guard try node.extract("object") == StripeSubscription.type else { throw NodeError.unableToConvert(input: node, expectation: StripeSubscription.type, path: ["object"]) } id = try node.extract("id") application_fee_percent = try? node.extract("application_fee_percent") cancel_at_period_end = try node.extract("cancel_at_period_end") canceled_at = try? node.extract("canceled_at") created = try node.extract("created") current_period_end = try node.extract("current_period_end") current_period_start = try node.extract("current_period_start") customer = try node.extract("customer") discount = try? node.extract("discount") ended_at = try? node.extract("ended_at") livemode = try node.extract("livemode") plan = try node.extract("plan") quantity = try node.extract("quantity") start = try node.extract("start") status = try node.extract("status") tax_percent = try? node.extract("tax_percent") trial_end = try? node.extract("trial_end") trial_start = try? node.extract("trial_start") metadata = try? node.extract("metadata") } public func makeNode(in context: Context?) throws -> Node { return try Node(node: [ "id" : .string(id), "cancel_at_period_end" : .bool(cancel_at_period_end), "created" : .number(.double(created.timeIntervalSince1970)), "current_period_end" : .number(.double(current_period_end.timeIntervalSince1970)), "current_period_start" : .number(.double(current_period_start.timeIntervalSince1970)), "customer" : .string(customer), "livemode" : .bool(livemode), "plan" : plan.makeNode(in: context), "quantity" : .number(.int(quantity)), "start" : .number(.double(start.timeIntervalSince1970)), "status" : .string(status.rawValue), ] as [String : Node]).add(objects: [ "canceled_at" : canceled_at, "ended_at" : ended_at, "tax_percent" : tax_percent, "trial_end" : trial_end, "trial_start" : trial_start, "application_fee_percent" : application_fee_percent, "discount" : discount, "metadata" : metadata ]) } }
mit
e4a18366cc8ede4857a4ccc0cd898f1d
35.083333
112
0.616339
4.12381
false
false
false
false
apple/swift-nio-extras
Tests/NIOHTTPCompressionTests/HTTPRequestDecompressorTest+XCTest.swift
1
1343
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // HTTPRequestDecompressorTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension HTTPRequestDecompressorTest { static var allTests : [(String, (HTTPRequestDecompressorTest) -> () throws -> Void)] { return [ ("testDecompressionNoLimit", testDecompressionNoLimit), ("testDecompressionLimitRatio", testDecompressionLimitRatio), ("testDecompressionLimitSize", testDecompressionLimitSize), ("testDecompression", testDecompression), ("testDecompressionTrailingData", testDecompressionTrailingData), ("testDecompressionTruncatedInput", testDecompressionTruncatedInput), ] } }
apache-2.0
a30f7abfe8d3ae1ef326fc853fe76b8c
34.342105
89
0.612807
5.415323
false
true
false
false
hollance/swift-algorithm-club
HaversineDistance/HaversineDistance.playground/Contents.swift
2
1045
import UIKit func haversineDistance(la1: Double, lo1: Double, la2: Double, lo2: Double, radius: Double = 6367444.7) -> Double { let haversin = { (angle: Double) -> Double in return (1 - cos(angle))/2 } let ahaversin = { (angle: Double) -> Double in return 2*asin(sqrt(angle)) } // Converts from degrees to radians let dToR = { (angle: Double) -> Double in return (angle / 360) * 2 * .pi } let lat1 = dToR(la1) let lon1 = dToR(lo1) let lat2 = dToR(la2) let lon2 = dToR(lo2) return radius * ahaversin(haversin(lat2 - lat1) + cos(lat1) * cos(lat2) * haversin(lon2 - lon1)) } let amsterdam = (52.3702, 4.8952) let newYork = (40.7128, -74.0059) // Google says it's 5857 km so our result is only off by 2km which could be due to all kinds of things, not sure how google calculates the distance or which latitude and longitude google uses to calculate the distance. haversineDistance(la1: amsterdam.0, lo1: amsterdam.1, la2: newYork.0, lo2: newYork.1)
mit
f40470d8adba807da8d3b4d51941269d
33.833333
218
0.639234
3.091716
false
false
false
false
danielmartin/swift
test/Sema/exhaustive_switch.swift
1
29697
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-resilience // RUN: %target-typecheck-verify-swift -swift-version 4 -enable-resilience -enable-nonfrozen-enum-exhaustivity-diagnostics func foo(a: Int?, b: Int?) -> Int { switch (a, b) { case (.none, _): return 1 case (_, .none): return 2 case (.some(_), .some(_)): return 3 } switch (a, b) { case (.none, _): return 1 case (_, .none): return 2 case (_?, _?): return 3 } switch Optional<(Int?, Int?)>.some((a, b)) { case .none: return 1 case let (_, x?)?: return x case let (x?, _)?: return x case (.none, .none)?: return 0 } } func bar(a: Bool, b: Bool) -> Int { switch (a, b) { case (false, false): return 1 case (true, _): return 2 case (false, true): return 3 } } enum Result<T> { case Ok(T) case Error(Error) func shouldWork<U>(other: Result<U>) -> Int { switch (self, other) { // No warning case (.Ok, .Ok): return 1 case (.Error, .Error): return 2 case (.Error, _): return 3 case (_, .Error): return 4 } } } func overParenthesized() { // SR-7492: Space projection needs to treat extra paren-patterns explicitly. let x: Result<(Result<Int>, String)> = .Ok((.Ok(1), "World")) switch x { case let .Error(e): print(e) case let .Ok((.Error(e), b)): print(e, b) case let .Ok((.Ok(a), b)): // No warning here. print(a, b) } } enum Foo { case A(Int) case B(Int) } func foo() { switch (Foo.A(1), Foo.B(1)) { case (.A(_), .A(_)): () case (.B(_), _): () case (_, .B(_)): () } switch (Foo.A(1), Optional<(Int, Int)>.some((0, 0))) { case (.A(_), _): break case (.B(_), (let q, _)?): print(q) case (.B(_), nil): break } } class C {} enum Bar { case TheCase(C?) } func test(f: Bar) -> Bool { switch f { case .TheCase(_?): return true case .TheCase(nil): return false } } func op(this : Optional<Bool>, other : Optional<Bool>) -> Optional<Bool> { switch (this, other) { // No warning case let (.none, w): return w case let (w, .none): return w case let (.some(e1), .some(e2)): return .some(e1 && e2) } } enum Threepeat { case a, b, c } func test3(x: Threepeat, y: Threepeat) { switch (x, y) { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{add missing case: '(.a, .c)'}} case (.a, .a): () case (.b, _): () case (.c, _): () case (_, .b): () } } enum A { case A(Int) case B(Bool) case C case D } enum B { case A case B } func s(a: A, b: B) { switch (a, b) { case (.A(_), .A): break case (.A(_), .B): break case (.B(_), let b): // expected-warning@-1 {{immutable value 'b' was never used; consider replacing with '_' or removing it}} break case (.C, _), (.D, _): break } } enum Grimble { case A case B case C } enum Gromble { case D case E } func doSomething(foo:Grimble, bar:Gromble) { switch(foo, bar) { // No warning case (.A, .D): break case (.A, .E): break case (.B, _): break case (.C, _): break } } enum E { case A case B } func f(l: E, r: E) { switch (l, r) { case (.A, .A): return case (.A, _): return case (_, .A): return case (.B, .B): return } } enum TestEnum { case A, B } func switchOverEnum(testEnumTuple: (TestEnum, TestEnum)) { switch testEnumTuple { case (_,.B): // Matches (.A, .B) and (.B, .B) break case (.A,_): // Matches (.A, .A) // Would also match (.A, .B) but first case takes precedent break case (.B,.A): // Matches (.B, .A) break } } func tests(a: Int?, b: String?) { switch (a, b) { case let (.some(n), _): print("a: ", n, "?") case (.none, _): print("Nothing", "?") } switch (a, b) { case let (.some(n), .some(s)): print("a: ", n, "b: ", s) case let (.some(n), .none): print("a: ", n, "Nothing") case (.none, _): print("Nothing") } switch (a, b) { case let (.some(n), .some(s)): print("a: ", n, "b: ", s) case let (.some(n), .none): print("a: ", n, "Nothing") case let (.none, .some(s)): print("Nothing", "b: ", s) case (.none, _): print("Nothing", "?") } switch (a, b) { case let (.some(n), .some(s)): print("a: ", n, "b: ", s) case let (.some(n), .none): print("a: ", n, "Nothing") case let (.none, .some(s)): print("Nothing", "b: ", s) case (.none, .none): print("Nothing", "Nothing") } } enum X { case Empty case A(Int) case B(Int) } func f(a: X, b: X) { switch (a, b) { case (_, .Empty): () case (.Empty, _): () case (.A, .A): () case (.B, .B): () case (.A, .B): () case (.B, .A): () } } func f2(a: X, b: X) { switch (a, b) { case (.A, .A): () case (.B, .B): () case (.A, .B): () case (.B, .A): () case (_, .Empty): () case (.Empty, _): () case (.A, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}} case (.B, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}} case (.A, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}} case (.B, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}} default: () } } enum XX : Int { case A case B case C case D case E } func switcheroo(a: XX, b: XX) -> Int { switch(a, b) { // No warning case (.A, _) : return 1 case (_, .A) : return 2 case (.C, _) : return 3 case (_, .C) : return 4 case (.B, .B) : return 5 case (.B, .D) : return 6 case (.D, .B) : return 7 case (.B, .E) : return 8 case (.E, .B) : return 9 case (.E, _) : return 10 case (_, .E) : return 11 case (.D, .D) : return 12 default: print("never hits this:", a, b) return 13 } } enum PatternCasts { case one(Any) case two case three(String) } func checkPatternCasts() { // Pattern casts with this structure shouldn't warn about duplicate cases. let x: PatternCasts = .one("One") switch x { case .one(let s as String): print(s) case .one: break case .two: break case .three: break } // But should warn here. switch x { case .one(_): print(s) case .one: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case .two: break case .three: break } // And not here switch x { case .one: break case .two: break case .three(let s as String?): print(s as Any) } } enum MyNever {} func ~= (_ : MyNever, _ : MyNever) -> Bool { return true } func myFatalError() -> MyNever { fatalError() } @_frozen public enum UninhabitedT4<A> { case x(A) } func checkUninhabited() { // Scrutinees of uninhabited type may match any number and kind of patterns // that Sema is willing to accept at will. After all, it's quite a feat to // productively inhabit the type of crashing programs. func test1(x : Never) { switch x {} // No diagnostic. } func test2(x : Never) { switch (x, x) {} // No diagnostic. } func test3(x : MyNever) { switch x { // No diagnostic. case myFatalError(): break case myFatalError(): break case myFatalError(): break } } func test4(x: UninhabitedT4<Never>) { switch x {} // No diagnostic. } } enum Runcible { case spoon case hat case fork } func checkDiagnosticMinimality(x: Runcible?) { switch (x!, x!) { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{add missing case: '(.fork, _)'}} // expected-note@-2 {{add missing case: '(.hat, .hat)'}} // expected-note@-3 {{add missing case: '(_, .fork)'}} case (.spoon, .spoon): break case (.spoon, .hat): break case (.hat, .spoon): break } switch (x!, x!) { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{add missing case: '(.fork, _)'}} // expected-note@-2 {{add missing case: '(.hat, .spoon)'}} // expected-note@-3 {{add missing case: '(.spoon, .hat)'}} // expected-note@-4 {{add missing case: '(_, .fork)'}} case (.spoon, .spoon): break case (.hat, .hat): break } } indirect enum InfinitelySized { case one case two case recur(InfinitelySized) case mutualRecur(MutuallyRecursive, InfinitelySized) } indirect enum MutuallyRecursive { case one case two case recur(MutuallyRecursive) case mutualRecur(InfinitelySized, MutuallyRecursive) } func infinitelySized() -> Bool { switch (InfinitelySized.one, InfinitelySized.one) { // expected-error {{switch must be exhaustive}} // expected-note@-1 8 {{add missing case:}} case (.one, .one): return true case (.two, .two): return true } switch (MutuallyRecursive.one, MutuallyRecursive.one) { // expected-error {{switch must be exhaustive}} // expected-note@-1 8 {{add missing case:}} case (.one, .one): return true case (.two, .two): return true } } func sr6316() { let bool1 = false let bool2 = false let bool3 = false let bool4 = true let bool5 = false let bool6 = true let bool7 = true let bool8 = false let bool9 = false switch (bool1, (bool2, bool4, bool6, bool8), (bool3, bool5, bool7, bool9)) { // expected-error@-1 {{switch must be exhaustive}} // expected-note@-2 {{add missing case: '(false, (_, false, true, _), (_, true, _, _))'}} // expected-note@-3 {{add missing case: '(_, (_, true, _, _), (_, false, true, _))'}} case (true, (_, _, _, _), (_, true, true, _)): break case (true, (_, _, _, _), (_, _, false, _)): break case (_, (_, true, true, _), (_, _, false, _)): break case (_, (_, _, false, _), (_, true, true, _)): break case (_, (_, true, true, _), (_, true, true, _)): break case (_, (_, _, false, _), (_, _, false, _)): break case (_, (_, false, _, _), (_, false, _, _)): break } } func sr6652() { enum A { indirect case a([A], foo: Bool) indirect case b(Dictionary<String, Int>) indirect case c(A, foo: [A]) indirect case d(if: A, then: A, else: A) indirect case e(A, A, foo: Bool) indirect case f(A) case g(String, foo: Bool) case string(String) case `nil` static func eke(_ lhs: A, _ rhs: A) -> Bool { return false } } enum B { static func eke(_ lhs: B, _ rhs: B) -> Bool { return false } } enum C { static func eke(_ lhs: C, _ rhs: C) -> Bool { return false } } enum D { case a(A) case b(B) case c(C) indirect case d([D]) // No diagnostic static func eke(_ lhs: D, _ rhs: D) -> Bool { switch (lhs, rhs) { case (.a(let r1), .a(let r2)): return A.eke(r1, r2) case (.a, _): return false case (.b(let r1), .b(let r2)): return B.eke(r1, r2) case (.b, _): return false case (.c(let r1), .c(let r2)): return C.eke(r1, r2) case (.c, _): return false case (.d(let r1), .d(let r2)): return zip(r1, r2).allSatisfy(D.eke) case (.d, _): return false } } } } func diagnoseDuplicateLiterals() { let str = "def" let int = 2 let dbl = 2.5 // No Diagnostics switch str { case "abc": break case "def": break case "ghi": break default: break } switch str { case "abc": break case "def": break // expected-note {{first occurrence of identical literal pattern is here}} case "def": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case "ghi": break default: break } switch str { case "abc", "def": break // expected-note 2 {{first occurrence of identical literal pattern is here}} case "ghi", "jkl": break case "abc", "def": break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}} default: break } switch str { case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}} case "ghi": break case "def": break case "abc": break case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } func someStr() -> String { return "sdlkj" } let otherStr = "ifnvbnwe" switch str { case "sdlkj": break case "ghi": break // expected-note {{first occurrence of identical literal pattern is here}} case someStr(): break case "def": break case otherStr: break case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}} case "ifnvbnwe": break case "ghi": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } // No Diagnostics switch int { case -2: break case -1: break case 0: break case 1: break case 2: break case 3: break default: break } switch int { case -2: break // expected-note {{first occurrence of identical literal pattern is here}} case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 1: break case 2: break // expected-note {{first occurrence of identical literal pattern is here}} case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 3: break default: break } switch int { case -2, -2: break // expected-note {{first occurrence of identical literal pattern is here}} expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 1, 2: break // expected-note 3 {{first occurrence of identical literal pattern is here}} case 2, 3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 1, 2: break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}} case 4, 5: break case 7, 7: break // expected-note {{first occurrence of identical literal pattern is here}} // expected-warning@-1 {{literal value is already handled by previous pattern; consider removing it}} default: break } switch int { case 1: break // expected-note {{first occurrence of identical literal pattern is here}} case 2: break // expected-note 2 {{first occurrence of identical literal pattern is here}} case 3: break case 17: break // expected-note {{first occurrence of identical literal pattern is here}} case 4: break case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 5: break case 0x11: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 0b10: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } switch int { case 10: break case 0b10: break // expected-note {{first occurrence of identical literal pattern is here}} case -0b10: break // expected-note {{first occurrence of identical literal pattern is here}} case 3000: break case 0x12: break // expected-note {{first occurrence of identical literal pattern is here}} case 400: break case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 18: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } func someInt() -> Int { return 0x1234 } let otherInt = 13254 switch int { case 13254: break case 3000: break case 00000002: break // expected-note {{first occurrence of identical literal pattern is here}} case 0x1234: break case someInt(): break case 400: break case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 18: break case otherInt: break case 230: break default: break } // No Diagnostics switch dbl { case -3.5: break case -2.5: break case -1.5: break case 1.5: break case 2.5: break case 3.5: break default: break } switch dbl { case -3.5: break case -2.5: break // expected-note {{first occurrence of identical literal pattern is here}} case -2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case -1.5: break case 1.5: break case 2.5: break // expected-note {{first occurrence of identical literal pattern is here}} case 2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 3.5: break default: break } switch dbl { case 1.5, 4.5, 7.5, 6.9: break // expected-note 2 {{first occurrence of identical literal pattern is here}} case 3.4, 1.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 7.5, 2.3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } switch dbl { case 1: break case 1.5: break // expected-note 2 {{first occurrence of identical literal pattern is here}} case 2.5: break case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}} case 5.3132: break case 1.500: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 46.2395: break case 1.5000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 23452.43: break default: break } func someDouble() -> Double { return 324.4523 } let otherDouble = 458.2345 switch dbl { case 1: break // expected-note {{first occurrence of identical literal pattern is here}} case 1.5: break case 2.5: break case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}} case 5.3132: break case 46.2395: break case someDouble(): break case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case otherDouble: break case 2.50505: break // expected-note {{first occurrence of identical literal pattern is here}} case 23452.43: break case 00001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 123453: break case 2.50505000000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } } func checkLiteralTuples() { let str1 = "abc" let str2 = "def" let int1 = 23 let int2 = 7 let dbl1 = 4.23 let dbl2 = 23.45 // No Diagnostics switch (str1, str2) { case ("abc", "def"): break case ("def", "ghi"): break case ("ghi", "def"): break case ("abc", "def"): break // We currently don't catch this default: break } // No Diagnostics switch (int1, int2) { case (94, 23): break case (7, 23): break case (94, 23): break // We currently don't catch this case (23, 7): break default: break } // No Diagnostics switch (dbl1, dbl2) { case (543.21, 123.45): break case (543.21, 123.45): break // We currently don't catch this case (23.45, 4.23): break case (4.23, 23.45): break default: break } } func sr6975() { enum E { case a, b } let e = E.b switch e { case .a as E: // expected-warning {{'as' test is always true}} print("a") case .b: // Valid! print("b") case .a: // expected-warning {{case is already handled by previous patterns; consider removing it}} print("second a") } func foo(_ str: String) -> Int { switch str { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{do you want to add a default clause?}} case let (x as Int) as Any: return x } } _ = foo("wtf") } public enum NonExhaustive { case a, b } public enum NonExhaustivePayload { case a(Int), b(Bool) } @_frozen public enum TemporalProxy { case seconds(Int) case milliseconds(Int) case microseconds(Int) case nanoseconds(Int) case never } // Inlinable code is considered "outside" the module and must include a default // case. @inlinable public func testNonExhaustive(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) { switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}} case .a: break } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}} case .a: break case .b: break } switch value { case .a: break case .b: break default: break // no-warning } switch value { case .a: break case .b: break @unknown case _: break // no-warning } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} case .a: break @unknown case _: break } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}} @unknown case _: break } switch value { case _: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } // Test being part of other spaces. switch value as Optional { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.some(_)'}} case .a?: break case .b?: break case nil: break } switch value as Optional { case .a?: break case .b?: break case nil: break @unknown case _: break } // no-warning switch value as Optional { case _?: break case nil: break } // no-warning switch (value, flag) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, false)'}} case (.a, _): break case (.b, false): break case (_, true): break } switch (value, flag) { case (.a, _): break case (.b, false): break case (_, true): break @unknown case _: break } // no-warning switch (flag, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(false, _)'}} case (_, .a): break case (false, .b): break case (true, _): break } switch (flag, value) { case (_, .a): break case (false, .b): break case (true, _): break @unknown case _: break } // no-warning switch (value, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, _)'}} case (.a, _), (_, .a): break case (.b, _), (_, .b): break } switch (value, value) { case (.a, _), (_, .a): break case (.b, _), (_, .b): break @unknown case _: break } // no-warning // Test payloaded enums. switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}} case .a: break } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}} case .a: break case .b: break } switch payload { case .a: break case .b: break default: break // no-warning } switch payload { case .a: break case .b: break @unknown case _: break // no-warning } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} case .a: break @unknown case _: break } switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}} case .a: break case .b(false): break } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} case .a: break case .b(false): break @unknown case _: break } // Test fully-covered switches. switch interval { case .seconds, .milliseconds, .microseconds, .nanoseconds: break case .never: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } switch flag { case true: break case false: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } switch flag as Optional { case _?: break case nil: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } switch (flag, value) { case (true, _): break case (false, _): break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } } public func testNonExhaustiveWithinModule(_ value: NonExhaustive, _ payload: NonExhaustivePayload, flag: Bool) { switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} case .a: break } switch value { // no-warning case .a: break case .b: break } switch value { case .a: break case .b: break default: break // no-warning } switch value { case .a: break case .b: break @unknown case _: break // no-warning } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} case .a: break @unknown case _: break } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}} @unknown case _: break } switch value { case _: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } // Test being part of other spaces. switch value as Optional { // no-warning case .a?: break case .b?: break case nil: break } switch value as Optional { case _?: break case nil: break } // no-warning switch (value, flag) { // no-warning case (.a, _): break case (.b, false): break case (_, true): break } switch (flag, value) { // no-warning case (_, .a): break case (false, .b): break case (true, _): break } switch (value, value) { // no-warning case (.a, _): break case (.b, _): break case (_, .a): break case (_, .b): break } switch (value, value) { // no-warning case (.a, _): break case (.b, _): break case (_, .a): break case (_, .b): break @unknown case _: break } // Test payloaded enums. switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} case .a: break } switch payload { // no-warning case .a: break case .b: break } switch payload { case .a: break case .b: break default: break // no-warning } switch payload { case .a: break case .b: break @unknown case _: break // no-warning } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} case .a: break @unknown case _: break } switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} case .a: break case .b(false): break } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} case .a: break case .b(false): break @unknown case _: break } } enum UnavailableCase { case a case b @available(*, unavailable) case oopsThisWasABadIdea } enum UnavailableCaseOSSpecific { case a case b #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) @available(macOS, unavailable) @available(iOS, unavailable) @available(tvOS, unavailable) @available(watchOS, unavailable) case unavailableOnAllTheseApplePlatforms #else @available(*, unavailable) case dummyCaseForOtherPlatforms #endif } enum UnavailableCaseOSIntroduced { case a case b @available(macOS 50, iOS 50, tvOS 50, watchOS 50, *) case notYetIntroduced } func testUnavailableCases(_ x: UnavailableCase, _ y: UnavailableCaseOSSpecific, _ z: UnavailableCaseOSIntroduced) { switch x { case .a: break case .b: break } // no-error switch y { case .a: break case .b: break } // no-error switch z { case .a: break case .b: break case .notYetIntroduced: break } // no-error } // The following test used to behave differently when the uninhabited enum was // defined in the same module as the function (as opposed to using Swift.Never). enum NoError {} extension Result where T == NoError { func testUninhabited() { switch self { case .Error(_): break // No .Ok case possible because of the 'NoError'. } switch self { case .Error(_): break case .Ok(_): break // But it's okay to write one. } } }
apache-2.0
3f14daf7b42e9f89458ef545be7be3ae
25.118734
205
0.623161
3.552698
false
false
false
false
nab0y4enko/PrettyExtensionsKit
Sources/Foundation/URL+PrettyExtensionsKit.swift
1
635
// // URL+PrettyExtensionsKit.swift // PrettyExtensionsKit // // Created by Oleksii Naboichenko on 10/10/17. // Copyright © 2017 Oleksii Naboichenko. All rights reserved. // import Foundation public extension URL { /// Returned trimmed url /// Example: /// http://www.example.com/folder/page.htm?param1=value1&param2=value2 => http://www.example.com/folder/page.htm var prettyTrimmedQuery: URL? { guard let urlComponents = NSURLComponents(url: self, resolvingAgainstBaseURL: false) else { return nil } urlComponents.query = nil return urlComponents.url } }
mit
26429834d1d480f2c2bd8a464548e75c
24.36
116
0.667192
3.937888
false
false
false
false
kotoole1/Paranormal
Paranormal/Paranormal/Operations/ChamferDialogController.swift
1
1998
import Foundation import Cocoa class ChamferDialogController : NSWindowController, NSOpenSavePanelDelegate { // TOOD: make a common PNOperationDialogController base class var parentWindow : NSWindow? var chamferOperation : ChamferOperation? var radius : Float = 20.0 var depth : Float = 2.0 var shape : Float = 0.0 @IBAction func radiusSet(sender: NSSlider) { self.radius = sender.floatValue self.updatePreview() } @IBAction func depthSet(sender: NSSlider) { self.depth = sender.floatValue self.updatePreview() } @IBAction func shapeSet(sender: NSSlider) { self.shape = sender.floatValue self.updatePreview() } override var windowNibName : String! { return "ChamferDialog" } init(parentWindow: NSWindow, chamfer: ChamferOperation) { super.init(window: nil) self.chamferOperation = chamfer self.parentWindow = parentWindow self.createChamferLayer() } override init() { super.init() } func createChamferLayer() { if let chamfer = chamferOperation { chamfer.create() } } func updatePreview() { if let chamfer = chamferOperation { chamfer.updatePreview(radius: radius, depth: depth, shape: shape) } } @IBAction func confirm(sender: NSButton) { if let chamfer = chamferOperation { chamfer.confirm() } closeSheet() } @IBAction func cancel(sender: NSButton) { if let chamfer = chamferOperation { chamfer.cancel() } closeSheet() } func closeSheet() { if let unwrapParentWindow = parentWindow { NSApp.endSheet(window!) window?.orderOut(unwrapParentWindow) } } override init(window: NSWindow?) { super.init(window:window) } required init?(coder: NSCoder) { super.init(coder: coder) } }
mit
a33c670e21a267edb102b79e82bc9ffe
23.365854
77
0.606607
4.343478
false
false
false
false
ben-ng/swift
test/SILGen/instrprof_operators.swift
25
2059
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -profile-generate %s | %FileCheck %s // CHECK: sil hidden @[[F_OPERATORS:.*operators.*]] : // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) func operators(a : Bool, b : Bool) { let c = a && b let d = a || b // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 3 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) let e = c ? a : b // CHECK-NOT: builtin "int_instrprof_increment" } // CHECK: implicit closure // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 1 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) // CHECK-NOT: builtin "int_instrprof_increment" // CHECK: implicit closure // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 2 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) // CHECK-NOT: builtin "int_instrprof_increment"
apache-2.0
09edc2f94c5d16f0ff7d18d4688b1149
54.648649
127
0.576493
3.31562
false
false
false
false
appsembler/edx-app-ios
Source/DiscussionNewPostViewController.swift
1
17804
// // DiscussionNewPostViewController.swift // edX // // Created by Tang, Jeff on 6/1/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit struct DiscussionNewThread { let courseID: String let topicID: String let type: DiscussionThreadType let title: String let rawBody: String } protocol DiscussionNewPostViewControllerDelegate : class { func newPostController(controller : DiscussionNewPostViewController, addedPost post: DiscussionThread) } public class DiscussionNewPostViewController: UIViewController, UITextViewDelegate, MenuOptionsViewControllerDelegate, InterfaceOrientationOverriding { public typealias Environment = protocol<DataManagerProvider, NetworkManagerProvider, OEXRouterProvider, OEXAnalyticsProvider> private let minBodyTextHeight : CGFloat = 66 // height for 3 lines of text private let environment: Environment private let growingTextController = GrowingTextViewController() private let insetsController = ContentInsetsController() @IBOutlet private var scrollView: UIScrollView! @IBOutlet private var backgroundView: UIView! @IBOutlet private var contentTextView: OEXPlaceholderTextView! @IBOutlet private var titleTextField: UITextField! @IBOutlet private var discussionQuestionSegmentedControl: UISegmentedControl! @IBOutlet private var bodyTextViewHeightConstraint: NSLayoutConstraint! @IBOutlet private var topicButton: UIButton! @IBOutlet private var postButton: SpinnerButton! @IBOutlet weak var contentTitleLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! private let loadController = LoadStateViewController() private let courseID: String private let topics = BackedStream<[DiscussionTopic]>() private var selectedTopic: DiscussionTopic? private var optionsViewController: MenuOptionsViewController? weak var delegate: DiscussionNewPostViewControllerDelegate? private let tapButton = UIButton() var titleTextStyle : OEXTextStyle{ return OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) } private var selectedThreadType: DiscussionThreadType = .Discussion { didSet { switch selectedThreadType { case .Discussion: self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout([titleTextStyle.attributedStringWithText(Strings.courseDashboardDiscussion), titleTextStyle.attributedStringWithText(Strings.asteric)]) postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle,withTitle: Strings.postDiscussion) contentTextView.accessibilityLabel = Strings.courseDashboardDiscussion case .Question: self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout([titleTextStyle.attributedStringWithText(Strings.question), titleTextStyle.attributedStringWithText(Strings.asteric)]) postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle, withTitle: Strings.postQuestion) contentTextView.accessibilityLabel = Strings.question } } } public init(environment: Environment, courseID: String, selectedTopic : DiscussionTopic?) { self.environment = environment self.courseID = courseID super.init(nibName: "DiscussionNewPostViewController", bundle: nil) let stream = environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID).topics topics.backWithStream(stream.map { return DiscussionTopic.linearizeTopics($0) } ) self.selectedTopic = selectedTopic } private var firstSelectableTopic : DiscussionTopic? { let selectablePredicate = { (topic : DiscussionTopic) -> Bool in topic.isSelectable } guard let topics = self.topics.value, selectableTopicIndex = topics.firstIndexMatching(selectablePredicate) else { return nil } return topics[selectableTopicIndex] } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func postTapped(sender: AnyObject) { postButton.enabled = false postButton.showProgress = true // create new thread (post) if let topic = selectedTopic, topicID = topic.id { let newThread = DiscussionNewThread(courseID: courseID, topicID: topicID, type: selectedThreadType ?? .Discussion, title: titleTextField.text ?? "", rawBody: contentTextView.text) let apiRequest = DiscussionAPI.createNewThread(newThread) environment.networkManager.taskForRequest(apiRequest) {[weak self] result in self?.postButton.enabled = true self?.postButton.showProgress = false if let post = result.data { self?.delegate?.newPostController(self!, addedPost: post) self?.dismissViewControllerAnimated(true, completion: nil) } else { self?.showOverlayMessage(DiscussionHelper.messageForError(result.error)) } } } } override public func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = Strings.post let cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: nil, action: nil) cancelItem.oex_setAction { [weak self]() -> Void in self?.dismissViewControllerAnimated(true, completion: nil) } self.navigationItem.leftBarButtonItem = cancelItem contentTitleLabel.isAccessibilityElement = false titleLabel.isAccessibilityElement = false titleLabel.attributedText = NSAttributedString.joinInNaturalLayout([titleTextStyle.attributedStringWithText(Strings.title), titleTextStyle.attributedStringWithText(Strings.asteric)]) contentTextView.textContainer.lineFragmentPadding = 0 contentTextView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets contentTextView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes contentTextView.placeholderTextColor = OEXStyles.sharedStyles().neutralLight() contentTextView.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle) contentTextView.delegate = self titleTextField.accessibilityLabel = Strings.title self.view.backgroundColor = OEXStyles.sharedStyles().neutralXXLight() configureSegmentControl() titleTextField.defaultTextAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes setTopicsButtonTitle() let insets = OEXStyles.sharedStyles().standardTextViewInsets topicButton.titleEdgeInsets = UIEdgeInsetsMake(0, insets.left, 0, insets.right) topicButton.accessibilityHint = Strings.accessibilityShowsDropdownHint topicButton.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle) topicButton.localizedHorizontalContentAlignment = .Leading let dropdownLabel = UILabel() dropdownLabel.attributedText = Icon.Dropdown.attributedTextWithStyle(titleTextStyle) topicButton.addSubview(dropdownLabel) dropdownLabel.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(topicButton).offset(-insets.right) make.top.equalTo(topicButton).offset(topicButton.frame.size.height / 2.0 - 5.0) } topicButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in self?.showTopicPicker() }, forEvents: UIControlEvents.TouchUpInside) postButton.enabled = false titleTextField.oex_addAction({[weak self] _ in self?.validatePostButton() }, forEvents: .EditingChanged) self.growingTextController.setupWithScrollView(scrollView, textView: contentTextView, bottomView: postButton) self.insetsController.setupInController(self, scrollView: scrollView) // Force setting it to call didSet which is only called out of initialization context self.selectedThreadType = .Question loadController.setupInController(self, contentView: self.scrollView) topics.listen(self, success : {[weak self]_ in self?.loadedData() }, failure : {[weak self] error in self?.loadController.state = LoadState.failed(error) }) backgroundView.addSubview(tapButton) backgroundView.sendSubviewToBack(tapButton) tapButton.backgroundColor = UIColor.clearColor() tapButton.frame = CGRectMake(0, 0, backgroundView.frame.size.width, backgroundView.frame.size.height) tapButton.isAccessibilityElement = false tapButton.accessibilityLabel = Strings.accessibilityHideKeyboard tapButton.oex_addAction({[weak self] (sender) in self?.view.endEditing(true) }, forEvents: .TouchUpInside) } private func configureSegmentControl() { discussionQuestionSegmentedControl.removeAllSegments() let questionIcon = Icon.Question.attributedTextWithStyle(titleTextStyle) let questionTitle = NSAttributedString.joinInNaturalLayout([questionIcon, titleTextStyle.attributedStringWithText(Strings.question)]) let discussionIcon = Icon.Comments.attributedTextWithStyle(titleTextStyle) let discussionTitle = NSAttributedString.joinInNaturalLayout([discussionIcon, titleTextStyle.attributedStringWithText(Strings.discussion)]) let segmentOptions : [(title : NSAttributedString, value : DiscussionThreadType)] = [ (title : questionTitle, value : .Question), (title : discussionTitle, value : .Discussion), ] for i in 0..<segmentOptions.count { discussionQuestionSegmentedControl.insertSegmentWithAttributedTitle(segmentOptions[i].title, index: i, animated: false) discussionQuestionSegmentedControl.subviews[i].accessibilityLabel = segmentOptions[i].title.string } discussionQuestionSegmentedControl.oex_addAction({ [weak self] (control:AnyObject) -> Void in if let segmentedControl = control as? UISegmentedControl { let index = segmentedControl.selectedSegmentIndex let threadType = segmentOptions[index].value self?.selectedThreadType = threadType self?.updateSelectedTabColor() } else { assert(true, "Invalid Segment ID, Remove this segment index OR handle it in the ThreadType enum") } }, forEvents: UIControlEvents.ValueChanged) discussionQuestionSegmentedControl.tintColor = OEXStyles.sharedStyles().neutralDark() discussionQuestionSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName: OEXStyles.sharedStyles().neutralWhite()], forState: UIControlState.Selected) discussionQuestionSegmentedControl.selectedSegmentIndex = 0 updateSelectedTabColor() } private func updateSelectedTabColor() { // //UIsegmentControl don't Multiple tint color so updating tint color of subviews to match desired behaviour let subViews:NSArray = discussionQuestionSegmentedControl.subviews for i in 0..<subViews.count { if subViews.objectAtIndex(i).isSelected ?? false { let view = subViews.objectAtIndex(i) as! UIView view.tintColor = OEXStyles.sharedStyles().primaryBaseColor() } else { let view = subViews.objectAtIndex(i) as! UIView view.tintColor = OEXStyles.sharedStyles().neutralDark() } } } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.environment.analytics.trackDiscussionScreenWithName(OEXAnalyticsScreenCreateTopicThread, courseId: self.courseID, value: selectedTopic?.name, threadId: nil, topicId: selectedTopic?.id, responseID: nil) } override public func shouldAutorotate() -> Bool { return true } override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .AllButUpsideDown } private func loadedData() { loadController.state = topics.value?.count == 0 ? LoadState.empty(icon: .NoTopics, message : Strings.unableToLoadCourseContent) : .Loaded if selectedTopic == nil { selectedTopic = firstSelectableTopic } setTopicsButtonTitle() } private func setTopicsButtonTitle() { if let topic = selectedTopic, name = topic.name { let title = Strings.topic(topic: name) topicButton.setAttributedTitle(OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()).attributedStringWithText(title), forState: .Normal) } } func showTopicPicker() { if self.optionsViewController != nil { return } view.endEditing(true) self.optionsViewController = MenuOptionsViewController() self.optionsViewController?.delegate = self guard let courseTopics = topics.value else { //Don't need to configure an empty state here because it's handled in viewDidLoad() return } self.optionsViewController?.options = courseTopics.map { return MenuOptionsViewController.MenuOption(depth : $0.depth, label : $0.name ?? "") } self.optionsViewController?.selectedOptionIndex = self.selectedTopicIndex() self.view.addSubview(self.optionsViewController!.view) self.optionsViewController!.view.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(self.topicButton) make.leading.equalTo(self.topicButton) make.top.equalTo(self.topicButton.snp_bottom).offset(-3) make.bottom.equalTo(self.view.snp_bottom) } self.optionsViewController?.view.alpha = 0.0 UIView.animateWithDuration(0.3) { self.optionsViewController?.view.alpha = 1.0 } } private func selectedTopicIndex() -> Int? { guard let selected = selectedTopic else { return 0 } return self.topics.value?.firstIndexMatching { return $0.id == selected.id } } public func textViewDidChange(textView: UITextView) { validatePostButton() growingTextController.handleTextChange() } public func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index : Int) -> Bool { return self.topics.value?[index].isSelectable ?? false } private func validatePostButton() { self.postButton.enabled = !(titleTextField.text ?? "").isEmpty && !contentTextView.text.isEmpty && self.selectedTopic != nil } func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int) { selectedTopic = self.topics.value?[index] if let topic = selectedTopic where topic.id != nil { setTopicsButtonTitle() UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, titleTextField); UIView.animateWithDuration(0.3, animations: { self.optionsViewController?.view.alpha = 0.0 }, completion: {[weak self](finished: Bool) in self?.optionsViewController?.view.removeFromSuperview() self?.optionsViewController = nil }) } } public override func viewDidLayoutSubviews() { self.insetsController.updateInsets() growingTextController.scrollToVisible() } func textFieldDidBeginEditing(textField: UITextField) { tapButton.isAccessibilityElement = true } func textFieldDidEndEditing(textField: UITextField) { tapButton.isAccessibilityElement = false } public func textViewDidBeginEditing(textView: UITextView) { tapButton.isAccessibilityElement = true } public func textViewDidEndEditing(textView: UITextView) { tapButton.isAccessibilityElement = false } } extension UISegmentedControl { //UIsegmentControl didn't support attributedTitle by default func insertSegmentWithAttributedTitle(title: NSAttributedString, index: NSInteger, animated: Bool) { let segmentLabel = UILabel() segmentLabel.backgroundColor = UIColor.clearColor() segmentLabel.textAlignment = .Center segmentLabel.attributedText = title segmentLabel.sizeToFit() self.insertSegmentWithImage(segmentLabel.toImage(), atIndex: 1, animated: false) } } extension UILabel { func toImage()-> UIImage? { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) self.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); return image; } } // For use in testing only extension DiscussionNewPostViewController { public func t_topicsLoaded() -> Stream<[DiscussionTopic]> { return topics } }
apache-2.0
e4fda7442e521d852043ce28b492c980
42.852217
230
0.681645
5.801238
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Augmented reality/View hidden infrastructure in AR/ViewHiddenInfrastructureARPipePlacingViewController.swift
1
9867
// Copyright 2020 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 ArcGIS class ViewHiddenInfrastructureARPipePlacingViewController: UIViewController { // MARK: Storyboard views /// The label to display pipe infrastructure planning status. @IBOutlet var statusLabel: UILabel! /// The bar button to add a new geometry. @IBOutlet var sketchBarButtonItem: UIBarButtonItem! { didSet { sketchBarButtonItem.possibleTitles = ["Add", "Done"] } } /// The bar button to remove all geometries. @IBOutlet var trashBarButtonItem: UIBarButtonItem! /// The bar button to launch the AR viewer. @IBOutlet var cameraBarButtonItem: UIBarButtonItem! /// The map view managed by the view controller. @IBOutlet var mapView: AGSMapView! { didSet { mapView.map = AGSMap(basemapStyle: .arcGISImagery) mapView.graphicsOverlays.add(pipeGraphicsOverlay) mapView.sketchEditor = AGSSketchEditor() } } // MARK: Properties /// A graphics overlay for showing the pipes. let pipeGraphicsOverlay: AGSGraphicsOverlay = { let overlay = AGSGraphicsOverlay() overlay.renderer = AGSSimpleRenderer( symbol: AGSSimpleLineSymbol(style: .solid, color: .red, width: 2) ) return overlay }() /// A KVO on the graphics array of the graphics overlay. var graphicsObservation: NSKeyValueObservation? /// The data source to track device location and provide updates to location display. let locationDataSource = AGSCLLocationDataSource() /// The elevation source with elevation service URL. let elevationSource = AGSArcGISTiledElevationSource(url: URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!) /// The elevation surface for drawing pipe graphics relative to groud level. let elevationSurface = AGSSurface() // MARK: Methods /// Add a graphic from the geometry of the sketch editor on current map view. /// /// - Parameters: /// - polyline: A polyline geometry created by the sketch editor. /// - elevationOffset: An offset added to the current elevation surface, /// to place the polyline (pipes) above or below the ground. func addGraphicsFromSketchEditor(polyline: AGSPolyline, elevationOffset: NSNumber) { guard let firstpoint = polyline.parts.array().first?.startPoint else { return } elevationSurface.elevation(for: firstpoint) { [weak self] (elevation: Double, error: Error?) in guard let self = self else { return } let graphic: AGSGraphic if error != nil { graphic = AGSGraphic(geometry: polyline, symbol: nil) self.setStatus(message: "Pipe added without elevation.") } else { let elevatedPolyline = AGSGeometryEngine.geometry(bySettingZ: elevation + elevationOffset.doubleValue, in: polyline) graphic = AGSGraphic(geometry: elevatedPolyline, symbol: nil, attributes: ["ElevationOffset": elevationOffset.doubleValue]) if elevationOffset.intValue < 0 { self.setStatus(message: "Pipe added \(elevationOffset.stringValue) meter(s) below surface.") } else if elevationOffset.intValue == 0 { self.setStatus(message: "Pipe added at ground level.") } else { self.setStatus(message: "Pipe added \(elevationOffset.stringValue) meter(s) above surface.") } } self.pipeGraphicsOverlay.graphics.add(graphic) } } // MARK: Actions @IBAction func sketchBarButtonTapped(_ sender: UIBarButtonItem) { guard let sketchEditor = mapView.sketchEditor else { return } switch sketchEditor.isStarted { case true: // Stop the sketch editor and create graphics when "Done" is tapped. if let polyline = sketchEditor.geometry as? AGSPolyline, polyline.parts.array().contains(where: { $0.pointCount >= 2 }) { // Let user provide an elevation if the geometry is a valid polyline. presentElevationAlert { [weak self] elevation in self?.addGraphicsFromSketchEditor(polyline: polyline, elevationOffset: elevation) } } else { setStatus(message: "No pipe added.") } sketchEditor.stop() sketchEditor.clearGeometry() sender.title = "Add" case false: // Start the sketch editor when "Add" is tapped. sketchEditor.start(with: nil, creationMode: .polyline) setStatus(message: "Tap on the map to add geometry.") sender.title = "Done" } } @IBAction func trashBarButtonTapped(_ sender: UIBarButtonItem) { pipeGraphicsOverlay.graphics.removeAllObjects() setStatus(message: "Tap add button to add pipes.") } // MARK: UI func setStatus(message: String) { statusLabel.text = message } func presentElevationAlert(completion: @escaping (NSNumber) -> Void) { let alert = UIAlertController(title: "Provide an elevation", message: "Between -10 and 10 meters", preferredStyle: .alert) alert.addTextField { textField in textField.keyboardType = .numbersAndPunctuation textField.placeholder = "3" } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) let doneAction = UIAlertAction(title: "Done", style: .default) { [textField = alert.textFields?.first] _ in let distanceFormatter = NumberFormatter() // Format the string to an integer. distanceFormatter.maximumFractionDigits = 0 // Ensure the elevation value is valid. guard let text = textField?.text, !text.isEmpty, let elevation = distanceFormatter.number(from: text), elevation.intValue >= -10, elevation.intValue <= 10 else { return } // Pass back the elevation value. completion(elevation) } alert.addAction(cancelAction) alert.addAction(doneAction) alert.preferredAction = doneAction present(alert, animated: true) } // MARK: UIViewController override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showViewer", let controller = segue.destination as? ViewHiddenInfrastructureARExplorerViewController, let graphics = pipeGraphicsOverlay.graphics as? [AGSGraphic] { controller.pipeGraphics = graphics } } override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = [ "ViewHiddenInfrastructureARPipePlacingViewController", "ViewHiddenInfrastructureARExplorerViewController", "ViewHiddenInfrastructureARCalibrationViewController" ] // Configure the elevation surface used to place drawn graphics relative to the ground. elevationSurface.elevationSources.append(elevationSource) elevationSource.load { [weak self] error in guard let self = self else { return } if let error = error { self.presentAlert(error: error) } } // Add a KVO to update the button states. graphicsObservation = pipeGraphicsOverlay.observe(\.graphics, options: .initial) { [weak self] overlay, _ in guard let self = self else { return } // 'NSMutableArray' has no member 'isEmpty'; check its count instead. let graphicsCount = overlay.graphics.count let hasGraphics = graphicsCount > 0 self.trashBarButtonItem.isEnabled = hasGraphics self.cameraBarButtonItem.isEnabled = hasGraphics } // Set location display. setStatus(message: "Adjusting to your current location…") locationDataSource.locationChangeHandlerDelegate = self locationDataSource.start { [weak self] error in guard let self = self else { return } if let error = error { self.presentAlert(error: error) } } } } // MARK: - Location change handler extension ViewHiddenInfrastructureARPipePlacingViewController: AGSLocationChangeHandlerDelegate { func locationDataSource(_ locationDataSource: AGSLocationDataSource, locationDidChange location: AGSLocation) { // Stop the location adjustment immediately after the first location update is received. let newViewpoint = AGSViewpoint(center: location.position!, scale: 1000) mapView.setViewpoint(newViewpoint, completion: nil) setStatus(message: "Tap add button to add pipes.") sketchBarButtonItem.isEnabled = true locationDataSource.locationChangeHandlerDelegate = nil locationDataSource.stop(completion: nil) } }
apache-2.0
8888ef6ec3aa11a4ea0bb888b2be96e0
43.840909
168
0.646325
5.130005
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Items/Rating/MoreRatingDetailsItem.swift
1
888
import UIKit class MoreRatingDetailsItem: NamedHotelDetailsItem { let moreHandler: (() -> Void)? init(moreCount: Int, moreHandler: (() -> Void)?) { self.moreHandler = moreHandler let name = String(format: NSLS("HL_HOTEL_DETAIL_RATING_DETAILS_MORE"), moreCount) super.init(name: name) } override func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: HLHotelDetailsRatingDetailsCell.hl_reuseIdentifier(), for: indexPath) as! HLHotelDetailsRatingDetailsCell cell.configureForMoreItem(self, columnCellStyle: .oneColumn) cell.first = first cell.last = last return cell } override func cellHeight(tableWidth: CGFloat) -> CGFloat { return HLHotelDetailsRatingDetailsCell.estimatedHeight(first, last: last) } }
mit
17e3a1f33a3c06db2b855e289f55423d
36
170
0.70045
4.41791
false
false
false
false
abelsanchezali/ViewBuilder
ViewBuilderDemo/ViewBuilderDemo/ViewControllers/LayoutTestScreenViewController.swift
1
3008
// // LayoutTestScreenViewController.swift // ViewBuilderDemo // // Created by Abel Sanchez on 9/24/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import UIKit import ViewBuilder public class LayoutTestScreenViewController: UIViewController { weak var actionButton: UIButton! override public func loadView() { view = DocumentBuilder.shared.load(Constants.bundle.path(forResource: "LayoutTestScreenView", ofType: "xml")!) actionButton = view.documentReferences!["actionButton"] as! UIButton actionButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(actionHandler))) } override public func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(composeHandler)) } override public func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if contentView == nil { createContentView() } } var contentView: UIView? = nil func createContentView() { contentView?.removeFromSuperview() if let path = Constants.bundle.path(forResource: "SampleCard5", ofType: "xml") { contentView = DocumentBuilder.shared.load(path, options: nil) if let subview = contentView { subview.verticalAlignment = .center subview.horizontalAlignment = .center subview.preferredSize = CGSize(width: 300, height: -1) view.addSubview(subview) view.sendSubviewToBack(subview) animateLayout() } } } func shuffleContentView() { guard let subview = contentView else { return } UIView.transition(with: subview, duration: 0.15, options: UIView.AnimationOptions.transitionCrossDissolve, animations: { (subview.documentReferences?["summaryLabel"] as? UILabel)?.text = Lorem.sentences(MathHelper.random() % 7 + 1) (subview.documentReferences?["insightLabel"] as? UILabel)?.text = Lorem.sentences(MathHelper.random() % 4 + 1) }, completion: nil) animateLayout() } func animateLayout() { UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: [.beginFromCurrentState], animations: { self.view.setNeedsLayout() self.view.layoutIfNeeded() }, completion: nil) } @objc func actionHandler() { shuffleContentView() } @objc func composeHandler() { NavigationHelper.presentDocumentVisualizer(self, path: Constants.bundle.path(forResource: "LayoutTestScreenView", ofType: "xml"), completion: nil) } }
mit
cec2d81362d936b7ea5f5138b1183153
35.228916
154
0.613236
5.247818
false
false
false
false
mirego/PinLayout
Tests/Common/AdjustSizeSpec.swift
1
48645
// Copyright (c) 2017 Luc Dion // 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 Quick import Nimble import PinLayout class AdjustSizeSpec: QuickSpec { override func spec() { var viewController: PViewController! var rootView: BasicView! var aView: BasicView! var aViewChild: BasicView! var bView: BasicView! var bViewChild: BasicView! /* root | - aView | | | - aViewChild | - bView | - bViewChild */ beforeEach { _pinlayoutSetUnitTest(scale: 2) Pin.lastWarningText = nil viewController = PViewController() viewController.view = BasicView() rootView = BasicView() viewController.view.addSubview(rootView) aView = BasicView() aView.sizeThatFitsExpectedArea = 40 * 40 rootView.addSubview(aView) aViewChild = BasicView() aView.addSubview(aViewChild) bView = BasicView() rootView.addSubview(bView) bViewChild = BasicView() bView.addSubview(bViewChild) rootView.frame = CGRect(x: 0, y: 0, width: 400, height: 400) aView.frame = CGRect(x: 140, y: 100, width: 100, height: 60) aViewChild.frame = CGRect(x: 10, y: 20, width: 50, height: 30) bView.frame = CGRect(x: 160, y: 200, width: 110, height: 80) bViewChild.frame = CGRect(x: 40, y: 10, width: 60, height: 20) } afterEach { _pinlayoutSetUnitTest(scale: nil) } describe("the result of the width(...) methods") { it("should adjust the width of aView") { aView.pin.width(35) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 35, height: 60.0))) } it("shouldn't adjust the width of aView due to a negative width") { aView.pin.width(-20) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100, height: 60.0))) } it("should adjust the width(percent: Percent) of aView") { aView.pin.width(50%) expect(aView.frame).to(equal(CGRect(x: 140, y: 100, width: 200, height: 60))) } it("should adjust the width(percent: Percent) of aView") { aView.pin.width(200%) expect(aView.frame).to(equal(CGRect(x: 140, y: 100, width: 800, height: 60))) } it("should not adjust the width(percent: Percent) of aView due to a negative width") { aView.pin.width(-20%) expect(aView.frame).to(equal(CGRect(x: 140, y: 100, width: 100, height: 60))) } it("should adjust the width(percent: Percent) of aView") { let unAttachedView = PView(frame: CGRect(x: 10, y: 10, width: 20, height: 30)) unAttachedView.pin.width(50%) expect(unAttachedView.frame).to(equal(CGRect(x: 10, y: 10, width: 20, height: 30))) } it("should adjust the width of aView") { aView.pin.width(of: aViewChild) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 60.0))) } it("should accept a width of 0") { aView.pin.width(0) expect(Pin.lastWarningText).to(beNil()) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 0.0, height: 60.0))) } it("should warn about negative width value") { aView.pin.width(-2) expect(Pin.lastWarningText).to(contain(["width", "won't be applied", "the width", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } it("should warn about NaN width value") { aView.pin.width(CGFloat.nan) expect(Pin.lastWarningText).to(contain(["width", "nan", "won't be applied", "the width", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } it("should warn about -NaN width value") { aView.pin.width(-CGFloat.nan) expect(Pin.lastWarningText).to(contain(["width", "nan", "won't be applied", "the width", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } it("should warn about infinity width value") { aView.pin.width(CGFloat.infinity) expect(Pin.lastWarningText).to(contain(["width", "inf", "won't be applied", "the width", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } it("should warn about -infinity width value") { aView.pin.width(-CGFloat.infinity) expect(Pin.lastWarningText).to(contain(["width", "inf", "won't be applied", "the width", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } } describe("the result of the height(...) methods") { it("should adjust the height of aView") { aView.pin.height(35) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 35.0))) } it("should not adjust the height of aView") { aView.pin.height(-20) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 60.0))) } it("should adjust the height of aView") { aView.pin.height(50%) expect(aView.frame).to(equal(CGRect(x: 140, y: 100, width: 100, height: 200))) } it("should adjust the height of aView") { aView.pin.height(200%) expect(aView.frame).to(equal(CGRect(x: 140, y: 100, width: 100, height: 800))) } it("should adjust the height of aView") { let unAttachedView = PView(frame: CGRect(x: 10, y: 10, width: 20, height: 30)) unAttachedView.pin.height(50%) expect(unAttachedView.frame).to(equal(CGRect(x: 10, y: 10, width: 20, height: 30))) } it("should adjust the height of aView") { aView.pin.height(of: aViewChild) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 30.0))) } it("should accept a height of 0") { aView.pin.height(0) expect(Pin.lastWarningText).to(beNil()) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 0.0))) } it("should warn about negative height value") { aView.pin.height(-2) expect(Pin.lastWarningText).to(contain(["height", "won't be applied", "the height", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } it("should warn about NaN height value") { aView.pin.height(CGFloat.nan) expect(Pin.lastWarningText).to(contain(["height", "nan", "won't be applied", "the height", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } it("should warn about -NaN height value") { aView.pin.height(-CGFloat.nan) expect(Pin.lastWarningText).to(contain(["height", "nan", "won't be applied", "the height", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } it("should warn about infinity height value") { aView.pin.height(CGFloat.infinity) expect(Pin.lastWarningText).to(contain(["height", "inf", "won't be applied", "the height", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } it("should warn about -infinity height value") { aView.pin.height(-CGFloat.infinity) expect(Pin.lastWarningText).to(contain(["height", "inf", "won't be applied", "the height", "must be greater than or equal to zero"])) expect(aView.frame).to(equal(CGRect(x: 140, y: 100.0, width: 100.0, height: 60.0))) } } describe("the result of the size(...) methods") { it("should adjust the size of aView") { aView.pin.size(CGSize(width: 25, height: 25)) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 25.0, height: 25.0))) } it("should adjust the size of aView") { aView.pin.size(100) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 100.0))) } it("should adjust the size of aView") { aView.pin.size(50%) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 200.0, height: 200.0))) } it("should warn that size()'s width won't be applied") { aView.pin.width(90).size(CGSize(width: 25, height: 25)) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 90.0, height: 25.0))) expect(Pin.lastWarningText).to(contain(["size", "width", "won't be applied", "value has already been set"])) } it("should warn that size()'s height won't be applied") { aView.pin.height(90).size(CGSize(width: 25, height: 25)) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 25.0, height: 90.0))) expect(Pin.lastWarningText).to(contain(["size", "height", "won't be applied", "value has already been set"])) } it("should adjust the size of aView by calling a size(...) method") { aView.pin.size(of: aViewChild) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 30.0))) } it("should warn that size(of)'s width won't be applied") { aView.pin.width(90).size(of: aViewChild) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 90.0, height: 30.0))) expect(Pin.lastWarningText).to(contain(["size", "width", "won't be applied", "value has already been set"])) } it("should warn that size()'s width won't be applied") { aView.pin.width(90).size(20) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 90.0, height: 20.0))) expect(Pin.lastWarningText).to(contain(["size", "width", "won't be applied", "value has already been set"])) } it("should warn that size()'s width won't be applied") { aView.pin.width(90).size(50%) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 90.0, height: 200.0))) expect(Pin.lastWarningText).to(contain(["size", "width", "won't be applied", "value has already been set"])) } } // // fitSize // #if os(iOS) || os(tvOS) describe("the result of the fitSize() method") { it("should adjust the size of aView by calling fitSize() method") { aView.pin.size(CGSize(width: 20, height: 100)).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 20.0, height: 80.0))) } it("should adjust the size of aView by calling sizeToFit(.height) method") { aView.pin.size(CGSize(width: 20, height: 100)).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 16.0, height: 100.0))) } it("should adjust the size of aView by calling sizeToFit(.width) method") { aView.pin.size(CGSize(width: 20, height: 100)).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 20.0, height: 80.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.size(CGSize(width: 20, height: 100)).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 20.0, height: 80.0))) } it("should adjust the size and position the view by calling center(), height() and fitSize()") { aViewChild.pin.center(to: aView.anchor.center).height(40).sizeToFit(.height) expect(aViewChild.frame).to(equal(CGRect(x: 30.0, y: 10.0, width: 40.0, height: 40.0))) } it("should adjust the size and position the view by calling center(), width() and fitSize()") { aViewChild.pin.center(to: aView.anchor.center).width(20).sizeToFit(.width) expect(aViewChild.frame).to(equal(CGRect(x: 40.0, y: -10.0, width: 20.0, height: 80.0))) } } describe("the result of the fitSize() method when pinning left and right edges") { it("should adjust the size with fitSize()") { aView.pin.left(20).right(80).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 100.0, width: 300.0, height: 5.5))) } it("should adjust the size with fitSize()") { aView.pin.left(20).right(80).marginLeft(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 100.0, width: 290.0, height: 6))) } it("should adjust the size with fitSize()") { aView.pin.left(20).right(80).marginRight(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 100.0, width: 290.0, height: 6.0))) } it("should adjust the size with fitSize()") { aView.pin.left(20).right(80).marginLeft(10).marginRight(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 100.0, width: 280.0, height: 6.0))) } it("should adjust the size with fitSize()") { aView.pin.left(20).right(80).marginLeft(10).marginRight(10).sizeToFit(.width).justify(.center) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 100.0, width: 280.0, height: 6.0))) } it("should adjust the size with fitSize()") { aView.pin.left(20).right(80).marginLeft(10).marginRight(10).sizeToFit(.width).justify(.right) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 100.0, width: 280.0, height: 6.0))) } } describe("the result of the fitSize() method when pinning top and bottom edges") { it("should adjust the size with fitSize()") { aView.pin.top(20).bottom(80).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 20.0, width: 5.5, height: 300))) } it("should adjust the size with fitSize()") { aView.pin.top(20).bottom(80).marginTop(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 30.0, width: 6, height: 290))) } it("should adjust the size with fitSize()") { aView.pin.top(20).bottom(80).marginBottom(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 20.0, width: 6, height: 290))) } it("should adjust the size with fitSize()") { aView.pin.top(20).bottom(80).marginTop(10).marginBottom(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 30.0, width: 6, height: 280))) } } describe("the result of the fitSize() method when pinning right edge + width") { it("should adjust the size with fitSize() and distribute extra width") { aView.pin.right(100).width(200).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 100.0, y: 100.0, width: 200, height: 8))) } it("should adjust the size with fitSize() and distribute extra width") { aView.pin.right(100).width(200).marginLeft(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 100.0, y: 100.0, width: 200, height: 8))) } it("should adjust the size with fitSize() and distribute extra width") { aView.pin.right(100).width(200).marginRight(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 90.0, y: 100.0, width: 200, height: 8))) } it("should adjust the size with fitSize() and distribute extra width") { aView.pin.right(100).width(200).marginLeft(10).marginRight(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 90.0, y: 100.0, width: 200, height: 8))) } } describe("the result of the fitSize() method when pinning right edge + width + pinEdges()") { it("should adjust the size with fitSize() and distribute extra width") { aView.pin.right(100).width(200).pinEdges().sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 100.0, y: 100.0, width: 200, height: 8))) } it("should adjust the size with fitSize() and distribute extra width") { aView.pin.right(100).width(200).pinEdges().marginLeft(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 110.0, y: 100.0, width: 190, height: 8.5))) } it("should adjust the size with fitSize() and distribute extra width") { aView.pin.right(100).width(200).pinEdges().marginRight(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 100.0, y: 100.0, width: 190, height: 8.5))) } it("should adjust the size with fitSize() and distribute extra width") { aView.pin.right(100).width(200).pinEdges().marginLeft(10).marginRight(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 110.0, y: 100.0, width: 180, height: 9))) } it("should adjust the size with fitSize() and distribute extra width") { aView.pin.right(100).width(200).pinEdges().marginLeft(10).marginRight(10).sizeToFit(.width).justify(.left) expect(aView.frame).to(equal(CGRect(x: 110.0, y: 100.0, width: 180, height: 9))) } it("should adjust the size with fitSize() and distribute extra width") { aView.pin.bottom(100).height(200).pinEdges().marginTop(10).marginBottom(10).sizeToFit(.height).justify(.left) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 110.0, width: 9, height: 180))) } it("should adjust the size with fitSize() and distribute extra width") { aView.pin.bottom(100).height(200).pinEdges().marginTop(10).marginBottom(10).sizeToFit(.height).justify(.left) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 110.0, width: 9, height: 180))) } } describe("the result of the fitSize() method when pinning bottom edge + height") { it("should adjust the size with fitSize() and distribute extra height") { aView.pin.bottom(100).height(200).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 8, height: 200))) } it("should adjust the size with fitSize() and distribute extra height") { aView.pin.bottom(100).height(200).marginTop(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 8, height: 200))) } it("should adjust the size with fitSize() and distribute extra height") { aView.pin.bottom(100).height(200).marginBottom(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 90.0, width: 8, height: 200))) } it("should adjust the size with fitSize() and distribute extra height") { aView.pin.bottom(100).height(200).marginTop(10).marginBottom(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 90.0, width: 8, height: 200))) } } describe("the result of the fitSize() method when pinning bottom edge + height + pinEdges()") { it("should adjust the size with fitSize() and distribute extra height") { aView.pin.bottom(100).height(200).pinEdges().sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 8, height: 200))) } it("should adjust the size with fitSize() and distribute extra height") { aView.pin.bottom(100).height(200).pinEdges().marginTop(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 110.0, width: 8.5, height: 190))) } it("should adjust the size with fitSize() and distribute extra height") { aView.pin.bottom(100).height(200).pinEdges().marginBottom(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 8.5, height: 190))) } it("should adjust the size with fitSize() and distribute extra height") { aView.pin.bottom(100).height(200).pinEdges().marginTop(10).marginBottom(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 110.0, width: 9, height: 180))) } } describe("the result of the fitSize() method when pinning top, left, bottom and right edges") { it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 20.0, width: 200.0, height: 8))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 20.0, width: 190.0, height: 8.5))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginRight(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 20.0, width: 190.0, height: 8.5))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginRight(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 20.0, width: 180.0, height: 9.0))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginTop(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 30.0, width: 200.0, height: 8))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginBottom(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 20.0, width: 200.0, height: 8.0))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginBottom(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 20.0, width: 190.0, height: 8.5))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginTop(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 30.0, width: 190.0, height: 8.5))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginBottom(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 20.0, width: 190.0, height: 8.5))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginTop(10).marginBottom(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 30.0, width: 190.0, height: 8.5))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginTop(10).marginBottom(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 30.0, width: 190.0, height: 8.5))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginRight(10).marginTop(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 30.0, width: 180.0, height: 9))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginRight(10).marginBottom(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 20.0, width: 180.0, height: 9.0))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginRight(10).marginTop(10).marginBottom(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 30.0, width: 180.0, height: 9.0))) } } describe("the result of the fitSize() with justify() or align()") { it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginRight(10).marginTop(10).sizeToFit(.width).justify(.left) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 30.0, width: 180.0, height: 9))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginRight(10).marginTop(10).sizeToFit(.width).justify(.center) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 30.0, width: 180.0, height: 9))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(15).marginRight(5).marginTop(10).sizeToFit(.width).justify(.right) expect(aView.frame).to(equal(CGRect(x: 35.0, y: 30.0, width: 180.0, height: 9))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginRight(10).marginTop(10).sizeToFit(.width).align(.top) expect(aView.frame).to(equal(CGRect(x: 30.0, y: 30.0, width: 180.0, height: 9))) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(180).right(180).marginLeft(10).marginRight(10).marginTop(10).sizeToFit(.width).align(.center) expect(aView.frame).to(beCloseTo(CGRect(x: 30.0, y: 120.5, width: 180.0, height: 9.0), within: 0.5)) } it("should adjust the size with fitSize()") { aView.pin.top(20).left(20).bottom(80).right(180).marginLeft(15).marginRight(5).marginTop(10).sizeToFit(.width).align(.bottom) expect(aView.frame).to(equal(CGRect(x: 35.0, y: 311.0, width: 180.0, height: 9.0))) } it("should adjust the size with fitSize()") { aView.pin.top(20).bottom(80).marginTop(10).marginBottom(10).sizeToFit(.height).align(.center) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 30.0, width: 6.0, height: 280.0))) } it("should adjust the size with fitSize()") { aView.pin.top(20).bottom(80).marginTop(10).marginBottom(10).sizeToFit(.height).align(.bottom) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 30.0, width: 6.0, height: 280.0))) } } // // fitSize() // describe("the result of the fitSize() method") { it("should adjust the size of aView by calling fitSize() method") { aView.pin.width(100).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 16.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.height(100).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 16.0, height: 100.0))) } it("should adjust the size of aView by calling fitSize()") { aView.pin.top(0).height(70).width(100).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 0.0, width: 100.0, height: 16.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.width(100).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 16.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.height(90).width(100).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 16.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.width(of: aViewChild).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 32.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.width(80).width(of: aViewChild).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 80.0, height: 20.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.height(100).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 16.0, height: 100.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.height(of: aViewChild).sizeToFit(.height) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 53.3333333333333, height: 30.0), within: 0.4)) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.width(90).height(of: aViewChild).sizeToFit(.width) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 90.0, height: 17.6), within: 0.4)) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.size(of: aViewChild) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 30.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.size(of: aViewChild).sizeToFit(.width) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 32.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.size(of: aViewChild).sizeToFit(.width).maxHeight(30) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 30.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.width(90).size(of: aViewChild).sizeToFit(.width) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 90.0, height: 17.6), within: 0.4)) } } // // fitSize && min/max width/height // describe("the result of the fitSize() method when min/max width/height are set") { it("should adjust the size of aView by calling fitSize() method") { aView.pin.width(100).minHeight(20).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 20.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.width(100).maxHeight(10).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 10.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.height(100).maxWidth(10).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 10.0, height: 100.0))) } it("should adjust the size of aView by calling fitSize() method") { aView.pin.height(100).minWidth(20).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 20.0, height: 100.0))) } // luc pq ci bas != ci haut? it("should adjust the size of aView by calling fitSize() method") { aView.pin.height(100).minWidth(20).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 20.0, height: 100.0))) } } // // fitHeight && fitWidth // describe("the result of the sizeToFit(.height) && sizeToFit(.width)") { it("should warn method") { aView.pin.width(100).sizeToFit(.height).sizeToFit(.height) expect(Pin.lastWarningText).to(contain(["sizeToFit(.height)", "won't be applied", "conflicts with sizeToFit(.height)"])) } it("should warn method") { aView.pin.width(100).aspectRatio(2).sizeToFit(.width) expect(Pin.lastWarningText).to(contain(["sizeToFit(.width)", "won't be applied", "aspectRatio(2.0)"])) } it("should warn method") { aView.pin.sizeToFit(.width).aspectRatio(2) expect(Pin.lastWarningText).to(contain([" aspectRatio(2.0)", "won't be applied", "conflicts with sizeToFit(.width)"])) } it("should warn method") { aView.pin.width(100).sizeToFit(.width).aspectRatio(2) expect(Pin.lastWarningText).to(contain([" aspectRatio(2.0)", "won't be applied", "conflicts with sizeToFit(.width)"])) } } // // fitWidth // describe("the result of the sizeToFit(.width)") { it("should adjust the aView") { aView.pin.sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 16.0))) } it("should adjust the aView") { aView.pin.width(50).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 32.0))) } it("should adjust the aView") { aView.pin.minWidth(160).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 160.0, height: 10.0))) } it("should adjust the aView") { aView.pin.maxWidth(50).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 32.0))) } it("should adjust the aView") { aView.pin.size(CGSize(width: 20, height: 100)).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 20.0, height: 80.0))) } it("should adjust the aView") { aView.pin.size(CGSize(width: 20, height: 100)).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 16.0, height: 100.0))) } } // // fitHeight // describe("the result of the sizeToFit(.height)") { it("should adjust the aView") { aView.pin.sizeToFit(.height) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 27, height: 60.0), within: 0.5)) } it("should adjust the aView") { aView.pin.height(50).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 32.0, height: 50.0))) } it("should adjust the aView") { aView.pin.minHeight(160).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 10.0, height: 160.0))) } it("should adjust the aView") { aView.pin.maxHeight(50).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 32.0, height: 50.0))) } } // // sizeToFit(.width) // describe("the result of the sizeToFit(.width) when the value return by sizeThatFits() is smaller then the width") { it("should adjust the aView") { aView.pin.sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 16.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.width(50).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 40.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.width(50).sizeToFit(.widthFlexible) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 40.0, height: 40.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.width(50).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 40.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.size(CGSize(width: 20, height: 100)).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 20.0, height: 160.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.size(CGSize(width: 20, height: 100)).sizeToFit(.widthFlexible) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 10.0, height: 160.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.size(CGSize(width: 20, height: 100)).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 20.0, height: 160.0))) } } // // sizeToFit(.height) // describe("the result of the sizeToFit(.height) when the value return by sizeThatFits() is smaller then the width") { it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 32.0, height: 60.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.sizeToFit(.heightFlexible) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 32.0, height: 50.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 32.0, height: 60.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.sizeToFit(.heightFlexible) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 32.0, height: 50.0))) } } // // fitSize() / sizeToFit(..) // describe("the result of the fitSize()") { it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.width(50).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 40.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.width(50).sizeToFit(.width) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 40.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = 10 aView.pin.width(50).sizeToFit(.width) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 26.6), within: 0.5)) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = 10 aView.pin.width(50).sizeToFit(.width) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 26.6), within: 0.5)) } it("should adjust the aView") { aView.pin.height(50).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 32.0, height: 50.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.height(50).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 40.0, height: 50.0))) } it("should adjust the aView") { aView.pin.height(50).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 32.0, height: 50.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = -10 aView.pin.height(50).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 40.0, height: 50.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = 10 aView.pin.height(30).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 40.0, height: 30.0))) } it("should adjust the aView") { aView.sizeThatFitSizeOffset = 10 aView.pin.height(30).sizeToFit(.height) expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 40.0, height: 30.0))) } it("should adjust the aView") { aView.pin.width(50).sizeToFit(.width) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 32.0), within: 0.5)) } it("should adjust the height using the current width") { aView.frame.size = CGSize(width: 50, height: 0) aView.pin.sizeToFit(.width) expect(aView.frame).to(beCloseTo(CGRect(x: 140.0, y: 100.0, width: 50.0, height: 32.0), within: 0.5)) } } // // sizeToFit() // describe("the result of the sizeToFit()") { it("should adjust the aView") { _pinlayoutSetUnitTest(scale: 3) aView.pin.sizeToFit().center() expect(aView.frame).to(beCloseTo(CGRect(x: 182.6667, y: 177.6667, width: 35.0, height: 45.0), within: 0.1)) } it("should produce the same size as the built-in sizeToFit() method") { _pinlayoutSetUnitTest(scale: nil) let label = PLabel(frame: CGRect.zero) label.text = "Lorem ipsum dolor sit amet" label.pin.sizeToFit() let size = label.bounds.size label.bounds.size = CGSize.zero label.sizeToFit() expect(size).to(equal(label.bounds.size)) } it("should produce the same size as the built-in sizeToFit() method when there is a transform applied") { _pinlayoutSetUnitTest(scale: nil) let label = PLabel(frame: CGRect.zero) label.text = "Lorem ipsum dolor sit amet" label.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) label.pin.sizeToFit() let size = label.bounds.size label.bounds.size = CGSize.zero label.sizeToFit() expect(size).to(equal(label.bounds.size)) } } #endif } }
mit
ec93556a34c5c7072ba26a1b9055c45e
49.409326
148
0.533539
3.886936
false
false
false
false
zwaldowski/ParksAndRecreation
Swift-2/Geometry.playground/Contents.swift
1
3724
//: ## Geometry Extensions import UIKit import XCPlayground let demoView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 100)) demoView.translatesAutoresizingMaskIntoConstraints = false demoView.backgroundColor = UIColor.redColor() let angle = CGFloat(M_PI_2) // toRadians(90) //: ### `CATransform3D` //: //: Initializers CATransform3D(tx: 12) CATransform3D(sx: 1.5, sy: 1.5) CATransform3D(scale: 1.5) CATransform3D(angle: angle, x: 12, y: 0, z: 0) CATransform3D(CATransform3D(scale: 2), CATransform3D(ty: 12)) CATransform3D(CGAffineTransform(scale: 2), CGAffineTransform(ty: 12)) //: Properties CATransform3D.identity.isIdentity CATransform3D(sx: 1.5, sy: 1.5, sz: 1).affineTransform //: Transformations and Equatable CATransform3D.identity.translated(x: 12) == CATransform3D(tx: 12) CATransform3D.identity.scaled(1.5) == CATransform3D(scale: 1.5) CATransform3D.identity.rotated(by: CGFloat(M_PI_2), x: 24, y: 0, z: 0) == CATransform3D(angle: CGFloat(M_PI_2), x: 24, y: 0, z: 0) //: Arithmetic -CATransform3D(scale: 2) == CATransform3D(scale: 0.5) let add1 = CATransform3D(tx: 12) + CATransform3D(scale: 2) let subtract1 = CATransform3D(tx: 12) - CATransform3D(scale: 2) let add2 = CATransform3D(tx: 12) + CGAffineTransform(scale: 2) //: ### `CGAffineTransform` //: //: Initializers let baseTransform1 = CGAffineTransform(scale: 2) let baseTransform2 = CGAffineTransform(tx: 12) let baseTransform3 = CGAffineTransform(sx: 1.5) CGAffineTransform(baseTransform1, baseTransform2) //: Printing String(baseTransform1) //: Properties CGAffineTransform.identity.isIdentity //: Transformations and Equatable CGAffineTransform.identity.translated(x: 12) == CGAffineTransform(tx: 12) CGAffineTransform.identity.scaled(1.5) == CGAffineTransform(scale: 1.5) CGAffineTransform.identity.rotated(by: angle) == CGAffineTransform(scale: angle) //: Arithmetic -CGAffineTransform(scale: 2) == CGAffineTransform(scale: 0.5) CGAffineTransform(tx: 12) + CGAffineTransform(scale: 2) CGAffineTransform(tx: 12) - CGAffineTransform(scale: 2) //: Application let applyTransform = CGAffineTransform(scale: 2) CGRect(x: 12, y: 12, width: 24, height: 48) * applyTransform CGPoint(x: 12, y: 12) * applyTransform CGSize(width: 24, height: 48) * applyTransform //: ### `CGPoint` let basePoint = CGPoint(x: 16, y: 24) let altPoint = CGPoint(x: 24, y: 16) //: Printing String(basePoint) //: Vector arithmetic basePoint + altPoint basePoint - altPoint basePoint + altPoint basePoint - altPoint //: Scalar arithmetic basePoint * 2 basePoint / 2 //: Trigonometry basePoint...altPoint basePoint.midpoint(altPoint) //: ### CGRect let baseRect = CGRect(x: 32, y: 32, width: 512, height: 128) //: Printing String(baseRect) //: Rect insetting let insetRect = demoView.frame.rectByInsetting(UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)) //: Corner manipulations let corners = baseRect.corners let rectWithCorners = CGRect(corners: corners) let newRect = baseRect.mapCorners { $0 + CGPoint(x: 12, y: 12) } //: ### `CGSize` let baseSize = CGSize(width: 48, height: 96) let altSize = CGSize(width: 96, height: 48) //: Printing String(baseSize) //: Vector arithmetic baseSize + altSize baseSize - altSize baseSize + altSize baseSize - altSize //: Scalar arithmetic baseSize * 2 baseSize / 2 //: ### `UIEdgeInsets` //: //: Extrema let leftInsets = UIEdgeInsets(top: 24, left: 24, bottom: 24, right: 24) let rightInsets = UIEdgeInsets(top: 12, left: 0, bottom: 0, right: 0) min(leftInsets, rightInsets) max(leftInsets, rightInsets) min(leftInsets, rightInsets, edges: .Top) max(leftInsets, rightInsets, edges: .Top) //: Rect insetting let inset1 = baseRect.rectByInsetting(UIEdgeInsets(top: 2, left: 2, bottom: 4, right: 4))
mit
be8b48668e38c21b6979232319cde382
27
130
0.733888
3.243902
false
false
false
false
mugby99/CardDeckExample
CardDeckExample/ViewController.swift
1
9207
// // ViewController.swift // CardDeckExample // // Created by Uribe, Martin on 1/16/17. // Copyright © 2017 MUGBY. All rights reserved. // import UIKit extension MutableCollection where Indices.Iterator.Element == Index { /// Shuffles the contents of this collection. mutating func shuffle() { let c = count guard c > 1 else { return } for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount))) guard d != 0 else { continue } let i = index(firstUnshuffled, offsetBy: d) swap(&self[firstUnshuffled], &self[i]) } } } typealias Listener = ([Card]) -> Void public enum CardSuit { case Clubs, Diamonds, Hearts, Spades func stringRepresentation() -> String { switch self { case .Clubs: return "\u{2663}" case .Diamonds: return "\u{2666}" case .Hearts: return "\u{2665}" case .Spades: return "\u{2660}" } } func rank() -> Int { switch self { case .Clubs: return 0 case .Diamonds: return 1 case .Hearts: return 2 case .Spades: return 3 } } } public enum CardDeck { case Red, Blue func reuseIdentifier() -> String { switch self { case .Red: return "RedDeckCard" case .Blue: return "BlueDeckCard" } } } public struct Card { let suit: CardSuit! let rank: String! let deck: CardDeck! func stringRepresentation() -> String { return "\(suit.stringRepresentation()) " + rank } static func intFromRank(rank: String) -> Int { switch rank { case "A": return 1 case "J": return 11 case "Q": return 12 case "K": return 13 default: return Int(rank) ?? -1 } } static func rankFromInt(rank: Int) -> String { switch rank { case 1: return "A" case 11: return "J" case 12: return "Q" case 13: return "K" default: return String(rank) } } } public struct Deck { var clubsDeck = [Card]() var diamondsDeck = [Card]() var heartsDeck = [Card]() var spadesDeck = [Card]() func deckForSection(section: Int) -> [Card] { switch section { case 0: return clubsDeck case 1: return diamondsDeck case 2: return heartsDeck case 3: return spadesDeck default: return [] } } } class ViewController: UIViewController { @IBOutlet weak var redDeckCollectionView: UICollectionView! @IBOutlet weak var blueDeckCollectionView: UICollectionView! @IBOutlet weak var scrambledDeckCollectionView: UICollectionView! var redDeck = Deck() var blueDeck = Deck() var scrambledDeck = [Card]() let standard52DeckRanks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] fileprivate var listener: Listener! var mergeProcessCounter = [Int:Int]() var threadSleep: UInt32 = 1 var currentSubArray:[Card]? override func viewDidLoad() { super.viewDidLoad() initListener() // Do any additional setup after loading the view, typically from a nib. let suits: [CardSuit] = [.Clubs, .Diamonds, .Hearts, .Spades] let decks: [CardDeck] = [.Red, .Blue] for deck in decks { for suit in suits { for rank in 1...13 { scrambledDeck.append(Card(suit: suit, rank: Card.rankFromInt(rank: rank), deck: deck)) } } } scrambledDeck.shuffle() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initListener() { listener = { [weak self] sortedSubArray in self?.currentSubArray = sortedSubArray guard let levelCounter = self?.mergeProcessCounter[sortedSubArray.count] as Int? else { self?.mergeProcessCounter[sortedSubArray.count] = 1 self?.scrambledDeckCollectionView.reloadData() self?.scrambledDeck.replaceSubrange(0..<sortedSubArray.count, with: sortedSubArray) self?.scrambledDeckCollectionView.reloadData() return } let startIndex = levelCounter*sortedSubArray.count if (startIndex + sortedSubArray.count) <= self?.scrambledDeck.count ?? 0 { self?.mergeProcessCounter[sortedSubArray.count] = levelCounter + 1 self?.scrambledDeckCollectionView.reloadData() self?.scrambledDeck.replaceSubrange(startIndex..<(startIndex + sortedSubArray.count), with: sortedSubArray) self?.scrambledDeckCollectionView.reloadData() } } } @IBAction func reorderDecks(_ sender: Any) { reorderDecks() } @IBAction func scrambleDecks(_ sender: Any) { listener = nil initListener() mergeProcessCounter.removeAll() scrambledDeck.shuffle() scrambledDeckCollectionView.reloadData() scrambledDeckCollectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: true) } func reorderDecks() { mergeProcessCounter.removeAll() listener = nil initListener() DispatchQueue.global(qos: .background).async { let deck = self.scrambledDeck self.scrambledDeck = deck.mergeSortWithListener(listener: self.listener, threadSleep: self.threadSleep) } } func threadSleepStringForRow(row: Int) -> String { switch row { case 0: return "0" case 1: return "0.5" case 2: return "1" case 3: return "1.5" default: return "0" } } func threadSleepIntForRow(row: Int) -> useconds_t { let second: Double = 1000000 return UInt32(Double(threadSleepStringForRow(row: row))! * second) } } extension ViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { if collectionView == scrambledDeckCollectionView { return 1 } return 4 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch collectionView { case scrambledDeckCollectionView: return scrambledDeck.count case redDeckCollectionView: return redDeck.deckForSection(section: section).count case blueDeckCollectionView: return blueDeck.deckForSection(section: section).count default: return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var card: Card! switch collectionView { case scrambledDeckCollectionView: card = scrambledDeck[indexPath.item] case redDeckCollectionView: card = redDeck.deckForSection(section: indexPath.section)[indexPath.item] case blueDeckCollectionView: card = blueDeck.deckForSection(section: indexPath.section)[indexPath.item] default: return UICollectionViewCell() } guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: card.deck.reuseIdentifier(), for: indexPath) as? CardCell else { return UICollectionViewCell() } cell.cardLabel.text = card.stringRepresentation() cell.alpha = 1 if mergeProcessCounter.count > 0 && currentSubArray != nil { if currentSubArray!.contains(scrambledDeck[indexPath.row]) { cell.alpha = 0.5 } } return cell } } extension ViewController: UICollectionViewDelegate { } extension ViewController: UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return component == 0 ? 1 : 4 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0 { return "Thread Sleep:" } else { return threadSleepStringForRow(row: row) } } } extension ViewController: UIPickerViewDelegate { func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { threadSleep = threadSleepIntForRow(row: row) } }
mit
f88c88c5126fc17a3f255f0010317e1c
28.50641
145
0.580382
4.663627
false
false
false
false
sschiau/swift
test/IRGen/big_types_corner_cases.swift
2
17840
// XFAIL: CPU=powerpc64le // RUN: %target-swift-frontend -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // REQUIRES: optimized_stdlib public struct BigStruct { var i0 : Int32 = 0 var i1 : Int32 = 1 var i2 : Int32 = 2 var i3 : Int32 = 3 var i4 : Int32 = 4 var i5 : Int32 = 5 var i6 : Int32 = 6 var i7 : Int32 = 7 var i8 : Int32 = 8 } func takeClosure(execute block: () -> Void) { } class OptionalInoutFuncType { private var lp : BigStruct? private var _handler : ((BigStruct?, Error?) -> ())? func execute(_ error: Error?) { var p : BigStruct? var handler: ((BigStruct?, Error?) -> ())? takeClosure { p = self.lp handler = self._handler self._handler = nil } handler?(p, error) } } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} i32 @main(i32, i8**) // CHECK: call void @llvm.lifetime.start // CHECK: call void @llvm.memcpy // CHECK: call void @llvm.lifetime.end // CHECK: ret i32 0 let bigStructGlobalArray : [BigStruct] = [ BigStruct() ] // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal swiftcc void @"$s22big_types_corner_cases21OptionalInoutFuncTypeC7executeyys5Error_pSgFyyXEfU_"(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_Sg* nocapture dereferenceable({{.*}}) // CHECK: call void @"$s22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOe // CHECK: call void @"$s22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOy // CHECK: ret void public func f1_returns_BigType(_ x: BigStruct) -> BigStruct { return x } public func f2_returns_f1() -> (_ x: BigStruct) -> BigStruct { return f1_returns_BigType } public func f3_uses_f2() { let x = BigStruct() let useOfF2 = f2_returns_f1() let _ = useOfF2(x) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10f3_uses_f2yyF"() // CHECK: call swiftcc void @"$s22big_types_corner_cases9BigStructVACycfC"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret // CHECK: call swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"() // CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void public func f4_tuple_use_of_f2() { let x = BigStruct() let tupleWithFunc = (f2_returns_f1(), x) let useOfF2 = tupleWithFunc.0 let _ = useOfF2(x) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18f4_tuple_use_of_f2yyF"() // CHECK: [[TUPLE:%.*]] = call swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"() // CHECK: [[TUPLE_EXTRACT:%.*]] = extractvalue { i8*, %swift.refcounted* } [[TUPLE]], 0 // CHECK: [[CAST_EXTRACT:%.*]] = bitcast i8* [[TUPLE_EXTRACT]] to void (%T22big_types_corner_cases9BigStructV*, %T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[CAST_EXTRACT]](%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself %{{.*}}) // CHECK: ret void public class BigClass { public init() { } public var optVar: ((BigStruct)-> Void)? = nil func useBigStruct(bigStruct: BigStruct) { optVar!(bigStruct) } } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases8BigClassC03useE6Struct0aH0yAA0eH0V_tF"(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}), %T22big_types_corner_cases8BigClassC* swiftself) // CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[BITCAST]](%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %swift.refcounted* swiftself // CHECK: ret void public struct MyStruct { public let a: Int public let b: String? } typealias UploadFunction = ((MyStruct, Int?) -> Void) -> Void func takesUploader(_ u: UploadFunction) { } class Foo { func blam() { takesUploader(self.myMethod) // crash compiling this } func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { } } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} linkonce_odr hidden swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases3FooC8myMethodyyyAA8MyStructV_SitXEFTc"(%T22big_types_corner_cases3FooC*) // CHECK: getelementptr inbounds %T22big_types_corner_cases3FooC, %T22big_types_corner_cases3FooC* // CHECK: getelementptr inbounds void (i8*, %swift.opaque*, %T22big_types_corner_cases3FooC*)*, void (i8*, %swift.opaque*, %T22big_types_corner_cases3FooC*)** // CHECK: call noalias %swift.refcounted* @swift_allocObject(%swift.type* getelementptr inbounds (%swift.full_boxmetadata, %swift.full_boxmetadata* // CHECK: ret { i8*, %swift.refcounted* } public enum LargeEnum { public enum InnerEnum { case simple(Int64) case hard(Int64, String?, Int64) } case Empty1 case Empty2 case Full(InnerEnum) } public func enumCallee(_ x: LargeEnum) { switch x { case .Full(let inner): print(inner) case .Empty1: break case .Empty2: break } } // CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10enumCalleeyAA9LargeEnumOF"(%T22big_types_corner_cases9LargeEnumO* noalias nocapture dereferenceable({{.*}})) #0 { // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO05InnerF0O // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: $ss5print_9separator10terminatoryypd_S2StF // CHECK-64: ret void // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal swiftcc void @"$s22big_types_corner_cases8SuperSubC1fyyFAA9BigStructVycfU_"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret, %T22big_types_corner_cases8SuperSubC*) // CHECK-64: [[ALLOC1:%.*]] = alloca %T22big_types_corner_cases9BigStructV // CHECK-64: [[ALLOC2:%.*]] = alloca %T22big_types_corner_cases9BigStructV // CHECK-64: [[ALLOC3:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg // CHECK-64: call swiftcc void @"$s22big_types_corner_cases9SuperBaseC4boomAA9BigStructVyF"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret [[ALLOC1]], %T22big_types_corner_cases9SuperBaseC* swiftself {{.*}}) // CHECK: ret void class SuperBase { func boom() -> BigStruct { return BigStruct() } } class SuperSub : SuperBase { override func boom() -> BigStruct { return BigStruct() } func f() { let _ = { nil ?? super.boom() } } } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10MUseStructV16superclassMirrorAA03BigF0VSgvg"(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret, %T22big_types_corner_cases10MUseStructV* noalias nocapture swiftself dereferenceable({{.*}})) // CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg // CHECK: [[LOAD:%.*]] = load %swift.refcounted*, %swift.refcounted** %.callInternalLet.data // CHECK: call swiftcc void %7(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret [[ALLOC]], %swift.refcounted* swiftself [[LOAD]]) // CHECK: ret void public struct MUseStruct { var x = BigStruct() public var superclassMirror: BigStruct? { return callInternalLet() } internal let callInternalLet: () -> BigStruct? } // CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, %Ts9SubstringV }>* noalias nocapture sret) #0 { // CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, [4 x i8], %Ts9SubstringV }>* noalias nocapture sret) #0 { // CHECK: alloca %TSs // CHECK: alloca %TSs // CHECK: ret void public func stringAndSubstring() -> (String, Substring) { let s = "Hello, World" let a = Substring(s).dropFirst() return (s, a) } func bigStructGet() -> BigStruct { return BigStruct() } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases11testGetFuncyyF"() // CHECK: ret void public func testGetFunc() { let testGetPtr: @convention(thin) () -> BigStruct = bigStructGet } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases7TestBigC4testyyF"(%T22big_types_corner_cases7TestBigC* swiftself) // CHECK: [[CALL1:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$sSayy22big_types_corner_cases9BigStructVcSgGMD" // CHECK: [[CALL2:%.*]] = call i8** @"$sSayy22big_types_corner_cases9BigStructVcSgGSayxGSlsWl // CHECK: call swiftcc void @"$sSlsE10firstIndex5where0B0QzSgSb7ElementQzKXE_tKF"(%TSq.{{.*}}* noalias nocapture sret {{.*}}, i8* bitcast (i1 (%T22big_types_corner_cases9BigStructVytIegnr_Sg*, %swift.refcounted*, %swift.error**)* @"$s22big_types_corner_cases9BigStructVIegy_SgSbs5Error_pIggdzo_ACytIegnr_SgSbsAE_pIegndzo_TRTA" to i8*), %swift.opaque* {{.*}}, %swift.type* [[CALL1]], i8** [[CALL2]], %swift.opaque* noalias nocapture swiftself // CHECK: ret void // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases7TestBigC5test2yyF"(%T22big_types_corner_cases7TestBigC* swiftself) // CHECK: [[CALL1:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$sSaySS2ID_y22big_types_corner_cases9BigStructVcSg7handlertGMD" // CHECK: [[CALL2:%.*]] = call i8** @"$sSaySS2ID_y22big_types_corner_cases9BigStructVcSg7handlertGSayxGSlsWl" // CHECK: call swiftcc void @"$sSlss16IndexingIteratorVyxG0B0RtzrlE04makeB0ACyF"(%Ts16IndexingIteratorV* noalias nocapture sret {{.*}}, %swift.type* [[CALL1]], i8** [[CALL2]], %swift.opaque* noalias nocapture swiftself {{.*}}) // CHECK: ret void class TestBig { typealias Handler = (BigStruct) -> Void func test() { let arr = [Handler?]() let d = arr.firstIndex(where: { _ in true }) } func test2() { let arr: [(ID: String, handler: Handler?)] = [] for (_, handler) in arr { takeClosure { handler?(BigStruct()) } } } } struct BigStructWithFunc { var incSize : BigStruct var foo: ((BigStruct) -> Void)? } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases20UseBigStructWithFuncC5crashyyF"(%T22big_types_corner_cases20UseBigStructWithFuncC* swiftself) // CHECK: call swiftcc void @"$s22big_types_corner_cases20UseBigStructWithFuncC10callMethod // CHECK: ret void class UseBigStructWithFunc { var optBigStructWithFunc: BigStructWithFunc? func crash() { guard let bigStr = optBigStructWithFunc else { return } callMethod(ptr: bigStr.foo) } private func callMethod(ptr: ((BigStruct) -> Void)?) -> () { } } struct BiggerString { var str: String var double: Double } struct LoadableStructWithBiggerString { public var a1: BiggerString public var a2: [String] public var a3: [String] } class ClassWithLoadableStructWithBiggerString { public func f() -> LoadableStructWithBiggerString { return LoadableStructWithBiggerString(a1: BiggerString(str:"", double:0.0), a2: [], a3: []) } } //===----------------------------------------------------------------------===// // SR-8076 //===----------------------------------------------------------------------===// public typealias sr8076_Filter = (BigStruct) -> Bool public protocol sr8076_Query { associatedtype Returned } public protocol sr8076_ProtoQueryHandler { func forceHandle_1<Q: sr8076_Query>(query: Q) -> Void func forceHandle_2<Q: sr8076_Query>(query: Q) -> (Q.Returned, BigStruct?) func forceHandle_3<Q: sr8076_Query>(query: Q) -> (Q.Returned, sr8076_Filter?) func forceHandle_4<Q: sr8076_Query>(query: Q) throws -> (Q.Returned, sr8076_Filter?) } public protocol sr8076_QueryHandler: sr8076_ProtoQueryHandler { associatedtype Handled: sr8076_Query func handle_1(query: Handled) -> Void func handle_2(query: Handled) -> (Handled.Returned, BigStruct?) func handle_3(query: Handled) -> (Handled.Returned, sr8076_Filter?) func handle_4(query: Handled) throws -> (Handled.Returned, sr8076_Filter?) } public extension sr8076_QueryHandler { // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_15queryyqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself) // CHECK: call swiftcc void {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void func forceHandle_1<Q: sr8076_Query>(query: Q) -> Void { guard let body = handle_1 as? (Q) -> Void else { fatalError("handler \(self) is expected to handle query \(query)") } body(query) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_25query8ReturnedQyd___AA9BigStructVSgtqd___tAA0e1_F0Rd__lF"(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself) // CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg // CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret [[ALLOC]], %swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void func forceHandle_2<Q: sr8076_Query>(query: Q) -> (Q.Returned, BigStruct?) { guard let body = handle_2 as? (Q) -> (Q.Returned, BigStruct?) else { fatalError("handler \(self) is expected to handle query \(query)") } return body(query) } // CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc { i64, i64 } @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_35query8ReturnedQyd___SbAA9BigStructVcSgtqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself) // CHECK-64: {{.*}} = call swiftcc { i64, i64 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK-64: ret { i64, i64 } // CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc { i32, i32} @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_35query8ReturnedQyd___SbAA9BigStructVcSgtqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself) // CHECK-32: {{.*}} = call swiftcc { i32, i32 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK-32: ret { i32, i32 } func forceHandle_3<Q: sr8076_Query>(query: Q) -> (Q.Returned, sr8076_Filter?) { guard let body = handle_3 as? (Q) -> (Q.Returned, sr8076_Filter?) else { fatalError("handler \(self) is expected to handle query \(query)") } return body(query) } // CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc { i64, i64 } @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_45query8ReturnedQyd___SbAA9BigStructVcSgtqd___tKAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself, %swift.error** swifterror) // CHECK-64: {{.*}} = call swiftcc { i64, i64 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}, %swift.error** noalias nocapture swifterror {{.*}}) // CHECK-64: ret { i64, i64 } // CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc { i32, i32} @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_45query8ReturnedQyd___SbAA9BigStructVcSgtqd___tKAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself, %swift.error** swifterror) // CHECK-32: {{.*}} = call swiftcc { i32, i32 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}, %swift.error** noalias nocapture {{.*}}) // CHECK-32: ret { i32, i32 } func forceHandle_4<Q: sr8076_Query>(query: Q) throws -> (Q.Returned, sr8076_Filter?) { guard let body = handle_4 as? (Q) throws -> (Q.Returned, sr8076_Filter?) else { fatalError("handler \(self) is expected to handle query \(query)") } return try body(query) } }
apache-2.0
28dfaf63c1605f71fcf219ae655a1cee
50.264368
472
0.680717
3.483695
false
false
false
false
the-grid/Disc
Disc/Networking/Authorization/CreateLoginUrl.swift
1
1246
public extension APIClient { /// Create a URL that can be opened in a web browser to request permission /// to access a user's account. If a user authorizes the application, the /// browser will redirect to the provided `redirectUri` that was passed to /// `init`. Included will be a `code` query string parameter for use with /// `getAccessToken(code:completionHandler:)`. /// /// - parameter clientId: The unique identifier of your application. /// - parameter clientSecret: Your application's passphrase. /// - parameter redirectUri: Your callback URI. /// - parameter scopes: The desired authentication scopes. /// - parameter provider: The desired identity provider, if any. static func createLoginUrl(_ clientId: String, redirectUri: String, scopes: [Scope] = [], provider: Provider? = nil) -> URL? { let queryItems = createRequestParameters(clientId: clientId, redirectUri: redirectUri, scopes: scopes) let pathComponent: String if let provider = provider { pathComponent = "/\(provider.rawValue)" } else { pathComponent = "" } return createUrl("login/authorize" + pathComponent, queryItems) } }
mit
8d1134817b14dd01cf59e570c152bc01
46.923077
130
0.662119
5.127572
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-5distinct_use.swift
3
10595
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5ValueVys4Int8VGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sBi8_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVys4Int8VGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$ss4Int8VN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVys5UInt8VGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sBi8_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVys5UInt8VGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$ss5UInt8VN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVySSGWV" = linkonce_odr hidden constant %swift.vwtable { // CHECK-SAME: i8* bitcast ({{.+}}$s4main5ValueVySSGwCP{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwxx{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwcp{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwca{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwta{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwet{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwst{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: [[INT]] {{[0-9]+}}, // CHECK-SAME: [[INT]] {{[0-9]+}}, // CHECK-SAME: i32 {{[0-9]+}}, // CHECK-SAME: i32 {{[0-9]+}} // CHECK-SAME: }, // NOTE: ignore COMDAT on PE/COFF target // CHECK-SAME: align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVySSGMf" = linkonce_odr hidden constant {{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), %swift.type* @"$sSSN", i32 0{{(, \[4 x i8\] zeroinitializer)?}}, i64 3 }>, align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVySdGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sBi64_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySdGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSdN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] struct Value<First> { let first: First } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySdGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySSGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVys5UInt8VGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVys4Int8VGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: } func doit() { consume( Value(first: 13) ) consume( Value(first: 13.0) ) consume( Value(first: "13") ) consume( Value(first: 13 as UInt8) ) consume( Value(first: 13 as Int8) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]] // CHECK: [[TYPE_COMPARISON_1]]: // CHECK: [[EQUAL_TYPE_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1]] // CHECK: br i1 [[EQUAL_TYPES_1]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[TYPE_COMPARISON_2:[0-9]+]] // CHECK: [[TYPE_COMPARISON_2]]: // CHECK: [[EQUAL_TYPE_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSdN" to i8*), [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES_2:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_2]] // CHECK: br i1 [[EQUAL_TYPES_2]], label %[[EXIT_PRESPECIALIZED_2:[0-9]+]], label %[[TYPE_COMPARISON_3:[0-9]+]] // CHECK: [[TYPE_COMPARISON_3]]: // CHECK: [[EQUAL_TYPE_3:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES_3:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_3]] // CHECK: br i1 [[EQUAL_TYPES_3]], label %[[EXIT_PRESPECIALIZED_3:[0-9]+]], label %[[TYPE_COMPARISON_4:[0-9]+]] // CHECK: [[TYPE_COMPARISON_4]]: // CHECK: [[EQUAL_TYPE_4:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$ss5UInt8VN" to i8*), [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES_4:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_4]] // CHECK: br i1 [[EQUAL_TYPES_4]], label %[[EXIT_PRESPECIALIZED_4:[0-9]+]], label %[[TYPE_COMPARISON_5:[0-9]+]] // CHECK: [[TYPE_COMPARISON_5]]: // CHECK: [[EQUAL_TYPE_5:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$ss4Int8VN" to i8*), [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES_5:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_5]] // CHECK: br i1 [[EQUAL_TYPES_5]], label %[[EXIT_PRESPECIALIZED_5:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED_1]]: // CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 } // CHECK: [[EXIT_PRESPECIALIZED_2]]: // CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySdGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 } // CHECK: [[EXIT_PRESPECIALIZED_3]]: // CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySSGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 } // CHECK: [[EXIT_PRESPECIALIZED_4]]: // CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVys5UInt8VGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 } // CHECK: [[EXIT_PRESPECIALIZED_5]]: // CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVys4Int8VGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 } // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* undef, i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
98c7b86e6669035f4573017b355a9326
65.21875
338
0.596602
2.976124
false
false
false
false