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
simonegenovese/Timbrum
Timbrum/TimeCounter.swift
1
1762
// // TimeCounter.swift // Timbrum // // Created by Simone Genovese on 05/03/16. // Copyright © 2016 ESTECO. All rights reserved. // import Foundation import UIKit class TimeCounter { var todayInterval = NSTimeInterval() var timeTable = [String: String]() func entrata(value: String) { let newValue = value.stringByReplacingOccurrencesOfString(":", withString: "") let hours = newValue.substringWithRange(newValue.startIndex ..< newValue.startIndex.advancedBy(2)) let minutes = newValue.substringWithRange(newValue.startIndex.advancedBy(2) ..< newValue.startIndex.advancedBy(4)) let count = todayInterval.advancedBy(((Double(hours)! * 60) + Double(minutes)!)*60) timeTable["\(hours):\(minutes)"] = "E" todayInterval = NSTimeInterval(count) } func uscita(value: String) { let newValue = value.stringByReplacingOccurrencesOfString(":", withString: "") let hours = newValue.substringWithRange(newValue.startIndex ..< newValue.startIndex.advancedBy(2)) let minutes = newValue.substringWithRange(newValue.startIndex.advancedBy(2) ..< newValue.startIndex.advancedBy(4)) let from = NSTimeInterval(((Double(hours)! * 60) + Double(minutes)!)*60) let count = todayInterval-from timeTable["\(hours):\(minutes)"] = "U" todayInterval = NSTimeInterval(count) } func getOreTotali() -> String { let hours = floor(abs(todayInterval) / 3600) let minutes = trunc(abs(todayInterval) / 60 - hours * 60) let text = NSString().stringByAppendingFormat("%02d:%02d", NSInteger(hours), NSInteger(minutes)) return text as String } func getTimeTable() -> [String:String] { return timeTable } }
gpl-3.0
92b17adbfb504ad13420dd1b9cb2365e
35.708333
122
0.667235
4.435768
false
false
false
false
goaairlines/capetown-ios
capetown/Model/CurrencyAPI.swift
1
4336
// // CurrencyAPI.swift // capetown // // Created by Alex Berger on 2/27/16. // Copyright © 2016 goa airlines. All rights reserved. // import Foundation class CurrencyAPI { func rates(base: String, completion: (success: Bool, object: Dictionary<String, AnyObject>?) -> ()) { let baseParameter = ["base": base] get(clientURLRequest("latest"), params: baseParameter) { (success, object) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in if success { completion(success: true, object: object) } else { completion(success: false, object: object) } }) } } private func post( request: NSMutableURLRequest, params: Dictionary<String, AnyObject>? = nil, completion: (success: Bool, object: Dictionary<String, AnyObject>?) -> ()) { dataTask(request, params: params, method: "POST", completion: completion) } private func put( request: NSMutableURLRequest, params: Dictionary<String, AnyObject>? = nil, completion: (success: Bool, object: Dictionary<String, AnyObject>?) -> ()) { dataTask(request, params: params, method: "PUT", completion: completion) } private func get( request: NSMutableURLRequest, params: Dictionary<String, AnyObject>? = nil, completion: (success: Bool, object: Dictionary<String, AnyObject>?) -> ()) { dataTask(request, params: params, method: "GET", completion: completion) } private func clientURLRequest(path: String) -> NSMutableURLRequest { let request = NSMutableURLRequest(URL: NSURL(string: "https://api.fixer.io/" + path)!) return request } private func dataTask( request: NSMutableURLRequest, params: Dictionary<String, AnyObject>? = nil, method: String, completion: (success: Bool, object: Dictionary<String, AnyObject>?) -> ()) { request.HTTPMethod = method if let params = params { var paramString = "" for (key, value) in params { let escapedKey = key.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()) let escapedValue = value.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()) if let escapedKey = escapedKey, let escapedValue = escapedValue { if method == "GET" || method == "DELETE" { paramString += "?" + escapedKey + "=" + escapedValue } else { paramString += "\(escapedKey)=\(escapedValue)&" } } } if method == "GET" || method == "DELETE" { var urlString = request.URL!.absoluteString urlString += paramString request.URL = NSURL(string: urlString) } else { request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding) } } let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) session.dataTaskWithRequest(request) { (data, response, error) -> Void in if let data = data { if let json: Dictionary<String, AnyObject> = try! NSJSONSerialization.JSONObjectWithData(data, options: []) as? Dictionary<String, AnyObject>, let response = response as? NSHTTPURLResponse where 200...299 ~= response.statusCode { completion(success: true, object: json) } else { completion(success: false, object: nil) } } }.resume() } }
mit
4a88a48240e56331b670bf9110111f29
38.770642
162
0.526413
5.749337
false
false
false
false
iOSDevLog/iOSDevLog
AutoLayout/AutoLayout/ViewController.swift
1
2483
// // ViewController.swift // AutoLayout // // Created by jiaxianhua on 15/9/25. // Copyright © 2015年 com.jiaxh. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var loginField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var passwordLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var companyLabel: UILabel! @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() updateUI() } var loggedInUser: User? { didSet { updateUI() } } var secure: Bool = false { didSet { updateUI() } } private func updateUI() { passwordField.secureTextEntry = secure passwordLabel.text = secure ? "Secured Password" : "Password" nameLabel.text = loggedInUser?.name companyLabel.text = loggedInUser?.company image = loggedInUser?.image } @IBAction func toggleSecurity() { secure = !secure } @IBAction func login() { loggedInUser = User.login(loginField.text ?? "", password: passwordField.text ?? "") } var image: UIImage? { get { return imageView.image } set { imageView.image = newValue if let constrainedView = imageView { if let newImage = newValue { aspectRatioConstraint = NSLayoutConstraint(item: constrainedView, attribute: .Width, relatedBy: .Equal, toItem: constrainedView, attribute: .Height, multiplier: newImage.aspectRatio, constant: 0) } else { aspectRatioConstraint = nil } } } } var aspectRatioConstraint: NSLayoutConstraint? { willSet { if let existingContraint = aspectRatioConstraint { view.removeConstraint(existingContraint) } } didSet { if let newContraint = aspectRatioConstraint { view.addConstraint(newContraint) } } } } extension User { var image: UIImage { if let image = UIImage(named: login) { return image } else { return UIImage(named: "unknown_user")! } } } extension UIImage { var aspectRatio: CGFloat { return size.height != 0 ? size.width / size.height : 0 } }
mit
766bb20362a64f34ca102b63b875eb28
26.252747
215
0.579839
5.092402
false
false
false
false
xiaomudegithub/iosstar
iOSStar/Scenes/Exchange/CustomView/ContactListCell.swift
2
5651
// // ContactListCell.swift // iOSStar // // Created by J-bb on 17/4/26. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit class GetOrderStarsVCCell : OEZTableViewCell{ @IBOutlet var dodetail: UIButton! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var chatButton: UIButton! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var contView: UIView! @IBOutlet var ownsecond: UILabel! var cellModel: StarInfoModel = StarInfoModel() override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func haveAChat(_sender: UIButton) { didSelectRowAction(3, data: cellModel) } override func update(_ data: Any!) { guard data != nil else{return} let model = data as! StarInfoModel StartModel.getStartName(startCode: model.starcode) { (response) in if let star = response as? StartModel { self.iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + star.pic_url_tail)) } } cellModel = model nameLabel.text = model.starname ownsecond.text = "\(model.ownseconds)" } @IBAction func dochat(_ sender: Any) { didSelectRowAction(5, data: cellModel) } @IBAction func domeet(_ sender: Any) { didSelectRowAction(4, data: cellModel) } } //MARK: -普通的cell class ContactListCell: OEZTableViewCell { //工作 @IBOutlet var doStarDeatil: UIButton! @IBOutlet weak var jobLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var unreadLabel: UILabel! @IBOutlet weak var chatButton: UIButton! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet var orderTime: UILabel! var cellModel: StarInfoModel = StarInfoModel() override func awakeFromNib() { super.awakeFromNib() chatButton.layer.cornerRadius = 2 chatButton.layer.masksToBounds = true self.clipsToBounds = true self.layer.masksToBounds = true self.layer.cornerRadius = 2 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func haveAChat(_sender: UIButton) { didSelectRowAction(3, data: cellModel) } override func update(_ data: Any!) { guard data != nil else{return} if let model = data as? StarInfoModel{ unreadLabel.text = " \(model.unreadCount) " unreadLabel.isHidden = model.unreadCount == 0 StartModel.getStartName(startCode: model.starcode) { (response) in if let star = response as? StartModel { self.iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + star.pic_url_tail)) } } var title = "" var color = "" if model.appoint == 0 { color = AppConst.Color.main title = "没有约见" } else if model.appoint == 1{ color = AppConst.Color.main title = "待确认" } else if model.appoint == 2{ color = "CCCCCC" title = "已拒绝" } else if model.appoint == 3{ color = AppConst.Color.main title = "已完成" } else { color = AppConst.Color.main title = "已同意" } chatButton.setTitle(title, for: .normal) chatButton.backgroundColor = UIColor.init(hexString: color) chatButton.backgroundColor = UIColor.init(hexString: AppConst.Color.orange) cellModel = model if (nameLabel != nil){ nameLabel.text = model.starname jobLabel.text = model.work chatButton.setTitle("聊一聊", for: .normal) } } else{ if let model = data as? OrderStarListInfoModel{ var title = "" var color = "" if model.meet_type == 4 { color = AppConst.Color.orange title = "已同意" } else if model.meet_type == 1{ color = AppConst.Color.orange title = "已预订" } else if model.meet_type == 2{ color = "CCCCCC" title = "已拒绝" } else if model.meet_type == 3{ color = "CCCCCC" title = "已完成" } else { color = "CCCCCC" title = "已同意" } chatButton.setTitle(title, for: .normal) chatButton.backgroundColor = UIColor.init(hexString: color) jobLabel.text = model.star_name orderTime.text = model.meet_time self.iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + model.star_pic)) orderTime.text = model.meet_time } } } }
gpl-3.0
b4cb3019b56a6484e76f17d2f11fc354
31.573099
124
0.534829
4.843478
false
false
false
false
cpoutfitters/cpoutfitters
CPOutfitters/ProfileViewController.swift
1
6858
// // ProfileViewController.swift // CPOutfitters // // Created by Aditya Purandare on 19/04/16. // Copyright © 2016 SnazzyLLama. All rights reserved. // import UIKit import Parse class ProfileViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate { @IBOutlet weak var userhandleLabel: UILabel! @IBOutlet weak var userProfileImageView: UIImageView! @IBOutlet weak var bioTextView: UITextView! @IBOutlet weak var fullnameTextField: UITextField! @IBOutlet weak var articleCount: UILabel! @IBOutlet weak var genderControl: UISegmentedControl! var bioText: String = "" var nameText: String = "" var genders = ["Male", "Female"] override func viewDidLoad() { super.viewDidLoad() bioTextView.userInteractionEnabled = true fullnameTextField.userInteractionEnabled = true bioTextView.delegate = self // NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) // NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard") view.addGestureRecognizer(tap) let user = PFUser.currentUser() let userName = user?.username!.characters.split("@").map(String.init) self.userhandleLabel.text = "@\(userName![0])" if user!["bio"] != nil { self.bioTextView.text = user!["bio"] as! String self.bioText = user!["bio"] as! String } if user!["fullname"] != nil { self.fullnameTextField.text = user!["fullname"] as? String self.nameText = user!["fullname"] as! String } if user!["gender"] != nil { let gender = user!["gender"] as! String self.genderControl.selectedSegmentIndex = self.genders.indexOf(gender)! } if user!["profilePicture"] != nil { let imageFile = user!["profilePicture"] as! PFFile imageFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in if let imageData = imageData { self.userProfileImageView.image = UIImage(data:imageData) self.userProfileImageView.layer.cornerRadius = self.userProfileImageView.frame.size.width / 2 self.userProfileImageView.clipsToBounds = true } } } ParseClient.sharedInstance.countArticles(["owner": PFUser.currentUser()!]) { (count:Int32?, error:NSError?) in var countFabrics: String = "0 Fabriqs in your wardrobe" if count! == 1 { countFabrics = "\(count!) Fabriq in your wardrobe" } else { countFabrics = "\(count!) Fabriqs in your wardrobe" } self.articleCount.text = countFabrics } if nameText != "" && bioText != "" { } } // func keyboardWillShow(notification: NSNotification) { // // if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { // self.view.frame.origin.y -= keyboardSize.height // } // // } // // func keyboardWillHide(notification: NSNotification) { // if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { // self.view.frame.origin.y += keyboardSize.height // } // } @IBAction func onValueChanged(sender: AnyObject) { let user = PFUser.currentUser()! user["gender"] = genders[genderControl.selectedSegmentIndex] user.saveInBackground() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onCamera(sender: AnyObject) { //Library picker being loaded let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = true vc.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(vc, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage userProfileImageView.image = editedImage let newSize = CGSize(width: 500, height: 500) if let image = userProfileImageView.image { let resizedImage = resizeImage(image, newSize: newSize) self.userProfileImageView.image = resizedImage self.userProfileImageView.layer.cornerRadius = self.userProfileImageView.frame.size.width / 2 self.userProfileImageView.clipsToBounds = true let user = PFUser.currentUser() user!["profilePicture"] = Article.getPFFileFromImage(resizedImage) user!.saveInBackground() } dismissViewControllerAnimated(true, completion: nil) } @IBAction func onLogout(sender: AnyObject) { ParseClient.sharedInstance.logoutUser() } func dismissKeyboard() { view.endEditing(true) } @IBAction func onEditingEnd(sender: AnyObject) { let user = PFUser.currentUser()! user["fullname"] = fullnameTextField.text user.saveInBackground() } func resizeImage(image: UIImage, newSize: CGSize) -> UIImage { let resizeImageView = UIImageView(frame: CGRectMake(0, 0, newSize.width, newSize.height)) resizeImageView.contentMode = UIViewContentMode.ScaleAspectFill resizeImageView.image = image UIGraphicsBeginImageContext(resizeImageView.frame.size) resizeImageView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } func textViewDidChange(textView: UITextView) { let user = PFUser.currentUser()! user["bio"] = bioTextView.text user.saveInBackground() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
74c6c9dadca11528e6727465998ceadd
37.307263
156
0.640659
5.373824
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/lib/SwiftColorPicker/ColorGradientView.swift
1
5029
// // ColorGradientView.swift // SwiftColorPicker // // Created by cstad on 12/10/14. // import UIKit import CGUtility public class ColorGradientView: UIView { var colorLayer: ColorLayer! weak var delegate: ColorPicker? var point:CGPoint! var knob:UIView! required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } let knobWidth:CGFloat = 30 var hasLayouted = false override public func layoutSubviews() { super.layoutSubviews() if !hasLayouted { layer.shadowOffset = CGSize(width: 0, height: 2) layer.shadowOpacity = 0.8 knob = UIView(frame: CGRect(x: 0, y: 0, width: knobWidth, height: knobWidth)) knob.layer.cornerRadius = knobWidth/2 knob.layer.borderColor = UIColor.white.cgColor knob.layer.borderWidth = 1 knob.backgroundColor = UIColor.white knob.layer.shadowOffset = CGSize(width: 0, height: 2) knob.layer.shadowOpacity = 0.8 hasLayouted = true addSubview(knob) initLayer() } } init(frame: CGRect, color: UIColor!) { super.init(frame: frame) //setColor(color) } var isTouchDown = false; override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first let point = touch!.location(in: self) _ = delegate?.colorSaturationAndBrightnessSelected(point) isTouchDown = true //let dis = point-(touch?.previousLocationInView(self))! UIView.animate(withDuration: 0.2, animations: { self.knob.center = point+CGPoint(x: 0,y: -20) self.knob.layer.transform = CATransform3DMakeScale(2, 2, 1) }) } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if(isTouchDown) { let touch = touches.first point = touch!.location(in: self) point.x = getLimitXCoordinate(point.x) point.y = getLimitYCoordinate(point.y) _ = delegate?.colorSaturationAndBrightnessSelected(point); self.knob.center = point+CGPoint(x: 0,y: -20) } } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { isTouchDown = false let touch = touches.first var point = touch!.location(in: self) point.x = getLimitXCoordinate(point.x) point.y = getLimitYCoordinate(point.y) UIView.animate(withDuration: 0.5, animations: { self.knob.center = point self.knob.layer.transform = CATransform3DIdentity }) } override public func draw(_ rect: CGRect) { //drawCoreGraphic() } func initLayer() { //drawCoreGraphic() colorLayer = ColorLayer(color: UIColor.red,hue:0) colorLayer.layer.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.width) // Insert the color.colorLayer into this views layer as a sublayer layer.insertSublayer(colorLayer.layer, at: 0) // Init new CAGradientLayer to be used as the grayScale overlay let grayScaleLayer = CAGradientLayer() // Set the grayScaleLayer colors to black and clear grayScaleLayer.colors = [UIColor.clear.cgColor,UIColor.black.cgColor] // Display gradient left to right grayScaleLayer.startPoint = CGPoint(x: 0.5, y: 0.0) grayScaleLayer.endPoint = CGPoint(x: 0.5, y: 1.0) // Use the size and position of this views frame to create a new frame for the grayScaleLayer grayScaleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.width) // Insert the grayScaleLayer into this views layer as a sublayer self.layer.insertSublayer(grayScaleLayer, at: 1) setNeedsDisplay() } public func setColor(_ _color: UIColor!,hue:CGFloat) { // Set member color to the new UIColor coming in colorLayer.layer.removeFromSuperlayer() colorLayer = ColorLayer(color: _color,hue:hue) // Set colorView sublayers to nil to remove any existing sublayers //layer.sublayers = nil; // Use the size and position of this views frame to create a new frame for the color.colorLayer colorLayer.layer.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.width) // Insert the color.colorLayer into this views layer as a sublayer layer.insertSublayer(colorLayer.layer, at: 0) knob.backgroundColor = _color // Init new CAGradientLayer to be used as the grayScale overlay } } public func - (a: CGPoint, b: CGPoint) ->CGPoint {return CGPoint(x: a.x-b.x, y: a.y-b.y)}
mit
756aad37bdadd5d58b082266824e0430
34.167832
110
0.605886
4.462289
false
false
false
false
natecook1000/swift
stdlib/public/SDK/CloudKit/CKSubscription_NotificationInfo.swift
19
5591
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// @_exported import CloudKit // Clang module #if !os(watchOS) /** The payload of a push notification delivered in the UIApplication `application:didReceiveRemoteNotification:` delegate method contains information about the firing subscription. Use `Notification(fromRemoteNotificationDictionary:)` to parse that payload. On tvOS, alerts, badges, sounds, and categories are not handled in push notifications. However, Subscriptions remain available to help you avoid polling the server. */ @nonobjc @available(macOS 10.10, iOS 8.0, *) @available(watchOS, unavailable) extension CKSubscription.NotificationInfo { /// A list of field names to take from the matching record that is used as substitution variables in a formatted alert string. #if !os(tvOS) @available(tvOS, unavailable) @available(swift 4.2) public var alertLocalizationArgs: [CKRecord.FieldKey]? { get { return self.__alertLocalizationArgs } set { self.__alertLocalizationArgs = newValue } } /// A list of field names to take from the matching record that is used as substitution variables in a formatted title string. @available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(swift 4.2) public var titleLocalizationArgs: [CKRecord.FieldKey]? { get { return self.__titleLocalizationArgs } set { self.__titleLocalizationArgs = newValue } } /// A list of field names to take from the matching record that is used as substitution variables in a formatted subtitle string. @available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(swift 4.2) public var subtitleLocalizationArgs: [CKRecord.FieldKey]? { get { return self.__subtitleLocalizationArgs } set { self.__subtitleLocalizationArgs = newValue } } #endif // !os(tvOS) /** A list of keys from the matching record to include in the notification payload. Only some keys are allowed. The value types associated with those keys on the server must be one of these classes: - CKRecord.Reference - CLLocation - NSDate - NSNumber - NSString */ @available(swift 4.2) public var desiredKeys: [CKRecord.FieldKey]? { get { return self.__desiredKeys } set { self.__desiredKeys = newValue } } public convenience init(alertBody: String? = nil, alertLocalizationKey: String? = nil, alertLocalizationArgs: [CKRecord.FieldKey] = [], title: String? = nil, titleLocalizationKey: String? = nil, titleLocalizationArgs: [CKRecord.FieldKey] = [], subtitle: String? = nil, subtitleLocalizationKey: String? = nil, subtitleLocalizationArgs: [CKRecord.FieldKey] = [], alertActionLocalizationKey: String? = nil, alertLaunchImage: String? = nil, soundName: String? = nil, desiredKeys: [CKRecord.FieldKey] = [], shouldBadge: Bool = false, shouldSendContentAvailable: Bool = false, shouldSendMutableContent: Bool = false, category: String? = nil, collapseIDKey: String? = nil) { self.init() #if !os(tvOS) do { self.alertBody = alertBody self.alertLocalizationKey = alertLocalizationKey self.alertLocalizationArgs = alertLocalizationArgs if #available(macOS 10.13, iOS 11.0, *) { self.title = title self.titleLocalizationKey = titleLocalizationKey self.titleLocalizationArgs = titleLocalizationArgs self.subtitle = subtitle self.subtitleLocalizationKey = subtitleLocalizationKey self.subtitleLocalizationArgs = subtitleLocalizationArgs } self.alertActionLocalizationKey = alertActionLocalizationKey self.alertLaunchImage = alertLaunchImage self.soundName = soundName } #endif // !os(tvOS) self.desiredKeys = desiredKeys if #available(tvOS 10.0, *) { self.shouldBadge = shouldBadge } self.shouldSendContentAvailable = shouldSendContentAvailable if #available(macOS 10.13, iOS 11.0, tvOS 11.0, *) { self.shouldSendMutableContent = shouldSendMutableContent } #if !os(tvOS) do { if #available(macOS 10.11, iOS 9.0, *) { self.category = category } } #endif // !os(tvOS) if #available(macOS 10.13, iOS 11.0, tvOS 11.0, *) { self.collapseIDKey = collapseIDKey } } } #endif // !os(watchOS)
apache-2.0
d12a3a0121b7ff8d83855358c7a6313d
40.723881
178
0.586836
5.334924
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PeerPhotosMonthItem.swift
1
34691
// // PeerPhotosMonthItem.swift // Telegram // // Created by Mikhail Filimonov on 17.10.2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import TelegramCore import TGUIKit import Postbox import SwiftSignalKit private struct LayoutItem : Equatable { static func == (lhs: LayoutItem, rhs: LayoutItem) -> Bool { return lhs.message == rhs.message && lhs.corners == rhs.corners && lhs.frame == rhs.frame } let message: Message let frame: NSRect let viewType:MediaCell.Type let corners:ImageCorners let chatInteraction: ChatInteraction var hasImmediateData: Bool { if let image = message.media.first as? TelegramMediaImage { return image.immediateThumbnailData != nil } else if let file = message.media.first as? TelegramMediaFile { return file.immediateThumbnailData != nil } return false } } class PeerPhotosMonthItem: GeneralRowItem { let items:[Message] fileprivate let context: AccountContext private var contentHeight: CGFloat = 0 fileprivate private(set) var layoutItems:[LayoutItem] = [] fileprivate private(set) var itemSize: NSSize = NSZeroSize fileprivate let chatInteraction: ChatInteraction fileprivate let galleryType: GalleryAppearType fileprivate let gallery: (Message, GalleryAppearType)->Void init(_ initialSize: NSSize, stableId: AnyHashable, viewType: GeneralViewType, context: AccountContext, chatInteraction: ChatInteraction, items: [Message], galleryType: GalleryAppearType, gallery: @escaping(Message, GalleryAppearType)->Void) { self.items = items self.context = context self.chatInteraction = chatInteraction self.galleryType = galleryType self.gallery = gallery super.init(initialSize, stableId: stableId, viewType: viewType, inset: NSEdgeInsets()) } override var canBeAnchor: Bool { return true } static func rowCount(blockWidth: CGFloat, viewType: GeneralViewType) -> (Int, CGFloat) { var rowCount:Int = 4 var perWidth: CGFloat = 0 while true { let maximum = blockWidth - viewType.innerInset.left - viewType.innerInset.right - CGFloat(rowCount * 2) perWidth = maximum / CGFloat(rowCount) if perWidth >= 90 { break } else { rowCount -= 1 } } return (rowCount, perWidth) } override func makeSize(_ width: CGFloat, oldWidth: CGFloat = 0) -> Bool { _ = super.makeSize(width, oldWidth: oldWidth) if !items.isEmpty { var t: time_t = time_t(TimeInterval(items[0].timestamp)) var timeinfo: tm = tm() localtime_r(&t, &timeinfo) if timeinfo.tm_mon == 2 { var bp:Int = 0 bp += 1 } } let (rowCount, perWidth) = PeerPhotosMonthItem.rowCount(blockWidth: self.blockWidth, viewType: self.viewType) assert(rowCount >= 1) let itemSize = NSMakeSize(ceil(perWidth) + 2, ceil(perWidth) + 2) layoutItems.removeAll() var point: CGPoint = CGPoint(x: self.viewType.innerInset.left, y: self.viewType.innerInset.top + itemSize.height) for (i, message) in self.items.enumerated() { let viewType: MediaCell.Type if let file = message.effectiveMedia as? TelegramMediaFile { if file.isAnimated && file.isVideo { viewType = MediaGifCell.self } else { viewType = MediaVideoCell.self } } else { viewType = MediaPhotoCell.self } var topLeft: ImageCorner = .Corner(0) var topRight: ImageCorner = .Corner(0) var bottomLeft: ImageCorner = .Corner(0) var bottomRight: ImageCorner = .Corner(0) if self.viewType.position != .first && self.viewType.position != .inner { if self.items.count < rowCount { if message == self.items.first { if self.viewType.position != .last { topLeft = .Corner(.cornerRadius) } bottomLeft = .Corner(.cornerRadius) } } else if self.items.count == rowCount { if message == self.items.first { if self.viewType.position != .last { topLeft = .Corner(.cornerRadius) } bottomLeft = .Corner(.cornerRadius) } else if message == self.items.last { if message == self.items.last { if self.viewType.position != .last { topRight = .Corner(.cornerRadius) } bottomRight = .Corner(.cornerRadius) } } } else { let i = i + 1 let firstLine = i <= rowCount let div = (items.count % rowCount) == 0 ? rowCount : (items.count % rowCount) let lastLine = i > (items.count - div) if firstLine { if self.viewType.position != .last { if i % rowCount == 1 { topLeft = .Corner(.cornerRadius) } else if i % rowCount == 0 { topRight = .Corner(.cornerRadius) } } } else if lastLine { if i % rowCount == 1 { bottomLeft = .Corner(.cornerRadius) } else if i % rowCount == 0 { bottomRight = .Corner(.cornerRadius) } } } } let corners = ImageCorners(topLeft: topLeft, topRight: topRight, bottomLeft: bottomLeft, bottomRight: bottomRight) self.layoutItems.append(LayoutItem(message: message, frame: CGRect(origin: point.offsetBy(dx: 0, dy: -itemSize.height), size: itemSize), viewType: viewType, corners: corners, chatInteraction: self.chatInteraction)) point.x += itemSize.width if self.layoutItems.count % rowCount == 0, message != self.items.last { point.y += itemSize.height point.x = self.viewType.innerInset.left } } self.itemSize = itemSize self.contentHeight = point.y - self.viewType.innerInset.top return true } func contains(_ id: MessageId) -> Bool { return layoutItems.contains(where: { $0.message.id == id}) } override var height: CGFloat { return self.contentHeight + self.viewType.innerInset.top + self.viewType.innerInset.bottom } override var instantlyResize: Bool { return true } deinit { } override func viewClass() -> AnyClass { return PeerPhotosMonthView.self } override func menuItems(in location: NSPoint) -> Signal<[ContextMenuItem], NoError> { var items:[ContextMenuItem] = [] let layoutItem = layoutItems.first(where: { NSPointInRect(location, $0.frame) }) if let layoutItem = layoutItem { let message = layoutItem.message if canForwardMessage(message, chatInteraction: chatInteraction) { items.append(ContextMenuItem(strings().messageContextForward, handler: { [weak self] in self?.chatInteraction.forwardMessages([message.id]) }, itemImage: MenuAnimation.menu_forward.value)) } items.append(ContextMenuItem(strings().messageContextGoto, handler: { [weak self] in self?.chatInteraction.focusMessageId(nil, message.id, .center(id: 0, innerId: nil, animated: false, focus: .init(focus: true), inset: 0)) }, itemImage: MenuAnimation.menu_show_message.value)) if canDeleteMessage(message, account: context.account, mode: .history) { items.append(ContextSeparatorItem()) items.append(ContextMenuItem(strings().messageContextDelete, handler: { [weak self] in self?.chatInteraction.deleteMessages([message.id]) }, itemMode: .destruct, itemImage: MenuAnimation.menu_delete.value)) } } return .single(items) } } private class MediaCell : Control { private var selectionView:SelectingControl? fileprivate let imageView: TransformImageView private(set) var layoutItem: LayoutItem? fileprivate var context: AccountContext? required init(frame frameRect: NSRect) { imageView = TransformImageView(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height)) super.init(frame: frameRect) addSubview(imageView) userInteractionEnabled = false } override func mouseMoved(with event: NSEvent) { superview?.superview?.mouseMoved(with: event) } override func mouseEntered(with event: NSEvent) { superview?.superview?.mouseEntered(with: event) } override func mouseExited(with event: NSEvent) { superview?.superview?.mouseExited(with: event) } func update(layout: LayoutItem, context: AccountContext, table: TableView?) { let previousLayout = self.layoutItem self.layoutItem = layout self.context = context if previousLayout != layout, !(self is MediaGifCell) { let media: Media let imageSize: NSSize let cacheArguments: TransformImageArguments let signal: Signal<ImageDataTransformation, NoError> if let image = layout.message.effectiveMedia as? TelegramMediaImage, let largestSize = largestImageRepresentation(image.representations)?.dimensions.size { media = image imageSize = largestSize.aspectFilled(NSMakeSize(150, 150)) cacheArguments = TransformImageArguments(corners: layout.corners, imageSize: imageSize, boundingSize: NSMakeSize(150, 150), intrinsicInsets: NSEdgeInsets()) signal = mediaGridMessagePhoto(account: context.account, imageReference: ImageMediaReference.message(message: MessageReference(layout.message), media: image), scale: backingScaleFactor) } else if let file = layout.message.effectiveMedia as? TelegramMediaFile { media = file let largestSize = file.previewRepresentations.last?.dimensions.size ?? file.imageSize imageSize = largestSize.aspectFilled(NSMakeSize(150, 150)) cacheArguments = TransformImageArguments(corners: layout.corners, imageSize: imageSize, boundingSize: NSMakeSize(150, 150), intrinsicInsets: NSEdgeInsets()) signal = chatMessageVideo(postbox: context.account.postbox, fileReference: FileMediaReference.message(message: MessageReference(layout.message), media: file), scale: backingScaleFactor) } else { return } self.imageView.setSignal(signal: cachedMedia(media: media, arguments: cacheArguments, scale: backingScaleFactor)) if !self.imageView.isFullyLoaded { self.imageView.setSignal(signal, animate: true, cacheImage: { result in cacheMedia(result, media: media, arguments: cacheArguments, scale: System.backingScale) }) } self.imageView.set(arguments: cacheArguments) } updateSelectionState(animated: false) } override func copy() -> Any { return imageView.copy() } func innerAction() -> InvokeActionResult { return .gallery } func addAccesoryOnCopiedView(view: NSView) { } func updateMouse(_ inside: Bool) { } func updateSelectionState(animated: Bool) { if let layoutItem = layoutItem { if let selectionState = layoutItem.chatInteraction.presentation.selectionState { let selected = selectionState.selectedIds.contains(layoutItem.message.id) if let selectionView = self.selectionView { selectionView.set(selected: selected, animated: animated) } else { selectionView = SelectingControl(unselectedImage: theme.icons.chatGroupToggleUnselected, selectedImage: theme.icons.chatGroupToggleSelected) addSubview(selectionView!) selectionView?.set(selected: selected, animated: animated) if animated { selectionView?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) selectionView?.layer?.animateScaleCenter(from: 0.5, to: 1.0, duration: 0.2) } } } else { if let selectionView = selectionView { self.selectionView = nil if animated { selectionView.layer?.animateScaleCenter(from: 1.0, to: 0.5, duration: 0.2) selectionView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak selectionView] completion in selectionView?.removeFromSuperview() }) } else { selectionView.removeFromSuperview() } } } needsLayout = true } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layout() { super.layout() imageView.frame = NSMakeRect(0, 0, frame.width - 1, frame.height) if let selectionView = selectionView { selectionView.setFrameOrigin(frame.width - selectionView.frame.width - 5, 5) } } } private final class MediaPhotoCell : MediaCell { } private enum InvokeActionResult { case nothing case gallery } private final class MediaVideoCell : MediaCell { private final class VideoAutoplayView { let mediaPlayer: MediaPlayer let view: MediaPlayerView fileprivate var playTimer: SwiftSignalKit.Timer? var status: MediaPlayerStatus? init(mediaPlayer: MediaPlayer, view: MediaPlayerView) { self.mediaPlayer = mediaPlayer self.view = view mediaPlayer.actionAtEnd = .loop(nil) } deinit { view.removeFromSuperview() playTimer?.invalidate() } } private let mediaPlayerStatusDisposable = MetaDisposable() private let progressView:RadialProgressView = RadialProgressView(theme: RadialProgressTheme(backgroundColor: .blackTransparent, foregroundColor: .white, icon: playerPlayThumb)) private let videoAccessory: ChatMessageAccessoryView = ChatMessageAccessoryView(frame: NSZeroRect) private var status:MediaResourceStatus? private var authenticStatus: MediaResourceStatus? private let statusDisposable = MetaDisposable() private let fetchingDisposable = MetaDisposable() private let partDisposable = MetaDisposable() private var videoView:VideoAutoplayView? required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.addSubview(self.videoAccessory) self.progressView.userInteractionEnabled = false self.addSubview(self.progressView) } override func updateMouse(_ inside: Bool) { } private func updateMediaStatus(_ status: MediaPlayerStatus, animated: Bool = false) { if let videoView = videoView, let media = self.layoutItem?.message.effectiveMedia as? TelegramMediaFile { videoView.status = status updateVideoAccessory(self.authenticStatus ?? .Local, mediaPlayerStatus: status, file: media, animated: animated) switch status.status { case .playing: videoView.playTimer?.invalidate() videoView.playTimer = SwiftSignalKit.Timer(timeout: 0.5, repeat: true, completion: { [weak self] in self?.updateVideoAccessory(self?.authenticStatus ?? .Local, mediaPlayerStatus: status, file: media, animated: animated) }, queue: .mainQueue()) videoView.playTimer?.start() default: videoView.playTimer?.invalidate() } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func fetch() { if let context = context, let layoutItem = self.layoutItem { let file = layoutItem.message.effectiveMedia as! TelegramMediaFile fetchingDisposable.set(messageMediaFileInteractiveFetched(context: context, messageId: layoutItem.message.id, messageReference: .init(layoutItem.message), file: file, userInitiated: true).start()) } } private func cancelFetching() { if let context = context, let layoutItem = self.layoutItem { let file = layoutItem.message.effectiveMedia as! TelegramMediaFile messageMediaFileCancelInteractiveFetch(context: context, messageId: layoutItem.message.id, file: file) } } override func innerAction() -> InvokeActionResult { if let file = layoutItem?.message.effectiveMedia as? TelegramMediaFile, let window = self.window { switch progressView.state { case .Fetching: if NSPointInRect(self.convert(window.mouseLocationOutsideOfEventStream, from: nil), progressView.frame) { cancelFetching() } else if file.isStreamable { return .gallery } case .Remote: fetch() default: return .gallery } } return .nothing } func preloadStreamblePart() { if let layoutItem = self.layoutItem { let context = layoutItem.chatInteraction.context if context.autoplayMedia.preloadVideos { if let media = layoutItem.message.effectiveMedia as? TelegramMediaFile { let reference = FileMediaReference.message(message: MessageReference(layoutItem.message), media: media) let preload = preloadVideoResource(postbox: context.account.postbox, resourceReference: reference.resourceReference(media.resource), duration: 3.0) partDisposable.set(preload.start()) } } } } private func updateVideoAccessory(_ status: MediaResourceStatus, mediaPlayerStatus: MediaPlayerStatus? = nil, file: TelegramMediaFile, animated: Bool) { let maxWidth = frame.width - 10 let text: String let status: MediaResourceStatus = .Local if let status = mediaPlayerStatus, status.generationTimestamp > 0, status.duration > 0 { text = String.durationTransformed(elapsed: Int(status.duration - (status.timestamp + (CACurrentMediaTime() - status.generationTimestamp)))) } else { text = String.durationTransformed(elapsed: file.videoDuration) } var isBuffering: Bool = false if let fetchStatus = self.authenticStatus, let status = mediaPlayerStatus { switch status.status { case .buffering: switch fetchStatus { case .Local: break default: isBuffering = true } default: break } } videoAccessory.updateText(text, maxWidth: maxWidth, status: status, isStreamable: file.isStreamable, isCompact: true, isBuffering: isBuffering, animated: animated, fetch: { [weak self] in self?.fetch() }, cancelFetch: { [weak self] in self?.cancelFetching() }) needsLayout = true } override func update(layout: LayoutItem, context: AccountContext, table: TableView?) { super.update(layout: layout, context: context, table: table) let file = layout.message.effectiveMedia as! TelegramMediaFile let updatedStatusSignal = chatMessageFileStatus(context: context, message: layout.message, file: file) |> deliverOnMainQueue |> map { status -> (MediaResourceStatus, MediaResourceStatus) in if file.isStreamable && layout.message.id.peerId.namespace != Namespaces.Peer.SecretChat { return (.Local, status) } return (status, status) } |> deliverOnMainQueue var first: Bool = true statusDisposable.set(updatedStatusSignal.start(next: { [weak self] status, authentic in guard let `self` = self else {return} self.updateVideoAccessory(authentic, mediaPlayerStatus: self.videoView?.status, file: file, animated: !first) first = false self.status = status self.authenticStatus = authentic let progressStatus: MediaResourceStatus switch authentic { case .Fetching: progressStatus = authentic default: progressStatus = status } switch progressStatus { case let .Fetching(_, progress), let .Paused(progress): self.progressView.state = .Fetching(progress: progress, force: false) case .Remote: self.progressView.state = .Remote case .Local: self.progressView.state = .Play } })) partDisposable.set(nil) } override func addAccesoryOnCopiedView(view: NSView) { let videoAccessory = self.videoAccessory.copy() as! ChatMessageAccessoryView if visibleRect.minY < videoAccessory.frame.midY && visibleRect.minY + visibleRect.height > videoAccessory.frame.midY { videoAccessory.frame.origin.y = frame.height - videoAccessory.frame.maxY view.addSubview(videoAccessory) } let pView = RadialProgressView(theme: progressView.theme, twist: true) pView.state = progressView.state pView.frame = progressView.frame if visibleRect.minY < progressView.frame.midY && visibleRect.minY + visibleRect.height > progressView.frame.midY { pView.frame.origin.y = frame.height - progressView.frame.maxY view.addSubview(pView) } } override func layout() { super.layout() progressView.center() videoAccessory.setFrameOrigin(5, 5) videoView?.view.frame = self.imageView.frame } deinit { statusDisposable.dispose() fetchingDisposable.dispose() partDisposable.dispose() mediaPlayerStatusDisposable.dispose() } } private final class MediaGifCell : MediaCell { private let gifView: GIFContainerView = GIFContainerView(frame: .zero) private var status:MediaResourceStatus? private let statusDisposable = MetaDisposable() private let fetchingDisposable = MetaDisposable() required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.addSubview(self.gifView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func fetch() { } private func cancelFetching() { } override func innerAction() -> InvokeActionResult { return .gallery } override func copy() -> Any { return gifView.copy() } override func update(layout: LayoutItem, context: AccountContext, table: TableView?) { let previousLayout = self.layoutItem super.update(layout: layout, context: context, table: table) if layout != previousLayout { let file = layout.message.effectiveMedia as! TelegramMediaFile let messageRefence = MessageReference(layout.message) let reference = FileMediaReference.message(message: messageRefence, media: file) let signal = chatMessageVideo(postbox: context.account.postbox, fileReference: reference, scale: backingScaleFactor) gifView.update(with: reference, size: frame.size, viewSize: frame.size, context: context, table: nil, iconSignal: signal) gifView.userInteractionEnabled = false } } override func layout() { super.layout() gifView.frame = NSMakeRect(0, 0, frame.width - 1, frame.height) } deinit { statusDisposable.dispose() fetchingDisposable.dispose() } } private final class PeerPhotosMonthView : TableRowView, Notifable { private let containerView = GeneralRowContainerView(frame: NSZeroRect) private var contentViews:[Optional<MediaCell>] = [] required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.addSubview(self.containerView) containerView.set(handler: { [weak self] _ in self?.action(event: .Down) }, for: .Down) containerView.set(handler: { [weak self] _ in self?.action(event: .MouseDragging) }, for: .MouseDragging) containerView.set(handler: { [weak self] _ in self?.action(event: .Click) }, for: .Click) } private var haveToSelectOnDrag: Bool = false private weak var currentMouseCell: MediaCell? @objc override func updateMouse() { super.updateMouse() guard let window = self.window else { return } let point = self.containerView.convert(window.mouseLocationOutsideOfEventStream, from: nil) let mediaCell = self.contentViews.first(where: { return $0 != nil && NSPointInRect(point, $0!.frame) })?.map { $0 } if currentMouseCell != mediaCell { currentMouseCell?.updateMouse(false) } currentMouseCell = mediaCell mediaCell?.updateMouse(window.isKeyWindow) } override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) updateMouse() } override func mouseExited(with event: NSEvent) { super.mouseExited(with: event) updateMouse() } override func mouseMoved(with event: NSEvent) { super.mouseMoved(with: event) updateMouse() } private func action(event: ControlEvent) { guard let item = self.item as? PeerPhotosMonthItem, let window = window else { return } let point = containerView.convert(window.mouseLocationOutsideOfEventStream, from: nil) if let layoutItem = item.layoutItems.first(where: { NSPointInRect(point, $0.frame) }) { if layoutItem.chatInteraction.presentation.state == .selecting { switch event { case .MouseDragging: layoutItem.chatInteraction.update { current in if !haveToSelectOnDrag { return current.withRemovedSelectedMessage(layoutItem.message.id) } else { return current.withUpdatedSelectedMessage(layoutItem.message.id) } } case .Down: layoutItem.chatInteraction.update { $0.withToggledSelectedMessage(layoutItem.message.id) } haveToSelectOnDrag = layoutItem.chatInteraction.presentation.isSelectedMessageId(layoutItem.message.id) default: break } } else { switch event { case .Click: let view = self.contentViews.compactMap { $0 }.first(where: { $0.layoutItem == layoutItem }) if let view = view { switch view.innerAction() { case .gallery: item.gallery(layoutItem.message, item.galleryType) case .nothing: break } } default: break } } } } func notify(with value: Any, oldValue:Any, animated:Bool) { if let value = value as? ChatPresentationInterfaceState, let oldValue = oldValue as? ChatPresentationInterfaceState { let views = contentViews.compactMap { $0 } for view in views { if let item = view.layoutItem { if (value.state == .selecting) != (oldValue.state == .selecting) || value.isSelectedMessageId(item.message.id) != oldValue.isSelectedMessageId(item.message.id) { view.updateSelectionState(animated: animated) } } } } } func isEqual(to other: Notifable) -> Bool { if let other = other as? PeerPhotosMonthView { return other == self } return false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var backdorColor: NSColor { return theme.colors.background } override func updateColors() { guard let item = item as? PeerPhotosMonthItem else { return } self.backgroundColor = item.viewType.rowBackground containerView.set(background: self.backdorColor, for: .Normal) } override func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() updateVisibleItems() if let item = self.item as? PeerPhotosMonthItem { if superview == nil { item.chatInteraction.remove(observer: self) } else { item.chatInteraction.add(observer: self) } } } @objc private func updateVisibleItems() { } private var previousRange: (Int, Int) = (0, 0) private var isCleaned: Bool = false private func layoutVisibleItems(animated: Bool) { guard let item = item as? PeerPhotosMonthItem else { return } CATransaction.begin() for (i, layout) in item.layoutItems.enumerated() { var view: MediaCell if self.contentViews[i] == nil || !self.contentViews[i]!.isKind(of: layout.viewType) { view = layout.viewType.init(frame: layout.frame) self.contentViews[i] = view } else { view = self.contentViews[i]! } if view.layoutItem != layout { view.update(layout: layout, context: item.context, table: item.table) } view.frame = layout.frame } containerView.subviews = self.contentViews.compactMap { $0 } CATransaction.commit() } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidMoveToWindow() { if window == nil { NotificationCenter.default.removeObserver(self) } else { NotificationCenter.default.addObserver(self, selector: #selector(updateVisibleItems), name: NSView.boundsDidChangeNotification, object: self.enclosingScrollView?.contentView) NotificationCenter.default.addObserver(self, selector: #selector(updateMouse), name: NSWindow.didBecomeKeyNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateMouse), name: NSWindow.didResignKeyNotification, object: nil) } updateVisibleItems() } override func layout() { super.layout() guard let item = item as? PeerPhotosMonthItem else { return } self.containerView.frame = NSMakeRect(floorToScreenPixels(backingScaleFactor, (frame.width - item.blockWidth) / 2), item.inset.top, item.blockWidth, frame.height - item.inset.bottom - item.inset.top) self.containerView.setCorners(item.viewType.corners) updateVisibleItems() } override func interactionContentView(for innerId: AnyHashable, animateIn: Bool) -> NSView { if let innerId = innerId.base as? MessageId { let view = contentViews.compactMap { $0 }.first(where: { $0.layoutItem?.message.id == innerId }) return view ?? NSView() } return self } override func addAccesoryOnCopiedView(innerId: AnyHashable, view: NSView) { if let innerId = innerId.base as? MessageId { let cell = contentViews.compactMap { $0 }.first(where: { $0.layoutItem?.message.id == innerId }) cell?.addAccesoryOnCopiedView(view: view) } } override func convertWindowPointToContent(_ point: NSPoint) -> NSPoint { return containerView.convert(point, from: nil) } override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? PeerPhotosMonthItem else { return } item.chatInteraction.add(observer: self) self.previousRange = (0, 0) while self.contentViews.count > item.layoutItems.count { self.contentViews.removeLast() } while self.contentViews.count < item.layoutItems.count { self.contentViews.append(nil) } layoutVisibleItems(animated: animated) } }
gpl-2.0
ba016c18a1c0c6bb0df2af0562874d83
37.803132
246
0.586163
5.341854
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Models/CoreData/CoreDataMigrations/CoreDataMigration.swift
1
711
// // CoreDataMigration.swift // MEGameTracker // // Created by Emily Ivie on 2/10/17. // Copyright © 2017 Emily Ivie. All rights reserved. // import Foundation public struct CoreDataMigration { enum MigrationError: String, Error { case missingOriginalStore = "Original store not found" case incompatibleModels = "Incompatible models" case missingModels = "Model not found" case invalidJson = "File JSON was not valid" } public let fromBuild: Int public let loadMigration: (() -> CoreDataMigrationType) public init(fromBuild: Int, loadMigration: @escaping (() -> CoreDataMigrationType)) { self.fromBuild = fromBuild self.loadMigration = loadMigration } }
mit
0afac8e1baacb667dc9aad1a85a6730f
27.4
86
0.707042
4.176471
false
false
false
false
applivery/applivery-ios-sdk
AppliverySDK/Applivery/Views/Feedback/Preview/PreviewVC.swift
1
2235
// // PreviewVC.swift // AppliverySDK // // Created by Alejandro Jiménez Agudo on 27/11/16. // Copyright © 2016 Applivery S.L. All rights reserved. // import UIKit class PreviewVC: UIViewController, UIGestureRecognizerDelegate { var screenshot: UIImage? { didSet { self.imageScreenshot?.image = self.screenshot } } var editedScreenshot: UIImage? { return self.imageScreenshot?.image } // PRIVATE private var brushWidth: CGFloat = 2 private var brushColor: UIColor = GlobalConfig.shared.palette.screenshotBrushColor private var lastPoint = CGPoint.zero // UI Properties @IBOutlet private weak var imageScreenshot: UIImageView? // MARK: - View's life cycle override func viewDidLoad() { super.viewDidLoad() } // MARK: - Gesture Delegate override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return logWarn("No touches found") } self.lastPoint = touch.location(in: self.imageScreenshot) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return logWarn("No touches found") } let currentPoint = touch.location(in: view) self.drawLineFrom(fromPoint: self.lastPoint, toPoint: currentPoint) self.lastPoint = currentPoint } func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) { guard let size = self.imageScreenshot?.frame.size.screenScaled() else { return logWarn("Could not retrieved size") } // Began to draw UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() self.imageScreenshot?.image?.draw(in: CGRect( x: 0, y: 0, width: size.width, height: size.height )) // Draw the line in the context context?.move(to: fromPoint.screenScaled()) context?.addLine(to: toPoint.screenScaled()) context?.setLineCap(.round) context?.setLineWidth(self.brushWidth * UIScreen.main.scale) context?.setStrokeColor(self.brushColor.cgColor) context?.setBlendMode(.normal) context?.strokePath() // En the draw self.imageScreenshot?.image = UIGraphicsGetImageFromCurrentImageContext() self.imageScreenshot?.alpha = 1.0 UIGraphicsEndImageContext() } }
mit
8750fee82e93b9e1dc9075f6d06d93fb
24.089888
83
0.722347
3.85
false
false
false
false
mking/ARTetris
ARTetris/TetrisEngine.swift
1
4414
// // TetrisEngine.swift // ARTetris // // Created by Yuri Strot on 6/30/17. // Copyright © 2017 Exyte. All rights reserved. // import Foundation import SceneKit /** Tetris game enigne */ class TetrisEngine { let config: TetrisConfig let well: TetrisWell let scene: TetrisScene let overlay: TetrisOverlay var current: TetrisState var timer: Timer? var scores = 0 var isRunning: Bool { get { return timer != nil } } init(_ config: TetrisConfig, _ well: TetrisWell, _ scene: TetrisScene, _ overlay: TetrisOverlay) { self.config = config self.well = well self.scene = scene self.current = .random(config) self.overlay = overlay startTimer() self.setState(current) } func rotateY(_ angle: Int) { setState(current.rotateY(angle)) } func rotateX(_ angle: Int) { setState(current.rotateX(angle)) } func forward() { setState(current.forward()) } func backward() { setState(current.backward()) } func left() { setState(current.left()) } func right() { setState(current.right()) } func drop() { animate(onComplete: addCurrentTetrominoToWell) { let initial = current while(!well.hasCollision(current.down())) { current = current.down() } return scene.drop(from: initial, to: current) } } func getProjection () -> TetrisState { var curCopy = current while(!well.hasCollision(curCopy.down())) { curCopy = curCopy.down() } return curCopy } func restart() { assert(!isRunning, "shouldn't restart game that isn't over") current = .random(config) startTimer() scores = 0 setState(current) well.restart() scene.restart() } private func setState(_ state: TetrisState) { // Disable movement while game is stopped if !isRunning { return } scene.showSideWall(well.hasSideCollision(state)) if (!well.hasCollision(state)) { self.current = state scene.show(state) let project = self.getProjection() scene.showProjection(project) } overlay.setScore(score: scores) } private func addCurrentTetrominoToWell() { let names = scene.addToWell(current) well.add(current, names) var transition = well.clearFilledLines() if (transition.isEmpty()) { nextTetromino() } else { animate(onComplete: nextTetromino) { var scores = 0 var result = 0.0 while transition.score > 0 { scores += transition.score print ("get score: ", transition.score) result += scene.removeLines(transition, scores) transition = well.clearFilledLines() } self.scores += getScores(scores) return result } } } private func nextTetromino() { repeat { current = .random(config) scene.enableProjectionNode() } while (well.hasSideCollision(current) > 0) if (well.hasCollision(current)) { stopTimer() scene.showGameOver(scores) } else { scene.show(current) } } private func getScores(_ lineCount: Int) -> Int { switch lineCount { case 1: return 100 case 2: return 300 case 3: return 500 case 4: return 800 default: return lineCount > 0 ? (Int(pow(3.0, Double(lineCount - 2))) * 100) : 0 } } private func animate(onComplete: @escaping () -> Void, block: () -> CFTimeInterval) { self.stopTimer() Timer.scheduledTimer(withTimeInterval: block(), repeats: false) { _ in self.startTimer() onComplete() } } private func startTimer() { self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in // When the current tetromino reaches the bottom, add it to the well. let down = self.current.down() let downProject = self.getProjection() if (down.y <= downProject.y) { self.scene.removeProjection() } if (self.well.hasCollision(down)) { self.addCurrentTetrominoToWell() } else { self.setState(down) } } } private func stopTimer() { timer?.invalidate() timer = nil } }
mit
b4cffbdd4732f1f1d0b48af6c8609896
23.381215
102
0.58305
3.982852
false
false
false
false
bitjammer/swift
test/SILGen/if_while_binding.swift
1
14655
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s func foo() -> String? { return "" } func bar() -> String? { return "" } func a(_ x: String) {} func b(_ x: String) {} func c(_ x: String) {} func marker_1() {} func marker_2() {} func marker_3() {} // CHECK-LABEL: sil hidden @_T016if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F func if_no_else() { // CHECK: [[FOO:%.*]] = function_ref @_T016if_while_binding3fooSSSgyF // CHECK: [[OPT_RES:%.*]] = apply [[FOO]]() // CHECK: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], default [[CONT:bb[0-9]+]] if let x = foo() { // CHECK: [[YES]]([[VAL:%[0-9]+]] : $String): // CHECK: [[A:%.*]] = function_ref @_T016if_while_binding1a // CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]] // CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]] // CHECK: apply [[A]]([[VAL_COPY]]) // CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]] // CHECK: destroy_value [[VAL]] // CHECK: br [[CONT]] a(x) } // CHECK: [[CONT]]: // CHECK-NEXT: tuple () } // CHECK: } // end sil function '_T016if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @_T016if_while_binding0A11_else_chainyyF : $@convention(thin) () -> () { func if_else_chain() { // CHECK: [[FOO:%.*]] = function_ref @_T016if_while_binding3foo{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: [[OPT_RES:%.*]] = apply [[FOO]]() // CHECK-NEXT: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YESX:bb[0-9]+]], default [[NOX:bb[0-9]+]] if let x = foo() { // CHECK: [[YESX]]([[VAL:%[0-9]+]] : $String): // CHECK: debug_value [[VAL]] : $String, let, name "x" // CHECK: [[A:%.*]] = function_ref @_T016if_while_binding1a // CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]] // CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]] // CHECK: apply [[A]]([[VAL_COPY]]) // CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]] // CHECK: destroy_value [[VAL]] // CHECK: br [[CONT_X:bb[0-9]+]] a(x) // CHECK: [[NOX]]: // CHECK: alloc_box ${ var String }, var, name "y" // CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YESY:bb[0-9]+]], default [[ELSE1:bb[0-9]+]] // CHECK: [[ELSE1]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: br [[ELSE:bb[0-9]+]] } else if var y = bar() { // CHECK: [[YESY]]([[VAL:%[0-9]+]] : $String): // CHECK: br [[CONT_Y:bb[0-9]+]] b(y) } else { // CHECK: [[ELSE]]: // CHECK: function_ref if_while_binding.c c("") // CHECK: br [[CONT_Y]] } // CHECK: [[CONT_Y]]: // br [[CONT_X]] // CHECK: [[CONT_X]]: } // CHECK-LABEL: sil hidden @_T016if_while_binding0B5_loopyyF : $@convention(thin) () -> () { func while_loop() { // CHECK: br [[LOOP_ENTRY:bb[0-9]+]] // CHECK: [[LOOP_ENTRY]]: // CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[LOOP_BODY:bb[0-9]+]], default [[LOOP_EXIT:bb[0-9]+]] while let x = foo() { // CHECK: [[LOOP_BODY]]([[X:%[0-9]+]] : $String): // CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] if let y = bar() { // CHECK: [[YES]]([[Y:%[0-9]+]] : $String): a(y) break // CHECK: destroy_value [[Y]] // CHECK: destroy_value [[X]] // CHECK: br [[LOOP_EXIT]] } // CHECK: [[NO]]: // CHECK: destroy_value [[X]] // CHECK: br [[LOOP_ENTRY]] } // CHECK: [[LOOP_EXIT]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // Don't leak alloc_stacks for address-only conditional bindings in 'while'. // <rdar://problem/16202294> // CHECK-LABEL: sil hidden @_T016if_while_binding0B13_loop_generic{{[_0-9a-zA-Z]*}}F // CHECK: br [[COND:bb[0-9]+]] // CHECK: [[COND]]: // CHECK: [[X:%.*]] = alloc_stack $T, let, name "x" // CHECK: [[OPTBUF:%[0-9]+]] = alloc_stack $Optional<T> // CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt.1: [[LOOPBODY:bb.*]], default [[OUT:bb[0-9]+]] // CHECK: [[OUT]]: // CHECK: dealloc_stack [[OPTBUF]] // CHECK: dealloc_stack [[X]] // CHECK: br [[DONE:bb[0-9]+]] // CHECK: [[LOOPBODY]]: // CHECK: [[ENUMVAL:%.*]] = unchecked_take_enum_data_addr // CHECK: copy_addr [take] [[ENUMVAL]] to [initialization] [[X]] // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // CHECK: br [[COND]] // CHECK: [[DONE]]: // CHECK: destroy_value %0 func while_loop_generic<T>(_ source: () -> T?) { while let x = source() { } } // <rdar://problem/19382942> Improve 'if let' to avoid optional pyramid of doom // CHECK-LABEL: sil hidden @_T016if_while_binding0B11_loop_multiyyF func while_loop_multi() { // CHECK: br [[LOOP_ENTRY:bb[0-9]+]] // CHECK: [[LOOP_ENTRY]]: // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[LOOP_EXIT0:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[LOOP_BODY:bb.*]], default [[LOOP_EXIT2a:bb[0-9]+]] // CHECK: [[LOOP_EXIT2a]]: // CHECK: destroy_value [[A]] // CHECK: br [[LOOP_EXIT0]] // CHECK: [[LOOP_BODY]]([[B:%[0-9]+]] : $String): while let a = foo(), let b = bar() { // CHECK: debug_value [[B]] : $String, let, name "b" // CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]] // CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]] // CHECK: debug_value [[A_COPY]] : $String, let, name "c" // CHECK: end_borrow [[BORROWED_A]] from [[A]] // CHECK: destroy_value [[A_COPY]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] // CHECK: br [[LOOP_ENTRY]] let c = a } // CHECK: [[LOOP_EXIT0]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_T016if_while_binding0A6_multiyyF func if_multi() { // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[IF_DONE:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b" // CHECK: [[PB:%[0-9]+]] = project_box [[B]] // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], default [[IF_EXIT1a:bb[0-9]+]] // CHECK: [[IF_EXIT1a]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE]] // CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : $String): if let a = foo(), var b = bar() { // CHECK: store [[BVAL]] to [init] [[PB]] : $*String // CHECK: debug_value {{.*}} : $String, let, name "c" // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE]] let c = a } // CHECK: [[IF_DONE]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_T016if_while_binding0A11_multi_elseyyF func if_multi_else() { // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[ELSE:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b" // CHECK: [[PB:%[0-9]+]] = project_box [[B]] // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], default [[IF_EXIT1a:bb[0-9]+]] // CHECK: [[IF_EXIT1a]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: destroy_value [[A]] // CHECK: br [[ELSE]] // CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : $String): if let a = foo(), var b = bar() { // CHECK: store [[BVAL]] to [init] [[PB]] : $*String // CHECK: debug_value {{.*}} : $String, let, name "c" // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE:bb[0-9]+]] let c = a } else { let d = 0 // CHECK: [[ELSE]]: // CHECK: debug_value {{.*}} : $Int, let, name "d" // CHECK: br [[IF_DONE]] } // CHECK: [[IF_DONE]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_T016if_while_binding0A12_multi_whereyyF func if_multi_where() { // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[ELSE:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: [[BBOX:%[0-9]+]] = alloc_box ${ var String }, var, name "b" // CHECK: [[PB:%[0-9]+]] = project_box [[BBOX]] // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECK_WHERE:bb.*]], default [[IF_EXIT1a:bb[0-9]+]] // CHECK: [[IF_EXIT1a]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: destroy_value [[A]] // CHECK: br [[ELSE]] // CHECK: [[CHECK_WHERE]]([[B:%[0-9]+]] : $String): // CHECK: function_ref Swift.Bool._getBuiltinLogicValue () -> Builtin.Int1 // CHECK: cond_br {{.*}}, [[IF_BODY:bb[0-9]+]], [[IF_EXIT3:bb[0-9]+]] // CHECK: [[IF_EXIT3]]: // CHECK: destroy_value [[BBOX]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE:bb[0-9]+]] if let a = foo(), var b = bar(), a == b { // CHECK: [[IF_BODY]]: // CHECK: destroy_value [[BBOX]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE]] let c = a } // CHECK: [[IF_DONE]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // <rdar://problem/19797158> Swift 1.2's "if" has 2 behaviors. They could be unified. // CHECK-LABEL: sil hidden @_T016if_while_binding0A16_leading_booleanySiF func if_leading_boolean(_ a : Int) { // Test the boolean condition. // CHECK: debug_value %0 : $Int, let, name "a" // CHECK: [[EQRESULT:%[0-9]+]] = apply {{.*}}(%0, %0{{.*}}) : $@convention({{.*}}) (Int, Int{{.*}}) -> Bool // CHECK-NEXT: [[EQRESULTI1:%[0-9]+]] = apply %2([[EQRESULT]]) : $@convention(method) (Bool) -> Builtin.Int1 // CHECK-NEXT: cond_br [[EQRESULTI1]], [[CHECKFOO:bb[0-9]+]], [[IFDONE:bb[0-9]+]] // Call Foo and test for the optional being present. // CHECK: [[CHECKFOO]]: // CHECK: [[OPTRESULT:%[0-9]+]] = apply {{.*}}() : $@convention(thin) () -> @owned Optional<String> // CHECK: switch_enum [[OPTRESULT]] : $Optional<String>, case #Optional.some!enumelt.1: [[SUCCESS:bb.*]], default [[IF_DONE:bb[0-9]+]] // CHECK: [[SUCCESS]]([[B:%[0-9]+]] : $String): // CHECK: debug_value [[B]] : $String, let, name "b" // CHECK: [[BORROWED_B:%.*]] = begin_borrow [[B]] // CHECK: [[B_COPY:%.*]] = copy_value [[BORROWED_B]] // CHECK: debug_value [[B_COPY]] : $String, let, name "c" // CHECK: end_borrow [[BORROWED_B]] from [[B]] // CHECK: destroy_value [[B_COPY]] // CHECK: destroy_value [[B]] // CHECK: br [[IFDONE]] if a == a, let b = foo() { let c = b } // CHECK: [[IFDONE]]: // CHECK-NEXT: tuple () } /// <rdar://problem/20364869> Assertion failure when using 'as' pattern in 'if let' class BaseClass {} class DerivedClass : BaseClass {} // CHECK-LABEL: sil hidden @_T016if_while_binding20testAsPatternInIfLetyAA9BaseClassCSgF func testAsPatternInIfLet(_ a : BaseClass?) { // CHECK: bb0([[ARG:%.*]] : $Optional<BaseClass>): // CHECK: debug_value [[ARG]] : $Optional<BaseClass>, let, name "a" // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] : $Optional<BaseClass> // CHECK: switch_enum [[ARG_COPY]] : $Optional<BaseClass>, case #Optional.some!enumelt.1: [[OPTPRESENTBB:bb[0-9]+]], default [[NILBB:bb[0-9]+]] // CHECK: [[NILBB]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br [[EXITBB:bb[0-9]+]] // CHECK: [[OPTPRESENTBB]]([[CLS:%.*]] : $BaseClass): // CHECK: checked_cast_br [[CLS]] : $BaseClass to $DerivedClass, [[ISDERIVEDBB:bb[0-9]+]], [[ISBASEBB:bb[0-9]+]] // CHECK: [[ISDERIVEDBB]]([[DERIVED_CLS:%.*]] : $DerivedClass): // CHECK: [[DERIVED_CLS_SOME:%.*]] = enum $Optional<DerivedClass>, #Optional.some!enumelt.1, [[DERIVED_CLS]] : $DerivedClass // CHECK: br [[MERGE:bb[0-9]+]]([[DERIVED_CLS_SOME]] : $Optional<DerivedClass>) // CHECK: [[ISBASEBB]]([[BASECLASS:%.*]] : $BaseClass): // CHECK: destroy_value [[BASECLASS]] : $BaseClass // CHECK: = enum $Optional<DerivedClass>, #Optional.none!enumelt // CHECK: br [[MERGE]]( // CHECK: [[MERGE]]([[OPTVAL:%[0-9]+]] : $Optional<DerivedClass>): // CHECK: switch_enum [[OPTVAL]] : $Optional<DerivedClass>, case #Optional.some!enumelt.1: [[ISDERIVEDBB:bb[0-9]+]], default [[NILBB:bb[0-9]+]] // CHECK: [[ISDERIVEDBB]]([[DERIVEDVAL:%[0-9]+]] : $DerivedClass): // CHECK: debug_value [[DERIVEDVAL]] : $DerivedClass // => SEMANTIC SIL TODO: This is benign, but scoping wise, this end borrow should be after derived val. // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[DERIVEDVAL]] : $DerivedClass // CHECK: br [[EXITBB]] // CHECK: [[EXITBB]]: // CHECK: destroy_value [[ARG]] : $Optional<BaseClass> // CHECK: tuple () // CHECK: return if case let b as DerivedClass = a { } } // <rdar://problem/22312114> if case crashes swift - bools not supported in let/else yet // CHECK-LABEL: sil hidden @_T016if_while_binding12testCaseBoolySbSgF func testCaseBool(_ value : Bool?) { // CHECK: bb0(%0 : $Optional<Bool>): // CHECK: switch_enum %0 : $Optional<Bool>, case #Optional.some!enumelt.1: bb1, default bb3 // CHECK: bb1(%3 : $Bool): // CHECK: [[ISTRUE:%[0-9]+]] = struct_extract %3 : $Bool, #Bool._value // CHECK: cond_br [[ISTRUE]], bb2, bb3 // CHECK: bb2: // CHECK: function_ref @_T016if_while_binding8marker_1yyF // CHECK: br bb3{{.*}} // id: %8 if case true? = value { marker_1() } // CHECK: bb3: // Preds: bb2 bb1 bb0 // CHECK: switch_enum %0 : $Optional<Bool>, case #Optional.some!enumelt.1: bb4, default bb6 // CHECK: bb4( // CHECK: [[ISTRUE:%[0-9]+]] = struct_extract %10 : $Bool, #Bool._value{{.*}}// user: %12 // CHECK: cond_br [[ISTRUE]], bb6, bb5 // CHECK: bb5: // CHECK: function_ref @_T016if_while_binding8marker_2yyF // CHECK: br bb6{{.*}} // id: %15 // CHECK: bb6: // Preds: bb5 bb4 bb3 if case false? = value { marker_2() } }
apache-2.0
5e5dde18f7ff289b6842158e7d00b73f
39.040984
148
0.540089
3.034161
false
false
false
false
marcelganczak/swift-js-transpiler
test/weheartswift/loops-16.swift
1
185
var a = 24 var b = 18 var maxDiv = a if b < maxDiv { maxDiv = b } var gcd = 1 for i in 1...maxDiv { if (a % i == 0) && (b % i == 0){ gcd = i } } print(gcd) // 6
mit
6f18f56df0f3e5f28d3b774474e210ab
9.333333
36
0.427027
2.3125
false
false
false
false
aotian16/Blog
Study/Dev/Swift/SwiftDesignPatterns/SwiftDesignPatterns_Mediator.playground/Contents.swift
1
2050
// 中介者模式 // 来自网络:类之间的交互行为被统一放在Mediator的对象中,对象通过Mediator对象同其他对象交互,Mediator对象起着控制器的作用 // 设计模式分类:行为型模式 /// 对象抽象 class Colleague { let name: String let mediator: Mediator init(name: String, mediator: Mediator) { self.name = name self.mediator = mediator } /** 发送消息 - parameter message: 消息 */ func send(message: String) { print("Colleague \(name) send: \(message)") mediator.send(message, colleague: self) } /** 接收消息 - parameter message: 消息 */ func receive(message: String) { assert(false, "Method should be overriden") } } /** * 中介者接口 */ protocol Mediator { /** 发送消息 - parameter message: 消息 - parameter colleague: 发送者 */ func send(message: String, colleague: Colleague) } /// 具体中介者 class MessageMediator: Mediator { private var colleagues: [Colleague] = [] func addColleague(colleague: Colleague) { colleagues.append(colleague) } func send(message: String, colleague: Colleague) { for c in colleagues { if c !== colleague { //for simplicity we compare object references c.receive(message) } } } } /// 具体对象 class ConcreteColleague: Colleague { override func receive(message: String) { print("Colleague \(name) received: \(message)") } } let messagesMediator = MessageMediator() let user0 = ConcreteColleague(name: "张三", mediator: messagesMediator) let user1 = ConcreteColleague(name: "李四", mediator: messagesMediator) let user2 = ConcreteColleague(name: "王五", mediator: messagesMediator) messagesMediator.addColleague(user0) messagesMediator.addColleague(user1) messagesMediator.addColleague(user2) user0.send("Hello") // user1 receives message
cc0-1.0
dd24f69dc23c24cf1acae59b94862862
21.9
78
0.631004
3.939785
false
false
false
false
hweetty/EasyTransitioning
EasyTransitioning/Classes/Actions/ETCornerRadiusAction.swift
1
1243
// // ETCornerRadiusAction.swift // EasyTransitioning // // Created by Jerry Yu on 2016-11-12. // Copyright © 2016 Jerry Yu. All rights reserved. // import UIKit public struct ETCornerRadiusAction: ETAction { public let toCornerRadius: CGFloat public let fromCornerRadius: CGFloat public init(toCornerRadius: CGFloat, fromCornerRadius: CGFloat) { self.toCornerRadius = toCornerRadius self.fromCornerRadius = fromCornerRadius } public func setup(snapshotView: UIView?, in containerView: UIView) { guard let snapshotView = snapshotView else { return } snapshotView.layer.cornerRadius = fromCornerRadius } public func animate(snapshotView: UIView?, in containerView: UIView, animationDuration: TimeInterval) { guard let snapshotView = snapshotView else { return } snapshotView.layer.masksToBounds = true let animation = CABasicAnimation(keyPath: "cornerRadius") animation.fromValue = snapshotView.layer.cornerRadius animation.duration = animationDuration snapshotView.layer.cornerRadius = toCornerRadius snapshotView.layer.add(animation, forKey: "cornerRadius") } public func reversed() -> ETAction { return ETCornerRadiusAction(toCornerRadius: fromCornerRadius, fromCornerRadius: toCornerRadius) } }
mit
5b77d5456deb0efe36e11111953f2720
31.684211
104
0.782609
4.435714
false
false
false
false
zhaobin19918183/zhaobinCode
miniship/minishop/HomeViewController/ShoppingCartViewCobtroller/TextViewController.swift
1
1001
// // TextViewController.swift // CSNavTabBarController-Demo // // Created by iMacHCS on 15/11/19. // Copyright © 2015年 CS. All rights reserved. // import UIKit class TextViewController: UIViewController { var textLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() print("text viewDidLoad") self.view.backgroundColor = UIColor.orange self.view.layer.borderColor = UIColor.green.cgColor self.view.layer.borderWidth = 60 textLabel = UILabel(frame: CGRect.zero) textLabel.text = self.title textLabel.sizeToFit() self.view.addSubview(textLabel) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() textLabel.center = CGPoint(x: self.view.width / 2.0, y: self.view.height / 2.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
e9e7ab60d3ac4037a33c6eee9b638852
24.589744
87
0.655311
4.495495
false
false
false
false
raulriera/HuntingCompanion
ProductHunt/CollectionsCollectionViewController.swift
1
3881
// // CollectionsCollectionViewController.swift // ProductHunt // // Created by Raúl Riera on 03/05/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit import HuntingKit class CollectionsCollectionViewController: UICollectionViewController { private var collections = [Collection]() { didSet { collectionView?.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Do any additional setup after loading the view. let request = ProductHunt.Endpoint.Collections(featured: true) ProductHunt.sendRequest(request) { [unowned self] response in switch response { case .Success(let box): self.collections = box.unbox case .Failure(let box): self.displayError(box.unbox) } } } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return collections.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(.CollectionCollectionViewCell, forIndexPath: indexPath) as! CollectionCollectionViewCell cell.collection = collections[indexPath.row] return cell } // MARK: Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == .ShowCollectionSegue { if let destinationViewController = segue.destinationViewController.contentViewController as? CollectionViewController { if let indexPaths = collectionView?.indexPathsForSelectedItems() as? [NSIndexPath] { destinationViewController.collection = collections[indexPaths.first!.row] } } } } // MARK: UICollectionViewDelegate override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { performSegue(.ShowCollectionSegue) } // MARK: UIContentContainer override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { collectionView?.collectionViewLayout.invalidateLayout() } } extension CollectionsCollectionViewController : UICollectionViewDelegateFlowLayout { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let size:CGSize let minimumInteritemSpacing:CGFloat = (collectionViewLayout as! UICollectionViewFlowLayout).minimumInteritemSpacing let screen = UIScreen.mainScreen().bounds.size let cellWidth: CGFloat let cellHeight: CGFloat let availableVerticalSpace = screen.height - collectionView.contentInset.top - collectionView.contentInset.bottom if traitCollection.horizontalSizeClass == .Regular { cellWidth = (screen.width - minimumInteritemSpacing) / 2 } else { cellWidth = screen.width } cellHeight = min(cellWidth * 0.75, availableVerticalSpace) size = CGSize(width: cellWidth, height: cellHeight) return size } }
mit
3b85062fcb7b5691a2489bbc65cb6190
34.281818
142
0.662887
6.598639
false
false
false
false
jhurray/SQLiteModel-Example-Project
iOS+SQLiteModel/Pods/Neon/Source/NeonAnchorable.swift
3
7951
// // NeonAnchorable.swift // Neon // // Created by Mike on 10/1/15. // Copyright © 2015 Mike Amaral. All rights reserved. // #if os(iOS) import UIKit #else import Cocoa #endif public protocol Anchorable : Frameable {} public extension Anchorable { /// Fill the superview, with optional padding values. /// /// - note: If you don't want padding, simply call `fillSuperview()` with no parameters. /// /// - parameters: /// - left: The padding between the left side of the view and the superview. /// /// - right: The padding between the right side of the view and the superview. /// /// - top: The padding between the top of the view and the superview. /// /// - bottom: The padding between the bottom of the view and the superview. /// public func fillSuperview(left left: CGFloat = 0, right: CGFloat = 0, top: CGFloat = 0, bottom: CGFloat = 0) { let width : CGFloat = superFrame.width - (left + right) let height : CGFloat = superFrame.height - (top + bottom) frame = CGRectMake(left, top, width, height) } /// Anchor a view in the center of its superview. /// /// - parameters: /// - width: The width of the view. /// /// - height: The height of the view. /// public func anchorInCenter(width width: CGFloat, height: CGFloat) { let xOrigin : CGFloat = (superFrame.width / 2.0) - (width / 2.0) let yOrigin : CGFloat = (superFrame.height / 2.0) - (height / 2.0) frame = CGRectMake(xOrigin, yOrigin, width, height) if height == AutoHeight { self.setHeightAutomatically() self.anchorInCenter(width: width, height: self.height) } } /// Anchor a view in one of the four corners of its superview. /// /// - parameters: /// - corner: The `CornerType` value used to specify in which corner the view will be anchored. /// /// - xPad: The *horizontal* padding applied to the view inside its superview, which can be applied /// to the left or right side of the view, depending upon the `CornerType` specified. /// /// - yPad: The *vertical* padding applied to the view inside its supeview, which will either be on /// the top or bottom of the view, depending upon the `CornerType` specified. /// /// - width: The width of the view. /// /// - height: The height of the view. /// public func anchorInCorner(corner: Corner, xPad: CGFloat, yPad: CGFloat, width: CGFloat, height: CGFloat) { var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 switch corner { case .TopLeft: xOrigin = xPad yOrigin = yPad case .BottomLeft: xOrigin = xPad yOrigin = superFrame.height - height - yPad case .TopRight: xOrigin = superFrame.width - width - xPad yOrigin = yPad case .BottomRight: xOrigin = superFrame.width - width - xPad yOrigin = superFrame.height - height - yPad } frame = CGRectMake(xOrigin, yOrigin, width, height) if height == AutoHeight { self.setHeightAutomatically() self.anchorInCorner(corner, xPad: xPad, yPad: yPad, width: width, height: self.height) } } /// Anchor a view in its superview, centered on a given edge. /// /// - parameters: /// - edge: The `Edge` used to specify which face of the superview the view /// will be anchored against and centered relative to. /// /// - padding: The padding applied to the view inside its superview. How this padding is applied /// will vary depending on the `Edge` provided. Views centered against the top or bottom of /// their superview will have the padding applied above or below them respectively, whereas views /// centered against the left or right side of their superview will have the padding applied to the /// right and left sides respectively. /// /// - width: The width of the view. /// /// - height: The height of the view. /// public func anchorToEdge(edge: Edge, padding: CGFloat, width: CGFloat, height: CGFloat) { var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 switch edge { case .Top: xOrigin = (superFrame.width / 2.0) - (width / 2.0) yOrigin = padding case .Left: xOrigin = padding yOrigin = (superFrame.height / 2.0) - (height / 2.0) case .Bottom: xOrigin = (superFrame.width / 2.0) - (width / 2.0) yOrigin = superFrame.height - height - padding case .Right: xOrigin = superFrame.width - width - padding yOrigin = (superFrame.height / 2.0) - (height / 2.0) } frame = CGRectMake(xOrigin, yOrigin, width, height) if height == AutoHeight { self.setHeightAutomatically() self.anchorToEdge(edge, padding: padding, width: width, height: self.height) } } /// Anchor a view in its superview, centered on a given edge and filling either the width or /// height of that edge. For example, views anchored to the `.Top` or `.Bottom` will have /// their widths automatically sized to fill their superview, with the xPad applied to both /// the left and right sides of the view. /// /// - parameters: /// - edge: The `Edge` used to specify which face of the superview the view /// will be anchored against, centered relative to, and expanded to fill. /// /// - xPad: The horizontal padding applied to the view inside its superview. If the `Edge` /// specified is `.Top` or `.Bottom`, this padding will be applied to the left and right sides /// of the view when it fills the width superview. /// /// - yPad: The vertical padding applied to the view inside its superview. If the `Edge` /// specified is `.Left` or `.Right`, this padding will be applied to the top and bottom sides /// of the view when it fills the height of the superview. /// /// - otherSize: The size parameter that is *not automatically calculated* based on the provided /// edge. For example, views anchored to the `.Top` or `.Bottom` will have their widths automatically /// calculated, so `otherSize` will be applied to their height, and subsequently views anchored to /// the `.Left` and `.Right` will have `otherSize` applied to their width as their heights are /// automatically calculated. /// public func anchorAndFillEdge(edge: Edge, xPad: CGFloat, yPad: CGFloat, otherSize: CGFloat) { var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var width : CGFloat = 0.0 var height : CGFloat = 0.0 var autoSize : Bool = false switch edge { case .Top: xOrigin = xPad yOrigin = yPad width = superFrame.width - (2 * xPad) height = otherSize autoSize = true case .Left: xOrigin = xPad yOrigin = yPad width = otherSize height = superFrame.height - (2 * yPad) case .Bottom: xOrigin = xPad yOrigin = superFrame.height - otherSize - yPad width = superFrame.width - (2 * xPad) height = otherSize autoSize = true case .Right: xOrigin = superFrame.width - otherSize - xPad yOrigin = yPad width = otherSize height = superFrame.height - (2 * yPad) } frame = CGRectMake(xOrigin, yOrigin, width, height) if height == AutoHeight && autoSize { self.setHeightAutomatically() self.anchorAndFillEdge(edge, xPad: xPad, yPad: yPad, otherSize: self.height) } } }
mit
2ae09f5f9a4dde66469566b736ac1592
35.30137
114
0.599748
4.494064
false
false
false
false
ByteriX/BxInputController
BxInputController/Sources/Rows/Date/BxInputSelectorDateRow.swift
1
2713
/** * @file BxInputSelectorDateRow.swift * @namespace BxInputController * * @details Selector row for choosing date from selector below this row * @date 12.01.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Row for choosing date from selector below this row open class BxInputSelectorDateRow : BxInputDateRow, BxInputSelectorRow { /// Make and return Binder for binding row with cell. override open var binder : BxInputRowBinder { return BxInputSelectorDateRowBinder<BxInputSelectorDateRow, BxInputSelectorCell>(row: self) } override open var resourceId : String { get { return "BxInputSelectorCell" } } override open var estimatedHeight : CGFloat { get { return 54 } } open var isOpened: Bool = false open var timeForAutoselection: TimeInterval = 0.0 // if < 0.5 then autoselection turned off public var child : BxInputChildSelectorDateRow public var children: [BxInputChildSelectorRow] { get { return [child] } } override public init(title: String? = nil, subtitle: String? = nil, placeholder: String? = nil, value: Date? = nil) { child = BxInputChildSelectorDateRow() super.init(title: title, subtitle: subtitle, placeholder: placeholder, value: value) child.parent = self } } /// Row for selector date. Is single child of BxInputSelectorDateRow open class BxInputChildSelectorDateRow: BxInputChildSelectorRow, BxInputStaticHeight { /// Make and return Binder for binding row with cell. open var binder : BxInputRowBinder { return BxInputChildSelectorDateRowBinder<BxInputChildSelectorDateRow, BxInputChildSelectorDateCell, BxInputSelectorDateRow>(row: self) } open var resourceId : String = "BxInputChildSelectorDateCell" open var height : CGFloat = 216 open var estimatedHeight : CGFloat { get { return height } } open var title : String? { get { return parent?.title ?? nil } } open var subtitle: String? { get { return parent?.subtitle ?? nil } } open var placeholder : String? { get { return parent?.placeholder ?? nil } } open var isEnabled : Bool { get { return parent?.isEnabled ?? false } set { parent?.isEnabled = newValue } } weak open var parent: BxInputSelectorRow? = nil }
mit
7efd755c26a3c9019d926277a36f3fa8
29.829545
142
0.647254
4.726481
false
false
false
false
ksco/swift-algorithm-club-cn
Combinatorics/Combinatorics.playground/Contents.swift
1
3843
//: Playground - noun: a place where people can play /* Calculates n! */ func factorial(n: Int) -> Int { var n = n var result = 1 while n > 1 { result *= n n -= 1 } return result } factorial(5) factorial(20) /* Calculates P(n, k), the number of permutations of n distinct symbols in groups of size k. */ func permutations(n: Int, _ k: Int) -> Int { var n = n var answer = n for _ in 1..<k { n -= 1 answer *= n } return answer } permutations(5, 3) permutations(50, 6) permutations(9, 4) /* Prints out all the permutations of the given array. Original algorithm by Niklaus Wirth. See also Dr.Dobb's Magazine June 1993, Algorithm Alley */ func permuteWirth<T>(a: [T], _ n: Int) { if n == 0 { print(a) // display the current permutation } else { var a = a permuteWirth(a, n - 1) for i in 0..<n { swap(&a[i], &a[n]) permuteWirth(a, n - 1) swap(&a[i], &a[n]) } } } let letters = ["a", "b", "c", "d", "e"] print("Permutations of \(letters):") permuteWirth(letters, letters.count - 1) let xyz = [ "x", "y", "z" ] print("\nPermutations of \(xyz):") permuteWirth(xyz, 2) /* Prints out all the permutations of an n-element collection. The initial array must be initialized with all zeros. The algorithm uses 0 as a flag that indicates more work to be done on each level of the recursion. Original algorithm by Robert Sedgewick. See also Dr.Dobb's Magazine June 1993, Algorithm Alley */ func permuteSedgewick(a: [Int], _ n: Int, inout _ pos: Int) { var a = a pos += 1 a[n] = pos if pos == a.count - 1 { print(a) // display the current permutation } else { for i in 0..<a.count { if a[i] == 0 { permuteSedgewick(a, i, &pos) } } } pos -= 1 a[n] = 0 } print("\nSedgewick permutations:") let numbers = [0, 0, 0, 0] // must be all zeros var pos = -1 permuteSedgewick(numbers, 0, &pos) /* Calculates C(n, k), or "n-choose-k", i.e. how many different selections of size k out of a total number of distinct elements (n) you can make. */ func combinations(n: Int, _ k: Int) -> Int { return permutations(n, k) / factorial(k) } combinations(3, 2) combinations(28, 5) print("\nCombinations:") for i in 1...20 { print("\(20)-choose-\(i) = \(combinations(20, i))") } /* Calculates C(n, k), or "n-choose-k", i.e. the number of ways to choose k things out of n possibilities. */ func quickBinomialCoefficient(n: Int, _ k: Int) -> Int { var result = 1 for i in 0..<k { result *= (n - i) result /= (i + 1) } return result } quickBinomialCoefficient(8, 2) quickBinomialCoefficient(30, 15) /* Supporting code because Swift doesn't have a built-in 2D array. */ struct Array2D<T> { let columns: Int let rows: Int private var array: [T] init(columns: Int, rows: Int, initialValue: T) { self.columns = columns self.rows = rows array = .init(count: rows*columns, repeatedValue: initialValue) } subscript(column: Int, row: Int) -> T { get { return array[row*columns + column] } set { array[row*columns + column] = newValue } } } /* Calculates C(n, k), or "n-choose-k", i.e. the number of ways to choose k things out of n possibilities. Thanks to the dynamic programming, this algorithm from Skiena allows for the calculation of much larger numbers, at the cost of temporary storage space for the cached values. */ func binomialCoefficient(n: Int, _ k: Int) -> Int { var bc = Array2D(columns: n + 1, rows: n + 1, initialValue: 0) for i in 0...n { bc[i, 0] = 1 bc[i, i] = 1 } if n > 0 { for i in 1...n { for j in 1..<i { bc[i, j] = bc[i - 1, j - 1] + bc[i - 1, j] } } } return bc[n, k] } binomialCoefficient(30, 15) binomialCoefficient(66, 33)
mit
055b0d4426c3de51ae1745b08bf6ceb2
19.66129
74
0.606037
3.109223
false
false
false
false
yichizhang/SwiftCGRectExtensions
CGRectExtensions/Demo.playground/section-1.swift
1
1377
// This playground requires Xcode 6.1. // Make sure to compile the CGRectExtensionsOSX target first. import Foundation import CGRectExtensions let rect = CGRect(1, 2, 100, 200) // shorter constructor let minY = rect.minY // shortcut properties let topCenter = rect.topCenter // OS-dependent coordinate system let oppositeOrigin = rect.origin + rect.size // adding let corneredRect = rect.with(x: 0, y: 0) // modified copy let nextPageRect = rect.rectByOffsetting(dx: 100) // offsetting let paddedRect = rect.rectByInsetting(top: 66, left: 10, right: 10) // insetting let quarterSize = rect.size * 0.5 // scaling sizes let corner = rect.rectByAligning(quarterSize, corner: .MinXEdge, .MinYEdge) // aligning sizes let halfWidthSize = rect.size * (0.5, 1) // scaling sizes let centeredRect = rect.rectByCentering(halfWidthSize) // centering sizes let scaledRect = rect * CGAffineTransformMakeScale(2.0, 3.0) // mutating functions import Cocoa let view = NSView() view.frame.size = CGSize(width: 100, height: 200) view.frame.bottomLeft = CGPoint(x: 1, y: 2) view.frame.offset(25, 25) view.frame.inset(top: 66, left: 10, right: 10) view.frame.setSizeCentered(CGSize(50, 50)) view.frame.setSizeCentered(CGSize(50, 50), alignTo: .MinXEdge) view.frame.setSizeAligned(CGSize(50, 50), corner: .MinXEdge, .MinYEdge) view.frame *= CGAffineTransformMakeScale(2.0, 3.0)
mit
d2b4eaad0d2b3d01fd1d36527945654e
27.6875
93
0.741467
3.358537
false
false
false
false
zeroc-ice/ice
swift/src/Ice/InputStream.swift
3
62179
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import IceImpl /// Stream class to read (unmarshal) Slice types from a sequence of bytes. public class InputStream { let data: Data let classResolverPrefix: [String]? private(set) var pos: Int = 0 private(set) var communicator: Communicator private let encoding: EncodingVersion private let traceSlicing: Bool fileprivate let acceptClassCycles: Bool private var encaps: Encaps! private var startSeq: Int32 = -1 private var minSeqSize: Int32 = 0 private let classGraphDepthMax: Int32 private var remaining: Int { return data.count - pos } var currentEncoding: EncodingVersion { return encaps != nil ? encaps.encoding : encoding } public convenience init(communicator: Communicator, bytes: Data) { let encoding = (communicator as! CommunicatorI).defaultsAndOverrides.defaultEncoding self.init(communicator: communicator, encoding: encoding, bytes: bytes) } public required init(communicator: Communicator, encoding: EncodingVersion, bytes: Data) { data = bytes classResolverPrefix = (communicator as! CommunicatorI).initData.classResolverPrefix self.communicator = communicator self.encoding = encoding classGraphDepthMax = (communicator as! CommunicatorI).classGraphDepthMax traceSlicing = (communicator as! CommunicatorI).traceSlicing acceptClassCycles = (communicator as! CommunicatorI).acceptClassCycles } /// Reads an encapsulation from the stream. /// /// - returns: `(bytes: Data, encoding: EncodingVersion)` The encapsulation. public func readEncapsulation() throws -> (bytes: Data, encoding: EncodingVersion) { let sz: Int32 = try read() if sz < 6 { throw UnmarshalOutOfBoundsException(reason: "Invalid size") } if sz - 4 > remaining { throw UnmarshalOutOfBoundsException(reason: "Invalid size") } let encoding: EncodingVersion = try read() try changePos(offset: -6) let bytes = data[pos ..< pos + Int(sz)] return (bytes, encoding) } /// Reads the start of an encapsulation. /// /// - returns: `Ice.EncodingVersion` - The encapsulation encoding version. @discardableResult public func startEncapsulation() throws -> EncodingVersion { precondition(encaps == nil, "Nested or sequential encapsulations are not supported") let start = pos // // I don't use readSize() and writeSize() for encapsulations, // because when creating an encapsulation, I must know in advance // how many bytes the size information will require in the data // stream. If I use an Int, it is always 4 bytes. For // readSize()/writeSize(), it could be 1 or 5 bytes. // let sz: Int32 = try read() if sz < 6 { throw UnmarshalOutOfBoundsException(reason: "invalid size") } if sz - 4 > remaining { throw UnmarshalOutOfBoundsException(reason: "invalid size") } let encoding: EncodingVersion = try read() try checkSupportedEncoding(encoding) encaps = Encaps(start: start, size: Int(sz), encoding: encoding) return encoding } /// Ends the previous encapsulation. public func endEncapsulation() throws { if !encaps.encoding_1_0 { try skipOptionals() if pos != encaps.start + encaps.sz { throw EncapsulationException(reason: "buffer size does not match decoded encapsulation size") } } else if pos != encaps.start + encaps.sz { if pos + 1 != encaps.start + encaps.sz { throw EncapsulationException(reason: "buffer size does not match decoded encapsulation size") } // // Ice version < 3.3 had a bug where user exceptions with // class members could be encoded with a trailing byte // when dispatched with AMD. So we tolerate an extra byte // in the encapsulation. // try skip(1) } } /// Skips an empty encapsulation. /// /// - returns: `Ice.EncodingVersion` - The encapsulation's encoding version. @discardableResult func skipEmptyEncapsulation() throws -> EncodingVersion { let sz: Int32 = try read() if sz < 6 { throw EncapsulationException(reason: "invalid size") } if sz - 4 > remaining { throw UnmarshalOutOfBoundsException(reason: "") } let encoding: EncodingVersion = try read() try checkSupportedEncoding(encoding) // Make sure the encoding is supported. if encoding == Encoding_1_0 { if sz != 6 { throw EncapsulationException(reason: "") } } else { // // Skip the optional content of the encapsulation if we are expecting an // empty encapsulation. // try skip(sz - 6) } return encoding } /// Skips over an encapsulation. /// /// - returns: `Ice.EncodingVersion` - The encoding version of the skipped encapsulation. func skipEncapsulation() throws -> EncodingVersion { let sz: Int32 = try read() if sz < 6 { throw EncapsulationException(reason: "invalid size") } let encodingVersion: EncodingVersion = try read() try changePos(offset: Int(sz) - 6) return encodingVersion } /// Reads the start of a class instance or exception slice. /// /// - returns: The Slice type ID for this slice. @discardableResult public func startSlice() throws -> String { precondition(encaps.decoder != nil) return try encaps.decoder.startSlice() } /// Indicates that the end of a class instance or exception slice has been reached. public func endSlice() throws { precondition(encaps.decoder != nil) try encaps.decoder.endSlice() } /// Skips over a class instance or exception slice. public func skipSlice() throws { precondition(encaps.decoder != nil) try encaps.decoder.skipSlice() } /// Indicates that unmarshaling is complete, except for any class instances. The application must call this method /// only if the stream actually contains class instances. Calling `readPendingValues` triggers the /// calls to consumers provided with {@link #readValue} to inform the application that unmarshaling of an instance /// is complete. public func readPendingValues() throws { if encaps.decoder != nil { try encaps.decoder.readPendingValues() } else if encaps.encoding_1_0 { // // If using the 1.0 encoding and no instances were read, we // still read an empty sequence of pending instances if // requested (i.e.: if this is called). // // This is required by the 1.0 encoding, even if no instances // are written we do marshal an empty sequence if marshaled // data types use classes. // try skipSize() } } /// Extracts a user exception from the stream and throws it. public func throwException() throws { initEncaps() try encaps.decoder.throwException() } func skipOptional(format: OptionalFormat) throws { switch format { case .F1: try skip(1) case .F2: try skip(2) case .F4: try skip(4) case .F8: try skip(8) case .Size: try skipSize() case .VSize: try skip(readSize()) case .FSize: try skip(read()) case .Class: try read(UnknownSlicedValue.self, cb: nil) } } func skipOptionals() throws { // // Skip remaining un-read optional members. // while true { if pos >= encaps.start + encaps.sz { return // End of encapsulation also indicates end of optionals. } let v: UInt8 = try read() if v == SliceFlags.OPTIONAL_END_MARKER.rawValue { return } // Read first 3 bits. guard let format = OptionalFormat(rawValue: v & 0x07) else { preconditionFailure("invalid optional format") } if v >> 3 == 30 { try skipSize() } try skipOptional(format: format) } } // Reset the InputStream to prepare for retry internal func startOver() { pos = 0 encaps = nil } private func changePos(offset: Int) throws { precondition(pos + offset >= 0, "Negative position") guard offset <= remaining else { throw UnmarshalOutOfBoundsException(reason: "Attempt to move past end of buffer") } pos += offset } /// Skips the given number of bytes. /// /// - parameter _: `Int` - The number of bytes to skip. public func skip(_ count: Int) throws { precondition(count >= 0, "skip count is negative") try changePos(offset: count) } /// Skips the given number of bytes. /// /// - parameter _: `Int32` - The number of bytes to skip. public func skip(_ count: Int32) throws { try changePos(offset: Int(count)) } /// Skip over a size value. public func skipSize() throws { let b: UInt8 = try read() if b == 255 { try skip(4) } } /// Marks the start of a class instance. public func startValue() { precondition(encaps.decoder != nil) encaps.decoder.startInstance(type: .ValueSlice) } /// Marks the end of a class instance. /// /// - parameter preserve: `Bool` - True if unknown slices should be preserved, false otherwise. /// /// - returns: `Ice.SlicedData` - A SlicedData object containing the preserved slices for unknown types. @discardableResult public func endValue(preserve: Bool) throws -> SlicedData? { precondition(encaps.decoder != nil) return try encaps.decoder.endInstance(preserve: preserve) } /// Marks the start of a user exception. public func startException() { precondition(encaps.decoder != nil) encaps.decoder.startInstance(type: .ExceptionSlice) } /// Marks the end of a user exception. /// /// - parameter preserve: `Bool` - True if unknown slices should be preserved, false otherwise. /// /// - returns: `Ice.SlicedData?` - A `SlicedData` object containing the preserved slices for unknown /// types. @discardableResult public func endException(preserve: Bool) throws -> SlicedData? { precondition(encaps.decoder != nil) return try encaps.decoder.endInstance(preserve: preserve) } func initEncaps() { if encaps == nil { encaps = Encaps(start: 0, size: data.count, encoding: encoding) } if encaps.decoder == nil { // Lazy initialization let valueFactoryManager = communicator.getValueFactoryManager() if encaps.encoding_1_0 { encaps.decoder = EncapsDecoder10(stream: self, valueFactoryManager: valueFactoryManager, classGraphDepthMax: classGraphDepthMax) } else { encaps.decoder = EncapsDecoder11(stream: self, valueFactoryManager: valueFactoryManager, classGraphDepthMax: classGraphDepthMax) } } } fileprivate func traceSkipSlice(typeId: String, sliceType: SliceType) { guard traceSlicing else { return } ICETraceUtil.traceSlicing(kind: sliceType == SliceType.ExceptionSlice ? "exception" : "object", typeId: typeId, slicingCat: "Slicing", logger: LoggerWrapper(handle: communicator.getLogger())) } static func throwUOE(expectedType: Value.Type, v: Value) throws { // // If the object is an unknown sliced object, we didn't find an // value factory, in this case raise a NoValueFactoryException // instead. // if let usv = v as? UnknownSlicedValue { throw NoValueFactoryException(reason: "", type: usv.ice_id()) } throw UnexpectedObjectException(reason: "expected element of type `\(expectedType)' but received `\(v)'", type: v.ice_id(), expectedType: expectedType.ice_staticId()) } } public extension InputStream { /// Reads a numeric value from the stream. /// /// - returns: `Element` - The numeric value read from the stream. func read<Element>() throws -> Element where Element: StreamableNumeric { let size = MemoryLayout<Element>.size guard size <= remaining else { throw UnmarshalOutOfBoundsException(reason: "attempting to read past buffer capacity") } var value: Element = 0 // We assume a little-endian platform withUnsafeMutablePointer(to: &value) { ptr in let buf = UnsafeMutableBufferPointer(start: ptr, count: 1) self.data.copyBytes(to: buf, from: self.pos ..< self.pos + size) } pos += size return value } /// Reads an optional numeric value from the stream. /// /// - parameter tag: `Int32` - The tag of the optional data member or parameter. /// /// - returns: `Element?` - The optional numeric value read from the stream. func read<Element>(tag: Int32) throws -> Element? where Element: StreamableNumeric { let expectedFormat = OptionalFormat(fixedSize: MemoryLayout<Element>.size) guard try readOptional(tag: tag, expectedFormat: expectedFormat!) else { return nil } return try read() } /// Reads a sequence of numeric values from the stream. /// /// - returns: `[Element]` - The sequence of numeric values read from the stream. func read<Element>() throws -> [Element] where Element: StreamableNumeric { let sz = try readAndCheckSeqSize(minSize: MemoryLayout<Element>.size) if sz == 0 { return [Element]() } else { let eltSize = MemoryLayout<Element>.size if sz == 1 || eltSize == MemoryLayout<Element>.stride { // Can copy directly from bytes to array var a = [Element](repeating: 0, count: sz) pos += a.withUnsafeMutableBufferPointer { buf in self.data.copyBytes(to: buf, from: self.pos ..< self.pos + sz * eltSize) } return a } else { var a = [Element]() a.reserveCapacity(sz) for _ in 0 ..< sz { try a.append(read()) } return a } } } /// Reads an optional sequence of numeric values from the stream. /// /// - parameter tag: `Int32` - The tag of the optional data member or parameter. /// /// - returns: `[Element]?` - The optional sequence read from the stream. func read<Element>(tag: Int32) throws -> [Element]? where Element: StreamableNumeric { guard try readOptional(tag: tag, expectedFormat: .VSize) else { return nil } if MemoryLayout<Element>.size > 1 { try skipSize() } return try read() } /// Reads a byte from the stream. /// /// - returns: `UInt8` - The byte read from the stream. func read() throws -> UInt8 { guard remaining > 0 else { throw UnmarshalOutOfBoundsException(reason: "attempting to read past buffer capacity") } let value = data[pos] pos += 1 return value } /// Reads a sequence of bytes from the stream. /// /// - returns: `[UInt8]` - The sequence of bytes read from the stream. func read() throws -> [UInt8] { let sz = try readAndCheckSeqSize(minSize: 1) let start = pos pos += sz return [UInt8](data[start ..< pos]) } /// Reads a sequence of bytes from the stream. /// /// - returns: `Data` - The sequence of bytes read from the stream. func read() throws -> Data { let sz = try readAndCheckSeqSize(minSize: 1) let start = pos pos += sz return data.subdata(in: start ..< pos) // copy } /// Reads an optional sequence of bytes from the stream. /// /// - parameter tag: `Int32` - The tag of the optional data member or parameter. /// /// - returns: `Data?` - The optional sequence of bytes read from the stream. func read(tag: Int32) throws -> Data? { guard try readOptional(tag: tag, expectedFormat: .VSize) else { return nil } // No skipSize here return try read() } /// Reads a boolean value from the stream. /// /// - returns: `Bool` - The boolean value read from the stream. func read() throws -> Bool { let value: UInt8 = try read() return value == 1 } /// Reads an optional boolean value from the stream. /// /// - parameter tag: `Int32` - The tag of the optional data member or parameter. /// /// - returns: `Bool?` - The optional boolean value read from the stream. func read(tag: Int32) throws -> Bool? { guard try readOptional(tag: tag, expectedFormat: .F1) else { return nil } return try read() as Bool } /// Reads a sequence of boolean value from the stream. /// /// - returns: `[Bool]` - The sequence of boolean values read from the stream. func read() throws -> [Bool] { let sz = try readAndCheckSeqSize(minSize: 1) if sz == 0 { return [Bool]() } else if MemoryLayout<Bool>.size == 1, MemoryLayout<Bool>.stride == 1 { // Copy directly from bytes to array var a = [Bool](repeating: false, count: sz) pos += a.withUnsafeMutableBufferPointer { buf in self.data.copyBytes(to: buf, from: self.pos ..< self.pos + sz) } return a } else { fatalError("Unsupported Bool memory layout") } } /// Reads an optional sequence of boolean value from the stream. /// /// - parameter tag: `Int32` - The tag of the optional data member or parameter. /// /// - returns: `[Bool]?` - The optional sequence of boolean values read from the stream. func read(tag: Int32) throws -> [Bool]? { guard try readOptional(tag: tag, expectedFormat: .VSize) else { return nil } return try read() } /// Reads a size from the stream. /// /// - returns: `Int32` - The size read from the stream. func readSize() throws -> Int32 { let byteVal: UInt8 = try read() if byteVal == 255 { return try read() } else { return Int32(byteVal) } } /// Reads a sequence size from the stream and ensures the stream has enough /// bytes for `size` elements, where each element's size is at least minSize. /// /// - parameter minSize: `Int` - The mininum element size to use for the check. /// /// - returns: `Int` - The size read from the stream. func readAndCheckSeqSize(minSize: Int) throws -> Int { let sz = try Int(readSize()) guard sz != 0 else { return sz } // // The startSeq variable points to the start of the sequence for which // we expect to read at least minSeqSize bytes from the stream. // // If not initialized or if we already read more data than minSeqSize, // we reset startSeq and minSeqSize for this sequence (possibly a // top-level sequence or enclosed sequence it doesn't really matter). // // Otherwise, we are reading an enclosed sequence and we have to bump // minSeqSize by the minimum size that this sequence will require on // the stream. // // The goal of this check is to ensure that when we start un-marshalling // a new sequence, we check the minimal size of this new sequence against // the estimated remaining buffer size. This estimatation is based on // the minimum size of the enclosing sequences, it's minSeqSize. // if startSeq == -1 || pos > (startSeq + minSeqSize) { startSeq = Int32(pos) minSeqSize = Int32(sz * minSize) } else { minSeqSize += Int32(sz * minSize) } // // If there isn't enough data to read on the stream for the sequence (and // possibly enclosed sequences), something is wrong with the marshalled // data: it's claiming having more data that what is possible to read. // if startSeq + minSeqSize > data.count { throw UnmarshalOutOfBoundsException(reason: "bad sequence size") } return sz } // // Optional // func readOptional(tag: Int32, expectedFormat: OptionalFormat) throws -> Bool { if encaps.decoder != nil { return try encaps.decoder.readOptional(tag: tag, format: expectedFormat) } return try readOptionalImpl(readTag: tag, expectedFormat: expectedFormat) } internal func readOptionalImpl(readTag: Int32, expectedFormat: OptionalFormat) throws -> Bool { if encaps.encoding_1_0 { return false // Optional members aren't supported with the 1.0 encoding. } while true { if pos >= encaps.start + encaps.sz { return false // End of encapsulation also indicates end of optionals. } let v: UInt8 = try read() if v == SliceFlags.OPTIONAL_END_MARKER.rawValue { try changePos(offset: -1) // Rewind return false } // First 3 bits. guard let format = OptionalFormat(rawValue: v & 0x07) else { throw MarshalException(reason: "invalid optional format") } var tag = Int32(v >> 3) if tag == 30 { tag = try readSize() } if tag > readTag { let offset = tag < 30 ? -1 : (tag < 255 ? -2 : -6) // Rewind try changePos(offset: offset) return false // No optional data members with the requested tag } else if tag < readTag { try skipOptional(format: format) // Skip optional data members } else { if format != expectedFormat { throw MarshalException(reason: "invalid optional data member `\(tag)': unexpected format") } return true } } } /// Reads an enumerator from the stream, as a byte. /// /// - parameter enumMaxValue: `Int32` - The maximum value for the enumerators (used only for the 1.0 encoding). /// /// - returns: `UInt8` - The enumerator's byte value. func read(enumMaxValue: Int32) throws -> UInt8 { if currentEncoding == Encoding_1_0 { if enumMaxValue < 127 { return try read() } else if enumMaxValue < 32767 { let v: Int16 = try read() guard v <= UInt8.max else { throw UnmarshalOutOfBoundsException(reason: "1.0 encoded enum value is larger than UInt8") } return UInt8(v) } else { let v: Int32 = try read() guard v <= UInt8.max else { throw UnmarshalOutOfBoundsException(reason: "1.0 encoded enum value is larger than UInt8") } return UInt8(v) } } else { let v = try readSize() guard v <= UInt8.max else { throw UnmarshalOutOfBoundsException(reason: "1.1 encoded enum value is larger than UInt8") } return UInt8(v) } } /// Reads an enumerator from the stream, as a Int32. /// /// - parameter enumMaxValue: `Int32` - The maximum value for the enumerators (used only for the 1.0 encoding). /// /// - returns: `Int32` - The enumerator's Int32 value. func read(enumMaxValue: Int32) throws -> Int32 { if currentEncoding == Encoding_1_0 { if enumMaxValue < 127 { return Int32(try read() as UInt8) } else if enumMaxValue < 32767 { return Int32(try read() as Int16) } else { return try read() } } else { return try readSize() } } /// Reads a string from the stream. /// /// - returns: `String` - The string read from the stream. func read() throws -> String { let size = try readSize() if size == 0 { return "" } else { let start = pos try skip(size) let end = pos guard let str = String(data: data[start ..< end], encoding: .utf8) else { throw MarshalException(reason: "unable to read string") } return str } } /// Reads an optional string from the stream. /// /// - parameter tag: `Int32` - The tag of the optional data member or parameter. /// /// - returns: `String?` - The optional string read from the stream. func read(tag: Int32) throws -> String? { guard try readOptional(tag: tag, expectedFormat: .VSize) else { return nil } return try read() as String } /// Reads a sequence of strings from the stream. /// /// - returns: `[String]` - The sequence of strings read from the stream. func read() throws -> [String] { let sz = try readAndCheckSeqSize(minSize: 1) var r: [String] = [String]() r.reserveCapacity(sz) for _ in 0 ..< sz { r.append(try read()) } return r } /// Reads an optional sequence of strings from the stream. /// /// - parameter tag: `Int32` - The tag of the optional data member or parameter. /// /// - returns: `[String]?` - The optional sequence of strings read from the stream. func read(tag: Int32) throws -> [String]? { guard try readOptional(tag: tag, expectedFormat: .FSize) else { return nil } try skip(4) return try read() as [String] } /// Reads a proxy from the stream (internal helper). /// /// - returns: `ProxyImpl?` - The proxy read from the stream. func read<ProxyImpl>() throws -> ProxyImpl? where ProxyImpl: ObjectPrxI { return try ProxyImpl.ice_read(from: self) } /// Reads an optional proxy from the stream (internal helper). /// /// - parameter tag: `Int32` - The tag of the optional data member or parameter. /// /// - returns: `ProxyImpl?` - The proxy read from the stream. func read<ProxyImpl>(tag: Int32) throws -> ProxyImpl? where ProxyImpl: ObjectPrxI { guard try readOptional(tag: tag, expectedFormat: .FSize) else { return nil } try skip(4) return try read() as ProxyImpl? } /// Reads a base proxy from the stream. /// /// - returns: `ObjectPrx?` - The proxy read from the stream. func read(_: ObjectPrx.Protocol) throws -> ObjectPrx? { return try read() as ObjectPrxI? } /// Reads an optional base proxy from the stream. /// /// - parameter tag: `Int32` - The tag of the optional data member or parameter. ///  /// - returns: `ObjectPrx?` - The proxy read from the stream. func read(tag: Int32, type _: ObjectPrx.Protocol) throws -> ObjectPrx? { return try read(tag: tag) as ObjectPrxI? } /// Reads a value from the stream. func read(cb: ((Value?) throws -> Void)?) throws { initEncaps() try encaps.decoder.readValue(cb: cb) } /// Reads an optional value from the stream. func read(tag: Int32, cb: ((Value?) throws -> Void)?) throws { if try readOptional(tag: tag, expectedFormat: .Class) { try read(cb: cb) } } /// Reads a value from the stream. func read<ValueType>(_ value: ValueType.Type, cb: ((ValueType?) -> Void)?) throws where ValueType: Value { initEncaps() if let cb = cb { try encaps.decoder.readValue { v in if v == nil || v is ValueType { cb(v as? ValueType) } else { try InputStream.throwUOE(expectedType: value, v: v!) } } } else { try encaps.decoder.readValue(cb: nil) } } /// Reads an optional value from the stream. func read<ValueType>(tag: Int32, value: ValueType.Type, cb: ((ValueType?) -> Void)?) throws where ValueType: Value { if try readOptional(tag: tag, expectedFormat: .Class) { try read(value, cb: cb) } } } private class Encaps { let start: Int let sz: Int let encoding: EncodingVersion let encoding_1_0: Bool var decoder: EncapsDecoder! init(start: Int, size: Int, encoding: EncodingVersion) { self.start = start sz = size self.encoding = encoding encoding_1_0 = encoding == Ice.Encoding_1_0 } } private enum SliceType { case NoSlice case ValueSlice case ExceptionSlice } private typealias Callback = (Value?) throws -> Void private struct PatchEntry { let cb: Callback let classGraphDepth: Int32 fileprivate init(cb: @escaping Callback, classGraphDepth: Int32) { self.cb = cb self.classGraphDepth = classGraphDepth } } private protocol EncapsDecoder: AnyObject { var stream: InputStream { get } var valueFactoryManager: ValueFactoryManager { get } // // Encapsulation attributes for value unmarshaling. // var patchMap: [Int32: [PatchEntry]] { get set } var unmarshaledMap: [Int32: Value?] { get set } var typeIdMap: [Int32: String] { get set } var typeIdIndex: Int32 { get set } var valueList: [Value] { get set } var typeIdCache: [String: Value.Type?] { get set } var classGraphDepthMax: Int32 { get } var classGraphDepth: Int32 { get set } func readValue(cb: Callback?) throws func throwException() throws func startInstance(type: SliceType) func endInstance(preserve: Bool) throws -> SlicedData? func startSlice() throws -> String func endSlice() throws func skipSlice() throws func readOptional(tag: Int32, format: OptionalFormat) throws -> Bool func readPendingValues() throws } extension EncapsDecoder { func readOptional(tag _: Int32, format _: OptionalFormat) throws -> Bool { return false } func readPendingValues() throws {} func readTypeId(isIndex: Bool) throws -> String { if isIndex { let index = try stream.readSize() guard let typeId = typeIdMap[index] else { throw UnmarshalOutOfBoundsException(reason: "invalid typeId") } return typeId } else { let typeId: String = try stream.read() typeIdIndex += 1 typeIdMap[typeIdIndex] = typeId return typeId } } func resolveClass(typeId: String) throws -> Value.Type? { if let cls = typeIdCache[typeId] { return cls } else { var cls: Value.Type? for prefix in stream.classResolverPrefix ?? [] { cls = ClassResolver.resolve(typeId: typeId, prefix: prefix) if cls != nil { break } } if cls == nil { cls = ClassResolver.resolve(typeId: typeId) } typeIdCache[typeId] = cls return cls } } func newInstance(typeId: String) throws -> Value? { // // Try to find a factory registered for the specific type. // if let factory = valueFactoryManager.find(typeId) { if let v = factory(typeId) { return v } } // // If that fails, invoke the default factory if one has been // registered. // if let factory = valueFactoryManager.find("") { if let v = factory(typeId) { return v } } // // Last chance: try to instantiate the class dynamically. // if let cls = try resolveClass(typeId: typeId) { return cls.init() } return nil } func addPatchEntry(index: Int32, cb: @escaping Callback) throws { precondition(index > 0, "invalid index") // // Check if we already unmarshaled the object. If that's the case, just patch the object smart pointer // and we're done. A null value indicates we've encountered a cycle and Ice.AllowClassCycles is false. // if let optObj = unmarshaledMap[index] { guard let obj = optObj else { assert(!stream.acceptClassCycles) throw MarshalException(reason: "cycle detected during Value unmarshaling") } try cb(obj) return } // // Add patch entry if the instance isn't unmarshaled yet, // the callback will be called when the instance is // unmarshaled. // var entries = patchMap[index] ?? [] entries.append(PatchEntry(cb: cb, classGraphDepth: classGraphDepth)) patchMap[index] = entries } func unmarshal(index: Int32, v: Value) throws { // // Add the instance to the map of unmarshaled instances, this must // be done before reading the instances (for circular references). // // If circular references are not allowed we insert null (for cycle detection) and add // the object to the map once it has been fully unmarshaled. // unmarshaledMap[index] = stream.acceptClassCycles ? v : (nil as Value?) assert(unmarshaledMap[index] != nil) // // Read the instance. // try v._iceRead(from: stream) // // Patch all instances now that the instance is unmarshaled. // if let l = patchMap[index] { precondition(!l.isEmpty) // // Patch all pointers that refer to the instance. // for entry in l { try entry.cb(v) } // // Clear out the patch map for that index -- there is nothing left // to patch for that index for the time being. // patchMap.removeValue(forKey: index) } if patchMap.isEmpty, valueList.isEmpty { v.ice_postUnmarshal() } else { valueList.append(v) if patchMap.isEmpty { // // Iterate over the instance list and invoke ice_postUnmarshal on // each instance. We must do this after all instances have been // unmarshaled in order to ensure that any instance data members // have been properly patched. // for p in valueList { p.ice_postUnmarshal() } valueList.removeAll() } } if !stream.acceptClassCycles { // This class has been fully unmarshaled without creating any cycles // It can be added to the map now. unmarshaledMap[index] = v } } } private class EncapsDecoder10: EncapsDecoder { // EncapsDecoder members unowned let stream: InputStream let valueFactoryManager: ValueFactoryManager lazy var patchMap = [Int32: [PatchEntry]]() lazy var unmarshaledMap = [Int32: Value?]() lazy var typeIdMap = [Int32: String]() var typeIdIndex: Int32 = 0 lazy var valueList = [Value]() lazy var typeIdCache = [String: Value.Type?]() // Value/exception attributes var sliceType: SliceType var skipFirstSlice: Bool! // Slice attributes var sliceSize: Int32! var typeId: String! let classGraphDepthMax: Int32 var classGraphDepth: Int32 init(stream: InputStream, valueFactoryManager: ValueFactoryManager, classGraphDepthMax: Int32) { self.stream = stream self.valueFactoryManager = valueFactoryManager sliceType = SliceType.NoSlice self.classGraphDepthMax = classGraphDepthMax classGraphDepth = 0 } func readValue(cb: Callback?) throws { guard let cb = cb else { preconditionFailure("patch fuction can not be nil") } // // Object references are encoded as a negative integer in 1.0. // var index: Int32 = try stream.read() if index > 0 { throw MarshalException(reason: "invalid object id") } index = -index if index == 0 { try cb(nil) } else { try addPatchEntry(index: index, cb: cb) } } func throwException() throws { precondition(sliceType == .NoSlice) // // User exception with the 1.0 encoding start with a boolean flag // that indicates whether or not the exception has classes. // // This allows reading the pending instances even if some part of // the exception was sliced. // let usesClasses: Bool = try stream.read() sliceType = .ExceptionSlice skipFirstSlice = false // // Read the first slice header. // try startSlice() let mostDerivedId = typeId! while true { // // Look for user exception // var userExceptionType: UserException.Type? for prefix in stream.classResolverPrefix ?? [] { userExceptionType = ClassResolver.resolve(typeId: typeId, prefix: prefix) if userExceptionType != nil { break } } if userExceptionType == nil { userExceptionType = ClassResolver.resolve(typeId: typeId) } // // We found the exception. // if let type = userExceptionType { let ex = type.init() try ex._iceRead(from: stream) if usesClasses { try readPendingValues() } throw ex } // // Slice off what we don't understand. // try skipSlice() do { try startSlice() } catch let ex as UnmarshalOutOfBoundsException { // // An oversight in the 1.0 encoding means there is no marker to indicate // the last slice of an exception. As a result, we just try to read the // next type ID, which raises UnmarshalOutOfBoundsException when the // input buffer underflows. // // Set the reason member to a more helpful message. // ex.reason = "unknown exception type `\(mostDerivedId)'" throw ex } } } func startInstance(type: SliceType) { precondition(sliceType == type) skipFirstSlice = true } func endInstance(preserve _: Bool) throws -> SlicedData? { // // Read the Ice::Value slice. // if sliceType == .ValueSlice { try startSlice() let sz = try stream.readSize() // For compatibility with the old AFM. if sz != 0 { throw MarshalException(reason: "invalid Object slice") } try endSlice() } sliceType = .NoSlice return nil } @discardableResult func startSlice() throws -> String { // // If first slice, don't read the header, it was already read in // readInstance or throwException to find the factory. // if skipFirstSlice { skipFirstSlice = false return typeId } // // For class instances, first read the type ID boolean which indicates // whether or not the type ID is encoded as a string or as an // index. For exceptions, the type ID is always encoded as a // string. // if sliceType == .ValueSlice { let isIndex: Bool = try stream.read() typeId = try readTypeId(isIndex: isIndex) } else { typeId = try stream.read() } sliceSize = try stream.read() if sliceSize < 4 { throw UnmarshalOutOfBoundsException(reason: "invalid slice size") } return typeId } func endSlice() throws {} func skipSlice() throws { stream.traceSkipSlice(typeId: typeId, sliceType: sliceType) try stream.skip(sliceSize - 4) } func readPendingValues() throws { var num: Int32 repeat { num = try stream.readSize() for _ in 0 ..< num { try readInstance() } } while num > 0 if !patchMap.isEmpty { // // If any entries remain in the patch map, the sender has sent an index for an object, but failed // to supply the object. // throw MarshalException(reason: "index for class received, but no instance") } } func readInstance() throws { let index: Int32 = try stream.read() if index <= 0 { throw MarshalException(reason: "invalid object id") } sliceType = SliceType.ValueSlice skipFirstSlice = false // // Read the first slice header. // try startSlice() let mostDerivedId = typeId! var v: Value! while true { // // For the 1.0 encoding, the type ID for the base Object class // marks the last slice. // if typeId == "::Ice::Object" { throw NoValueFactoryException(reason: "invalid typeId", type: mostDerivedId) } v = try newInstance(typeId: typeId) // // We found a factory, we get out of this loop. // if v != nil { break } // // Slice off what we don't understand. // try skipSlice() try startSlice() // Read next Slice header for next iteration. } // // Compute the biggest class graph depth of this object. To compute this, // we get the class graph depth of each ancestor from the patch map and // keep the biggest one. // classGraphDepth = 0 if let l = patchMap[index] { precondition(l.count > 0) classGraphDepth = l.reduce(0) { max($0, $1.classGraphDepth) } } classGraphDepth += 1 if classGraphDepth > classGraphDepthMax { throw MarshalException(reason: "maximum class graph depth reached") } // // Unmarshal the instance and add it to the map of unmarshaled instances. // try unmarshal(index: index, v: v) } } private class EncapsDecoder11: EncapsDecoder { // EncapsDecoder members unowned let stream: InputStream let valueFactoryManager: ValueFactoryManager lazy var patchMap = [Int32: [PatchEntry]]() lazy var unmarshaledMap = [Int32: Value?]() lazy var typeIdMap = [Int32: String]() var typeIdIndex: Int32 = 0 lazy var valueList = [Value]() lazy var typeIdCache = [String: Value.Type?]() let classGraphDepthMax: Int32 var classGraphDepth: Int32 private var current: InstanceData! var valueIdIndex: Int32 = 1 // The ID of the next instance to unmarshal. lazy var compactIdCache = [Int32: Value.Type]() // Cache of compact type IDs. private struct IndirectPatchEntry { var index: Int32 var cb: Callback init(index: Int32, cb: @escaping Callback) { self.index = index self.cb = cb } } private class InstanceData { // Instance attributes var sliceType: SliceType! var skipFirstSlice: Bool! lazy var slices = [SliceInfo]() // Preserved slices. lazy var indirectionTables = [[Int32]]() // Slice attributes var sliceFlags: SliceFlags! var sliceSize: Int32! var typeId: String! var compactId: Int32! lazy var indirectPatchList = [IndirectPatchEntry]() let previous: InstanceData? weak var next: InstanceData? init(previous: InstanceData?) { self.previous = previous next = nil previous?.next = self } } init(stream: InputStream, valueFactoryManager: ValueFactoryManager, classGraphDepthMax: Int32) { self.stream = stream self.valueFactoryManager = valueFactoryManager self.classGraphDepthMax = classGraphDepthMax classGraphDepth = 0 } func readValue(cb: Callback?) throws { let index = try stream.readSize() if index < 0 { throw MarshalException(reason: "invalid object id") } else if index == 0 { try cb?(nil) } else if current != nil, current.sliceFlags.contains(.FLAG_HAS_INDIRECTION_TABLE) { // // When reading a class instance within a slice and there's an // indirect instance table, always read an indirect reference // that points to an instance from the indirect instance table // marshaled at the end of the Slice. // // Maintain a list of indirect references. Note that the // indirect index starts at 1, so we decrement it by one to // derive an index into the indirection table that we'll read // at the end of the slice. // if let cb = cb { current.indirectPatchList.append(IndirectPatchEntry(index: index - 1, cb: cb)) } } else { _ = try readInstance(index: index, cb: cb) } } func throwException() throws { precondition(current == nil) push(sliceType: .ExceptionSlice) // // Read the first slice header. // try startSlice() let mostDerivedId = current.typeId! while true { // // Look for user exception // var userExceptionType: UserException.Type? for prefix in stream.classResolverPrefix ?? [] { userExceptionType = ClassResolver.resolve(typeId: current.typeId, prefix: prefix) if userExceptionType != nil { break } } if userExceptionType == nil { userExceptionType = ClassResolver.resolve(typeId: current.typeId) } // // We found the exception. // if let userEx = userExceptionType { let ex = userEx.init() try ex._iceRead(from: stream) throw ex } // // Slice off what we don't understand. // try skipSlice() if current.sliceFlags.contains(.FLAG_IS_LAST_SLICE) { if let range = mostDerivedId.range(of: "::") { throw UnknownUserException(unknown: String(mostDerivedId[range.upperBound...])) } else { throw UnknownUserException(unknown: mostDerivedId) } } try startSlice() } } func startInstance(type: SliceType) { precondition(current.sliceType == type) current.skipFirstSlice = true } func endInstance(preserve: Bool) throws -> SlicedData? { var slicedData: SlicedData? if preserve { slicedData = try readSlicedData() } current.slices.removeAll() current.indirectionTables.removeAll() current = current.previous return slicedData } @discardableResult func startSlice() throws -> String { // // If first slice, don't read the header, it was already read in // readInstance or throwException to find the factory. // if current.skipFirstSlice { current.skipFirstSlice = false return current.typeId } current.sliceFlags = try SliceFlags(rawValue: stream.read()) // // Read the type ID, for value slices the type ID is encoded as a // string or as an index, for exceptions it's always encoded as a // string. // if current.sliceType == .ValueSlice { // Must be checked 1st! if current.sliceFlags.contains(.FLAG_HAS_TYPE_ID_COMPACT) { current.typeId = "" current.compactId = try stream.readSize() } else if current.sliceFlags.contains(.FLAG_HAS_TYPE_ID_INDEX) || current.sliceFlags.contains(.FLAG_HAS_TYPE_ID_STRING) { current.typeId = try readTypeId(isIndex: current.sliceFlags.contains(.FLAG_HAS_TYPE_ID_INDEX)) current.compactId = -1 } else { // // Only the most derived slice encodes the type ID for the compact format. // current.typeId = "" current.compactId = -1 } } else { current.typeId = try stream.read() current.compactId = -1 } // // Read the slice size if necessary. // if current.sliceFlags.contains(SliceFlags.FLAG_HAS_SLICE_SIZE) { current.sliceSize = try stream.read() if current.sliceSize < 4 { throw UnmarshalOutOfBoundsException(reason: "invalid slice size") } } else { current.sliceSize = 0 } return current.typeId } func endSlice() throws { if current.sliceFlags.contains(.FLAG_HAS_OPTIONAL_MEMBERS) { try stream.skipOptionals() } // // Read the indirection table if one is present and transform the // indirect patch list into patch entries with direct references. // if current.sliceFlags.contains(.FLAG_HAS_INDIRECTION_TABLE) { var indirectionTable = [Int32](repeating: 0, count: Int(try stream.readAndCheckSeqSize(minSize: 1))) for i in 0 ..< indirectionTable.count { indirectionTable[i] = try readInstance(index: stream.readSize(), cb: nil) } // // Sanity checks. If there are optional members, it's possible // that not all instance references were read if they are from // unknown optional data members. // if indirectionTable.isEmpty { throw MarshalException(reason: "empty indirection table") } if current.indirectPatchList.isEmpty, !current.sliceFlags.contains(.FLAG_HAS_OPTIONAL_MEMBERS) { throw MarshalException(reason: "no references to indirection table") } // // Convert indirect references into direct references. // for e in current.indirectPatchList { precondition(e.index >= 0) if e.index >= indirectionTable.count { throw MarshalException(reason: "indirection out of range") } try addPatchEntry(index: indirectionTable[Int(e.index)], cb: e.cb) } current.indirectPatchList.removeAll() } } func skipSlice() throws { stream.traceSkipSlice(typeId: current.typeId, sliceType: current.sliceType) let start = stream.pos if current.sliceFlags.contains(.FLAG_HAS_SLICE_SIZE) { precondition(current.sliceSize >= 4) try stream.skip(current.sliceSize - 4) } else { if current.sliceType == .ValueSlice { throw NoValueFactoryException(reason: "no value factory found and compact format prevents " + "slicing (the sender should use the sliced format instead)", type: current.typeId) } else { if let r = current.typeId.range(of: "::") { throw UnknownUserException(unknown: String(current.typeId[r.upperBound...])) } else { throw UnknownUserException(unknown: current.typeId) } } } // // Preserve this slice. // let hasOptionalMembers = current.sliceFlags.contains(.FLAG_HAS_OPTIONAL_MEMBERS) let isLastSlice = current.sliceFlags.contains(.FLAG_IS_LAST_SLICE) var dataEnd = stream.pos if hasOptionalMembers { // // Don't include the optional member end marker. It will be re-written by // endSlice when the sliced data is re-written. // dataEnd -= 1 } let bytes = stream.data.subdata(in: start ..< dataEnd) // copy let info = SliceInfo(typeId: current.typeId, compactId: current.compactId, bytes: bytes, instances: [], hasOptionalMembers: hasOptionalMembers, isLastSlice: isLastSlice) // // Read the indirect instance table. We read the instances or their // IDs if the instance is a reference to an already unmarhsaled // instance. // // The SliceInfo object sequence is initialized only if // readSlicedData is called. // if current.sliceFlags.contains(.FLAG_HAS_INDIRECTION_TABLE) { var indirectionTable = [Int32](repeating: 0, count: Int(try stream.readAndCheckSeqSize(minSize: 1))) for i in 0 ..< indirectionTable.count { indirectionTable[i] = try readInstance(index: stream.readSize(), cb: nil) } current.indirectionTables.append(indirectionTable) } else { current.indirectionTables.append([]) } current.slices.append(info) } func readOptional(tag: Int32, format: OptionalFormat) throws -> Bool { if current == nil { return try stream.readOptionalImpl(readTag: tag, expectedFormat: format) } else if current.sliceFlags.contains(.FLAG_HAS_OPTIONAL_MEMBERS) { return try stream.readOptionalImpl(readTag: tag, expectedFormat: format) } return false } func readInstance(index: Int32, cb: Callback?) throws -> Int32 { precondition(index > 0) if index > 1 { if let cb = cb { try addPatchEntry(index: index, cb: cb) } return index } push(sliceType: .ValueSlice) // // Get the instance ID before we start reading slices. If some // slices are skipped, the indirect instance table is still read and // might read other instances. // valueIdIndex += 1 let index = valueIdIndex // // Read the first slice header. // try startSlice() let mostDerivedId = current.typeId! var v: Value? while true { var updateCache = false if current.compactId >= 0 { updateCache = true // // Translate a compact (numeric) type ID into a class. // if !compactIdCache.isEmpty { // // Check the cache to see if we've already translated the compact type ID into a class. // if let cls: Value.Type = compactIdCache[current.compactId] { v = cls.init() updateCache = false } } // // If we haven't already cached a class for the compact ID, then try to translate the // compact ID into a type ID. // if v == nil { current.typeId = TypeIdResolver.resolve(compactId: current.compactId) ?? "" } } if v == nil, !current.typeId.isEmpty { v = try newInstance(typeId: current.typeId) } if let v = v { if updateCache { precondition(current.compactId >= 0) compactIdCache[current.compactId] = type(of: v) } // // We have an instance, get out of this loop. // break } // // Slice off what we don't understand. // try skipSlice() // // If this is the last slice, keep the instance as an opaque // UnknownSlicedValue object. // if current.sliceFlags.contains(.FLAG_IS_LAST_SLICE) { // // Provide a factory with an opportunity to supply the instance. // We pass the "::Ice::Object" ID to indicate that this is the // last chance to preserve the instance. // v = try newInstance(typeId: "::Ice::Object") if v == nil { v = UnknownSlicedValue(unknownTypeId: mostDerivedId) } break } try startSlice() // Read next Slice header for next iteration. } classGraphDepth += 1 if classGraphDepth > classGraphDepthMax { throw MarshalException(reason: "maximum class graph depth reached") } // // Unmarshal the instance. // try unmarshal(index: index, v: v!) classGraphDepth -= 1 if current == nil, !patchMap.isEmpty { // // If any entries remain in the patch map, the sender has sent an index for an instance, but failed // to supply the instance. // throw MarshalException(reason: "index for class received, but no instance") } try cb?(v) return index } func readSlicedData() throws -> SlicedData? { // No preserved slices. if current.slices.isEmpty { return nil } // // The _indirectionTables member holds the indirection table for each slice // in _slices. // precondition(current.slices.count == current.indirectionTables.count) for n in 0 ..< current.slices.count { // // We use the "instances" list in SliceInfo to hold references // to the target instances. Note that the instances might not have // been read yet in the case of a circular reference to an // enclosing instance. let sz = current.indirectionTables[n].count current.slices[n].instances = [Ice.Value]() current.slices[n].instances.reserveCapacity(sz) for j in 0 ..< sz { try addPatchEntry(index: current.indirectionTables[n][j]) { v in self.current.slices[n].instances.append(v!) } } } return SlicedData(slices: current.slices) } func push(sliceType: SliceType) { if current == nil { current = InstanceData(previous: nil) } else { current = current.next ?? InstanceData(previous: current) } current.sliceType = sliceType current.skipFirstSlice = false } } public struct DictEntry<K, V> { public var key: K! public var value: UnsafeMutablePointer<V>! public init(key: K? = nil, value: UnsafeMutablePointer<V>? = nil) { self.key = key self.value = value } } public class DictEntryArray<K, V> { public var values: [DictEntry<K, V>] public init(size: Int) { values = [DictEntry<K, V>](repeating: DictEntry<K, V>(), count: size) } } /// A Numeric type that can be marshaled (written) using an OutputStream and /// unmarshaled (read) using an InputStream public protocol StreamableNumeric: Numeric {} extension UInt8: StreamableNumeric {} extension Int16: StreamableNumeric {} extension Int32: StreamableNumeric {} extension Int64: StreamableNumeric {} extension Float: StreamableNumeric {} extension Double: StreamableNumeric {}
gpl-2.0
49bc433b7c4366e76a96248e18dc60a0
32.42957
120
0.558774
4.985887
false
false
false
false
gottesmm/swift
test/IRGen/generic_tuples.swift
4
7284
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s | %FileCheck %s // Make sure that optimization passes don't choke on storage types for generic tuples // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -O %s // REQUIRES: CPU=x86_64 // CHECK: [[TYPE:%swift.type]] = type { // CHECK: [[OPAQUE:%swift.opaque]] = type opaque // CHECK: [[TUPLE_TYPE:%swift.tuple_type]] = type { [[TYPE]], i64, i8*, [0 x %swift.tuple_element_type] } // CHECK: %swift.tuple_element_type = type { [[TYPE]]*, i64 } func dup<T>(_ x: T) -> (T, T) { var x = x; return (x,x) } // CHECK: define hidden void @_TF14generic_tuples3dup{{.*}}(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) // CHECK: entry: // Allocate a local variable for 'x'. // CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[TYPE_ADDR]], i64 -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK: [[SIZE_WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 17 // CHECK: [[SIZE_WITNESS:%.*]] = load i8*, i8** [[SIZE_WITNESS_ADDR]] // CHECK: [[SIZE:%.*]] = ptrtoint i8* [[SIZE_WITNESS]] // CHECK: [[X_ALLOCA:%.*]] = alloca i8, {{.*}} [[SIZE]], align 16 // CHECK: [[X_TMP:%.*]] = bitcast i8* [[X_ALLOCA]] to %swift.opaque* // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 6 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]], align 8 // CHECK-NEXT: [[INITIALIZE_WITH_COPY:%.*]] = bitcast i8* [[WITNESS]] to [[OPAQUE]]* ([[OPAQUE]]*, [[OPAQUE]]*, [[TYPE]]*)* // CHECK-NEXT: [[X:%.*]] = call [[OPAQUE]]* [[INITIALIZE_WITH_COPY]]([[OPAQUE]]* [[X_TMP]], [[OPAQUE]]* {{.*}}, [[TYPE]]* %T) // Copy 'x' into the first result. // CHECK-NEXT: call [[OPAQUE]]* [[INITIALIZE_WITH_COPY]]([[OPAQUE]]* %0, [[OPAQUE]]* [[X_TMP]], [[TYPE]]* %T) // Copy 'x' into the second element. // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]], align 8 // CHECK-NEXT: [[TAKE_FN:%.*]] = bitcast i8* [[WITNESS]] to [[OPAQUE]]* ([[OPAQUE]]*, [[OPAQUE]]*, [[TYPE]]*)* // CHECK-NEXT: call [[OPAQUE]]* [[TAKE_FN]]([[OPAQUE]]* %1, [[OPAQUE]]* [[X_TMP]], [[TYPE]]* %T) struct S {} func callDup(_ s: S) { _ = dup(s) } // CHECK-LABEL: define hidden void @_TF14generic_tuples7callDupFVS_1ST_() // CHECK-NEXT: entry: // CHECK-NEXT: call void @_TF14generic_tuples3dupurFxTxx_({{.*}} undef, {{.*}} undef, %swift.type* {{.*}} @_TMfV14generic_tuples1S, {{.*}}) // CHECK-NEXT: ret void class C {} func dupC<T : C>(_ x: T) -> (T, T) { return (x, x) } // CHECK-LABEL: define hidden { %C14generic_tuples1C*, %C14generic_tuples1C* } @_TF14generic_tuples4dupCuRxCS_1CrFxTxx_(%C14generic_tuples1C*, %swift.type* %T) // CHECK-NEXT: entry: // CHECK: [[REF:%.*]] = bitcast %C14generic_tuples1C* %0 to %swift.refcounted* // CHECK-NEXT: call void @swift_rt_swift_retain(%swift.refcounted* [[REF]]) // CHECK-NEXT: [[TUP1:%.*]] = insertvalue { %C14generic_tuples1C*, %C14generic_tuples1C* } undef, %C14generic_tuples1C* %0, 0 // CHECK-NEXT: [[TUP2:%.*]] = insertvalue { %C14generic_tuples1C*, %C14generic_tuples1C* } [[TUP1:%.*]], %C14generic_tuples1C* %0, 1 // CHECK-NEXT: ret { %C14generic_tuples1C*, %C14generic_tuples1C* } [[TUP2]] func callDupC(_ c: C) { _ = dupC(c) } // CHECK-LABEL: define hidden void @_TF14generic_tuples8callDupCFCS_1CT_(%C14generic_tuples1C*) // CHECK-NEXT: entry: // CHECK-NEXT: [[REF:%.*]] = bitcast %C14generic_tuples1C* %0 to %swift.refcounted* // CHECK-NEXT: call void @swift_rt_swift_retain(%swift.refcounted* [[REF]]) // CHECK-NEXT: [[METATYPE:%.*]] = call %swift.type* @_TMaC14generic_tuples1C() // CHECK-NEXT: [[TUPLE:%.*]] = call { %C14generic_tuples1C*, %C14generic_tuples1C* } @_TF14generic_tuples4dupCuRxCS_1CrFxTxx_(%C14generic_tuples1C* %0, %swift.type* [[METATYPE]]) // CHECK-NEXT: [[LEFT:%.*]] = extractvalue { %C14generic_tuples1C*, %C14generic_tuples1C* } [[TUPLE]], 0 // CHECK-NEXT: [[RIGHT:%.*]] = extractvalue { %C14generic_tuples1C*, %C14generic_tuples1C* } [[TUPLE]], 1 // CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_rt_swift_release to void (%C14generic_tuples1C*)*)(%C14generic_tuples1C* [[RIGHT]]) // CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_rt_swift_release to void (%C14generic_tuples1C*)*)(%C14generic_tuples1C* [[LEFT]]) // CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_rt_swift_release to void (%C14generic_tuples1C*)*)(%C14generic_tuples1C* %0) // CHECK-NEXT: ret void // CHECK: define hidden i64 @_TF14generic_tuples4lump{{.*}}(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func lump<T>(_ x: T) -> (Int, T, T) { return (0,x,x) } // CHECK: define hidden { i64, i64 } @_TF14generic_tuples5lump2{{.*}}(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func lump2<T>(_ x: T) -> (Int, Int, T) { return (0,0,x) } // CHECK: define hidden void @_TF14generic_tuples5lump3{{.*}}(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func lump3<T>(_ x: T) -> (T, T, T) { return (x,x,x) } // CHECK: define hidden i64 @_TF14generic_tuples5lump4{{.*}}(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func lump4<T>(_ x: T) -> (T, Int, T) { return (x,0,x) } // CHECK: define hidden i64 @_TF14generic_tuples6unlump{{.*}}(i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump<T>(_ x: (Int, T, T)) -> Int { return x.0 } // CHECK: define hidden void @_TF14generic_tuples7unlump{{.*}}(%swift.opaque* noalias nocapture sret, i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump1<T>(_ x: (Int, T, T)) -> T { return x.1 } // CHECK: define hidden void @_TF14generic_tuples7unlump2{{.*}}(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump2<T>(_ x: (T, Int, T)) -> T { return x.0 } // CHECK: define hidden i64 @_TF14generic_tuples7unlump3{{.*}}(%swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump3<T>(_ x: (T, Int, T)) -> Int { return x.1 } // CHECK: tuple_existentials func tuple_existentials() { // Empty tuple: var a : Any = () // CHECK: store %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* @_TMT_, i32 0, i32 1), // 2 element tuple var t2 = (1,2.0) a = t2 // CHECK: call %swift.type* @swift_getTupleTypeMetadata2({{.*}}@_TMSi{{.*}},{{.*}}@_TMSd{{.*}}, i8* null, i8** null) // 3 element tuple var t3 = ((),(),()) a = t3 // CHECK: call %swift.type* @swift_getTupleTypeMetadata3({{.*}}@_TMT_{{.*}},{{.*}}@_TMT_{{.*}},{{.*}}@_TMT_{{.*}}, i8* null, i8** null) // 4 element tuple var t4 = (1,2,3,4) a = t4 // CHECK: call %swift.type* @swift_getTupleTypeMetadata(i64 4, {{.*}}, i8* null, i8** null) }
apache-2.0
a0aa86acd0cad7b9218c690134689136
64.035714
214
0.633169
3.038798
false
false
false
false
JustForFunOrg/6-CurrentDateAndTime
CurrentDateAndTime/MainViewController.swift
1
789
// // MainViewController.swift // CurrentDateAndTime // // Created by Alice Aponasko on 2/8/16. // Copyright © 2016 justforfun. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var currentDateAndTimeLabel: UILabel! let formatter = NSDateFormatter() override func viewDidLoad() { super.viewDidLoad() formatter.dateStyle = .MediumStyle formatter.timeStyle = .MediumStyle currentDateAndTimeLabel.text = currentDateAndTime() } func currentDateAndTime() -> String { return formatter.stringFromDate(NSDate()) } @IBAction func refreshButtonTapped(sender: AnyObject) { currentDateAndTimeLabel.text = currentDateAndTime() } }
mit
54836caed2ed4b9657bb4c83f4d27c0e
21.514286
59
0.668782
4.987342
false
false
false
false
Yanze/TTFFCamp
TTFFCamp/HiddenMenuViewController.swift
1
7227
// // HiddenMenuViewController.swift // TTFFCamp // // Created by yanze on 3/13/16. // Copyright © 2016 The Taylor Family Foundation. All rights reserved. // import UIKit import Alamofire import Foundation class HiddenMenuViewController: UIViewController { @IBOutlet weak var userInputLabel: UITextField! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var testImage: UIImageView! @IBOutlet weak var passwordInput: UITextField! override func viewDidLoad() { super.viewDidLoad() messageLabel.hidden = true messageLabel.textColor = UIColor.redColor() userInputLabel.attributedPlaceholder = NSAttributedString(string:"Please enter your IP address", attributes:[NSForegroundColorAttributeName: UIColor.grayColor()]) passwordInput.attributedPlaceholder = NSAttributedString(string:"Please enter your password", attributes:[NSForegroundColorAttributeName: UIColor.grayColor()]) } @IBAction func clickToSynchronize(sender: UIButton) { let ipCheck = regExIpAddressCheck(userInputLabel.text!) if ipCheck && passwordInput.text == "ttff" { messageLabel.text = "Downloading..." messageLabel.textColor = UIColor.blueColor() messageLabel.hidden = false var successCheck = false Alamofire.request(.GET, "http://\(userInputLabel.text!):8001/getAllPlants") .responseJSON { response in if let JSON = response.result.value { var plantArray = [Plant]() // parse JSON data and create new Plant objs and Plant array for anItem in JSON as! [Dictionary<String, AnyObject>] { let plantObj = Plant() if let newName = anItem["name"] { plantObj.plantName = newName as! String } if let newLocation = anItem["location"] { plantObj.location = newLocation as! String } if let newOrigin = anItem["origin"] { plantObj.origin = newOrigin as! String } if let newDesc = anItem["description"] { plantObj.plantDescription = newDesc as! String } if let newWTP = anItem["whenToPlant"] { plantObj.whenToPlant = newWTP as! String } if let newCF = anItem["coolFact"] { plantObj.coolFact = newCF as! String } if let newMF = anItem["moreFact"] { plantObj.moreFacts = newMF as! String } if let newImage1 = anItem["imgStr1"] { let image1 = newImage1 as! String if image1 != ""{ plantObj.images.append(image1) } } if let newImage2 = anItem["imgStr2"] { let image2 = newImage2 as! String if image2 != ""{ plantObj.images.append(image2) } } if let newImage3 = anItem["imgStr3"] { let image3 = newImage3 as! String if image3 != ""{ plantObj.images.append(image3) } } if let newImage4 = anItem["imgStr4"] { let image4 = newImage4 as! String if image4 != ""{ plantObj.images.append(image4) } } if let newCaption1 = anItem["imgname1"] { let caption1 = newCaption1 as! String if caption1 != "" { plantObj.captions.append(caption1) } } if let newCaption2 = anItem["imgname2"] { let caption2 = newCaption2 as! String if caption2 != "" { plantObj.captions.append(caption2) } } if let newCaption3 = anItem["imgname3"] { let caption3 = newCaption3 as! String if caption3 != "" { plantObj.captions.append(caption3) } } if let newCaption4 = anItem["imgname4"] { let caption4 = newCaption4 as! String if caption4 != "" { plantObj.captions.append(caption4) } } plantArray.append(plantObj) } print("new plant array", plantArray) Database.save(plantArray, toSchema: Plant.schema, forKey: Plant.key) // save all to local storage successCheck = true } if successCheck { self.messageLabel.text = "COMPLETE" successCheck = false } else { self.messageLabel.text = "ERROR" self.messageLabel.textColor = UIColor.redColor() } } } else { messageLabel.text = "Wrong Entry" messageLabel.hidden = false messageLabel.textColor = UIColor.redColor() } } func regExIpAddressCheck(ipAddress: String) -> Bool { let validIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" if ipAddress.rangeOfString(validIpAddressRegex, options: .RegularExpressionSearch) != nil { print("IP is valid") return true } else { print("IP is NOT valid") return false } } }
mit
d49078c8f3f5db594f9889f58989ae96
41.511765
142
0.406172
6.423111
false
false
false
false
alessandrostone/Menubar-Colors
sources/Preferences.swift
2
2493
// // Preferences.swift // Menubar Colors // // Created by Nikolai Vazquez on 7/19/15. // Copyright (c) 2015 Nikolai Vazquez. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // Mark: Preferences Class class Preferences { // MARK: Preferences Keys private struct Keys { static var ResetLocation: String = "Reset Location" static var ShowsAlpha: String = "Shows Alpha" } // MARK: Shared Preferences private static let _sharedPreferences = Preferences() static func sharedPreferences() -> Preferences { return _sharedPreferences } // MARK: Private Variables private let defaults = NSUserDefaults.standardUserDefaults() // MARK: Variables var resetLocation: Location { get { if let resetLocation = defaults.objectForKey(Keys.ResetLocation) as? String { if let location: Location = Location.CasesDictionary[resetLocation] { return location } } return .None } set { defaults.setValue(newValue.stringValue, forKey: Keys.ResetLocation) } } var showsAlpha: Bool { get { return defaults.objectForKey(Keys.ShowsAlpha) as? Bool ?? false } set { defaults.setBool(newValue, forKey: Keys.ShowsAlpha) } } }
mit
10805f4cd9102ea5b0c367c636591451
32.689189
89
0.663458
4.76673
false
false
false
false
hyperoslo/Tabby
Demo/TabbyDemo/TabbyDemo/AppDelegate.swift
1
2025
import UIKit import Tabby class MainController: TabbyController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setIndex = 1 } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { lazy var items: [TabbyBarItem] = [ TabbyBarItem(controller: self.firstNavigation, image: "cow"), TabbyBarItem(controller: self.secondController, image: "donut"), TabbyBarItem(controller: self.thirdNavigation, image: "fish") ] lazy var mainController: MainController = { [unowned self] in let controller = MainController(items: self.items) controller.delegate = self controller.translucent = false return controller }() lazy var firstNavigation: UINavigationController = UINavigationController(rootViewController: self.firstController) lazy var thirdNavigation: UINavigationController = UINavigationController(rootViewController: self.thirdController) lazy var firstController: FirstController = FirstController() lazy var secondController: SecondController = SecondController() lazy var thirdController: ThirdController = ThirdController() var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { Tabby.Constant.Color.background = UIColor.white Tabby.Constant.Color.selected = UIColor(red:0.22, green:0.81, blue:0.99, alpha:1.00) Tabby.Constant.Behavior.labelVisibility = .activeVisible window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = mainController window?.makeKeyAndVisible() return true } } extension AppDelegate: TabbyDelegate { func tabbyDidPress(_ item: TabbyBarItem) { // Do your awesome transformations! if items.index(of: item) == 1 { mainController.barHidden = true } let when = DispatchTime.now() + 2 DispatchQueue.main.asyncAfter(deadline: when) { self.mainController.barHidden = false } } }
mit
2dfe9f88c861bec0489eef0a5459c193
28.779412
142
0.74716
4.844498
false
false
false
false
johnno1962c/swift-corelibs-foundation
Foundation/URLSession/URLSessionTask.swift
4
26732
// Foundation/URLSession/URLSessionTask.swift - URLSession API // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- /// /// URLSession API code. /// - SeeAlso: URLSession.swift /// // ----------------------------------------------------------------------------- import CoreFoundation import Dispatch /// A cancelable object that refers to the lifetime /// of processing a given request. open class URLSessionTask : NSObject, NSCopying { public var countOfBytesClientExpectsToReceive: Int64 { NSUnimplemented() } public var countOfBytesClientExpectsToSend: Int64 { NSUnimplemented() } public var earliestBeginDate: Date? { NSUnimplemented() } /// How many times the task has been suspended, 0 indicating a running task. internal var suspendCount = 1 internal var session: URLSessionProtocol! //change to nil when task completes internal let body: _Body fileprivate var _protocol: URLProtocol? = nil private let syncQ = DispatchQueue(label: "org.swift.URLSessionTask.SyncQ") /// All operations must run on this queue. internal let workQueue: DispatchQueue public override init() { // Darwin Foundation oddly allows calling this initializer, even though // such a task is quite broken -- it doesn't have a session. And calling // e.g. `taskIdentifier` will crash. // // We set up the bare minimum for init to work, but don't care too much // about things crashing later. session = _MissingURLSession() taskIdentifier = 0 originalRequest = nil body = .none workQueue = DispatchQueue(label: "URLSessionTask.notused.0") super.init() } /// Create a data task. If there is a httpBody in the URLRequest, use that as a parameter internal convenience init(session: URLSession, request: URLRequest, taskIdentifier: Int) { if let bodyData = request.httpBody { self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: _Body.data(createDispatchData(bodyData))) } else { self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: .none) } } internal init(session: URLSession, request: URLRequest, taskIdentifier: Int, body: _Body) { self.session = session /* make sure we're actually having a serial queue as it's used for synchronization */ self.workQueue = DispatchQueue.init(label: "org.swift.URLSessionTask.WorkQueue", target: session.workQueue) self.taskIdentifier = taskIdentifier self.originalRequest = request self.body = body super.init() if session.configuration.protocolClasses != nil { guard let protocolClasses = session.configuration.protocolClasses else { fatalError() } if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) { guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() } self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil) } else { guard let protocolClasses = URLProtocol.getProtocols() else { fatalError() } if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) { guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() } self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil) } } } else { guard let protocolClasses = URLProtocol.getProtocols() else { fatalError() } if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) { guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() } self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil) } } } deinit { //TODO: Do we remove the EasyHandle from the session here? This might run on the wrong thread / queue. } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone?) -> Any { return self } /// An identifier for this task, assigned by and unique to the owning session open let taskIdentifier: Int /// May be nil if this is a stream task /*@NSCopying*/ open let originalRequest: URLRequest? /// May differ from originalRequest due to http server redirection /*@NSCopying*/ open internal(set) var currentRequest: URLRequest? { get { return self.syncQ.sync { return self._currentRequest } } set { self.syncQ.sync { self._currentRequest = newValue } } } fileprivate var _currentRequest: URLRequest? = nil /*@NSCopying*/ open internal(set) var response: URLResponse? { get { return self.syncQ.sync { return self._response } } set { self.syncQ.sync { self._response = newValue } } } fileprivate var _response: URLResponse? = nil /* Byte count properties may be zero if no body is expected, * or URLSessionTransferSizeUnknown if it is not possible * to know how many bytes will be transferred. */ /// Number of body bytes already received open internal(set) var countOfBytesReceived: Int64 { get { return self.syncQ.sync { return self._countOfBytesReceived } } set { self.syncQ.sync { self._countOfBytesReceived = newValue } } } fileprivate var _countOfBytesReceived: Int64 = 0 /// Number of body bytes already sent */ open internal(set) var countOfBytesSent: Int64 { get { return self.syncQ.sync { return self._countOfBytesSent } } set { self.syncQ.sync { self._countOfBytesSent = newValue } } } fileprivate var _countOfBytesSent: Int64 = 0 /// Number of body bytes we expect to send, derived from the Content-Length of the HTTP request */ open internal(set) var countOfBytesExpectedToSend: Int64 = 0 /// Number of byte bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */ open internal(set) var countOfBytesExpectedToReceive: Int64 = 0 /// The taskDescription property is available for the developer to /// provide a descriptive label for the task. open var taskDescription: String? /* -cancel returns immediately, but marks a task as being canceled. * The task will signal -URLSession:task:didCompleteWithError: with an * error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some * cases, the task may signal other work before it acknowledges the * cancelation. -cancel may be sent to a task that has been suspended. */ open func cancel() { workQueue.sync { guard self.state == .running || self.state == .suspended else { return } self.state = .canceling self.workQueue.async { let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil)) self.error = urlError self._protocol?.stopLoading() self._protocol?.client?.urlProtocol(self._protocol!, didFailWithError: urlError) } } } /* * The current state of the task within the session. */ open var state: URLSessionTask.State { get { return self.syncQ.sync { self._state } } set { self.syncQ.sync { self._state = newValue } } } fileprivate var _state: URLSessionTask.State = .suspended /* * The error, if any, delivered via -URLSession:task:didCompleteWithError: * This property will be nil in the event that no error occured. */ /*@NSCopying*/ open internal(set) var error: Error? /// Suspend the task. /// /// Suspending a task will prevent the URLSession from continuing to /// load data. There may still be delegate calls made on behalf of /// this task (for instance, to report data received while suspending) /// but no further transmissions will be made on behalf of the task /// until -resume is sent. The timeout timer associated with the task /// will be disabled while a task is suspended. -suspend and -resume are /// nestable. open func suspend() { // suspend / resume is implemented simply by adding / removing the task's // easy handle fromt he session's multi-handle. // // This might result in slightly different behaviour than the Darwin Foundation // implementation, but it'll be difficult to get complete parity anyhow. // Too many things depend on timeout on the wire etc. // // TODO: It may be worth looking into starting over a task that gets // resumed. The Darwin Foundation documentation states that that's what // it does for anything but download tasks. // We perform the increment and call to `updateTaskState()` // synchronous, to make sure the `state` is updated when this method // returns, but the actual suspend will be done asynchronous to avoid // dead-locks. workQueue.sync { self.suspendCount += 1 guard self.suspendCount < Int.max else { fatalError("Task suspended too many times \(Int.max).") } self.updateTaskState() if self.suspendCount == 1 { self.workQueue.async { self._protocol?.stopLoading() } } } } /// Resume the task. /// /// - SeeAlso: `suspend()` open func resume() { workQueue.sync { self.suspendCount -= 1 guard 0 <= self.suspendCount else { fatalError("Resuming a task that's not suspended. Calls to resume() / suspend() need to be matched.") } self.updateTaskState() if self.suspendCount == 0 { self.workQueue.async { if let _protocol = self._protocol { _protocol.startLoading() } else if self.error == nil { var userInfo: [String: Any] = [NSLocalizedDescriptionKey: "unsupported URL"] if let url = self.originalRequest?.url { userInfo[NSURLErrorFailingURLErrorKey] = url userInfo[NSURLErrorFailingURLStringErrorKey] = url.absoluteString } let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorUnsupportedURL, userInfo: userInfo)) self.error = urlError _ProtocolClient().urlProtocol(task: self, didFailWithError: urlError) } } } } } /// The priority of the task. /// /// Sets a scaling factor for the priority of the task. The scaling factor is a /// value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest /// priority and 1.0 is considered the highest. /// /// The priority is a hint and not a hard requirement of task performance. The /// priority of a task may be changed using this API at any time, but not all /// protocols support this; in these cases, the last priority that took effect /// will be used. /// /// If no priority is specified, the task will operate with the default priority /// as defined by the constant URLSessionTask.defaultPriority. Two additional /// priority levels are provided: URLSessionTask.lowPriority and /// URLSessionTask.highPriority, but use is not restricted to these. open var priority: Float { get { return self.workQueue.sync { return self._priority } } set { self.workQueue.sync { self._priority = newValue } } } fileprivate var _priority: Float = URLSessionTask.defaultPriority } extension URLSessionTask { public enum State : Int { /// The task is currently being serviced by the session case running case suspended /// The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message. case canceling /// The task has completed and the session will receive no more delegate notifications case completed } } extension URLSessionTask : ProgressReporting { public var progress: Progress { NSUnimplemented() } } internal extension URLSessionTask { /// Updates the (public) state based on private / internal state. /// /// - Note: This must be called on the `workQueue`. internal func updateTaskState() { func calculateState() -> URLSessionTask.State { if suspendCount == 0 { return .running } else { return .suspended } } state = calculateState() } } internal extension URLSessionTask { enum _Body { case none case data(DispatchData) /// Body data is read from the given file URL case file(URL) case stream(InputStream) } } internal extension URLSessionTask._Body { enum _Error : Error { case fileForBodyDataNotFound } /// - Returns: The body length, or `nil` for no body (e.g. `GET` request). func getBodyLength() throws -> UInt64? { switch self { case .none: return 0 case .data(let d): return UInt64(d.count) /// Body data is read from the given file URL case .file(let fileURL): guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else { throw _Error.fileForBodyDataNotFound } return s.uint64Value case .stream: return nil } } } fileprivate func errorCode(fileSystemError error: Error) -> Int { func fromCocoaErrorCode(_ code: Int) -> Int { switch code { case CocoaError.fileReadNoSuchFile.rawValue: return NSURLErrorFileDoesNotExist case CocoaError.fileReadNoPermission.rawValue: return NSURLErrorNoPermissionsToReadFile default: return NSURLErrorUnknown } } switch error { case let e as NSError where e.domain == NSCocoaErrorDomain: return fromCocoaErrorCode(e.code) default: return NSURLErrorUnknown } } public extension URLSessionTask { /// The default URL session task priority, used implicitly for any task you /// have not prioritized. The floating point value of this constant is 0.5. public static let defaultPriority: Float = 0.5 /// A low URL session task priority, with a floating point value above the /// minimum of 0 and below the default value. public static let lowPriority: Float = 0.25 /// A high URL session task priority, with a floating point value above the /// default value and below the maximum of 1.0. public static let highPriority: Float = 0.75 } /* * An URLSessionDataTask does not provide any additional * functionality over an URLSessionTask and its presence is merely * to provide lexical differentiation from download and upload tasks. */ open class URLSessionDataTask : URLSessionTask { } /* * An URLSessionUploadTask does not currently provide any additional * functionality over an URLSessionDataTask. All delegate messages * that may be sent referencing an URLSessionDataTask equally apply * to URLSessionUploadTasks. */ open class URLSessionUploadTask : URLSessionDataTask { } /* * URLSessionDownloadTask is a task that represents a download to * local storage. */ open class URLSessionDownloadTask : URLSessionTask { internal var fileLength = -1.0 /* Cancel the download (and calls the superclass -cancel). If * conditions will allow for resuming the download in the future, the * callback will be called with an opaque data blob, which may be used * with -downloadTaskWithResumeData: to attempt to resume the download. * If resume data cannot be created, the completion handler will be * called with nil resumeData. */ open func cancel(byProducingResumeData completionHandler: @escaping (Data?) -> Void) { NSUnimplemented() } } /* * An URLSessionStreamTask provides an interface to perform reads * and writes to a TCP/IP stream created via URLSession. This task * may be explicitly created from an URLSession, or created as a * result of the appropriate disposition response to a * -URLSession:dataTask:didReceiveResponse: delegate message. * * URLSessionStreamTask can be used to perform asynchronous reads * and writes. Reads and writes are enquened and executed serially, * with the completion handler being invoked on the sessions delegate * queuee. If an error occurs, or the task is canceled, all * outstanding read and write calls will have their completion * handlers invoked with an appropriate error. * * It is also possible to create InputStream and OutputStream * instances from an URLSessionTask by sending * -captureStreams to the task. All outstanding read and writess are * completed before the streams are created. Once the streams are * delivered to the session delegate, the task is considered complete * and will receive no more messsages. These streams are * disassociated from the underlying session. */ open class URLSessionStreamTask : URLSessionTask { /* Read minBytes, or at most maxBytes bytes and invoke the completion * handler on the sessions delegate queue with the data or an error. * If an error occurs, any outstanding reads will also fail, and new * read requests will error out immediately. */ open func readData(ofMinLength minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: @escaping (Data?, Bool, Error?) -> Void) { NSUnimplemented() } /* Write the data completely to the underlying socket. If all the * bytes have not been written by the timeout, a timeout error will * occur. Note that invocation of the completion handler does not * guarantee that the remote side has received all the bytes, only * that they have been written to the kernel. */ open func write(_ data: Data, timeout: TimeInterval, completionHandler: @escaping (Error?) -> Void) { NSUnimplemented() } /* -captureStreams completes any already enqueued reads * and writes, and then invokes the * URLSession:streamTask:didBecomeInputStream:outputStream: delegate * message. When that message is received, the task object is * considered completed and will not receive any more delegate * messages. */ open func captureStreams() { NSUnimplemented() } /* Enqueue a request to close the write end of the underlying socket. * All outstanding IO will complete before the write side of the * socket is closed. The server, however, may continue to write bytes * back to the client, so best practice is to continue reading from * the server until you receive EOF. */ open func closeWrite() { NSUnimplemented() } /* Enqueue a request to close the read side of the underlying socket. * All outstanding IO will complete before the read side is closed. * You may continue writing to the server. */ open func closeRead() { NSUnimplemented() } /* * Begin encrypted handshake. The hanshake begins after all pending * IO has completed. TLS authentication callbacks are sent to the * session's -URLSession:task:didReceiveChallenge:completionHandler: */ open func startSecureConnection() { NSUnimplemented() } /* * Cleanly close a secure connection after all pending secure IO has * completed. */ open func stopSecureConnection() { NSUnimplemented() } } /* Key in the userInfo dictionary of an NSError received during a failed download. */ public let URLSessionDownloadTaskResumeData: String = "NSURLSessionDownloadTaskResumeData" extension _ProtocolClient : URLProtocolClient { func urlProtocol(_ protocol: URLProtocol, didReceive response: URLResponse, cacheStoragePolicy policy: URLCache.StoragePolicy) { guard let task = `protocol`.task else { fatalError("Received response, but there's no task.") } task.response = response let session = task.session as! URLSession guard let dataTask = task as? URLSessionDataTask else { return } switch session.behaviour(for: task) { case .taskDelegate(let delegate as URLSessionDataDelegate): session.delegateQueue.addOperation { delegate.urlSession(session, dataTask: dataTask, didReceive: response, completionHandler: { _ in URLSession.printDebug("warning: Ignoring disposition from completion handler.") }) } case .noDelegate, .taskDelegate, .dataCompletionHandler, .downloadCompletionHandler: break } } func urlProtocolDidFinishLoading(_ protocol: URLProtocol) { guard let task = `protocol`.task else { fatalError() } guard let session = task.session as? URLSession else { fatalError() } switch session.behaviour(for: task) { case .taskDelegate(let delegate): if let downloadDelegate = delegate as? URLSessionDownloadDelegate, let downloadTask = task as? URLSessionDownloadTask { session.delegateQueue.addOperation { downloadDelegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: `protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as! URL) } } session.delegateQueue.addOperation { delegate.urlSession(session, task: task, didCompleteWithError: nil) task.state = .completed task.workQueue.async { session.taskRegistry.remove(task) } } case .noDelegate: task.state = .completed session.taskRegistry.remove(task) case .dataCompletionHandler(let completion): session.delegateQueue.addOperation { completion(`protocol`.properties[URLProtocol._PropertyKey.responseData] as? Data ?? Data(), task.response, nil) task.state = .completed session.taskRegistry.remove(task) } case .downloadCompletionHandler(let completion): session.delegateQueue.addOperation { completion(`protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as? URL, task.response, nil) task.state = .completed session.taskRegistry.remove(task) } } task._protocol = nil } func urlProtocol(_ protocol: URLProtocol, didCancel challenge: URLAuthenticationChallenge) { NSUnimplemented() } func urlProtocol(_ protocol: URLProtocol, didReceive challenge: URLAuthenticationChallenge) { NSUnimplemented() } func urlProtocol(_ protocol: URLProtocol, didLoad data: Data) { `protocol`.properties[.responseData] = data guard let task = `protocol`.task else { fatalError() } guard let session = task.session as? URLSession else { fatalError() } switch session.behaviour(for: task) { case .taskDelegate(let delegate): let dataDelegate = delegate as? URLSessionDataDelegate let dataTask = task as? URLSessionDataTask session.delegateQueue.addOperation { dataDelegate?.urlSession(session, dataTask: dataTask!, didReceive: data) } default: return } } func urlProtocol(_ protocol: URLProtocol, didFailWithError error: Error) { guard let task = `protocol`.task else { fatalError() } urlProtocol(task: task, didFailWithError: error) } func urlProtocol(task: URLSessionTask, didFailWithError error: Error) { guard let session = task.session as? URLSession else { fatalError() } switch session.behaviour(for: task) { case .taskDelegate(let delegate): session.delegateQueue.addOperation { delegate.urlSession(session, task: task, didCompleteWithError: error as Error) task.state = .completed task.workQueue.async { session.taskRegistry.remove(task) } } case .noDelegate: task.state = .completed session.taskRegistry.remove(task) case .dataCompletionHandler(let completion): session.delegateQueue.addOperation { completion(nil, nil, error) task.state = .completed task.workQueue.async { session.taskRegistry.remove(task) } } case .downloadCompletionHandler(let completion): session.delegateQueue.addOperation { completion(nil, nil, error) task.state = .completed session.taskRegistry.remove(task) } } task._protocol = nil } func urlProtocol(_ protocol: URLProtocol, cachedResponseIsValid cachedResponse: CachedURLResponse) { NSUnimplemented() } func urlProtocol(_ protocol: URLProtocol, wasRedirectedTo request: URLRequest, redirectResponse: URLResponse) { NSUnimplemented() } } extension URLProtocol { enum _PropertyKey: String { case responseData case temporaryFileURL } }
apache-2.0
f14649d1f590369dce8444441359ad1a
40.703588
182
0.639496
5.264277
false
false
false
false
LiveFlightApp/Connect-OSX
LiveFlight/Keyboard/KeyboardListenerWindow.swift
1
8215
// // KeyboardListenerWindow.swift // LiveFlight // // Created by Cameron Carmichael Alonso on 26/12/2015. // Copyright © 2015 Cameron Carmichael Alonso. All rights reserved. // import Cocoa // // List of Apple keyboard keyCodes // http://macbiblioblog.blogspot.com.es/2014/12/key-codes-for-function-and-special-keys.html // class KeyboardListenerWindow: NSWindow { var connector = InfiniteFlightAPIConnector() let controls = FlightControls() var keydown = false var shiftPressed = false //MARK - keyboard events override func keyDown(with event: NSEvent) { NSLog("keyDown: \(event.keyCode)!") if (event.keyCode == 0) { //A key if (keydown != true) { connector.atcMenu() } keydown = true } else if (event.keyCode == 18) { //1 key if (keydown != true) { connector.atc1() } keydown = true } else if (event.keyCode == 19) { //2 key if (keydown != true) { connector.atc2() } keydown = true } else if (event.keyCode == 20) { //3 key if (keydown != true) { connector.atc3() } keydown = true } else if (event.keyCode == 21) { //4 key if (keydown != true) { connector.atc4() } keydown = true } else if (event.keyCode == 23) { //5 key if (keydown != true) { connector.atc5() } keydown = true } else if (event.keyCode == 22) { //6 key if (keydown != true) { connector.atc6() } keydown = true } else if (event.keyCode == 26) { //7 key if (keydown != true) { connector.atc7() } keydown = true } else if (event.keyCode == 28) { //8 key if (keydown != true) { connector.atc8() } keydown = true } else if (event.keyCode == 25) { //9 key if (keydown != true) { connector.atc9() } keydown = true } else if (event.keyCode == 29) { //0 key if (keydown != true) { connector.atc10() } keydown = true } else if (event.keyCode == 12) { //A key if (keydown != true) { connector.previousCamera() } keydown = true } else if (event.keyCode == 14) { //D key if (keydown != true) { connector.nextCamera() } keydown = true } else if (event.keyCode == 5) { //G key if (keydown != true) { connector.landingGear() } keydown = true } else if (event.keyCode == 47) { //. key if (keydown != true) { connector.parkingBrakes() } keydown = true } else if (event.keyCode == 44) { // / key if (keydown != true) { connector.spoilers() } keydown = true } else if (event.keyCode == 35) { // P key if (keydown != true) { connector.pushback() } keydown = true } else if (event.keyCode == 49) { // space key if (keydown != true) { connector.togglePause() } keydown = true } else if (event.keyCode == 6) { // Z key if (keydown != true) { connector.autopilot() } keydown = true } else if (event.keyCode == 24) { // = key if (keydown != true) { connector.zoomIn() } keydown = true } else if (event.keyCode == 27) { // - key if (keydown != true) { connector.zoomOut() } keydown = true } else if (event.keyCode == 30) { // ] key if (keydown != true) { connector.flapsDown() } keydown = true } else if (event.keyCode == 33) { // [ key if (keydown != true) { connector.flapsUp() } keydown = true } else if (event.keyCode == 37) { // L key if (keydown != true) { connector.landing() } keydown = true } else if (event.keyCode == 45) { // N key if (keydown != true) { connector.nav() } keydown = true } else if (event.keyCode == 11) { // B key if (keydown != true) { connector.beacon() } keydown = true } else if (event.keyCode == 1) { // S key if (keydown != true) { connector.strobe() } keydown = true } else if (event.keyCode == 123) { // - The following don't need the keyDown bool; timing is handled by InfiniteFlightAPIConnector // left arrow key if shiftPressed != true { controls.leftArrow() } else { // move camera left connector.movePOV(withValue: 270) } } else if (event.keyCode == 124) { // right arrow key if shiftPressed != true { controls.rightArrow() } else { // move camera right connector.movePOV(withValue: 90) } } else if (event.keyCode == 126) { // up arrow key if shiftPressed != true { controls.upArrow() } else { // move camera up connector.movePOV(withValue: 0) } } else if (event.keyCode == 125) { // down arrow key if shiftPressed != true { controls.downArrow() } else { // move camera down connector.movePOV(withValue: 180) } } else if (event.keyCode == 2) { // D key controls.throttleUpArrow() } else if (event.keyCode == 8) { // C arrow key controls.throttleDownArrow() } /* // TODO - send keyboard commands as buttons. issue with alternate cmds. connector.didPressButton(Int32(event.keyCode), state: 0) keydown = true */ } override func keyUp(with event: NSEvent) { //connector.didPressButton(Int32(event.keyCode), state: 1) connector.movePOV(withValue: -2) keydown = false } override func flagsChanged(with event: NSEvent) { switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) { case NSEvent.ModifierFlags.shift: NSLog("Shift key pressed") shiftPressed = true case NSEvent.ModifierFlags.control: NSLog("Control Pressed..") case NSEvent.ModifierFlags.option: NSLog("Option pressend...") case NSEvent.ModifierFlags.command: NSLog("Command key pressed..") default: NSLog("No modifier keys pressed") shiftPressed = false } } }
gpl-3.0
4d839b26d8e5a7dc43cfcd0aa1ccf854
26.938776
107
0.412588
5.140175
false
false
false
false
NunoAlexandre/broccoli_mobile
ios/broccoli/AZDialogViewController.swift
1
26392
// // Popup.swift // broccoli // // Created by Nuno on 18/05/2017. // Copyright © 2017 nunoalexandre. All rights reserved. // import Foundation // // DialogViewController.swift // test2 // // Created by Tony Zaitoun on 2/24/17. // Copyright © 2017 Crofis. All rights reserved. // import Foundation import UIKit public typealias ActionHandler = ((AZDialogViewController)->(Void)) open class AZDialogViewController: UIViewController { // Title of the dialog. fileprivate var mTitle: String? // Message of the dialog. fileprivate var mMessage: String? // The container that holds the image view. fileprivate var imageViewHolder: UIView! // The image view. fileprivate var imageView: UIImageView! // The Title Label. fileprivate var titleLabel: UILabel! // The message label. fileprivate var messageLabel: UILabel! // The cancel button. fileprivate var cancelButton: UIButton! // The stackview that holds the buttons. fileprivate var stackView: UIStackView! // The seperatorView fileprivate var seperatorView: UIView! fileprivate var leftToolItem: UIButton! fileprivate var rightToolItem: UIButton! // The array which holds the actions fileprivate var actions: [AZDialogAction?]! // The primary draggable view. fileprivate var baseView: BaseView! fileprivate var didInitAnimation = false // Show separator open var showSeparator = true open var dismissWithOutsideTouch = true open var buttonStyle: ((UIButton,_ height: CGFloat,_ position: Int)->Void)? open var leftToolStyle: ((UIButton)->Bool)? open var rightToolStyle: ((UIButton)->Bool)? open var leftToolAction: ((UIButton)->Void)? open var rightToolAction: ((UIButton)->Void)? open var cancelButtonStyle: ((UIButton,CGFloat)->Bool)? open var imageHandler: ((UIImageView)->Bool)? open var dismissDirection: AZDialogDismissDirection = .both open var backgroundAlpha: Float = 0.2 open private (set) var spacing: CGFloat = 0 open private (set) var stackSpacing: CGFloat = 0 open private (set) var sideSpacing: CGFloat = 0 open private (set) var titleFontSize: CGFloat = 0 open private (set) var messageFontSize: CGFloat = 0 open private (set) var buttonHeight: CGFloat = 0 open private (set) var cancelButtonHeight:CGFloat = 0 open private (set) var fontName = UIFont.systemFont(ofSize: 10).fontName open private (set) var fontNameBold = UIFont.systemFont(ofSize: 10).fontName /// The primary fuction to present the dialog. /// /// - Parameter controller: The View controller in which you wish to present the dialog. open func show(in controller: UIViewController){ let navigationController = FixedNavigationController(rootViewController: self) navigationController.isNavigationBarHidden = true navigationController.modalPresentationStyle = .overFullScreen navigationController.modalTransitionStyle = .crossDissolve controller.present(navigationController, animated: false, completion: nil) } /// The primary function to dismiss the dialog. /// /// - Parameters: /// - animated: Should it dismiss with animation? default is true. /// - completion: Completion block that is called after the controller is dismiss. open override func dismiss(animated: Bool = true,completion: (()->Void)?=nil){ if animated { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.baseView.center.y = self.view.bounds.maxY + (self.baseView.bounds.midY) self.view.backgroundColor = .clear }, completion: { (complete) -> Void in super.dismiss(animated: false, completion: completion) }) }else{ super.dismiss(animated: false, completion: completion) } } /// Add an action button to the dialog. Make sure you add the actions before calling the .show() function. /// /// - Parameter action: The AZDialogAction. open func addAction(_ action: AZDialogAction){ actions.append(action) } override open func loadView() { super.loadView() baseView = BaseView() imageViewHolder = UIView() imageView = UIImageView() stackView = UIStackView() titleLabel = UILabel() messageLabel = UILabel() cancelButton = UIButton(type: .system) seperatorView = UIView() leftToolItem = UIButton(type: .system) rightToolItem = UIButton(type: .system) if spacing == -1 {spacing = self.view.bounds.height * 0.012} if stackSpacing == -1 {stackSpacing = self.view.bounds.height * 0.015} let margins = self.view! let side = margins.bounds.size.width / 8 let labelWidth = margins.bounds.width - side * 2 - sideSpacing let showImage = imageHandler?(imageView) ?? false let imagePadding:CGFloat = 5 let separatorColor = UIColor(colorLiteralRed: 208/255, green: 211/255, blue: 214/255, alpha: 1) // Disable translate auto resizing mask into constraints baseView.translatesAutoresizingMaskIntoConstraints = false imageViewHolder.translatesAutoresizingMaskIntoConstraints = false imageView.translatesAutoresizingMaskIntoConstraints = false titleLabel.translatesAutoresizingMaskIntoConstraints = false messageLabel.translatesAutoresizingMaskIntoConstraints = false seperatorView.translatesAutoresizingMaskIntoConstraints = false stackView.translatesAutoresizingMaskIntoConstraints = false cancelButton.translatesAutoresizingMaskIntoConstraints = false leftToolItem.translatesAutoresizingMaskIntoConstraints = false rightToolItem.translatesAutoresizingMaskIntoConstraints = false view.addSubview(baseView) baseView.addSubview(imageViewHolder) baseView.addSubview(titleLabel) baseView.addSubview(seperatorView) baseView.addSubview(messageLabel) baseView.addSubview(stackView) baseView.addSubview(cancelButton) imageViewHolder.addSubview(imageView) // Setup Image View let imageHolderSize: CGFloat = showImage ? CGFloat(Int((margins.bounds.width - 2 * side) / 3)) : 0 let imageMultiplier:CGFloat = showImage ? 0.0 : 1.0 imageViewHolder.layer.cornerRadius = imageHolderSize / 2 imageViewHolder.layer.masksToBounds = true imageViewHolder.backgroundColor = UIColor.white imageViewHolder.topAnchor.constraint(equalTo: baseView.topAnchor, constant: -imageHolderSize/3).isActive = true imageViewHolder.centerXAnchor.constraint(equalTo: baseView.centerXAnchor, constant: 0).isActive = true imageViewHolder.heightAnchor.constraint(equalToConstant: imageHolderSize).isActive = true imageViewHolder.widthAnchor.constraint(equalToConstant: imageHolderSize).isActive = true if showImage { imageView.layer.cornerRadius = (imageHolderSize - 2 * imagePadding) / 2 imageView.layer.masksToBounds = true imageView.topAnchor.constraint(equalTo: imageViewHolder.topAnchor, constant: imagePadding).isActive = true imageView.rightAnchor.constraint(equalTo: imageViewHolder.rightAnchor, constant: -imagePadding).isActive = true imageView.leftAnchor.constraint(equalTo: imageViewHolder.leftAnchor, constant: imagePadding).isActive = true imageView.bottomAnchor.constraint(equalTo: imageViewHolder.bottomAnchor, constant: -imagePadding).isActive = true } if titleFontSize == 0 {titleFontSize = self.view.bounds.height * 0.0269} // Setup Title Label let titleFont = UIFont(name: fontNameBold, size: titleFontSize) let titleHeight:CGFloat = mTitle == nil ? 0 : heightForView(mTitle!, font: titleFont!, width: labelWidth) titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping titleLabel.text = mTitle titleLabel.font = titleFont titleLabel.textAlignment = .center titleLabel.topAnchor.constraint(equalTo: imageViewHolder.bottomAnchor, constant: spacing + spacing * imageMultiplier).isActive = true titleLabel.centerXAnchor.constraint(equalTo: baseView.centerXAnchor).isActive = true titleLabel.heightAnchor.constraint(equalToConstant: titleHeight).isActive = true titleLabel.widthAnchor.constraint(lessThanOrEqualTo: messageLabel.widthAnchor, multiplier: 1.0).isActive = true // Setup Seperator Line let seperatorHeight: CGFloat = self.showSeparator ? 0.7 : 0.0 let seperatorMultiplier: CGFloat = seperatorHeight > 0 ? 1.0 : 0.0 seperatorView.backgroundColor = separatorColor seperatorView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor,constant: spacing * seperatorMultiplier).isActive = true seperatorView.widthAnchor.constraint(equalTo: titleLabel.widthAnchor, multiplier: 1.0).isActive = true seperatorView.centerXAnchor.constraint(equalTo: baseView.centerXAnchor).isActive = true seperatorView.heightAnchor.constraint(equalToConstant: seperatorHeight).isActive = true // Setup Message Label if messageFontSize == 0 {messageFontSize = self.view.bounds.height * 0.0239} let labelFont = UIFont(name: fontName, size: messageFontSize)! let messageLableHeight:CGFloat = mMessage == nil ? 0 : heightForView(mMessage!, font: labelFont, width: labelWidth) let messageLabelMultiplier: CGFloat = messageLableHeight > 0 ? 1.0 : 0.0 messageLabel.numberOfLines = 0 messageLabel.lineBreakMode = NSLineBreakMode.byWordWrapping messageLabel.font = labelFont messageLabel.text = mMessage messageLabel.textAlignment = .center messageLabel.topAnchor.constraint(equalTo: seperatorView.bottomAnchor, constant: spacing * messageLabelMultiplier).isActive = true messageLabel.rightAnchor.constraint(equalTo: baseView.rightAnchor,constant: -sideSpacing/2).isActive = true messageLabel.leftAnchor.constraint(equalTo: baseView.leftAnchor,constant: sideSpacing/2).isActive = true messageLabel.heightAnchor.constraint(equalToConstant: messageLableHeight).isActive = true // Setup Buttons (StackView) if buttonHeight == 0 {buttonHeight = CGFloat(Int(self.view.bounds.height * 0.07))} let stackViewSize: Int = self.actions.count * Int(buttonHeight) + (self.actions.count-1) * Int(stackSpacing) let stackMultiplier:CGFloat = stackViewSize > 0 ? 1.0 : 0.0 stackView.distribution = .fillEqually stackView.alignment = .fill stackView.axis = .vertical stackView.spacing = stackSpacing stackView.topAnchor.constraint(equalTo: messageLabel.bottomAnchor, constant: spacing * 2 * stackMultiplier).isActive = true stackView.rightAnchor.constraint(equalTo: baseView.rightAnchor,constant: -side).isActive = true stackView.leftAnchor.constraint(equalTo: baseView.leftAnchor,constant: side).isActive = true for i in 0 ..< actions.count{ let button = UIButton(type: .custom) let action = actions[i] button.isExclusiveTouch = true button.setTitle(action?.title, for: []) button.setTitleColor(button.tintColor, for: []) button.layer.borderColor = button.tintColor.cgColor button.layer.borderWidth = 1 button.layer.cornerRadius = buttonHeight/2 button.titleLabel?.font = UIFont(name: fontName, size: buttonHeight * 0.35) self.buttonStyle?(button,buttonHeight,i) button.tag = i button.addTarget(self, action: #selector(AZDialogViewController.handleAction(_:)), for: .touchUpInside) stackView.addArrangedSubview(button) } // Setup Cancel button if cancelButtonHeight == 0 {cancelButtonHeight = self.view.bounds.height * 0.0449} cancelButton.setTitle("CANCEL", for: []) cancelButton.titleLabel?.font = UIFont(name: fontName, size: cancelButtonHeight * 0.433) let showCancelButton = cancelButtonStyle?(cancelButton,cancelButtonHeight) ?? false let cancelMultiplier: CGFloat = showCancelButton ? 1.0 : 0.0 cancelButton.isHidden = (showCancelButton ? cancelButtonHeight : 0) <= 0 cancelButton.topAnchor.constraint(equalTo: stackView.bottomAnchor,constant: spacing).isActive = true cancelButton.rightAnchor.constraint(equalTo: baseView.rightAnchor,constant: -side/2).isActive = true cancelButton.leftAnchor.constraint(equalTo: baseView.leftAnchor,constant: side/2).isActive = true cancelButton.bottomAnchor.constraint(equalTo: baseView.bottomAnchor,constant: -spacing).isActive = true cancelButton.heightAnchor.constraint(equalToConstant: cancelButtonHeight * cancelMultiplier).isActive = true cancelButton.addTarget(self, action: #selector(AZDialogViewController.cancelAction(_:)), for: .touchUpInside) // Setup Base View // Elaboration on spacingCalc: // // 3 * spacing : The space between titleLabel and baseView + space between stackView and cancelButton + space between baseView and cancelButton. // spacing * (seperatorMultiplier + messageLabelMultiplier + 2 * stackMultiplier) : This ranges from 0 to 4. // seperatorMultiplier: 0 if the seperator has no height, thus it will not have spacing. // messageLabelMultiplier: 0 if the messageLabel is empty and has no text which means it has no height thus it has no spacing. // 2 * stackMultiplier: 0 if the stack has no buttons. 2 if the stack has atleast 1 button. There is a 2 because the spacing between the stack and other views is 2 * spacing. // // This gives us a total of 7 if all views are present, or 3 which is the minimum. let spacingCalc = 3 * spacing + spacing * (imageMultiplier + seperatorMultiplier + messageLabelMultiplier + 2 * stackMultiplier) // The baseViewHeight: // Total Space Between Views // + Image Holder half height // + Title Height // + Seperator Height // + Message Label Height // + Stack View Height // + Cancel Button Height. let baseViewHeight = Int(spacingCalc) + Int(2 * imageHolderSize/3) + Int(titleHeight) + Int(seperatorHeight) + Int(messageLableHeight) + Int(stackViewSize) + Int(cancelButtonHeight * cancelMultiplier) self.baseView.isExclusiveTouch = true self.baseView.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -side).isActive = true self.baseView.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: side).isActive = true self.baseView.centerYAnchor.constraint(equalTo: (baseView.superview?.centerYAnchor)!,constant: 0).isActive = true self.baseView.heightAnchor.constraint(equalToConstant: CGFloat(baseViewHeight)).isActive = true if leftToolStyle?(leftToolItem) ?? false{ baseView.addSubview(leftToolItem) leftToolItem.topAnchor.constraint(equalTo: baseView.topAnchor, constant: spacing*2).isActive = true leftToolItem.leftAnchor.constraint(equalTo: baseView.leftAnchor,constant: spacing*2).isActive = true leftToolItem.widthAnchor.constraint(equalTo: leftToolItem.heightAnchor).isActive = true leftToolItem.addTarget(self, action: #selector(AZDialogViewController.handleLeftTool(_:)), for: .touchUpInside) } if rightToolStyle?(rightToolItem) ?? false{ baseView.addSubview(rightToolItem) rightToolItem.topAnchor.constraint(equalTo: baseView.topAnchor, constant: spacing*2).isActive = true rightToolItem.rightAnchor.constraint(equalTo: baseView.rightAnchor,constant: -spacing*2).isActive = true rightToolItem.widthAnchor.constraint(equalTo: rightToolItem.heightAnchor).isActive = true rightToolItem.heightAnchor.constraint(equalToConstant: 20).isActive = true rightToolItem.addTarget(self, action: #selector(AZDialogViewController.handleRightTool(_:)), for: .touchUpInside) } } override open func viewDidLoad() { super.viewDidLoad() view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AZDialogViewController.handleTapGesture(_:)))) baseView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AZDialogViewController.handleTapGesture(_:)))) baseView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(AZDialogViewController.handlePanGesture(_:)))) baseView.layer.cornerRadius = 15 baseView.layer.backgroundColor = UIColor.white.cgColor baseView.isHidden = true baseView.lastLocation = self.view.center } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !didInitAnimation{ didInitAnimation = true baseView.center.y = self.view.bounds.maxY + baseView.bounds.midY baseView.isHidden = false UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 6.0, options: [], animations: { () -> Void in self.baseView.center = (self.baseView.superview?.center)! let backgroundColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: self.backgroundAlpha) self.view.backgroundColor = backgroundColor }) { (complete) -> Void in } } } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setup() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Primary initializer /// /// - Parameters: /// - title: The title that will be set on the dialog. /// - message: The message that will be set on the dialog. /// - spacing: The vertical spacing between views. /// - stackSpacing: The vertical spacing between the buttons. /// - sideSpacing: The spacing on the side of the views (Between the views and the base dialog view) /// - titleFontSize: The title font size. /// - messageFontSize: The message font size. /// - buttonsHeight: The buttons' height. /// - cancelButtonHeight: The cancel button height. /// - fontName: The font name that will be used for the message label and the buttons. /// - boldFontName: The font name that will be used for the title. public convenience init(title: String?, message: String?, verticalSpacing spacing: CGFloat = -1, buttonSpacing stackSpacing:CGFloat = 10, sideSpacing: CGFloat = 20, titleFontSize: CGFloat = 0, messageFontSize: CGFloat = 0, buttonsHeight: CGFloat = 0, cancelButtonHeight: CGFloat = 0, fontName: String = "AvenirNext-Medium", boldFontName: String = "AvenirNext-DemiBold"){ self.init(nibName: nil, bundle: nil) mTitle = title mMessage = message self.spacing = spacing self.stackSpacing = stackSpacing self.sideSpacing = sideSpacing self.titleFontSize = titleFontSize self.messageFontSize = messageFontSize self.buttonHeight = buttonsHeight self.cancelButtonHeight = cancelButtonHeight self.fontName = fontName self.fontNameBold = boldFontName } /// Selector method - used to handle the dragging. /// /// - Parameter sender: The Gesture Recognizer. internal func handlePanGesture(_ sender: UIPanGestureRecognizer){ let translation = sender.translation(in: self.view) baseView.center = CGPoint(x: baseView.lastLocation.x , y: baseView.lastLocation.y + translation.y) let returnToCenter:(CGPoint,Bool)->Void = { (finalPoint,animate) in if !animate { self.baseView.center = finalPoint return } UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 2.0, options: [], animations: { () -> Void in self.baseView.center = finalPoint }, completion: { (complete) -> Void in }) } let dismissInDirection:(CGPoint)->Void = { (finalPoint) in UIView.animate(withDuration: 0.2, animations: { () -> Void in self.baseView.center = finalPoint self.view.backgroundColor = .clear }, completion: { (complete) -> Void in self.dismiss(animated: false, completion: nil) }) } var finalPoint = (baseView.superview?.center)! if sender.state == .ended{ let velocity = sender.velocity(in: view) let mag = sqrtf(Float(velocity.x * velocity.x) + Float(velocity.y * velocity.y)) let slideMult = mag / 200 let dismissWithGesture = dismissDirection != .none ? true : false if dismissWithGesture && slideMult > 1 { //dismiss if velocity.y > 0{ //dismiss downward if dismissDirection == .bottom || dismissDirection == .both { finalPoint.y = (baseView.superview?.frame.maxY)! + (baseView.bounds.midY) dismissInDirection(finalPoint) }else{ returnToCenter(finalPoint,true) } }else{ //dismiss upward if dismissDirection == .top || dismissDirection == .both { finalPoint.y = -(baseView.bounds.midY) dismissInDirection(finalPoint) }else{ returnToCenter(finalPoint,true) } } }else{ //return to center returnToCenter(finalPoint,true) } } if sender.state == .cancelled || sender.state == .failed{ returnToCenter(finalPoint,false) } } /// Selector method - used to handle view touch. /// /// - Parameter sender: The Gesture Recognizer. internal func handleTapGesture(_ sender: UITapGestureRecognizer){ if sender.view is BaseView{ return } if dismissWithOutsideTouch{ self.dismiss() } } /// Selector method - used when cancel button is clicked. /// /// - Parameter sender: The cancel button. internal func cancelAction(_ sender: UIButton){ dismiss() } /// Selector method - used when left tool item button is clicked. /// /// - Parameter sender: The left tool button. internal func handleLeftTool(_ sender: UIButton){ leftToolAction?(sender) } /// Selector method - used when right tool item button is clicked. /// /// - Parameter sender: The right tool button. internal func handleRightTool(_ sender: UIButton){ rightToolAction?(sender) } /// Selector method - used when one of the action buttons are clicked. /// /// - Parameter sender: Action Button internal func handleAction(_ sender: UIButton){ (actions[sender.tag]!.handler)?(self) } fileprivate func setup(){ actions = [AZDialogAction?]() self.modalPresentationStyle = .overCurrentContext self.modalTransitionStyle = .crossDissolve } fileprivate func heightForView(_ text:String, font:UIFont, width:CGFloat) -> CGFloat{ let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.byWordWrapping label.font = font label.text = text label.textAlignment = .center label.sizeToFit() return label.frame.height } } public enum AZDialogDismissDirection{ case top case bottom case both case none } open class AZDialogAction{ open var title: String? open var isEnabled: Bool = true open var handler: ActionHandler? public init(title: String,handler: ActionHandler? = nil){ self.title = title self.handler = handler } } fileprivate class BaseView: UIView{ var lastLocation = CGPoint(x: 0, y: 0) override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { lastLocation = self.center super.touchesBegan(touches, with: event) } } fileprivate class FixedNavigationController: UINavigationController{ open override var shouldAutorotate: Bool{ return true } open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{ return .portrait } open override var supportedInterfaceOrientations: UIInterfaceOrientationMask{ return .portrait } }
mit
dc6a38ea4c6d5b514275f67b377c76c1
42.983333
187
0.644524
5.389014
false
false
false
false
WXYC/wxyc-ios-64
Shared/Core/RadioPlayer.swift
1
1048
// // RadioPlayer.swift // WXYC // // Created by Jake Bromberg on 12/1/17. // Copyright © 2017 wxyc.org. All rights reserved. // import Foundation import AVFoundation internal final class RadioPlayer { let streamURL: URL init(streamURL: URL = URL.WXYCStream) { self.streamURL = streamURL } var isPlaying: Bool { return player.isPlaying } func play() { if self.isPlaying { return } try? AVAudioSession.sharedInstance().setActive(true) player.play() } func pause() { player.pause() self.resetStream() } // MARK: Private private lazy var player: AVPlayer = AVPlayer(url: self.streamURL) private func resetStream() { let asset = AVAsset(url: self.streamURL) let playerItem = AVPlayerItem(asset: asset) player.replaceCurrentItem(with: playerItem) } } private extension AVPlayer { var isPlaying: Bool { return rate > 0.0 } }
mit
15b5c9ccbfbb66c864547830c068a8b0
18.754717
69
0.582617
4.344398
false
false
false
false
CodeEagle/Animate
Example/Animate/TestVC/CALayerTestViewController.swift
1
4015
// // CALayerTestViewController.swift // Animate // // Created by LawLincoln on 15/6/8. // Copyright (c) 2015年 CocoaPods. All rights reserved. // import UIKit import pop import Animate class CALayerTestViewController: TestTemplateViewController { private var currentProperty: Int = 0 { didSet{ animateCombine() } } private var currentStyle: Int = 0 { didSet{ animateCombine() } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.testView.layer.spring { (make) -> Void in make.backgroundColor = UIColor.greenColor() make.bounds = CGRectMake(0, 0, 200, 200) }.decay { (make) -> Void in make.velocity(M_PI * 180, forProperty: kPOPLayerRotationY) }.basic { (make) -> Void in make.bounds = CGRectMake(0, 0, 100, 100) make.position = CGPointMake(self.view.bounds.size.width/2 - 50, 64 + 80); } } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Layer" let r = Double(30.0)*M_PI let rx = Double(-30.0)*M_PI let ry = Double(80.0)*M_PI self.dataList = [ "BackgroundColor":UIColor.greenColor(), "Bounds":NSValue(CGRect: CGRectMake(0, 0, 200, 200)), "CornerRadius":50, "BorderWidth":6.0, "BorderColor":UIColor.orangeColor(), "Opacity":0.1, "Position":NSValue(CGPoint:CGPointMake(200, 100)), "PositionX":150, "PositionY":160, "Rotation":r, "RotationX":rx, "RotationY":ry, "ScaleX":2.0, "ScaleXY":NSValue( CGSize:CGSizeMake(2.0, 2.0)), "ScaleY":2.0, "Size":NSValue(CGSize:CGSizeMake(200.0, 200.0)), "SubscaleXY":NSValue(CGSize:CGSizeMake(5.0, 5.0)), "SubtranslationX":120, "SubtranslationXY":NSValue(CGSize:CGSizeMake(120.0, 100.0)), "SubtranslationY":100, "SubtranslationZ":90, "TranslationX":80, "TranslationXY":NSValue(CGSize:CGSizeMake(70, 90)), "TranslationY":100, "TranslationZ":120, "ZPosition":300, "ShadowColor":UIColor.cyanColor(), "ShadowOffset":NSValue(CGSize:CGSizeMake(20, 10)), "ShadowOpacity":0.7, "ShadowRadius":40 ] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func animateCombine(){ UIView.animateWithDuration(0.2, animations: { () -> Void in self.testView.alpha = 0 }) { (b) -> Void in if b { self.testView.removeFromSuperview() self.testView = nil self.view.addSubview(self.testView) self.Animate() } } } func Animate(){ let animator = currentStyle == 0 ? self.testView.layer.spring : (currentStyle == 1 ? self.testView.layer.decay : self.testView.layer.basic) self.testView.layer.spring.springBounciness = 20 self.testView.layer.spring.springSpeed = 20 self.testView.layer.basic.timingFunction = CAMediaTimingFunction.easeIn() var value: AnyObject! = Array(dataList.values)[currentProperty] let key = Array(dataList.keys)[currentProperty] if currentStyle == 1 && key == "Alpha" { value = -1.8 } animator.setValue(value, forKeyPath: "Animate"+key) } } extension CALayerTestViewController { override func changeSegment(sender: UISegmentedControl) { currentStyle = sender.selectedSegmentIndex } override func changeProperty(row: Int) { currentProperty = row } }
mit
b80197329446fb524747ed91a6ef1259
32.173554
147
0.557937
4.473802
false
true
false
false
rchatham/SwiftyTypeForm
SwiftyTypeForm/FormViewController.swift
1
1556
// // FormViewController.swift // HermesTranslator // // Created by Reid Chatham on 2/19/17. // Copyright © 2017 Hermes Messenger LLC. All rights reserved. // import UIKit /** FormViewController - Sets up a FormView as the view and holds a reference to it with `formView`. Also sets itself to the delegate and if a dataSource object is specified it automatically udpates its backing data when a FormField updates it's content. */ open class FormViewController: UIViewController, FormViewDelegate { /** Holds a reference to the FormView. Sets the FormViewController's view property to the formView when set and sets the formView's formDelegate property to itself. */ open var formView: FormView? { didSet { formView?.delegate = self view = formView } } /** Optional FormViewControllerDataSource property that sets the FormViewController to its formView property and sets itself to the formView's formDataSource property. */ open var dataSource: FormViewControllerDataSource? { didSet { dataSource?.formView = formView } } override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. formView = FormView(frame: view.frame) } // MARK: - FormViewDelegate open func formView(_ formView: FormView, fieldAtIndex index: Int, returnedWithData data: FormData) -> Bool { dataSource?.formData[index] = data return true } }
mit
51f90d55bcd396de7103050f2da1a005
30.734694
251
0.677814
5.065147
false
false
false
false
UncleJoke/Spiral
Spiral/Reaper.swift
2
576
// // Reaper.swift // Spiral // // Created by 杨萧玉 on 14-10-11. // Copyright (c) 2014年 杨萧玉. All rights reserved. // import SpriteKit class Reaper: Shape { convenience init() { self.init(name:"Reaper",imageName:"reaper") physicsBody!.categoryBitMask = reaperCategory physicsBody!.contactTestBitMask ^= reaperCategory self.moveSpeed = 250 light.lightColor = SKColor(red: 78.0/255, green: 146.0/255, blue: 223.0/255, alpha: 1) light.categoryBitMask = reaperLightCategory light.enabled = true } }
mit
6203675d0a0bbef19eb238f0b0c85f5c
25.761905
94
0.649466
3.673203
false
false
false
false
swotge/calendar
calendar/ViewController.swift
1
8249
// // ViewController.swift // calendar // // Created by Madasamy Sankarapandian on 01/12/2016. // Copyright © 2016 mCruncher. All rights reserved. // import UIKit import EventKit import EventKitUI /** * Calender interaction https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/EventKitProgGuide/Introduction/Introduction.html * Registering for Notifications https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/EventKitProgGuide/ObservingChanges/ObservingChanges.html#//apple_ref/doc/uid/TP40009765-CH4-SW1 */ class ViewController: UITableViewController { let eventStore = EKEventStore() let userDefaults = UserDefaults.standard var events = [EKEvent]() override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 60 tableView.rowHeight = UITableViewAutomaticDimension addNotification() } override func viewWillAppear(_ animated: Bool) { requestAccessToCalendar() } func requestAccessToCalendar() { eventStore.requestAccess(to: EKEntityType.event, completion: { (accessGranted: Bool, error: Error?) in if accessGranted == true { DispatchQueue.main.sync(execute: { self.saveCalendar() self.loadEvents() }) } }) } func saveCalendar() { let calender = EKCalendar(for: .event, eventStore: eventStore) calender.title = "Furiend" calender.source = eventStore.defaultCalendarForNewEvents.source do { let calendarIdentifier = userDefaults.string(forKey: "EventTrackerPrimaryCalendar") if calendarIdentifier == nil { try eventStore.saveCalendar(calender, commit: true) userDefaults.set(calender.calendarIdentifier, forKey: "EventTrackerPrimaryCalendar") userDefaults.synchronize() } } catch { print("Error occurred while creating calendar ") } } @IBAction func addNewEvent(_ sender: Any) { eventStore.requestAccess(to: EKEntityType.event, completion: { (accessGranted: Bool, error: Error?) in if accessGranted == true { let eventController = EKEventEditViewController() let calenderIdentifier = self.userDefaults.string(forKey: "EventTrackerPrimaryCalendar") let calendar = self.eventStore.calendar(withIdentifier: calenderIdentifier!) eventController.eventStore = self.eventStore eventController.editViewDelegate = self let event = EKEvent(eventStore: self.eventStore) event.title = "" event.calendar = calendar! eventController.event = event self.present(eventController, animated: true, completion: nil) } else { } }) } func loadEvents() { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" // Create start and end date NSDate instances to build a predicate for which events to select let startDate = dateFormatter.date(from: "2016-01-01") let endDate = dateFormatter.date(from: "2016-12-31") let calenderIdentifier = self.userDefaults.string(forKey: "EventTrackerPrimaryCalendar") let calendar = self.eventStore.calendar(withIdentifier: calenderIdentifier!) let eventPredicate = self.eventStore.predicateForEvents(withStart: startDate!, end: endDate!, calendars: [calendar!]) self.events = self.eventStore.events(matching: eventPredicate).sorted(){ (e1: EKEvent, e2: EKEvent) -> Bool in return e1.startDate.compare(e2.startDate) == ComparisonResult.orderedAscending } tableView.reloadData() } func addNotification() { NotificationCenter.default.addObserver(self, selector: #selector(ViewController.storeChanged(_:)), name: NSNotification.Name.EKEventStoreChanged, object: eventStore) } func storeChanged(_ nsNotification: NSNotification) { print("Event name \(nsNotification.userInfo?["EKEventStoreChangedObjectIDsUserInfoKey"])") self.loadEvents() } func getDateFormatter() -> DateFormatter { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter } } extension ViewController: EKEventEditViewDelegate { func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) { self.dismiss(animated: true, completion: nil) } } // MARK: - UITableViewDataSource, UITableViewDelegate extension ViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return events.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CalendarCell let event = events[indexPath.row] print("Event identifier \(event.eventIdentifier)") cell.eventDateLabel.text = getDateFormatter().string(from: event.startDate) cell.locationLabel.text = event.location return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteAction = getDeleteAction(indexPath) deleteAction.backgroundColor = UIColor.red return [deleteAction] } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { eventStore.requestAccess(to: EKEntityType.event, completion: { (accessGranted: Bool, error: Error?) in if accessGranted == true { let eventController = EKEventEditViewController() eventController.eventStore = self.eventStore eventController.editViewDelegate = self eventController.event = self.events[indexPath.row] self.present(eventController, animated: true, completion: nil) } else { } }) } } // MARK: - Delete action extension ViewController { fileprivate func getDeleteAction(_ indexPath: IndexPath) -> UITableViewRowAction { return UITableViewRowAction(style: UITableViewRowActionStyle.normal, title: "Delete") { (action, indexPath) -> Void in self.isEditing = false let confirmationAlertController = self.getDeleteController(self.events[indexPath.row]) confirmationAlertController.addAction(self.getConfirmDeleteAction(self.events[indexPath.row])) confirmationAlertController.addAction(self.getCancelDeleteAction(indexPath)) self.present(confirmationAlertController, animated: true, completion: nil) } } fileprivate func getDeleteController(_ event: EKEvent) -> UIAlertController { return UIAlertController(title: "Delete", message: "Are you sure want to delete "+event.title+"?", preferredStyle: UIAlertControllerStyle.alert) } fileprivate func getConfirmDeleteAction(_ event: EKEvent) -> UIAlertAction { return UIAlertAction(title: "Yes", style: .default, handler: {(alert: UIAlertAction!) -> Void in do { try self.eventStore.remove(event, span: .thisEvent, commit: true) } catch { print("Error occurred while deleting event " + event.title) } }) } fileprivate func getCancelDeleteAction(_ indexPath: IndexPath) -> UIAlertAction { return UIAlertAction(title: "no", style: UIAlertActionStyle.default,handler: {(alert: UIAlertAction!) -> Void in self.tableView.reloadRows(at: [IndexPath(row: indexPath.row, section: 0)], with: UITableViewRowAnimation.none) }) } }
apache-2.0
b4623cd6f6d9e35d8c2523b9fcedc087
40.656566
212
0.66016
5.311011
false
false
false
false
chieryw/actor-platform
actor-apps/app-ios/Actor/Controllers/Conversation/ConversationViewController.swift
1
32255
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import Foundation import UIKit import MobileCoreServices class ConversationViewController: ConversationBaseViewController { // MARK: - // MARK: Private vars private let BubbleTextIdentifier = "BubbleTextIdentifier" private let BubbleMediaIdentifier = "BubbleMediaIdentifier" private let BubbleDocumentIdentifier = "BubbleDocumentIdentifier" private let BubbleServiceIdentifier = "BubbleServiceIdentifier" private let BubbleBannerIdentifier = "BubbleBannerIdentifier" private let titleView: UILabel = UILabel(); private let subtitleView: UILabel = UILabel(); private let navigationView: UIView = UIView(); private let avatarView = BarAvatarView(frameSize: 36, type: .Rounded) private let backgroundView: UIView = UIView() private var layoutCache: LayoutCache! // private let heightCache = HeightCache() // // // MARK: - // MARK: Public vars let binder: Binder = Binder(); var unreadMessageId: jlong = 0 // MARK: - // MARK: Constructors override init(peer: AMPeer) { super.init(peer: peer); // Messages self.collectionView.registerClass(AABubbleTextCell.self, forCellWithReuseIdentifier: BubbleTextIdentifier) self.collectionView.registerClass(AABubbleMediaCell.self, forCellWithReuseIdentifier: BubbleMediaIdentifier) self.collectionView.registerClass(AABubbleDocumentCell.self, forCellWithReuseIdentifier: BubbleDocumentIdentifier) self.collectionView.registerClass(AABubbleServiceCell.self, forCellWithReuseIdentifier: BubbleServiceIdentifier) self.collectionView.backgroundColor = UIColor.clearColor() self.collectionView.alwaysBounceVertical = true backgroundView.clipsToBounds = true backgroundView.backgroundColor = UIColor( patternImage:UIImage(named: "bg_foggy_birds")!.tintBgImage(MainAppTheme.bubbles.chatBgTint)) view.insertSubview(backgroundView, atIndex: 0) // Text Input self.textInputbar.backgroundColor = MainAppTheme.chat.chatField self.textInputbar.autoHideRightButton = false; self.textView.placeholder = NSLocalizedString("ChatPlaceholder",comment: "Placeholder") self.rightButton.setTitle(NSLocalizedString("ChatSend", comment: "Send"), forState: UIControlState.Normal) self.rightButton.setTitleColor(MainAppTheme.chat.sendEnabled, forState: UIControlState.Normal) self.rightButton.setTitleColor(MainAppTheme.chat.sendDisabled, forState: UIControlState.Disabled) self.keyboardPanningEnabled = true; self.textView.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light self.leftButton.setImage(UIImage(named: "conv_attach")! .tintImage(MainAppTheme.chat.attachColor) .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), forState: UIControlState.Normal) // Navigation Title navigationView.frame = CGRectMake(0, 0, 190, 44); navigationView.autoresizingMask = UIViewAutoresizing.FlexibleWidth; titleView.frame = CGRectMake(0, 4, 190, 20) titleView.font = UIFont(name: "HelveticaNeue-Medium", size: 17)! titleView.adjustsFontSizeToFitWidth = false; titleView.textColor = Resources.PrimaryLightText titleView.textAlignment = NSTextAlignment.Center; titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail; titleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth; subtitleView.frame = CGRectMake(0, 22, 190, 20); subtitleView.font = UIFont.systemFontOfSize(13); subtitleView.adjustsFontSizeToFitWidth=false; subtitleView.textColor = Resources.SecondaryLightText subtitleView.textAlignment = NSTextAlignment.Center; subtitleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail; subtitleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth; navigationView.addSubview(titleView); navigationView.addSubview(subtitleView); self.navigationItem.titleView = navigationView; // Navigation Avatar avatarView.frame = CGRectMake(0, 0, 36, 36) var avatarTapGesture = UITapGestureRecognizer(target: self, action: "onAvatarTap"); avatarTapGesture.numberOfTapsRequired = 1 avatarTapGesture.numberOfTouchesRequired = 1 avatarView.addGestureRecognizer(avatarTapGesture) var barItem = UIBarButtonItem(customView: avatarView) self.navigationItem.rightBarButtonItem = barItem // self.singleTapGesture.cancelsTouchesInView = true // var longPressGesture = AALongPressGestureRecognizer(target: self, action: Selector("longPress:")) // self.collectionView.addGestureRecognizer(longPressGesture) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) textView.text = MSG.loadDraftWithPeer(peer) // Installing bindings if (UInt(peer.getPeerType().ordinal()) == AMPeerType.PRIVATE.rawValue) { let user = MSG.getUserWithUid(peer.getPeerId()) var nameModel = user.getNameModel(); binder.bind(nameModel, closure: { (value: NSString?) -> () in self.titleView.text = String(value!); self.navigationView.sizeToFit(); }) binder.bind(user.getAvatarModel(), closure: { (value: AMAvatar?) -> () in self.avatarView.bind(user.getNameModel().get(), id: user.getId(), avatar: value) }) binder.bind(MSG.getTypingWithUid(peer.getPeerId())!, valueModel2: user.getPresenceModel()!, closure:{ (typing:JavaLangBoolean?, presence:AMUserPresence?) -> () in if (typing != nil && typing!.booleanValue()) { self.subtitleView.text = MSG.getFormatter().formatTyping(); self.subtitleView.textColor = Resources.PrimaryLightText } else { var stateText = MSG.getFormatter().formatPresence(presence, withSex: user.getSex()) self.subtitleView.text = stateText; var state = UInt(presence!.getState().ordinal()) if (state == AMUserPresence_State.ONLINE.rawValue) { self.subtitleView.textColor = Resources.PrimaryLightText } else { self.subtitleView.textColor = Resources.SecondaryLightText } } }) } else if (UInt(peer.getPeerType().ordinal()) == AMPeerType.GROUP.rawValue) { let group = MSG.getGroupWithGid(peer.getPeerId()) var nameModel = group.getNameModel() binder.bind(nameModel, closure: { (value: NSString?) -> () in self.titleView.text = String(value!); self.navigationView.sizeToFit(); }) binder.bind(group.getAvatarModel(), closure: { (value: AMAvatar?) -> () in self.avatarView.bind(group.getNameModel().get(), id: group.getId(), avatar: value) }) binder.bind(MSG.getGroupTypingWithGid(group.getId())!, valueModel2: group.getMembersModel(), valueModel3: group.getPresenceModel(), closure: { (typingValue:IOSIntArray?, members:JavaUtilHashSet?, onlineCount:JavaLangInteger?) -> () in // if (!group.isMemberModel().get().booleanValue()) { // self.subtitleView.text = NSLocalizedString("ChatNoGroupAccess", comment: "You is not member") // self.textInputbar.hidden = true // return // } else { // self.textInputbar.hidden = false // } if (typingValue != nil && typingValue!.length() > 0) { self.subtitleView.textColor = Resources.PrimaryLightText if (typingValue!.length() == 1) { var uid = typingValue!.intAtIndex(0); var user = MSG.getUserWithUid(uid) self.subtitleView.text = MSG.getFormatter().formatTypingWithName(user.getNameModel().get()) } else { self.subtitleView.text = MSG.getFormatter().formatTypingWithCount(typingValue!.length()); } } else { var membersString = MSG.getFormatter().formatGroupMembers(members!.size()) if (onlineCount == nil || onlineCount!.integerValue == 0) { self.subtitleView.textColor = Resources.SecondaryLightText self.subtitleView.text = membersString; } else { membersString = membersString + ", "; var onlineString = MSG.getFormatter().formatGroupOnline(onlineCount!.intValue()); var attributedString = NSMutableAttributedString(string: (membersString + onlineString)) attributedString.addAttribute(NSForegroundColorAttributeName, value: Resources.PrimaryLightText, range: NSMakeRange(membersString.size(), onlineString.size())) self.subtitleView.attributedText = attributedString } } }) } MSG.onConversationOpenWithPeer(peer) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() backgroundView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height) } override func viewDidLoad() { super.viewDidLoad() // unreadMessageId = MSG.loadLastReadState(peer) navigationItem.backBarButtonItem = UIBarButtonItem(title: NSLocalizedString("NavigationBack",comment: "Back button"), style: UIBarButtonItemStyle.Plain, target: nil, action: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) MSG.onConversationOpenWithPeer(peer) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if count(navigationController!.viewControllers) > 2 { if let firstController = navigationController!.viewControllers[0] as? UIViewController, let currentController: AnyObject = navigationController!.viewControllers[count(navigationController!.viewControllers) - 1] as? ConversationViewController { navigationController!.setViewControllers([firstController, currentController], animated: false) } } } override func setUnread(rid: jlong) { self.unreadMessageId = rid } // override func afterLoaded() { // NSLog("afterLoaded") // var sortState = MSG.loadLastReadState(peer) // // if (sortState == 0) { // NSLog("lastReadMessage == 0") // return // } // // if (getCount() == 0) { // NSLog("getCount() == 0") // return // } // // var index = -1 // unreadMessageId = 0 // for var i = getCount() - 1; i >= 0; --i { // var item = objectAtIndex(i) as! AMMessage // if (item.getSortDate() > sortState && item.getSenderId() != MSG.myUid()) { // index = i // unreadMessageId = item.getRid() // break // } // } // // if (index < 0) { // NSLog("Not found") // } else { // NSLog("Founded @\(index)") // // self.tableView.reloadData() // // self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: Int(index), inSection: 0), atScrollPosition: UITableViewScrollPosition.Middle, animated: false) // } // } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated); MSG.saveDraftWithPeer(peer, withDraft: textView.text); } // MARK: - // MARK: Methods func longPress(gesture: UILongPressGestureRecognizer) { if gesture.state == UIGestureRecognizerState.Began { let point = gesture.locationInView(self.collectionView) let indexPath = self.collectionView.indexPathForItemAtPoint(point) if indexPath != nil { if let cell = collectionView.cellForItemAtIndexPath(indexPath!) as? AABubbleCell { if cell.bubble.superview != nil { var bubbleFrame = cell.bubble.frame bubbleFrame = collectionView.convertRect(bubbleFrame, fromView: cell.bubble.superview) if CGRectContainsPoint(bubbleFrame, point) { // cell.becomeFirstResponder() var menuController = UIMenuController.sharedMenuController() menuController.setTargetRect(bubbleFrame, inView:collectionView) menuController.menuItems = [UIMenuItem(title: "Copy", action: "copy")] menuController.setMenuVisible(true, animated: true) } } } } } } override func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { // if (touch.view == self.tableView) { // return true // } if (touch.view is UITableViewCell) { return true } if (touch.view.superview is UITableViewCell) { return true } // if (touch.view.superview?.superview is UITableViewCell) { // return true // } // if([touch.view isKindOfClass:[UITableViewCell class]]) { // return NO; // } // // UITableViewCellContentView => UITableViewCell // if([touch.view.superview isKindOfClass:[UITableViewCell class]]) { // return NO; // } // // UITableViewCellContentView => UITableViewCellScrollView => UITableViewCell // if([touch.view.superview.superview isKindOfClass:[UITableViewCell class]]) { // return NO; // } // if (touch.view is UITableViewCellContentView && gestureRecognizer == self.singleTapGesture) { // return true // } // if (touch.view.superview is AABubbleCell && gestureRecognizer == self.singleTapGesture) { // return false // } return false } // func tap(gesture: UITapGestureRecognizer) { // if gesture.state == UIGestureRecognizerState.Ended { // let point = gesture.locationInView(tableView) // let indexPath = tableView.indexPathForRowAtPoint(point) // if indexPath != nil { // if let cell = tableView.cellForRowAtIndexPath(indexPath!) as? AABubbleCell { // // // } else if let content = item.getContent() as? AMDocumentContent { // if let documentCell = cell as? AABubbleDocumentCell { // var frame = documentCell.bubble.frame // frame = tableView.convertRect(frame, fromView: cell.bubble.superview) // if CGRectContainsPoint(frame, point) { // if let fileSource = content.getSource() as? AMFileRemoteSource { // MSG.requestStateWithFileId(fileSource.getFileReference().getFileId(), withCallback: CocoaDownloadCallback( // notDownloaded: { () -> () in // MSG.startDownloadingWithReference(fileSource.getFileReference()) // }, onDownloading: { (progress) -> () in // MSG.cancelDownloadingWithFileId(fileSource.getFileReference().getFileId()) // }, onDownloaded: { (reference) -> () in // var controller = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: CocoaFiles.pathFromDescriptor(reference))!) // controller.delegate = self // controller.presentPreviewAnimated(true) // })) // } else if let fileSource = content.getSource() as? AMFileLocalSource { // MSG.requestUploadStateWithRid(item.getRid(), withCallback: CocoaUploadCallback( // notUploaded: { () -> () in // MSG.resumeUploadWithRid(item.getRid()) // }, onUploading: { (progress) -> () in // MSG.pauseUploadWithRid(item.getRid()) // }, onUploadedClosure: { () -> () in // var controller = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: CocoaFiles.pathFromDescriptor(fileSource.getFileDescriptor()))!) // controller.delegate = self // controller.presentPreviewAnimated(true) // })) // } // } // } // } else if let content = item.getContent() as? AMBannerContent { // if let bannerCell = cell as? AABubbleAdCell { // var frame = bannerCell.contentView.frame // frame = tableView.convertRect(frame, fromView: cell.contentView.superview) // if CGRectContainsPoint(frame, point) { // UIApplication.sharedApplication().openURL(NSURL(string: content.getAdUrl())!) // } // } // } // } // } // } // } func onAvatarTap() { let id = Int(peer.getPeerId()) var controller: AAViewController if (UInt(peer.getPeerType().ordinal()) == AMPeerType.PRIVATE.rawValue) { controller = UserViewController(uid: id) } else if (UInt(peer.getPeerType().ordinal()) == AMPeerType.GROUP.rawValue) { controller = GroupViewController(gid: id) } else { return } if (isIPad) { var navigation = AANavigationController() navigation.viewControllers = [controller] var popover = UIPopoverController(contentViewController: navigation) controller.popover = popover popover.presentPopoverFromBarButtonItem(navigationItem.rightBarButtonItem!, permittedArrowDirections: UIPopoverArrowDirection.Up, animated: true) } else { navigateNext(controller, removeCurrent: false) } } func onBubbleAvatarTap(view: UIView, uid: jint) { var controller = UserViewController(uid: Int(uid)) if (isIPad) { var navigation = AANavigationController() navigation.viewControllers = [controller] var popover = UIPopoverController(contentViewController: navigation) controller.popover = popover popover.presentPopoverFromRect(view.bounds, inView: view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) } else { navigateNext(controller, removeCurrent: false) } } override func textWillUpdate() { super.textWillUpdate(); MSG.onTypingWithPeer(peer); } override func didPressRightButton(sender: AnyObject!) { MSG.trackTextSendWithPeer(peer) MSG.sendMessageWithPeer(peer, withText: textView.text) super.didPressRightButton(sender); } override func didPressLeftButton(sender: AnyObject!) { super.didPressLeftButton(sender) var hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) var buttons = hasCamera ? ["PhotoCamera", "PhotoLibrary", "SendDocument"] : ["PhotoLibrary", "SendDocument"] var tapBlock = { (index: Int) -> () in if index == 0 || (hasCamera && index == 1) { var pickerController = AAImagePickerController() pickerController.sourceType = (hasCamera && index == 0) ? UIImagePickerControllerSourceType.Camera : UIImagePickerControllerSourceType.PhotoLibrary pickerController.mediaTypes = [kUTTypeImage] pickerController.view.backgroundColor = MainAppTheme.list.bgColor pickerController.navigationBar.tintColor = MainAppTheme.navigation.barColor pickerController.delegate = self pickerController.navigationBar.tintColor = MainAppTheme.navigation.titleColor pickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: MainAppTheme.navigation.titleColor] self.presentViewController(pickerController, animated: true, completion: nil) } else if index >= 0 { var documentPicker = UIDocumentMenuViewController(documentTypes: UTTAll, inMode: UIDocumentPickerMode.Import) documentPicker.view.backgroundColor = UIColor.clearColor() documentPicker.delegate = self self.presentViewController(documentPicker, animated: true, completion: nil) } } if (isIPad) { showActionSheet(buttons, cancelButton: "AlertCancel", destructButton: nil, sourceView: self.leftButton, sourceRect: self.leftButton.bounds, tapClosure: tapBlock) } else { showActionSheetFast(buttons, cancelButton: "AlertCancel", tapClosure: tapBlock) } } override func buildCell(collectionView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UICollectionViewCell { var message = (item as! AMMessage); var cell: AABubbleCell if (message.getContent() is AMTextContent) { cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleTextIdentifier, forIndexPath: indexPath) as! AABubbleTextCell } else if (message.getContent() is AMPhotoContent) { cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleMediaIdentifier, forIndexPath: indexPath) as! AABubbleMediaCell } else if (message.getContent() is AMDocumentContent) { cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleDocumentIdentifier, forIndexPath: indexPath) as! AABubbleDocumentCell } else if (message.getContent() is AMServiceContent){ cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleServiceIdentifier, forIndexPath: indexPath) as! AABubbleServiceCell } else { cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleTextIdentifier, forIndexPath: indexPath) as! AABubbleTextCell } cell.setConfig(peer, controller: self) return cell } override func bindCell(collectionView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UICollectionViewCell) { var message = item as! AMMessage var bubbleCell = (cell as! AABubbleCell) var setting = buildCellSetting(indexPath.row) bubbleCell.performBind(message, setting: setting, layoutCache: layoutCache) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(6, 0, 100, 0) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, idForItemAtIndexPath indexPath: NSIndexPath) -> Int64 { var message = objectAtIndexPath(indexPath) as! AMMessage return Int64(message.getRid()) } override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, gravityForItemAtIndexPath indexPath: NSIndexPath) -> MessageGravity { return MessageGravity.Center } override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var message = objectAtIndexPath(indexPath) as! AMMessage; var setting = buildCellSetting(indexPath.row) let group = peer.getPeerType().ordinal() == jint(AMPeerType.GROUP.rawValue) var height = MessagesLayouting.measureHeight(message, group: group, setting: setting, layoutCache: layoutCache) return CGSizeMake(self.view.bounds.width, height) } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!) -> Bool { return true } override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!) { } override func onItemsAdded(indexes: [Int]) { var toUpdate = [Int]() for ind in indexes { if !indexes.contains(ind + 1) { if ind + 1 < getCount() { toUpdate.append(ind + 1) } } if !indexes.contains(ind - 1) { if ind > 0 { toUpdate.append(ind - 1) } } } updateRows(toUpdate) } override func needFullReload(item: AnyObject?, cell: UICollectionViewCell) -> Bool { var message = (item as! AMMessage); if cell is AABubbleTextCell { if (message.getContent() is AMPhotoContent) { return true } } return false } func buildCellSetting(index: Int) -> CellSetting { // return CellSetting(showDate: false, clenchTop: false, clenchBottom: false, showNewMessages: false) var current = objectAtIndex(index) as! AMMessage var next: AMMessage! = index > 0 ? objectAtIndex(index - 1) as! AMMessage : nil var prev: AMMessage! = index + 1 < getCount() ? objectAtIndex(index + 1) as! AMMessage : nil var isShowDate = true var isShowDateNext = true var isShowNewMessages = (unreadMessageId == current.getRid()) var clenchTop = false var clenchBottom = false if (prev != nil) { isShowDate = !areSameDate(current, prev: prev) if !isShowDate { clenchTop = useCompact(current, next: prev) } } if (next != nil) { if areSameDate(next, prev: current) { clenchBottom = useCompact(current, next: next) } } return CellSetting(showDate: isShowDate, clenchTop: clenchTop, clenchBottom: clenchBottom, showNewMessages: isShowNewMessages) } func useCompact(source: AMMessage, next: AMMessage) -> Bool { if (source.getContent() is AMServiceContent) { if (next.getContent() is AMServiceContent) { return true } } else { if (next.getContent() is AMServiceContent) { return false } if (source.getSenderId() == next.getSenderId()) { return true } } return false } func areSameDate(source:AMMessage, prev: AMMessage) -> Bool { let calendar = NSCalendar.currentCalendar() var currentDate = NSDate(timeIntervalSince1970: Double(source.getDate())/1000.0) var currentDateComp = calendar.components(.CalendarUnitDay | .CalendarUnitYear | .CalendarUnitMonth, fromDate: currentDate) var nextDate = NSDate(timeIntervalSince1970: Double(prev.getDate())/1000.0) var nextDateComp = calendar.components(.CalendarUnitDay | .CalendarUnitYear | .CalendarUnitMonth, fromDate: nextDate) return (currentDateComp.year == nextDateComp.year && currentDateComp.month == nextDateComp.month && currentDateComp.day == nextDateComp.day) } override func displayListForController() -> AMBindedDisplayList { var res = MSG.getMessagesGlobalListWithPeer(peer) if (res.getBackgroundProcessor() == nil) { res.setBackgroundProcessor(BubbleBackgroundProcessor()) } layoutCache = (res.getBackgroundProcessor() as! BubbleBackgroundProcessor).layoutCache return res } } // MARK: - // MARK: UIDocumentPicker Delegate extension ConversationViewController: UIDocumentPickerDelegate { func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) { var path = url.path!; var fileName = url.lastPathComponent var range = path.rangeOfString("/tmp", options: NSStringCompareOptions.allZeros, range: nil, locale: nil) var descriptor = path.substringFromIndex(range!.startIndex) NSLog("Picked file: \(descriptor)") MSG.trackDocumentSendWithPeer(peer) MSG.sendDocumentWithPeer(peer, withName: fileName, withMime: "application/octet-stream", withDescriptor: descriptor) } } // MARK: - // MARK: UIImagePickerController Delegate extension ConversationViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { MainAppTheme.navigation.applyStatusBar() picker.dismissViewControllerAnimated(true, completion: nil) MSG.trackPhotoSendWithPeer(peer) MSG.sendUIImage(image, peer: peer) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { MainAppTheme.navigation.applyStatusBar() picker.dismissViewControllerAnimated(true, completion: nil) MSG.sendUIImage(info[UIImagePickerControllerOriginalImage] as! UIImage, peer: peer) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { MainAppTheme.navigation.applyStatusBar() picker.dismissViewControllerAnimated(true, completion: nil) } } extension ConversationViewController: UIDocumentMenuDelegate { func documentMenu(documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) { documentPicker.delegate = self self.presentViewController(documentPicker, animated: true, completion: nil) } }
mit
9f536a2841c31c7b67edd561805d5771
46.435294
246
0.61978
5.651831
false
false
false
false
twocentstudios/todostream
todostream/AppDelegate.swift
1
2876
// // Created by Christopher Trott on 12/5/15. // Copyright © 2015 twocentstudios. All rights reserved. // import UIKit import RealmSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var appContext: AppContext! var modelServer: ModelServer! var viewModelServer: ViewModelServer! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.appContext = AppContext() self.modelServer = ModelServer(configuration: Realm.Configuration.defaultConfiguration, appContext: appContext) self.viewModelServer = ViewModelServer(appContext: appContext) let todoListViewModel = TodoListViewModel() let todoListViewController = TodoListViewController(viewModel: todoListViewModel, appContext: appContext) let navigationController = UINavigationController(rootViewController: todoListViewController) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.rootViewController = navigationController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
fe413f0a5dc412e2c02db5efdb62075d
47.728814
285
0.750609
5.761523
false
true
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Swift Note/ObjC.io/Swift4/Advanced/StructAndClass.swift
1
11830
// // StructAndClass.swift // Advanced // // Created by 朱双泉 on 2018/6/4. // Copyright © 2018 Castie!. All rights reserved. // import Foundation struct StructAndClass { static func run() { let mutableArray: NSMutableArray = [1, 2, 3] for _ in mutableArray { mutableArray.removeLastObject() } var mutableArray1 = [1, 2, 3] for _ in mutableArray1 { mutableArray1.removeLast() } let otherArray = mutableArray mutableArray.add(4) print(otherArray) func scanRemainingBytes(scanner: BinaryScanner) { while let byte = scanner.scanByte() { print(byte) } } let scanner = BinaryScanner(data: Data("hi".utf8)) print(scanRemainingBytes(scanner: scanner)) #if false for _ in 0..<Int.max { let newScanner = BinaryScanner(data: Data("hi".utf8)) DispatchQueue.global().async { print(scanRemainingBytes(scanner: newScanner)) } print(scanRemainingBytes(scanner: newScanner)) } #endif var a = 42 var b = a b += 1 print(b) print(a) let origin = Point(x: 0, y: 0) // Cannot assign to property: 'origin' is a 'let' constant // origin.x = 10 var otherPoint = Point(x: 0, y: 0) otherPoint.x += 10 print(otherPoint) var thirdPoint = origin thirdPoint.x += 10 print(thirdPoint) print(origin) let rect = Rectangle(origin: Point.zero, size: Size(width: 320, height: 480)) var screen = Rectangle(width: 320, height: 480) { didSet { print("Screen changed: \(screen)") } } screen.origin.x = 10 var screens: [Rectangle] = [] { didSet { print("Screebs array changed: \(screen)") } } screens.append(Rectangle(width: 320, height: 480)) screens[0].origin.x += 100 print(screen.origin + Point(x: 10, y: 10)) screen.translate(by: Point(x: 10, y: 10)) print(screen) let otherScreen = screen // Cannot use mutating member on immutable value: 'otherScreen' is a 'let' constant // otherScreen.translate(by: Point(x: 10, y: 10)) let point = Point.zero // Cannot assign to property: 'point' is a 'let' constant // point.x = 10 print(screen.translated(by: Point(x: 20, y: 20))) screen = translatedByTenTen(rectangle: screen) print(screen) translateByTwentyTwenty(rectangle: &screen) print(screen) let immutableScreen = screen // Cannot pass immutable value as inout argument: 'immutableScreen' is a 'let' constant // translateByTwentyTwenty(rectangle: &immutableScreen) var array = [Point(x: 0, y: 0), Point(x: 10, y: 10)] array[0] += Point(x: 100, y: 100) print(array) var myPoint = Point.zero myPoint += Point(x: 10, y: 10) print(myPoint) #if false for _ in 0..<Int.max { let newScanner = BinaryScanner(data: Data("hi".utf8)) DispatchQueue.global().async { scanRemainingBytes(scanner: newScanner) } scanRemainingBytes(scanner: newScanner) } for _ in 0..<Int.max { let newScanner = BinaryScanner(data: Data("hi".utf8)) DispatchQueue.global().async { while let byte = newScanner.scanByte() { print(byte) } } while let byte = newScanner.scanByte() { print(byte) } } #endif var x = [1, 2, 3] var y = x x.append(5) y.removeLast() print(x) print(y) var input: [UInt8] = [0x0b, 0xab, 0xf0, 0x0d] var other: [UInt8] = [0x0d] var d = Data(bytes: input) var e = d d.append(contentsOf: other) print(d) print(e) var f = NSMutableData(bytes: &input, length: input.count) var g = f f.append(&other, length: other.count) print(f) print(g) print(f === g) #if false let theData = NSData(base64Encoded: "wAEP/w==")! var x1 = MyData(theData) let y1 = x1 print(x1._data === y1._data) x1.append(0x55) print(y1) print(x1._data === y1._data) var buffer = MyData(NSData()) for byte in 0..<5 as CountableRange<UInt8> { buffer.append(byte) } #endif var x2 = Box(NSMutableData()) print(isKnownUniquelyReferenced(&x2)) var y2 = x2 print(isKnownUniquelyReferenced(&x2)) var bytes = MyData() var copy = bytes for byte in 0..<5 as CountableRange<UInt8> { print("Append 0x\(String(byte, radix: 16))") bytes.append(byte) } print(bytes) print(copy) var s = COWStruct() print(s.change()) var original = COWStruct() var copy1 = original print(original.change()) var array1 = [COWStruct()] print(array1[0].change()) var otherArray1 = [COWStruct()] var x3 = array1[0] print(x3.change()) var dict = ["key" : COWStruct()] print(dict["key"]?.change()) var d1 = ContainerStruct(storage: COWStruct()) print(d1.storage.change()) print(d1["test"].change()) var i = 0 func uniqueInteger() -> Int { i += 1 return i } let otherFunction: () -> Int = uniqueInteger func uniqueIntegerProvider() -> () -> Int { var i = 0 return { i += 1 return i } } func uniqueIntegerProvider1() -> AnyIterator<Int> { var i = 0 return AnyIterator { i += 1 return i } } var john = Person(name: "John", parents: []) john.parents = [john] print(john) var myWindow: Window? = Window() myWindow = nil var window: Window? = Window() var view: View? = View(window: window!) window?.rootView = view // view = nil // window = nil #if false let handle = FileHandle(forWritingAtPath: "out.html") let request = URLRequest(url: URL(string: "https://www.objc.io")!) URLSession.shared.dataTask(with: request) { (data, _, _) in guard let theData = data else {return} handle?.write(theData) }.resume() #endif window?.onRotate = {[weak view] in print("We not also need to update the view: \(String(describing: view))") } window?.onRotate = {[weak view, weak myWindow = window, x = 5 * 5] in print("We now also need to update the view: \(String(describing: view))") print("Because the window \(String(describing: myWindow)) changed") } } } class BinaryScanner { var position: Int let data: Data init(data: Data) { self.position = 0 self.data = data } } extension BinaryScanner { func scanByte() -> UInt8? { guard position < data.endIndex else { return nil } position += 1 return data[position - 1] } } struct Point { var x: Int var y: Int } struct Size { var width: Int var height: Int } struct Rectangle { var origin: Point var size: Size } extension Point { static let zero = Point(x: 0, y: 0) } extension Rectangle { init(x: Int = 0, y: Int = 0, width: Int, height: Int) { origin = Point(x: x, y: y) size = Size(width: width, height: height) } } func +(lhs: Point, rhs: Point) -> Point { return Point(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } extension Rectangle { mutating func translate(by offset: Point) { origin = origin + offset } } extension Rectangle { func translated(by offset: Point) -> Rectangle { var copy = self copy.translate(by: offset) return copy } } func translatedByTenTen(rectangle: Rectangle) -> Rectangle { return rectangle.translated(by: Point(x: 10, y: 10)) } func translateByTwentyTwenty(rectangle: inout Rectangle) { rectangle.translate(by: Point(x: 20, y: 20)) } func +=(lhs: inout Point, rhs: Point) { lhs = lhs + rhs } struct MyData { #if false var _data: NSMutableData init(_ data: NSData) { _data = data.mutableCopy() as! NSMutableData } #endif #if false fileprivate var _data: NSMutableData fileprivate var _dataForWriting: NSMutableData { mutating get { _data = _data.mutableCopy() as! NSMutableData return _data } } init() { _data = NSMutableData() } init(_ data: NSData) { _data = data.mutableCopy() as! NSMutableData } #endif private var _data: Box<NSMutableData> var _dataForWriting: NSMutableData { mutating get { if !isKnownUniquelyReferenced(&_data) { _data = Box(_data.unbox.mutableCopy() as! NSMutableData) print("Making a copy") } return _data.unbox } } init() { _data = Box(NSMutableData()) } init(_ data: NSData) { _data = Box(data.mutableCopy() as! NSMutableData) } } extension MyData { #if false func append(_ byte: UInt8) { var mutableByte = byte _data.append(&mutableByte, length: 1) } #endif mutating func append(_ byte: UInt8) { var mutableByte = byte _dataForWriting.append(&mutableByte, length: 1) } } final class Box<A> { var unbox: A init(_ value: A) {self.unbox = value} } final class Empty {} struct COWStruct { var ref = Empty() mutating func change() -> String { if isKnownUniquelyReferenced(&ref) { return "No copy" } else { return "Copy" } } } struct ContainerStruct<A> { var storage: A subscript(s: String) -> A { get {return storage} set {storage = newValue} } } struct Person { let name: String var parents: [Person] } class View { #if false var window: Window init(window: Window) { self.window = window } #endif #if false var window: Window init(window: Window) { self.window = window } deinit { print("Deinit View") } #endif #if false unowned var window: Window init(window: Window) { self.window = window } deinit { print("Deinit View") } #endif var window: Window init(window: Window) { self.window = window } deinit { print("Deinit View") } } class Window { #if false var rootView: View? #endif #if false weak var rootView: View? deinit { print("Deinit Window") } #endif #if false var rootView: View? deinit { print("Deinit Window") } #endif weak var rootView: View? var onRotate: (() -> ())? deinit { print("Deinit Window") } }
mit
cb37d6a8efd388a2622837a7d93779ae
23.682672
94
0.514421
4.151334
false
false
false
false
twilio/video-quickstart-swift
AudioDeviceExample/ViewController.swift
1
24947
// // ViewController.swift // AudioDeviceExample // // Copyright © 2018-2019 Twilio Inc. All rights reserved. // import TwilioVideo import UIKit class ViewController: UIViewController { // MARK:- View Controller Members // Configure access token manually for testing, if desired! Create one manually in the console // at https://www.twilio.com/console/video/runtime/testing-tools var accessToken = "TWILIO_ACCESS_TOKEN" // Configure remote URL to fetch token from let tokenUrl = "http://localhost:8000/token.php" // Video SDK components var room: Room? var camera: CameraSource? var localVideoTrack: LocalVideoTrack! var localAudioTrack: LocalAudioTrack! var audioDevice: AudioDevice = ExampleCoreAudioDevice() // MARK:- UI Element Outlets and handles @IBOutlet weak var audioDeviceButton: UIButton! @IBOutlet weak var connectButton: UIButton! @IBOutlet weak var disconnectButton: UIButton! @IBOutlet weak var musicButton: UIButton! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var remoteViewStack: UIStackView! @IBOutlet weak var roomTextField: UITextField! @IBOutlet weak var roomLine: UIView! @IBOutlet weak var roomLabel: UILabel! var messageTimer: Timer! let kPreviewPadding = CGFloat(10) let kTextBottomPadding = CGFloat(4) let kMaxRemoteVideos = Int(2) static let coreAudioDeviceText = "CoreAudio Device" static let engineAudioDeviceText = "AVAudioEngine Device" deinit { // We are done with camera if let camera = self.camera { camera.stopCapture() self.camera = nil } } override func viewDidLoad() { super.viewDidLoad() title = "AudioDevice Example" disconnectButton.isHidden = true musicButton.isHidden = true disconnectButton.setTitleColor(UIColor(white: 0.75, alpha: 1), for: .disabled) connectButton.setTitleColor(UIColor(white: 0.75, alpha: 1), for: .disabled) connectButton.adjustsImageWhenDisabled = true roomTextField.autocapitalizationType = .none roomTextField.delegate = self logMessage(messageText: ViewController.coreAudioDeviceText + " selected") audioDeviceButton.setTitle("CoreAudio Device", for: .normal) prepareLocalMedia() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func selectAudioDevice() { var selectedButton : UIAlertAction! let alertController = UIAlertController(title: "Select Audio Device", message: nil, preferredStyle: .actionSheet) // ExampleCoreAudioDevice let coreAudioDeviceButton = UIAlertAction(title: ViewController.coreAudioDeviceText, style: .default, handler: { (action) -> Void in self.coreAudioDeviceSelected() }) alertController.addAction(coreAudioDeviceButton) // EngineAudioDevice let audioEngineDeviceButton = UIAlertAction(title: ViewController.engineAudioDeviceText, style: .default, handler: { (action) -> Void in self.avAudioEngineDeviceSelected() }) alertController.addAction(audioEngineDeviceButton) if (self.audioDevice is ExampleCoreAudioDevice) { selectedButton = coreAudioDeviceButton } else if (self.audioDevice is ExampleAVAudioEngineDevice) { selectedButton = audioEngineDeviceButton } if UIDevice.current.userInterfaceIdiom == .pad { alertController.popoverPresentationController?.sourceView = self.audioDeviceButton alertController.popoverPresentationController?.sourceRect = self.audioDeviceButton.bounds } else { selectedButton?.setValue("true", forKey: "checked") // Adding the cancel action let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in }) alertController.addAction(cancelButton) } self.navigationController!.present(alertController, animated: true, completion: nil) } func coreAudioDeviceSelected() { /* * To set an audio device on Video SDK, it is necessary to destroyed the media engine first. By cleaning up the * Room and Tracks the media engine gets destroyed. */ self.unprepareLocalMedia() self.audioDevice = ExampleCoreAudioDevice() self.audioDeviceButton.setTitle(ViewController.coreAudioDeviceText, for: .normal) self.logMessage(messageText: ViewController.coreAudioDeviceText + " Selected") self.prepareLocalMedia() } func avAudioEngineDeviceSelected() { /* * To set an audio device on Video SDK, it is necessary to destroyed the media engine first. By cleaning up the * Room and Tracks the media engine gets destroyed. */ self.unprepareLocalMedia() self.audioDevice = ExampleAVAudioEngineDevice() self.audioDeviceButton.setTitle(ViewController.engineAudioDeviceText, for: .normal) self.logMessage(messageText: ViewController.coreAudioDeviceText + " Selected") self.prepareLocalMedia() } func connectToARoom() { connectButton.isEnabled = true // Preparing the connect options with the access token that we fetched (or hardcoded). let connectOptions = ConnectOptions(token: accessToken) { (builder) in if let videoTrack = self.localVideoTrack { builder.videoTracks = [videoTrack] } // We will share a local audio track only if ExampleAVAudioEngineDevice is selected. if let audioTrack = self.localAudioTrack { builder.audioTracks = [audioTrack] } // Use the preferred codecs if let preferredAudioCodec = Settings.shared.audioCodec { builder.preferredAudioCodecs = [preferredAudioCodec] } if let preferredVideoCodec = Settings.shared.videoCodec { builder.preferredVideoCodecs = [preferredVideoCodec] } // Use the preferred encoding parameters if let encodingParameters = Settings.shared.getEncodingParameters() { builder.encodingParameters = encodingParameters } // Use the preferred signaling region if let signalingRegion = Settings.shared.signalingRegion { builder.region = signalingRegion } // The name of the Room where the Client will attempt to connect to. Please note that if you pass an empty // Room `name`, the Client will create one for you. You can get the name or sid from any connected Room. builder.roomName = self.roomTextField.text } // Connect to the Room using the options we provided. room = TwilioVideoSDK.connect(options: connectOptions, delegate: self) logMessage(messageText: "Connecting to \(roomTextField.text ?? "a Room")") self.showRoomUI(inRoom: true) self.dismissKeyboard() } // MARK:- IBActions @IBAction func connect(sender: AnyObject) { connectButton.isEnabled = false // Configure access token either from server or manually. // If the default wasn't changed, try fetching from server. if (accessToken == "TWILIO_ACCESS_TOKEN") { TokenUtils.fetchToken(from: tokenUrl) { [weak self] (token, error) in DispatchQueue.main.async { if let error = error { let message = "Failed to fetch access token:" + error.localizedDescription self?.logMessage(messageText: message) self?.connectButton.isEnabled = true return } self?.accessToken = token; self?.connectToARoom() } } } else { self.connectToARoom() } } @IBAction func disconnect(sender: UIButton) { if let room = self.room { logMessage(messageText: "Disconnecting from \(room.name)") room.disconnect() sender.isEnabled = false } } @IBAction func playMusic(sender: UIButton) { if let audioDevice = self.audioDevice as? ExampleAVAudioEngineDevice { audioDevice.playMusic(true) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // Layout the preview view. if let previewView = self.camera?.previewView { var bottomRight = CGPoint(x: view.bounds.width, y: view.bounds.height) // Ensure the preview fits in the safe area. let safeAreaGuide = self.view.safeAreaLayoutGuide let layoutFrame = safeAreaGuide.layoutFrame bottomRight.x = layoutFrame.origin.x + layoutFrame.width bottomRight.y = layoutFrame.origin.y + layoutFrame.height let dimensions = previewView.videoDimensions var previewBounds = CGRect(origin: CGPoint.zero, size: CGSize(width: 160, height: 160)) previewBounds = AVMakeRect(aspectRatio: CGSize(width: CGFloat(dimensions.width), height: CGFloat(dimensions.height)), insideRect: previewBounds) previewBounds = previewBounds.integral previewView.bounds = previewBounds previewView.center = CGPoint(x: bottomRight.x - previewBounds.width / 2 - kPreviewPadding, y: bottomRight.y - previewBounds.height / 2 - kPreviewPadding) } } override var prefersHomeIndicatorAutoHidden: Bool { return self.room != nil } override var prefersStatusBarHidden: Bool { return self.room != nil } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { if (newCollection.horizontalSizeClass == .regular || (newCollection.horizontalSizeClass == .compact && newCollection.verticalSizeClass == .compact)) { remoteViewStack.axis = .horizontal } else { remoteViewStack.axis = .vertical } } // Update our UI based upon if we are in a Room or not func showRoomUI(inRoom: Bool) { self.connectButton.isHidden = inRoom self.connectButton.isEnabled = !inRoom self.roomTextField.isHidden = inRoom self.roomLine.isHidden = inRoom self.roomLabel.isHidden = inRoom self.disconnectButton.isHidden = !inRoom self.disconnectButton.isEnabled = inRoom UIApplication.shared.isIdleTimerDisabled = inRoom self.audioDeviceButton.isHidden = inRoom self.audioDeviceButton.isEnabled = !inRoom if ((self.audioDevice as? ExampleAVAudioEngineDevice) != nil) { self.musicButton.isHidden = !inRoom self.musicButton.isEnabled = inRoom } self.setNeedsUpdateOfHomeIndicatorAutoHidden() self.setNeedsStatusBarAppearanceUpdate() self.navigationController?.setNavigationBarHidden(inRoom, animated: true) } func dismissKeyboard() { if (self.roomTextField.isFirstResponder) { self.roomTextField.resignFirstResponder() } } func logMessage(messageText: String) { NSLog(messageText) messageLabel.text = messageText if (messageLabel.alpha < 1.0) { self.messageLabel.isHidden = false UIView.animate(withDuration: 0.4, animations: { self.messageLabel.alpha = 1.0 }) } // Hide the message with a delay. self.messageTimer?.invalidate() self.messageTimer = Timer(timeInterval: TimeInterval(6), target: self, selector: #selector(hideMessageLabel), userInfo: nil, repeats: false) RunLoop.main.add(self.messageTimer, forMode: RunLoop.Mode.common) } @objc func hideMessageLabel() { if (self.messageLabel.isHidden == false) { UIView.animate(withDuration: 0.6, animations: { self.messageLabel.alpha = 0 }, completion: { (complete) in if (complete) { self.messageLabel.isHidden = true } }) } } func prepareLocalMedia() { /* * The important thing to remember when using a custom AudioDevice is that the device must be set * before performing any other actions with the SDK (such as creating Tracks, or connecting to a Room). */ TwilioVideoSDK.audioDevice = self.audioDevice // Only the ExampleAVAudioEngineDevice supports local audio capturing. if (TwilioVideoSDK.audioDevice is ExampleAVAudioEngineDevice) { localAudioTrack = LocalAudioTrack() } /* * ExampleCoreAudioDevice is a playback only device. Because of this, any attempts to create a * LocalAudioTrack will result in an exception being thrown. In this example we will only share video * (where available) and not audio. */ guard let frontCamera = CameraSource.captureDevice(position: .front) else { logMessage(messageText: "Front camera is not available, using audio only.") return } // We will render the camera using CameraPreviewView. let cameraSourceOptions = CameraSourceOptions() { (builder) in builder.enablePreview = true } camera = CameraSource(options: cameraSourceOptions, delegate: self) localVideoTrack = LocalVideoTrack(source: camera!) if (localVideoTrack == nil) { logMessage(messageText: "Failed to create video track!") } else { logMessage(messageText: "Video track created.") if let preview = camera?.previewView { view.addSubview(preview); } camera!.startCapture(device: frontCamera) { (captureDevice, videoFormat, error) in if let error = error { self.logMessage(messageText: "Capture failed with error.\ncode = \((error as NSError).code) error = \(error.localizedDescription)") self.camera?.previewView?.removeFromSuperview() } else { // Layout the camera preview with dimensions appropriate for our orientation. self.view.setNeedsLayout() } } } } func unprepareLocalMedia() { self.room = nil self.localAudioTrack = nil self.localVideoTrack = nil if let camera = self.camera { camera.previewView?.removeFromSuperview() camera.stopCapture() } self.camera = nil; } func setupRemoteVideoView(publication: RemoteVideoTrackPublication) { // Create a `VideoView` programmatically, and add to our `UIStackView` if let remoteView = VideoView(frame: CGRect.zero, delegate:nil) { // We will bet that a hash collision between two unique SIDs is very rare. remoteView.tag = publication.trackSid.hashValue // `VideoView` supports scaleToFill, scaleAspectFill and scaleAspectFit. // scaleAspectFit is the default mode when you create `VideoView` programmatically. remoteView.contentMode = .scaleAspectFit; // Double tap to change the content mode. let recognizerDoubleTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.changeRemoteVideoAspect)) recognizerDoubleTap.numberOfTapsRequired = 2 remoteView.addGestureRecognizer(recognizerDoubleTap) // Start rendering, and add to our stack. publication.remoteTrack?.addRenderer(remoteView) self.remoteViewStack.addArrangedSubview(remoteView) } } func removeRemoteVideoView(publication: RemoteVideoTrackPublication) { let viewTag = publication.trackSid.hashValue if let remoteView = self.remoteViewStack.viewWithTag(viewTag) { // Stop rendering, we don't want to receive any more frames. publication.remoteTrack?.removeRenderer(remoteView as! VideoRenderer) // Automatically removes us from the UIStackView's arranged subviews. remoteView.removeFromSuperview() } } @objc func changeRemoteVideoAspect(gestureRecognizer: UIGestureRecognizer) { guard let remoteView = gestureRecognizer.view else { print("Couldn't find a view attached to the tap recognizer. \(gestureRecognizer)") return; } if (remoteView.contentMode == .scaleAspectFit) { remoteView.contentMode = .scaleAspectFill } else { remoteView.contentMode = .scaleAspectFit } } } // MARK:- UITextFieldDelegate extension ViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.connect(sender: textField) return true } } // MARK:- RoomDelegate extension ViewController : RoomDelegate { func roomDidConnect(room: Room) { // Listen to events from existing `RemoteParticipant`s for remoteParticipant in room.remoteParticipants { remoteParticipant.delegate = self } let connectMessage = "Connected to room \(room.name) as \(room.localParticipant?.identity ?? "")." logMessage(messageText: connectMessage) } func roomDidDisconnect(room: Room, error: Error?) { if let disconnectError = error { logMessage(messageText: "Disconnected from \(room.name).\ncode = \((disconnectError as NSError).code) error = \(disconnectError.localizedDescription)") } else { logMessage(messageText: "Disconnected from \(room.name)") } self.room = nil self.showRoomUI(inRoom: false) } func roomDidFailToConnect(room: Room, error: Error) { logMessage(messageText: "Failed to connect to Room:\n\(error.localizedDescription)") self.room = nil self.showRoomUI(inRoom: false) } func roomIsReconnecting(room: Room, error: Error) { logMessage(messageText: "Reconnecting to room \(room.name), error = \(String(describing: error))") } func roomDidReconnect(room: Room) { logMessage(messageText: "Reconnected to room \(room.name)") } func participantDidConnect(room: Room, participant: RemoteParticipant) { participant.delegate = self logMessage(messageText: "Participant \(participant.identity) connected with \(participant.remoteAudioTracks.count) audio and \(participant.remoteVideoTracks.count) video tracks") } func participantDidDisconnect(room: Room, participant: RemoteParticipant) { logMessage(messageText: "Room \(room.name), Participant \(participant.identity) disconnected") } } // MARK:- RemoteParticipantDelegate extension ViewController : RemoteParticipantDelegate { func remoteParticipantDidPublishVideoTrack(participant: RemoteParticipant, publication: RemoteVideoTrackPublication) { // Remote Participant has offered to share the video Track. logMessage(messageText: "Participant \(participant.identity) published \(publication.trackName) video track") } func remoteParticipantDidUnpublishVideoTrack(participant: RemoteParticipant, publication: RemoteVideoTrackPublication) { // Remote Participant has stopped sharing the video Track. logMessage(messageText: "Participant \(participant.identity) unpublished \(publication.trackName) video track") } func remoteParticipantDidPublishAudioTrack(participant: RemoteParticipant, publication: RemoteAudioTrackPublication) { // Remote Participant has offered to share the audio Track. logMessage(messageText: "Participant \(participant.identity) published \(publication.trackName) audio track") } func remoteParticipantDidUnpublishAudioTrack(participant: RemoteParticipant, publication: RemoteAudioTrackPublication) { // Remote Participant has stopped sharing the audio Track. logMessage(messageText: "Participant \(participant.identity) unpublished \(publication.trackName) audio track") } func didSubscribeToVideoTrack(videoTrack: RemoteVideoTrack, publication: RemoteVideoTrackPublication, participant: RemoteParticipant) { // We are subscribed to the remote Participant's video Track. We will start receiving the // remote Participant's video frames now. logMessage(messageText: "Subscribed to \(publication.trackName) video track for Participant \(participant.identity)") // Start remote rendering, and add a touch handler. if (self.remoteViewStack.arrangedSubviews.count < kMaxRemoteVideos) { setupRemoteVideoView(publication: publication) } } func didUnsubscribeFromVideoTrack(videoTrack: RemoteVideoTrack, publication: RemoteVideoTrackPublication, participant: RemoteParticipant) { // We are unsubscribed from the remote Participant's video Track. We will no longer receive the // remote Participant's video. logMessage(messageText: "Unsubscribed from \(publication.trackName) video track for Participant \(participant.identity)") // Stop remote rendering. removeRemoteVideoView(publication: publication) } func didSubscribeToAudioTrack(audioTrack: RemoteAudioTrack, publication: RemoteAudioTrackPublication, participant: RemoteParticipant) { // We are subscribed to the remote Participant's audio Track. We will start receiving the // remote Participant's audio now. logMessage(messageText: "Subscribed to \(publication.trackName) audio track for Participant \(participant.identity)") } func didUnsubscribeFromAudioTrack(audioTrack: RemoteAudioTrack, publication: RemoteAudioTrackPublication, participant: RemoteParticipant) { // We are unsubscribed from the remote Participant's audio Track. We will no longer receive the // remote Participant's audio. logMessage(messageText: "Unsubscribed from \(publication.trackName) audio track for Participant \(participant.identity)") } func remoteParticipantDidEnableVideoTrack(participant: RemoteParticipant, publication: RemoteVideoTrackPublication) { logMessage(messageText: "Participant \(participant.identity) enabled \(publication.trackName) video track") } func remoteParticipantDidDisableVideoTrack(participant: RemoteParticipant, publication: RemoteVideoTrackPublication) { logMessage(messageText: "Participant \(participant.identity) disabled \(publication.trackName) video track") } func remoteParticipantDidEnableAudioTrack(participant: RemoteParticipant, publication: RemoteAudioTrackPublication) { logMessage(messageText: "Participant \(participant.identity) enabled \(publication.trackName) audio track") } func remoteParticipantDidDisableAudioTrack(participant: RemoteParticipant, publication: RemoteAudioTrackPublication) { // We will continue to record silence and/or recognize audio while a Track is disabled. logMessage(messageText: "Participant \(participant.identity) disabled \(publication.trackName) audio track") } func didFailToSubscribeToAudioTrack(publication: RemoteAudioTrackPublication, error: Error, participant: RemoteParticipant) { logMessage(messageText: "FailedToSubscribe \(publication.trackName) audio track, error = \(String(describing: error))") } func didFailToSubscribeToVideoTrack(publication: RemoteVideoTrackPublication, error: Error, participant: RemoteParticipant) { logMessage(messageText: "FailedToSubscribe \(publication.trackName) video track, error = \(String(describing: error))") } } // MARK:- CameraSourceDelegate extension ViewController : CameraSourceDelegate { func cameraSourceDidFail(source: CameraSource, error: Error) { logMessage(messageText: "Camera source failed with error: \(error.localizedDescription)") source.previewView?.removeFromSuperview() } }
mit
1f81c1a8211896348acce25e391ddcef
40.507488
186
0.657701
5.62734
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/EC2InstanceConnect/EC2InstanceConnect_Error.swift
1
2971
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for EC2InstanceConnect public struct EC2InstanceConnectErrorType: AWSErrorType { enum Code: String { case authException = "AuthException" case eC2InstanceNotFoundException = "EC2InstanceNotFoundException" case invalidArgsException = "InvalidArgsException" case serviceException = "ServiceException" case throttlingException = "ThrottlingException" } private let error: Code public let context: AWSErrorContext? /// initialize EC2InstanceConnect public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// Indicates that either your AWS credentials are invalid or you do not have access to the EC2 instance. public static var authException: Self { .init(.authException) } /// Indicates that the instance requested was not found in the given zone. Check that you have provided a valid instance ID and the correct zone. public static var eC2InstanceNotFoundException: Self { .init(.eC2InstanceNotFoundException) } /// Indicates that you provided bad input. Ensure you have a valid instance ID, the correct zone, and a valid SSH public key. public static var invalidArgsException: Self { .init(.invalidArgsException) } /// Indicates that the service encountered an error. Follow the message's instructions and try again. public static var serviceException: Self { .init(.serviceException) } /// Indicates you have been making requests too frequently and have been throttled. Wait for a while and try again. If higher call volume is warranted contact AWS Support. public static var throttlingException: Self { .init(.throttlingException) } } extension EC2InstanceConnectErrorType: Equatable { public static func == (lhs: EC2InstanceConnectErrorType, rhs: EC2InstanceConnectErrorType) -> Bool { lhs.error == rhs.error } } extension EC2InstanceConnectErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
b7f8d583f9c5fa7cfd9f1d299bd54449
42.057971
175
0.686301
4.886513
false
false
false
false
mmoaay/MBNetwork
Bamboots/Classes/Core/Extension/UIView+Bamboots.swift
1
1631
// // UIView+Bamboots.swift // Pods // // Created by Perry on 16/7/7. // // import Foundation internal extension UIView { /// Inner addSubView for Bamboots, making autolayout when addSubView /// /// - Parameters: /// - subview: view to be added /// - insets: insets between subview and view itself internal func addSubView(_ subview: UIView, insets: UIEdgeInsets = UIEdgeInsets.zero) { self.addSubview(subview) subview.translatesAutoresizingMaskIntoConstraints = false let views: [String : UIView] = ["subview": subview] let layoutStringH: String = "H:|-" + String(describing: insets.left) + "-[subview]-" + String(describing: insets.right) + "-|" let layoutStringV: String = "V:|-" + String(describing: insets.top) + "-[subview]-" + String(describing: insets.bottom) + "-|" let contraintsH: [NSLayoutConstraint] = NSLayoutConstraint.constraints( withVisualFormat: layoutStringH, options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: views ) let contraintsV: [NSLayoutConstraint] = NSLayoutConstraint.constraints( withVisualFormat: layoutStringV, options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: views ) self.addConstraints(contraintsH) self.addConstraints(contraintsV) } } // MARK: - Making `UIView` conforms to `Containable` extension UIView: Containable { /// Return self as container for `UIView` /// /// - Returns: `UIView` itself @objc public func containerView() -> UIView? { return self } }
mit
7525d58dedfcb5f4056627107a45e001
32.285714
114
0.648069
4.420054
false
false
false
false
Hodglim/hacking-with-swift
Project-14/WhackAPenguin/GameScene.swift
1
3366
// // GameScene.swift // WhackAPenguin // // Created by Darren Hodges on 27/10/2015. // Copyright (c) 2015 Darren Hodges. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene { var slots = [WhackSlot]() var popupTime = 0.85 var numRounds = 0 var gameScore: SKLabelNode! var score: Int = 0 { didSet { gameScore.text = "Score: \(score)" } } override func didMoveToView(view: SKView) { // Background let background = SKSpriteNode(imageNamed: "whackBackground") background.position = CGPoint(x: 512, y: 384) background.blendMode = .Replace background.zPosition = -1 addChild(background) // Score label gameScore = SKLabelNode(fontNamed: "Chalkduster") gameScore.text = "Score: 0" gameScore.position = CGPoint(x: 8, y: 8) gameScore.horizontalAlignmentMode = .Left gameScore.fontSize = 48 addChild(gameScore) // Create slots for i in 0 ..< 5 { createSlotAt(CGPoint(x: 100 + (i * 170), y: 410)) } for i in 0 ..< 4 { createSlotAt(CGPoint(x: 180 + (i * 170), y: 320)) } for i in 0 ..< 5 { createSlotAt(CGPoint(x: 100 + (i * 170), y: 230)) } for i in 0 ..< 4 { createSlotAt(CGPoint(x: 180 + (i * 170), y: 140)) } // Start creating enemies after 1 second delay RunAfterDelay(1) { [unowned self] in self.createEnemy() } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { let location = touch.locationInNode(self) let nodes = nodesAtPoint(location) for node in nodes { if node.name == "charFriend" { let whackSlot = node.parent!.parent as! WhackSlot if !whackSlot.visible { continue } if whackSlot.isHit { continue } whackSlot.hit() score -= 5 runAction(SKAction.playSoundFileNamed("whackBad.caf", waitForCompletion:false)) } else if node.name == "charEnemy" { let whackSlot = node.parent!.parent as! WhackSlot if !whackSlot.visible { continue } if whackSlot.isHit { continue } whackSlot.charNode.xScale = 0.85 whackSlot.charNode.yScale = 0.85 whackSlot.hit() ++score runAction(SKAction.playSoundFileNamed("whack.caf", waitForCompletion:false)) } } } } func createSlotAt(pos: CGPoint) { let slot = WhackSlot() slot.configureAtPosition(pos) addChild(slot) slots.append(slot) } func createEnemy() { // Game Over after 30 rounds if ++numRounds >= 30 { for slot in slots { slot.hide() } let gameOver = SKSpriteNode(imageNamed: "gameOver") gameOver.position = CGPoint(x: 512, y: 384) gameOver.zPosition = 1 addChild(gameOver) return } popupTime *= 0.991 slots = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(slots) as! [WhackSlot] slots[0].show(hideTime: popupTime) if RandomInt(min: 0, max: 12) > 4 { slots[1].show(hideTime: popupTime) } if RandomInt(min: 0, max: 12) > 8 { slots[2].show(hideTime: popupTime) } if RandomInt(min: 0, max: 12) > 10 { slots[3].show(hideTime: popupTime) } if RandomInt(min: 0, max: 12) > 11 { slots[4].show(hideTime: popupTime) } let minDelay = popupTime / 2.0 let maxDelay = popupTime * 2 RunAfterDelay(RandomDouble(min: minDelay, max: maxDelay)) { [unowned self] in self.createEnemy() } } }
mit
8f78aa1529d55a6ac0272750f2df4438
23.042857
93
0.647059
3.35259
false
false
false
false
fiveagency/ios-five-persistence
Sources/Keeper+UIImage.swift
1
4955
// // Keeper+UIImage.swift // FivePersistence // // Created by Miran Brajsa on 30/09/16. // Copyright © 2016 Five Agency. All rights reserved. // import CoreGraphics import Foundation #if os(iOS) import UIKit /** Keeper image format specification. This enum is used while specifying a format in which an image will be converted to `Data`. */ public enum KeeperImageFormat { case png case jpg(CGFloat) } /** Keeper image return type for synchronous calls. The first `bool` flag is stating whether or not the call was successfull. The second `UIImage` object represents the requested `UIImage` provided `success` equals `true`. If `success` equals `false` the third `Error` parameter will present the underlaying error. */ public typealias KeeperImageResult = (Bool, UIImage?, Error?) /** Keeper image return type for asynchronous calls. - parameter result: The tuple values those represented by `KeeperImageResult` which are(success: Bool, image: UIImage?, error: Error?) */ public typealias KeeperImageCompletion = (_ result: KeeperImageResult) -> Void /** Keeper errors. */ public enum KeeperImageError: Error { case unableToCreateImageData } // MARK: Asynchronous extension Keeper { /** Retrieves an `UIImage` object for a given key. - Important: This method is thread safe with the completion block always executed on the `main queue`. - parameter key: A key which identifies our `UIImage`. - parameter completion: A completion block containing `KeeperImageCompletion` tuple. */ public func image(forKey key: String, completion: @escaping KeeperImageCompletion) { data(forKey: key) { success, data, error in guard let imageData = data, success else { completion((false, nil, error)) return } completion((success, UIImage(data: imageData), error)) } } /** Saves the `UIImage` object, for a given key, in memory and on disk. If a disk operation fails, object is not stored into memory. If the object for a given key already exists, it will be overwriten. - Important: This method is thread safe with the completion block always executed on the `main queue`. - parameter image: An `UIImage` object to save. - parameter key: A key which identifies our `UIImage`. - parameter format: A format in which the image should be stored. For list of supported formats see `KeeperImageFormat` enum. - parameter completion: A completion block containing `KeeperImageCompletion` tuple. */ public func save(image: UIImage, forKey key: String, format: KeeperImageFormat = .png, completion: @escaping KeeperImageCompletion) { guard let data = data(fromImage: image, format: format) else { DispatchQueue.main.async { completion((false, nil, KeeperImageError.unableToCreateImageData)) } return } save(data: data, forKey: key) { success, data, error in completion((success, image, error)) } } } // MARK: Synchronous extension Keeper { /** Retrieves an `UIImage` object for a given key. - parameter key: A key which identifies our `UIImage`. - returns: An `KeeperImageResult` tuple. */ public func image(forKey key: String) -> KeeperImageResult { let (success, data, error) = self.data(forKey: key) guard let imageData = data, success else { return (false, nil, error) } return (success, UIImage(data: imageData), error) } /** Saves the `UIImage` object, for a given key, in memory and on disk. If a disk operation fails, object is not stored into memory. If the object for a given key already exists, it will be overwriten. - parameter image: An `UIImage` object to save. - parameter key: A key which identifies our `UIImage`. - parameter format: A format in which the image should be stored. For list of supported formats see `KeeperImageFormat` enum. - returns: An `KeeperImageResult` tuple. */ public func save(image: UIImage, forKey key: String, format: KeeperImageFormat = .png) -> KeeperImageResult { guard let imageData = data(fromImage: image, format: format) else { return (false, nil, KeeperImageError.unableToCreateImageData) } let (success, _, error) = save(data: imageData, forKey: key) return (success, image, error) } } extension Keeper { fileprivate func data(fromImage image: UIImage, format: KeeperImageFormat) -> Data? { let data: Data? switch format { case .png: data = UIImagePNGRepresentation(image) case .jpg(let compressionQuality): data = UIImageJPEGRepresentation(image, compressionQuality) } return data } } #endif
mit
b65b99697a7b346f4375fe9cae7fee25
32.248322
137
0.662495
4.53663
false
false
false
false
coryoso/HanekeSwift
Haneke/Haneke.swift
1
1411
// // Haneke.swift // Haneke // // Created by Hermes Pique on 9/9/14. // Copyright (c) 2014 Haneke. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif public struct HanekeGlobals { public static let Domain = "io.haneke" } public struct Shared { public static var imageCache : Cache<Image> { struct Static { static let name = "shared-images" static let cache = Cache<Image>(name: name) } return Static.cache } public static var dataCache : Cache<NSData> { struct Static { static let name = "shared-data" static let cache = Cache<NSData>(name: name) } return Static.cache } public static var stringCache : Cache<String> { struct Static { static let name = "shared-strings" static let cache = Cache<String>(name: name) } return Static.cache } public static var JSONCache : Cache<JSON> { struct Static { static let name = "shared-json" static let cache = Cache<JSON>(name: name) } return Static.cache } } func errorWithCode(code: Int, description: String) -> NSError { let userInfo = [NSLocalizedDescriptionKey: description] return NSError(domain: HanekeGlobals.Domain, code: code, userInfo: userInfo) }
apache-2.0
2715636c2718f35a0734dfb7f9064b76
22.915254
80
0.588235
4.314985
false
false
false
false
nheagy/WordPress-iOS
WordPress/WordPressTest/PlanListViewControllerTest.swift
1
1956
import XCTest import Nimble @testable import WordPress class PlanListViewControllerTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: - PlanListRow tests func testPlanListRowAttributedTitleWhenCurrent() { let attributedTitle = PlanListRow.Formatter.attributedTitle("Title", price: "$99", active: true) expect(attributedTitle.string).to(equal("Title CURRENT PLAN")) } func testPlanListRowAttributedTitleWhenNotCurrent() { let attributedTitle = PlanListRow.Formatter.attributedTitle("Title", price: "$99", active: false) expect(attributedTitle.string).to(equal("Title $99 per year")) } // MARK: - PlanListViewModel tests func testPlanImageWhenActivePlanSet() { let model = PlanListViewModel.Ready((activePlan: defaultPlans[1], availablePlans: plansWithPrices)) let tableViewModel = model.tableViewModelWithPresenter(nil, planService: nil) let freeRow = tableViewModel.planRowAtIndex(0) let premiumRow = tableViewModel.planRowAtIndex(1) let businessRow = tableViewModel.planRowAtIndex(2) expect(freeRow.icon).to(equal(defaultPlans[0].image)) expect(premiumRow.icon).to(equal(defaultPlans[1].activeImage)) expect(businessRow.icon).to(equal(defaultPlans[2].image)) } let plansWithPrices: [PricedPlan] = [ (defaultPlans[0], ""), (defaultPlans[1], "$99.99"), (defaultPlans[2], "$299.99") ] } extension ImmuTable { private func planRowAtIndex(index: Int) -> PlanListRow { return rowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as! PlanListRow } }
gpl-2.0
0b6b3b4b0407c1304c2c31f86476669c
35.222222
111
0.687117
4.455581
false
true
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/SolutionsTests/Medium/Medium_022_Generate_Parentheses_Test.swift
1
1569
// // Medium_022_Generate_Parentheses_Test.swift // Solutions // // Created by Di Wu on 5/5/15. // Copyright (c) 2015 diwu. All rights reserved. // import XCTest class Medium_022_Generate_Parentheses_Test: XCTestCase, SolutionsTestCase { func test_001() { let input: Int = 1 let expected: [String] = ["()"] asyncHelper(input: input, expected: expected) } func test_002() { let input: Int = 0 let expected: [String] = [""] asyncHelper(input: input, expected: expected) } func test_003() { let input: Int = 3 let expected: [String] = ["((()))", "(()())", "(())()", "()(())", "()()()"] asyncHelper(input: input, expected: expected) } private func asyncHelper(input: Int, expected: [String]) { weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName()) serialQueue().async(execute: { () -> Void in let result: [String] = Medium_022_Generate_Parentheses.generateParenthesis(input) assertHelper(Set(expected) == Set(result), problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected) if let unwrapped = expectation { unwrapped.fulfill() } }) waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in if error != nil { assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected) } } } }
mit
2167fffc990b43d06167c390771cdffb
35.488372
146
0.589547
4.263587
false
true
false
false
antonio081014/LeeCode-CodeBase
Swift/clone-graph.swift
2
2516
/** * https://leetcode.com/problems/clone-graph/ * * */ // Date: Thu Oct 22 10:44:31 PDT 2020 /** * Definition for a Node. * public class Node { * public var val: Int * public var neighbors: [Node?] * public init(_ val: Int) { * self.val = val * self.neighbors = [] * } * } */ /// DFS with memorized nodes. /// DFS could simply result to endless loop in a cycle, which is why we memorized all the visied nodes. /// - Complexity: /// - Time: O(E + V), try visit all the nodes and edges connecting two nodes. /// - Space: O(E + V), since we need to make a copy. No extra. class Solution { var visitedNode: [Int: Node] = [:] func cloneGraph(_ node: Node?) -> Node? { guard let val = node?.val else { return nil } if let cloneNode = visitedNode[val] { return cloneNode } let root = Node(val) visitedNode[val] = root for neighbor in node?.neighbors ?? [] { if let cloneNeighbor = cloneGraph(neighbor) { root.neighbors.append(cloneGraph(neighbor)) } } return root } }/** * https://leetcode.com/problems/clone-graph/ * * */ // Date: Thu Oct 22 11:23:07 PDT 2020 /** * Definition for a Node. * public class Node { * public var val: Int * public var neighbors: [Node?] * public init(_ val: Int) { * self.val = val * self.neighbors = [] * } * } */ /// /// BFS, traverse all the nodes and edges from starting node. /// /// - Complexity: /// - Time: O(E + V) /// - Space: O(E + V) class Solution { func cloneGraph(_ node: Node?) -> Node? { guard let val = node?.val else { return nil } var visited: [Int : Node] = [:] let root = Node(val) visited[val] = root // Keep original nodes in the queue, // while keep all the new created nodes in the visited dictionary. var queue: [Node] = [node!] while let first = queue.first { queue.removeFirst() for neighbor in first.neighbors where neighbor != nil { if visited[neighbor!.val] == nil { queue.append(neighbor!) visited[neighbor!.val] = Node(neighbor!.val) } if let cloneNode = visited[first.val], let nextNode = visited[neighbor!.val] { cloneNode.neighbors.append(nextNode) } } } return root } }
mit
25fa44921ccf73739b27e3a059a418d1
28.267442
103
0.535771
3.841221
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Helpers/Glob.swift
1
3474
import Foundation #if canImport(Darwin) import Darwin private let globFunction = Darwin.glob #elseif canImport(Glibc) import Glibc private let globFunction = Glibc.glob #else #error("Unsupported platform") #endif // Adapted from https://gist.github.com/efirestone/ce01ae109e08772647eb061b3bb387c3 struct Glob { static func resolveGlob(_ pattern: String) -> [String] { let globCharset = CharacterSet(charactersIn: "*?[]") guard pattern.rangeOfCharacter(from: globCharset) != nil else { return [pattern] } return expandGlobstar(pattern: pattern) .reduce(into: [String]()) { paths, pattern in var globResult = glob_t() defer { globfree(&globResult) } if globFunction(pattern, GLOB_TILDE | GLOB_BRACE | GLOB_MARK, nil, &globResult) == 0 { paths.append(contentsOf: populateFiles(globResult: globResult)) } } .unique .sorted() .map { $0.absolutePathStandardized() } } // MARK: Private private static func expandGlobstar(pattern: String) -> [String] { guard pattern.contains("**") else { return [pattern] } var results = [String]() var parts = pattern.components(separatedBy: "**") let firstPart = parts.removeFirst() var lastPart = parts.joined(separator: "**") let fileManager = FileManager.default var directories: [String] let searchPath = firstPart.isEmpty ? fileManager.currentDirectoryPath : firstPart do { directories = try fileManager.subpathsOfDirectory(atPath: searchPath).compactMap { subpath in let fullPath = firstPart.bridge().appendingPathComponent(subpath) guard isDirectory(path: fullPath) else { return nil } return fullPath } } catch { directories = [] queuedPrintError("Error parsing file system item: \(error)") } // Check the base directory for the glob star as well. directories.insert(firstPart, at: 0) // Include the globstar root directory ("dir/") in a pattern like "dir/**" or "dir/**/" if lastPart.isEmpty { results.append(firstPart) lastPart = "*" } for directory in directories { let partiallyResolvedPattern: String if directory.isEmpty { partiallyResolvedPattern = lastPart.starts(with: "/") ? String(lastPart.dropFirst()) : lastPart } else { partiallyResolvedPattern = directory.bridge().appendingPathComponent(lastPart) } results.append(contentsOf: expandGlobstar(pattern: partiallyResolvedPattern)) } return results } private static func isDirectory(path: String) -> Bool { var isDirectoryBool = ObjCBool(false) let isDirectory = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectoryBool) return isDirectory && isDirectoryBool.boolValue } private static func populateFiles(globResult: glob_t) -> [String] { #if os(Linux) let matchCount = globResult.gl_pathc #else let matchCount = globResult.gl_matchc #endif return (0..<Int(matchCount)).compactMap { index in globResult.gl_pathv[index].flatMap { String(validatingUTF8: $0) } } } }
mit
675a57db1da4eb4eeb8de5d14dbb4b68
32.403846
111
0.611111
4.771978
false
false
false
false
marklin2012/iOS_Animation
Section1/Chapter2/O2UIViewAnimation_completion/O2UIViewAnimation/ViewController.swift
1
5338
// // ViewController.swift // O2UIViewAnimation // // Created by O2.LinYi on 16/3/10. // Copyright © 2016年 jd.com. All rights reserved. // import UIKit // a delay function func delay(seconds seconds: Double, completion: () -> ()) { let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * seconds)) dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in completion() } } class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var loginBtn: UIButton! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var headingLabel: UILabel! @IBOutlet weak var cloud1: UIImageView! @IBOutlet weak var cloud2: UIImageView! @IBOutlet weak var cloud3: UIImageView! @IBOutlet weak var cloud4: UIImageView! // MARK: - further UI let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) let status = UIImageView(image: UIImage(named: "banner")) let label = UILabel() let messages = ["Connectiong ...", "Authorizing ...", "Sending credentials ...", "Failed"] // MARK: - Lift cycle override func viewDidLoad() { super.viewDidLoad() // set up the UI loginBtn.layer.cornerRadius = 8.0 loginBtn.layer.masksToBounds = true spinner.frame = CGRect(x: -20, y: 6, width: 20, height: 20) spinner.startAnimating() spinner.alpha = 0 loginBtn.addSubview(spinner) status.hidden = true status.center = loginBtn.center view.addSubview(status) label.frame = CGRect(x: 0, y: 0, width: status.frame.size.width, height: status.frame.size.height) label.font = UIFont(name: "HelveticaNeue", size: 18) label.textColor = UIColor(red: 0.89, green: 0.38, blue: 0, alpha: 1) label.textAlignment = .Center status.addSubview(label) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // set first position to move out the screen headingLabel.center.x -= view.bounds.width usernameField.center.x -= view.bounds.width passwordField.center.x -= view.bounds.width cloud1.alpha = 0.0 cloud2.alpha = 0.0 cloud3.alpha = 0.0 cloud4.alpha = 0.0 loginBtn.center.y += 30 loginBtn.alpha = 0 // present animation UIView.animateWithDuration(0.5) { () -> Void in self.headingLabel.center.x += self.view.bounds.width // usernameField.center.x += view.bounds.width } UIView.animateWithDuration(0.5, delay: 0.3, options: [], animations: { () -> Void in self.usernameField.center.x += self.view.bounds.width }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.4, options: [.CurveEaseInOut], animations: { () -> Void in self.passwordField.center.x += self.view.bounds.width }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.5, options: [], animations: { () -> Void in self.cloud1.alpha = 1 }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.7, options: [], animations: { () -> Void in self.cloud2.alpha = 1 }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.9, options: [], animations: { () -> Void in self.cloud3.alpha = 1 }, completion: nil) UIView.animateWithDuration(0.5, delay: 1.1, options: [], animations: { () -> Void in self.cloud4.alpha = 1 }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [], animations: { () -> Void in self.loginBtn.center.y -= 30 self.loginBtn.alpha = 1.0 }, completion: nil) } // MARK: - further methods @IBAction func login() { view.endEditing(true) // add animation UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: [], animations: { () -> Void in self.loginBtn.bounds.size.width += 80 }, completion: nil) UIView.animateWithDuration(0.33, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in self.loginBtn.center.y += 60 self.loginBtn.backgroundColor = UIColor(red: 0.85, green: 0.83, blue: 0.45, alpha: 1) self.spinner.center = CGPoint(x: 40, y: self.loginBtn.frame.size.height/2) self.spinner.alpha = 1 }, completion: nil) } // MARK: - UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { let nextField = (textField === usernameField) ? passwordField : usernameField nextField.becomeFirstResponder() return true } }
mit
56742e7ab8d00a7e26ebfab268f7776e
33.419355
147
0.589128
4.409091
false
false
false
false
modocache/Gift
Gift/Reference/Reference.swift
1
1526
import Foundation import LlamaKit /** References point to an underlying Git object, but have more semantically meaningful names. A branch, for example, is a named reference pointing to the latest commit in a series of work. */ public class Reference { internal let cReference: COpaquePointer internal init(cReference: COpaquePointer) { self.cReference = cReference } deinit { git_reference_free(cReference) } } public extension Reference { /** The name of the reference. */ public var name: Result<String, NSError> { let referenceName = git_reference_name(cReference) if let name = String.fromCString(referenceName) { return success(name) } else { let description = "An error occurred when attempting to convert reference name \(referenceName) " + "provided by git_reference_name to a String." return failure(NSError.giftError(.StringConversionFailure, description: description)) } } /** Returns a 40-digit hexadecimal number string representation of the SHA1 of the reference. The SHA1 is a unique name obtained by applying the SHA1 hashing algorithm to the contents of the reference. This is a string representation of the object ID. */ public var SHA: Result<String, NSError> { return object.flatMap { objectIDSHA($0.objectID) } } /** Whether or not the reference is to a remote tracking branch. */ public var isRemote: Bool { return git_reference_is_remote(cReference) != 0 } }
mit
a01409ebf056d25e6d2b9daa2fd6a6d4
28.346154
103
0.703145
4.44898
false
false
false
false
kronik/swift4fun
LeaveList/LeaveList/Model.swift
1
7983
// // Model.swift // LeaveList // // Created by Dmitry on 7/7/16. // Copyright © 2016 Dmitry Klimkin. All rights reserved. // import Foundation import RealmSwift public typealias DataDidChangeHandler = () -> Void public class Model { static let sharedInstance = Model() private let realmDbSchemaVersion: UInt64 = 3 private var updateToken: NotificationToken? public var dataChangeHandler: DataDidChangeHandler = { } { didSet { updateToken?.stop() let realm = try! Realm() updateToken = realm.addNotificationBlock { (notification, realm) in self.dataChangeHandler() } } } private init() { var config = Realm.Configuration( schemaVersion: realmDbSchemaVersion, migrationBlock: {(migration: Migration, oldSchemaVersion: UInt64) in if oldSchemaVersion < 1 { } } ) let containerUrl = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(Model.appGroupId) if let containerUrl = containerUrl { config.fileURL = containerUrl.URLByAppendingPathComponent("db.realm", isDirectory: false) } Realm.Configuration.defaultConfiguration = config } public class func save(object: ModelObject) { let objectToSave = object.copyToSave() let realm = try! Realm() try! realm.write { realm.add(objectToSave, update: true) } } public class func delete(object: ModelObject) { let realm = try! Realm() try! realm.write { realm.delete(object) } } public class func update(block: (() -> Void)) { let realm = try! Realm() try! realm.write { block() } } deinit { updateToken?.stop() } } public class ModelObject: Object { dynamic var key = "" dynamic var isDeleted = false dynamic var createdAt = NSDate() public override class func primaryKey() -> String? { return "key" } public func copyToSave() -> ModelObject { return self } public func markAsDeleted() { let record = copyToSave() record.isDeleted = true Model.save(record) } public override func isEqual(object: AnyObject?) -> Bool { if let rhs = object as? ModelObject { return key == rhs.key } return false } } public class ListEntry: ModelObject { dynamic var lastActionDate = NSDate() dynamic var textDescription = "" dynamic var listKey = "" dynamic var cachedDescription = "" public override func copyToSave() -> ModelObject { if key.isEmpty { key = String.uniqueString() return self } let newObject = ListEntry() newObject.key = key newObject.listKey = listKey newObject.isDeleted = isDeleted newObject.lastActionDate = lastActionDate newObject.textDescription = textDescription newObject.createdAt = createdAt newObject.cachedDescription = cachedDescription return newObject } public override static func ignoredProperties() -> [String] { return ["cachedDescription"] } public class func loadByKey(key: String) -> ListEntry? { var filter = NSPredicate(format: "key == %@ AND isDeleted == 0", key) let realm = try! Realm() var record: ListEntry? var results = realm.objects(ListEntry).filter(filter).sorted("createdAt", ascending: true) if results.count == 0 { filter = NSPredicate(format: "key == %@", key) results = realm.objects(ListEntry).filter(filter).sorted("createdAt", ascending: true) } record = results.first if let recordValue = record { record = recordValue.copyToSave() as? ListEntry } return record } public class func loadAllEntries() -> Results<ListEntry>? { let realm = try! Realm() let results = realm.objects(ListEntry).filter("isDeleted == 0").sorted("createdAt", ascending: false) return results } public class func loadEntriesContaining(text: String) -> Results<ListEntry>? { let realm = try! Realm() let results = realm.objects(ListEntry).filter("isDeleted == 0 AND textDescription CONTAINS[c] '\(text)'").sorted("createdAt", ascending: false) return results } public func markAsDone() { let record = self.copyToSave() as! ListEntry record.lastActionDate = NSDate() Model.save(record) } public func loadAllEvents() -> Results<ListEntryEvent>? { let realm = try! Realm() let filter = NSPredicate(format: "listEntryKey == %@ AND isDeleted == 0", key) let results = realm.objects(ListEntryEvent).filter(filter).sorted("createdAt", ascending: true) return results } } public class ListEntryEvent: ModelObject { dynamic var listEntryKey = "" dynamic var text = "" dynamic var longitude: Double = 0.0 dynamic var latitude: Double = 0.0 public override func copyToSave() -> ModelObject { if key.isEmpty { key = String.uniqueString() return self } let newObject = ListEntryEvent() newObject.key = key newObject.listEntryKey = listEntryKey newObject.isDeleted = isDeleted newObject.text = text newObject.longitude = longitude newObject.latitude = latitude newObject.createdAt = createdAt return newObject } public class func loadByKey(key: String) -> ListEntryEvent? { var filter = NSPredicate(format: "key == %@ AND isDeleted == 0", key) let realm = try! Realm() var record: ListEntryEvent? var results = realm.objects(ListEntryEvent).filter(filter).sorted("createdAt", ascending: true) if results.count == 0 { filter = NSPredicate(format: "key == %@", key) results = realm.objects(ListEntryEvent).filter(filter).sorted("createdAt", ascending: true) } record = results.first if let recordValue = record { record = recordValue.copyToSave() as? ListEntryEvent } return record } public class func loadAllEventsByListEntryKey(listEntryKey: String) -> Results<ListEntryEvent>? { let realm = try! Realm() let filter = NSPredicate(format: "listEntryKey == %@ AND isDeleted == 0", listEntryKey) let results = realm.objects(ListEntryEvent).filter(filter).sorted("createdAt", ascending: true) return results } } extension Model { static var bundleId: String { get { let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier; if let identifier = bundleIdentifier { return identifier } else { #if DEBUG let appBundleId = "com.leave-list.ios-test" #else let appBundleId = "com.leave-list.ios" #endif return appBundleId } } } static var appGroupId: String { get { return "group.\(Model.bundleId)" } } } extension String { static func uniqueString() -> String { return NSUUID().UUIDString } }
mit
c85f63d0320b0d0a35d0ee89f4efba0f
27.507143
151
0.562641
5.230668
false
false
false
false
anzfactory/QiitaCollection
QiitaCollection/SearchViewController.swift
1
6771
// // SearchViewController.swift // QiitaCollection // // Created by ANZ on 2015/02/22. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit class SearchViewController: BaseViewController, SearchConditionViewDelegate, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, SWTableViewCellDelegate { typealias SearchConditionItem = (query:String, isExclude:Bool, type: SearchConditionView.SearchType) typealias SearchCallback = (SearchViewController, String) -> Void // MARK: UI @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var searchConditionView: SearchConditionView! @IBOutlet weak var tableView: UITableView! // MARK: 制約 @IBOutlet weak var constraintHeightSearchCondition: NSLayoutConstraint! // プロパティ var items: [SearchConditionItem] = [SearchConditionItem]() var tapGesture: UITapGestureRecognizer! var callback: SearchCallback? // MARK: ライフサイクル override func viewDidLoad() { super.viewDidLoad() self.setupForPresentedVC(self.navigationBar) self.searchConditionView.delegate = self self.searchConditionView.query.delegate = self self.searchConditionView.showGuide(GuideManager.GuideType.SearchConditionView, inView: self.view) self.tableView.separatorColor = UIColor.borderTableView() self.tableView.tableFooterView = UIView(frame: CGRect.zeroRect) self.tableView.dataSource = self self.tableView.delegate = self self.tapGesture = UITapGestureRecognizer(target: self, action: "tapView:") self.view.addGestureRecognizer(self.tapGesture) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveKeyboardShowNotification:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveKeyboardHideNotification:", name: UIKeyboardWillHideNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Actions @IBAction func tapClose(sender: AnyObject) { self.dismiss() } // MARK: メソッド func tapSearch() { // もし入力中のものがあればついか if !self.searchConditionView.query.text.isEmpty { self.addCondition() } if self.items.isEmpty { if self.searchConditionView.query.text.isEmpty { Toast.show("検索キーワードを入力してください", style: JFMinimalNotificationStytle.StyleWarning, title: "", targetView: self.searchConditionView) return } } // サーチ self.searchConditionView.doSearch.enabled = false self.view.endEditing(true) // 検索クエリを作って渡す var q: String = "" for item in self.items { q += String(format: " %@%@%@", item.isExclude ? "-" : "", item.type.query(), item.query) } q = q.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) self.callback?(self, q) } func receiveKeyboardShowNotification(notification: NSNotification) { if let userInfo = notification.userInfo { if let keyboard = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { let keyBoardRect: CGRect = keyboard.CGRectValue() self.constraintHeightSearchCondition.constant = keyBoardRect.size.height UIView.animateWithDuration(0.5, animations: { () -> Void in self.view.layoutIfNeeded() }) } } } func receiveKeyboardHideNotification(notification: NSNotification) { self.constraintHeightSearchCondition.constant = 0.0 UIView.animateWithDuration(0.5, animations: { () -> Void in self.view.layoutIfNeeded() }) } func tapView(gesture: UITapGestureRecognizer) { self.view.endEditing(true) } func dismiss() { self.view.endEditing(true) self.transitionSenderPoint = self.searchConditionView.convertPoint(self.searchConditionView.doSearch.center, toView: self.view) self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } func addCondition() { let item: SearchConditionItem = SearchConditionItem(query: self.searchConditionView.query.text, isExclude: self.searchConditionView.excludeCheck.selected, type: SearchConditionView.SearchType(rawValue: self.searchConditionView.searchType.selectedSegmentIndex)!) self.items.append(item) self.tableView.reloadData() self.searchConditionView.clear() } func deleteSeachCondition(index: Int) { self.items.removeAtIndex(index) self.tableView.reloadData() } // MARK: SearchConditionViewDelegate func searchVC(viewController: SearchConditionView, sender: UIButton) { if sender == viewController.doSearch { self.tapSearch() } } // MARK: UITableViewDataSource func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 56.0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: SearchTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("CELL") as! SearchTableViewCell cell.show(self.items[indexPath.row]) cell.delegate = self cell.tag = indexPath.row return cell } // MARK: UITableViewDelegate func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 { cell.showGuide(.SearchConditionSwaipeCell, inView: self.view) } } // MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { self.addCondition() textField.resignFirstResponder() return true } // MARK: SWTableViewCellDelegate func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) { if index == 0 { self.deleteSeachCondition(cell.tag) } } }
mit
5d8ee67c64a7ce509a0b48cb73f969cd
35.103261
269
0.661749
5.234831
false
false
false
false
vapor/node
Sources/Node/Fuzzy/Fuzzy+Any.swift
1
557
extension StructuredDataWrapper { public mutating func set(_ path: String, _ any: Any?) throws { let value = try Node.fuzzy.represent(any, in: context) wrapped[path] = value.wrapped } public func get<T>(_ path: String) throws -> T { let data = wrapped[path] ?? .null let node = Node(data, in: context) return try Node.fuzzy.initialize(node: node) } public func get<T>() throws -> T { let node = Node(wrapped, in: context) return try Node.fuzzy.initialize(node: node) } }
mit
5d5449c719fbc8f3a82570f9d708c43c
31.764706
66
0.599641
3.895105
false
false
false
false
hironytic/Moltonf-iOS
Moltonf/ViewModel/SelectPeriodViewModel.swift
1
4272
// // SelectPeriodViewModel.swift // Moltonf // // Copyright (c) 2016 Hironori Ichimiya <[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. // import Foundation import RxCocoa import RxSwift fileprivate typealias R = Resource public enum SelectPeriodViewModelResult { case selected(PeriodReference) case cancelled } public struct SelectPeriodViewModelItem { public let periodReference: PeriodReference public let title: String public let checked: Bool } public protocol ISelectPeriodViewModel: IViewModel { var periodsLine: Observable<[SelectPeriodViewModelItem]> { get } var cancelAction: AnyObserver<Void> { get } var selectAction: AnyObserver<SelectPeriodViewModelItem> { get } var onResult: ((SelectPeriodViewModelResult) -> Void)? { get set } } public class SelectPeriodViewModel: ViewModel, ISelectPeriodViewModel { public private(set) var periodsLine: Observable<[SelectPeriodViewModelItem]> public private(set) var cancelAction: AnyObserver<Void> public private(set) var selectAction: AnyObserver<SelectPeriodViewModelItem> public var onResult: ((SelectPeriodViewModelResult) -> Void)? = nil private let _disposeBag = DisposeBag() private let _storyWatching: IStoryWatching private let _cancelAction = ActionObserver<Void>() private let _selectAction = ActionObserver<SelectPeriodViewModelItem>() public init(storyWatching: IStoryWatching) { _storyWatching = storyWatching periodsLine = Observable .combineLatest(_storyWatching.availablePeriodRefsLine, _storyWatching.currentPeriodLine, resultSelector: { ($0, $1) }) .asDriver(onErrorDriveWith: Driver.empty()) .asObservable() .map { (periodList, currentPeriod) -> [SelectPeriodViewModelItem] in let currentDay = currentPeriod.day return periodList .map { periodRef in var title = "" switch periodRef.type { case .prologue: title = ResourceUtils.getString(R.String.periodPrologue) case .epilogue: title = ResourceUtils.getString(R.String.periodEpilogue) case .progress: title = ResourceUtils.getString(format: R.String.periodDayFormat, periodRef.day) } let checked = periodRef.day == currentDay return SelectPeriodViewModelItem(periodReference: periodRef, title: title, checked: checked) } } cancelAction = _cancelAction.asObserver() selectAction = _selectAction.asObserver() super.init() _cancelAction.handler = { [weak self] in self?.cancel() } _selectAction.handler = { [weak self] item in self?.select(item) } } private func cancel() { sendMessage(DismissingMessage()) onResult?(.cancelled) } private func select(_ item: SelectPeriodViewModelItem) { sendMessage(DismissingMessage()) onResult?(.selected(item.periodReference)) } }
mit
46420dae819bcc1bc5685e567a9eb567
39.685714
130
0.672285
5.235294
false
false
false
false
li978406987/DayDayZB
DayDayZB/Classes/Main/View/CollectionViewPrettyCell.swift
1
1569
// // CollectionViewPrettyCell.swift // DayDayZB // // Created by 洛洛大人 on 16/11/9. // Copyright © 2016年 洛洛大人. All rights reserved. // import UIKit class CollectionViewPrettyCell: UICollectionViewCell { // Mark : - 控件属性 @IBOutlet var iconImageView: UIImageView! @IBOutlet var onlineBtn: UIButton! @IBOutlet var nickNameLabel: UILabel! @IBOutlet var nickNameImageView: UIImageView! @IBOutlet var cityBtn: UIButton! // Mark : -定义模型属性 var anchor : AnchorModel? { didSet { // 0.校验模型是否有值 guard let anchor = anchor else { return } // 1.去除在线人数显示的文字 var onlineStr : String = "" if anchor.online >= 10000 { onlineStr = String(format: "%.1f万", (Double(anchor.online) / 10000.0)) } else { onlineStr = "\(anchor.online)" } onlineBtn.setTitle(onlineStr, for: .normal) // 2.昵称的显示 nickNameLabel.text = anchor.nickname // 3.所在城市 cityBtn.setTitle(anchor.anchor_city, for: .normal) // 4.设置封面 guard let iconURL = URL(string : anchor.vertical_src) else { return } iconImageView.kf.setImage(with: iconURL) } } }
mit
bbd824f88ab21f2b00909e29b278f73b
23
86
0.493852
4.847682
false
false
false
false
xedin/swift
test/SILGen/if_expr.swift
25
2271
// RUN: %target-swift-emit-silgen %s | %FileCheck %s func fizzbuzz(i: Int) -> String { return i % 3 == 0 ? "fizz" : i % 5 == 0 ? "buzz" : "\(i)" // CHECK: cond_br {{%.*}}, [[OUTER_TRUE:bb[0-9]+]], [[OUTER_FALSE:bb[0-9]+]] // CHECK: [[OUTER_TRUE]]: // CHECK: br [[OUTER_CONT:bb[0-9]+]] // CHECK: [[OUTER_FALSE]]: // CHECK: cond_br {{%.*}}, [[INNER_TRUE:bb[0-9]+]], [[INNER_FALSE:bb[0-9]+]] // CHECK: [[INNER_TRUE]]: // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_FALSE]]: // CHECK: function_ref {{.*}}stringInterpolation // CHECK: br [[INNER_CONT]] // CHECK: [[INNER_CONT]]({{.*}}): // CHECK: br [[OUTER_CONT]] // CHECK: [[OUTER_CONT]]({{.*}}): // CHECK: return } protocol AddressOnly {} struct A : AddressOnly {} struct B : AddressOnly {} func consumeAddressOnly(_: AddressOnly) {} // CHECK: sil hidden [ossa] @$s7if_expr19addr_only_ternary_1{{[_0-9a-zA-Z]*}}F func addr_only_ternary_1(x: Bool) -> AddressOnly { // CHECK: bb0([[RET:%.*]] : $*AddressOnly, {{.*}}): // CHECK: [[a:%[0-9]+]] = alloc_box ${ var AddressOnly }, var, name "a" // CHECK: [[PBa:%.*]] = project_box [[a]] var a : AddressOnly = A() // CHECK: [[b:%[0-9]+]] = alloc_box ${ var AddressOnly }, var, name "b" // CHECK: [[PBb:%.*]] = project_box [[b]] var b : AddressOnly = B() // CHECK: cond_br {{%.*}}, [[TRUE:bb[0-9]+]], [[FALSE:bb[0-9]+]] // CHECK: [[TRUE]]: // CHECK: [[READa:%.*]] = begin_access [read] [unknown] [[PBa]] // CHECK: copy_addr [[READa]] to [initialization] [[RET]] // CHECK: br [[CONT:bb[0-9]+]] // CHECK: [[FALSE]]: // CHECK: [[READb:%.*]] = begin_access [read] [unknown] [[PBb]] // CHECK: copy_addr [[READb]] to [initialization] [[RET]] // CHECK: br [[CONT]] return x ? a : b } // <rdar://problem/31595572> - crash when conditional expression is an // lvalue of IUO type // CHECK-LABEL: sil hidden [ossa] @$s7if_expr18iuo_lvalue_ternary1xSiSbSgz_tF : $@convention(thin) (@inout Optional<Bool>) -> Int // CHECK: [[IUO_BOOL_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*Optional<Bool> // CHECK: [[IUO_BOOL:%.*]] = load [trivial] [[IUO_BOOL_ADDR]] : $*Optional<Bool> // CHECK: switch_enum [[IUO_BOOL]] func iuo_lvalue_ternary(x: inout Bool!) -> Int { return x ? 1 : 0 }
apache-2.0
1e8bc5d83106205f782547b5c834e3c7
35.047619
129
0.550418
3.007947
false
false
false
false
zSOLz/viper-base
ViperBase-Sample/ViperBase-Sample/Modules/RegistrationEmail/View/RegistrationEmailViewController.swift
1
2140
// // RegistrationEmailViewController.swift // ViperBase-Sample // // Created by SOL on 08.05.17. // Copyright © 2017 SOL. All rights reserved. // import ViperBase final class RegistrationEmailViewController: PresentableViewController { @IBOutlet var emailTextField: UITextField! @IBOutlet var continueButton: UIButton! @IBOutlet var continueButtonBottomConstraint: NSLayoutConstraint! fileprivate let keyboardObserver = KeyboardHeightObserver() @IBAction func continueButtonTapped(_ sender: Any) { presenter?.continueButtonTapped() } @IBAction func emailTextChanged(_ sender: Any) { presenter?.emailChanged(email: emailTextField.text ?? "") } @objc func cancelButonTapped(_ sender: Any) { presenter?.cancelButonTapped() } } // MARK: - Fileprivate fileprivate extension RegistrationEmailViewController { final var presenter: RegistrationEmailPresenterInterface? { return presenterInterface as? RegistrationEmailPresenterInterface } } // MARK: - RegistrationEmailViewInterface extension RegistrationEmailViewController: RegistrationEmailViewInterface { func setup(email: String) { emailTextField.text = email } func setContinueButton(enabled isEnabled: Bool) { continueButton.isEnabled = isEnabled } } // MARK: - ContentContainerInterface extension RegistrationEmailViewController { override func setupContent() { super.setupContent() title = "Registration: Email" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(RegistrationEmailViewController.cancelButonTapped(_:))) keyboardObserver.heightChangedClosure = { [weak self] height in self?.continueButtonBottomConstraint.constant = height UIView.animate(withDuration: .standart) { [weak self] in self?.view.layoutIfNeeded() } } } }
mit
8aa8b324ec83cb895e563c78a16e4578
30.925373
133
0.661992
5.876374
false
false
false
false
february29/Learning
swift/Fch_Contact/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift
16
8612
// // URLSession+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 3/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import struct Foundation.URL import struct Foundation.URLRequest import struct Foundation.Data import struct Foundation.Date import struct Foundation.TimeInterval import class Foundation.HTTPURLResponse import class Foundation.URLSession import class Foundation.URLResponse import class Foundation.JSONSerialization import class Foundation.NSError import var Foundation.NSURLErrorCancelled import var Foundation.NSURLErrorDomain #if os(Linux) // don't know why import Foundation #endif #if !RX_NO_MODULE import RxSwift #endif /// RxCocoa URL errors. public enum RxCocoaURLError : Swift.Error { /// Unknown error occurred. case unknown /// Response is not NSHTTPURLResponse case nonHTTPResponse(response: URLResponse) /// Response is not successful. (not in `200 ..< 300` range) case httpRequestFailed(response: HTTPURLResponse, data: Data?) /// Deserialization error. case deserializationError(error: Swift.Error) } extension RxCocoaURLError : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { switch self { case .unknown: return "Unknown error has occurred." case let .nonHTTPResponse(response): return "Response is not NSHTTPURLResponse `\(response)`." case let .httpRequestFailed(response, _): return "HTTP request failed with `\(response.statusCode)`." case let .deserializationError(error): return "Error during deserialization of the response: \(error)" } } } fileprivate func escapeTerminalString(_ value: String) -> String { return value.replacingOccurrences(of: "\"", with: "\\\"", options:[], range: nil) } fileprivate func convertURLRequestToCurlCommand(_ request: URLRequest) -> String { let method = request.httpMethod ?? "GET" var returnValue = "curl -X \(method) " if let httpBody = request.httpBody, request.httpMethod == "POST" { let maybeBody = String(data: httpBody, encoding: String.Encoding.utf8) if let body = maybeBody { returnValue += "-d \"\(escapeTerminalString(body))\" " } } for (key, value) in request.allHTTPHeaderFields ?? [:] { let escapedKey = escapeTerminalString(key as String) let escapedValue = escapeTerminalString(value as String) returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" " } let URLString = request.url?.absoluteString ?? "<unknown url>" returnValue += "\n\"\(escapeTerminalString(URLString))\"" returnValue += " -i -v" return returnValue } fileprivate func convertResponseToString(_ response: URLResponse?, _ error: NSError?, _ interval: TimeInterval) -> String { let ms = Int(interval * 1000) if let response = response as? HTTPURLResponse { if 200 ..< 300 ~= response.statusCode { return "Success (\(ms)ms): Status \(response.statusCode)" } else { return "Failure (\(ms)ms): Status \(response.statusCode)" } } if let error = error { if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { return "Canceled (\(ms)ms)" } return "Failure (\(ms)ms): NSError > \(error)" } return "<Unhandled response from server>" } extension Reactive where Base: URLSession { /** Observable sequence of responses for URL request. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. - parameter request: URL request. - returns: Observable sequence of URL responses. */ public func response(request: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> { return Observable.create { observer in // smart compiler should be able to optimize this out let d: Date? if Logging.URLRequests(request) { d = Date() } else { d = nil } let task = self.base.dataTask(with: request) { (data, response, error) in if Logging.URLRequests(request) { let interval = Date().timeIntervalSince(d ?? Date()) print(convertURLRequestToCurlCommand(request)) #if os(Linux) print(convertResponseToString(response, error.flatMap { $0 as? NSError }, interval)) #else print(convertResponseToString(response, error.map { $0 as NSError }, interval)) #endif } guard let response = response, let data = data else { observer.on(.error(error ?? RxCocoaURLError.unknown)) return } guard let httpResponse = response as? HTTPURLResponse else { observer.on(.error(RxCocoaURLError.nonHTTPResponse(response: response))) return } observer.on(.next((httpResponse, data))) observer.on(.completed) } task.resume() return Disposables.create(with: task.cancel) } } /** Observable sequence of response data for URL request. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. If response is not HTTP response with status code in the range of `200 ..< 300`, sequence will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. - parameter request: URL request. - returns: Observable sequence of response data. */ public func data(request: URLRequest) -> Observable<Data> { return response(request: request).map { pair -> Data in if 200 ..< 300 ~= pair.0.statusCode { return pair.1 } else { throw RxCocoaURLError.httpRequestFailed(response: pair.0, data: pair.1) } } } /** Observable sequence of response JSON for URL request. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. If response is not HTTP response with status code in the range of `200 ..< 300`, sequence will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. If there is an error during JSON deserialization observable sequence will fail with that error. - parameter request: URL request. - returns: Observable sequence of response JSON. */ public func json(request: URLRequest, options: JSONSerialization.ReadingOptions = []) -> Observable<Any> { return data(request: request).map { (data) -> Any in do { return try JSONSerialization.jsonObject(with: data, options: options) } catch let error { throw RxCocoaURLError.deserializationError(error: error) } } } /** Observable sequence of response JSON for GET request with `URL`. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. If response is not HTTP response with status code in the range of `200 ..< 300`, sequence will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. If there is an error during JSON deserialization observable sequence will fail with that error. - parameter url: URL of `NSURLRequest` request. - returns: Observable sequence of response JSON. */ public func json(url: Foundation.URL) -> Observable<Any> { return json(request: URLRequest(url: url)) } }
mit
52a012762d2bf672c694da8a8d582d5b
34.146939
123
0.639066
5.257021
false
false
false
false
RevenueCat/purchases-ios
Tests/UnitTests/Networking/DNSCheckerTests.swift
1
5493
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // DNSCheckerTests.swift // // Created by Joshua Liebowitz on 12/21/21. import Foundation import Nimble import XCTest @testable import RevenueCat class DNSCheckerTests: TestCase { private let apiURL = URL(string: "https://api.revenuecat.com")! private let fakeSubscribersURL1 = URL(string: "https://0.0.0.0/subscribers")! private let fakeSubscribersURL2 = URL(string: "https://127.0.0.1/subscribers")! private let fakeOffersURL = URL(string: "https://0.0.0.0/offers")! func testResolvedHost() throws { guard let host = DNSChecker.resolvedHost(fromURL: apiURL) else { throw XCTSkip("The host couldn't be resolved. Note that this test requires a working internet connection") } // swiftlint:disable:next line_length let validIPAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" expect(host.range(of: validIPAddressRegex, options: .regularExpression)).toNot(beNil()) expect(DNSChecker.invalidHosts.contains(host)).to(equal(false)) } func testIsBlockedURL() throws { let blockedURLs = ["https://127.0.0.1/subscribers", "https://0.0.0.0/offers"] for urlString in blockedURLs { expect(DNSChecker.isBlockedURL(try XCTUnwrap(URL(string: urlString)))) == true } expect(DNSChecker.isBlockedURL(try XCTUnwrap(URL(string: "https://api.revenuecat.com/offers")))) == false } func testIsBlockedLocalHostFromError() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) let error = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo as Error) let expectedError: NetworkError = .dnsError(failedURL: fakeSubscribersURL2, resolvedHost: "127.0.0.1") expect(error) == expectedError } func testIsBlockedHostIPAPIError() { let userInfo: [String: Any] = [ NSURLErrorFailingURLErrorKey: fakeSubscribersURL1 ] let nsErrorWithUserInfo = NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) expect(DNSChecker.isBlockedAPIError(nsErrorWithUserInfo as Error)) == true let blockedHostError = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo) expect(blockedHostError) == NetworkError.dnsError(failedURL: fakeSubscribersURL1, resolvedHost: "0.0.0.0") } func testWrongErrorCode() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: NSURLErrorDomain, code: -1, userInfo: userInfo as [String: Any]) expect(DNSChecker.isBlockedAPIError(nsErrorWithUserInfo as Error)) == false } func testWrongErrorDomain() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: "FakeDomain", code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) expect(DNSChecker.isBlockedAPIError(nsErrorWithUserInfo as Error)) == false let blockedError = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo) expect(blockedError) == nil } func testWrongErrorDomainAndWrongErrorCode() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: "FakeDomain", code: -1, userInfo: userInfo as [String: Any]) let blockedError = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo) expect(blockedError) == nil } func testIsOnlyValidForCorrectErrorDomainAnd() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: "FakeDomain", code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) let blockedError = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo) expect(blockedError) == nil } func testIsBlockedZerosIPHostAPIError() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL1] let nsErrorWithUserInfo = NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) expect(DNSChecker.isBlockedAPIError(nsErrorWithUserInfo as Error)) == true } }
mit
fc7b57d62c75cc5cfbb5ba0cbb8044b1
45.948718
142
0.627162
5.109767
false
true
false
false
podverse/podverse-ios
Podverse/MakeClipTimeViewController.swift
1
26462
// // MakeClipTimeViewController.swift // Podverse // // Created by Mitchell Downey on 8/26/17. // Copyright © 2017 Podverse LLC. All rights reserved. // import StreamingKit import UIKit class MakeClipTimeViewController: UIViewController, UITextFieldDelegate { let audioPlayer = PVMediaPlayer.shared.audioPlayer var endTime: Int? var endTimePreview: Int? var playerHistoryItem: PlayerHistoryItem? let pvMediaPlayer = PVMediaPlayer.shared var startTime: Int? var timer: Timer? var isPublic = false var editingItem: PlayerHistoryItem? let hasSeenHint = UserDefaults.standard.bool(forKey: "HAS_SEEN_CLIP_HINT") var shouldAnimate = true @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var currentTime: UILabel! @IBOutlet weak var duration: UILabel! @IBOutlet weak var endPreview: UIButton! @IBOutlet weak var playbackControlView: UIView! @IBOutlet weak var progress: UISlider! @IBOutlet weak var startPreview: UIButton! @IBOutlet weak var play: UIImageView! @IBOutlet weak var visibilityButton: UIButton! @IBOutlet weak var clearEndTimeButton: UIButton! @IBOutlet weak var titleInput: UITextField! @IBOutlet weak var startTimeLabel: UILabel! @IBOutlet weak var endTimeLabel: UILabel! @IBOutlet weak var startTimeInputView: UIView! @IBOutlet weak var endTimeInputView: UIView! @IBOutlet weak var loadingOverlay: UIView! @IBOutlet weak var loadingActivityInidicator: UIActivityIndicatorView! @IBOutlet weak var podcastImage: UIImageView! @IBOutlet weak var speed: UIButton! @IBOutlet weak var hintView: UIView! @IBOutlet weak var hintViewImage: UIImageView! @IBOutlet weak var startTimeFlagView: UIView! @IBOutlet weak var endTimeFlagView: UIView! @IBOutlet weak var startTimeLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var endTimeLeadingConstraint: NSLayoutConstraint! func loadMakeClipInputs() { self.startTimeLabel.text = PVTimeHelper.convertIntToHMSString(time: self.startTime) self.clearEndTimeButton.isHidden = true self.endTimeLabel.text = "optional" self.endTimeLabel.textColor = UIColor.lightGray self.titleInput.leftView = UIView(frame: CGRect(x:0, y:0, width:10, height:35)) self.titleInput.leftViewMode = UITextFieldViewMode.always self.titleInput.returnKeyType = .done } func loadEditClipInputs() { if let editingItem = self.editingItem { if let startTime = editingItem.startTime, let startTimeInt = Int(exactly: Float(startTime)) { self.startTimeLabel.text = PVTimeHelper.convertIntToHMSString(time: startTimeInt) self.startTime = startTimeInt } if let endTime = editingItem.endTime, let endTimeInt = Int(exactly: Float(endTime)) { self.clearEndTimeButton.isHidden = false self.endTimeLabel.text = PVTimeHelper.convertIntToHMSString(time: endTimeInt) self.endTimeLabel.textColor = UIColor.black self.endTime = endTimeInt } else { self.clearEndTimeButton.isHidden = true self.endTimeLabel.text = "optional" self.endTimeLabel.textColor = UIColor.lightGray } self.titleInput.leftView = UIView(frame: CGRect(x:0, y:0, width:10, height:35)) self.titleInput.leftViewMode = UITextFieldViewMode.always self.titleInput.returnKeyType = .done if let title = editingItem.clipTitle { self.titleInput.text = title } if let isPublic = editingItem.isPublic { self.isPublic = isPublic let visibilityText = self.isPublic ? VisibilityOptions.isPublic.text : VisibilityOptions.isOnlyWithLink.text self.visibilityButton.setTitle(visibilityText + " ▼", for: .normal) } } } override func viewDidLoad() { super.viewDidLoad() setupTimer() populatePlayerInfo() self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"Back", style:.plain, target:nil, action:nil) self.activityIndicator.startAnimating() self.progress.setThumbImage(#imageLiteral(resourceName: "SliderCurrentPosition"), for: .normal) self.podcastImage.image = Podcast.retrievePodcastImage(fullSized: true, podcastImageURLString: self.pvMediaPlayer.nowPlayingItem?.podcastImageUrl, feedURLString: nil, completion: { (image) in self.podcastImage.image = image }) self.loadingOverlay.isHidden = true self.loadingActivityInidicator.hidesWhenStopped = true if let savedVisibilityType = UserDefaults.standard.value(forKey: kMakeClipVisibilityType) as? String, let visibilityType = VisibilityOptions(rawValue: savedVisibilityType) { self.visibilityButton.setTitle(visibilityType.text + " ▼", for: .normal) self.isPublic = visibilityType == VisibilityOptions.isPublic ? true : false } else { self.visibilityButton.setTitle(VisibilityOptions.isPublic.text + " ▼", for: .normal) self.isPublic = true } updateSpeedLabel() if self.editingItem == nil { self.title = "Make Clip" loadMakeClipInputs() } else { self.title = "Edit Clip" loadEditClipInputs() } setupClipFlags() let dataAssetImages = (1...20).map { NSDataAsset(name: "animation-\($0)")! } var loadingImages = [UIImage]() for asset in dataAssetImages { if let image = UIImage(data: asset.data) { loadingImages.append(image) } } hintViewImage.animationImages = loadingImages if (hasSeenHint) { self.hintView.removeFromSuperview() setupBarButtonItems() } else { hintViewImage.animationDuration = 1.5 hintViewImage.animationRepeatCount = 500 hintViewImage.startAnimating() } } func setupBarButtonItems() { let saveBtn = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(save)) let deleteBtn = UIBarButtonItem(title: "Delete", style: .plain, target: self, action: #selector(deleteClip)) if self.editingItem == nil { self.navigationItem.rightBarButtonItems = [saveBtn] } else { // Make a copy in case the current PlayerHistoryItem reference disappears while on the edit view self.editingItem = self.editingItem?.copyPlayerHistoryItem() self.navigationItem.rightBarButtonItems = [saveBtn, deleteBtn] } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch:UITouch = touches.first! if touch.view == self.hintView || touch.view == self.hintViewImage { self.shouldAnimate = false self.hintView.removeFromSuperview() setupBarButtonItems() UserDefaults.standard.set(true, forKey: "HAS_SEEN_CLIP_HINT") } } override func viewWillAppear(_ animated: Bool) { navigationController?.interactivePopGestureRecognizer?.isEnabled = false self.pvMediaPlayer.delegate = self togglePlayIcon() updateTime() } override func viewWillDisappear(_ animated: Bool) { navigationController?.interactivePopGestureRecognizer?.isEnabled = true } deinit { removeTimer() } @IBAction func sliderAction(_ sender: Any, forEvent event: UIEvent) { if let sender = sender as? UISlider, let touchEvent = event.allTouches?.first { switch touchEvent.phase { case .began: removeTimer() case .ended: if let duration = pvMediaPlayer.duration { let newTime = Double(sender.value) * duration self.pvMediaPlayer.seek(toTime: newTime) updateTime() } setupTimer() default: break } } } @IBAction func startTimePreview(_ sender: Any) { if let startTime = self.startTime { self.pvMediaPlayer.seek(toTime: Double(startTime)) self.pvMediaPlayer.play() } if let endTime = self.endTime { self.pvMediaPlayer.shouldStopAtEndTime = Int64(endTime) } } @IBAction func endTimePreview(_ sender: Any) { if let endTime = self.endTime { self.endTimePreview = endTime self.pvMediaPlayer.seek(toTime: (endTime < 3) ? 0 : Double(endTime) - 3) self.pvMediaPlayer.play() } } @IBAction func timeJumpBackward(_ sender: Any) { let newTime = self.pvMediaPlayer.progress - 15 if newTime >= 14 { self.pvMediaPlayer.seek(toTime: newTime) } else { self.pvMediaPlayer.seek(toTime: 0) } updateTime() } @IBAction func timeJumpForward(_ sender: Any) { let newTime = self.pvMediaPlayer.progress + 15 self.pvMediaPlayer.seek(toTime: newTime) updateTime() } @IBAction func setStartTime(_ sender: Any) { let currentTime = Int(self.pvMediaPlayer.progress) self.startTime = Int(currentTime) self.startTimeLabel.text = PVTimeHelper.convertIntToHMSString(time: currentTime) setupClipFlags() } @IBAction func setEndTime(_ sender: Any) { let currentTime = Int(self.pvMediaPlayer.progress) self.endTime = Int(currentTime) self.endTimeLabel.text = PVTimeHelper.convertIntToHMSString(time: currentTime) self.endTimeLabel.textColor = UIColor.black self.clearEndTimeButton.isHidden = false setupClipFlags() } @IBAction func clearEndTime(_ sender: Any) { self.endTime = nil self.endTimeLabel.text = "optional" self.endTimeLabel.textColor = UIColor.lightGray self.clearEndTimeButton.isHidden = true setupClipFlags() } @IBAction func showVisibilityMenu(_ sender: Any) { let visibilityActions = UIAlertController(title: "Clip Visibility", message: nil, preferredStyle: .actionSheet) visibilityActions.addAction(UIAlertAction(title: VisibilityOptions.isPublic.text, style: .default, handler: { action in self.isPublic = true UserDefaults.standard.set(VisibilityOptions.isPublic.text, forKey: kMakeClipVisibilityType) self.visibilityButton.setTitle(VisibilityOptions.isPublic.text + " ▼", for: .normal) } )) visibilityActions.addAction(UIAlertAction(title: VisibilityOptions.isOnlyWithLink.text, style: .default, handler: { action in self.isPublic = false UserDefaults.standard.set(VisibilityOptions.isOnlyWithLink.text, forKey: kMakeClipVisibilityType) self.visibilityButton.setTitle(VisibilityOptions.isOnlyWithLink.text + " ▼", for: .normal) } )) visibilityActions.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(visibilityActions, animated: true, completion: nil) } func validateInputs() -> Bool { guard let startTime = self.startTime else { let alertController = UIAlertController(title: "Invalid Clip Time", message: "Start time must be provided.", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) return false } if let endTime = self.endTime { var alertMessage = "Start time is later than end time." if startTime == endTime { alertMessage = "Start time is equal to end time." } if startTime == endTime || startTime >= endTime { let alertController = UIAlertController(title: "Invalid Clip Time", message: alertMessage, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) return false } } return true } @objc fileprivate func setupClipFlags() { self.startTimeLeadingConstraint.constant = 0 self.endTimeLeadingConstraint.constant = 0 let sliderThumbWidthAdjustment:CGFloat = 2.0 if let startTime = self.startTime, let dur = self.pvMediaPlayer.duration, dur > 0 { self.startTimeFlagView.isHidden = false self.endTimeFlagView.isHidden = self.endTime == nil // Use UIScreen.main.bounds.width because self.progress.frame.width was giving inconsistent sizes. self.startTimeLeadingConstraint.constant = (CGFloat(Double(startTime) / dur) * UIScreen.main.bounds.width) - sliderThumbWidthAdjustment if let endTime = self.endTime { self.endTimeLeadingConstraint.constant = (CGFloat(Double(endTime) / dur) * UIScreen.main.bounds.width) - sliderThumbWidthAdjustment } } } @objc func save() { self.view.endEditing(true) guard validateInputs() else { return } var mediaRefItem:PlayerHistoryItem? = nil if let editingItem = self.editingItem { mediaRefItem = editingItem } else if let nowPlayingItem = self.playerHistoryItem?.copyPlayerHistoryItem() { mediaRefItem = nowPlayingItem } if let item = mediaRefItem { showLoadingOverlay() if let startTime = self.startTime { item.startTime = Int64(startTime) } if let endTime = self.endTime { item.endTime = Int64(endTime) } if let title = self.titleInput.text { item.clipTitle = title } item.isPublic = self.isPublic if editingItem == nil { item.saveToServerAsMediaRef() { mediaRef in self.hideLoadingOverlay() if let id = mediaRef?.id { self.displayClipCreatedAlert(mediaRefId: id) } else { self.displayFailedToCreateClipAlert() } } } else { item.updateMediaRefOnServer() { wasSuccessful in self.hideLoadingOverlay() if wasSuccessful { self.displayClipUpdatedAlert(item: item) } else { self.displayFailedToUpdateClipAlert() } } } } } @objc func deleteClip() { self.view.endEditing(true) if let item = self.editingItem, let id = item.mediaRefId { showLoadingOverlay() MediaRef.deleteMediaRefFromServer(id: id) { wasSuccessful in self.hideLoadingOverlay() DispatchQueue.main.async { if (wasSuccessful) { let actions = UIAlertController(title: "Delete successful", message: "The clip was successfully deleted.", preferredStyle: .alert) actions.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: { action in self.navigationController?.popViewController(animated: true) })) self.present(actions, animated: true, completion: nil) } else { let actions = UIAlertController(title: "Failed to delete clip", message: "Please check your internet connection and try again.", preferredStyle: .alert) actions.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(actions, animated: true, completion: nil) } } } } } @IBAction func changeSpeed(_ sender: Any) { switch self.pvMediaPlayer.playerSpeedRate { case .regular: self.pvMediaPlayer.playerSpeedRate = .timeAndQuarter break case .timeAndQuarter: self.pvMediaPlayer.playerSpeedRate = .timeAndHalf break case .timeAndHalf: self.pvMediaPlayer.playerSpeedRate = .double break case .double: self.pvMediaPlayer.playerSpeedRate = .half case .half: self.pvMediaPlayer.playerSpeedRate = .threeQuarts break case .threeQuarts: self.pvMediaPlayer.playerSpeedRate = .regular break } updateSpeedLabel() } private func showLoadingOverlay() { self.loadingOverlay.isHidden = false self.loadingActivityInidicator.startAnimating() } private func hideLoadingOverlay() { DispatchQueue.main.async { self.loadingOverlay.isHidden = true self.loadingActivityInidicator.stopAnimating() } } private func displayClipCreatedAlert(mediaRefId: String) { DispatchQueue.main.async { let actions = UIAlertController(title: "Clip Created", message: BASE_URL + "clips/" + mediaRefId, preferredStyle: .alert) actions.addAction(UIAlertAction(title: "Share", style: .default, handler: { action in let clipUrlItem = [BASE_URL + "clips/" + mediaRefId] let activityVC = UIActivityViewController(activityItems: clipUrlItem, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = self.view activityVC.completionWithItemsHandler = { activityType, success, items, error in if activityType == UIActivityType.copyToPasteboard { self.showToast(message: kClipLinkCopiedToast) } self.navigationController?.popViewController(animated: true) } self.present(activityVC, animated: true, completion: nil) })) actions.addAction(UIAlertAction(title: "Done", style: .cancel, handler: { action in self.navigationController?.popViewController(animated: true) })) self.present(actions, animated: true, completion: nil) } } private func displayFailedToCreateClipAlert() { DispatchQueue.main.async { let actions = UIAlertController(title: "Failed to create clip", message: "Please check your internet connection and try again.", preferredStyle: .alert) actions.addAction(UIAlertAction(title: "Ok", style: .cancel)) self.present(actions, animated: true, completion: nil) } } private func displayClipUpdatedAlert(item: PlayerHistoryItem) { DispatchQueue.main.async { let actions = UIAlertController(title: "Clip successfully updated", message: nil, preferredStyle: .alert) actions.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in self.navigationController?.popViewController(animated: true) })) self.present(actions, animated: true, completion: nil) } } private func displayFailedToUpdateClipAlert() { DispatchQueue.main.async { let actions = UIAlertController(title: "Failed to update clip", message: "Please check your internet connection and try again.", preferredStyle: .alert) actions.addAction(UIAlertAction(title: "Ok", style: .cancel)) self.present(actions, animated: true, completion: nil) } } private func setupTimer() { self.timer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true) } private func removeTimer() { if let timer = self.timer { timer.invalidate() } } private func populatePlayerInfo() { if let dur = pvMediaPlayer.duration { duration.text = Int64(dur).toMediaPlayerString() } } func togglePlayIcon() { // Grab audioPlayer each time to ensure we are checking the correct state let audioPlayer = PVMediaPlayer.shared.audioPlayer if audioPlayer.state == .stopped || audioPlayer.state == .paused { self.activityIndicator.isHidden = true self.play.image = UIImage(named:"play") self.play.tintColor = UIColor.black self.play.isHidden = false } else if audioPlayer.state == .error { self.activityIndicator.isHidden = true self.play.image = UIImage(named:"playerror")?.withRenderingMode(.alwaysTemplate) self.play.tintColor = UIColor.red self.play.isHidden = false } else if audioPlayer.state == .playing && !self.pvMediaPlayer.shouldSetupClip { self.activityIndicator.isHidden = true self.play.image = UIImage(named:"pause") self.play.tintColor = UIColor.black self.play.isHidden = false } else if audioPlayer.state == .buffering || self.pvMediaPlayer.shouldSetupClip { self.activityIndicator.isHidden = false self.play.isHidden = true } else { self.activityIndicator.isHidden = true self.play.image = UIImage(named:"play") self.play.tintColor = UIColor.black self.play.isHidden = false } } @objc func updateTime () { var playbackPosition = Double(0) if self.pvMediaPlayer.progress > 0 { playbackPosition = self.pvMediaPlayer.progress } else if let dur = self.pvMediaPlayer.duration { playbackPosition = Double(self.progress.value) * dur } self.currentTime.text = Int64(playbackPosition).toMediaPlayerString() if let dur = self.pvMediaPlayer.duration { self.duration.text = Int64(dur).toMediaPlayerString() self.progress.value = Float(playbackPosition / dur) } if let endTimePreview = self.endTimePreview { if Int(self.pvMediaPlayer.progress) >= endTimePreview { self.pvMediaPlayer.pause() self.endTimePreview = nil } } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @IBAction func sliderTapped(_ sender: Any) { pvMediaPlayer.playOrPause() } @IBAction func slidingRecognized(_ sender: Any) { if let pan = sender as? UIPanGestureRecognizer, let duration = pvMediaPlayer.duration { if !pvMediaPlayer.playerIsLoaded() { let panPoint = pan.velocity(in: self.playbackControlView) let newTime = ((Double(self.progress.value) * duration) + Double(panPoint.x / 180.0)) self.progress.value = Float(newTime / duration) self.pvMediaPlayer.seek(toTime: newTime) updateTime() } else { let panPoint = pan.velocity(in: self.playbackControlView) var newTime = (self.pvMediaPlayer.progress + Double(panPoint.x / 180.0)) if newTime <= 0 { newTime = 0 } else if newTime >= duration { newTime = duration - 1 self.audioPlayer.pause() } self.pvMediaPlayer.seek(toTime: newTime) updateTime() } } } func updateSpeedLabel() { DispatchQueue.main.async { self.speed.setImage(self.pvMediaPlayer.playerSpeedRate.speedImage, for: .normal) } } } extension MakeClipTimeViewController:PVMediaPlayerUIDelegate { func playerHistoryItemBuffering() { self.togglePlayIcon() } func playerHistoryItemErrored() { self.togglePlayIcon() } func playerHistoryItemLoaded() { DispatchQueue.main.async { self.setupClipFlags() self.updateTime() self.togglePlayIcon() } } func playerHistoryItemLoadingBegan() { DispatchQueue.main.async { self.togglePlayIcon() } } func playerHistoryItemPaused() { self.togglePlayIcon() } }
agpl-3.0
db7d693c9d0be5669babeb4b0f7c04dd
37.898529
199
0.5796
5.475264
false
false
false
false
utahiosmac/jobs
Sources/MutuallyExclusive.swift
2
1706
// // MutuallyExclusive.swift // Jobs // import Foundation public struct MutuallyExclusive<T>: Condition { public init() { } public func evaluate(ticket: Ticket, completion: @escaping (NSError?) -> Void) { let exclusivityClass = "\(type(of: self))" MutualExclusivityController.shared.add(ticket: ticket, for: exclusivityClass, completion: { completion(nil) }) } } private class MutualExclusivityController { static let shared = MutualExclusivityController() private let lock = NSLock() private var tickets = Dictionary<String, [Ticket]>() func add(ticket: Ticket, for exclusivityClass: String, completion: @escaping () -> Void) { var mutableTicket = ticket var previousTicket: Ticket? lock.withCriticalScope { var ticketsForThisClass = tickets[exclusivityClass] ?? [] previousTicket = ticketsForThisClass.last ticketsForThisClass.append(ticket) tickets[exclusivityClass] = ticketsForThisClass } mutableTicket.onFinish { _ in // clean up self.cleanUp(ticket: ticket, for: exclusivityClass) } if var previous = previousTicket { previous.onFinish { _ in completion() } } else { completion() } } private func cleanUp(ticket: Ticket, for exclusivityClass: String) { lock.withCriticalScope { if let ticketsForThisClass = tickets[exclusivityClass] { let filtered = ticketsForThisClass.filter { $0 != ticket } tickets[exclusivityClass] = filtered } } } }
mit
3f9ae5a5142f9ce5714e7f4813fa328a
28.929825
118
0.606096
5.169697
false
false
false
false
Piwigo/Piwigo-Mobile
piwigoKit/Network/pwg/pwg.getInfos.swift
1
4296
// // pwg.getInfos.swift // piwigoKit // // Created by Eddy Lelièvre-Berna on 23/08/2021. // Copyright © 2021 Piwigo.org. All rights reserved. // import Foundation // MARK: - pwg.getInfos public let kPiwigoGetInfos = "format=json&method=pwg.getInfos" public struct GetInfosJSON: Decodable { public var status: String? public var data = [InfoKeyValue]() public var errorCode = 0 public var errorMessage = "" private enum RootCodingKeys: String, CodingKey { case status = "stat" case data = "result" case errorCode = "err" case errorMessage = "message" } private enum ResultCodingKeys: String, CodingKey { case infos } private enum ErrorCodingKeys: String, CodingKey { case code = "code" case message = "msg" } public init(from decoder: Decoder) throws { // Root container keyed by RootCodingKeys let rootContainer = try decoder.container(keyedBy: RootCodingKeys.self) // Status returned by Piwigo status = try rootContainer.decodeIfPresent(String.self, forKey: .status) if (status == "ok") { // Result container keyed by ResultCodingKeys let resultContainer = try rootContainer.nestedContainer(keyedBy: ResultCodingKeys.self, forKey: .data) // dump(resultContainer) // Decodes infos from the data and store them in the array do { // Use TagProperties struct try data = resultContainer.decode([InfoKeyValue].self, forKey: .infos) } catch { // Could not decode JSON data } } else if (status == "fail") { // Retrieve Piwigo server error do { // Retrieve Piwigo server error errorCode = try rootContainer.decode(Int.self, forKey: .errorCode) errorMessage = try rootContainer.decode(String.self, forKey: .errorMessage) } catch { // Error container keyed by ErrorCodingKeys ("format=json" forgotten in call) let errorContainer = try rootContainer.nestedContainer(keyedBy: ErrorCodingKeys.self, forKey: .errorCode) errorCode = Int(try errorContainer.decode(String.self, forKey: .code)) ?? NSNotFound errorMessage = try errorContainer.decode(String.self, forKey: .message) } } else { // Unexpected Piwigo server error errorCode = -1 errorMessage = NSLocalizedString("serverUnknownError_message", comment: "Unexpected error encountered while calling server method with provided parameters.") } } } /** A struct for decoding JSON returned by kPiwigoGetinfos. All members are optional in case they are missing from the data. */ public struct InfoKeyValue: Decodable { public let name: String? // "version" public let value: StringOrInt? // "11.5.0" } public enum StringOrInt: Codable { case integer(Int) case string(String) public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let x = try? container.decode(Int.self) { self = .integer(x) return } if let x = try? container.decode(String.self) { self = .string(x) return } throw DecodingError.typeMismatch(StringOrInt.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Value")) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .integer(let x): try container.encode(x) case .string(let x): try container.encode(x) } } public var stringValue: String { switch self { case .integer(let x): return String(x) case .string(let x): return x } } public var intValue: Int { switch self { case .integer(let x): return x case .string(let x): return Int(x) ?? NSNotFound } } }
mit
b1e39e2db295ceb0de8364cc912be976
30.573529
169
0.592687
4.744751
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/NSCFSet.swift
1
5573
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // @_implementationOnly import CoreFoundation internal final class _NSCFSet : NSMutableSet { deinit { _CFDeinit(self) _CFZeroUnsafeIvars(&_storage) } required init() { fatalError() } required init?(coder aDecoder: NSCoder) { fatalError() } required init(capacity numItems: Int) { fatalError() } override var classForCoder: AnyClass { return NSMutableSet.self } override var count: Int { return CFSetGetCount(_cfObject) } override func member(_ object: Any) -> Any? { guard let value = CFSetGetValue(_cfObject, unsafeBitCast(__SwiftValue.store(object), to: UnsafeRawPointer.self)) else { return nil } return __SwiftValue.fetch(nonOptional: unsafeBitCast(value, to: AnyObject.self)) } override func objectEnumerator() -> NSEnumerator { var objArray: [AnyObject] = [] let cf = _cfObject let count = CFSetGetCount(cf) let objects = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: count) CFSetGetValues(cf, objects) for idx in 0..<count { let obj = unsafeBitCast(objects.advanced(by: idx).pointee!, to: AnyObject.self) objArray.append(obj) } objects.deinitialize(count: 1) objects.deallocate() return NSGeneratorEnumerator(objArray.makeIterator()) } override func add(_ object: Any) { CFSetAddValue(_cfMutableObject, unsafeBitCast(__SwiftValue.store(object), to: UnsafeRawPointer.self)) } override func remove(_ object: Any) { CFSetRemoveValue(_cfMutableObject, unsafeBitCast(__SwiftValue.store(object), to: UnsafeRawPointer.self)) } } internal func _CFSwiftSetGetCount(_ set: AnyObject) -> CFIndex { return (set as! NSSet).count } internal func _CFSwiftSetGetCountOfValue(_ set: AnyObject, value: AnyObject) -> CFIndex { if _CFSwiftSetContainsValue(set, value: value) { return 1 } else { return 0 } } internal func _CFSwiftSetContainsValue(_ set: AnyObject, value: AnyObject) -> Bool { return _CFSwiftSetGetValue(set, value: value, key: value) != nil } internal func _CFSwiftSetGetValues(_ set: AnyObject, _ values: UnsafeMutablePointer<Unmanaged<AnyObject>?>?) { var idx = 0 if values == nil { return } let set = set as! NSSet if type(of: set) === NSSet.self || type(of: set) === NSMutableSet.self { for obj in set._storage { values?[idx] = Unmanaged<AnyObject>.passUnretained(obj) idx += 1 } } else { set.enumerateObjects( { v, _ in let value = __SwiftValue.store(v) values?[idx] = Unmanaged<AnyObject>.passUnretained(value) set._storage.update(with: value) idx += 1 }) } } internal func _CFSwiftSetGetValue(_ set: AnyObject, value: AnyObject, key: AnyObject) -> Unmanaged<AnyObject>? { let set = set as! NSSet if type(of: set) === NSSet.self || type(of: set) === NSMutableSet.self { if let idx = set._storage.firstIndex(of: value as! NSObject){ return Unmanaged<AnyObject>.passUnretained(set._storage[idx]) } } else { let v = __SwiftValue.store(set.member(value)) if let obj = v { set._storage.update(with: obj) return Unmanaged<AnyObject>.passUnretained(obj) } } return nil } internal func _CFSwiftSetGetValueIfPresent(_ set: AnyObject, object: AnyObject, value: UnsafeMutablePointer<Unmanaged<AnyObject>?>?) -> Bool { if let val = _CFSwiftSetGetValue(set, value: object, key: object) { value?.pointee = val return true } else { value?.pointee = nil return false } } internal func _CFSwiftSetApplyFunction(_ set: AnyObject, applier: @convention(c) (AnyObject, UnsafeMutableRawPointer) -> Void, context: UnsafeMutableRawPointer) { (set as! NSSet).enumerateObjects({ value, _ in applier(__SwiftValue.store(value), context) }) } internal func _CFSwiftSetMember(_ set: CFTypeRef, _ object: CFTypeRef) -> Unmanaged<CFTypeRef>? { return _CFSwiftSetGetValue(set, value: object, key: object) } internal func _CFSwiftSetAddValue(_ set: AnyObject, value: AnyObject) { (set as! NSMutableSet).add(value) } internal func _CFSwiftSetReplaceValue(_ set: AnyObject, value: AnyObject) { let set = set as! NSMutableSet if (set.contains(value)){ set.remove(value) set.add(value) } } internal func _CFSwiftSetSetValue(_ set: AnyObject, value: AnyObject) { let set = set as! NSMutableSet set.remove(value) set.add(value) } internal func _CFSwiftSetRemoveValue(_ set: AnyObject, value: AnyObject) { (set as! NSMutableSet).remove(value) } internal func _CFSwiftSetRemoveAllValues(_ set: AnyObject) { (set as! NSMutableSet).removeAllObjects() } internal func _CFSwiftSetCreateCopy(_ set: AnyObject) -> Unmanaged<AnyObject> { return Unmanaged<AnyObject>.passRetained((set as! NSSet).copy() as! NSObject) }
apache-2.0
dba98fec3be7d546cccc8253c5dbc715
29.620879
162
0.635923
4.405534
false
false
false
false
studyYF/SingleSugar
SingleSugar/SingleSugar/Classes/Classification(分类)/Model/YFClassifyItem.swift
1
962
// // YFClassifyItem.swift // SingleSugar // // Created by YangFan on 2017/4/27. // Copyright © 2017年 YangFan. All rights reserved. // import UIKit class YFClassifyItem: NSObject { var status: Int? var banner_image_url: String? var subtitle: String? var id: Int? var created_at: Int? var title: String? var cover_image_url: String? var updated_at: Int? var posts_count: Int? init(dict: [String: AnyObject]) { super.init() status = dict["status"] as? Int banner_image_url = dict["banner_image_url"] as? String subtitle = dict["subtitle"] as? String id = dict["id"] as? Int created_at = dict["created_at"] as? Int title = dict["title"] as? String cover_image_url = dict["cover_image_url"] as? String updated_at = dict["updated_at"] as? Int posts_count = dict["posts_count"] as? Int } }
apache-2.0
1fd91dafb686813a2549d4a5a0405efb
21.833333
62
0.573514
3.646388
false
false
false
false
spark/photon-tinker-ios
Photon-Tinker/Global/Controls/SearchBarView.swift
1
5497
// // Created by Raimundas Sakalauskas on 2019-08-07. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation protocol SearchBarViewDelegate: class { func searchBarTextDidChange(searchBar: SearchBarView, text: String?) func searchBarDidBeginEditing(searchBar: SearchBarView) func searchBarDidEndEditing(searchBar: SearchBarView) } class SearchBarView: UIView, UITextFieldDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var inputText: CustomizableTextField! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var backgroundView: UIView! weak var delegate: SearchBarViewDelegate? override func awakeFromNib() { super.awakeFromNib() backgroundColor = UIColor.clear backgroundView.backgroundColor = ParticleStyle.EthernetToggleBackgroundColor backgroundView.layer.masksToBounds = true inputText.font = UIFont(name: ParticleStyle.RegularFont, size: CGFloat(ParticleStyle.RegularSize)) inputText.textColor = ParticleStyle.PrimaryTextColor inputText.borderStyle = .none inputText.clearButtonMode = .whileEditing inputText.tintColor = ParticleStyle.ButtonColor inputText.placeholder = "" inputText.placeholderColor = ParticleStyle.SecondaryTextColor inputText.clearButtonTintColor = ParticleStyle.ClearButtonColor inputText.text = "" inputText.delegate = self cancelButton.alpha = 0 cancelButton.isHidden = true cancelButton.isEnabled = false } override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) NotificationCenter.default.removeObserver(self) if let superview = newSuperview { NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: UITextField.textDidChangeNotification, object: self.inputText) } } override func layoutSubviews() { super.layoutSubviews() backgroundView.layer.cornerRadius = backgroundView.frame.height / 2 } @IBAction func cancelClicked() { inputText.text = "" self.endEditing(true) hideCancel() textChanged() } private func showCancel() { cancelButton.alpha = 0 cancelButton.isHidden = false cancelButton.isEnabled = true UIView.animate(withDuration: 0.25) { self.layoutIfNeeded() self.cancelButton.alpha = 1 } } private func hideCancel() { cancelButton.alpha = 1 cancelButton.isEnabled = false UIView.animate(withDuration: 0.25, animations: { self.layoutIfNeeded() self.cancelButton.alpha = 0 }, completion: { b in self.cancelButton.isHidden = true }) } @objc public func textChanged() { if var searchTerm = inputText.text?.lowercased().trimmingCharacters(in: .whitespacesAndNewlines), searchTerm.count > 0 { self.delegate?.searchBarTextDidChange(searchBar: self, text: searchTerm) } else { self.delegate?.searchBarTextDidChange(searchBar: self, text: nil) } } //MARK: TextField Delegate public func textFieldDidBeginEditing(_ textField: UITextField) { delegate?.searchBarDidBeginEditing(searchBar: self) showCancel() } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } public func textFieldDidEndEditing(_ textField: UITextField) { if let value = textField.text { textField.text = value.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) } delegate?.searchBarDidEndEditing(searchBar: self) if (textField.text?.isEmpty ?? false) { hideCancel() } } } class CustomizableTextField: UITextField { var placeholderColor: UIColor? = nil { didSet { evalPlaceholderColor() } } override var placeholder: String? { get { return super.placeholder } set { super.placeholder = newValue evalPlaceholderColor() } } var clearButtonTintColor: UIColor? = nil { didSet { evalClearButtonTintColor() } } func evalPlaceholderColor() { if let placeholder = placeholder, let placeHolderColor = placeholderColor { attributedPlaceholder = NSAttributedString.init(string: placeholder, attributes: [ NSAttributedString.Key.foregroundColor: placeHolderColor, NSAttributedString.Key.font: UIFont(name: ParticleStyle.RegularFont, size: CGFloat(ParticleStyle.RegularSize))! ]) } } override func layoutSubviews() { super.layoutSubviews() evalClearButtonTintColor() } private func evalClearButtonTintColor() { for view in subviews as [UIView] { if view is UIButton { let button = view as! UIButton if let clearButtonTintColor = clearButtonTintColor { let tintedImage = UIImage(named: "IconClear")!.image(withColor: clearButtonTintColor) button.setImage(tintedImage, for: .normal) button.setImage(tintedImage, for: .highlighted) } } } } }
apache-2.0
fc092e6691a3840d484fb3eb0eeb6340
29.709497
159
0.647808
5.637949
false
false
false
false
Cofyc/MineSweeper
MineSweeper/GameboardView.swift
1
4284
// // GameboardView.swift // MineSweeper // // Created by Cofyc on 9/14/14. // Copyright (c) 2014 Cofyc. All rights reserved. // import UIKit protocol GameboardDelegate: class { func revealGrid(pos: (Int, Int)) func doubleClickGrid(pos: (Int, Int)) func flagGrid(pos: (Int, Int)) } /** * * A board containing grids. (262x262) * */ class GameboardView: UIView, UIGestureRecognizerDelegate { var dimension: Int = 10 var gridPadding: CGFloat = 2.0 var gridWidth: CGFloat = 24.0 var cornerRadius: CGFloat = 2.0 var bgColor: UIColor = UIColor.whiteColor() var gridColor: UIColor = UIColor.grayColor() var grids: Dictionary<NSIndexPath, GridView> = Dictionary() var delegate: GameboardDelegate? required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) // background self.backgroundColor = UIColor.blackColor() // background for grid var xCursor:CGFloat = gridPadding var yCursor:CGFloat = gridPadding for i in 0..<dimension { // draw a row for j in 0..<dimension { let grid = UIView(frame: CGRectMake(xCursor, yCursor, gridWidth, gridWidth)) grid.layer.cornerRadius = cornerRadius grid.backgroundColor = gridColor addSubview(grid) xCursor += gridPadding + gridWidth } xCursor = gridPadding yCursor += gridPadding + gridWidth } } func reset() { for (key, grid) in grids { grid.removeFromSuperview() } grids.removeAll(keepCapacity: true) } /// Return whether a given position is valid. Used for bounds checking. func positionIsValid(pos: (Int, Int)) -> Bool { let (x, y) = pos return (x >= 0 && x < dimension && y >= 0 && y < dimension) } // Update a grid. func updateGrid(pos: (Int, Int), value: Int) { assert(positionIsValid(pos)) let (row, col) = pos let x = gridPadding + CGFloat(col)*(gridWidth + gridPadding) let y = gridPadding + CGFloat(row)*(gridWidth + gridPadding) let grid = GridView(frame: CGRectMake(x, y, gridWidth, gridWidth), pos: pos, value: value) // tap once grid.addTarget(self, action: "tap:", forControlEvents: UIControlEvents.TouchUpInside) // tap twice grid.addTarget(self, action: "taptwice:withEvent:", forControlEvents: UIControlEvents.TouchDownRepeat) // tap and hold var longPressGesture = UILongPressGestureRecognizer(target: self, action: "handleLongPressGesture:") longPressGesture.delegate = self longPressGesture.minimumPressDuration = 0.2 grid.addGestureRecognizer(longPressGesture) addSubview(grid) bringSubviewToFront(grid) grids[NSIndexPath(forRow: row, inSection: col)] = grid } func revealGrid(pos: (Int, Int)) { assert(positionIsValid(pos)) let (row, col) = pos var grid:GridView = grids[NSIndexPath(forRow: row, inSection: col)]! grid.revealed = true grid.update() } // tap a grid func tap(sender: GridView!) { println("tap") sender.revealed = true sender.update() self.delegate?.revealGrid((sender.x, sender.y)) } func taptwice(sender: GridView!, withEvent event: UIEvent) { var touch:UITouch = event.allTouches()?.first as! UITouch if (touch.tapCount == 2) { println("taptwice") tap(sender) self.delegate?.doubleClickGrid((sender.x, sender.y)) } } // tap and hold a grid func handleLongPressGesture(recognizer: UILongPressGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Ended) { return } let sender = recognizer.view as! GridView println("tapAndHold") sender.flagged = !sender.flagged if (sender.flagged) { println("flagged:") } else { println("flagged: no") } sender.update() self.delegate?.flagGrid((sender.x, sender.y)) } }
mit
3a1dbf2c112e40e8a719cdd7c159c37c
30.5
110
0.605042
4.457856
false
false
false
false
3DprintFIT/octoprint-ios-client
OctoPhone/View Related/Detail/View/JobStateCell.swift
1
1135
// // JobStateCell.swift // OctoPhone // // Created by Josef Dolezal on 01/05/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import UIKit import SnapKit import ReactiveSwift /// Cell with job state class JobStateCell: UICollectionViewCell, TypedCell { /// Reuse identifier of cell static let identifier = "JobStateCell" // MARK: Public API /// Label for job state let stateLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: .headline) label.textAlignment = .center return label }() // MARK: Private properties // MARK: Initializers override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(stateLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Cell lifecycle override func layoutSubviews() { super.layoutSubviews() stateLabel.snp.makeConstraints { make in make.edges.equalToSuperview() } } // MARK: Internal logic }
mit
168c3f319c1c4f49cf11514d604434c8
19.25
66
0.637566
4.591093
false
false
false
false
chrisjmendez/swift-exercises
Games/Timer/Timer/CountdownTimer.swift
1
1622
import UIKit class CountdownTimer: ASAttributedLabelNode { var endTime: NSDate! func update() { let remainingTime = timeLeft() attributedString = stringFromTimeInterval(remainingTime) } func startWithDuration(duration: NSTimeInterval) { let timeNow = NSDate() endTime = timeNow.dateByAddingTimeInterval(duration) } func hasFinished() -> Bool { return timeLeft() == 0 } func createAttributedString(string: String) -> NSMutableAttributedString { let font = UIFont(name: "Futura-Medium", size: 65) let textAttributes = [ NSFontAttributeName : font!, // Note: SKColor.whiteColor().CGColor breaks this NSForegroundColorAttributeName: UIColor.whiteColor(), NSStrokeColorAttributeName: UIColor.blackColor(), // Note: Use negative value here if you want foreground color to show NSStrokeWidthAttributeName: -3 ] return NSMutableAttributedString(string: string , attributes: textAttributes) } func stringFromTimeInterval(interval: NSTimeInterval) -> NSMutableAttributedString { let interval = Int(interval) let seconds = interval % 60 let minutes = (interval / 60) % 60 let timeString = String(format: "%01d:%02d", minutes, seconds) return createAttributedString(timeString) } private func timeLeft() -> NSTimeInterval { let now = NSDate() let remainingSeconds = endTime.timeIntervalSinceDate(now) return max(remainingSeconds, 0) } }
mit
edf7a5958d66accb233b7924efcfc7b8
32.8125
88
0.644883
5.651568
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILinkKeyRequest.swift
1
2151
// // HCILinkKeyRequest.swift // Bluetooth // // Created by Carlos Duclos on 8/3/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// Link Key Request Event /// /// The Link Key Request event is used to indicate that a Link Key is required for the connection with the device specified in BD_ADDR. If the Host has the requested stored Link Key, then the Host shall pass the requested Key to the Controller using the Link_Key_Request_Reply command. If the Host does not have the requested stored Link Key, or the stored Link Key does not meet the security requirements for the requested service, then the Host shall use the Link_Key_Request_Negative_Reply command to indicate to the Controller that the Host does not have the requested key. /// /// - Note: If the Link Key Request event is masked away, then the BR/EDR Con- troller will assume that the Host has no additional link keys. /// If the Host uses the Link_Key_Request_Negative_Reply command when the requested service requires an authenticated Link Key and the current Link Key is unauthenticated, the Host should set the Authentication_Requirements parameter one of the MITM Protection Required options. /// /// When the Controller generates a Link Key Request event in order for the local Link Manager to respond to the request from the remote Link Manager (as a result of a Create_Connection or Authentication_Requested command from the remote Host), the local Host must respond with either a Link_Key_Request_Reply or Link_Key_Request_Negative_Reply command before the remote Link Manager detects LMP response timeout. @frozen public struct HCILinkKeyRequest: HCIEventParameter { public static let event = HCIGeneralEvent.linkKeyRequest public static let length: Int = 6 public let address: BluetoothAddress public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let address = BluetoothAddress(littleEndian: BluetoothAddress(bytes: (data[0], data[1], data[2], data[3], data[4], data[5]))) self.address = address } }
mit
a5ab6c7ec897ea6b86e7ba8868282d81
57.108108
577
0.742326
4.594017
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Model/Manager/VersionModel.swift
1
5313
// // VersionModel.swift // selluv-ios // // Created by 조백근 on 2016. 11. 28.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // import SwiftyJSON import ObjectMapper import AlamofireObjectMapper import RealmSwift class VersionModel: NSObject { let realm = try! Realm() var items: [AnyObject] let onGetData: Foundation.Notification = Foundation.Notification(name: NSNotification.Name(rawValue: "onGetData"), object: nil) static let shared = VersionModel() override init() { self.items = [] super.init() } func getItems(_ term: String){ NotificationCenter.default.post(onGetData) } func detectRecvObjects(_ itemId: String) -> Version? { var flag: Version? for i in 0 ..< self.items.count { let item = self.items[i] as? Version if let piece = item { if(piece.id == itemId) { flag = piece break } } } return flag } public func versionCheck(_ itemIds: [String]) -> [String: AnyObject]? { // var add: [String] = [] var update: [String] = [] var skip: [String] = [] for (_, v) in itemIds.enumerated() { let ver = self.detect(v) if ver != nil { let recv = self.detectRecvObjects(v) let recvVersion = recv?.version ?? -1 let oldVersion = ver?.version ?? -1 if recvVersion > oldVersion { update.append((ver?.name)!) } else { skip.append((ver?.name)!) } } else { let recv = self.detectRecvObjects(v) //add.append(v) update.append((recv?.name)!) } } return [/*"add": add as AnyObject,*/ "update": update as AnyObject, "skip": skip as AnyObject] } public func checkContain(_ itemIds: [String]) -> Bool { let inText = itemIds.joined(separator: "\', \'") let p = NSPredicate(format: "id in (\'%@\')", inText) let list = realm.objects(Version.self).filter(p) if list.count > 0 { return true } else { return false } } public func detect(_ itemId: String) -> Version? { let p = NSPredicate(format: "id=%@", itemId) let list = realm.objects(Version.self).filter(p) if list.count > 0 { return list.first } else { return nil } } public func save(_ new: Version) { try! realm.write { realm.add(new, update: true) self.getItems("") } } func destroy(_ itemId: String) { let p = NSPredicate(format: "id=%@", itemId) let list = realm.objects(Version.self).filter(p) if list.count > 0 { try! realm.write { realm.delete(list) self.getItems("") } } } public func saveAllRecvObjects() { if self.items.count == 0 { return } try! realm.write { realm.add(self.items as! [Version], update: true) self.getItems("") } } func versionCheck(updateBlock: @escaping (_ result: [String: AnyObject])->(), skipBlock: @escaping (_ result: [String: AnyObject])->()) { LoadingIndicatorView.show("Loading") BBProvider.sharedProvider.request(.version, queue: networkQueue, progress: progressClosure) { result in LoadingIndicatorView.hide() switch result { case let .success(moyaResponse): let resText = try? moyaResponse.mapString() let data = moyaResponse.data // Data, your JSON response is probably in here! let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etc if let txt = resText { let r: Response? = Response(JSONString: txt) if r?.status == "success" { let v: [Version] = Mapper<Version>().mapArray(JSONArray: r!.data! as! [[String : Any]])! //항목별로 내려와서 소팅 필요없음 // let sort = v.sorted { // $0.version < $1.version // } var all: [String] = [] _ = v.map() { all.append($0.id) } self.items = v let sorting = self.versionCheck(all) //add, update, skip 이 내려오면 이중 add, update 만 처리하자. updateBlock(sorting!) skipBlock(sorting!) self.saveAllRecvObjects() } } break case let .failure(error): log.error("Error: \(error.localizedDescription)") } } } }
mit
16453df92729c1824e0a53d857ac410d
32.452229
141
0.465727
4.740072
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Common/Data Rows/Base/Value Data Row/ValueDataRow.swift
1
2087
// // ValueDataRow.swift // MEGameTracker // // Created by Emily Ivie on 5/24/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit @IBDesignable final public class ValueDataRow: HairlineBorderView, ValueDataRowDisplayable { // MARK: Inspectable @IBInspectable public var typeName: String = "None" { didSet { setDummyDataRowType() } } @IBInspectable public var isHideOnEmpty: Bool = true // MARK: Outlets @IBOutlet weak public var headingLabel: UILabel? @IBOutlet weak public var valueLabel: UILabel? @IBOutlet weak public var disclosureImageView: UIImageView? @IBOutlet weak public var button: UIButton? @IBAction public func buttonClicked(_ sender: UIButton) { onClick?(sender) } // MARK: Properties public var didSetup = false public var isSettingUp = false // Protocol: IBViewable public var isAttachedNibWrapper = false public var isAttachedNib = false public var onClick: ((UIButton) -> Void)? // MARK: IBViewable override public func awakeFromNib() { super.awakeFromNib() _ = attachOrAttachedNib() } override public func prepareForInterfaceBuilder() { _ = attachOrAttachedNib() super.prepareForInterfaceBuilder() } // MARK: Hide when not initialized (as though if empty) public override func layoutSubviews() { if !UIWindow.isInterfaceBuilder && !isAttachedNib && isHideOnEmpty && !didSetup { isHidden = true } else { setDummyDataRowType() } super.layoutSubviews() } // mARK: Customization Options private func setDummyDataRowType() { guard (isInterfaceBuilder || App.isInitializing) && !didSetup && isAttachedNibWrapper else { return } var dataRowType: ValueDataRowType? switch typeName { case "Appearance": dataRowType = AppearanceLinkType() case "ConversationRewards": dataRowType = ConversationRewardsRowType() case "DecisionsListLink": dataRowType = DecisionsListLinkType() case "MapLink": dataRowType = MapLinkType() default: break } dataRowType?.row = self dataRowType?.setupView() } } // MARK: Spinnerable extension ValueDataRow: Spinnerable {}
mit
87565968f3f95073b30fc47f3492d09f
25.075
103
0.735858
4.098232
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/Widgets/Countdown/View/ConventionCountdownTableViewDataSource.swift
1
1868
import Combine import ComponentBase import UIKit public class ConventionCountdownTableViewDataSource< ViewModel: ConventionCountdownViewModel >: NSObject, TableViewMediator { private let viewModel: ViewModel private var subscriptions = Set<AnyCancellable>() init(viewModel: ViewModel) { self.viewModel = viewModel super.init() viewModel .publisher(for: \.showCountdown) .sink { [weak self] (_) in if let self = self { self.delegate?.dataSourceContentsDidChange(self) } } .store(in: &subscriptions) } public var delegate: TableViewMediatorDelegate? public func registerReusableViews(into tableView: UITableView) { tableView.registerConventionBrandedHeader() tableView.register(NewsConventionCountdownTableViewCell.self) } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewModel.showCountdown ? 1 : 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(NewsConventionCountdownTableViewCell.self) viewModel .publisher(for: \.countdownDescription) .map({ $0 ?? "" }) .sink { [weak cell] (countdownDescription) in cell?.setTimeUntilConvention(countdownDescription) } .store(in: &subscriptions) return cell } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueConventionBrandedHeader() headerView.textLabel?.text = .daysUntilConvention return headerView } }
mit
ab45482a333ab2efade5c804f1db72c8
31.206897
107
0.631156
5.677812
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/02711-swift-declcontext-lookupqualified.swift
11
991
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class C<T where f: A<b: a { func g: A.c { func a<A<T where f: String { let a : A<T where f: T where f: A { class d<b class A { class C<h : a : T protocol c : T : T where f: A? = c let a : b = e protocol c : a { struct A? { for b = c<h : b in c class d<T where f: a { class A { for b { func a() -> <h : (f: A { let a { protocol c { typealias e = Swift.c : T, AnyObject struct A<T, A { struct A : a { private let v: b in c<T where f: a { Any) private let v: b in c class C<T : A<b: A : T) -> Bool { class d<T where S.c typealias e = e [Void{ if true { func b: A<b: Int = [] typealias e = [Void{ struct B<T where f: T where f: Int = Swift.c : a = e struct A<A.e = 1) for b = e struct A? = e struct B<T where B : Int = { func a() -> V { func b (""""""" func a() -> <T where S.e = e struct A, A { class b class b: A<T) -> Bool
mit
9f0df44f0bd56b2c7a2d4da9ff7a8e04
20.543478
87
0.598385
2.534527
false
false
false
false
dcilia/swift-executor
Playgrounds/ExecutorKit.playground/Pages/Basic Example.xcplaygroundpage/Contents.swift
1
2315
//: Playground - noun: a place where people can play import Foundation import ExecutorKit /** Subclassing AsyncOperation use case: The "isSetup" property here highlights the custom implementation of how one might mark the operation as "ready". Note this is optional. */ final class Foo: AsyncOperation { var result: Int = Int.max private var nums: [Int] private let id = "com.executorKit.foo" var isSetup = false //Custom initializer init(nums: [Int]) { self.nums = nums super.init(identifier: id) } //The custom implementation of "ready" state. override func ready() { if isSetup { super.ready() } } override func execute() { var sum = 0 for i in 0..<nums.endIndex { sum += i } result = sum finish() } } struct FooObserver: ExecutorObserver, CustomStringConvertible { func did(start operation: AsyncOperation) { print(operation) print(#function) } func did(cancel operation: AsyncOperation) { print(operation) print(#function) } func did(finish operation: AsyncOperation) { print(operation) print(#function) } func did(becomeReady operation: AsyncOperation) { print(operation) print(#function) } var description: String { return "FooObserver" } } var op1 = Foo(nums: [2,4,5,6,7]) let obs = FooObserver() op1.add(observer: obs) op1.isSetup = true op1.completionBlock = { print(op1.result) } op1.start() //Example using the run closure //note that we must use the 2nd initializer to set the ready state var op2 = AsyncOperation(identifier: "com.executorKit.foo") //won't run, use other initializer op2.run = { print("Hello World!") } op2.add(observer: obs) op2.completionBlock = { print("Completion Block") } op2.start() var op3 = AsyncOperation(identifier: "com.executorKit.bar",readyToExecute: true) op3.run = { print("Hello World") } op3.add(observer: obs) op3.didStart = { print("did start") } op3.didFinish = { //do something here } //Use the "start" or add to an OperationQueue var q = OperationQueue() q.name = "myqueue" q.addOperation(op3)
mit
677a2972c991d4b007fb9e871757cd25
18.618644
94
0.620734
3.897306
false
false
false
false
CodePath2017Group4/travel-app
RoadTripPlanner/NotificationViewController.swift
1
10447
// // NotificationViewController.swift // RoadTripPlanner // // Created by Nanxi Kang on 10/28/17. // Copyright © 2017 RoadTripPlanner. All rights reserved. // import Parse import UIKit class NotificationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, InvitationDelegate, InviteUserDelegate { @IBOutlet weak var notificationTable: UITableView! let MAX_INVITATIONS: Int = 3 var expandPending: Bool = false var expandPast: Bool = false var trips: [Trip] = [] var pendingInvitations: [TripMember] = [] var pastInvitations: [TripMember] = [] override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.tintColor = Constants.Colors.NavigationBarDarkTintColor let textAttributes = [NSForegroundColorAttributeName:Constants.Colors.NavigationBarDarkTintColor] navigationController?.navigationBar.titleTextAttributes = textAttributes navigationItem.title = "Notifications" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Invite", style: .plain, target: self, action: #selector(inviteTapped)) notificationTable.delegate = self notificationTable.dataSource = self notificationTable.tableFooterView = UIView() // Add "Pull to refresh" let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) notificationTable.insertSubview(refreshControl, at: 0) // fakeNotifications() requestNotifications(nil) notificationTable.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func refreshControlAction(_ refreshControl: UIRefreshControl) { print("refresh!") requestNotifications(refreshControl) } private func stopRefreshing(_ refreshControl: UIRefreshControl?) { if let refreshControl = refreshControl { refreshControl.endRefreshing() } } private func requestNotifications(_ refreshControl: UIRefreshControl?) { if let user = PFUser.current() { ParseBackend.getInvitedTrips(user: user) { (tripMember, error) in self.stopRefreshing(refreshControl) if let tripMember = tripMember { self.pendingInvitations = tripMember DispatchQueue.main.async { self.notificationTable.reloadData() } } else { print("Error to get invited trips \(error)") } } ParseBackend.getTripsCreatedByUser(user: user) { (trips, error) in if let trips = trips { self.trips = trips print("trips created by me: \(trips.count)") ParseBackend.getTripMemberOnTrips(trips: trips, excludeCreator: true) { (tripMember, error) in self.stopRefreshing(refreshControl) if let tripMember = tripMember { self.pastInvitations = tripMember DispatchQueue.main.async { self.notificationTable.reloadData() } } else { print("Error to get past invitations: \(error)") } } self.notificationTable.reloadData() } else { self.stopRefreshing(refreshControl) print("Error to get created trips: \(error)") } } } } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return getNumInvitations(isPending: isPendingSection(section: section)) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (isPendingSection(section: indexPath.section)) { if (!isLast(indexPath: indexPath)) { let cell = tableView.dequeueReusableCell(withIdentifier: "pendingCell") as! PendingInvitationTableViewCell cell.displayInvitaion(tripMember: self.pendingInvitations[indexPath.row]) cell.delegate = self cell.index = indexPath.row return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "controlCell") as! NotificationControlTableViewCell cell.showStatus(more: expandPending) return cell } } else { if (!isLast(indexPath: indexPath)) { let cell = tableView.dequeueReusableCell(withIdentifier: "pastCell") as! HistoryInvitationTableViewCell cell.displayInvitaion(tripMember: self.pastInvitations[indexPath.row]) return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "controlCell") as! NotificationControlTableViewCell cell.showStatus(more: expandPast) return cell } } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (isPendingSection(section: section)) { return "RECEIVED" } else { return "SENT" } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if (isLast(indexPath: indexPath)) { if (isPendingSection(section: indexPath.section)) { expandPending = !expandPending } else { expandPast = !expandPast } tableView.reloadData() } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if (isPendingSection(section: indexPath.section)) { if (!isLast(indexPath: indexPath)) { return 90.0 } else { return 50.0 } } else { return 50.0 } } func inviteTapped(_ sender: Any) { if let vc = InviteToTripViewController.storyboardInstance() { vc.delegate = self self.show(vc, sender: self) } } private func isPendingSection(section: Int) -> Bool { return section == 0 } private func getNumInvitations(isPending: Bool) -> Int { if (isPending) { if (!expandPending && self.pendingInvitations.count > MAX_INVITATIONS) { return MAX_INVITATIONS + 1 } else { return self.pendingInvitations.count + 1 } } else { if (!expandPast && self.pastInvitations.count > MAX_INVITATIONS) { return MAX_INVITATIONS + 1 } else { return self.pastInvitations.count + 1 } } } private func isLast(indexPath: IndexPath) -> Bool { return indexPath.row == getNumInvitations(isPending: isPendingSection(section: indexPath.section)) - 1 } private func fakeNotifications() { let user = PFUser.current()! for i in 0 ... 6 { let creator = PFUser() creator.username = "a\(i)" let date = Date() let trip = Trip.createTrip(name: "Trip\(i)", date: date, creator: creator) let tripMember = TripMember(user: user, isCreator: false, trip: trip) if (i % 3 == 0) { tripMember.status = InviteStatus.Pending.hashValue } else if (i % 3 == 1) { tripMember.status = InviteStatus.Confirmed.hashValue } else if (i % 3 == 2) { tripMember.status = InviteStatus.Rejected.hashValue } self.pendingInvitations.append(tripMember) } for i in 0 ... 6 { let invitee = PFUser() invitee.username = "b\(i)" let date = Date() let trip = Trip.createTrip(name: "Trip\(i)", date: date, creator: user) let tripMember = TripMember(user: invitee, isCreator: false, trip: trip) if (i % 3 == 0) { tripMember.status = InviteStatus.Pending.hashValue } else if (i % 3 == 1) { tripMember.status = InviteStatus.Confirmed.hashValue } else if (i % 3 == 2) { tripMember.status = InviteStatus.Rejected.hashValue } self.pastInvitations.append(tripMember) } } func addInvitation(tripMember: TripMember) { self.pastInvitations.append(tripMember) DispatchQueue.main.async { self.notificationTable.reloadData() } } func confirmInvitation(index: Int) { self.pendingInvitations[index].status = InviteStatus.Confirmed.hashValue self.pendingInvitations[index].saveInBackground{ (success, error) in if success { log.info("Invitation \(index) confirmed") } else { guard let error = error else { log.error("Unknown error occurred confirming invitations") return } log.error("Error confirming invitations: \(error)") } } } func rejectInvitation(index: Int) { self.pendingInvitations[index].status = InviteStatus.Rejected.hashValue self.pendingInvitations[index].saveInBackground{ (success, error) in if success { log.info("Invitation \(index) rejected") } else { guard let error = error else { log.error("Unknown error occurred rejecting invitations") return } log.error("Error rejecting invitations: \(error)") } } } }
mit
4b4411014df5aecf01805c8ab0f57a8a
36.985455
138
0.56548
5.538706
false
false
false
false
Senspark/ee-x
src/ios/ee/core/PluginManager.swift
1
9668
// // PluginManager.swift // ee-x-366f64ba // // Created by eps on 6/12/20. // import Foundation private typealias PluginExecutor = (_ plugin: IPlugin) -> Bool public class PluginManager: NSObject { private static let _sharedInstance = PluginManager() private let _logger = Logger("ee-x") private let _bridge = MessageBridge() private var _plugins: [String: IPlugin] #if os(iOS) private var _delegate: UIApplicationDelegate? #endif // os(iOS) public class var instance: PluginManager { return _sharedInstance } override private init() { _plugins = [:] } public var bridge: IMessageBridge { return _bridge } public var logger: ILogger { return _logger } #if os(iOS) fileprivate func initializePlugins(_ version: String, _ delegate: UIApplicationDelegate) -> Bool { let expectedVersion = "2.10.3" if version != expectedVersion { _logger.error("Version mismatched: found \(version) expected \(expectedVersion)") assert(false) return false } _logger.info("Initialize ee-x plugin version \(version)") _delegate = delegate swizzle(#selector(UIApplicationDelegate.application(_:open:options:)), #selector(PluginManager.application(_:open:options:))) swizzle(#selector(UIApplicationDelegate.application(_:open:sourceApplication:annotation:)), #selector(PluginManager.application(_:open:sourceApplication:annotation:))) swizzle(#selector(UIApplicationDelegate.application(_:continue:restorationHandler:)), #selector(PluginManager.application(_:continue:restorationHandler:))) Platform.registerHandlers(_bridge) return true } #else // os(iOS) fileprivate func initializePlugins() -> Bool { Platform.registerHandlers(_bridge) return true } #endif // os(iOS) fileprivate func setLogLevel(_ level: Int) { if let logLevel = LogLevel(rawValue: level) { _logger.logLevel = logLevel } } /// Adds and initialize a plugin. /// @param[in] name The plugin's name, e.g. AdMob, Vungle. fileprivate func addPlugin(_ name: String) -> Bool { if _plugins.contains(where: { key, _ -> Bool in key == name }) { assert(false, "Plugin already exists: \(name)") return false } guard let plugin = // Swift plugins. (NSClassFromString("EE\(name)Bridge") as? IPlugin.Type)?.init(_bridge, _logger) ?? // Objective-C plugins. (NSClassFromString("EE\(name)") as? NSObject.Type)?.init() as? IPlugin else { assert(false, "Invalid plugin: \(name)") return false } _plugins[name] = plugin return true } /// Removes and deinitialize a plugin. /// @param[in] name The plugin's name, e.g. AdMob, Vungle. fileprivate func removePlugin(_ name: String) -> Bool { guard let plugin = _plugins[name] else { assert(false, "Plugin not exists: \(name)") return false } plugin.destroy() _plugins.removeValue(forKey: name) return true } private func executePlugins(_ executor: PluginExecutor) -> Bool { var response = false for entry in _plugins { if executor(entry.value) { response = true } } return response } #if os(iOS) private func swizzle(_ originalSelector: Selector, _ replacedSelector: Selector) { guard let replacedMethod = class_getInstanceMethod(PluginManager.self, replacedSelector) else { assert(false, "Invalid method") return } let originalClass: AnyClass? = object_getClass(_delegate) if let originalMethod = class_getInstanceMethod(originalClass, originalSelector) { method_exchangeImplementations(originalMethod, replacedMethod) } else { class_addMethod(originalClass, originalSelector, method_getImplementation(replacedMethod), method_getTypeEncoding(replacedMethod)) // https://stackoverflow.com/questions/28211973/swift-closure-as-anyobject/32454665 let block: (AnyObject) -> Bool = { _ in false } let impl = imp_implementationWithBlock(unsafeBitCast(block as @convention(block) (AnyObject) -> Bool, to: AnyObject.self)) method_setImplementation(replacedMethod, impl) } } @objc private func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool { // https://stackoverflow.com/questions/39003876/calling-original-function-from-swizzled-function typealias Func = @convention(c) (AnyObject, Selector, UIApplication, URL, [UIApplication.OpenURLOptionsKey: Any]) -> Bool let closure = ee_closureCast(#selector(PluginManager.application(_:open:options:)), Func.self) var response = closure(self, #selector(UIApplicationDelegate.application(_:open:options:)), application, url, options) if (PluginManager.instance.executePlugins { $0.application?(application, open: url, options: options) ?? false }) { response = true } return response } @objc private func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { typealias Func = @convention(c) (AnyObject, Selector, UIApplication, URL, String?, Any) -> Bool let closure = ee_closureCast(#selector(PluginManager.application(_:open:sourceApplication:annotation:)), Func.self) var response = closure(self, #selector(UIApplicationDelegate.application(_:open:sourceApplication:annotation:)), application, url, sourceApplication, annotation) if (PluginManager.instance.executePlugins { $0.application?(application, open: url, sourceApplication: sourceApplication, annotation: annotation) ?? false }) { response = true } return response } @objc private func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { typealias Func = @convention(c) (AnyObject, Selector, UIApplication, NSUserActivity, @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool let closure = ee_closureCast(#selector(PluginManager.application(_:continue:restorationHandler:)), Func.self) var response = closure(self, #selector(UIApplicationDelegate.application(_:continue:restorationHandler:)), application, userActivity, restorationHandler) if (PluginManager.instance.executePlugins { $0.application?(application, continue: userActivity, restorationHandler: restorationHandler) ?? false }) { response = true } return response } #endif // os(iOS) fileprivate class func staticAddPlugin(_ name: UnsafePointer<CChar>) -> Bool { let name_str = String(cString: name) return _sharedInstance.addPlugin(name_str) } fileprivate class func staticRemovePlugin(_ name: UnsafePointer<CChar>) -> Bool { let name_str = String(cString: name) return _sharedInstance.removePlugin(name_str) } } private func ee_closureCast<T>(_ swizzledSelector: Selector, _ type: T.Type) -> T { let impl = class_getMethodImplementation(PluginManager.self, swizzledSelector) return unsafeBitCast(impl, to: T.self) } @_cdecl("ee_staticInitializePlugins") public func ee_staticInitializePlugins(_ version: UnsafePointer<CChar>) -> Bool { let version_str = String(cString: version) #if os(iOS) guard let delegate = UIApplication.shared.delegate else { assert(false, "Delegate not assigned") return false } return PluginManager.instance.initializePlugins(version_str, delegate) #else // os(iOS) return PluginManager.instance.initializePlugins(version_str) #endif // os(iOS) } @_cdecl("ee_staticSetLogLevel") public func ee_staticSetLogLevel(_ level: Int) { PluginManager.instance.setLogLevel(level) } @_cdecl("ee_staticGetActivity") public func ee_staticGetActivity() -> Any? { return nil } @_cdecl("ee_staticSetActivity") public func ee_staticSetActivity(_ activity: UnsafeRawPointer) { // No-op. } @_cdecl("ee_staticAddPlugin") public func ee_staticAddPlugin(_ name: UnsafePointer<CChar>) -> Bool { return PluginManager.staticAddPlugin(name) } @_cdecl("ee_staticRemovePlugin") public func ee_staticRemovePlugin(_ name: UnsafePointer<CChar>) -> Bool { return PluginManager.staticRemovePlugin(name) }
mit
1234c809474856853b31d446ad670a6c
39.621849
148
0.600641
5.104541
false
false
false
false
thedistance/TheDistanceComponents
TDCContentLoading/View Model/PagedContentLoadingViewModel.swift
1
3421
// // PagedContentLoadingViewModel.swift // ComponentLibrary // // Created by Josh Campion on 19/04/2016. // Copyright © 2016 The Distance. All rights reserved. // import Foundation import ReactiveSwift /** Subclass of `ContentLoadingViewModel` for loading paged content. This class handles the aggregation of the loaded content allowing subclasses to provide only the content for a given page. The current page and whether there is more content available is handled automatically. `InputType` is a `Bool` indicating whether the next page of content should be fetched (`true`), or whether the currently loaded content should be cleared and the first page of content requested again (`false`). */ open class PagingContentLoadingViewModel<ValueType>: ListLoadingViewModel<Bool, PagedOutput<ValueType>>, ChangesetLoadingModel { /// The number of objects that should be fetched per page. The default value is 25. Changing the value of this causes a refresh of the content as the current page number will be incorrect. public let pageCount = MutableProperty<UInt>(25) /// Default initialiser passing the parameters through to `super`. public override init(lifetimeTrigger: ViewLifetime? = .WillAppear, refreshFlattenStrategy: FlattenStrategy = .latest) { super.init(lifetimeTrigger: lifetimeTrigger, refreshFlattenStrategy: refreshFlattenStrategy) pageCount.producer.combinePrevious(25).filter { $0 != $1 }.startWithValues { _ in self.refreshObserver.send(value: false) } } /** Point of customisation for subclasses. The given page of content should be requested from an APIManager or other external source. */ open func contentForPage(page: UInt) -> SignalProducer<[ValueType], NSError> { return SignalProducer.empty } /** Aggregate the results of `contentForPage(_:)` that have been loaded so far. - parameter nextPage: Flag for whether the next page of content is being loaded (`true`) or the content is being loaded again from scratch (`false`). */ override public func loadingProducerWithInput(input nextPage: Bool?) -> SignalProducer<PagedOutput<ValueType>, NSError> { let page:UInt let currentContent:PagedOutput<ValueType> if nextPage ?? false { let currentCount = loadedContent?.currentContent.count ?? 0 page = UInt(currentCount) / pageCount.value currentContent = loadedContent ?? PagedOutput(currentContent:[ValueType](), moreAvailable:true) } else { currentContent = PagedOutput(currentContent:[ValueType](), moreAvailable:true) page = 0 } return contentForPage(page: page) .scan(currentContent) { let aggregatedContent = $0.currentContent + $1 let moreAvailable = UInt($1.count) == self.pageCount.value return PagedOutput(currentContent: aggregatedContent, moreAvailable: moreAvailable ) } } // MARK: Changeset Loading Model /// - returns: The currently loaded content from the `PagedOutput` or and empty array if nothing has been downloaded. public func currentItems() -> [ValueType] { return loadedContent?.currentContent ?? [] } }
mit
78b4123e9522de567328c547c01fe613
41.75
276
0.676901
5.34375
false
false
false
false
Sticky-Gerbil/furry-adventure
FurryAdventure/Controller/AddIngredientsVC.swift
1
5854
// // AddIngredientsVC.swift // FurryAdventure // // Created by Sang Saephan on 3/20/17. // Copyright © 2017 Sticky Gerbils. All rights reserved. // import UIKit class AddIngredientsVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var addIngLine: UIView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var toolBar: UIToolbar! var categories = ["Vegetables", "Fruits", "Meat", "Dairy", "Grains and Carbs", "Herbs and Spices"] var images = [UIImage(named: "vegetables"), UIImage(named: "fruits"), UIImage(named: "meat"), UIImage(named: "dairy"), UIImage(named: "grains_and_carbs"), UIImage(named: "herbs_and_spices")] var ingredients = [vegetables, fruits, meat, dairy, grainsAndCarbs, herbsAndSpices, fish, oil, seafood, sweeteners, seasonings, nuts, condiments, dessertsAndSnacks, beverages, soup, dairyAlternatives, legumes, sauces, alcohol].joined(separator: []).map{$0} var filteredIngredients = [vegetables, fruits, meat, dairy, grainsAndCarbs, herbsAndSpices, fish, oil, seafood, sweeteners, seasonings, nuts, condiments, dessertsAndSnacks, beverages, soup, dairyAlternatives, legumes, sauces, alcohol].joined(separator: []).map{$0} override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self tableView.delegate = self tableView.dataSource = self searchBar.delegate = self } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return categories.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddIngredientCell", for: indexPath) as! AddIngredientsCollectionCell cell.nameLabel.text = categories[indexPath.row] cell.posterImageView.image = images[indexPath.row] return cell } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text == nil || searchBar.text == "" { tableView.isHidden = true collectionView.isHidden = false } else { tableView.isHidden = false collectionView.isHidden = true } filteredIngredients = searchText.isEmpty ? ingredients.sorted() : ingredients.sorted().filter({ $0.range(of: searchText, options: .caseInsensitive) != nil }) tableView.reloadData() } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) collectionView.alpha = 0.5 } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() searchBar.setShowsCancelButton(false, animated: true) searchBar.text = "" tableView.isHidden = true collectionView.isHidden = false collectionView.alpha = 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredIngredients.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SearchIngredientCell", for: indexPath) cell.textLabel?.text = filteredIngredients[indexPath.row].capitalized return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) cart.append(filteredIngredients[indexPath.row]) let alertController = UIAlertController(title: "Added Ingredient:", message: "\(filteredIngredients[indexPath.row].capitalized)", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: nil)) self.present(alertController, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Pass ingredients into selected category if segue.identifier == "CategoryViewSegue" { let cell = sender as! AddIngredientsCollectionCell let indexPath = collectionView.indexPath(for: cell) let title = cell.nameLabel.text let navigationController = segue.destination as! UINavigationController let detailViewController = navigationController.topViewController as! CategoryVC detailViewController.navigationController?.navigationBar.topItem?.title = title if indexPath?.row == 0 { detailViewController.categoryIngredients = vegetables.sorted() } else if indexPath?.row == 1 { detailViewController.categoryIngredients = fruits.sorted() } else if indexPath?.row == 2 { detailViewController.categoryIngredients = meat.sorted() } else if indexPath?.row == 3 { detailViewController.categoryIngredients = dairy.sorted() } else if indexPath?.row == 4 { detailViewController.categoryIngredients = grainsAndCarbs.sorted() } else if indexPath?.row == 5 { detailViewController.categoryIngredients = herbsAndSpices.sorted() } } } }
apache-2.0
3f8c94d81b6b94f336d72b7cb506cd76
42.679104
268
0.666325
5.30163
false
false
false
false
zisko/swift
test/SILGen/objc_attr_NSManaged_multi.swift
1
2232
// RUN: %target-swift-frontend -sdk %S/Inputs -primary-file %s %S/objc_attr_NSManaged.swift -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import Foundation // CHECK-LABEL: sil hidden @$S25objc_attr_NSManaged_multi9testMultiyyXlAA10SwiftGizmoCF : $@convention(thin) (@owned SwiftGizmo) -> @owned AnyObject { // CHECK: bb0([[ARG:%.*]] : @owned $SwiftGizmo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: = objc_method [[BORROWED_ARG]] : $SwiftGizmo, #SwiftGizmo.kvc!1.foreign : (SwiftGizmo) -> () -> (), $@convention(objc_method) (SwiftGizmo) -> () // CHECK-NOT: return // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: = objc_method [[BORROWED_ARG]] : $SwiftGizmo, #SwiftGizmo.extKVC!1.foreign : (SwiftGizmo) -> () -> (), $@convention(objc_method) (SwiftGizmo) -> () // CHECK-NOT: return // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: objc_method [[BORROWED_ARG]] : $SwiftGizmo, #SwiftGizmo.x!getter.1.foreign : (SwiftGizmo) -> () -> X, $@convention(objc_method) (SwiftGizmo) -> @autoreleased X // CHECK: return func testMulti(_ obj: SwiftGizmo) -> AnyObject { obj.kvc() obj.extKVC() return obj.x } // CHECK-LABEL: sil hidden @$S25objc_attr_NSManaged_multi14testFinalMultiySSAA0F5GizmoCF : $@convention(thin) (@owned FinalGizmo) -> @owned String { // CHECK: bb0([[ARG:%.*]] : @owned $FinalGizmo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: objc_method [[BORROWED_ARG]] : $FinalGizmo, #FinalGizmo.kvc2!1.foreign : (FinalGizmo) -> () -> (), $@convention(objc_method) (FinalGizmo) -> () // CHECK-NOT: return // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: objc_method [[BORROWED_ARG]] : $FinalGizmo, #FinalGizmo.extKVC2!1.foreign : (FinalGizmo) -> () -> (), $@convention(objc_method) (FinalGizmo) -> () // CHECK-NOT: return // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: objc_method [[BORROWED_ARG]] : $FinalGizmo, #FinalGizmo.y!getter.1.foreign : (FinalGizmo) -> () -> String, $@convention(objc_method) (FinalGizmo) -> @autoreleased NSString // CHECK: return func testFinalMulti(_ obj: FinalGizmo) -> String { obj.kvc2() obj.extKVC2() return obj.y }
apache-2.0
1aa1195800b40f223cd7cdb7929ece9c
56.230769
181
0.658602
3.351351
false
true
false
false
lieonCX/Live
Live/Others/Lib/RITLImagePicker/Photofiles/Photo/RITLPhotoBottomReusableView.swift
1
1736
// // RITLPhotoBottomReusableView.swift // RITLImagePicker-Swift // // Created by YueWen on 2017/1/16. // Copyright © 2017年 YueWen. All rights reserved. // import UIKit class RITLPhotoBottomReusableView: UICollectionReusableView { /// 资源的数目 var ritl_numberOfAsset = 0 { willSet{ self.ritl_assetLabel.text = "共有\(newValue)张照片" } } /// 在标签上的自定义文字 var ritl_customText = "" { willSet{ self.ritl_assetLabel.text = newValue } } /// 显示title的标签 var ritl_assetLabel : UILabel = { var assetLabel = UILabel() assetLabel.font = .systemFont(ofSize: 14) assetLabel.textAlignment = .center // assetLabel.textColor = .colorValue(with: 0x6F7179) assetLabel.textColor = 0x6F7179.ritl_color return assetLabel }() override init(frame: CGRect) { super.init(frame: frame) layoutOwnSubviews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() layoutOwnSubviews() } override func prepareForReuse() { super.prepareForReuse() ritl_customText = "" } // MARK: private fileprivate func layoutOwnSubviews() { self.addSubview(ritl_assetLabel) //layout ritl_assetLabel.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } }
mit
0e098316b7969422408cef6c008ccbc3
18.125
60
0.530006
4.78125
false
false
false
false
lamb/trials
Notify/Notify/ViewController.swift
1
2225
// // ViewController.swift // Notify // // Created by Lamb on 15/10/27. // Copyright © 2015年 Lamb. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: "drwaAShape:", name: "actionOnePressed", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "showAMessage:", name: "actionTwoPressed", object: nil) let dateComp: NSDateComponents = NSDateComponents() dateComp.year = 2015 dateComp.month = 10 dateComp.day = 28 dateComp.hour = 18 dateComp.minute = 017 dateComp.timeZone = NSTimeZone.systemTimeZone() let calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! //let date: NSDate = calender.dateFromComponents(dateComp)! let date: NSDate = NSDate(timeIntervalSinceNow: 60) let notification: UILocalNotification = UILocalNotification() notification.category = "FIRST_CATEGORY" notification.alertBody = "Hi, I am a notification!" notification.fireDate = date UIApplication.sharedApplication().scheduleLocalNotification(notification) } func drwaAShape(notification: NSNotification) { let view: UIView = UIView(frame: CGRectMake(10, 10, 100, 100)) view.backgroundColor = UIColor.lightGrayColor() self.view.addSubview(view) } func showAMessage(notification: NSNotification) { let messageVC: UIAlertController = UIAlertController(title: "A Notification Message", message: "Hello there", preferredStyle: UIAlertControllerStyle.Alert) messageVC.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(messageVC, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
e1538d3e7dac2ee8f15dc79026103c44
35.42623
163
0.679568
5.240566
false
false
false
false
myfreeweb/SwiftCBOR
Sources/SwiftCBOR/Util.swift
2
1874
final class Util { // https://stackoverflow.com/questions/24465475/how-can-i-create-a-string-from-utf8-in-swift static func decodeUtf8(_ bytes: ArraySlice<UInt8>) throws -> String { var result = "" var decoder = UTF8() var generator = bytes.makeIterator() var finished = false repeat { let decodingResult = decoder.decode(&generator) switch decodingResult { case .scalarValue(let char): result.append(String(char)) case .emptyInput: finished = true case .error: throw CBORError.incorrectUTF8String } } while (!finished) return result } static func djb2Hash(_ array: [Int]) -> Int { return array.reduce(5381, { hash, elem in ((hash << 5) &+ hash) &+ Int(elem) }) } // https://gist.github.com/martinkallman/5049614 // rewritten to Swift + applied fixes from comments + added NaN/Inf checks // should be good enough, who cares about float16 static func readFloat16(x: UInt16) -> Float32 { if (x & 0x7fff) > 0x7c00 { return Float32.nan } if x == 0x7c00 { return Float32.infinity } if x == 0xfc00 { return -Float32.infinity } var t1 = UInt32(x & 0x7fff) // Non-sign bits var t2 = UInt32(x & 0x8000) // Sign bit let t3 = UInt32(x & 0x7c00) // Exponent t1 <<= 13 // Align mantissa on MSB t2 <<= 16 // Shift sign bit into position t1 += 0x38000000 // Adjust bias t1 = (t3 == 0 ? 0 : t1) // Denormals-as-zero t1 |= t2 // Re-insert sign bit return Float32(bitPattern: t1) } }
unlicense
5d7c6bd2364e1f3c3c1ddef9c3fa1f08
37.244898
96
0.513874
4.012848
false
false
false
false
aichamorro/fitness-tracker
Clients/Apple/FitnessTracker/FitnessTrackerTests/InsightsTests.swift
1
7363
// // InsightsTests.swift // FitnessTracker // // Created by Alberto Chamorro - Personal on 01/01/2017. // Copyright © 2017 OnsetBits. All rights reserved. // import Foundation import Quick import Nimble import RxSwift import RxTest @testable import FitnessTracker class InsightsTests: QuickSpec { // swiftlint:disable function_body_length override func spec() { describe("As user I would like to see some insights of my data") { context("Compare with previous results") { var fitnessInfoRepository: IFitnessInfoRepository! var interactor: IFindInsights! var disposeBag: DisposeBag! beforeEach { let managedObjectContext = SetUpInMemoryManagedObjectContext() let coreDataEngine = CoreDataEngineImpl(managedObjectContext: managedObjectContext) fitnessInfoRepository = CoreDataFitnessInfoRepository(coreDataEngine: coreDataEngine) interactor = FindInsights(repository: fitnessInfoRepository) disposeBag = DisposeBag() } it("Creates a comparison of the data from the previous day") { fitnessInfoRepository.rx_save(many: [FitnessInfo(weight: 60.9, height: 171, bodyFatPercentage: 20.0, musclePercentage: 20.0, waterPercentage: 20.0), FitnessInfo(weight: 61.0, height: 171, bodyFatPercentage: 20.0, musclePercentage: 20.0, waterPercentage: 20.0)]) .bindNext { _ in } .addDisposableTo(disposeBag) waitUntil { done in interactor.rx_output.subscribe(onNext: { insights in guard let daily = insights.dayInsight else { fail(); done(); return } expect(daily.height).to(equal(0)) expect(daily.weight).to(equal(61.0 - 60.9)) expect(daily.bodyFatPercentage).to(equal(0.0)) expect(daily.musclePercentage).to(equal(0.0)) expect(daily.waterPercentage).to(equal(0.0)) done() }).addDisposableTo(disposeBag) interactor.rx_input.onNext() } } it("Creates a comparison of the data from the previous week") { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yy hh:mm" let dates = ["22/01/17 11:16", "21/01/17 09:18", "20/01/17 07:53", "19/01/17 07:52", "18/01/17 09:17", "17/01/17 09:42", "16/01/17 12:06"] .map { return dateFormatter.date(from: $0)! as NSDate } let weekFitnessInfo = [FitnessInfo(weight: 68.28, height: 171, bodyFatPercentage: 20.1, musclePercentage: 33.2, waterPercentage: 54.3, date: dates[0]), FitnessInfo(weight: 67.98, height: 171, bodyFatPercentage: 19.9, musclePercentage: 33.5, waterPercentage: 54.4, date: dates[1]), FitnessInfo(weight: 67.98, height: 171, bodyFatPercentage: 20.1, musclePercentage: 33.3, waterPercentage: 54.3, date: dates[2]), FitnessInfo(weight: 67.82, height: 171, bodyFatPercentage: 20.0, musclePercentage: 33.4, waterPercentage: 54.4, date: dates[3]), FitnessInfo(weight: 67.98, height: 171, bodyFatPercentage: 19.7, musclePercentage: 33.7, waterPercentage: 54.6, date: dates[4]), FitnessInfo(weight: 67.58, height: 171, bodyFatPercentage: 19.9, musclePercentage: 33.4, waterPercentage: 54.4, date: dates[5]), FitnessInfo(weight: 67.41, height: 171, bodyFatPercentage: 19.6, musclePercentage: 33.7, waterPercentage: 54.6, date: dates[6])] for info in weekFitnessInfo { do { try fitnessInfoRepository.save(info) } catch { fail() return } } waitUntil { done in interactor.rx_output.subscribe(onNext: { insights in guard let weekly = insights.weekInsight else { fail(); done(); return; } expect(weekly.weight - 0.87 < 0.0000001).to(beTrue()) expect(weekly.bodyFatPercentage - 0.5 < 0.0000001).to(beTrue()) expect(weekly.musclePercentage - (-0.5) < 0.0000001).to(beTrue()) expect(weekly.waterPercentage - (-0.3) < 0.0000001).to(beTrue()) done() }).addDisposableTo(disposeBag) interactor.rx_input.onNext() } } } } } }
gpl-3.0
98b1722b260617ea331bebf54ff5c690
50.125
137
0.365526
6.945283
false
false
false
false
lcddhr/DouyuTV
DouyuTV/Vender/DDKit/Color/UIColor+Addition.swift
1
1044
// // UIColor+Addition.swift // DouyuTV // // Created by lovelydd on 16/1/14. // Copyright © 2016年 xiaomutou. All rights reserved. // import Foundation import UIKit func RGB(red:Int16, _ green: Int16, _ blue : Int16, alpha: CGFloat = 1.0) -> UIColor { let color = UIColor.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha); return color } extension UIColor { enum ColorName: UInt32 { case Translucent = 0xffffffcc var color: UIColor { return UIColor(named: self) } } convenience init(named name: ColorName) { let rgbaValue = name.rawValue let red = CGFloat((rgbaValue >> 24) & 0xff) / 255.0 let green = CGFloat((rgbaValue >> 16) & 0xff) / 255.0 let blue = CGFloat((rgbaValue >> 8) & 0xff) / 255.0 let alpha = CGFloat((rgbaValue ) & 0xff) / 255.0 self.init(red: red, green: green, blue: blue, alpha: alpha) } }
mit
74bae7ae8706d51045f5ef8df328024e
24.414634
130
0.572526
3.565068
false
false
false
false
PraveenSakthivel/BRGO-IOS
BRGO/HandbookController.swift
1
2933
// // PlannerController.swift // BRGO // // Created by Praveen Sakthivel on 7/21/16. // Copyright © 2016 TBLE Technologies. All rights reserved. // import UIKit class HandbookController: UIViewController, UIWebViewDelegate { @IBOutlet var browser: UIWebView! override func viewDidLoad() { super.viewDidLoad() browser.delegate = self browser.isOpaque = false browser.backgroundColor = UIColor.clear browser.scalesPageToFit = true let navicon = UIButton(type: UIButtonType.system) navicon.setImage(defaultMenuImage(), for: UIControlState()) navicon.frame = CGRect(x: 0, y: 0, width: 30, height: 30) let menu = UIBarButtonItem(customView: navicon) self.navigationItem.leftBarButtonItem = menu self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) navicon.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside) var pdfLoc: URL! let defaults = UserDefaults.standard switch defaults.object(forKey: "School") as! Int { case 14273: pdfLoc = URL(fileURLWithPath:Bundle.main.path(forResource: "14273Planner", ofType:"pdf")!) case 14274: pdfLoc = URL(fileURLWithPath:Bundle.main.path(forResource: "14274Planner", ofType:"pdf")!) case 14271: pdfLoc = URL(fileURLWithPath:Bundle.main.path(forResource: "14271Planner", ofType:"pdf")!) case 14269: pdfLoc = URL(fileURLWithPath:Bundle.main.path(forResource: "14269Planner", ofType:"pdf")!) case 14268: pdfLoc = URL(fileURLWithPath:Bundle.main.path(forResource: "14264Planner", ofType:"pdf")!) case 14264: pdfLoc = URL(fileURLWithPath:Bundle.main.path(forResource: "14276Planner", ofType:"pdf")!) case 14276: pdfLoc = URL(fileURLWithPath:Bundle.main.path(forResource: "14268Planner", ofType:"pdf")!) default: pdfLoc = URL(fileURLWithPath:Bundle.main.path(forResource: "14273Planner", ofType:"pdf")!) } let request = URLRequest(url: pdfLoc); browser.loadRequest(request); self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
f8cba622efd7807499f13ff4e8685e5e
40.885714
135
0.666439
4.783034
false
false
false
false
leacode/LCYCoreDataHelper
LCYCoreDataHelperExample/LCYCoreDataHelperExample/CoreDataTableViewController.swift
1
2301
// // CoreDataTableViewController.swift // LCYCoreDataHelperExample // // Created by LiChunyu on 16/1/24. // Copyright © 2016年 leacode. All rights reserved. // import UIKit import LCYCoreDataHelper import CoreData class CoreDataTableViewController: LCYCoreDataTVC { override func viewDidLoad() { super.viewDidLoad() let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Product") let sortDescriptor = NSSortDescriptor(key: "productId", ascending: true) let sortDescriptors = [sortDescriptor] fetchRequest.sortDescriptors = sortDescriptors self.frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: globalContext!, sectionNameKeyPath: nil, cacheName: "productCache") self.frc.delegate = self self.performFetch() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "productCellId", for: indexPath as IndexPath) let product: Product = self.frc.object(at: indexPath as IndexPath) as! Product cell.textLabel?.text = product.productName cell.detailTextLabel?.text = product.productIntroduction return cell } @IBAction func addOneProduct(_ sender: AnyObject) { Product.insertCoreDataModel() } @IBAction func deleteLast(_ sender: AnyObject) { if let object = frc.fetchedObjects?.last, let context = globalContext { context.delete(object as! NSManagedObject) do { try coreDataHelper?.backgroundSaveContext() } catch { fatalError("Failure to save context: \(error)") } } } @IBAction func deleteAll(_ sender: AnyObject) { do { try coreDataHelper?.deleteAllExistingObjectOfEntity("Product", ctx: globalContext!) NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: "productCache") try self.frc.performFetch() tableView.reloadData() } catch { } } }
mit
c36ba3c975c9630ec9627d1e9f5e0143
30.479452
163
0.636205
5.604878
false
false
false
false
thachpv91/loafwallet
BreadWallet/BRBitID.swift
3
6877
// // BRBitID.swift // BreadWallet // // Created by Samuel Sutch on 6/17/16. // Copyright © 2016 breadwallet LLC. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Security @objc open class BRBitID : NSObject { static let SCHEME = "bitid" static let PARAM_NONCE = "x" static let PARAM_UNSECURE = "u" static let USER_DEFAULTS_NONCE_KEY = "brbitid_nonces" static let DEFAULT_INDEX: UInt32 = 42 class open func isBitIDURL(_ url: URL!) -> Bool { return url.scheme == SCHEME } open static let BITCOIN_SIGNED_MESSAGE_HEADER = "Bitcoin Signed Message:\n".data(using: String.Encoding.utf8)! open class func formatMessageForBitcoinSigning(_ message: String) -> Data { let data = NSMutableData() data.append(UInt8(BITCOIN_SIGNED_MESSAGE_HEADER.count)) data.append(BITCOIN_SIGNED_MESSAGE_HEADER) let msgBytes = message.data(using: String.Encoding.utf8)! data.appendVarInt(UInt64(msgBytes.count)) data.append(msgBytes) return data as Data } // sign a message with a key and return a base64 representation open class func signMessage(_ message: String, usingKey key: BRKey) -> String { let signingData = formatMessageForBitcoinSigning(message) let signature = key.compactSign((signingData as NSData).sha256_2())! return String(bytes: signature.base64EncodedData(options: []), encoding: String.Encoding.utf8) ?? "" } open let url: URL open var siteName: String { return "\(url.host!)\(url.path)" } public init(url: URL!) { self.url = url } open func newNonce() -> String { let defs = UserDefaults.standard let nonceKey = "\(url.host!)/\(url.path)" var allNonces = [String: [String]]() var specificNonces = [String]() // load previous nonces. we save all nonces generated for each service // so they are not used twice from the same device if let existingNonces = defs.object(forKey: BRBitID.USER_DEFAULTS_NONCE_KEY) { allNonces = existingNonces as! [String: [String]] } if let existingSpecificNonces = allNonces[nonceKey] { specificNonces = existingSpecificNonces } // generate a completely new nonce var nonce: String repeat { nonce = "\(Int(Date().timeIntervalSince1970))" } while (specificNonces.contains(nonce)) // save out the nonce list specificNonces.append(nonce) allNonces[nonceKey] = specificNonces defs.set(allNonces, forKey: BRBitID.USER_DEFAULTS_NONCE_KEY) return nonce } open func runCallback(_ completionHandler: @escaping (Data?, URLResponse?, NSError?) -> Void) { guard let manager = BRWalletManager.sharedInstance() else { DispatchQueue.main.async { completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("No wallet", comment: "")])) } return } autoreleasepool { guard let seed = manager.seed(withPrompt: "", forAmount: 0) else { DispatchQueue.main.async { completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Could not unlock", comment: "")])) } return } let seq = BRBIP32Sequence() var scheme = "https" var nonce: String guard let query = url.query?.parseQueryString() else { DispatchQueue.main.async { completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Malformed URI", comment: "")])) } return } if let u = query[BRBitID.PARAM_UNSECURE] , u.count == 1 && u[0] == "1" { scheme = "http" } if let x = query[BRBitID.PARAM_NONCE] , x.count == 1 { nonce = x[0] // service is providing a nonce } else { nonce = newNonce() // we are generating our own nonce } let uri = "\(scheme)://\(url.host!)\(url.path)" // build a payload consisting of the signature, address and signed uri let priv = BRKey(privateKey: seq.bitIdPrivateKey(BRBitID.DEFAULT_INDEX, forURI: uri, fromSeed: seed)!)! let uriWithNonce = "bitid://\(url.host!)\(url.path)?x=\(nonce)" let signature = BRBitID.signMessage(uriWithNonce, usingKey: priv) let payload: [String: String] = [ "address": priv.address!, "signature": signature, "uri": uriWithNonce ] let json = try! JSONSerialization.data(withJSONObject: payload, options: []) // send off said payload var req = URLRequest(url: URL(string: "\(uri)?x=\(nonce)")!) req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.httpMethod = "POST" req.httpBody = json let session = URLSession.shared session.dataTask(with: req, completionHandler: { (dat: Data?, resp: URLResponse?, err: Error?) in var rerr: NSError? if err != nil { rerr = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "\(err)"]) } completionHandler(dat, resp, rerr) }).resume() } } }
mit
42603777f6a28b0983b1a830a9f62b25
41.975
115
0.60064
4.55666
false
false
false
false
caicai0/ios_demo
load/thirdpart/SwiftKuery/Select.swift
1
17760
/** Copyright IBM Corporation 2016, 2017 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Mark: Select /// The SQL SELECT statement. public struct Select: Query { /// An array of `Field` elements to select. public let fields: [Field]? /// The table to select rows from. public let tables: [Table] /// The SQL WHERE clause containing the filter for rows to retrieve. /// Could be represented with a `Filter` clause or a `String` containing raw SQL. public private (set) var whereClause: QueryFilterProtocol? /// A boolean indicating whether the selected values have to be distinct. /// If true, corresponds to the SQL SELECT DISTINCT statement. public private (set) var distinct = false /// The number of rows to select. /// If specified, corresponds to the SQL SELECT TOP/LIMIT clause. public private (set) var rowsToReturn: Int? /// The number of rows to skip. /// If specified, corresponds to the SQL SELECT OFFSET clause. public private (set) var offset: Int? /// An array containing `OrderBy` elements to sort the selected rows. /// The SQL ORDER BY keyword. public private (set) var orderBy: [OrderBy]? /// An array containing `Column` elements to group the selected rows. /// The SQL GROUP BY statement. public private (set) var groupBy: [Column]? /// The SQL HAVING clause containing the filter for the rows to select when aggregate functions are used. /// Could be represented with a `Having` clause or a `String` containing raw SQL. public private (set) var havingClause: QueryHavingProtocol? /// The SQL UNION clauses. public private (set) var unions: [Union]? /// The SQL JOIN, ON and USING clauses. /// ON clause can be represented as `Filter` or a `String` containing raw SQL. /// USING clause: an array of `Column` elements that have to match in a JOIN query. public private (set) var joins = [(join: Join, on: QueryFilterProtocol?, using: [Column]?)]() /// An array of `AuxiliaryTable` which will be used in a query with a WITH clause. public private (set) var with: [AuxiliaryTable]? private var syntaxError = "" /// Initialize an instance of Select. /// /// - Parameter fields: A list of `Field` elements to select. /// - Parameter from table: The table to select from. public init(_ fields: Field..., from table: Table) { self.fields = fields self.tables = [table] } /// Initialize an instance of Select. /// /// - Parameter fields: An array of `Field` elements to select. /// - Parameter from table: The table(s) to select from. public init(_ fields: [Field], from table: Table...) { self.fields = fields self.tables = table } /// Initialize an instance of Select. /// /// - Parameter fields: A list of `Field` elements to select. /// - Parameter from table: An array of tables to select from. public init(_ fields: Field..., from tables: [Table]) { self.fields = fields self.tables = tables } /// Initialize an instance of Select. /// /// - Parameter fields: An array of `Field` elements to select. /// - Parameter from table: An array of tables to select from. public init(fields: [Field], from tables: [Table]) { self.fields = fields self.tables = tables } /// Build the query using `QueryBuilder`. /// /// - Parameter queryBuilder: The QueryBuilder to use. /// - Returns: A String representation of the query. /// - Throws: QueryError.syntaxError if query build fails. public func build(queryBuilder: QueryBuilder) throws -> String { var syntaxError = self.syntaxError if groupBy == nil && havingClause != nil { syntaxError += "Having clause is not allowed without a group by clause. " } if syntaxError != "" { throw QueryError.syntaxError(syntaxError) } var result = "" if let with = with { result += "WITH " + "\(try with.map { try $0.buildWith(queryBuilder: queryBuilder) }.joined(separator: ", "))" + " " } result += "SELECT " if distinct { result += "DISTINCT " } if let fields = fields, fields.count != 0 { result += try "\(fields.map { try $0.build(queryBuilder: queryBuilder) }.joined(separator: ", "))" } else { result += "*" } result += " FROM " result += try "\(tables.map { try $0.build(queryBuilder: queryBuilder) }.joined(separator: ", "))" for item in joins { result += try item.join.build(queryBuilder: queryBuilder) if let on = item.on { result += try " ON " + on.build(queryBuilder: queryBuilder) } if let using = item.using { result += " USING (" + using.map { $0.name }.joined(separator: ", ") + ")" } } if let whereClause = whereClause { result += try " WHERE " + whereClause.build(queryBuilder: queryBuilder) } if let groupClause = groupBy { result += try " GROUP BY " + groupClause.map { try $0.build(queryBuilder: queryBuilder) }.joined(separator: ", ") } if let havingClause = havingClause { result += try " HAVING " + havingClause.build(queryBuilder: queryBuilder) } if let orderClause = orderBy { result += try " ORDER BY " + orderClause.map { try $0.build(queryBuilder: queryBuilder) }.joined(separator: ", ") } if let rowsToReturn = rowsToReturn { result += " LIMIT \(rowsToReturn)" } if let offset = offset { if rowsToReturn == nil { throw QueryError.syntaxError("Offset requires a limit to be set. ") } result += " OFFSET \(offset)" } if let unions = unions, unions.count != 0 { for union in unions { result += try union.build(queryBuilder: queryBuilder) } } result = Utils.updateParameterNumbers(query: result, queryBuilder: queryBuilder) return result } /// Create a SELECT DISTINCT query. /// /// - Parameter fields: A list of `Field`s to select. /// - Parameter from: The table to select from. /// - Returns: A new instance of Select with `distinct` flag set. public static func distinct(_ fields: Field..., from table: Table) -> Select { var selectQuery = Select(fields, from: table) selectQuery.distinct = true return selectQuery } /// Create a SELECT DISTINCT query. /// /// - Parameter fields: An array of `Field`s to select. /// - Parameter from table: The table to select from. /// - Returns: A new instance of Select with `distinct` flag set. public static func distinct(_ fields: [Field], from table: Table...) -> Select { var selectQuery = Select(fields: fields, from: table) selectQuery.distinct = true return selectQuery } /// Create a SELECT DISTINCT query. /// /// - Parameter fields: A list of `Field`s to select. /// - Parameter from: An array of tables to select from. /// - Returns: A new instance of Select with `distinct` flag set. public static func distinct(_ fields: Field..., from tables: [Table]) -> Select { var selectQuery = Select(fields: fields, from: tables) selectQuery.distinct = true return selectQuery } /// Create a SELECT DISTINCT query. /// /// - Parameter fields: An array of `Field`s to select. /// - Parameter from: An array of tables to select from. /// - Returns: A new instance of Select with `distinct` flag set. public static func distinct(fields: [Field], from tables: [Table]) -> Select { var selectQuery = Select(fields: fields, from: tables) selectQuery.distinct = true return selectQuery } /// Add the HAVING clause to the query. /// /// - Parameter clause: The `Having` clause or a `String` containing SQL HAVING clause to apply. /// - Returns: A new instance of Select with the `Having` clause. public func having(_ clause: QueryHavingProtocol) -> Select { var new = self if havingClause != nil { new.syntaxError += "Multiple having clauses. " } else { new.havingClause = clause } return new } /// Add the ORDER BY keyword to the query. /// /// - Parameter by: A list of the `OrderBy` to apply. /// - Returns: A new instance of Select with the ORDER BY keyword. public func order(by clause: OrderBy...) -> Select { return order(by: clause) } /// Add the ORDER BY keyword to the query. /// /// - Parameter by: An array of the `OrderBy` to apply. /// - Returns: A new instance of Select with the ORDER BY keyword. public func order(by clause: [OrderBy]) -> Select { var new = self if orderBy != nil { new.syntaxError += "Multiple order by clauses. " } else { new.orderBy = clause } return new } /// Add the GROUP BY clause to the query. /// /// - Parameter by: A list of `Column`s to group by. /// - Returns: A new instance of Select with the GROUP BY clause. public func group(by clause: Column...) -> Select { return group(by: clause) } /// Add the GROUP BY clause to the query. /// /// - Parameter by: A list of `Column`s to group by. /// - Returns: A new instance of Select with the GROUP BY clause. public func group(by clause: [Column]) -> Select { var new = self if groupBy != nil { new.syntaxError += "Multiple group by clauses. " } else { new.groupBy = clause } return new } /// Add the LIMIT/TOP clause to the query. /// /// - Parameter to: The limit of the number of rows to select. /// - Returns: A new instance of Select with the LIMIT clause. public func limit(to newLimit: Int) -> Select { var new = self if rowsToReturn != nil { new.syntaxError += "Multiple limits. " } else { new.rowsToReturn = newLimit } return new } /// Add the OFFSET clause to the query. /// /// - Parameter to: The number of rows to skip. /// - Returns: A new instance of Select with the OFFSET clause. public func offset(_ offset: Int) -> Select { var new = self if new.offset != nil { new.syntaxError += "Multiple offsets. " } else { new.offset = offset } return new } /// Add an SQL WHERE clause to the select statement. /// /// - Parameter conditions: The `Filter` clause or a `String` containing SQL WHERE clause to apply. /// - Returns: A new instance of Select with the WHERE clause. public func `where`(_ conditions: QueryFilterProtocol) -> Select { var new = self if whereClause != nil { new.syntaxError += "Multiple where clauses. " } else { new.whereClause = conditions } return new } /// Add an SQL ON clause to the JOIN statement. /// /// - Parameter conditions: The `Filter` clause or a `String` containing SQL ON clause to apply. /// - Returns: A new instance of Select with the ON clause. public func on(_ conditions: QueryFilterProtocol) -> Select { var new = self guard new.joins.count > 0 else { new.syntaxError += "On clause set for statement that is not join. " return new } if new.joins.last?.on != nil { new.syntaxError += "Multiple on clauses for a single join." } else if new.joins.last?.using != nil { new.syntaxError += "An on clause is not allowed with a using clause for a single join." } else { new.joins[new.joins.count - 1].on = conditions } return new } /// Add an SQL USING clause to the JOIN statement. /// /// - Parameter columns: A list of `Column`s to match in the JOIN statement. /// - Returns: A new instance of Select with the USING clause. public func using(_ columns: Column...) -> Select { return using(columns) } /// Add an SQL USING clause to the JOIN statement. /// /// - Parameter columns: An array of `Column`s to match in the JOIN statement. /// - Returns: A new instance of Select with the USING clause. public func using(_ columns: [Column]) -> Select { var new = self guard new.joins.count > 0 else { new.syntaxError += "Using clause set for statement that is not join. " return new } if new.joins.last?.using != nil { new.syntaxError += "Multiple using clauses for a single join." } else if new.joins.last?.on != nil { new.syntaxError += "A using clause is not allowed with an on clause for single join." } else { new.joins[new.joins.count - 1].using = columns } return new } /// Create an SQL SELECT UNION statement. /// /// - Parameter table: The second Select query used in performing the union. /// - Returns: A new instance of Select corresponding to the SELECT UNION. public func union(_ query: Select) -> Select { var new = self if unions == nil { new.unions = [Union]() } new.unions!.append(.union(query)) return new } /// Create an SQL SELECT UNION ALL statement. /// /// - Parameter table: The second Select query used in performing the union. /// - Returns: A new instance of Select corresponding to the SELECT UNION ALL. public func unionAll(_ query: Select) -> Select { var new = self if unions == nil { new.unions = [Union]() } new.unions!.append(.unionAll(query)) return new } /// Create an SQL SELECT INNER JOIN statement. /// /// - Parameter table: The right table used in performing the join. The left table is the table field of this `Select` instance. /// - Returns: A new instance of Select corresponding to the SELECT INNER JOIN. public func join(_ table: Table) -> Select { var new = self new.joins.append((.join(table), nil, nil)) return new } /// Create an SQL SELECT LEFT JOIN statement. /// /// - Parameter table: The right table used in performing the join. The left table is the table field of this `Select` instance. /// - Returns: A new instance of Select corresponding to the SELECT LEFT JOIN. public func leftJoin(_ table: Table) -> Select { var new = self new.joins.append((.left(table), nil, nil)) return new } /// Create an SQL SELECT CROSS JOIN statement. /// /// - Parameter table: The right table used in performing the join. The left table is the table field of this `Select` instance. /// - Returns: A new instance of Select corresponding to the SELECT CROSS JOIN. public func crossJoin(_ table: Table) -> Select { var new = self new.joins.append((.cross(table), nil, nil)) return new } /// Create an SQL SELECT NATURAL JOIN statement. /// /// - Parameter table: The right table used in performing the join. The left table is the table field of this `Select` instance. /// - Returns: A new instance of Select corresponding to the SELECT NATURAL JOIN. public func naturalJoin(_ table: Table) -> Select { var new = self new.joins.append((.natural(table), nil, nil)) return new } /// Create a join statement with the type of join specified in the String. /// /// - Parameter raw: A String containg a join to apply. /// - Parameter table: The right table used in performing the join. The left table is the table field of this `Select` instance. /// - Returns: A new instance of Select corresponding to the join. public func rawJoin(_ raw: String, _ table: Table) -> Select { var new = self new.joins.append((.raw(raw, table), nil, nil)) return new } /// Set tables to be used for WITH clause. /// /// - Parameter tables: A list of the `AuxiliaryTable` to apply. /// - Returns: A new instance of Select with tables for WITH clause. func with(_ tables: [AuxiliaryTable]) -> Select { var new = self if new.with != nil { new.syntaxError += "Multiple with clauses. " } else { new.with = tables } return new } }
mit
5166cd708894edeb607fc77ab542dabd
35.244898
132
0.589302
4.596273
false
false
false
false
vsujan92/SVValidator
SVValidator/Util/Validator/CharactetSet.swift
1
995
// // CharactetSet.swift // Login // // Created by Sujan Vaidya on 7/24/17. // Copyright © 2017 Sujan Vaidya. All rights reserved. // import UIKit public protocol CharacterSetValidator: Validator { var characterCase: CharacterSet { get } var error: Error { get } } public extension CharacterSetValidator { func validate<T>(_ value: T) -> ValidationResult<T> { guard let stringValue = value as? String else { return .error(nil) } return stringValue.rangeOfCharacter(from: characterCase) != nil ? .ok(value) : .error(error) } } public protocol CharacterSetExclusiveValidator: Validator { var characterCase: CharacterSet { get } var error: Error { get } } public extension CharacterSetExclusiveValidator { func validate<T>(_ value: T) -> ValidationResult<T> { guard let stringValue = value as? String else { return .error(nil) } return stringValue.rangeOfCharacter(from: characterCase) == nil ? .ok(value) : .error(error) } }
mit
b735820b72043f4e9b14e33613dabf79
24.487179
72
0.689135
3.823077
false
false
false
false
karstengresch/rw_studies
SBLoader - Starter/SBLoader/ViewController.swift
1
2174
// // ViewController.swift // SBLoader // // Created by Satraj Bambra on 2015-03-16. // Copyright (c) 2015 Satraj Bambra. All rights reserved. // import UIKit class ViewController: UIViewController, HolderViewDelegate { var holderView = HolderView(frame: CGRectZero) override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) addHolderView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func addHolderView() { let boxSize: CGFloat = 100.0 holderView.frame = CGRect(x: view.bounds.width / 2 - boxSize / 2, y: view.bounds.height / 2 - boxSize / 2, width: boxSize, height: boxSize) holderView.parentFrame = view.frame holderView.delegate = self view.addSubview(holderView) holderView.addOval() } func animateLabel() { holderView.removeFromSuperview() view.backgroundColor = Colors.blue let label = UILabel(frame: view.frame) label.textColor = Colors.white label.font = UIFont(name: "HelveticaNeue-Thin", size: 170.0) label.textAlignment = NSTextAlignment.Center label.text = "G" label.transform = CGAffineTransformScale(label.transform, 0.25, 0.25) view.addSubview(label) UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.CurveEaseInOut, animations: ( { label.transform = CGAffineTransformScale(label.transform, 4.0, 4.0) } ), completion: { finished in self.addButton() }) } func addButton() { let button = UIButton() button.frame = CGRectMake(0.0, 0.0, view.bounds.width, view.bounds.height) button.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside) view.addSubview(button) } func buttonPressed(sender: UIButton!) { view.backgroundColor = Colors.white view.subviews.forEach({ $0.removeFromSuperview() }) holderView = HolderView(frame: CGRectZero) addHolderView() } }
unlicense
5652af3268214708b9a5dddc3b55b594
27.986667
287
0.665593
4.339321
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/path-sum.swift
2
1519
/** * https://leetcode.com/problems/path-sum/ * * */ // Date: Thu May 21 11:42:30 PDT 2020 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ /// - Complexity: /// - Time: O(n), n is the number of nodes in the tree. /// - Space: O(n), n is the number of nodes in the tree. /// class Solution { func hasPathSum(_ root: TreeNode?, _ sum: Int) -> Bool { guard let root = root else { return false } var nodeQueue = [root] var sumQueue = [root.val] while nodeQueue.isEmpty == false { let node = nodeQueue.removeFirst() let sumtmp = sumQueue.removeFirst() if node.left == nil, node.right == nil, sumtmp == sum { return true } if let left = node.left { nodeQueue.append(left) sumQueue.append(sumtmp + left.val) } if let right = node.right { nodeQueue.append(right) sumQueue.append(sumtmp + right.val) } } return false } }
mit
62701888abe5b28d7e78c12058ff87ad
30
85
0.518104
3.723039
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01677-swift-dependentmembertype-get.swift
7
1851
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse ] == 1) func a<A? { func a(object1, V, (T] { init(() -> Any] == 1]() assert(T> Any, U>(.<c<f = compose<T.c where Optional<D>Bool)] as String): A" func a) let n1: Collection where f: b: l.endIndex - range..b(b(i> { protocol a { } } struct c, U, let start = { let foo as a: T: [0 func b> String func compose<T>(self, x in a { } })? () extension String = Swift.B } } (c } var b> T : (b: T) { func f) enum B == Int>: () -> e() -> T : A<T where H.startIndex) return p: String)!.startIndex) } } class a: Int { class A) -> String { print() } f: a { d } } func c(c: ()) init()() import Foundation typealias F>](.c : b(b[c return p return [Any) { i() protocol a { typealias e { class d() -> { var b: A, A : d : d = { typealias f = { self.h : T, () { c struct A.dynamicType) import Foundation class func i(T>(a) let end = B } private class A, B protocol b { func e: (""")) -> String = b<T class b: d = [Int>? = T>] { } struct A { protocol b { f) } print(T> func f.h : d = true { } } } } func a: String func f<c] struct c, i : b() -> Any) -> { map("foo"foobar" self[1) } typealias f == g<U) { struct B, d>() convenience init() -> U, k : a { typealias C { } protocol A { var a"" return { _, g = Int }(c) -> : T>(f() -> (z: Boolean>(m(v: Int>()] = { c } typealias e : NSObject { let n1: 1], let g == Swift.join(h, Bool) -> (g.endIndex - range.lowerBound)) func f()) class A? { } typealias F>(g..substringWithRange(") } func i<Q<T, e: S() -> String { } var f = b.init(t: H
apache-2.0
f192d84539581519319cc9fef9b72f38
16.970874
78
0.596975
2.614407
false
false
false
false
ibru/Swifter
Swifter/SwifterSavedSearches.swift
2
3905
// // SwifterSavedSearches.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Swifter { /* GET saved_searches/list Returns the authenticated user's saved search queries. */ public func getSavedSearchesListWithSuccess(success: ((savedSearches: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) { let path = "saved_searches/list.json" self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(savedSearches: json.array) return }, failure: failure) } /* GET saved_searches/show/:id Retrieve the information for the saved search represented by the given id. The authenticating user must be the owner of saved search ID being requested. */ public func getSavedSearchesShowWithID(id: String, success: ((savedSearch: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) { let path = "saved_searches/show/\(id).json" self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(savedSearch: json.object) return }, failure: failure) } /* POST saved_searches/create Create a new saved search for the authenticated user. A user may only have 25 saved searches. */ public func postSavedSearchesCreateShowWithQuery(query: String, success: ((savedSearch: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) { let path = "saved_searches/create.json" var parameters = Dictionary<String, Any>() parameters["query"] = query self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(savedSearch: json.object) return }, failure: failure) } /* POST saved_searches/destroy/:id Destroys a saved search for the authenticating user. The authenticating user must be the owner of saved search id being destroyed. */ public func postSavedSearchesDestroyWithID(id: String, success: ((savedSearch: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) { let path = "saved_searches/destroy/\(id).json" self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(savedSearch: json.object) return }, failure: failure) } }
mit
ea5c44fb08849d3dcd56087c2f713389
37.663366
174
0.677593
4.621302
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/AutoLayout/TextViewSelfsizingController.swift
1
2596
// // TextViewSelfsizing.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/12/23. // Copyright © 2017年 伯驹 黄. All rights reserved. // class TextViewSelfsizingCell: UITableViewCell, Reusable { private lazy var textView: UITextView = { let textView = UITextView() textView.translatesAutoresizingMaskIntoConstraints = false textView.delegate = self textView.isScrollEnabled = false return textView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none contentView.addSubview(textView) textView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15).isActive = true textView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true textView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true textView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TextViewSelfsizingCell: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { let vc: TextViewSelfsizingController? = viewController() let currentOffset = vc!.tableView.contentOffset UIView.setAnimationsEnabled(false) vc?.tableView.beginUpdates() vc?.tableView.endUpdates() UIView.setAnimationsEnabled(true) vc?.tableView.setContentOffset(currentOffset, animated: false) } } class TextViewSelfsizingController: AutoLayoutBaseController { fileprivate lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.frame, style: .grouped) tableView.dataSource = self tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 100 tableView.register(TextViewSelfsizingCell.self, forCellReuseIdentifier: "cell") return tableView }() override func initSubviews() { view.addSubview(tableView) } } extension TextViewSelfsizingController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) } }
mit
03fbb39fae4f17255111959c8899599d
33.878378
110
0.712515
5.422269
false
false
false
false
huonw/swift
stdlib/public/SDK/Metal/Metal.swift
1
9983
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Metal // Clang module @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLBlitCommandEncoder { public func fill(buffer: MTLBuffer, range: Range<Int>, value: UInt8) { __fill(buffer, range: NSRange(location: range.lowerBound, length: range.count), value: value) } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLBuffer { #if os(macOS) @available(macOS, introduced: 10.11) public func didModifyRange(_ range: Range<Int>) { __didModifyRange(NSRange(location: range.lowerBound, length: range.count)) } #endif @available(macOS 10.12, iOS 10.0, tvOS 10.0, *) public func addDebugMarker(_ marker: String, range: Range<Int>) { __addDebugMarker(marker, range: NSRange(location: range.lowerBound, length: range.count)) } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLComputeCommandEncoder { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) { __use(resources, count: resources.count, usage: usage) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useHeaps(_ heaps: [MTLHeap]) { __use(heaps, count: heaps.count) } public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } public func setSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) public func memoryBarrier(_ resources:[MTLResource]) { __memoryBarrier(resources: resources, count: resources.count) } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLDevice { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func getDefaultSamplePositions(sampleCount: Int) -> [MTLSamplePosition] { var positions = [MTLSamplePosition](repeating: MTLSamplePosition(x: 0,y: 0), count: sampleCount) __getDefaultSamplePositions(&positions, count: sampleCount) return positions } } #if os(macOS) @available(swift 4) @available(macOS 10.13, *) public func MTLCopyAllDevicesWithObserver(handler: @escaping MTLDeviceNotificationHandler) -> (devices:[MTLDevice], observer:NSObject) { var resultTuple: (devices:[MTLDevice], observer:NSObject) resultTuple.observer = NSObject() resultTuple.devices = __MTLCopyAllDevicesWithObserver(AutoreleasingUnsafeMutablePointer<NSObjectProtocol?>(&resultTuple.observer), handler) return resultTuple } #endif @available(macOS 10.12, iOS 10.0, tvOS 10.0, *) extension MTLFunctionConstantValues { public func setConstantValues(_ values: UnsafeRawPointer, type: MTLDataType, range: Range<Int>) { __setConstantValues(values, type: type, with: NSRange(location: range.lowerBound, length: range.count)) } } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) extension MTLArgumentEncoder { public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLRenderCommandEncoder { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) { __use(resources, count: resources.count, usage: usage) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useHeaps(_ heaps: [MTLHeap]) { __use(heaps, count: heaps.count) } #if os(macOS) @available(macOS 10.13, *) public func setViewports(_ viewports: [MTLViewport]) { __setViewports(viewports, count: viewports.count) } @available(macOS 10.13, *) public func setScissorRects(_ scissorRects: [MTLScissorRect]) { __setScissorRects(scissorRects, count: scissorRects.count) } #endif public func setVertexBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setVertexBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setVertexTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setVertexTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setVertexSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setVertexSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setFragmentBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setFragmentTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setFragmentSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setFragmentSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } #if os(iOS) @available(iOS 11.0, *) public func setTileBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setTileBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } @available(iOS 11.0, *) public func setTileTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setTileTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } @available(iOS 11.0, *) public func setTileSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setTileSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } @available(iOS 11.0, *) public func setTileSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setTileSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } #endif #if os(macOS) @available(macOS 10.14, *) public func memoryBarrier(_ resources: [MTLResource], after: MTLRenderStages, before: MTLRenderStages) { __memoryBarrier(resources: resources, count: resources.count, after: after, before: before) } #endif } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLRenderPassDescriptor { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func setSamplePositions(_ positions: [MTLSamplePosition]) { __setSamplePositions(positions, count: positions.count) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func getSamplePositions() -> [MTLSamplePosition] { let numPositions = __getSamplePositions(nil, count: 0) var positions = [MTLSamplePosition](repeating: MTLSamplePosition(x: 0,y: 0), count: numPositions) __getSamplePositions(&positions, count: numPositions) return positions } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLTexture { @available(macOS 10.11, iOS 9.0, tvOS 9.0, *) public func makeTextureView(pixelFormat: MTLPixelFormat, textureType: MTLTextureType, levels levelRange: Range<Int>, slices sliceRange: Range<Int>) -> MTLTexture? { return __newTextureView(with: pixelFormat, textureType: textureType, levels: NSRange(location: levelRange.lowerBound, length: levelRange.count), slices: NSRange(location: sliceRange.lowerBound, length: sliceRange.count)) } }
apache-2.0
47e5302ef3da504c4c3e27e8b2096d6f
41.662393
228
0.677852
4.224714
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Setting/YellowPage/PhoneBook.swift
1
7108
// // PhoneBook.swift // WePeiYang // // Created by Halcao on 2017/4/8. // Copyright © 2017年 twtstudio. All rights reserved. // import UIKit let YELLOWPAGE_SAVE_KEY = "YellowPageItems" class PhoneBook: NSObject { static let shared = PhoneBook() private override init() {} static let url = "http://open.twtstudio.com/api/v1/yellowpage/data3" var favorite: [ClientItem] = [] var sections: [String] = [] var members: [String: [String]] = [:] var items: [ClientItem] = [] // given a name, return its phone number func getPhoneNumber(with string: String) -> String? { for item in items { if item.name.containsString(string) { return item.phone } } return nil } // get members with section func getMembers(with section: String) -> [String] { guard let dict = members[section] else { return [] } return dict } func addToFavorite(with name: String, success: ()->()) { for item in items { if item.name == name { item.isFavorite = true favorite.append(item) success() return } } } func removeFromFavorite(with name: String, success: ()->()) { for item in items { if item.name == name { item.isFavorite = false break } } favorite = favorite.filter { item in return name != item.name } success() } // get models with member name func getModels(with member: String) -> [ClientItem] { return items.filter { item in return item.owner == member } } // seach result func getResult(with string: String) -> [ClientItem] { return items.filter { item in return item.name.containsString(string) } } static func checkVersion(success: ()->()) { let manager = AFHTTPSessionManager() manager.responseSerializer.acceptableContentTypes?.insert("text/json") manager.responseSerializer.acceptableContentTypes?.insert("text/javascript") manager.responseSerializer.acceptableContentTypes?.insert("text/html") manager.GET(PhoneBook.url, parameters: nil, progress: nil, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) in // guard let dict = responseObject as? Dictionary<String, AnyObject> else { MsgDisplay.showErrorMsg("身份认证失败") return } if let categories = dict["category_list"] as? Array<Dictionary<String, AnyObject>> { for category in categories { let category_name = category["category_name"] as! String PhoneBook.shared.sections.append(category_name) if let departments = category["department_list"] as? Array<Dictionary<String, AnyObject>>{ for department in departments { let department_name = department["department_name"] as! String if PhoneBook.shared.members[category_name] != nil { PhoneBook.shared.members[category_name]!.append(department_name) } else { PhoneBook.shared.members[category_name] = [department_name] } let items = department["unit_list"] as! Array<Dictionary<String, String>> for item in items { let item_name = item["item_name"] let item_phone = item["item_phone"] PhoneBook.shared.items.append(ClientItem(with: item_name!, phone: item_phone!, owner: department_name)) } } } } } PhoneBook.shared.save() success() }, failure: { (_, error) in log.error(error)/ MsgDisplay.showErrorMsg("身份认证失败") }) } private func request() { } } extension PhoneBook { func save() { let path = self.dataFilePath() //声明文件管理器 let defaultManager = NSFileManager() if defaultManager.fileExistsAtPath(path) { try! defaultManager.removeItemAtPath(path) } let data = NSMutableData() //申明一个归档处理对象 let archiver = NSKeyedArchiver(forWritingWithMutableData: data) //将lists以对应Checklist关键字进行编码 archiver.encodeObject(PhoneBook.shared.items, forKey: YELLOWPAGE_SAVE_KEY) archiver.encodeObject(PhoneBook.shared.members, forKey: "yp_member_key") archiver.encodeObject(PhoneBook.shared.sections, forKey: "yp_section_key") archiver.encodeObject(PhoneBook.shared.favorite, forKey: "yp_favorite_key") //编码结束 archiver.finishEncoding() //数据写入 data.writeToFile(dataFilePath(), atomically: true) } //读取数据 func load(success: ()->(), failure: ()->()) { //获取本地数据文件地址 let path = self.dataFilePath() //声明文件管理器 let defaultManager = NSFileManager() //通过文件地址判断数据文件是否存在 if defaultManager.fileExistsAtPath(path) { //读取文件数据 let url = NSURL(fileURLWithPath: path) let data = NSData(contentsOfURL: url) //解码器 let unarchiver = NSKeyedUnarchiver(forReadingWithData: data!) //通过归档时设置的关键字Checklist还原lists if let array = unarchiver.decodeObjectForKey(YELLOWPAGE_SAVE_KEY) as? Array<ClientItem>, let favorite = unarchiver.decodeObjectForKey("yp_favorite_key") as? Array<ClientItem>, let members = unarchiver.decodeObjectForKey("yp_member_key") as? [String: [String]], let sections = unarchiver.decodeObjectForKey("yp_section_key") as? [String] { guard array.count > 0 else { failure() return } PhoneBook.shared.favorite = favorite PhoneBook.shared.members = members PhoneBook.shared.sections = sections PhoneBook.shared.items = array unarchiver.finishDecoding() success() return } //结束解码 } failure() } //获取数据文件地址 func dataFilePath() -> String{ let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let documentsDirectory = paths.first! return documentsDirectory + "/YellowPage.plist" } }
mit
1215f0b36dbb4d1d6972eaacb2a74678
34.765625
137
0.547692
5.049265
false
false
false
false
snailjj/iOSDemos
SnailSwiftDemos/SnailSwiftDemos/Foundations/ViewControllers/CFetchResultViewController.swift
2
5495
// // CFetchResultViewController.swift // SnailSwiftDemos // // Created by Jian Wu on 2017/7/13. // Copyright © 2017年 Snail. All rights reserved. // 迁移管理器迁移数据 import UIKit import CoreData class CFetchResultViewController: CustomViewController,NSFetchedResultsControllerDelegate,UITableViewDelegate,UITableViewDataSource { var fetchResultsController : NSFetchedResultsController<NSFetchRequestResult>! var data : [Person] = [Person]() @IBOutlet weak var aTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.rightBtn.isHidden = false getRequest() } func getRequest() { let manager = CoreDataManager.shared let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person") // request.predicate = NSPredicate(format: "name like \"1*\"") //按照uid升序排列 let sortDescription = NSSortDescriptor(key: "age", ascending: true) //升序 request.sortDescriptors = [sortDescription] /* 初始化fetchResultController request : 请求对象 managedObjectContext : 上下文,操作数据的对象 sectionNameKeyPath : 分组依据,可为空 cacheName : 关于什么缓存的??没搞明白 **/ self.fetchResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: manager.managedObjectContext!, sectionNameKeyPath: "age", cacheName: nil) //开始查询数据 do { try fetchResultsController.performFetch() }catch { print(error.localizedDescription) } self.fetchResultsController.delegate = self self.aTableView.reloadData() } //MARK : - 添加一条数据测试用 override func rightAction() { super.rightAction() let coreDataManager = CoreDataManager.shared let person = Person(entity: NSEntityDescription.entity(forEntityName: "Person", in: coreDataManager.managedObjectContext!)!, insertInto: nil) person.uid = Int64(NSDate().timeIntervalSince1970) person.name = "Snail" person.age = Int64(arc4random() % 100) person.headImage = UIImage(named: "greymine")?.imageData() as! NSData if coreDataManager.create(model: person) { print("保存成功") } else { print("保存失败") } } //MARK: - NSFetchResultsControllerDelegate methods func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { print("数据即将改变的时候") } /* public enum NSFetchedResultsChangeType : UInt { case insert 1 case delete 2 case move 3 case update 4 } */ func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { print("具体哪个对象要改变:\(anObject),具体要做什么改变\(indexPath),增删改还是重新排序:\(type.rawValue),以及受影响的模块是谁\(newIndexPath),这个方法紧紧连接这tableView和CoreData") } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { print("结束了,刷新数据") do { try fetchResultsController.performFetch() }catch { print(error.localizedDescription) } aTableView.reloadData() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { print("分组变化了:\(type)") } //MARK: - UITableViewDelegate methods func numberOfSections(in tableView: UITableView) -> Int { if self.fetchResultsController != nil { //分多少组 let sections = self.fetchResultsController.sections return (sections?.count)! } return 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sections = self.fetchResultsController.sections //TODO: 每组里有多少个数据 let sectionInfo = sections?[section] return (sectionInfo?.numberOfObjects)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "FetchCell") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "FetchCell") } cell?.selectionStyle = .none let person = fetchResultsController.object(at: indexPath) as! Person cell?.imageView?.image = UIImage(data: person.headImage as! Data) cell?.textLabel?.text = person.name cell?.detailTextLabel?.text = "\(person.age)" return cell! } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.000001 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 20 } }
apache-2.0
e83f7edb140b5a6981181de80b6e1ad7
33.198675
209
0.645043
5.323711
false
false
false
false
1457792186/JWSwift
SwiftWX/LGWeChatKit/LGChatKit/conversionList/view/LGConversionListCell.swift
1
3983
// // LGConversionListCell.swift // LGChatViewController // // Created by jamy on 10/19/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit class LGConversionListCell: LGConversionListBaseCell { let iconView: UIImageView! let userNameLabel: UILabel! let messageLabel: UILabel! let timerLabel: UILabel! let messageListCellHeight = 64 var viewModel: LGConversionListCellModel? { didSet { viewModel?.iconName.observe { [unowned self] in self.iconView.image = UIImage(named: $0) } viewModel?.lastMessage.observe { [unowned self] in self.messageLabel.text = $0 } viewModel?.userName.observe { [unowned self] in self.userNameLabel.text = $0 } viewModel?.timer.observe { [unowned self] in self.timerLabel.text = $0 } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { iconView = UIImageView(frame: CGRect(x: 5, y: CGFloat(messageListCellHeight - 50) / 2, width: 50, height: 50)) iconView.layer.cornerRadius = 5.0 iconView.layer.masksToBounds = true userNameLabel = UILabel() userNameLabel.textAlignment = .left userNameLabel.font = UIFont.systemFont(ofSize: 14.0) messageLabel = UILabel() messageLabel.textAlignment = .left messageLabel.font = UIFont.systemFont(ofSize: 13.0) messageLabel.textColor = UIColor.lightGray timerLabel = UILabel() timerLabel.textAlignment = .right timerLabel.font = UIFont.systemFont(ofSize: 14.0) timerLabel.textColor = UIColor.lightGray super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(iconView) contentView.addSubview(userNameLabel) contentView.addSubview(messageLabel) contentView.addSubview(timerLabel) userNameLabel.translatesAutoresizingMaskIntoConstraints = false messageLabel.translatesAutoresizingMaskIntoConstraints = false timerLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addConstraint(NSLayoutConstraint(item: userNameLabel, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: CGFloat(messageListCellHeight + 8))) contentView.addConstraint(NSLayoutConstraint(item: userNameLabel, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 5)) contentView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .left, relatedBy: .equal, toItem: userNameLabel, attribute: .left, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .top, relatedBy: .equal, toItem: userNameLabel, attribute: .bottom, multiplier: 1, constant: 10)) contentView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -70)) contentView.addConstraint(NSLayoutConstraint(item: timerLabel, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -65)) contentView.addConstraint(NSLayoutConstraint(item: timerLabel, attribute: .top, relatedBy: .equal, toItem: userNameLabel, attribute: .top, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: timerLabel, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -5)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
b969c33e87f169b2e6fe903bf4e8bb91
42.282609
211
0.658714
5.212042
false
false
false
false
apple/swift-syntax
Sources/SwiftParser/CharacterInfo.swift
1
3108
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension Character { fileprivate struct Info: OptionSet { var rawValue: UInt8 init(rawValue: UInt8) { self.rawValue = rawValue } static let IDENT_START: Self = .init(rawValue: 0x01) static let IDENT_CONT: Self = .init(rawValue: 0x02) static let DECIMAL: Self = .init(rawValue: 0x04) static let HEX: Self = .init(rawValue: 0x08) static let LETTER: Self = .init(rawValue: 0x10) } } extension Unicode.Scalar { var isASCII: Bool { return self.value <= 127 } /// A Boolean value indicating whether this scalar is one which is recommended /// to be allowed to appear in a starting position in a programming language /// identifier. var isAsciiIdentifierStart: Bool { self.testCharacterInfo(.IDENT_START) } /// A Boolean value indicating whether this scalar is one which is recommended /// to be allowed to appear in a non-starting position in a programming /// language identifier. var isAsciiIdentifierContinue: Bool { self.testCharacterInfo(.IDENT_CONT) } /// A Boolean value indicating whether this scalar is an ASCII character used /// for the representation of base-10 numbers. var isDigit: Bool { self.testCharacterInfo(.DECIMAL) } /// A Boolean value indicating whether this scalar is considered to be either /// an uppercase or lowercase ASCII character. var isLetter: Bool { self.testCharacterInfo(.LETTER) } /// A Boolean value indicating whether this scalar is an ASCII character /// commonly used for the representation of hexadecimal numbers. var isHexDigit: Bool { self.testCharacterInfo(.HEX) } } extension Unicode.Scalar { private func testCharacterInfo( _ match: Character.Info ) -> Bool { let info: Character.Info switch self.value { case // '0'-'9' 48, 49, 50, 51, 52, 53, 54, 55, 56, 57: info = [.IDENT_CONT, .DECIMAL, .HEX] case // 'A'-'F' 65, 66, 67, 68, 69, 70, // 'a'-'f' 97, 98, 99, 100, 101, 102: info = [.IDENT_START, .IDENT_CONT, .HEX, .LETTER] case // 'G'-'Z' 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, // 'g'-'z' 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122: info = [.IDENT_START, .IDENT_CONT, .LETTER] case // '_' 95: info = [.IDENT_START, .IDENT_CONT] case // '$' 36: info = [.IDENT_CONT] default: info = [] } return info.contains(match) } }
apache-2.0
12d7c905090fc06ab9e5fa1f44f65e0b
27.513761
80
0.599743
3.929204
false
true
false
false
k-o-d-e-n/CGLayout
Sources/Classes/layoutGuide.cglayout.swift
1
12447
// // CGLayoutExtended.swift // CGLayout // // Created by Denis Koryttsev on 04/09/2017. // Copyright © 2017 K-o-D-e-N. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #elseif os(macOS) import Cocoa #elseif os(Linux) import Foundation #endif // MARK: LayoutGuide and placeholders /// LayoutGuides will not show up in the view hierarchy, but may be used as layout element in /// an `RectBasedConstraint` and represent a rectangle in the layout engine. /// Create a LayoutGuide with -init /// Add to a view with UIView.add(layoutGuide:) /// If you use subclass LayoutGuide, that manages `LayoutElement` elements, than you should use /// `layout(in: frame)` method for apply layout, otherwise elements will be have wrong position. open class LayoutGuide<Super: LayoutElement>: LayoutElement, ElementInLayoutTime { public /// Entity that represents element in layout time var inLayoutTime: ElementInLayoutTime { return self } public /// Internal space for layout subelements var layoutBounds: CGRect { return CGRect(origin: CGPoint(x: frame.origin.x + bounds.origin.x, y: frame.origin.y + bounds.origin.y), size: bounds.size) } /// Layout element where added this layout guide. For addition use `func add(layoutGuide:)`. open internal(set) weak var ownerElement: Super? { didSet { didAddToOwner() } } open /// External representation of layout entity in coordinate space var frame: CGRect { didSet { // if oldValue != frame { bounds = contentRect(forFrame: frame) } // TODO: Temporary calls always, because content does not layout on equal bounds = contentRect(forFrame: frame) } } open /// Internal coordinate space of layout entity var bounds: CGRect { didSet { layout() } } open /// Layout element that maintained this layout entity var superElement: LayoutElement? { return ownerElement } open /// Removes layout element from hierarchy func removeFromSuperElement() { ownerElement = nil } public init(frame: CGRect = .zero) { self.frame = frame self.bounds = CGRect(origin: .zero, size: frame.size) } /// Tells that a this layout guide was added to owner open func didAddToOwner() { // subclass override } /// Performs layout for subelements, which this layout guide manages, in layout space rect /// /// - Parameter rect: Space for layout open func layout(in rect: CGRect) { // subclass override } open func add(to owner: Super) { self.ownerElement = owner } /// Defines rect for `bounds` property. Calls on change `frame`. /// /// - Parameter frame: New frame value. /// - Returns: Content rect open func contentRect(forFrame frame: CGRect) -> CGRect { return CGRect(origin: .zero, size: frame.size) } internal func layout() { layout(in: layoutBounds) } open var debugContentOfDescription: String { return "" } } extension LayoutGuide: CustomDebugStringConvertible { public var debugDescription: String { return "\(ObjectIdentifier(self)) {\n - frame: \(frame)\n - bounds: \(bounds)\n - super: \(String(describing: superElement ?? nil))\n\(debugContentOfDescription)\n}" } } #if os(iOS) || os(tvOS) public extension LayoutGuide where Super: UIView { /// Fabric method for generation layer with any type /// /// - Parameter type: Type of layer /// - Returns: Generated layer func build<L: CALayer>(_ type: L.Type) -> L { let layer = L() layer.frame = frame return layer } /// Generates layer and adds to `superElement` hierarchy /// /// - Parameter type: Type of layer /// - Returns: Added layer @discardableResult func add<L: CALayer>(_ type: L.Type) -> L? { guard let superElement = ownerElement else { fatalError("You must add layout guide to container using `func add(layoutGuide:)` method") } let layer = build(type) superElement.layer.addSublayer(layer) return layer } /// Fabric method for generation view with any type /// /// - Parameter type: Type of view /// - Returns: Generated view func build<V: UIView>(_ type: V.Type) -> V { return V(frame: frame) } /// Generates view and adds to `superElement` hierarchy /// /// - Parameter type: Type of view /// - Returns: Added view @discardableResult func add<V: UIView>(_ type: V.Type) -> V? { guard let superElement = ownerElement else { fatalError("You must add layout guide to container using `func add(layoutGuide:)` method") } let view = build(type) superElement.addSubview(view) return view } } #endif #if os(macOS) || os(iOS) || os(tvOS) public extension LayoutGuide where Super: CALayer { /// Fabric method for generation layer with any type /// /// - Parameter type: Type of layer /// - Returns: Generated layer func build<L: CALayer>(_ type: L.Type) -> L { let layer = L() layer.frame = frame return layer } /// Generates layer and adds to `superElement` hierarchy /// /// - Parameter type: Type of layer /// - Returns: Added layer @discardableResult func add<L: CALayer>(_ type: L.Type) -> L? { guard let superItem = ownerElement else { fatalError("You must add layout guide to container using `func add(layoutGuide:)` method") } let layer = build(type) superItem.addSublayer(layer) return layer } } public extension CALayer { /// Bind layout element to layout guide. /// /// - Parameter layoutGuide: Layout guide for binding func add<T: CALayer>(layoutGuide: LayoutGuide<T>) { unsafeBitCast(layoutGuide, to: LayoutGuide<CALayer>.self).ownerElement = self } } #endif #if os(iOS) || os(tvOS) public extension UIView { /// Bind layout element to layout guide. /// /// - Parameter layoutGuide: Layout guide for binding func add<T: UIView>(layoutGuide: LayoutGuide<T>) { unsafeBitCast(layoutGuide, to: LayoutGuide<UIView>.self).ownerElement = self } } #endif #if os(macOS) public extension NSView { /// Bind layout element to layout guide. /// /// - Parameter layoutGuide: Layout guide for binding func add<T: NSView>(layoutGuide: LayoutGuide<T>) { unsafeBitCast(layoutGuide, to: LayoutGuide<NSView>.self).ownerElement = self } } #endif public extension LayoutGuide { /// Creates dependency between two layout guides. /// /// - Parameter layoutGuide: Child layout guide. func add(layoutGuide: LayoutGuide<Super>) { layoutGuide.ownerElement = self.ownerElement } } // MARK: Placeholders /// Base class for any view placeholder that need dynamic position and/or size. /// Used UIViewController pattern for loading target view, therefore will be very simply use him. open class LayoutPlaceholder<Element: LayoutElement, Super: LayoutElement>: LayoutGuide<Super> { open private(set) lazy var itemLayout: LayoutBlock<Element> = self.element.layoutBlock() fileprivate var _element: Element? open var element: Element! { loadElementIfNeeded() return elementIfLoaded } open var isElementLoaded: Bool { return _element != nil } open var elementIfLoaded: Element? { return _element } open func loadElement() { // subclass override } open func elementDidLoad() { // subclass override } open func loadElementIfNeeded() { if !isElementLoaded { loadElement() elementDidLoad() } } open override func layout(in rect: CGRect) { itemLayout.layout(in: rect) } override func layout() { if isElementLoaded, ownerElement != nil { layout(in: layoutBounds) } } open override func didAddToOwner() { super.didAddToOwner() if ownerElement == nil { element.removeFromSuperElement() } } } //extension LayoutPlaceholder: AdjustableLayoutElement where Item: AdjustableLayoutElement { // public var contentConstraint: RectBasedConstraint { return element.contentConstraint } //} #if os(macOS) || os(iOS) || os(tvOS) /// Base class for any layer placeholder that need dynamic position and/or size. /// Used UIViewController pattern for loading target view, therefore will be very simply use him. open class LayerPlaceholder<Layer: CALayer>: LayoutPlaceholder<Layer, CALayer> { open override func loadElement() { _element = add(Layer.self) } } #endif #if os(iOS) || os(tvOS) /// Base class for any view placeholder that need dynamic position and/or size. /// Used UIViewController pattern for loading target view, therefore will be very simply use him. open class ViewPlaceholder<View: UIView>: LayoutPlaceholder<View, UIView> { var load: (() -> View)? var didLoad: ((View) -> Void)? public convenience init(_ load: @autoclosure @escaping () -> View, _ didLoad: ((View) -> Void)?) { self.init(frame: .zero) self.load = load self.didLoad = didLoad } public convenience init(_ load: (() -> View)? = nil, _ didLoad: ((View) -> Void)?) { self.init(frame: .zero) self.load = load self.didLoad = didLoad } open override func loadElement() { _element = load?() ?? add(View.self) } open override func elementDidLoad() { super.elementDidLoad() if let owner = self.ownerElement { owner.addSubview(element) } didLoad?(element) } open override func didAddToOwner() { super.didAddToOwner() if isElementLoaded, let owner = self.ownerElement { owner.addSubview(element) } } } extension ViewPlaceholder: AdjustableLayoutElement where View: AdjustableLayoutElement { open var contentConstraint: RectBasedConstraint { return isElementLoaded ? element.contentConstraint : LayoutAnchor.Constantly(value: .zero) } } // MARK: UILayoutGuide -> UIViewPlaceholder @available(iOS 9.0, *) public extension UILayoutGuide { /// Fabric method for generation view with any type /// /// - Parameter type: Type of view /// - Returns: Generated view func build<V: UIView>(_ type: V.Type) -> V { return V() } /// Generates view and adds to `superElement` hierarchy /// /// - Parameter type: Type of view /// - Returns: Added view @discardableResult func add<V: UIView>(_ type: V.Type) -> V? { guard let superElement = owningView else { fatalError("You must add layout guide to container using `func addLayoutGuide(_:)` method") } let view = build(type) superElement.addSubview(view) return view } } @available(iOS 9.0, *) open class UIViewPlaceholder<View: UIView>: UILayoutGuide { var load: (() -> View)? var didLoad: ((View) -> Void)? private weak var _view: View? open weak var view: View! { set { if _view !== newValue { _view?.removeFromSuperview() _view = newValue if let v = newValue { owningView?.addSubview(v) _view?.translatesAutoresizingMaskIntoConstraints = false viewDidLoad() } } } get { loadViewIfNeeded() return viewIfLoaded } } open var isViewLoaded: Bool { return _view != nil } open var viewIfLoaded: View? { return _view } public convenience init(_ load: @autoclosure @escaping () -> View, _ didLoad: ((View) -> Void)?) { self.init() self.load = load self.didLoad = didLoad } public convenience init(_ load: (() -> View)? = nil, _ didLoad: ((View) -> Void)?) { self.init() self.load = load self.didLoad = didLoad } open func loadView() { if let l = load { self.view = l() } else { self.view = add(View.self) } } open func viewDidLoad() { didLoad?(view) } open func loadViewIfNeeded() { if !isViewLoaded { loadView() } } } #endif
mit
d234a5d666dcdb6ec129faabdf21d774
31.581152
176
0.625984
4.530761
false
false
false
false