repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wyz5120/DrinkClock
refs/heads/master
DrinkClock/DrinkClock/Classes/View/MenuCell.swift
mit
1
// // MenuCell.swift // DrinkClock // // Created by wyz on 16/4/25. // Copyright © 2016年 wyz. All rights reserved. // import UIKit class MenuCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clearColor() selectionStyle = UITableViewCellSelectionStyle.None contentView.addSubview(containerView) containerView.addSubview(bgView) bgView.addSubview(shadowView) contentView.addSubview(titleLabel) containerView.snp_makeConstraints { (make) in make.edges.equalTo(self.contentView).inset(UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15)) } bgView.snp_makeConstraints { (make) in make.edges.equalTo(containerView) } shadowView.snp_makeConstraints { (make) in make.edges.equalTo(bgView) } titleLabel.snp_makeConstraints { (make) in make.center.equalTo(self) } startAnimation() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var containerView:UIView = { let view = UIView() view.backgroundColor = UIColor.clearColor() view.clipsToBounds = true view.layer.cornerRadius = 10 view.layer.masksToBounds = true return view }() lazy var bgView: UIImageView = { let imageView = UIImageView() imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true return imageView }() private lazy var shadowView:UIView = { let view = UIView() view.backgroundColor = UIColor(white: 0.0, alpha: 0.1) return view }() lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont(name: "GloberxBold", size: 25) label.textColor = UIColor.whiteColor() label.sizeToFit() label.textAlignment = NSTextAlignment.Center label.shadowColor = UIColor.blackColor() label.shadowOffset = CGSize(width: 0, height: 1) return label }() private func startAnimation() { // UIView.animateWithDuration(10, animations: { // self.bgView.transform = CGAffineTransformMakeScale(1.2, 1.2) // }) { (_) in // UIView.animateWithDuration(10, animations: { // self.bgView.transform = CGAffineTransformIdentity // }, completion: { (_) in // self.startAnimation() // }) // } } }
7ceefa6dfef36c41ff5179883980735d
30.340909
110
0.596809
false
false
false
false
wanghdnku/Whisper
refs/heads/master
Whisper/ChatListTableViewController.swift
mit
1
// // ChatListTableViewController.swift // Whisper // // Created by Hayden on 2016/10/13. // Copyright © 2016年 unimelb. All rights reserved. // import UIKit import Firebase class ChatListTableViewController: UITableViewController { var chatsArray = [ChatRoom]() var chatFunctions = ChatFunctions() var databaseRef: FIRDatabaseReference! { return FIRDatabase.database().reference() } var storageRef: FIRStorage! { return FIRStorage.storage() } override func viewDidLoad() { super.viewDidLoad() UINavigationBar.appearance().tintColor = UIColor.white navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) navigationController?.navigationBar.tintColor = UIColor.white tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1) fetchChats() NotificationCenter.default.addObserver(self, selector: #selector(ChatListTableViewController.fetchChats), name: NSNotification.Name(rawValue: "updateDiscussion"), object: nil) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func fetchChats() { chatsArray.removeAll(keepingCapacity: false) databaseRef.child("ChatRooms").queryOrdered(byChild: "userId").queryEqual(toValue: FIRAuth.auth()!.currentUser!.uid).observe(.childAdded, with: { (snapshot) in // print("\n\n\n\nObserver!\n\n\n\n") let key = snapshot.key let ref = snapshot.ref let snap = snapshot.value as! [String: AnyObject] let username = snap["username"] as! String let other_Username = snap["other_Username"] as! String let userId = snap["userId"] as! String let other_UserId = snap["other_UserId"] as! String let members = snap["members"] as! [String] let chatRoomId = snap["chatRoomId"] as! String let lastMessage = snap["lastMessage"] as! String let userPhotoUrl = snap["userPhotoUrl"] as! String let other_UserPhotoUrl = snap["other_UserPhotoUrl"] as! String let date = snap["date"] as! NSNumber var newChat = ChatRoom(username: username, other_Username: other_Username, userId: userId, other_UserId: other_UserId, members: members, chatRoomId: chatRoomId, lastMessage: lastMessage, userPhotoUrl: userPhotoUrl, other_UserPhotoUrl: other_UserPhotoUrl, date: date) newChat.ref = ref newChat.key = key self.chatsArray.insert(newChat, at: 0) self.tableView.reloadData() }) { (error) in print(error.localizedDescription) // let alertView = SCLAlertView() // alertView.showError("Chatrooms Error", subTitle: error.localizedDescription) } databaseRef.child("ChatRooms").queryOrdered(byChild: "other_UserId").queryEqual(toValue: FIRAuth.auth()!.currentUser!.uid).observe(.childAdded, with: { (snapshot) in //print("\n\n\n\nObserver!\n\n\n\n") let key = snapshot.key let ref = snapshot.ref let snap = snapshot.value as! [String: AnyObject] let username = snap["username"] as! String let other_Username = snap["other_Username"] as! String let userId = snap["userId"] as! String let other_UserId = snap["other_UserId"] as! String let members = snap["members"] as! [String] let chatRoomId = snap["chatRoomId"] as! String let lastMessage = snap["lastMessage"] as! String let userPhotoUrl = snap["userPhotoUrl"] as! String let other_UserPhotoUrl = snap["other_UserPhotoUrl"] as! String let date = snap["date"] as! NSNumber var newChat = ChatRoom(username: username, other_Username: other_Username, userId: userId, other_UserId: other_UserId, members: members, chatRoomId: chatRoomId, lastMessage: lastMessage, userPhotoUrl: userPhotoUrl, other_UserPhotoUrl: other_UserPhotoUrl, date: date) newChat.ref = ref newChat.key = key self.chatsArray.insert(newChat, at: 0) self.tableView.reloadData() }) { (error) in print(error.localizedDescription) // let alertView = SCLAlertView() // alertView.showError("Chatrooms Error", subTitle: error.localizedDescription) } } override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return chatsArray.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 76 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "chatlistCell", for: indexPath) as! ChatListTableViewCell var userPhotoUrlString: String! = "" if chatsArray[indexPath.row].userId == FIRAuth.auth()!.currentUser!.uid { userPhotoUrlString = chatsArray[indexPath.row].other_UserPhotoUrl! cell.usernameLabel.text = chatsArray[indexPath.row].other_Username } else { userPhotoUrlString = chatsArray[indexPath.row].userPhotoUrl! cell.usernameLabel.text = chatsArray[indexPath.row].username } let fromDate = NSDate(timeIntervalSince1970: TimeInterval(chatsArray[indexPath.row].date)) let toDate = NSDate() let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth]) let differenceOfDate = Calendar.current.dateComponents(components, from: fromDate as Date, to: toDate as Date) if differenceOfDate.second! <= 0 { cell.dateLabel.text = "now" cell.fireImage.image = UIImage(named: "fire-1") } else if differenceOfDate.second! > 0 && differenceOfDate.minute! == 0 { cell.dateLabel.text = "\(differenceOfDate.second!)s" cell.fireImage.image = UIImage(named: "fire-2") } else if differenceOfDate.minute! > 0 && differenceOfDate.hour! == 0 { cell.dateLabel.text = "\(differenceOfDate.minute!)m" cell.fireImage.image = UIImage(named: "fire-3") } else if differenceOfDate.hour! > 0 && differenceOfDate.day! == 0 { cell.dateLabel.text = "\(differenceOfDate.hour!)h" cell.fireImage.image = UIImage(named: "fire-4") } else if differenceOfDate.day! > 0 && differenceOfDate.weekOfMonth! == 0 { cell.dateLabel.text = "\(differenceOfDate.day!)d" cell.fireImage.image = UIImage(named: "fire-5") } else if differenceOfDate.weekOfMonth! > 0 { cell.dateLabel.text = "\(differenceOfDate.weekOfMonth!)w" cell.fireImage.image = UIImage(named: "fire-6") } //let components: CFCalendarUnit = [.second, .minute, .hour, .day, .weekOfMonth] //let differenceOfDate = Calendar.current //let differenceOfDate = CFCalendar.currentCalendar().components(components, fromDate: fromDate, toDate: toDate, option: []) //if differenceOfDate.second // Observe the message of each chat room. Then update the last message label. databaseRef.child("ChatRooms").child(chatsArray[indexPath.row].chatRoomId).child("lastMessage").observe(.value, with: { (snapshot) in cell.lastMessageLabel.text = (snapshot.value as? String)! }) if let urlString = userPhotoUrlString { storageRef.reference(forURL: urlString).data(withMaxSize: 6*1024*1024, completion: { (imgData, error) in if let error = error { let alertView = SCLAlertView() alertView.showError("Chatrooms Error", subTitle: error.localizedDescription) } else { DispatchQueue.main.async { if let data = imgData { cell.userImageView.image = UIImage(data: data) } } } }) } // Configure the cell... cell.userImageView.layer.cornerRadius = 30.0 cell.userImageView.clipsToBounds = true return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { // Delete button let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete",handler: { (action, indexPath) -> Void in // Delete the row from the data source // if let pRef = self.chatsArray[indexPath.row].ref { // pRef.removeValue() // } self.chatsArray.remove(at: indexPath.row) self.tableView.deleteRows(at: [indexPath], with: .fade) print("\n\nDelete") }) deleteAction.backgroundColor = whisper_red //UIColor(red: 202.0/255.0, green: 202.0/255.0, blue: 203.0/255.0, alpha: 1.0) return [deleteAction] } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let currentUser = User(username: FIRAuth.auth()!.currentUser!.displayName!, userId: FIRAuth.auth()!.currentUser!.uid, photoUrl: "\(FIRAuth.auth()!.currentUser!.photoURL!)") var otherUser: User! if currentUser.uid == chatsArray[indexPath.row].userId { otherUser = User(username: chatsArray[indexPath.row].other_Username, userId: chatsArray[indexPath.row].other_UserId, photoUrl: chatsArray[indexPath.row].other_UserPhotoUrl) } else { otherUser = User(username: chatsArray[indexPath.row].username, userId: chatsArray[indexPath.row].userId, photoUrl: chatsArray[indexPath.row].userPhotoUrl) } chatFunctions.startChat(user1: currentUser, user2: otherUser) performSegue(withIdentifier: "goToChatFromChats", sender: self) tableView.deselectRow(at: indexPath, animated: true) } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ @IBAction func goBackToCam(_ sender: AnyObject) { dismiss(animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "goToChatFromChats" { let chatVC = segue.destination as! ChatViewController chatVC.senderId = FIRAuth.auth()!.currentUser!.uid chatVC.senderDisplayName = FIRAuth.auth()!.currentUser!.displayName chatVC.chatRoomId = chatFunctions.chatRoom_id } } }
eb3a650287414979a50f62996c67175c
42.277397
278
0.626731
false
false
false
false
Harley-xk/SimpleDataKit
refs/heads/master
Example/Pods/Comet/Comet/Extensions/Numbers+Comet.swift
mit
1
// // Numbers+Comet.swift // Comet // // Created by Harley.xk on 2017/8/18. // import Foundation // Convert String to Numbers public extension String { // convert string to int // returns 0 if failed public var intValue: Int { return Int(self) ?? 0 } // convert string to double // returns 0 if failed public var doubleValue: Double { return Double(self) ?? 0 } // convert string to float // returns 0 if failed public var floatValue: Float { return Float(self) ?? 0 } } // Convert Float to String public extension Float { // 返回指定小数位数的字符串 public func string(decimals: Int = 0) -> String { return String(format: "%.\(decimals)f", self) } // 返回指定格式的字符串 public func string(format: String?) -> String { if let format = format { return String(format: format, self) } else { return string(decimals: 0) } } } // Convert Double to String public extension Double { // 返回指定小数位数的字符串 public func string(decimals: Int = 0) -> String { return String(format: "%.\(decimals)f", self) } // 返回指定格式的字符串 public func string(format: String?) -> String { if let format = format { return String(format: format, self) } else { return string(decimals: 0) } } } extension Int { // 返回指定格式的字符串 public func string(format: String? = nil) -> String { if let format = format { return String(format: format, self) } else { return "\(self)" } } // random number from min to max static public func random(min: Int = 0, max: Int) -> Int { let random = Int(arc4random()) let number = random % (max + 1 - min) + min return number } }
8b9ee82501461b223017db90bf55d846
21.481928
62
0.554126
false
false
false
false
TieShanWang/KKAutoScrollView
refs/heads/master
KKAutoScrollView/KKAutoScrollView/KKAutoCollectionViewCell.swift
mit
1
// // KKAutoCollectionViewCell.swift // KKAutoScrollController // // Created by KING on 2017/1/4. // Copyright © 2017年 KING. All rights reserved. // import UIKit import Security let KKAutoCollectionViewCellReuseID = "KKAutoCollectionViewCellReuseID" class KKAutoCollectionViewCell: UICollectionViewCell { var imageView: UIImageView! var titleLabel: UILabel! var downloadURL: String? var model: KKAutoScrollViewModel? override init(frame: CGRect) { super.init(frame: frame) self.imageView = UIImageView() self.titleLabel = UILabel.init() self.contentView.addSubview(self.titleLabel) self.contentView.addSubview(self.imageView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } func reloadData() { if let m = self.model { self.showData(m) } } func showData(_ data: KKAutoScrollViewModel) { self.model = data let url = data.url self.downloadURL = url data.downModel { [weak self] (img) in DispatchQueue.main.async { self?.imageView.image = img } } } override func layoutSubviews() { super.layoutSubviews() self.imageView.frame = self.contentView.bounds } }
656d50ea77bcaa7dee3e853da2de1af4
19.986486
71
0.576304
false
false
false
false
GeekSpeak/GeekSpeak-Show-Timer
refs/heads/master
AngleGear/AngleGear/AccumulatedAngle.swift
mit
1
import UIKit public typealias Rotation = AccumulatedAngle // MARK: AccumulatedAngle - A number that represents an angle in both // degrees or radians. public struct AccumulatedAngle: AngularType, CustomStringConvertible { public var value: Double public init(_ value: Double) { self.value = value } // All other initilizers call the above init() public init(_ accumulatedAngle: AccumulatedAngle) { self.init(Double(accumulatedAngle.value)) } public init(_ angle: Angle) { self.init(Double(angle.value)) } public init(_ value: CGFloat) { self.init(Double(value)) } public init(_ value: Int) { self.init(Double(value)) } public init(radians: Double) { self.init(radians) } public init(radians: CGFloat) { self.init(Double(radians)) } public init(radians: Int) { self.init(Double(radians)) } public init(degrees: Double) { self.init(radians: Angle.degrees2radians(degrees)) } public init(degrees: CGFloat) { self.init(degrees: Double(degrees)) } public init(degrees: Int) { self.init(degrees: Double(degrees)) } public var radians: Double { return value } public var degrees: Double { return Angle.radians2Degrees(value) } public var angle: Angle { return Angle(radians) } public var description: String { return "\(value)" } } // Extend CGFloat to convert from radians public extension CGFloat { public init(_ rotation: Rotation) { self.init(CGFloat(rotation.radians)) } } // MARK: Protocol Conformance extension AccumulatedAngle: ExpressibleByIntegerLiteral { public init(integerLiteral: IntegerLiteralType) { self.init(Double(integerLiteral)) } } extension AccumulatedAngle: ExpressibleByFloatLiteral { public init(floatLiteral: FloatLiteralType) { self.init(Double(floatLiteral)) } } // MARK: Extend Int to initialize with an AccumulatedAngle public extension Int { public init(_ accumulatedAngle: AccumulatedAngle) { self = Int(accumulatedAngle.radians) } } public extension AccumulatedAngle { public enum Preset { case circle case halfCircle case quarterCircle case threeQuarterCircle case tau case pi } } // MARK: Class Methods public extension AccumulatedAngle { public static func preset(_ preset: Preset) -> AccumulatedAngle { switch preset { case .circle, .tau: return AccumulatedAngle(Double.pi * 2) case .halfCircle, .pi: return AccumulatedAngle(Double.pi) case .quarterCircle: return AccumulatedAngle(Double.pi * 0.50) case .threeQuarterCircle: return AccumulatedAngle(Double.pi * 1.50) } } public static var pi: AccumulatedAngle { return AccumulatedAngle.preset(.pi) } public static var tau: AccumulatedAngle { return AccumulatedAngle.preset(.tau) } public static var circle: AccumulatedAngle { return AccumulatedAngle.preset(.circle) } public static var halfCircle: AccumulatedAngle { return AccumulatedAngle.preset(.halfCircle) } public static var quarterCircle: AccumulatedAngle { return AccumulatedAngle.preset(.quarterCircle) } public static var threeQuarterCircle: AccumulatedAngle { return AccumulatedAngle.preset(.threeQuarterCircle) } } // MARK: AccumulatedAngle & Angle specific overloads public func % (lhs: AccumulatedAngle, rhs: Angle) -> AccumulatedAngle { return AccumulatedAngle(lhs.value.truncatingRemainder(dividingBy: rhs.value)) } public func + (lhs: Angle, rhs: AccumulatedAngle) -> AccumulatedAngle { return AccumulatedAngle(lhs.value + rhs.value) } public func - (lhs: Angle, rhs: AccumulatedAngle) -> AccumulatedAngle { return AccumulatedAngle(lhs.value - rhs.value) } public func + (lhs: AccumulatedAngle, rhs: Angle) -> AccumulatedAngle { return AccumulatedAngle(lhs.value + rhs.value) } public func - (lhs: AccumulatedAngle, rhs: Angle) -> AccumulatedAngle { return AccumulatedAngle(lhs.value - rhs.value) } public func < (lhs: Angle, rhs: AccumulatedAngle) -> Bool { return lhs.value < rhs.value } public func == (lhs: Angle, rhs: AccumulatedAngle) -> Bool { return lhs.value == rhs.value } public func < (lhs: AccumulatedAngle, rhs: Angle) -> Bool { return lhs.value < rhs.value } public func == (lhs: AccumulatedAngle, rhs: Angle) -> Bool { return lhs.value == rhs.value } public func += (lhs: inout AccumulatedAngle, rhs: Angle) { lhs.value = lhs.value + rhs.value } public func -= (lhs: inout AccumulatedAngle, rhs: Angle) { lhs.value = lhs.value - rhs.value } public func / (lhs: AccumulatedAngle, rhs: Angle) -> AccumulatedAngle { return AccumulatedAngle(lhs.value / rhs.value) } public func * (lhs: AccumulatedAngle, rhs: Angle) -> AccumulatedAngle { return AccumulatedAngle(lhs.value * rhs.value) } // MARK: AccumulatedAngle & Int specific overloads public func % (lhs: AccumulatedAngle, rhs: Int) -> AccumulatedAngle { return AccumulatedAngle(lhs.value.truncatingRemainder(dividingBy: Double(rhs))) } public func + (lhs: Int, rhs: AccumulatedAngle) -> AccumulatedAngle { return AccumulatedAngle(Double(lhs) + rhs.value) } public func - (lhs: Int, rhs: AccumulatedAngle) -> AccumulatedAngle { return AccumulatedAngle(Double(lhs) - Double(rhs.value)) } public func + (lhs: AccumulatedAngle, rhs: Int) -> AccumulatedAngle { return AccumulatedAngle(lhs.value + Double(rhs)) } public func - (lhs: AccumulatedAngle, rhs: Int) -> AccumulatedAngle { return AccumulatedAngle(lhs.value - Double(rhs)) } public func < (lhs: Int, rhs: AccumulatedAngle) -> Bool { return Double(lhs) < rhs.value } public func == (lhs: Int, rhs: AccumulatedAngle) -> Bool { return Double(lhs) == rhs.value } public func < (lhs: AccumulatedAngle, rhs: Int) -> Bool { return lhs.value < Double(rhs) } public func == (lhs: AccumulatedAngle, rhs: Int) -> Bool { return lhs.value == Double(rhs) } public func += (lhs: inout AccumulatedAngle, rhs: Int) { lhs.value = lhs.value + Double(rhs) } public func -= (lhs: inout AccumulatedAngle, rhs: Int) { lhs.value = lhs.value - Double(rhs) } public func / (lhs: AccumulatedAngle, rhs: Int) -> AccumulatedAngle { return AccumulatedAngle(lhs.value / Double(rhs)) } public func * (lhs: AccumulatedAngle, rhs: Int) -> AccumulatedAngle { return AccumulatedAngle(lhs.value * Double(rhs)) }
7ee637703f2f97ff2e6f7068f790b520
21.819788
81
0.694797
false
false
false
false
NghiaTranUIT/Titan
refs/heads/master
TitanCore/TitanCore/StackTableViewModel.swift
mit
2
// // StackTableViewModel.swift // TitanCore // // Created by Nghia Tran on 4/25/17. // Copyright © 2017 nghiatran. All rights reserved. // import Foundation import RxSwift import RxCocoa import SwiftyPostgreSQL public protocol StackTableViewModelType { var input: StackTableViewModelInput {get} var output: StackTableViewModelOutput {get} } public protocol StackTableViewModelInput { var previousTableIndex: Int {get set} var selectedTablePublisher: PublishSubject<IndexPath> {get} } public protocol StackTableViewModelOutput { var stackTableDriver: Driver<[Table]>! {get} var stackTableVariable: Variable<[Table]> {get} var selectedIndexVariable: Variable<Int> {get} } public class StackTableViewModel: BaseViewModel, StackTableViewModelType, StackTableViewModelInput, StackTableViewModelOutput { // // MARK: - Type public var input: StackTableViewModelInput {return self} public var output: StackTableViewModelOutput {return self} // // MARK: - Input fileprivate var _previousTableIndex = -1 public var previousTableIndex: Int { get {return self._previousTableIndex} set {self._previousTableIndex = newValue} } public var selectedTablePublisher = PublishSubject<IndexPath>() // // MARK: - Output public var stackTableDriver: Driver<[Table]>! public var stackTableVariable: Variable<[Table]> { return MainStore.globalStore.detailDatabaseStore.stackTables } public var selectedIndexVariable: Variable<Int> {return MainStore.globalStore.detailDatabaseStore.selectedIndexStackTables} // // MARK: - Init override public init() { super.init() self.binding() } fileprivate func binding() { // Stack table self.stackTableDriver = MainStore.globalStore.detailDatabaseStore.stackTables.asDriver() // Selected table self.selectedTablePublisher .do(onNext: { indexPath in let action = SelectedIndexInStackViewAction(selectedIndex: indexPath.item) MainStore.dispatch(action) }) .subscribe() .addDisposableTo(self.disposeBag) } }
0a1cfc27bd6ca0a095ece2f869798934
28.891892
127
0.69575
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/Models/AbstractPost.swift
gpl-2.0
2
import Foundation extension AbstractPost { // MARK: - Status @objc var statusTitle: String? { guard let status = self.status else { return nil } return AbstractPost.title(for: status) } @objc var remoteStatus: AbstractPostRemoteStatus { get { guard let remoteStatusNumber = remoteStatusNumber?.uintValue, let status = AbstractPostRemoteStatus(rawValue: remoteStatusNumber) else { return .pushing } return status } set { remoteStatusNumber = NSNumber(value: newValue.rawValue) } } /// The status of self when we last received its data from the API. /// /// This is mainly used to identify which Post List tab should the post be shown in. For /// example, if a published post is transitioned to a draft but the app has not finished /// updating the server yet, we will continue to show the post in the Published list instead of /// the Drafts list. We believe this behavior is less confusing for the user. /// /// This is not meant to be up to date with the remote API. Eventually, this information will /// be outdated. For example, the user could have changed the status in the web while the device /// was offline. So we wouldn't recommend using this value aside from its original intention. /// /// - SeeAlso: PostService /// - SeeAlso: PostListFilter var statusAfterSync: Status? { get { return rawValue(forKey: "statusAfterSync") } set { setRawValue(newValue, forKey: "statusAfterSync") } } /// The string value of `statusAfterSync` based on `BasePost.Status`. /// /// This should only be used in Objective-C. For Swift, use `statusAfterSync`. /// /// - SeeAlso: statusAfterSync @objc(statusAfterSync) var statusAfterSyncString: String? { get { return statusAfterSync?.rawValue } set { statusAfterSync = newValue.flatMap { Status(rawValue: $0) } } } static func title(for status: Status) -> String { return title(forStatus: status.rawValue) } /// Returns the localized title for the specified status. Status should be /// one of the `PostStatus...` constants. If a matching title is not found /// the status is returned. /// /// - parameter status: The post status value /// /// - returns: The localized title for the specified status, or the status if a title was not found. /// @objc static func title(forStatus status: String) -> String { switch status { case PostStatusDraft: return NSLocalizedString("Draft", comment: "Name for the status of a draft post.") case PostStatusPending: return NSLocalizedString("Pending review", comment: "Name for the status of a post pending review.") case PostStatusPrivate: return NSLocalizedString("Private", comment: "Name for the status of a post that is marked private.") case PostStatusPublish: return NSLocalizedString("Published", comment: "Name for the status of a published post.") case PostStatusTrash: return NSLocalizedString("Trashed", comment: "Name for the status of a trashed post") case PostStatusScheduled: return NSLocalizedString("Scheduled", comment: "Name for the status of a scheduled post") default: return status } } // MARK: - Misc /// Represent the supported properties used to sort posts. /// enum SortField { case dateCreated case dateModified /// The keyPath to access the underlying property. /// var keyPath: String { switch self { case .dateCreated: return #keyPath(AbstractPost.date_created_gmt) case .dateModified: return #keyPath(AbstractPost.dateModified) } } } @objc func containsGutenbergBlocks() -> Bool { return content?.contains("<!-- wp:") ?? false } @objc func containsStoriesBlocks() -> Bool { return content?.contains("<!-- wp:jetpack/story") ?? false } var analyticsPostType: String? { switch self { case is Post: return "post" case is Page: return "page" default: return nil } } @objc override open func featuredImageURLForDisplay() -> URL? { return featuredImageURL } /// Returns true if the post has any media that needs manual intervention to be uploaded /// func hasPermanentFailedMedia() -> Bool { return media.first(where: { !$0.willAttemptToUploadLater() }) != nil } }
f73e07475b22026f53b3233241bfa3c4
31.825503
113
0.608669
false
false
false
false
dduan/swift
refs/heads/master
test/SILGen/cf.swift
apache-2.0
1
// RUN: %target-swift-frontend -import-cf-types -sdk %S/Inputs %s -emit-silgen -o - | FileCheck %s // REQUIRES: objc_interop import CoreCooling // CHECK: sil hidden @_TF2cf8useEmAllFCSo16CCMagnetismModelT_ : func useEmAll(model: CCMagnetismModel) { // CHECK: function_ref @CCPowerSupplyGetDefault : $@convention(c) () -> @autoreleased ImplicitlyUnwrappedOptional<CCPowerSupply> let power = CCPowerSupplyGetDefault() // CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (ImplicitlyUnwrappedOptional<CCPowerSupply>) -> ImplicitlyUnwrappedOptional<Unmanaged<CCRefrigerator>> let unmanagedFridge = CCRefrigeratorCreate(power) // CHECK: function_ref @CCRefrigeratorSpawn : $@convention(c) (ImplicitlyUnwrappedOptional<CCPowerSupply>) -> @owned ImplicitlyUnwrappedOptional<CCRefrigerator> let managedFridge = CCRefrigeratorSpawn(power) // CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (ImplicitlyUnwrappedOptional<CCRefrigerator>) -> () CCRefrigeratorOpen(managedFridge) // CHECK: function_ref @CCRefrigeratorCopy : $@convention(c) (ImplicitlyUnwrappedOptional<CCRefrigerator>) -> @owned ImplicitlyUnwrappedOptional<CCRefrigerator> let copy = CCRefrigeratorCopy(managedFridge) // CHECK: function_ref @CCRefrigeratorClone : $@convention(c) (ImplicitlyUnwrappedOptional<CCRefrigerator>) -> @autoreleased ImplicitlyUnwrappedOptional<CCRefrigerator> let clone = CCRefrigeratorClone(managedFridge) // CHECK: function_ref @CCRefrigeratorDestroy : $@convention(c) (@owned ImplicitlyUnwrappedOptional<CCRefrigerator>) -> () CCRefrigeratorDestroy(clone) // CHECK: class_method [volatile] %0 : $CCMagnetismModel, #CCMagnetismModel.refrigerator!1.foreign : CCMagnetismModel -> () -> Unmanaged<CCRefrigerator>! , $@convention(objc_method) (CCMagnetismModel) -> ImplicitlyUnwrappedOptional<Unmanaged<CCRefrigerator>> let f0 = model.refrigerator() // CHECK: class_method [volatile] %0 : $CCMagnetismModel, #CCMagnetismModel.getRefrigerator!1.foreign : CCMagnetismModel -> () -> CCRefrigerator! , $@convention(objc_method) (CCMagnetismModel) -> @autoreleased ImplicitlyUnwrappedOptional<CCRefrigerator> let f1 = model.getRefrigerator() // CHECK: class_method [volatile] %0 : $CCMagnetismModel, #CCMagnetismModel.takeRefrigerator!1.foreign : CCMagnetismModel -> () -> CCRefrigerator! , $@convention(objc_method) (CCMagnetismModel) -> @owned ImplicitlyUnwrappedOptional<CCRefrigerator> let f2 = model.takeRefrigerator() // CHECK: class_method [volatile] %0 : $CCMagnetismModel, #CCMagnetismModel.borrowRefrigerator!1.foreign : CCMagnetismModel -> () -> CCRefrigerator! , $@convention(objc_method) (CCMagnetismModel) -> @autoreleased ImplicitlyUnwrappedOptional<CCRefrigerator> let f3 = model.borrowRefrigerator() // CHECK: class_method [volatile] %0 : $CCMagnetismModel, #CCMagnetismModel.setRefrigerator!1.foreign : CCMagnetismModel -> (CCRefrigerator!) -> () , $@convention(objc_method) (ImplicitlyUnwrappedOptional<CCRefrigerator>, CCMagnetismModel) -> () model.setRefrigerator(copy) // CHECK: class_method [volatile] %0 : $CCMagnetismModel, #CCMagnetismModel.giveRefrigerator!1.foreign : CCMagnetismModel -> (CCRefrigerator!) -> () , $@convention(objc_method) (@owned ImplicitlyUnwrappedOptional<CCRefrigerator>, CCMagnetismModel) -> () model.giveRefrigerator(copy) // rdar://16846555 let prop: CCRefrigerator = model.fridgeProp } // Ensure that accessors are emitted for fields used as protocol witnesses. protocol Impedance { associatedtype Component var real: Component { get } var imag: Component { get } } extension CCImpedance: Impedance {} // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWVSC11CCImpedance2cf9ImpedanceS0_FS1_g4realwx9Component // CHECK-LABEL: sil shared [transparent] [fragile] @_TFVSC11CCImpedanceg4realSd // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWVSC11CCImpedance2cf9ImpedanceS0_FS1_g4imagwx9Component // CHECK-LABEL: sil shared [transparent] [fragile] @_TFVSC11CCImpedanceg4imagSd class MyMagnetism : CCMagnetismModel { // CHECK-LABEL: sil hidden [thunk] @_TToFC2cf11MyMagnetism15getRefrigerator{{.*}} : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func getRefrigerator() -> CCRefrigerator { return super.getRefrigerator() } // CHECK-LABEL: sil hidden [thunk] @_TToFC2cf11MyMagnetism16takeRefrigerator{{.*}} : $@convention(objc_method) (MyMagnetism) -> @owned CCRefrigerator override func takeRefrigerator() -> CCRefrigerator { return super.takeRefrigerator() } // CHECK-LABEL: sil hidden [thunk] @_TToFC2cf11MyMagnetism18borrowRefrigerator{{.*}} : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func borrowRefrigerator() -> CCRefrigerator { return super.borrowRefrigerator() } }
3249497d462f8ea70b7f77df3b0a3997
58.074074
258
0.773668
false
false
false
false
bandit412/SwiftCodeCollection
refs/heads/master
MathUtilities/Line.swift
gpl-3.0
1
// // Line.swift // MathUtilities // // Created by Allan Anderson on 2014-Nov-19. // Copyright (c) 2014 Allan Anderson. All rights reserved. // import Foundation struct Line { var slope:Double var yIntercept:Double init(slope:Double, yIntercept:Double){ self.slope = slope self.yIntercept = yIntercept } init(aPoint:Point, and bPoint:Point){ slope = (bPoint.yCoordinate - aPoint.yCoordinate) / (bPoint.xCoordinate - aPoint.xCoordinate) yIntercept = aPoint.yCoordinate - slope * aPoint.xCoordinate } func toString() -> String{ var lineString:String = "y = \(slope)x" if yIntercept < 0{ lineString += " - \(yIntercept * -1)" } if yIntercept > 0{ lineString += " + \(yIntercept)" } return lineString } } func SolveLine(_ lineA:Line, lineB:Line) -> Point{ let x = (lineA.yIntercept - lineB.yIntercept) / (lineA.slope - lineB.slope) let y = x * lineA.slope + lineA.yIntercept let intersection = Point(x: x, y: y) return intersection }
bcdd64656cf9a8602211b7ddb060071e
25.285714
101
0.604167
false
false
false
false
firebase/quickstart-ios
refs/heads/master
authentication/AuthenticationExample/Models/UserActions.swift
apache-2.0
1
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Namespace for peformable actions on a Firebase User instance enum UserAction: String { case signOut = "Sign Out" case link = "Link/Unlink Auth Providers" case requestVerifyEmail = "Request Verify Email" case tokenRefresh = "Token Refresh" case delete = "Delete" case updateEmail = "Email" case updatePhotoURL = "Photo URL" case updateDisplayName = "Display Name" case refreshUserInfo = "Refresh User Info" }
b326b6f57dd8b718b8e552eae87304ab
38.192308
75
0.740922
false
false
false
false
loregr/LGButton
refs/heads/develop
LGButton/Classes/SwiftIconFont/SwiftIconFont.swift
mit
1
// // UIFont+SwiftIconFont.swift // SwiftIconFont // // Created by Sedat Ciftci on 18/03/16. // Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved. // import UIKit public class SwiftIconFont { private (set) static var fonts: [String: IconFont] = [:] private init() { } public static func registFont(from font: IconFont, name: String) { self.fonts[name] = font } } public protocol IconFont { var fontName: String {get} var fileName: String {get} var icons: [String: String] {get} } public enum Fonts: IconFont { case awesome// = "FontAwesome" case ic// = "open-iconic" case ion// = "Ionicons" case oct// = "octicons" case themify// = "themify" case map// = "map-icons" case material// = "MaterialIcons-Regular" public var fontName: String { switch self { case .awesome: return FontAwesome.__fontName__ case .ic: return FontOpenic.__fontName__ case .ion: return FontIon.__fontName__ case .oct: return FontOct.__fontName__ case .themify: return FontThemify.__fontName__ case .map: return FontMap.__fontName__ case .material: return FontMaterial.__fontName__ } } public var fileName: String { switch self { case .awesome: return FontAwesome.__fileName__ case .ic: return FontOpenic.__fileName__ case .ion: return FontIon.__fileName__ case .oct: return FontOct.__fileName__ case .themify: return FontThemify.__fileName__ case .map: return FontMap.__fileName__ case .material: return FontMaterial.__fileName__ } } public var icons: [String : String] { switch self { case .awesome: return FontAwesome.icons//"FontAwesome" case .ic: return FontOpenic.icons//"Icons" case .ion: return FontIon.icons//"Ionicons" case .oct: return FontOct.icons//"octicons" case .themify: return FontThemify.icons//"Themify" case .map: return FontMap.icons//"map-icons" case .material: return FontMaterial.icons//"Material Icons" } } } public extension UIFont{ static func icon(from font: IconFont, ofSize size: CGFloat) -> UIFont { if (UIFont.fontNames(forFamilyName: font.fontName).count == 0) { /* dispatch_once(&token) { FontLoader.loadFont(fontName) } */ FontLoader.loadFont(font.fileName) } return UIFont(name: font.fontName, size: size)! } } public extension UIImage { public static func icon(from font: IconFont, iconColor: UIColor, code: String, imageSize: CGSize, ofSize size: CGFloat) -> UIImage { let drawText = String.getIcon(from: font, code: code) UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = NSTextAlignment.center drawText!.draw(in: CGRect(x:0, y:0, width:imageSize.width, height:imageSize.height), withAttributes: [NSAttributedString.Key.font : UIFont.icon(from: font, ofSize: size), NSAttributedString.Key.paragraphStyle: paragraphStyle, NSAttributedString.Key.foregroundColor: iconColor]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } } public extension String { public static func getIcon(from font: IconFont, code: String) -> String? { if let icon = font.icons[code] { return icon } return nil } } func replace(withText string: NSString) -> NSString { if string.lowercased.range(of: "-") != nil { return string.replacingOccurrences(of: "-", with: "_") as NSString } return string } func getAttributedString(_ text: NSString, ofSize size: CGFloat) -> NSMutableAttributedString { let attributedString = NSMutableAttributedString(string: text as String) for substring in ((text as String).split{$0 == " "}.map(String.init)) { var splitArr = ["", ""] splitArr = substring.split{$0 == ":"}.map(String.init) if splitArr.count < 2 { continue } let substringRange = text.range(of: substring) let fontPrefix: String = splitArr[0].lowercased() var fontCode: String = splitArr[1] if fontCode.lowercased().range(of: "_") != nil { fontCode = (fontCode as NSString).replacingOccurrences(of: "_", with: "-") } var fontType: IconFont = Fonts.awesome var fontArr: [String: String] = ["": ""] if let iconFont = SwiftIconFont.fonts[fontPrefix] { fontType = iconFont fontArr = iconFont.icons } if let _ = fontArr[fontCode] { attributedString.replaceCharacters(in: substringRange, with: String.getIcon(from: fontType, code: fontCode)!) let newRange = NSRange(location: substringRange.location, length: 1) attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.icon(from: fontType, ofSize: size), range: newRange) } } return attributedString } func GetIconIndexWithSelectedIcon(_ icon: String) -> String { let text = icon as NSString var iconIndex: String = "" for substring in ((text as String).split{$0 == " "}.map(String.init)) { var splitArr = ["", ""] splitArr = substring.split{$0 == ":"}.map(String.init) if splitArr.count == 1{ continue } var fontCode: String = splitArr[1] if fontCode.lowercased().range(of: "_") != nil { fontCode = (fontCode as NSString).replacingOccurrences(of: "_", with: "-") } iconIndex = fontCode } return iconIndex } func GetFontTypeWithSelectedIcon(_ icon: String) -> IconFont { let text = icon as NSString var fontType: IconFont = Fonts.awesome for substring in ((text as String).split{$0 == " "}.map(String.init)) { var splitArr = ["", ""] splitArr = substring.split{$0 == ":"}.map(String.init) if splitArr.count == 1{ continue } let fontPrefix: String = splitArr[0].lowercased() var fontCode: String = splitArr[1] if fontCode.lowercased().range(of: "_") != nil { fontCode = (fontCode as NSString).replacingOccurrences(of: "_", with: "-") } if let iconFont = SwiftIconFont.fonts[fontPrefix] { fontType = iconFont } } return fontType } // Extensions public extension UILabel { func parseIcon() { let text = replace(withText: (self.text! as NSString)) self.attributedText = getAttributedString(text, ofSize: self.font!.pointSize) } }
dd86b57d2fecc6fc81dba2d61b65c48f
29.196653
285
0.580574
false
false
false
false
IngmarStein/swift
refs/heads/master
test/SILGen/metatype_abstraction.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen -module-name Swift -parse-stdlib %s | %FileCheck %s enum Optional<Wrapped> { case none case some(Wrapped) } struct S {} class C {} struct Generic<T> { var value: T } struct GenericMetatype<T> { var value: T.Type } // CHECK-LABEL: sil hidden @_TFs26genericMetatypeFromGeneric // CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}} : $*Generic<T.Type>, #Generic.value // CHECK: [[META:%.*]] = load [[ADDR]] : $*@thick T.Type // CHECK: return [[META]] : $@thick T.Type // CHECK: } func genericMetatypeFromGeneric<T>(_ x: Generic<T.Type>) -> T.Type { var x = x return x.value } // CHECK-LABEL: sil hidden @_TFs26dynamicMetatypeFromGeneric // CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}} : $*Generic<C.Type>, #Generic.value // CHECK: [[META:%.*]] = load [[ADDR]] : $*@thick C.Type // CHECK: return [[META]] : $@thick C.Type // CHECK: } func dynamicMetatypeFromGeneric(_ x: Generic<C.Type>) -> C.Type { var x = x return x.value } // CHECK-LABEL: sil hidden @_TFs25staticMetatypeFromGeneric // CHECK: [[META:%.*]] = metatype $@thin S.Type // CHECK: return [[META]] : $@thin S.Type // CHECK: } func staticMetatypeFromGeneric(_ x: Generic<S.Type>) -> S.Type { return x.value } // CHECK-LABEL: sil hidden @_TFs34genericMetatypeFromGenericMetatype // CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}} : $*GenericMetatype<T>, #GenericMetatype.value // CHECK: [[META:%.*]] = load [[ADDR]] : $*@thick T.Type // CHECK: return [[META]] : $@thick T.Type // CHECK: } func genericMetatypeFromGenericMetatype<T>(_ x: GenericMetatype<T>)-> T.Type { var x = x return x.value } // CHECK-LABEL: sil hidden @_TFs34dynamicMetatypeFromGenericMetatypeFGVs15GenericMetatypeCs1C_MS0_ // CHECK: [[XBOX:%[0-9]+]] = alloc_box $GenericMetatype<C> // CHECK: [[PX:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[ADDR:%.*]] = struct_element_addr [[PX]] : $*GenericMetatype<C>, #GenericMetatype.value // CHECK: [[META:%.*]] = load [[ADDR]] : $*@thick C.Type // CHECK: return [[META]] : $@thick C.Type // CHECK: } func dynamicMetatypeFromGenericMetatype(_ x: GenericMetatype<C>) -> C.Type { var x = x return x.value } func takeGeneric<T>(_ x: T) {} func takeGenericMetatype<T>(_ x: T.Type) {} // CHECK-LABEL: sil hidden @_TFs23staticMetatypeToGeneric // CHECK: [[MAT:%.*]] = alloc_stack $@thick S.Type // CHECK: [[META:%.*]] = metatype $@thick S.Type // CHECK: store [[META]] to [[MAT]] : $*@thick S.Type // CHECK: apply {{%.*}}<S.Type>([[MAT]]) func staticMetatypeToGeneric(_ x: S.Type) { takeGeneric(x) } // CHECK-LABEL: sil hidden @_TFs31staticMetatypeToGenericMetatype // CHECK: [[META:%.*]] = metatype $@thick S.Type // CHECK: apply {{%.*}}<S>([[META]]) func staticMetatypeToGenericMetatype(_ x: S.Type) { takeGenericMetatype(x) } // CHECK-LABEL: sil hidden @_TFs24dynamicMetatypeToGeneric // CHECK: [[MAT:%.*]] = alloc_stack $@thick C.Type // CHECK: apply {{%.*}}<C.Type>([[MAT]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> () func dynamicMetatypeToGeneric(_ x: C.Type) { var x = x takeGeneric(x) } // CHECK-LABEL: sil hidden @_TFs32dynamicMetatypeToGenericMetatypeFMCs1CT_ // CHECK: [[XBOX:%[0-9]+]] = alloc_box $@thick C.Type // CHECK: [[PX:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[META:%.*]] = load [[PX]] : $*@thick C.Type // CHECK: apply {{%.*}}<C>([[META]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> () func dynamicMetatypeToGenericMetatype(_ x: C.Type) { var x = x takeGenericMetatype(x) } // CHECK-LABEL: sil hidden @_TFs24genericMetatypeToGeneric // CHECK: [[MAT:%.*]] = alloc_stack $@thick U.Type // CHECK: apply {{%.*}}<U.Type>([[MAT]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> () func genericMetatypeToGeneric<U>(_ x: U.Type) { var x = x takeGeneric(x) } func genericMetatypeToGenericMetatype<U>(_ x: U.Type) { takeGenericMetatype(x) } // CHECK-LABEL: sil hidden @_TFs27static_metatype_of_metatypeFVs1SMMS_ // CHECK: metatype $@thin S.Type.Type func static_metatype_of_metatype(_ x: S) -> S.Type.Type { return type(of: type(of: x)) } // CHECK-LABEL: sil hidden @_TFs26class_metatype_of_metatypeFCs1CMMS_ // CHECK: [[METATYPE:%.*]] = value_metatype $@thick C.Type // CHECK: [[META_METATYPE:%.*]] = value_metatype $@thick C.Type.Type, [[METATYPE]] func class_metatype_of_metatype(_ x: C) -> C.Type.Type { return type(of: type(of: x)) } // CHECK-LABEL: sil hidden @_TFs28generic_metatype_of_metatype // CHECK: [[METATYPE:%.*]] = value_metatype $@thick T.Type // CHECK: [[META_METATYPE:%.*]] = value_metatype $@thick T.Type.Type, [[METATYPE]] func generic_metatype_of_metatype<T>(_ x: T) -> T.Type.Type { return type(of: type(of: x)) } // FIXME rdar://problem/18419772 /* func existential_metatype_of_metatype(_ x: Any) -> Any.Type.Type { return type(of: type(of: x)) } */ func function_metatype_of_metatype(_ x: @escaping () -> ()) -> (() -> ()).Type.Type { return type(of: type(of: x)) }
bc0a2178e17c6f09f3aab588100b7b31
36.438849
107
0.60146
false
false
false
false
lixiangzhou/ZZSwiftTool
refs/heads/master
ZZSwiftTool/ZZSwiftTool/ZZExtension/ZZUIExtension/UITextField+ZZExtension.swift
mit
1
// // UITextField+ZZExtension.swift // ZZSwiftTool // // Created by lixiangzhou on 2017/3/17. // Copyright © 2017年 lixiangzhou. All rights reserved. // import UIKit public extension UITextField { /// 选中所有文字 func zz_selectAllText() { guard let range = textRange(from: beginningOfDocument, to: endOfDocument) else { return } selectedTextRange = range } /// 选中指定范围的文字 /// /// - parameter selectedRange: 指定的范围 func zz_set(selectedRange range: NSRange) { guard let start = position(from: beginningOfDocument, offset: range.location), let end = position(from: beginningOfDocument, offset: NSMaxRange(range)) else { return; } selectedTextRange = textRange(from: start, to: end) } }
622944558903b358b09a8da2dbe965b2
23.411765
91
0.607229
false
false
false
false
ludagoo/Perfect
refs/heads/master
Examples/URL Routing/URL Routing/PerfectHandlers.swift
agpl-3.0
2
// // PerfectHandlers.swift // URL Routing // // Created by Kyle Jessup on 2015-12-15. // Copyright (C) 2015 PerfectlySoft, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version, as supplemented by the // Perfect Additional Terms. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License, as supplemented by the // Perfect Additional Terms, for more details. // // You should have received a copy of the GNU Affero General Public License // and the Perfect Additional Terms that immediately follow the terms and // conditions of the GNU Affero General Public License along with this // program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>. // import PerfectLib // This is the function which all Perfect Server modules must expose. // The system will load the module and call this function. // In here, register any handlers or perform any one-time tasks. public func PerfectServerModuleInit() { // Install the built-in routing handler. // Using this system is optional and you could install your own system if desired. Routing.Handler.registerGlobally() Routing.Routes["GET", ["/", "index.html"] ] = { (_:WebResponse) in return IndexHandler() } Routing.Routes["/foo/*/baz"] = { _ in return EchoHandler() } Routing.Routes["/foo/bar/baz"] = { _ in return EchoHandler() } Routing.Routes["GET", "/user/{id}/baz"] = { _ in return Echo2Handler() } Routing.Routes["GET", "/user/{id}"] = { _ in return Echo2Handler() } Routing.Routes["POST", "/user/{id}/baz"] = { _ in return Echo3Handler() } // Test this one via command line with curl: // curl --data "{\"id\":123}" http://0.0.0.0:8181/raw --header "Content-Type:application/json" Routing.Routes["POST", "/raw"] = { _ in return RawPOSTHandler() } // Check the console to see the logical structure of what was installed. print("\(Routing.Routes.description)") } class IndexHandler: RequestHandler { func handleRequest(request: WebRequest, response: WebResponse) { response.appendBodyString("Index handler: You accessed path \(request.requestURI())") response.requestCompletedCallback() } } class EchoHandler: RequestHandler { func handleRequest(request: WebRequest, response: WebResponse) { response.appendBodyString("Echo handler: You accessed path \(request.requestURI()) with variables \(request.urlVariables)") response.requestCompletedCallback() } } class Echo2Handler: RequestHandler { func handleRequest(request: WebRequest, response: WebResponse) { response.appendBodyString("<html><body>Echo 2 handler: You GET accessed path \(request.requestURI()) with variables \(request.urlVariables)<br>") response.appendBodyString("<form method=\"POST\" action=\"/user/\(request.urlVariables["id"] ?? "error")/baz\"><button type=\"submit\">POST</button></form></body></html>") response.requestCompletedCallback() } } class Echo3Handler: RequestHandler { func handleRequest(request: WebRequest, response: WebResponse) { response.appendBodyString("<html><body>Echo 3 handler: You POSTED to path \(request.requestURI()) with variables \(request.urlVariables)</body></html>") response.requestCompletedCallback() } } class RawPOSTHandler: RequestHandler { func handleRequest(request: WebRequest, response: WebResponse) { response.appendBodyString("<html><body>Raw POST handler: You POSTED to path \(request.requestURI()) with content-type \(request.contentType()) and POST body \(request.postBodyString)</body></html>") response.requestCompletedCallback() } }
0ba92d8785c05fc316e33e321592af98
41.391304
200
0.734872
false
false
false
false
naokits/my-programming-marathon
refs/heads/master
BondYTPlayerDemo/RACPlayground/ViewController.swift
mit
1
// // ViewController.swift // RACPlayground // // Created by Naoki Tsutsui on 8/2/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit import Bond import youtube_ios_player_helper import ObjectiveC class ViewController: UIViewController, UIWebViewDelegate { let viewModel = ViewModel() // MARK: - YouTubeDataApi_iOS myKey // let YouTubeApiKey = "AIzaSyCBGyBYhnXtLV1A6VPEvrbOw8Vg9_NyYiQ" // MARK: - ディスプレイサイズ取得 let displayWidth = UIScreen.mainScreen().bounds.size.width let displayHeight = UIScreen.mainScreen().bounds.size.height // MARK: - Properties @IBOutlet weak var playerView: YTPlayerView! @IBOutlet weak var TitleLabel: UILabel! @IBOutlet weak var PlayerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var playtimeSlider: UISlider! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var previousButton: UIButton! @IBOutlet weak var shuffleButton: UIButton! @IBOutlet weak var repeatButton: UIButton! // var shuffledVideoList: [String]? // var videoList = ["YvzB97ge80g"] var PlayerWidth: String! // Playerの幅 var PlayerHeight: String! // Playerの高さ // 自動的にunsubscribeする場合に使用する let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.playerView.delegate = self self.loadCurrentVideo() } override func viewDidAppear(animated: Bool) { self.setup() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Misc func loadVideo(moveID: String) { self.playerView.loadWithVideoId(moveID, playerVars: [ "playsinline":0, "rel": 0, "controls": 1, "showinfo": 0, "autoplay": 0, "autohide": 1, "modestbranding": 1, "origin": "https://www.youtube.com/" ]) } // MARK: - Setup func setup() { self.setupUI() self.setupObserver() self.setupBind() } func setupBind() { self.viewModel.playerState.map { (state) -> String in var str = "" switch state { case .Unstarted: // str = "停止中" str = "▶️" self.playButton.enabled = true case .Ended: // str = "再生終了" str = "▶️" if self.viewModel.repeatButtonState.value == RepeatStateType.One { self.loadCurrentVideo() // self.playerView.stopVideo() // self.playerView.playVideo() } else { if self.viewModel.repeatButtonState.value == RepeatStateType.All { self.viewModel.nextVideoIndex() } } case .Playing: self.playButton.enabled = true self.playButton.tintColor = UIColor.redColor() // return "再生中" return "⏸" case .Paused: // str = "一時停止中" str = "▶️" // if self.isBackgroundPlay { // log.debug("バックグラウンドで再生する") // playerView.playVideo() // self.isBackgroundPlay = false // } case .Buffering: self.playButton.enabled = false // str = "読込中" str = "🔄" case .Queued: str = "キュー" default: str = "デフォルト" } return str }.bindTo(self.playButton.bnd_title) self.viewModel.shuffleButtonState.map { (state) -> String in if self.viewModel.isShuffle() { self.viewModel.shufflePlaylist() return "🔀" } else { return String("S:\(state)") } }.bindTo(self.shuffleButton.bnd_title) self.viewModel.repeatButtonState.map({ (state) -> String in print(state) if state == RepeatStateType.One { return "🔂" } else if state == RepeatStateType.All { return "🔁" } else { return String("R:\(state)") } }).bindTo(self.repeatButton.bnd_title) } func setupObserver() { self.playButton.bnd_tap.observe { _ in print("再生ボタンがタップされた: \(self.viewModel.playerState.value.rawValue)") if self.viewModel.isPlayingVideo() { self.playerView.pauseVideo() } else if self.viewModel.isEndedVideo() { self.loadCurrentVideo() self.playerView.playVideo() } else { self.playerView.playVideo() } } self.shuffleButton.bnd_tap.observe { _ in self.viewModel.updateShuffleState() } self.repeatButton.bnd_tap.observe { _ in self.viewModel.updateRepeatState() } self.previousButton.bnd_tap.observe { (_) in self.viewModel.previousVideoIndex() } self.nextButton.bnd_tap.observe { (_) in self.viewModel.nextVideoIndex() } self.viewModel.currentPlayListIndex.observeNew { (index) in log.debug("インデックス: \(index)") log.info("再生中のビデオを停止してから、\(self.viewModel.playlist.value[index]) のビデオをローディング") self.playerView.stopVideo() let videoid = self.viewModel.playlist.value[index] self.loadVideo(videoid) } self.viewModel.playlist.observe { (playlist) in print("プレイリスト: \(playlist)") } } func setupUI() { // self.setupPlayerSize() self.allDisablePlayerButton() } func setupPlayerSize() { // Playerのサイズを計算 let width: Int = Int(displayWidth) self.PlayerWidth = String(width) let Height = displayWidth / 1.77777777777778 let height: Int = Int(Height) self.PlayerHeight = String(height) } // 現在の再生インデックスの動画をロードする func loadCurrentVideo() { let index = self.viewModel.currentPlayListIndex.value let videoid = self.viewModel.playlist.value[index] self.loadVideo(videoid) } private func allDisablePlayerButton() { self.playButton.enabled = false self.previousButton.enabled = false self.nextButton.enabled = false self.shuffleButton.enabled = false self.repeatButton.enabled = false } } // MARK: - YTPlayerViewDelegate /** * A delegate for ViewControllers to respond to YouTube player events outside * of the view, such as changes to video playback state or playback errors. * The callback functions correlate to the events fired by the IFrame API. * For the full documentation, see the IFrame documentation here: * https://developers.google.com/youtube/iframe_api_reference#Events */ extension ViewController: YTPlayerViewDelegate { /** * Invoked when the player view is ready to receive API calls. * * @param playerView The YTPlayerView instance that has become ready. */ func playerViewDidBecomeReady(playerView: YTPlayerView) { log.debug("準備完了") self.playButton.enabled = true if self.viewModel.playlist.value.count > 0 { self.previousButton.enabled = true self.nextButton.enabled = true self.repeatButton.enabled = true self.shuffleButton.enabled = true } self.playerView.playVideo() } /** * Callback invoked when player state has changed, e.g. stopped or started playback. * * @param playerView The YTPlayerView instance where playback state has changed. * @param state YTPlayerState designating the new playback state. */ func playerView(playerView: YTPlayerView, didChangeToState state: YTPlayerState) { log.debug(state.rawValue) self.viewModel.updatePlayState(state) } /** * Callback invoked when an error has occured. * * @param playerView The YTPlayerView instance where the error has occurred. * @param error YTPlayerError containing the error state. */ func playerView(playerView: YTPlayerView, receivedError error: YTPlayerError) { log.error(error.rawValue) } /** * Callback invoked when playback quality has changed. * * @param playerView The YTPlayerView instance where playback quality has changed. * @param quality YTPlaybackQuality designating the new playback quality. */ func playerView(playerView: YTPlayerView, didChangeToQuality quality: YTPlaybackQuality) { // log.debug(quality.rawValue) } /** * Callback invoked frequently when playBack is plaing. * * @param playerView The YTPlayerView instance where the error has occurred. * @param playTime float containing curretn playback time. */ func playerView(playerView: YTPlayerView, didPlayTime playTime: Float) { // let progress = NSTimeInterval(playTime) / self.playerView.duration() // log.debug("再生時間: \(progress)") // self.playtimeSlider.value = Float(progress) } }
e1803b8c412c1ab23d2d694beef7a215
31.262458
94
0.577386
false
false
false
false
v2panda/DaysofSwift
refs/heads/master
swift2.3/My-SlideMenu/My-SlideMenu/Model/TransitionManager.swift
mit
1
// // TransitionManager.swift // My-SlideMenu // // Created by v2panda on 16/3/2. // Copyright © 2016年 v2panda. All rights reserved. // import UIKit @objc protocol TransitionManagerDelegate { func transitionManagerDismiss() } class TransitionManager: NSObject ,UIViewControllerAnimatedTransitioning,UIViewControllerTransitioningDelegate{ // 持续时间 var duration = 0.5 var isPresenting = false var delegate:TransitionManagerDelegate? var snapshot:UIView? { didSet { if let _delegate = delegate { let tapGestureRecognizer = UITapGestureRecognizer(target: _delegate, action: "transitionManagerDismiss") snapshot?.addGestureRecognizer(tapGestureRecognizer) } } } //MARK: UIViewControllerTransitioningDelegate func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! let container = transitionContext.containerView() let moveDown = CGAffineTransformMakeTranslation(0, container!.frame.height - 150) let moveUp = CGAffineTransformMakeTranslation(0, -50) if isPresenting { toView.transform = moveUp snapshot = fromView.snapshotViewAfterScreenUpdates(true) container?.addSubview(toView) container?.addSubview(snapshot!) } UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.3, options: .CurveEaseInOut, animations: { if self.isPresenting { self.snapshot?.transform = moveDown toView.transform = CGAffineTransformIdentity }else { self.snapshot?.transform = CGAffineTransformIdentity fromView.transform = moveUp } }, completion: { hehe in transitionContext.completeTransition(true) if !self.isPresenting { self.snapshot?.removeFromSuperview() } }) } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } }
2c139992e5284244793be8957fb3d636
34.296296
217
0.664568
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/Extensions/NSURL+Yep.swift
mit
1
// // NSURL+Yep.swift // Yep // // Created by nixzhu on 15/11/9. // Copyright © 2015年 Catch Inc. All rights reserved. // import Foundation import YepKit extension NSURL { private var allQueryItems: [NSURLQueryItem] { if let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false), queryItems = components.queryItems { return queryItems } return [] } private func queryItemForKey(key: String) -> NSURLQueryItem? { let predicate = NSPredicate(format: "name=%@", key) return (allQueryItems as NSArray).filteredArrayUsingPredicate(predicate).first as? NSURLQueryItem } func yep_matchSharedFeed(completion: (feed: DiscoveredFeed?) -> Void) -> Bool { guard let host = host where host == yepHost else { return false } guard let pathComponents = pathComponents else { return false } guard let first = pathComponents[safe: 1] where first == "groups", let second = pathComponents[safe: 2] where second == "share", let sharedToken = queryItemForKey("token")?.value else { return false } feedWithSharedToken(sharedToken, failureHandler: { reason, errorMessage in SafeDispatch.async { completion(feed: nil) } }, completion: { feed in SafeDispatch.async { completion(feed: feed) } }) return true } // make sure put it in last func yep_matchProfile(completion: DiscoveredUser -> Void) -> Bool { guard let host = host where host == yepHost else { return false } guard let pathComponents = pathComponents else { return false } if let username = pathComponents[safe: 1] { discoverUserByUsername(username, failureHandler: nil, completion: { discoveredUser in SafeDispatch.async { completion(discoveredUser) } }) return true } return false } } extension NSURL { var yep_isNetworkURL: Bool { switch scheme { case "http", "https": return true default: return false } } var yep_validSchemeNetworkURL: NSURL? { if scheme.isEmpty { guard let URLComponents = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) else { return nil } URLComponents.scheme = "http" return URLComponents.URL } else { if yep_isNetworkURL { return self } else { return nil } } } }
8c167d74f6ec7b8a0d5080044e84955a
22.081967
124
0.549716
false
false
false
false
objecthub/swift-lispkit
refs/heads/master
Sources/LispKit/Base/Compression.swift
apache-2.0
1
// // Compression.swift // LispKit // // Created by Matthias Zenger on 01/12/2017. // // Based on DataCompression by Markus Wanke found at: // https://github.com/mw99/DataCompression // // libcompression wrapper as an extension for the `Data` type // (ZLIB, LZFSE, LZMA, LZ4, deflate, RFC-1950, RFC-1951) // // Created by Markus Wanke, 2016/12/05 // // Apache License, Version 2.0 // // Copyright 2016, Markus Wanke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Compression /// /// Extensions providing compression and decompression functionality. /// public extension Data { /// Supported compression algorithms. enum CompressionAlgorithm { /// Deflate: Fast with a good compression rate. Proved itself over time and is supported /// everywhere. case zlib /// Apples custom Lempel-Ziv style compression algorithm. Claims to compress as good as zlib /// but 2 to 3 times faster. case lzfse /// Horribly slow. Compression as well as decompression. Compresses better than zlib though. case lzma /// Fast, but compression rate is very bad. Apples lz4 implementation often do not /// compress at all. case lz4 fileprivate var lowLevelType: compression_algorithm { switch self { case .zlib : return COMPRESSION_ZLIB case .lzfse : return COMPRESSION_LZFSE case .lz4 : return COMPRESSION_LZ4 case .lzma : return COMPRESSION_LZMA } } } /// Compresses the data. /// - parameter withAlgorithm: Compression algorithm to use. See the `CompressionAlgorithm` type /// - returns: compressed data func compress(withAlgorithm algo: CompressionAlgorithm) -> Data? { return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: algo.lowLevelType) return perform(config, source: sourcePtr, sourceSize: count) } } /// Decompresses the data. /// - parameter withAlgorithm: Compression algorithm to use. See the `CompressionAlgorithm` type /// - returns: decompressed data func decompress(withAlgorithm algo: CompressionAlgorithm) -> Data? { return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: algo.lowLevelType) return perform(config, source: sourcePtr, sourceSize: count) } } /// Compresses the data using the zlib deflate algorithm. /// - returns: raw deflated data according to [RFC-1951](https://tools.ietf.org/html/rfc1951). /// - note: Fixed at compression level 5 (best trade off between speed and time) func deflate() -> Data? { return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: sourcePtr, sourceSize: count) } } /// Decompresses the data using the zlib deflate algorithm. Self is expected to be a raw deflate /// stream according to [RFC-1951](https://tools.ietf.org/html/rfc1951). /// - returns: uncompressed data func inflate() -> Data? { return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: sourcePtr, sourceSize: count) } } /// Compresses the data using the deflate algorithm and makes it comply to the zlib format. /// - returns: deflated data in zlib format [RFC-1950](https://tools.ietf.org/html/rfc1950) /// - note: Fixed at compression level 5 (best trade off between speed and time) func zip() -> Data? { let header = Data([0x78, 0x5e]) let deflated = self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: sourcePtr, sourceSize: count, preload: header) } guard var result = deflated else { return nil } var adler = self.adler32().checksum.bigEndian result.append(Data(bytes: &adler, count: MemoryLayout<UInt32>.size)) return result } /// Decompresses the data using the zlib deflate algorithm. Self is expected to be a zlib deflate /// stream according to [RFC-1950](https://tools.ietf.org/html/rfc1950). /// - returns: uncompressed data func unzip(skipCheckSumValidation: Bool = true) -> Data? { // 2 byte header + 4 byte adler32 checksum let overhead = 6 guard count > overhead else { return nil } let header: UInt16 = withUnsafeBytes { (ptr: UnsafePointer<UInt16>) -> UInt16 in return ptr.pointee.bigEndian } // check for the deflate stream bit guard header >> 8 & 0b1111 == 0b1000 else { return nil } // check the header checksum guard header % 31 == 0 else { return nil } let cresult: Data? = withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data? in let source = ptr.advanced(by: 2) let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: source, sourceSize: count - overhead) } guard let inflated = cresult else { return nil } if skipCheckSumValidation { return inflated } else { let cksum: UInt32 = withUnsafeBytes { (bytePtr: UnsafePointer<UInt8>) -> UInt32 in let last = bytePtr.advanced(by: count - 4) return last.withMemoryRebound(to: UInt32.self, capacity: 1) { (intPtr) -> UInt32 in return intPtr.pointee.bigEndian } } return cksum == inflated.adler32().checksum ? inflated : nil } } /// Compresses the data using the deflate algorithm and makes it comply to the gzip stream format. /// - returns: deflated data in gzip format [RFC-1952](https://tools.ietf.org/html/rfc1952) /// - note: Fixed at compression level 5 (best trade off between speed and time) func gzip() -> Data? { var header = Data([0x1f, 0x8b, 0x08, 0x00]) // magic, magic, deflate, noflags var unixtime = UInt32(Date().timeIntervalSince1970).littleEndian header.append(Data(bytes: &unixtime, count: MemoryLayout<UInt32>.size)) header.append(contentsOf: [0x00, 0x03]) // normal compression level, unix file type let deflated = self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: sourcePtr, sourceSize: count, preload: header) } guard var result = deflated else { return nil } // append checksum var crc32: UInt32 = self.crc32().checksum.littleEndian result.append(Data(bytes: &crc32, count: MemoryLayout<UInt32>.size)) // append size of original data var isize: UInt32 = UInt32(truncatingIfNeeded: count).littleEndian result.append(Data(bytes: &isize, count: MemoryLayout<UInt32>.size)) return result } /// Decompresses the data using the gzip deflate algorithm. Self is expected to be a gzip deflate /// stream according to [RFC-1952](https://tools.ietf.org/html/rfc1952). /// - returns: uncompressed data func gunzip() -> Data? { // 10 byte header + data + 8 byte footer. See https://tools.ietf.org/html/rfc1952#section-2 let overhead = 10 + 8 guard count >= overhead else { return nil } typealias GZipHeader = (id1: UInt8, id2: UInt8, cm: UInt8, flg: UInt8, xfl: UInt8, os: UInt8) let hdr: GZipHeader = withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> GZipHeader in // +---+---+---+---+---+---+---+---+---+---+ // |ID1|ID2|CM |FLG| MTIME |XFL|OS | // +---+---+---+---+---+---+---+---+---+---+ return (id1: ptr[0], id2: ptr[1], cm: ptr[2], flg: ptr[3], xfl: ptr[8], os: ptr[9]) } typealias GZipFooter = (crc32: UInt32, isize: UInt32) let ftr: GZipFooter = withUnsafeBytes { (bptr: UnsafePointer<UInt8>) -> GZipFooter in // +---+---+---+---+---+---+---+---+ // | CRC32 | ISIZE | // +---+---+---+---+---+---+---+---+ return bptr.advanced(by: count - 8).withMemoryRebound(to: UInt32.self, capacity: 2) { ptr in return (ptr[0].littleEndian, ptr[1].littleEndian) } } // Wrong gzip magic or unsupported compression method guard hdr.id1 == 0x1f && hdr.id2 == 0x8b && hdr.cm == 0x08 else { return nil } let has_crc16: Bool = hdr.flg & 0b00010 != 0 let has_extra: Bool = hdr.flg & 0b00100 != 0 let has_fname: Bool = hdr.flg & 0b01000 != 0 let has_cmmnt: Bool = hdr.flg & 0b10000 != 0 let cresult: Data? = withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data? in var pos = 10 ; let limit = count - 8 if has_extra { pos += ptr.advanced(by: pos).withMemoryRebound(to: UInt16.self, capacity: 1) { return Int($0.pointee.littleEndian) + 2 // +2 for xlen } } if has_fname { while pos < limit && ptr[pos] != 0x0 { pos += 1 } pos += 1 // skip null byte as well } if has_cmmnt { while pos < limit && ptr[pos] != 0x0 { pos += 1 } pos += 1 // skip null byte as well } if has_crc16 { pos += 2 // ignoring header crc16 } guard pos < limit else { return nil } let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: ptr.advanced(by: pos), sourceSize: limit - pos) } guard let inflated = cresult, ftr.isize == UInt32(truncatingIfNeeded: inflated.count), ftr.crc32 == inflated.crc32().checksum else { return nil } return inflated } /// Calculate the Adler32 checksum of the data. /// - returns: Adler32 checksum type. Can still be further advanced. func adler32() -> Adler32 { var res = Adler32() res.advance(withChunk: self) return res } /// Calculate the Crc32 checksum of the data. /// - returns: Crc32 checksum type. Can still be further advanced. func crc32() -> Crc32 { var res = Crc32() res.advance(withChunk: self) return res } } /// Struct based type representing a Crc32 checksum. public struct Crc32: CustomStringConvertible { private static let zLibCrc32: ZLibCrc32FuncPtr? = loadCrc32fromZLib() public init() { } // C convention function pointer type matching the signature of `libz::crc32` private typealias ZLibCrc32FuncPtr = @convention(c) ( _ cks: UInt32, _ buf: UnsafePointer<UInt8>, _ len: UInt32 ) -> UInt32 /// Raw checksum. Updated after a every call to `advance(withChunk:)` private(set) public var checksum: UInt32 = 0 /// Advance the current checksum with a chunk of data. Designed t be called multiple times. /// - parameter chunk: data to advance the checksum public mutating func advance(withChunk chunk: Data) { if let fastCrc32 = Crc32.zLibCrc32 { checksum = chunk.withUnsafeBytes({ (ptr: UnsafePointer<UInt8>) -> UInt32 in return fastCrc32(checksum, ptr, UInt32(chunk.count)) }) } else { checksum = slowCrc32(start: checksum, data: chunk) } } /// Formatted checksum. public var description: String { return String(format: "%08x", checksum) } /// Load `crc32()` from '/usr/lib/libz.dylib' if libz is installed. /// - returns: A function pointer to crc32() of zlib or nil if zlib can't be found private static func loadCrc32fromZLib() -> ZLibCrc32FuncPtr? { guard let libz = dlopen("/usr/lib/libz.dylib", RTLD_NOW), let fptr = dlsym(libz, "crc32") else { return nil } return unsafeBitCast(fptr, to: ZLibCrc32FuncPtr.self) } /// Rudimentary fallback implementation of the crc32 checksum. This is only a backup used /// when zlib can't be found under '/usr/lib/libz.dylib'. /// - returns: crc32 checksum (4 byte) private func slowCrc32(start: UInt32, data: Data) -> UInt32 { return ~data.reduce(~start) { (crc: UInt32, next: UInt8) -> UInt32 in let tableOffset = (crc ^ UInt32(next)) & 0xff return lookUpTable[Int(tableOffset)] ^ crc >> 8 } } /// Lookup table for faster crc32 calculation. /// table source: http://web.mit.edu/freebsd/head/sys/libkern/crc32.c private let lookUpTable: [UInt32] = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, ] } /// Struct based type representing a Adler32 checksum. public struct Adler32: CustomStringConvertible { private static let zLibAdler32: ZLibAdler32FuncPtr? = loadAdler32fromZLib() public init() { } // C convention function pointer type matching the signature of `libz::adler32` private typealias ZLibAdler32FuncPtr = @convention(c) ( _ cks: UInt32, _ buf: UnsafePointer<UInt8>, _ len: UInt32 ) -> UInt32 /// Raw checksum. Updated after a every call to `advance(withChunk:)` private(set) public var checksum: UInt32 = 1 /// Advance the current checksum with a chunk of data. Designed t be called multiple times. /// - parameter chunk: data to advance the checksum public mutating func advance(withChunk chunk: Data) { if let fastAdler32 = Adler32.zLibAdler32 { checksum = chunk.withUnsafeBytes({ (ptr: UnsafePointer<UInt8>) -> UInt32 in return fastAdler32(checksum, ptr, UInt32(chunk.count)) }) } else { checksum = slowAdler32(start: checksum, data: chunk) } } /// Formatted checksum. public var description: String { return String(format: "%08x", checksum) } /// Load `adler32()` from '/usr/lib/libz.dylib' if libz is installed. /// - returns: A function pointer to adler32() of zlib or nil if zlib can't be found private static func loadAdler32fromZLib() -> ZLibAdler32FuncPtr? { guard let libz = dlopen("/usr/lib/libz.dylib", RTLD_NOW), let fptr = dlsym(libz, "adler32") else { return nil } return unsafeBitCast(fptr, to: ZLibAdler32FuncPtr.self) } /// Rudimentary fallback implementation of the adler32 checksum. This is only a backup used /// when zlib can't be found under '/usr/lib/libz.dylib'. /// - returns: adler32 checksum (4 byte) private func slowAdler32(start: UInt32, data: Data) -> UInt32 { var s1: UInt32 = start & 0xffff var s2: UInt32 = (start >> 16) & 0xffff let prime: UInt32 = 65521 for byte in data { s1 += UInt32(byte) if s1 >= prime { s1 = s1 % prime } s2 += s1 if s2 >= prime { s2 = s2 % prime } } return (s2 << 16) | s1 } } fileprivate extension Data { func withUnsafeBytes<ResultType, ContentType>( _ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try self.withUnsafeBytes({ (rawBufferPointer: UnsafeRawBufferPointer) -> ResultType in return try body(rawBufferPointer.bindMemory(to: ContentType.self).baseAddress!) }) } } fileprivate typealias Config = (operation: compression_stream_operation, algorithm: compression_algorithm) fileprivate func perform(_ config: Config, source: UnsafePointer<UInt8>, sourceSize: Int, preload: Data = Data()) -> Data? { guard config.operation == COMPRESSION_STREAM_ENCODE || sourceSize > 0 else { return nil } let streamBase = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1) defer { streamBase.deallocate() } var stream = streamBase.pointee let status = compression_stream_init(&stream, config.operation, config.algorithm) guard status != COMPRESSION_STATUS_ERROR else { return nil } defer { compression_stream_destroy(&stream) } var result = preload var flags: Int32 = Int32(COMPRESSION_STREAM_FINALIZE.rawValue) let blockLimit = 64 * 1024 var bufferSize = Swift.max(sourceSize, 64) if sourceSize > blockLimit { bufferSize = blockLimit if config.algorithm == COMPRESSION_LZFSE && config.operation != COMPRESSION_STREAM_ENCODE { // This fixes a bug in Apples lzfse decompressor. it will sometimes fail randomly when the // input gets splitted into multiple chunks and the flag is not 0. Even though it should // always work with FINALIZE... flags = 0 } } let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) defer { buffer.deallocate() } stream.dst_ptr = buffer stream.dst_size = bufferSize stream.src_ptr = source stream.src_size = sourceSize while true { switch compression_stream_process(&stream, flags) { case COMPRESSION_STATUS_OK: guard stream.dst_size == 0 else { return nil } result.append(buffer, count: stream.dst_ptr - buffer) stream.dst_ptr = buffer stream.dst_size = bufferSize if flags == 0 && stream.src_size == 0 { // part of the lzfse bugfix above flags = Int32(COMPRESSION_STREAM_FINALIZE.rawValue) } case COMPRESSION_STATUS_END: result.append(buffer, count: stream.dst_ptr - buffer) return result default: return nil } } }
0b1af74dcda78241feae48600f59a2d7
41.228745
100
0.679498
false
false
false
false
Arnoymous/AListViewController
refs/heads/master
Carthage/Checkouts/pull-to-refresh/Sources/ESRefreshComponent.swift
apache-2.0
7
// // ESRefreshComponent.swift // // Created by egg swift on 16/4/7. // Copyright (c) 2013-2016 ESPullToRefresh (https://github.com/eggswift/pull-to-refresh) // // 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 UIKit public typealias ESRefreshHandler = (() -> ()) open class ESRefreshComponent: UIView { open weak var scrollView: UIScrollView? /// @param handler Refresh callback method open var handler: ESRefreshHandler? /// @param animator Animated view refresh controls, custom must comply with the following two protocol open var animator: (ESRefreshProtocol & ESRefreshAnimatorProtocol)! /// @param refreshing or not fileprivate var _isRefreshing = false open var isRefreshing: Bool { get { return self._isRefreshing } } /// @param auto refreshing or not fileprivate var _isAutoRefreshing = false open var isAutoRefreshing: Bool { get { return self._isAutoRefreshing } } /// @param tag observing fileprivate var isObservingScrollView = false fileprivate var isIgnoreObserving = false public override init(frame: CGRect) { super.init(frame: frame) autoresizingMask = [.flexibleLeftMargin, .flexibleWidth, .flexibleRightMargin] } public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler) { self.init(frame: frame) self.handler = handler self.animator = ESRefreshAnimator.init() } public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler, animator: ESRefreshProtocol & ESRefreshAnimatorProtocol) { self.init(frame: frame) self.handler = handler self.animator = animator } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { removeObserver() } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) /// Remove observer from superview immediately self.removeObserver() DispatchQueue.main.async { [weak self, newSuperview] in guard let weakSelf = self else { return } /// Add observer to new superview in next runloop weakSelf.addObserver(newSuperview) } } open override func didMoveToSuperview() { super.didMoveToSuperview() self.scrollView = self.superview as? UIScrollView if let _ = animator { let v = animator.view if v.superview == nil { let inset = animator.insets self.addSubview(v) v.frame = CGRect.init(x: inset.left, y: inset.right, width: self.bounds.size.width - inset.left - inset.right, height: self.bounds.size.height - inset.top - inset.bottom) v.autoresizingMask = [ .flexibleWidth, .flexibleTopMargin, .flexibleHeight, .flexibleBottomMargin ] } } } } extension ESRefreshComponent /* KVO methods */ { fileprivate static var context = "ESRefreshKVOContext" fileprivate static let offsetKeyPath = "contentOffset" fileprivate static let contentSizeKeyPath = "contentSize" public func ignoreObserver(_ ignore: Bool = false) { if let scrollView = scrollView { scrollView.isScrollEnabled = !ignore } isIgnoreObserving = ignore } fileprivate func addObserver(_ view: UIView?) { if let scrollView = view as? UIScrollView, !isObservingScrollView { scrollView.addObserver(self, forKeyPath: ESRefreshComponent.offsetKeyPath, options: [.initial, .new], context: &ESRefreshComponent.context) scrollView.addObserver(self, forKeyPath: ESRefreshComponent.contentSizeKeyPath, options: [.initial, .new], context: &ESRefreshComponent.context) isObservingScrollView = true } } fileprivate func removeObserver() { if let scrollView = superview as? UIScrollView, isObservingScrollView { scrollView.removeObserver(self, forKeyPath: ESRefreshComponent.offsetKeyPath, context: &ESRefreshComponent.context) scrollView.removeObserver(self, forKeyPath: ESRefreshComponent.contentSizeKeyPath, context: &ESRefreshComponent.context) isObservingScrollView = false } } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &ESRefreshComponent.context { guard isUserInteractionEnabled == true && isHidden == false else { return } if keyPath == ESRefreshComponent.contentSizeKeyPath { if isIgnoreObserving == false { sizeChangeAction(object: object as AnyObject?, change: change) } } else if keyPath == ESRefreshComponent.offsetKeyPath { if isIgnoreObserving == false { offsetChangeAction(object: object as AnyObject?, change: change) } } } else { } } } public extension ESRefreshComponent /* Action */ { public final func startRefreshing(isAuto: Bool = false) -> Void { guard isRefreshing == false && isAutoRefreshing == false else { return } _isRefreshing = !isAuto _isAutoRefreshing = isAuto self.start() } public final func stopRefreshing() -> Void { guard isRefreshing == true || isAutoRefreshing == true else { return } self.stop() } public func start() { } public func stop() { _isRefreshing = false _isAutoRefreshing = false } // ScrollView contentSize change action public func sizeChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { } // ScrollView offset change action public func offsetChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { } }
c276ac23119b2ee53eddfa442dea533b
34.45283
156
0.62959
false
false
false
false
caronae/caronae-ios
refs/heads/master
Caronae/Categories/DataRequest+responseCaronae.swift
gpl-3.0
1
import Alamofire extension DataRequest { static func caronaeResponseSerializer(options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer<Any> { return DataResponseSerializer { _, response, data, error in let result = Request.serializeResponseJSON(options: options, response: response, data: data, error: error) guard let response = response else { return result } if response.statusCode == 401 { // Invalid credentials DispatchQueue.main.async { let userService = UserService.instance if userService.user != nil { userService.signOut(force: true) } } } if let authorizationHeader = response.allHeaderFields["Authorization"] as? String, let jwtToken = authorizationHeader.components(separatedBy: "Bearer ").last { NSLog("New token returned from API") let userService = UserService.instance userService.jwtToken = jwtToken userService.userToken = nil } return result } } @discardableResult func responseCaronae( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.caronaeResponseSerializer(options: options), completionHandler: completionHandler ) } }
4d7fe678bf944df9ab29523c07d6b697
37.478261
135
0.563277
false
false
false
false
jifusheng/MyDouYuTV
refs/heads/master
DouYuTV/DouYuTV/Classes/Main/Controller/BaseViewController.swift
mit
1
// // BaseViewController.swift // DouYuTV // // Created by 王建伟 on 2016/11/23. // Copyright © 2016年 jifusheng. All rights reserved. // 基础控制器,带加载动画的 import UIKit class BaseViewController: UIViewController { // MARK: 定义属性需子类赋值 var contentView : UIView? // MARK: 懒加载属性 fileprivate lazy var animaImageView : UIImageView = { [unowned self] in let imageView = UIImageView(image: UIImage(named: "img_loading_1")) imageView.center = self.view.center imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin] imageView.animationImages = [UIImage(named: "img_loading_1")!, UIImage(named: "img_loading_2")!] imageView.animationDuration = 0.5 imageView.animationRepeatCount = LONG_MAX return imageView }() // MARK: 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension BaseViewController { func setupUI() { //1、隐藏contentView contentView?.isHidden = true //2、添加执行动画的视图 view.addSubview(animaImageView) //3、执行动画 animaImageView.startAnimating() } func loadDataCompletion() { //1、结束动画 animaImageView.stopAnimating() //2、隐藏animaImageView animaImageView.isHidden = true //3、显示contentView contentView?.isHidden = false } }
a7ec586379bbb9371d65b303363bb0f8
25.5
104
0.63643
false
false
false
false
reactive-swift/UV
refs/heads/master
UV/TCP.swift
apache-2.0
1
//===--- TCP.swift -------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===-----------------------------------------------------------------------===// import Foundation import Boilerplate import CUV public typealias uv_tcp_p = UnsafeMutablePointer<uv_tcp_t> extension uv_connect_t : uv_request_type { } public class ConnectRequest : Request<uv_connect_t> { } public final class TCP : Stream<uv_tcp_p> { public init(loop:Loop, connectionCallback:@escaping TCP.SimpleCallback, readCallback:@escaping TCP.ReadCallback) throws { try super.init(readCallback: readCallback, connectionCallback: connectionCallback) { handle in uv_tcp_init(loop.loop, handle.portable) } } public convenience init(loop:Loop, readCallback:@escaping TCP.ReadCallback) throws { try self.init(loop: loop, connectionCallback: {_ in}, readCallback: readCallback) } public convenience init(loop:Loop, connectionCallback:@escaping TCP.SimpleCallback) throws { try self.init(loop: loop, connectionCallback: connectionCallback, readCallback: {_,_ in}) } func fresh<A>(_ tcp:TCP) -> A { return tcp as! A } override func fresh(on loop:Loop, readCallback:@escaping ReadCallback) throws -> Self { return try fresh(TCP(loop: loop, readCallback: readCallback)) } public func bind(to addr:UnsafePointer<sockaddr>, ipV6only:Bool = false) throws { let flags:UInt32 = ipV6only ? UV_TCP_IPV6ONLY.rawValue : 0 try ccall(Error.self) { uv_tcp_bind(handle.portable, addr, flags) } } public func connect(to addr:UnsafePointer<sockaddr>, callback:@escaping ConnectRequest.RequestCallback = {_,_ in}) { ConnectRequest.perform(callback: callback) { req in uv_tcp_connect(req, self.handle.portable, addr, connect_cb) } } } func connect_cb(req:UnsafeMutablePointer<uv_connect_t>?, status:Int32) { req_cb(req, status: status) }
b92cc27d7f2577dad707c3aac8b5dbb4
36.753623
125
0.654511
false
false
false
false
tjarratt/Xcode-Better-Refactor-Tools
refs/heads/master
Fake4SwiftKit/Use Cases/Implement Equatable/Dependencies/XMASEquatableTemplateStamper.swift
mit
3
import Mustache import Foundation @objc open class XMASEquatableTemplateStamper : NSObject { fileprivate(set) open var bundle : Bundle @objc public init(bundle: Bundle) { self.bundle = bundle } @objc open func equatableImplementationForStruct(_ structDecl: StructDeclaration) throws -> String { let templateName = "SwiftEquatableStruct" let path : String! = self.bundle.path(forResource: templateName, ofType: "mustache") guard path != nil else { let userInfo = [NSLocalizedFailureReasonErrorKey: "Fatal : missing template: " + templateName] throw NSError.init( domain: "swift-implement-equatable-domain", code: 2, userInfo: userInfo ) } let template = try Template(path: path) let result : String = try template.render(boxDataForStruct(structDecl)) return result.components(separatedBy: "\n").filter({ !$0.hasPrefix("*") }).joined(separator: "\n") } // Mark - Private fileprivate func boxDataForStruct(_ structDecl: StructDeclaration) -> MustacheBox { return Box([ "name": structDecl.name, "field_equality_comparisons": equalityComparisons(structDecl.fieldNames) ]) } fileprivate func equalityComparisons(_ fields: [String]) -> String { return fields.map({ "a." + $0 + " == b." + $0 }).joined(separator: " &&\n ") } }
26479413560336ad8ef7f1b36c16531b
32.422222
106
0.605053
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorSDK.swift
mit
1
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import JDStatusBarNotification import PushKit import SafariServices import DZNWebViewController @objc public class ActorSDK: NSObject, PKPushRegistryDelegate { // // Shared instance // private static let shared = ActorSDK() public static func sharedActor() -> ActorSDK { return shared } // // Root Objects // /// Main Messenger object public var messenger : ACCocoaMessenger! // Actor Style public let style = ActorStyle() /// SDK Delegate public var delegate: ActorSDKDelegate = ActorSDKDelegateDefault() /// SDK Analytics public var analyticsDelegate: ActorSDKAnalytics? // // Configuration // /// Server Endpoints public var endpoints = [ "tcp://front1-mtproto-api-rev3.actor.im:443", "tcp://front2-mtproto-api-rev3.actor.im:443" ] { didSet { trustedKeys = [] } } /// Trusted Server Keys public var trustedKeys = [ "d9d34ed487bd5b434eda2ef2c283db587c3ae7fb88405c3834d9d1a6d247145b", "4bd5422b50c585b5c8575d085e9fae01c126baa968dab56a396156759d5a7b46", "ff61103913aed3a9a689b6d77473bc428d363a3421fdd48a8e307a08e404f02c", "20613ab577f0891102b1f0a400ca53149e2dd05da0b77a728b62f5ebc8095878", "fc49f2f2465f5b4e038ec7c070975858a8b5542aa6ec1f927a57c4f646e1c143", "6709b8b733a9f20a96b9091767ac19fd6a2a978ba0dccc85a9ac8f6b6560ac1a" ] /// API ID public var apiId = 2 /// API Key public var apiKey = "2ccdc3699149eac0a13926c77ca84e504afd68b4f399602e06d68002ace965a3" /// Push registration mode public var autoPushMode = AAAutoPush.AfterLogin /// Push token registration id. Required for sending push tokens public var apiPushId: Int? = nil /// Strategy about authentication public var authStrategy = AAAuthStrategy.PhoneOnly /// Enable phone book import public var enablePhoneBookImport = true /// Invitation URL for apps public var inviteUrl: String = "https://actor.im/dl" /// Privacy Policy URL public var privacyPolicyUrl: String? = nil /// Privacy Policy Text public var privacyPolicyText: String? = nil /// Terms of Service URL public var termsOfServiceUrl: String? = nil /// Terms of Service Text public var termsOfServiceText: String? = nil /// App name public var appName: String = "Actor" /// Use background on welcome screen public var useBackgroundOnWelcomeScreen: Bool? = false /// Support email public var supportEmail: String? = nil /// Support email public var supportActivationEmail: String? = nil /// Support account public var supportAccount: String? = nil /// Support home page public var supportHomepage: String? = "https://actor.im" /// Support account public var supportTwitter: String? = "actorapp" /// Invite url scheme public var inviteUrlScheme: String? = nil /// Web Invite Domain host public var inviteUrlHost: String? = nil /// Enable voice calls feature public var enableCalls: Bool = true /// Enable custom sound on Groups and Chats public var enableChatGroupSound: Bool = false /// Enable experimental features public var enableExperimentalFeatures: Bool = false /// Enable Automatic Download and Save public var enableAutomaticDownload: Bool = true /// Disable this if you want dowloadMediaAutomaticaly public var autoDownloadPhotoContent: Bool = true public var autoDownloadVideoContent: Bool = false let storage = CocoaStorageRuntime() public var isAutomaticDownloadEnabled: Bool { set { storage.preferences.putBoolWithKey("isAutomaticDownloadEnabled", withValue: newValue) } get { return storage.preferences.getBoolWithKey("isAutomaticDownloadEnabled", withDefault: true) } } func setAutomaticDownloads(isEnabled:Bool){ self.isAutomaticDownloadEnabled = isEnabled self.autoDownloadPhotoContent = isEnabled self.autoDownloadVideoContent = isEnabled } // // User Onlines // /// Is User online private(set) public var isUserOnline = false /// Disable this if you want manually handle online states public var automaticOnlineHandling = true // // Internal State // /// Is Actor Started private(set) public var isStarted = false private var binder = AABinder() private var syncTask: UIBackgroundTaskIdentifier? private var completionHandler: ((UIBackgroundFetchResult) -> Void)? // View Binding info private(set) public var bindedToWindow: UIWindow! // Reachability private var reachability: Reachability! public override init() { // Auto Loading Application name if let name = NSBundle.mainBundle().objectForInfoDictionaryKey(String(kCFBundleNameKey)) as? String { self.appName = name } } public func createActor() { if isStarted { return } isStarted = true AAActorRuntime.configureRuntime() let builder = ACConfigurationBuilder() // Api Connections let deviceKey = NSUUID().UUIDString let deviceName = UIDevice.currentDevice().name let appTitle = "Actor iOS" for url in endpoints { builder.addEndpoint(url) } for key in trustedKeys { builder.addTrustedKey(key) } builder.setApiConfiguration(ACApiConfiguration(appTitle: appTitle, withAppId: jint(apiId), withAppKey: apiKey, withDeviceTitle: deviceName, withDeviceId: deviceKey)) // Providers builder.setPhoneBookProvider(PhoneBookProvider()) builder.setNotificationProvider(iOSNotificationProvider()) builder.setCallsProvider(iOSCallsProvider()) // Stats builder.setPlatformType(ACPlatformType.IOS()) builder.setDeviceCategory(ACDeviceCategory.MOBILE()) // Locale for lang in NSLocale.preferredLanguages() { log("Found locale :\(lang)") builder.addPreferredLanguage(lang) } // TimeZone let timeZone = NSTimeZone.defaultTimeZone().name log("Found time zone :\(timeZone)") builder.setTimeZone(timeZone) // Logs // builder.setEnableFilesLogging(true) // Application name builder.setCustomAppName(appName) // Config builder.setPhoneBookImportEnabled(jboolean(enablePhoneBookImport)) builder.setVoiceCallsEnabled(jboolean(enableCalls)) builder.setIsEnabledGroupedChatList(false) // builder.setEnableFilesLogging(true) // Creating messenger messenger = ACCocoaMessenger(configuration: builder.build()) // Configure bubbles AABubbles.layouters = delegate.actorConfigureBubbleLayouters(AABubbles.builtInLayouters) checkAppState() // Bind Messenger LifeCycle binder.bind(messenger.getGlobalState().isSyncing, closure: { (value: JavaLangBoolean?) -> () in if value!.booleanValue() { if self.syncTask == nil { self.syncTask = UIApplication.sharedApplication().beginBackgroundTaskWithName("Background Sync", expirationHandler: { () -> Void in }) } } else { if self.syncTask != nil { UIApplication.sharedApplication().endBackgroundTask(self.syncTask!) self.syncTask = nil } if self.completionHandler != nil { self.completionHandler!(UIBackgroundFetchResult.NewData) self.completionHandler = nil } } }) // Bind badge counter binder.bind(Actor.getGlobalState().globalCounter, closure: { (value: JavaLangInteger?) -> () in if let v = value { UIApplication.sharedApplication().applicationIconBadgeNumber = Int(v.integerValue) } else { UIApplication.sharedApplication().applicationIconBadgeNumber = 0 } }) // Push registration if autoPushMode == .FromStart { requestPush() } // Subscribe to network changes do { reachability = try Reachability.reachabilityForInternetConnection() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ActorSDK.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability) try reachability.startNotifier() } catch { print("Unable to create Reachability") return } } @objc func reachabilityChanged(note: NSNotification) { print("reachabilityChanged (\(reachability.isReachable()))") if reachability.isReachable() { messenger.forceNetworkCheck() } } func didLoggedIn() { // Push registration if autoPushMode == .AfterLogin { requestPush() } var controller: UIViewController! = delegate.actorControllerAfterLogIn() if controller == nil { controller = delegate.actorControllerForStart() } if controller == nil { let tab = AARootTabViewController() tab.viewControllers = self.getMainNavigations() tab.selectedIndex = 0 tab.selectedIndex = 1 if (AADevice.isiPad) { let splitController = AARootSplitViewController() splitController.viewControllers = [tab, AANoSelectionViewController()] controller = splitController } else { controller = tab } } bindedToWindow.rootViewController = controller! } // // Push support // /// Token need to be with stripped everything except numbers and letters func pushRegisterToken(token: String) { if !isStarted { fatalError("Messenger not started") } if apiPushId != nil { messenger.registerApplePushWithApnsId(jint(apiPushId!), withToken: token) } } func pushRegisterKitToken(token: String) { if !isStarted { fatalError("Messenger not started") } if apiPushId != nil { messenger.registerApplePushKitWithApnsId(jint(apiPushId!), withToken: token) } } private func requestPush() { let types: UIUserNotificationType = [.Alert, .Badge, .Sound] let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() } private func requestPushKit() { let voipRegistry = PKPushRegistry(queue: dispatch_get_main_queue()) voipRegistry.delegate = self voipRegistry.desiredPushTypes = Set([PKPushTypeVoIP]) } @objc public func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) { if (type == PKPushTypeVoIP) { let tokenString = "\(credentials.token)".replace(" ", dest: "").replace("<", dest: "").replace(">", dest: "") pushRegisterKitToken(tokenString) } } @objc public func pushRegistry(registry: PKPushRegistry!, didInvalidatePushTokenForType type: String!) { if (type == PKPushTypeVoIP) { } } @objc public func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) { if (type == PKPushTypeVoIP) { let aps = payload.dictionaryPayload["aps"] as! [NSString: AnyObject] if let callId = aps["callId"] as? String { if let attempt = aps["attemptIndex"] as? String { Actor.checkCall(jlong(callId)!, withAttempt: jint(attempt)!) } else { Actor.checkCall(jlong(callId)!, withAttempt: 0) } } else if let seq = aps["seq"] as? String { Actor.onPushReceivedWithSeq(jint(seq)!) } } } /// Get main navigations with check in delegate for customize from SDK private func getMainNavigations() -> [AANavigationController] { var mainNavigations = [AANavigationController]() //////////////////////////////////// // contacts //////////////////////////////////// if let contactsController = self.delegate.actorControllerForContacts() { mainNavigations.append(AANavigationController(rootViewController: contactsController)) } else { mainNavigations.append(AANavigationController(rootViewController: AAContactsViewController())) } //////////////////////////////////// // recent dialogs //////////////////////////////////// if let recentDialogs = self.delegate.actorControllerForDialogs() { mainNavigations.append(AANavigationController(rootViewController: recentDialogs)) } else { mainNavigations.append(AANavigationController(rootViewController: AARecentViewController())) } //////////////////////////////////// // settings //////////////////////////////////// if let settingsController = self.delegate.actorControllerForSettings() { mainNavigations.append(AANavigationController(rootViewController: settingsController)) } else { mainNavigations.append(AANavigationController(rootViewController: AASettingsViewController())) } return mainNavigations; } // // Presenting Messenger // public func presentMessengerInWindow(window: UIWindow) { if !isStarted { fatalError("Messenger not started") } self.bindedToWindow = window if messenger.isLoggedIn() { if autoPushMode == .AfterLogin { requestPush() } var controller: UIViewController! = delegate.actorControllerForStart() if controller == nil { let tab = AARootTabViewController() tab.viewControllers = self.getMainNavigations() tab.selectedIndex = 0 tab.selectedIndex = 1 if (AADevice.isiPad) { let splitController = AARootSplitViewController() splitController.viewControllers = [tab, AANoSelectionViewController()] controller = splitController } else { controller = tab } } window.rootViewController = controller! } else { let controller: UIViewController! = delegate.actorControllerForAuthStart() if controller == nil { window.rootViewController = AAWelcomeController() } else { window.rootViewController = controller } } // Bind Status Bar connecting if !style.statusBarConnectingHidden { JDStatusBarNotification.setDefaultStyle { (style) -> JDStatusBarStyle! in style.barColor = self.style.statusBarConnectingBgColor style.textColor = self.style.statusBarConnectingTextColor return style } dispatchOnUi { () -> Void in self.binder.bind(self.messenger.getGlobalState().isSyncing, valueModel2: self.messenger.getGlobalState().isConnecting) { (isSyncing: JavaLangBoolean?, isConnecting: JavaLangBoolean?) -> () in if isSyncing!.booleanValue() || isConnecting!.booleanValue() { if isConnecting!.booleanValue() { JDStatusBarNotification.showWithStatus(AALocalized("StatusConnecting")) } else { JDStatusBarNotification.showWithStatus(AALocalized("StatusSyncing")) } } else { JDStatusBarNotification.dismiss() } } } } } public func presentMessengerInNewWindow() { let window = UIWindow(frame: UIScreen.mainScreen().bounds); window.backgroundColor = UIColor.whiteColor() presentMessengerInWindow(window) window.makeKeyAndVisible() } // // Data Processing // /// Handling URL Opening in application func openUrl(url: String) { if let u = NSURL(string: url) { // Handle phone call if (u.scheme.lowercaseString == "telprompt") { UIApplication.sharedApplication().openURL(u) return } // Handle web invite url if (u.scheme.lowercaseString == "http" || u.scheme.lowercaseString == "https") && inviteUrlHost != nil { if u.host == inviteUrlHost { if let token = u.lastPathComponent { joinGroup(token) return } } } // Handle custom scheme invite url if (u.scheme.lowercaseString == inviteUrlScheme?.lowercaseString) { if (u.host == "invite") { let token = u.query?.componentsSeparatedByString("=")[1] if token != nil { joinGroup(token!) return } } if let bindedController = bindedToWindow?.rootViewController { let alert = UIAlertController(title: nil, message: AALocalized("ErrorUnableToJoin"), preferredStyle: .Alert) alert.addAction(UIAlertAction(title: AALocalized("AlertOk"), style: .Cancel, handler: nil)) bindedController.presentViewController(alert, animated: true, completion: nil) } return } if (url.isValidUrl()){ if let bindedController = bindedToWindow?.rootViewController { // Dismiss Old Presented Controller to show new one if let presented = bindedController.presentedViewController { presented.dismissViewControllerAnimated(true, completion: nil) } // Building Controller for Web preview let controller: UIViewController if #available(iOS 9.0, *) { controller = SFSafariViewController(URL: u) } else { controller = AANavigationController(rootViewController: DZNWebViewController(URL: u)) } if AADevice.isiPad { controller.modalPresentationStyle = .FullScreen } // Presenting controller bindedController.presentViewController(controller, animated: true, completion: nil) } else { // Just Fallback. Might never happend UIApplication.sharedApplication().openURL(u) } } } } /// Handling joining group by token func joinGroup(token: String) { if let bindedController = bindedToWindow?.rootViewController { let alert = UIAlertController(title: nil, message: AALocalized("GroupJoinMessage"), preferredStyle: .Alert) alert.addAction(UIAlertAction(title: AALocalized("AlertNo"), style: .Cancel, handler: nil)) alert.addAction(UIAlertAction(title: AALocalized("GroupJoinAction"), style: .Default){ (action) -> Void in AAExecutions.execute(Actor.joinGroupViaLinkCommandWithToken(token)!, type: .Safe, ignore: [], successBlock: { (val) -> Void in // TODO: Fix for iPad let groupId = val as! JavaLangInteger let tabBarController = bindedController as! UITabBarController let index = tabBarController.selectedIndex let navController = tabBarController.viewControllers![index] as! UINavigationController if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer.groupWithInt(groupId.intValue)) { navController.pushViewController(customController, animated: true) } else { navController.pushViewController(ConversationViewController(peer: ACPeer.groupWithInt(groupId.intValue)), animated: true) } }, failureBlock: nil) }) bindedController.presentViewController(alert, animated: true, completion: nil) } } /// Tracking page visible func trackPageVisible(page: ACPage) { analyticsDelegate?.analyticsPageVisible(page) } /// Tracking page hidden func trackPageHidden(page: ACPage) { analyticsDelegate?.analyticsPageHidden(page) } /// Tracking event func trackEvent(event: ACEvent) { analyticsDelegate?.analyticsEvent(event) } // // File System // public func fullFilePathForDescriptor(descriptor: String) -> String { return CocoaFiles.pathFromDescriptor(descriptor) } // // Manual Online handling // public func didBecameOnline() { if automaticOnlineHandling { fatalError("Manual Online handling not enabled!") } if !isStarted { fatalError("Messenger not started") } if !isUserOnline { isUserOnline = true messenger.onAppVisible() } } public func didBecameOffline() { if automaticOnlineHandling { fatalError("Manual Online handling not enabled!") } if !isStarted { fatalError("Messenger not started") } if isUserOnline { isUserOnline = false messenger.onAppHidden() } } // // Automatic Online handling // func checkAppState() { if UIApplication.sharedApplication().applicationState == .Active { if !isUserOnline { isUserOnline = true // Mark app as visible messenger.onAppVisible() // Notify Audio Manager about app visiblity change AAAudioManager.sharedAudio().appVisible() // Notify analytics about visibilibty change // Analytics.track(ACAllEvents.APP_VISIBLEWithBoolean(true)) // Hack for resync phone book Actor.onPhoneBookChanged() } } else { if isUserOnline { isUserOnline = false // Notify Audio Manager about app visiblity change AAAudioManager.sharedAudio().appHidden() // Mark app as hidden messenger.onAppHidden() // Notify analytics about visibilibty change // Analytics.track(ACAllEvents.APP_VISIBLEWithBoolean(false)) } } } public func applicationDidFinishLaunching(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } checkAppState() } public func applicationDidBecomeActive(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } checkAppState() } public func applicationWillEnterForeground(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } checkAppState() } public func applicationDidEnterBackground(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } checkAppState() // Keep application running for 40 secs if messenger.isLoggedIn() { var completitionTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid completitionTask = application.beginBackgroundTaskWithName("Completition", expirationHandler: { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid }) // Wait for 40 secs before app shutdown dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(40.0 * Double(NSEC_PER_SEC))), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid } } } public func applicationWillResignActive(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } // // This event is fired when user press power button and lock screeen. // In iOS power button also cancel ongoint call. // // messenger.probablyEndCall() checkAppState() } // // Handling remote notifications // public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { if !messenger.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { // Nothing? } public func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { requestPushKit() } // // Handling background fetch events // public func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { if !messenger.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } // // Handling invite url // func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { dispatchOnUi { () -> Void in self.openUrl(url.absoluteString) } return true } public func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool { dispatchOnUi { () -> Void in self.openUrl(url.absoluteString) } return true } } public enum AAAutoPush { case None case FromStart case AfterLogin } public enum AAAuthStrategy { case PhoneOnly case EmailOnly case PhoneEmail }
b49a66ba8e69544af5037c0ca863afe7
32.701405
197
0.576755
false
false
false
false
orientsun6/cardSwift
refs/heads/master
CardTilt/CardTableViewCell.swift
mit
1
// // CardTableViewCell.swift // CardTilt // // Created by Ray Fix on 6/25/14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // import UIKit import QuartzCore class CardTableViewCell: UITableViewCell { @IBOutlet var mainView: UIView! @IBOutlet var nameLabel: UILabel! @IBOutlet var titleLabel: UILabel! @IBOutlet var locationLabel: UILabel! @IBOutlet var aboutLabel: UILabel! @IBOutlet var profilePictureView: UIImageView! @IBOutlet var webLabel: UILabel! @IBOutlet var webButton: UIButton! @IBOutlet var twitterButton: UIButton! @IBOutlet var twitterImage: UIImageView! @IBOutlet var facebookButton: UIButton! @IBOutlet var facebookImage: UIImageView! var twitter:String? var facebook:String? func useMember(member:Member) { // Round those corners mainView.layer.cornerRadius = 10; mainView.layer.masksToBounds = true; // Fill in the data nameLabel.text = member.name titleLabel.text = member.title locationLabel.text = member.location aboutLabel.text = member.about profilePictureView.image = UIImage(named: member.imageName) // Fill the buttons and show or hide them webLabel.text = member.web if let twitterURLString = member.twitter { twitterImage.hidden = false twitter = twitterURLString } else { twitterImage.hidden = true twitter = nil } if let facebookURLString = member.facebook { facebookImage.hidden = false facebook = facebookURLString } else { facebookImage.hidden = true facebook = nil } } func jumpTo(URLString:String?) { if let URL = NSURL.URLWithString(URLString!) { UIApplication.sharedApplication().openURL(URL) } } @IBAction func webButtonTapped(sender: AnyObject) { jumpTo(webLabel.text) } @IBAction func twitterButtonTapped(sender: AnyObject) { jumpTo(twitter) } @IBAction func facebookButtonTapped(sender: AnyObject) { jumpTo(facebook) } }
3ab410920902660329e47ba9267d30ae
26.85
67
0.626122
false
false
false
false
tony-dinh/today
refs/heads/master
today/today WatchKit Extension/EventList.swift
mit
1
// // EventList.swift // day // // Created by Tony Dinh on 2016-11-04. // Copyright © 2016 Tony Dinh. All rights reserved. // import Foundation import EventKit final class EventList { let eventManager = EventManager.sharedInstance var events: [EKEvent]? { return eventManager.events } init() { if eventManager.accessGranted { eventManager.getTodaysEvents() } else { eventManager.requestAccess() { granted, error in if granted { self.eventManager.getTodaysEvents() } } } } func reloadEvents(completion: ((Bool) -> Void)? = nil) { guard eventManager.accessGranted == true else { completion?(false) return } eventManager.getTodaysEvents() completion?(true) } func eventsEndingBefore(date: Date) -> [EKEvent] { guard let events = events else { return [EKEvent]() } return events.filter({$0.endDate <= date}) } func eventsEndingAfter(date: Date) -> [EKEvent] { guard let events = events else { return [EKEvent]() } return events.filter({$0.endDate > date}) } }
19f0e5ca02ea5c2a6d579ec5bc0da41a
23.192308
60
0.554054
false
false
false
false
argon/WordPress-iOS
refs/heads/buildAndLearn5.5
WordPress/WordPressTodayWidget/TodayViewController.swift
gpl-2.0
10
import UIKit import NotificationCenter class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet var siteNameLabel: UILabel! @IBOutlet var visitorsCountLabel: UILabel! @IBOutlet var visitorsLabel: UILabel! @IBOutlet var viewsCountLabel: UILabel! @IBOutlet var viewsLabel: UILabel! var siteName: String = "" var visitorCount: String = "" var viewCount: String = "" var siteId: NSNumber? override func viewDidLoad() { super.viewDidLoad() let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)! self.siteId = sharedDefaults.objectForKey(WPStatsTodayWidgetUserDefaultsSiteIdKey) as! NSNumber? visitorsLabel?.text = NSLocalizedString("Visitors", comment: "Stats Visitors Label") viewsLabel?.text = NSLocalizedString("Views", comment: "Stats Views Label") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // Manual state restoration var userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject(self.siteName, forKey: WPStatsTodayWidgetUserDefaultsSiteNameKey) userDefaults.setObject(self.visitorCount, forKey: WPStatsTodayWidgetUserDefaultsVisitorCountKey) userDefaults.setObject(self.viewCount, forKey: WPStatsTodayWidgetUserDefaultsViewCountKey) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Manual state restoration let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)! self.siteName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteNameKey) ?? "" let userDefaults = NSUserDefaults.standardUserDefaults() self.visitorCount = userDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsVisitorCountKey) ?? "0" self.viewCount = userDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsViewCountKey) ?? "0" self.siteNameLabel?.text = self.siteName self.visitorsCountLabel?.text = self.visitorCount self.viewsCountLabel?.text = self.viewCount } @IBAction func launchContainingApp() { self.extensionContext!.openURL(NSURL(string: "\(WPCOM_SCHEME)://viewstats?siteId=\(siteId!)")!, completionHandler: nil) } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) { // Perform any setup necessary in order to update the view. // If an error is encoutered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)! let siteId = sharedDefaults.objectForKey(WPStatsTodayWidgetUserDefaultsSiteIdKey) as! NSNumber? self.siteName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteNameKey) ?? "" let timeZoneName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteTimeZoneKey) let oauth2Token = self.getOAuth2Token() if siteId == nil || timeZoneName == nil || oauth2Token == nil { WPDDLogWrapper.logError("Missing site ID, timeZone or oauth2Token") let bundle = NSBundle(forClass: TodayViewController.classForCoder()) NCWidgetController.widgetController().setHasContent(false, forWidgetWithBundleIdentifier: bundle.bundleIdentifier) completionHandler(NCUpdateResult.Failed) return } let timeZone = NSTimeZone(name: timeZoneName!) var statsService: WPStatsService = WPStatsService(siteId: siteId, siteTimeZone: timeZone, oauth2Token: oauth2Token, andCacheExpirationInterval:0) statsService.retrieveTodayStatsWithCompletionHandler({ (wpStatsSummary: StatsSummary!, error: NSError!) -> Void in WPDDLogWrapper.logInfo("Downloaded data in the Today widget") self.visitorCount = wpStatsSummary.visitors self.viewCount = wpStatsSummary.views self.siteNameLabel?.text = self.siteName self.visitorsCountLabel?.text = self.visitorCount self.viewsCountLabel?.text = self.viewCount completionHandler(NCUpdateResult.NewData) }, failureHandler: { (error) -> Void in WPDDLogWrapper.logError("\(error)") completionHandler(NCUpdateResult.Failed) }) } func getOAuth2Token() -> String? { var error:NSError? var oauth2Token:NSString? = SFHFKeychainUtils.getPasswordForUsername(WPStatsTodayWidgetOAuth2TokenKeychainUsername, andServiceName: WPStatsTodayWidgetOAuth2TokenKeychainServiceName, accessGroup: WPStatsTodayWidgetOAuth2TokenKeychainAccessGroup, error: &error) return oauth2Token as String? } }
563e128c5b33f0ea084c20b2154b71c3
45.766355
267
0.697981
false
false
false
false
christophhagen/Signal-iOS
refs/heads/master
SignalMessaging/Views/OWSFlatButton.swift
gpl-3.0
1
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import SignalServiceKit @objc public class OWSFlatButton: UIView { let TAG = "[OWSFlatButton]" private let button: UIButton private var pressedBlock : (() -> Void)? private var upColor: UIColor? private var downColor: UIColor? override public var backgroundColor: UIColor? { willSet { owsFail("Use setBackgroundColors(upColor:) instead.") } } @objc public init() { AssertIsOnMainThread() button = UIButton(type:.custom) super.init(frame:CGRect.zero) createContent() } @available(*, unavailable, message:"use other constructor instead.") required public init?(coder aDecoder: NSCoder) { fatalError("\(#function) is unimplemented.") } private func createContent() { self.addSubview(button) button.addTarget(self, action:#selector(buttonPressed), for:.touchUpInside) button.autoPinToSuperviewEdges() } @objc public class func button(title: String, font: UIFont, titleColor: UIColor, backgroundColor: UIColor, width: CGFloat, height: CGFloat, target:Any, selector: Selector) -> OWSFlatButton { let button = OWSFlatButton() button.setTitle(title:title, font: font, titleColor: titleColor ) button.setBackgroundColors(upColor:backgroundColor) button.useDefaultCornerRadius() button.setSize(width:width, height:height) button.addTarget(target:target, selector:selector) return button } @objc public class func button(title: String, titleColor: UIColor, backgroundColor: UIColor, width: CGFloat, height: CGFloat, target:Any, selector: Selector) -> OWSFlatButton { return OWSFlatButton.button(title:title, font:fontForHeight(height), titleColor:titleColor, backgroundColor:backgroundColor, width:width, height:height, target:target, selector:selector) } @objc public class func button(title: String, font: UIFont, titleColor: UIColor, backgroundColor: UIColor, target:Any, selector: Selector) -> OWSFlatButton { let button = OWSFlatButton() button.setTitle(title:title, font: font, titleColor: titleColor ) button.setBackgroundColors(upColor:backgroundColor) button.useDefaultCornerRadius() button.addTarget(target:target, selector:selector) return button } @objc public class func fontForHeight(_ height: CGFloat) -> UIFont { // Cap the "button height" at 40pt or button text can look // excessively large. let fontPointSize = round(min(40, height) * 0.45) return UIFont.ows_mediumFont(withSize:fontPointSize)! } // MARK: Methods @objc public func setTitle(title: String, font: UIFont, titleColor: UIColor ) { button.setTitle(title, for: .normal) button.setTitleColor(titleColor, for: .normal) button.titleLabel!.font = font } @objc public func setBackgroundColors(upColor: UIColor, downColor: UIColor ) { button.setBackgroundImage(UIImage(color:upColor), for: .normal) button.setBackgroundImage(UIImage(color:downColor), for: .highlighted) } @objc public func setBackgroundColors(upColor: UIColor ) { setBackgroundColors(upColor: upColor, downColor: upColor.withAlphaComponent(0.7) ) } @objc public func setSize(width: CGFloat, height: CGFloat) { button.autoSetDimension(.width, toSize:width) button.autoSetDimension(.height, toSize:height) } @objc public func useDefaultCornerRadius() { // To my eye, this radius tends to look right regardless of button size // (within reason) or device size. button.layer.cornerRadius = 5 button.clipsToBounds = true } @objc public func setEnabled(_ isEnabled: Bool) { button.isEnabled = isEnabled } @objc public func addTarget(target:Any, selector: Selector) { button.addTarget(target, action:selector, for:.touchUpInside) } @objc public func setPressedBlock(_ pressedBlock: @escaping () -> Void) { guard self.pressedBlock == nil else { owsFail("Button already has pressed block.") return } self.pressedBlock = pressedBlock } @objc internal func buttonPressed() { pressedBlock?() } }
ff5e369ddff2a63fe3a80f7cc3ef3c0c
30.812865
83
0.546324
false
false
false
false
gtranchedone/NFYU
refs/heads/master
NFYUTests/MocksAndStubs/FakeLocationManager.swift
mit
1
// // FakeLocationManager.swift // NFYU // // Created by Gianluca Tranchedone on 02/11/2015. // Copyright © 2015 Gianluca Tranchedone. All rights reserved. // import Foundation import CoreLocation @testable import NFYU class FakeUserLocationManager: UserLocationManager { private(set) var didRequestPermissions = false private(set) var didRequestCurrentLocation = false var allowUseOfLocationServices = false var shouldCallCompletionBlock = true var stubDidRequestPermissions = true var stubResult: UserLocationManagerResult? var locationServicesEnabled: Bool { return allowUseOfLocationServices } var didRequestAuthorization: Bool { return didRequestPermissions } @discardableResult func requestUserAuthorizationForUsingLocationServices(_ completionBlock: @escaping () -> ()) -> Bool { didRequestPermissions = stubDidRequestPermissions completionBlock() return stubDidRequestPermissions } @discardableResult func requestCurrentLocation(_ completionBlock: @escaping (UserLocationManagerResult) -> ()) { didRequestCurrentLocation = true if let stubResult = stubResult, shouldCallCompletionBlock { completionBlock(stubResult) } } } class FakeLocationManager: CLLocationManager { static var stubAuthorizationStatus: CLAuthorizationStatus = .notDetermined var didRequestAuthorizationForInUse = false var didRequestLocation = false override class func authorizationStatus() -> CLAuthorizationStatus { return stubAuthorizationStatus } override func requestLocation() { didRequestLocation = true } override func requestWhenInUseAuthorization() { didRequestAuthorizationForInUse = true } }
04749358f14c989a8b654fd879c6fda7
27.765625
125
0.715372
false
false
false
false
Gorgodzila/iOS-Trainings
refs/heads/master
NewMyInstagramm/NewMyInstagramm/Registration.swift
apache-2.0
1
// // Registration.swift // NewMyInstagramm // // Created by Korneli Mamulashvili on 6/4/17. // Copyright © 2017 Kakha Mamulashvili. All rights reserved. // import UIKit class Registration: UIViewController { @IBOutlet weak var txtUserName: UITextField! @IBOutlet weak var txtPass: UITextField! @IBAction func regPressButton(_ sender: UIButton) { } @IBAction func loginPressButton(_ sender: UIButton) { if !txtUserName.text!.isEmpty || !txtPass.text!.isEmpty { // temp variables to hold textFields info let userEmail = txtUserName.text! let pass = txtPass.text! // create data load variable let defaults = UserDefaults.standard // load real password and email let realUserEmail = defaults.value(forKey: "userEmail") as! String // KEY: 'userEmail' holds email let realPassword = defaults.value(forKey: "userPassw") as! String // KEY: 'userPassw' holds password // check if typed password and email matches origianl a.k.a real password and email if realUserEmail == userEmail && realPassword == pass { let vc = storyboard?.instantiateViewController(withIdentifier: "xxxBaseScreen") as! BaseScreen self.navigationController?.pushViewController(vc, animated: true) } } else { print("Fields are empty!") } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } extension Registration: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if !textField.text!.isEmpty { print("Jigaro") } else { print("Figaro") } return true } func isKeyPresentInUserDefaults(key: String) -> Bool { return UserDefaults.standard.object(forKey: key) != nil } }
ffe0aa159c29d112b2cc7eab34875308
26.946667
112
0.587786
false
false
false
false
flyuqian/abcd
refs/heads/master
FlyuABCD/FlyuABCD/Configur/UIColor+Extention.swift
unlicense
1
// // UIColor+Extention.swift // FlyuABCD // // Created by coding Tools on 16/10/26. // Copyright © 2016年 1236544. All rights reserved. // import Foundation import UIKit extension UIColor { class func randomColor() -> UIColor { let colorR: CGFloat = CGFloat(arc4random_uniform(255)) / 255.0 let colorG: CGFloat = CGFloat(arc4random_uniform(255)) / 255.0 let colorB: CGFloat = CGFloat(arc4random_uniform(255)) / 255.0 return UIColor(red: colorR, green: colorG, blue: colorB, alpha: 1.0) } class func RGB(R: Int, G: Int, B: Int) -> UIColor { let colorR: CGFloat = CGFloat(R) / 255.0 let colorG: CGFloat = CGFloat(G) / 255.0 let colorB: CGFloat = CGFloat(B) / 255.0 return UIColor(red: colorR, green: colorG, blue: colorB, alpha: 1.0) } }
0bb3a53a92e3aeb3a47d7e4a33fa98f1
27.333333
76
0.612941
false
false
false
false
bugsnag/bugsnag-cocoa
refs/heads/master
features/fixtures/shared/scenarios/AppAndDeviceAttributesCallbackOverrideScenario.swift
mit
1
class AppAndDeviceAttributesCallbackOverrideScenario: Scenario { override func startBugsnag() { self.config.autoTrackSessions = false self.config.addOnSendError { (event) -> Bool in event.app.type = "newAppType" event.app.releaseStage = "thirdStage" event.app.version = "999" event.app.bundleVersion = "42" event.device.manufacturer = "Nokia" event.device.modelNumber = "0898" return true } super.startBugsnag() } override func run() { let error = NSError(domain: "AppAndDeviceAttributesCallbackOverrideScenario", code: 100, userInfo: nil) Bugsnag.notifyError(error) } }
ca894334d3c3613e0fce8f30f7dfcfc2
29.166667
111
0.617403
false
true
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/NCTransferViewController.swift
lgpl-2.1
2
// // NCTransferViewController.swift // Neocom // // Created by Artem Shimanski on 17.10.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import Foundation import CoreData import EVEAPI import Futures class NCTransferRow: TreeRow { let loadout: (typeID: Int, data: NCFittingLoadout, name: String) lazy var type: NCDBInvType? = { return NCDatabase.sharedDatabase?.invTypes[self.loadout.typeID] }() init(loadout: (typeID: Int, data: NCFittingLoadout, name: String)) { self.loadout = loadout super.init(prototype: Prototype.NCDefaultTableViewCell.default) } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCDefaultTableViewCell else {return} cell.titleLabel?.text = type?.typeName cell.iconView?.image = type?.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image cell.subtitleLabel?.text = loadout.name } } class NCTransferViewController: NCTreeViewController { @IBOutlet weak var selectAllItem: UIBarButtonItem! var loadouts: NCLoadoutRepresentation? private var allRows: [TreeNode]? override func viewDidLoad() { super.viewDidLoad() navigationController?.setToolbarHidden(false, animated: false) setEditing(true, animated: false) tableView.register([Prototype.NCHeaderTableViewCell.default, Prototype.NCDefaultTableViewCell.default]) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) let fileManager = FileManager.default guard let groupURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.shimanski.neocom") else {return} let flagURL = groupURL.appendingPathComponent(".already_transferred") try? "".write(to: flagURL, atomically: true, encoding: .utf8) let loadoutsURL = groupURL.appendingPathComponent("loadouts.xml") try? fileManager.removeItem(at: loadoutsURL) } override func content() -> Future<TreeNode?> { if let loadouts = loadouts?.loadouts { return NCDatabase.sharedDatabase!.performBackgroundTask { managedObjectContext -> TreeNode? in let invTypes = NCDBInvType.invTypes(managedObjectContext: managedObjectContext) var groups = [String: [NCTransferRow]]() for loadout in loadouts { guard let type = invTypes[loadout.typeID] else {continue} guard let group = type.group?.groupName?.uppercased() else {continue} groups[group, default: []].append(NCTransferRow(loadout: loadout)) } let sections = groups.sorted {$0.key < $1.key}.map { DefaultTreeSection(title: $0.key, children: $0.value) } guard !sections.isEmpty else {throw NCTreeViewControllerError.noResult} return RootNode(sections) }.finally(on: .main) { guard let sections = self.treeController?.content?.children else {return} let allRows = sections.map{$0.children}.joined() allRows.forEach { self.treeController?.selectCell(for: $0, animated: false, scrollPosition: .none) } self.allRows = Array(allRows) self.updateButtons() } } else { return .init(.failure(NCTreeViewControllerError.noResult)) } } @IBAction func onCancel(_ sender: Any) { let controller = UIAlertController(title: NSLocalizedString("Cancel Import", comment: ""), message: NSLocalizedString("Are you sure you want to cancel? You can finish import later.", comment: ""), preferredStyle: .alert) controller.addAction(UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default, handler: { [weak self] (_) in self?.dismiss(animated: true, completion: nil) })) controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil)) present(controller, animated: true, completion: nil) } @IBAction func onDone(_ sender: Any) { dismiss(animated: true, completion: nil) guard let loadouts = loadouts?.loadouts, !loadouts.isEmpty else {return} let progress = NCProgressHandler(viewController: self, totalUnitCount: Int64(loadouts.count)) UIApplication.shared.beginIgnoringInteractionEvents() NCStorage.sharedStorage?.performBackgroundTask { managedObjectContext in loadouts.forEach { i in let loadout = NCLoadout(entity: NSEntityDescription.entity(forEntityName: "Loadout", in: managedObjectContext)!, insertInto: managedObjectContext) loadout.data = NCLoadoutData(entity: NSEntityDescription.entity(forEntityName: "LoadoutData", in: managedObjectContext)!, insertInto: managedObjectContext) loadout.typeID = Int32(i.typeID) loadout.name = i.name loadout.data?.data = i.data loadout.uuid = UUID().uuidString progress.progress.completedUnitCount += 1 } DispatchQueue.main.async { progress.finish() UIApplication.shared.endIgnoringInteractionEvents() self.dismiss(animated: true, completion: nil) } } } @IBAction func onSelectAll(_ sender: Any) { if treeController?.selectedNodes().count == allRows?.count { treeController?.selectedNodes().forEach { treeController?.deselectCell(for: $0, animated: true) } } else { allRows?.forEach { treeController?.selectCell(for: $0, animated: true, scrollPosition: .none) } } } func treeController(_ treeController: TreeController, editActionsForNode node: TreeNode) -> [UITableViewRowAction]? { return node is NCTransferRow ? [] : nil } override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) { super.treeController(treeController, didSelectCellWithNode: node) updateButtons() } override func treeController(_ treeController: TreeController, didDeselectCellWithNode node: TreeNode) { super.treeController(treeController, didDeselectCellWithNode: node) updateButtons() } private func updateButtons() { if allRows?.isEmpty == false { selectAllItem.isEnabled = true if treeController?.selectedNodes().count == allRows?.count { selectAllItem.title = NSLocalizedString("Deselect All", comment: "") } else { selectAllItem.title = NSLocalizedString("Select All", comment: "") } } } }
1b47f92a5fc7a156238270fbe8dd98bc
35.251497
222
0.734886
false
false
false
false
tomburns/ios
refs/heads/master
FiveCalls/FiveCalls/AboutViewController.swift
mit
1
// // AboutViewController.swift // FiveCalls // // Created by Alex on 2/6/17. // Copyright © 2017 5calls. All rights reserved. // import Foundation import UIKit import MessageUI import CPDAcknowledgements import Crashlytics class AboutViewController : UITableViewController, MFMailComposeViewControllerDelegate { static let appId = "1202558609" static let appUrl = URL(string: "https://itunes.apple.com/us/app/myapp/id\(appId)?ls=1&mt=8") @IBOutlet weak var feedbackCell: UITableViewCell! @IBOutlet weak var followOnTwitterCell: UITableViewCell! @IBOutlet weak var shareCell: UITableViewCell! @IBOutlet weak var rateCell: UITableViewCell! @IBOutlet weak var openSourceCell: UITableViewCell! @IBOutlet weak var showWelcomeCell: UITableViewCell! override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.tintColor = .white Answers.logCustomEvent(withName:"Screen: About") } @IBAction func close(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let clickedCell = tableView.cellForRow(at: indexPath) else { return } switch clickedCell { case feedbackCell: sendFeedback() case followOnTwitterCell: followOnTwitter() case shareCell: shareApp(from: tableView.cellForRow(at: indexPath)) case rateCell: promptForRating() case openSourceCell: showOpenSource() case showWelcomeCell: showWelcome() default: break; } tableView.deselectRow(at: indexPath, animated: true) } func sendFeedback() { Answers.logCustomEvent(withName: "Action: Feedback") if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setToRecipients(["[email protected]"]) mail.setMessageBody("", isHTML: true) present(mail, animated: true) } else { let alertController = UIAlertController(title: R.string.localizable.cantSendEmailTitle(), message: R.string.localizable.cantSendEmailMessage(), preferredStyle: .alert) alertController.addAction(UIAlertAction(title: R.string.localizable.dismissTitle(), style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } } func promptForRating() { Answers.logCustomEvent(withName: "Action: Rate the App") guard let url = URL(string: "itms-apps://itunes.apple.com/app/viewContentsUserReviews?id=\(AboutViewController.appId)") else { return } UIApplication.shared.fvc_open(url) } func shareApp(from view: UIView?) { Answers.logCustomEvent(withName: "Action: Share The App") guard let url = AboutViewController.appUrl else { return } let vc = UIActivityViewController(activityItems: [R.string.localizable.shareTheAppMessage(), url], applicationActivities: []) vc.excludedActivityTypes = [.addToReadingList, .airDrop, .assignToContact, .copyToPasteboard, .openInIBooks, .print, .saveToCameraRoll] if UIDevice.current.userInterfaceIdiom == .pad { vc.popoverPresentationController?.sourceRect = view?.bounds ?? self.view.bounds vc.popoverPresentationController?.sourceView = view ?? self.view } self.present(vc, animated: true, completion: nil) } func followOnTwitter() { Answers.logCustomEvent(withName: "Action: Follow On Twitter") guard let url = URL(string: "https://twitter.com/make5calls") else { return } UIApplication.shared.fvc_open(url) } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true) } func showOpenSource() { Answers.logCustomEvent(withName: "Screen: Open Source Libraries") let acknowledgementsVC = CPDAcknowledgementsViewController(style: nil, acknowledgements: nil, contributions: nil) navigationController?.pushViewController(acknowledgementsVC, animated: true) } func showWelcome() { let welcomeVC = R.storyboard.welcome.welcomeViewController()! welcomeVC.completionBlock = { [weak self] in self?.dismiss(animated: true, completion: nil) } present(welcomeVC, animated: true) } }
6a40b11bcca65af5c854df5b280f1eb1
39.871795
179
0.674195
false
false
false
false
maciejtrybilo/BioSwift
refs/heads/master
BioSwift/NucleicAcid.swift
mit
1
// // NucleicAcid.swift // BioSwift // // Created by Maciej Trybilo on 29/02/2016. // Copyright © 2016 Maciej Trybilo. 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 public struct NucleicAcid: Equatable, CustomStringConvertible { public let identifier: String? public let desc: String? let nucleotides: [Nucleotide] public init(nucleotides: [Nucleotide], identifier: String? = nil, desc: String? = nil) { self.identifier = identifier self.desc = desc self.nucleotides = nucleotides } public init?(_ string: String) { if string.isEmpty { return nil } var nucleotides = [Nucleotide]() var lines = string.componentsSeparatedByCharactersInSet(.newlineCharacterSet()) var identifier: String? = nil var desc: String? = nil if let firstLine = lines.first where firstLine.hasPrefix(">") { // description starts after ">" let defline = firstLine.substringFromIndex(firstLine.rangeOfString(">")!.startIndex.successor()) if let nameEndIndex = defline.rangeOfCharacterFromSet(.whitespaceCharacterSet())?.startIndex { identifier = defline.substringToIndex(nameEndIndex).stringByTrimmingCharactersInSet(.whitespaceCharacterSet()) identifier = identifier!.isEmpty ? nil : identifier desc = defline.substringFromIndex(nameEndIndex).stringByTrimmingCharactersInSet(.whitespaceCharacterSet()) desc = desc!.isEmpty ? nil : desc } lines.removeFirst() } self.identifier = identifier self.desc = desc for line in lines { for character in line.characters { if let nucleotide = Nucleotide(character) { nucleotides += [nucleotide] } else { return nil } } } self.nucleotides = nucleotides } public subscript(var subRange: Range<Int>) -> NucleicAcid? { if subRange.startIndex >= nucleotides.count { return nil } if subRange.endIndex >= nucleotides.count { subRange.endIndex = nucleotides.count } return NucleicAcid(nucleotides: Array<Nucleotide>(self.nucleotides[subRange])) } public func complement() -> NucleicAcid { var nucleotides = [Nucleotide]() for nucleotide in self.nucleotides { nucleotides += [nucleotide.complement()] } return NucleicAcid(nucleotides: nucleotides) } public func reverse() -> NucleicAcid { return NucleicAcid(nucleotides: nucleotides.reverse()) } public func toString() -> String { var string = "" for nucleotide in nucleotides { string.append(nucleotide.toCharacter()) } return string } } // MARK: - CustomStringConvertible extension NucleicAcid { public var description: String { return toString() } } // MARK: - Equatable public func ==(lhs: NucleicAcid, rhs: NucleicAcid) -> Bool { if lhs.nucleotides.count != rhs.nucleotides.count { return false } for (idx, element) in lhs.nucleotides.enumerate() { if element != rhs.nucleotides[idx] { return false } } return true }
4fe1855f870f1e904f922d1ab5ce8688
30.413333
126
0.608447
false
false
false
false
customerly/Customerly-iOS-SDK
refs/heads/master
CustomerlySDK/Library/Subclasses/CyTableView.swift
apache-2.0
1
// // CyTableView.swift // Customerly // // Created by Paolo Musolino on 08/12/16. // Copyright © 2016 Customerly. All rights reserved. // import UIKit class CyTableView: UITableView { private var refresh: (() -> Void)? private var pullToRefresh : UIRefreshControl? override func awakeFromNib() { super.awakeFromNib() } func addPullToRefresh(action: (() -> Void)? = nil){ // Initialize the refresh control. pullToRefresh = UIRefreshControl() pullToRefresh?.backgroundColor = UIColor.clear pullToRefresh?.tintColor = UIColor.gray pullToRefresh?.attributedTitle = NSAttributedString(string: "pullToRefresh".localized(comment: "Extra")) pullToRefresh?.addTarget(self, action: #selector(refreshStart), for: UIControl.Event.valueChanged) self.addSubview(pullToRefresh!) self.refresh = action } func endPulltoRefresh(){ pullToRefresh?.endRefreshing() } func pullToRefreshIsRefreshing() -> Bool{ return pullToRefresh?.isRefreshing ?? false } @objc func refreshStart(){ self.refresh?() } }
18913dae5ee6165fe5179ec93eaba45a
24.782609
112
0.63575
false
false
false
false
coderwjq/swiftweibo
refs/heads/master
SwiftWeibo/SwiftWeibo/Classes/Compose/ComposeViewController.swift
apache-2.0
1
// // ComposeViewController.swift // SwiftWeibo // // Created by mzzdxt on 2016/11/7. // Copyright © 2016年 wjq. All rights reserved. // import UIKit import SVProgressHUD class ComposeViewController: UIViewController { // MARK:- 控件的属性 @IBOutlet weak var textView: ComposeTextView! @IBOutlet weak var picPickerView: PicPickerCollectionView! // MARK:- 懒加载属性 fileprivate lazy var titleView: ComposeTitleView = ComposeTitleView() fileprivate lazy var images: [UIImage] = [UIImage]() fileprivate lazy var emoticonVc: EmoticonController = EmoticonController {[weak self] (emoticon) in self?.textView.insertEmoticon(emoticon: emoticon) self?.textViewDidChange(self!.textView) } // MARK:- 约束的属性 @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint! @IBOutlet weak var picPickerViewHCons: NSLayoutConstraint! // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 设置导航栏 setupNavigationBar() // 监听通知 setupNotifications() // 设置代理 textView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 在界面显示完成后再弹出键盘 textView.becomeFirstResponder() } deinit { NotificationCenter.default.removeObserver(self) } } // MARK:- 设置UI界面 extension ComposeViewController { fileprivate func setupNavigationBar() { // 设置左右item navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(ComposeViewController.closeItemClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(ComposeViewController.sendItemClick)) navigationItem.rightBarButtonItem?.isEnabled = false // 设置标题 titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40) navigationItem.titleView = titleView } fileprivate func setupNotifications() { // 监听键盘的弹出 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(note:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) // 监听添加照片按钮的点击 NotificationCenter.default.addObserver(self, selector: #selector(addPhotoClick), name: NSNotification.Name(rawValue: PicPickerAddPhotoNote), object: nil) // 监听删除照片按钮的点击 NotificationCenter.default.addObserver(self, selector: #selector(removePhotoClick(note:)), name: NSNotification.Name(rawValue: PicPickerRemovePhotoNote), object: nil) } } // MARK:- 事件监听函数 extension ComposeViewController { @objc fileprivate func closeItemClick() { dismiss(animated: true, completion: nil) } @objc fileprivate func sendItemClick() { // 键盘退出 textView.resignFirstResponder() // 获取要发送的微博正文 let statusText = textView.getEmoticonString() // 定义回调的闭包 let finishedCallback = { (isSucess: Bool) -> () in if !isSucess { SVProgressHUD.showError(withStatus: "发送微博失败") } SVProgressHUD.showSuccess(withStatus: "发送微博成功") self.dismiss(animated: true, completion: nil) } // 获取用户选中的图片 if let image = images.first { NetworkTools.sharedInstance.sendStatus(statusText: statusText, image: image, isSucess: finishedCallback) } else { NetworkTools.sharedInstance.sendStatus(statusText: statusText, isSucess: finishedCallback) } } @objc fileprivate func keyboardWillChangeFrame(note: Notification) { // 获取动画执行的时间 let duration = (note as NSNotification).userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval // 获取键盘的最终Y值 let endFrame = ((note as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let y = endFrame.origin.y // 计算工具栏距离底部的间距 let margin = UIScreen.main.bounds.height - y; // 执行动画 toolBarBottomCons.constant = margin UIView.animate(withDuration: duration, animations: { self.view.layoutIfNeeded() }, completion: nil) } @IBAction func picPickerBtnClick() { // 退出键盘 textView.resignFirstResponder() // 执行动画 picPickerViewHCons.constant = UIScreen.main.bounds.height * 0.65 UIView.animate(withDuration: 0.5, animations: { () -> Void in self.view.layoutIfNeeded() }) } @IBAction func emoticonBtnClick() { // 1.退出键盘 textView.resignFirstResponder() // 2.切换键盘 textView.inputView = textView.inputView != nil ? nil : emoticonVc.view // 3.弹出键盘 textView.becomeFirstResponder() } } // MARK:- 添加照片和删除照片的事件 extension ComposeViewController { @objc fileprivate func addPhotoClick() { // 判断数据源是否可用 if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { return } // 创建照片选择控制器 let ipc = UIImagePickerController() // 设置照片源 ipc.sourceType = .photoLibrary // 设置代理 ipc.delegate = self // 弹出选择照片的控制器 present(ipc, animated: true, completion: nil) } @objc fileprivate func removePhotoClick(note: Notification) { // 获取image对象 guard let image = note.object as? UIImage else { print("未获取到image对象") return } // 获取image对象所在的下标值 guard let index = images.index(of: image) else { print("未获取到index") return } // 将图片从数组删除 images.remove(at: index) // 重新赋值collectionView新的数组 picPickerView.images = images } } // MARK:- UIImagePickerController的代理方法 extension ComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // 获取选中的图片 let image = info[UIImagePickerControllerOriginalImage] as! UIImage // 将选中图片添加到数组 images.append(image) // 将数组赋值给collectionView并展示数据 picPickerView.images = images // 退出选中照片的控制器 picker.dismiss(animated: true, completion: nil) } } // MARK:- UITextView的代理方法 extension ComposeViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { self.textView.placeHolderLabel.isHidden = textView.hasText navigationItem.rightBarButtonItem?.isEnabled = textView.hasText } func scrollViewDidScroll(_ scrollView: UIScrollView) { textView.resignFirstResponder() } }
fe44f239167b912e2cea10fc472145d7
30.477477
174
0.632084
false
false
false
false
DanielAsher/VIPER-SWIFT
refs/heads/master
Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/RxTest+Controls.swift
apache-2.0
3
// // RxTest+Controls.swift // Rx // // Created by Krunoslav Zaher on 3/12/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation import RxCocoa import RxSwift import XCTest extension RxTest { func ensurePropertyDeallocated<C, T: Equatable where C: NSObject>(createControl: () -> C, _ initialValue: T, _ propertySelector: C -> ControlProperty<T>) { let variable = Variable(initialValue) var completed = false var deallocated = false var lastReturnedPropertyValue: T! autoreleasepool { var control: C! = createControl() let property = propertySelector(control) let disposable = variable.asObservable().bindTo(property) _ = property.subscribe(onNext: { n in lastReturnedPropertyValue = n }, onCompleted: { completed = true disposable.dispose() }) _ = control.rx_deallocated.subscribeNext { _ in deallocated = true } control = nil } // this code is here to flush any events that were scheduled to // run on main loop dispatch_async(dispatch_get_main_queue()) { let runLoop = CFRunLoopGetCurrent() CFRunLoopStop(runLoop) } let runLoop = CFRunLoopGetCurrent() CFRunLoopWakeUp(runLoop) CFRunLoopRun() XCTAssertTrue(deallocated) XCTAssertTrue(completed) XCTAssertEqual(initialValue, lastReturnedPropertyValue) } func ensureEventDeallocated<C, T where C: NSObject>(createControl: () -> C, _ eventSelector: C -> ControlEvent<T>) { return ensureEventDeallocated({ () -> (C, Disposable) in (createControl(), NopDisposable.instance) }, eventSelector) } func ensureEventDeallocated<C, T where C: NSObject>(createControl: () -> (C, Disposable), _ eventSelector: C -> ControlEvent<T>) { var completed = false var deallocated = false let outerDisposable = SingleAssignmentDisposable() autoreleasepool { let (control, disposable) = createControl() let eventObservable = eventSelector(control) _ = eventObservable.subscribe(onNext: { n in }, onCompleted: { completed = true }) _ = control.rx_deallocated.subscribeNext { _ in deallocated = true } outerDisposable.disposable = disposable } outerDisposable.dispose() XCTAssertTrue(deallocated) XCTAssertTrue(completed) } func ensureControlObserverHasWeakReference<C, T where C: NSObject>(@autoclosure createControl: () -> (C), _ observerSelector: C -> AnyObserver<T>, _ observableSelector: () -> (Observable<T>)) { var deallocated = false let disposeBag = DisposeBag() autoreleasepool { let control = createControl() let propertyObserver = observerSelector(control) let observable = observableSelector() observable.bindTo(propertyObserver).addDisposableTo(disposeBag) _ = control.rx_deallocated.subscribeNext { _ in deallocated = true } } XCTAssertTrue(deallocated) } }
494ce46df373df2cee723abaff9fb438
29.117117
197
0.602932
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/CardViewController.swift
mit
1
// // CardViewController.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/9/4. // Copyright © 2017年 伯驹 黄. All rights reserved. // import UIKit class CardViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .blue view.addSubview(UIView()) let items = (0 ... 3).map { $0.description } let vipDetailHeader = LinerCardView(datas: items) vipDetailHeader.delgete = self vipDetailHeader.frame.origin.y = 100 view.addSubview(vipDetailHeader) } } extension CardViewController: LinerCardViewDelegate { func didSelectItem(at index: Int, model: String) { print(index) } }
38efff1d4965d2f390d06aab34072790
21.75
57
0.648352
false
false
false
false
KyoheiG3/AttributedLabel
refs/heads/master
AttributedLabel/AttributedLabel.swift
mit
1
// // AttributedLabel.swift // AttributedLabel // // Created by Kyohei Ito on 2015/07/17. // Copyright © 2015年 Kyohei Ito. All rights reserved. // import UIKit @IBDesignable open class AttributedLabel: UIView { public enum ContentAlignment: Int { case center case top case bottom case left case right case topLeft case topRight case bottomLeft case bottomRight func alignOffset(viewSize: CGSize, containerSize: CGSize) -> CGPoint { let xMargin = viewSize.width - containerSize.width let yMargin = viewSize.height - containerSize.height switch self { case .center: return CGPoint(x: max(xMargin / 2, 0), y: max(yMargin / 2, 0)) case .top: return CGPoint(x: max(xMargin / 2, 0), y: 0) case .bottom: return CGPoint(x: max(xMargin / 2, 0), y: max(yMargin, 0)) case .left: return CGPoint(x: 0, y: max(yMargin / 2, 0)) case .right: return CGPoint(x: max(xMargin, 0), y: max(yMargin / 2, 0)) case .topLeft: return CGPoint(x: 0, y: 0) case .topRight: return CGPoint(x: max(xMargin, 0), y: 0) case .bottomLeft: return CGPoint(x: 0, y: max(yMargin, 0)) case .bottomRight: return CGPoint(x: max(xMargin, 0), y: max(yMargin, 0)) } } } /// default is `0`. @IBInspectable open var numberOfLines: Int { get { return container.maximumNumberOfLines } set { container.maximumNumberOfLines = newValue setNeedsDisplay() } } /// default is `Left`. open var contentAlignment: ContentAlignment = .left { didSet { setNeedsDisplay() } } /// `lineFragmentPadding` of `NSTextContainer`. default is `0`. @IBInspectable open var padding: CGFloat { get { return container.lineFragmentPadding } set { container.lineFragmentPadding = newValue setNeedsDisplay() } } /// default is system font 17 plain. open var font = UIFont.systemFont(ofSize: 17) { didSet { setNeedsDisplay() } } /// default is `ByTruncatingTail`. open var lineBreakMode: NSLineBreakMode { get { return container.lineBreakMode } set { container.lineBreakMode = newValue setNeedsDisplay() } } /// default is nil (text draws black). @IBInspectable open var textColor: UIColor? { didSet { setNeedsDisplay() } } /// default is nil. open var paragraphStyle: NSParagraphStyle? { didSet { setNeedsDisplay() } } /// default is nil. open var shadow: NSShadow? { didSet { setNeedsDisplay() } } /// default is nil. open var attributedText: NSAttributedString? { didSet { setNeedsDisplay() } } /// default is nil. @IBInspectable open var text: String? { get { return attributedText?.string } set { if let value = newValue { attributedText = NSAttributedString(string: value) } else { attributedText = nil } } } /// Support for constraint-based layout (auto layout) /// If nonzero, this is used when determining -intrinsicContentSize for multiline labels open var preferredMaxLayoutWidth: CGFloat = 0 /// If need to use intrinsicContentSize set true. /// Also should call invalidateIntrinsicContentSize when intrinsicContentSize is cached. When text was changed for example. public var usesIntrinsicContentSize = false var mergedAttributedText: NSAttributedString? { if let attributedText = attributedText { return mergeAttributes(attributedText) } return nil } let container = NSTextContainer() let layoutManager = NSLayoutManager() public override init(frame: CGRect) { super.init(frame: frame) isOpaque = false contentMode = .redraw lineBreakMode = .byTruncatingTail padding = 0 layoutManager.addTextContainer(container) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) isOpaque = false contentMode = .redraw lineBreakMode = .byTruncatingTail padding = 0 layoutManager.addTextContainer(container) } open override func setNeedsDisplay() { if Thread.isMainThread { super.setNeedsDisplay() } } open override var intrinsicContentSize: CGSize { if usesIntrinsicContentSize { let width = preferredMaxLayoutWidth == 0 ? bounds.width : preferredMaxLayoutWidth let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) return sizeThatFits(size) } else { return bounds.size } } open override func draw(_ rect: CGRect) { guard let attributedText = mergedAttributedText else { return } let storage = NSTextStorage(attributedString: attributedText) storage.addLayoutManager(layoutManager) container.size = rect.size let frame = layoutManager.usedRect(for: container) let point = contentAlignment.alignOffset(viewSize: rect.size, containerSize: frame.integral.size) let glyphRange = layoutManager.glyphRange(for: container) layoutManager.drawBackground(forGlyphRange: glyphRange, at: point) layoutManager.drawGlyphs(forGlyphRange: glyphRange, at: point) } open override func sizeThatFits(_ size: CGSize) -> CGSize { guard let attributedText = mergedAttributedText else { return .zero } let storage = NSTextStorage(attributedString: attributedText) storage.addLayoutManager(layoutManager) container.size = size let frame = layoutManager.usedRect(for: container) return frame.integral.size } open override func sizeToFit() { super.sizeToFit() let width = preferredMaxLayoutWidth == 0 ? CGFloat.greatestFiniteMagnitude : preferredMaxLayoutWidth let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) frame.size = sizeThatFits(size) } func mergeAttributes(_ attributedText: NSAttributedString) -> NSAttributedString { let attrString = NSMutableAttributedString(attributedString: attributedText) attrString.addAttribute(.font, attr: font) if let textColor = textColor { attrString.addAttribute(.foregroundColor, attr: textColor) } if let paragraphStyle = paragraphStyle { attrString.addAttribute(.paragraphStyle, attr: paragraphStyle) } if let shadow = shadow { attrString.addAttribute(.shadow, attr: shadow) } return attrString } } extension NSMutableAttributedString { @discardableResult func addAttribute(_ attrName: NSAttributedString.Key, attr: AnyObject, in range: NSRange? = nil) -> Self { let range = range ?? NSRange(location: 0, length: length) enumerateAttribute(attrName, in: range, options: .reverse) { object, range, pointer in if object == nil { addAttributes([attrName: attr], range: range) } } return self } }
a7620898219035884d46bbf433db1915
30.234568
127
0.609223
false
false
false
false
xoyip/AzureStorageApiClient
refs/heads/master
Example/AzureStorageApiClient_Example/ViewController.swift
mit
1
// // ViewController.swift // AzureStorageApiClient_Example // // Created by Hiromasa Ohno on 8/11/15. // Copyright (c) 2015 CocoaPods. All rights reserved. // import UIKit import AzureStorageApiClient import BrightFutures class ViewController: UIViewController { var blobClient : AzureBlob.Client! var queueClient : AzureQueue.Client! override func viewDidLoad() { super.viewDidLoad() blobClient = AzureBlob.Client(accoutName: Config.Account, accessKey: Config.Key, useHTTPS: true, hostName: nil) queueClient = AzureQueue.Client(accoutName: Config.Account, accessKey: Config.Key, useHTTPS: true, hostName: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func handleResponse<T>(response: Response<T>) { switch response { case .Success(let wrapper): println(wrapper.value) case .Failure(let wrapper): println(wrapper.value) } } } // MARK: Examples for Blob extension ViewController { func listContainers() { let request = AzureBlob.ListContainersRequest() blobClient?.call(request, handler: handleResponse) } func getBlobServiceProperties() { let request = AzureBlob.GetBlobServicePropertiesRequest() blobClient?.call(request, handler: handleResponse) } func setBlobServiceCors() { var cors = AzureBlob.CorsRule(allowedOrigins: ["http://example.com"], allowedMethods: ["POST", "PUT"], allowedHeaders: ["*"], exposedHeaders: ["*"], maxAgeInSeconds: 10000) if let corsRule = cors { let request = AzureBlob.SetBlobServiceCorsRequest(rules: [corsRule]) blobClient?.call(request, handler: handleResponse) } } func createContainer() { let request = AzureBlob.CreateContainerRequest(container: "containername", accessibility: .Private) blobClient?.call(request, handler: handleResponse) } func deleteContainer() { let request = AzureBlob.DeleteContainerRequest(container: "containername") blobClient?.call(request, handler: handleResponse) } func listBlobs() { let request = AzureBlob.ListBlobsRequest(container: "containername", maxResults: nil, nextMarker: nil) blobClient?.call(request, handler: handleResponse) } func putBlob() { if let url = NSURL(string: "https://avatars2.githubusercontent.com/u/3599510?v=3&s=10") { let data = NSData(contentsOfURL: url)! let request = AzureBlob.PutBlobRequest(container: "containername", name: "file.png", data: data, mimetype: "image/png") blobClient?.call(request, handler: handleResponse) } } func getBlob() { let request = AzureBlob.GetBlobRequest(container: "containername", name: "file.png", mimetype: "image/png") blobClient?.call(request, handler: handleResponse) } func getBlobProperties() { let request = AzureBlob.GetBlobPropertiesRequest(container: "containername", name: "file.png") blobClient?.call(request, handler: handleResponse) } func deleteBlob() { let request = AzureBlob.DeleteBlobRequest(container: "containername", name: "file.png") blobClient?.call(request, handler: handleResponse) } } // MARK: Examples for Queue extension ViewController { func listQueues() { let request = AzureQueue.ListQueuesRequest() queueClient?.call(request, handler: handleResponse) } func createQueue() { let request = AzureQueue.CreateQueueRequest(queue: "queuename") queueClient?.call(request, handler: handleResponse) } func deleteQueue() { let request = AzureQueue.DeleteQueueRequest(queue: "queuename") queueClient?.call(request, handler: handleResponse) } func putMessage() { let request = AzureQueue.PutMessagesRequest(queue: "queuename", message: "a message", messageTTL: 3600, visibilityTimeout: 600) queueClient?.call(request, handler: handleResponse) } func getMessages() { let request = AzureQueue.GetMessagesRequest(queue: "queuename", visibilityTimeout: 600, numberOfMessages: 32) queueClient?.call(request, handler: handleResponse) } func peekMessage() { let request = AzureQueue.PeekMessagesRequest(queue: "queuename", numberOfMessages: 32) queueClient?.call(request, handler: handleResponse) } func deleteMessage() { let request = AzureQueue.DeleteMessageRequest(queue: "queuename", messageId: "message-id(UUID)", popReceipt: "pop-receipt") queueClient?.call(request, handler: handleResponse) } func clearMessage() { let request = AzureQueue.ClearMessagesRequest(queue: "queuename") queueClient?.call(request, handler: handleResponse) } func updateMessage() { let request = AzureQueue.UpdateMessageRequest(queue: "queuename", message: "new message", messageId: "message-id(UUID)", popReceipt: "pop-receipt", visibilityTimeout: 3600) queueClient?.call(request, handler: handleResponse) } } // MARK: Examples for BrightFutures' way extension ViewController { func listCreateDelete() { let req1 = AzureQueue.ListQueuesRequest() queueClient.future(req1) .flatMap { response -> Future<AzureQueue.CreateQueueRequest.Response, NSError> in let req = AzureQueue.CreateQueueRequest(queue: "brandnewqueue") return self.queueClient.future(req) } .flatMap { response -> Future<AzureQueue.DeleteQueueRequest.Response, NSError> in let req = AzureQueue.DeleteQueueRequest(queue: "sample2") return self.queueClient.future(req) } .onSuccess { response in println(response) } .onFailure { error in println(error) } } }
0947106abcaef580b1b738d998415c24
35.819277
180
0.656904
false
false
false
false
codestergit/swift
refs/heads/master
test/SILGen/function_conversion.swift
apache-2.0
2
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s // Check SILGen against various FunctionConversionExprs emitted by Sema. // ==== Representation conversions // CHECK-LABEL: sil hidden @_T019function_conversion7cToFuncS2icS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_owned (Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @_T0S2iItCyd_S2iIxyd_TR // CHECK: [[FUNC:%.*]] = partial_apply [[THUNK]](%0) // CHECK: return [[FUNC]] func cToFunc(_ arg: @escaping @convention(c) (Int) -> Int) -> (Int) -> Int { return arg } // CHECK-LABEL: sil hidden @_T019function_conversion8cToBlockS2iXBS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] // CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) (Int) -> Int // CHECK: return [[COPY]] func cToBlock(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(block) (Int) -> Int { return arg } // ==== Throws variance // CHECK-LABEL: sil hidden @_T019function_conversion12funcToThrowsyyKcyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> @owned @callee_owned () -> @error Error // CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> ()): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_owned () -> () to $@callee_owned () -> @error Error // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[FUNC]] // CHECK: } // end sil function '_T019function_conversion12funcToThrowsyyKcyycF' func funcToThrows(_ x: @escaping () -> ()) -> () throws -> () { return x } // CHECK-LABEL: sil hidden @_T019function_conversion12thinToThrowsyyKXfyyXfF : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error Error // CHECK: [[FUNC:%.*]] = convert_function %0 : $@convention(thin) () -> () to $@convention(thin) () -> @error Error // CHECK: return [[FUNC]] : $@convention(thin) () -> @error Error func thinToThrows(_ x: @escaping @convention(thin) () -> ()) -> @convention(thin) () throws -> () { return x } // FIXME: triggers an assert because we always do a thin to thick conversion on DeclRefExprs /* func thinFunc() {} func thinToThrows() { let _: @convention(thin) () -> () = thinFunc } */ // ==== Class downcasts and upcasts class Feral {} class Domesticated : Feral {} // CHECK-LABEL: sil hidden @_T019function_conversion12funcToUpcastAA5FeralCycAA12DomesticatedCycF : $@convention(thin) (@owned @callee_owned () -> @owned Domesticated) -> @owned @callee_owned () -> @owned Feral { // CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> @owned Domesticated): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_owned () -> @owned Domesticated to $@callee_owned () -> @owned Feral // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[FUNC]] // CHECK: } // end sil function '_T019function_conversion12funcToUpcastAA5FeralCycAA12DomesticatedCycF' func funcToUpcast(_ x: @escaping () -> Domesticated) -> () -> Feral { return x } // CHECK-LABEL: sil hidden @_T019function_conversion12funcToUpcastyAA12DomesticatedCcyAA5FeralCcF : $@convention(thin) (@owned @callee_owned (@owned Feral) -> ()) -> @owned @callee_owned (@owned Domesticated) -> () // CHECK: bb0([[ARG:%.*]] : // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_owned (@owned Feral) -> () to $@callee_owned (@owned Domesticated) -> (){{.*}} // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[FUNC]] func funcToUpcast(_ x: @escaping (Feral) -> ()) -> (Domesticated) -> () { return x } // ==== Optionals struct Trivial { let n: Int8 } class C { let n: Int8 init(n: Int8) { self.n = n } } struct Loadable { let c: C var n: Int8 { return c.n } init(n: Int8) { c = C(n: n) } } struct AddrOnly { let a: Any var n: Int8 { return a as! Int8 } init(n: Int8) { a = n } } // CHECK-LABEL: sil hidden @_T019function_conversion19convOptionalTrivialyAA0E0VADSgcF func convOptionalTrivial(_ t1: @escaping (Trivial?) -> Trivial) { // CHECK: function_ref @_T019function_conversion7TrivialVSgACIxyd_AcDIxyd_TR // CHECK: partial_apply let _: (Trivial) -> Trivial? = t1 // CHECK: function_ref @_T019function_conversion7TrivialVSgACIxyd_A2DIxyd_TR // CHECK: partial_apply let _: (Trivial!) -> Trivial? = t1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion7TrivialVSgACIxyd_AcDIxyd_TR : $@convention(thin) (Trivial, @owned @callee_owned (Optional<Trivial>) -> Trivial) -> Optional<Trivial> // CHECK: enum $Optional<Trivial> // CHECK-NEXT: apply %1(%2) // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion7TrivialVSgACIxyd_A2DIxyd_TR : $@convention(thin) (Optional<Trivial>, @owned @callee_owned (Optional<Trivial>) -> Trivial) -> Optional<Trivial> // CHECK: apply %1(%0) // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: return // CHECK-LABEL: sil hidden @_T019function_conversion20convOptionalLoadableyAA0E0VADSgcF func convOptionalLoadable(_ l1: @escaping (Loadable?) -> Loadable) { // CHECK: function_ref @_T019function_conversion8LoadableVSgACIxxo_AcDIxxo_TR // CHECK: partial_apply let _: (Loadable) -> Loadable? = l1 // CHECK: function_ref @_T019function_conversion8LoadableVSgACIxxo_A2DIxxo_TR // CHECK: partial_apply let _: (Loadable!) -> Loadable? = l1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion8LoadableVSgACIxxo_A2DIxxo_TR : $@convention(thin) (@owned Optional<Loadable>, @owned @callee_owned (@owned Optional<Loadable>) -> @owned Loadable) -> @owned Optional<Loadable> // CHECK: apply %1(%0) // CHECK-NEXT: enum $Optional<Loadable> // CHECK-NEXT: return // CHECK-LABEL: sil hidden @_T019function_conversion20convOptionalAddrOnlyyAA0eF0VADSgcF func convOptionalAddrOnly(_ a1: @escaping (AddrOnly?) -> AddrOnly) { // CHECK: function_ref @_T019function_conversion8AddrOnlyVSgACIxir_A2DIxir_TR // CHECK: partial_apply let _: (AddrOnly?) -> AddrOnly? = a1 // CHECK: function_ref @_T019function_conversion8AddrOnlyVSgACIxir_A2DIxir_TR // CHECK: partial_apply let _: (AddrOnly!) -> AddrOnly? = a1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion8AddrOnlyVSgACIxir_A2DIxir_TR : $@convention(thin) (@in Optional<AddrOnly>, @owned @callee_owned (@in Optional<AddrOnly>) -> @out AddrOnly) -> @out Optional<AddrOnly> // CHECK: alloc_stack $AddrOnly // CHECK-NEXT: apply %2(%3, %1) // CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly> // CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*AddrOnly // CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly> // CHECK-NEXT: tuple () // CHECK-NEXT: dealloc_stack {{.*}} : $*AddrOnly // CHECK-NEXT: return // ==== Existentials protocol Q { var n: Int8 { get } } protocol P : Q {} extension Trivial : P {} extension Loadable : P {} extension AddrOnly : P {} // CHECK-LABEL: sil hidden @_T019function_conversion22convExistentialTrivialyAA0E0VAA1Q_pc_AdaE_pSgc2t3tF func convExistentialTrivial(_ t2: @escaping (Q) -> Trivial, t3: @escaping (Q?) -> Trivial) { // CHECK: function_ref @_T019function_conversion1Q_pAA7TrivialVIxid_AdA1P_pIxyr_TR // CHECK: partial_apply let _: (Trivial) -> P = t2 // CHECK: function_ref @_T019function_conversion1Q_pSgAA7TrivialVIxid_AESgAA1P_pIxyr_TR // CHECK: partial_apply let _: (Trivial?) -> P = t3 // CHECK: function_ref @_T019function_conversion1Q_pAA7TrivialVIxid_AA1P_pAaE_pIxir_TR // CHECK: partial_apply let _: (P) -> P = t2 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion1Q_pAA7TrivialVIxid_AdA1P_pIxyr_TR : $@convention(thin) (Trivial, @owned @callee_owned (@in Q) -> Trivial) -> @out P // CHECK: alloc_stack $Q // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK-NEXT: apply // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion1Q_pSgAA7TrivialVIxid_AESgAA1P_pIxyr_TR // CHECK: switch_enum // CHECK: bb1([[TRIVIAL:%.*]] : $Trivial): // CHECK: init_existential_addr // CHECK: init_enum_data_addr // CHECK: copy_addr // CHECK: inject_enum_addr // CHECK: bb2: // CHECK: inject_enum_addr // CHECK: bb3: // CHECK: apply // CHECK: init_existential_addr // CHECK: store // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion1Q_pAA7TrivialVIxid_AA1P_pAaE_pIxir_TR : $@convention(thin) (@in P, @owned @callee_owned (@in Q) -> Trivial) -> @out P // CHECK: alloc_stack $Q // CHECK-NEXT: open_existential_addr immutable_access %1 : $*P // CHECK-NEXT: init_existential_addr %3 : $*Q // CHECK-NEXT: copy_addr {{.*}} to [initialization] {{.*}} // CHECK-NEXT: apply // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK: destroy_addr // CHECK: return // ==== Existential metatypes // CHECK-LABEL: sil hidden @_T019function_conversion23convExistentialMetatypeyAA7TrivialVmAA1Q_pXpSgcF func convExistentialMetatype(_ em: @escaping (Q.Type?) -> Trivial.Type) { // CHECK: function_ref @_T019function_conversion1Q_pXmTSgAA7TrivialVXMtIxyd_AEXMtAA1P_pXmTIxyd_TR // CHECK: partial_apply let _: (Trivial.Type) -> P.Type = em // CHECK: function_ref @_T019function_conversion1Q_pXmTSgAA7TrivialVXMtIxyd_AEXMtSgAA1P_pXmTIxyd_TR // CHECK: partial_apply let _: (Trivial.Type?) -> P.Type = em // CHECK: function_ref @_T019function_conversion1Q_pXmTSgAA7TrivialVXMtIxyd_AA1P_pXmTAaF_pXmTIxyd_TR // CHECK: partial_apply let _: (P.Type) -> P.Type = em } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion1Q_pXmTSgAA7TrivialVXMtIxyd_AEXMtAA1P_pXmTIxyd_TR : $@convention(thin) (@thin Trivial.Type, @owned @callee_owned (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype %2 : $@thick Trivial.Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK-NEXT: apply // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion1Q_pXmTSgAA7TrivialVXMtIxyd_AEXMtSgAA1P_pXmTIxyd_TR : $@convention(thin) (Optional<@thin Trivial.Type>, @owned @callee_owned (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: switch_enum %0 : $Optional<@thin Trivial.Type> // CHECK: bb1([[META:%.*]] : $@thin Trivial.Type): // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK: bb2: // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK: bb3({{.*}}): // CHECK-NEXT: apply // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion1Q_pXmTSgAA7TrivialVXMtIxyd_AA1P_pXmTAaF_pXmTIxyd_TR : $@convention(thin) (@thick P.Type, @owned @callee_owned (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: open_existential_metatype %0 : $@thick P.Type to $@thick (@opened({{.*}}) P).Type // CHECK-NEXT: init_existential_metatype %2 : $@thick (@opened({{.*}}) P).Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK-NEXT: apply // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // ==== Class metatype upcasts class Parent {} class Child : Parent {} // Note: we add a Trivial => Trivial? conversion here to force a thunk // to be generated // CHECK-LABEL: sil hidden @_T019function_conversion18convUpcastMetatypeyAA5ChildCmAA6ParentCm_AA7TrivialVSgtc_ADmAFmSg_AItc2c5tF func convUpcastMetatype(_ c4: @escaping (Parent.Type, Trivial?) -> Child.Type, c5: @escaping (Parent.Type?, Trivial?) -> Child.Type) { // CHECK: function_ref @_T019function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIxyyd_AHXMTAeCXMTIxyyd_TR // CHECK: partial_apply let _: (Child.Type, Trivial) -> Parent.Type = c4 // CHECK: function_ref @_T019function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIxyyd_AIXMTAfCXMTIxyyd_TR // CHECK: partial_apply let _: (Child.Type, Trivial) -> Parent.Type = c5 // CHECK: function_ref @_T019function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIxyyd_AIXMTSgAfDIxyyd_TR // CHECK: partial_apply let _: (Child.Type?, Trivial) -> Parent.Type? = c5 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIxyyd_AHXMTAeCXMTIxyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @owned @callee_owned (@thick Parent.Type, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type // CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIxyyd_AIXMTAfCXMTIxyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @owned @callee_owned (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type // CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: enum $Optional<@thick Parent.Type> // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIxyyd_AIXMTSgAfDIxyyd_TR : $@convention(thin) (Optional<@thick Child.Type>, Trivial, @owned @callee_owned (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> Optional<@thick Parent.Type> // CHECK: unchecked_trivial_bit_cast %0 : $Optional<@thick Child.Type> to $Optional<@thick Parent.Type> // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: enum $Optional<@thick Parent.Type> // CHECK: return // ==== Function to existential -- make sure we maximally abstract it // CHECK-LABEL: sil hidden @_T019function_conversion19convFuncExistentialyS2icypcF : $@convention(thin) (@owned @callee_owned (@in Any) -> @owned @callee_owned (Int) -> Int) -> () // CHECK: bb0([[ARG:%.*]] : // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @_T0ypS2iIxyd_Ixio_S2iIxyd_ypIxxr_TR // CHECK: [[PA:%.*]] = partial_apply [[REABSTRACT_THUNK]]([[ARG_COPY]]) // CHECK: destroy_value [[PA]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T019function_conversion19convFuncExistentialyS2icypcF' func convFuncExistential(_ f1: @escaping (Any) -> (Int) -> Int) { let _: ((Int) -> Int) -> Any = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypS2iIxyd_Ixio_S2iIxyd_ypIxxr_TR : $@convention(thin) (@owned @callee_owned (Int) -> Int, @owned @callee_owned (@in Any) -> @owned @callee_owned (Int) -> Int) -> @out Any // CHECK: alloc_stack $Any // CHECK: function_ref @_T0S2iIxyd_S2iIxir_TR // CHECK-NEXT: partial_apply // CHECK-NEXT: init_existential_addr %3 : $*Any, $(Int) -> Int // CHECK-NEXT: store // CHECK-NEXT: apply // CHECK: function_ref @_T0S2iIxyd_S2iIxir_TR // CHECK-NEXT: partial_apply // CHECK-NEXT: init_existential_addr %0 : $*Any, $(Int) -> Int // CHECK-NEXT: store {{.*}} to {{.*}} : $*@callee_owned (@in Int) -> @out Int // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0S2iIxyd_S2iIxir_TR : $@convention(thin) (@in Int, @owned @callee_owned (Int) -> Int) -> @out Int // CHECK: load [trivial] %1 : $*Int // CHECK-NEXT: apply %2(%3) // CHECK-NEXT: store {{.*}} to [trivial] %0 // CHECK: return // ==== Class-bound archetype upcast // CHECK-LABEL: sil hidden @_T019function_conversion29convClassBoundArchetypeUpcast{{[_0-9a-zA-Z]*}}F func convClassBoundArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent) -> (T, Trivial)) { // CHECK: function_ref @_T019function_conversion6ParentCxAA7TrivialVIxxod_xAcESgIxxod_ACRbzlTR // CHECK: partial_apply let _: (T) -> (Parent, Trivial?) = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion6ParentCxAA7TrivialVIxxod_xAcESgIxxod_ACRbzlTR : $@convention(thin) <T where T : Parent> (@owned T, @owned @callee_owned (@owned Parent) -> (@owned T, Trivial)) -> (@owned Parent, Optional<Trivial>) // CHECK: bb0([[ARG:%.*]] : $T, [[CLOSURE:%.*]] : $@callee_owned (@owned Parent) -> (@owned T, Trivial)): // CHECK: [[CASTED_ARG:%.*]] = upcast [[ARG]] : $T to $Parent // CHECK: [[RESULT:%.*]] = apply [[CLOSURE]]([[CASTED_ARG]]) // CHECK: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]] : $(T, Trivial) // CHECK: [[FIRST_RESULT:%.*]] = tuple_extract [[BORROWED_RESULT]] : $(T, Trivial), 0 // CHECK: [[COPIED_FIRST_RESULT:%.*]] = copy_value [[FIRST_RESULT]] // CHECK: tuple_extract [[BORROWED_RESULT]] : $(T, Trivial), 1 // CHECK: end_borrow [[BORROWED_RESULT]] from [[RESULT]] // CHECK: destroy_value [[RESULT]] // CHECK: [[CAST_COPIED_FIRST_RESULT:%.*]] = upcast [[COPIED_FIRST_RESULT]] : $T to $Parent // CHECK: enum $Optional<Trivial> // CHECK: [[RESULT:%.*]] = tuple ([[CAST_COPIED_FIRST_RESULT]] : $Parent, {{.*}} : $Optional<Trivial>) // CHECK: return [[RESULT]] // CHECK-LABEL: sil hidden @_T019function_conversion37convClassBoundMetatypeArchetypeUpcast{{[_0-9a-zA-Z]*}}F func convClassBoundMetatypeArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent.Type) -> (T.Type, Trivial)) { // CHECK: function_ref @_T019function_conversion6ParentCXMTxXMTAA7TrivialVIxydd_xXMTACXMTAESgIxydd_ACRbzlTR // CHECK: partial_apply let _: (T.Type) -> (Parent.Type, Trivial?) = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion6ParentCXMTxXMTAA7TrivialVIxydd_xXMTACXMTAESgIxydd_ACRbzlTR : $@convention(thin) <T where T : Parent> (@thick T.Type, @owned @callee_owned (@thick Parent.Type) -> (@thick T.Type, Trivial)) -> (@thick Parent.Type, Optional<Trivial>) // CHECK: upcast %0 : $@thick T.Type to $@thick Parent.Type // CHECK-NEXT: apply // CHECK-NEXT: tuple_extract // CHECK-NEXT: tuple_extract // CHECK-NEXT: upcast {{.*}} : $@thick T.Type to $@thick Parent.Type // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: tuple // CHECK-NEXT: return // ==== Make sure we destructure one-element tuples // CHECK-LABEL: sil hidden @_T019function_conversion15convTupleScalaryyAA1Q_pc_yAaC_pc2f2ySi_SitSgc2f3tF // CHECK: function_ref @_T019function_conversion1Q_pIxi_AA1P_pIxi_TR // CHECK: function_ref @_T019function_conversion1Q_pIxi_AA1P_pIxi_TR // CHECK: function_ref @_T0Si_SitSgIxy_S2iIxyy_TR // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T019function_conversion1Q_pIxi_AA1P_pIxi_TR : $@convention(thin) (@in P, @owned @callee_owned (@in Q) -> ()) -> () // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0Si_SitSgIxy_S2iIxyy_TR : $@convention(thin) (Int, Int, @owned @callee_owned (Optional<(Int, Int)>) -> ()) -> () func convTupleScalar(_ f1: @escaping (Q) -> (), f2: @escaping (_ parent: Q) -> (), f3: @escaping (_ tuple: (Int, Int)?) -> ()) { let _: (P) -> () = f1 let _: (P) -> () = f2 let _: (Int, Int) -> () = f3 } func convTupleScalarOpaque<T>(_ f: @escaping (T...) -> ()) -> ((_ args: T...) -> ())? { return f } // CHECK-LABEL: sil hidden @_T019function_conversion25convTupleToOptionalDirectSi_SitSgSicSi_SitSicF : $@convention(thin) (@owned @callee_owned (Int) -> (Int, Int)) -> @owned @callee_owned (Int) -> Optional<(Int, Int)> // CHECK: bb0([[ARG:%.*]] : $@callee_owned (Int) -> (Int, Int)): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[FN:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0S3iIxydd_S2i_SitSgIxyd_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[FN]]) // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[THUNK]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0S3iIxydd_S2i_SitSgIxyd_TR : $@convention(thin) (Int, @owned @callee_owned (Int) -> (Int, Int)) -> Optional<(Int, Int)> // CHECK: bb0(%0 : $Int, %1 : $@callee_owned (Int) -> (Int, Int)): // CHECK: [[RESULT:%.*]] = apply %1(%0) // CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Int) // CHECK-NEXT: [[OPTIONAL:%.*]] = enum $Optional<(Int, Int)>, #Optional.some!enumelt.1, [[RESULT]] // CHECK-NEXT: return [[OPTIONAL]] func convTupleToOptionalDirect(_ f: @escaping (Int) -> (Int, Int)) -> (Int) -> (Int, Int)? { return f } // CHECK-LABEL: sil hidden @_T019function_conversion27convTupleToOptionalIndirectx_xtSgxcx_xtxclF : $@convention(thin) <T> (@owned @callee_owned (@in T) -> (@out T, @out T)) -> @owned @callee_owned (@in T) -> @out Optional<(T, T)> // CHECK: bb0([[ARG:%.*]] : $@callee_owned (@in T) -> (@out T, @out T)): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[FN:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xxxIxirr_xx_xtSgIxir_lTR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<T>([[FN]]) // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[THUNK]] // CHECK: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0xxxIxirr_xx_xtSgIxir_lTR : $@convention(thin) <T> (@in T, @owned @callee_owned (@in T) -> (@out T, @out T)) -> @out Optional<(T, T)> // CHECK: bb0(%0 : $*Optional<(T, T)>, %1 : $*T, %2 : $@callee_owned (@in T) -> (@out T, @out T)): // CHECK: [[OPTIONAL:%.*]] = init_enum_data_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt.1 // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr %3 : $*(T, T), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr %3 : $*(T, T), 1 // CHECK-NEXT: apply %2([[LEFT]], [[RIGHT]], %1) // CHECK-NEXT: inject_enum_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt.1 // CHECK: return func convTupleToOptionalIndirect<T>(_ f: @escaping (T) -> (T, T)) -> (T) -> (T, T)? { return f } // ==== Make sure we support AnyHashable erasure // CHECK-LABEL: sil hidden @_T019function_conversion15convAnyHashableyx1t_ts0E0RzlF // CHECK: function_ref @_T019function_conversion15convAnyHashableyx1t_ts0E0RzlFSbs0dE0V_AFtcfU_ // CHECK: function_ref @_T0s11AnyHashableVABSbIxiid_xxSbIxiid_s0B0RzlTR // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0s11AnyHashableVABSbIxiid_xxSbIxiid_s0B0RzlTR : $@convention(thin) <T where T : Hashable> (@in T, @in T, @owned @callee_owned (@in AnyHashable, @in AnyHashable) -> Bool) -> Bool // CHECK: alloc_stack $AnyHashable // CHECK: function_ref @_swift_convertToAnyHashable // CHECK: apply {{.*}}<T> // CHECK: alloc_stack $AnyHashable // CHECK: function_ref @_swift_convertToAnyHashable // CHECK: apply {{.*}}<T> // CHECK: return func convAnyHashable<T : Hashable>(t: T) { let fn: (T, T) -> Bool = { (x: AnyHashable, y: AnyHashable) in x == y } } // ==== Convert exploded tuples to Any or Optional<Any> // CHECK-LABEL: sil hidden @_T019function_conversion12convTupleAnyyyyc_Si_SitycyypcyypSgctF // CHECK: function_ref @_T0Ix_ypIxr_TR // CHECK: partial_apply // CHECK: function_ref @_T0Ix_ypSgIxr_TR // CHECK: partial_apply // CHECK: function_ref @_T0S2iIxdd_ypIxr_TR // CHECK: partial_apply // CHECK: function_ref @_T0S2iIxdd_ypSgIxr_TR // CHECK: partial_apply // CHECK: function_ref @_T0ypIxi_S2iIxyy_TR // CHECK: partial_apply // CHECK: function_ref @_T0ypSgIxi_S2iIxyy_TR // CHECK: partial_apply func convTupleAny(_ f1: @escaping () -> (), _ f2: @escaping () -> (Int, Int), _ f3: @escaping (Any) -> (), _ f4: @escaping (Any?) -> ()) { let _: () -> Any = f1 let _: () -> Any? = f1 let _: () -> Any = f2 let _: () -> Any? = f2 let _: ((Int, Int)) -> () = f3 let _: ((Int, Int)) -> () = f4 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0Ix_ypIxr_TR : $@convention(thin) (@owned @callee_owned () -> ()) -> @out Any // CHECK: init_existential_addr %0 : $*Any, $() // CHECK-NEXT: apply %1() // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0Ix_ypSgIxr_TR : $@convention(thin) (@owned @callee_owned () -> ()) -> @out Optional<Any> // CHECK: [[ENUM_PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Optional<Any>, #Optional.some!enumelt.1 // CHECK-NEXT: init_existential_addr [[ENUM_PAYLOAD]] : $*Any, $() // CHECK-NEXT: apply %1() // CHECK-NEXT: inject_enum_addr %0 : $*Optional<Any>, #Optional.some!enumelt.1 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0S2iIxdd_ypIxr_TR : $@convention(thin) (@owned @callee_owned () -> (Int, Int)) -> @out Any // CHECK: [[ANY_PAYLOAD:%.*]] = init_existential_addr %0 // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RESULT:%.*]] = apply %1() // CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0S2iIxdd_ypSgIxr_TR : $@convention(thin) (@owned @callee_owned () -> (Int, Int)) -> @out Optional<Any> { // CHECK: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr %0 // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[OPTIONAL_PAYLOAD]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RESULT:%.*]] = apply %1() // CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypIxi_S2iIxyy_TR : $@convention(thin) (Int, Int, @owned @callee_owned (@in Any) -> ()) -> () // CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: apply %2([[ANY_VALUE]]) // CHECK-NEXT: tuple () // CHECK-NEXT: dealloc_stack [[ANY_VALUE]] // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypSgIxi_S2iIxyy_TR : $@convention(thin) (Int, Int, @owned @callee_owned (@in Optional<Any>) -> ()) -> () // CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: [[OPTIONAL_VALUE:%.*]] = alloc_stack $Optional<Any> // CHECK-NEXT: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: copy_addr [take] [[ANY_VALUE]] to [initialization] [[OPTIONAL_PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: apply %2([[OPTIONAL_VALUE]]) // CHECK-NEXT: tuple () // CHECK-NEXT: dealloc_stack [[OPTIONAL_VALUE]] // CHECK-NEXT: dealloc_stack [[ANY_VALUE]] // CHECK-NEXT: return
1d8102187aec3d8fa5b26c540fbae872
50.34609
350
0.63411
false
false
false
false
GYLibrary/GPRS
refs/heads/master
OznerGPRS/AirPuterfierCell.swift
mit
1
// // AirPuterfierCell.swift // OznerGPRS // // Created by ZGY on 2017/9/20. // Copyright © 2017年 macpro. All rights reserved. // // Author: Airfight // My GitHub: https://github.com/airfight // My Blog: http://airfight.github.io/ // My Jane book: http://www.jianshu.com/users/17d6a01e3361 // Current Time: 2017/9/20 上午9:57 // GiantForJade: Efforts to do my best // Real developers ship. import UIKit class AirPuterfierCell: UITableViewCell { @IBOutlet weak var pmLb: UILabel! @IBOutlet weak var lxtimeLb: UILabel! @IBOutlet weak var powerLb: UILabel! @IBOutlet weak var speedLb: UILabel! @IBOutlet weak var lockStateLb: UILabel! @IBOutlet weak var vocLb: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func reloadUI(_ models: [ValuesModel]) { for item in models { switch item.key { case "PM25": pmLb.text = String(describing: (item.value!)) break case "VOCVAL": vocLb.text = String(describing: (item.value!)) break case "TIMEFIX1": lxtimeLb.text = secondstoString(String(describing: (item.value!))) break case "WINDSPEED": speedLb.text = String(describing: (item.value!)) break case "CHILDLOCK": lockStateLb.text = String(describing: (item.value!)) == "0" ? "关" : "开" break case "POWER": powerLb.text = String(describing: (item.value!)) == "0" ? "关机" : "开机" break default: break } } } private func secondstoString(_ seconds:String) -> String{ let data = Date.init(timeIntervalSince1970: TimeInterval(seconds)!) let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" formatter.locale = NSLocale(localeIdentifier: "en") as Locale! return formatter.string(from: data) } var currenSpeed = 0 @IBAction func speed2Action(_ sender: UIButton) { var speedArr = [0,4,5] currenSpeed += 1 if currenSpeed >= 3 { currenSpeed = 0 } // let arr = [["key":"WINDSPEED","value":speedArr[currenSpeed],"type":"Integer","updateTime":Date().timeIntervalSince1970]] // // let data = try! JSONSerialization.data(withJSONObject: arr, options: JSONSerialization.WritingOptions.prettyPrinted) // // let str = String.init(data: data, encoding: String.Encoding.utf8) // print(str!) let model = MqttSendStruct(key: "WINDSPEED", value: speedArr[currenSpeed], type: "Integer") let mqtt = MQTTHelper.default mqtt.sendStringToDevice(GYHelper.mqttModelToJsonString(model), topic: "AirPurifier/f0fe6b49d02d") } //童锁 @IBAction func speedSetAction(_ sender: UIButton) { var isPower = true if sender.titleLabel?.text == "关" { isPower = !isPower sender.setTitle("开", for: UIControlState.normal) } else { sender.setTitle("关", for: UIControlState.normal) } let model = MqttSendStruct(key: "CHILDLOCK", value: isPower , type: "Boolean") let mqtt = MQTTHelper.default mqtt.sendStringToDevice(GYHelper.mqttModelToJsonString(model), topic: "AirPurifier/f0fe6b49d02d") // let arr = [["key":"CHILDLOCK","value":isPower,"type":"Boolean","updateTime":Date().timeIntervalSince1970]] // let data = try! JSONSerialization.data(withJSONObject: arr, options: JSONSerialization.WritingOptions.prettyPrinted) // // let str = String.init(data: data, encoding: String.Encoding.utf8) // print(str!) // let mqtt = MQTTHelper.default // mqtt.sendStringToDevice(str!, topic: "AirPurifier/f0fe6b49d02d") } var power:Bool = true @IBAction func power(_ sender: UIButton) { var isPower = true if sender.titleLabel?.text == "关机" { isPower = !isPower sender.setTitle("开机", for: UIControlState.normal) } else { sender.setTitle("关机", for: UIControlState.normal) } let model = MqttSendStruct(key: "POWER", value: isPower, type: "Boolean") let mqtt = MQTTHelper.default mqtt.sendStringToDevice(GYHelper.mqttModelToJsonString(model), topic: "AirPurifier/f0fe6b49d02d") // let arr = [["key":"POWER","value":isPower,"type":"Boolean","updateTime":Date().timeIntervalSince1970]] // let data = try! JSONSerialization.data(withJSONObject: arr, options: JSONSerialization.WritingOptions.prettyPrinted) // // let str = String.init(data: data, encoding: String.Encoding.utf8) // print(str!) // let mqtt = MQTTHelper.default // mqtt.sendStringToDevice(str!, topic: "AirPurifier/f0fe6b49d02d") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
977aae29265acf799d3525a1cd143ad9
31.855422
130
0.574991
false
false
false
false
TribeMedia/MaterialKit-1
refs/heads/v1.x.x
Source/RaisedButton.swift
agpl-3.0
3
// // Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program located at the root of the software package // in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>. // import UIKit public class RaisedButton : MaterialButton { // // :name: prepareButton // internal override func prepareView() { super.prepareView() titleLabel!.font = Roboto.medium setTitleColor(MaterialTheme.white.color, forState: .Normal) backgroundColor = MaterialTheme.blue.accent2 contentEdgeInsets = UIEdgeInsetsMake(6, 16, 6, 16) } // // :name: prepareButton // internal override func prepareButton() { super.prepareButton() prepareShadow() backgroundColorView.layer.cornerRadius = 3 } // // :name: pulseBegan // internal override func pulseBegan(touches: Set<NSObject>, withEvent event: UIEvent) { super.pulseBegan(touches, withEvent: event) UIView.animateWithDuration(0.3, animations: { self.pulseView!.transform = CGAffineTransformMakeScale(4, 4) self.transform = CGAffineTransformMakeScale(1.05, 1.05) }) } }
9d0c2708baae064ff29d794c879a0966
31.283019
90
0.73758
false
false
false
false
zhangjk4859/animal-plant_pool
refs/heads/master
animal-plant_pool/animal-plant_pool/我的/View/HeaderView.swift
mit
1
// // HeaderView.swift // animal-plant_pool // // Created by 张俊凯 on 2017/2/15. // Copyright © 2017年 张俊凯. All rights reserved. // import UIKit class HeaderView: UIView { @IBOutlet weak var focusLabel: UILabel! @IBOutlet weak var fansLabel: UILabel! @IBOutlet weak var likeLabel: UILabel! @IBOutlet weak var headImageView: UIImageView! // required init(coder aDecoder: NSCoder) { // // super.init(coder: aDecoder)! // // } // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. // override func draw(_ rect: CGRect) { // // //开启图片上下文 // let size = headImageView.frame.size // // UIGraphicsBeginImageContextWithOptions(size, false, 0) // let ctx = UIGraphicsGetCurrentContext() // //绘制路径 // let path = UIBezierPath() // //描述路径 // path.addArc(withCenter: CGPoint(x: size.width * 0.5,y: size.height * 0.5), radius: size.height * 0.5, startAngle: 0.0, endAngle: CGFloat(M_PI) * 2, clockwise: false) // ctx!.addPath(path.cgPath) // ctx?.clip() // //// self.drawAtPoint(CGPointZero) // let clipImage = UIGraphicsGetImageFromCurrentImageContext() // UIGraphicsEndImageContext() // //// headImageView.image = clipImage // } }
337354dd1fe7a81c1de1784553988570
26.901961
175
0.598032
false
false
false
false
onevcat/RandomColorSwift
refs/heads/master
Demo/ViewController.swift
mit
1
// // ViewController.swift // RandomColorSwift // // Copyright (c) 2020 Wei Wang (http://onevcat.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import RandomColor class ViewController: UICollectionViewController { var colors: [UIColor]! fileprivate var count = 99 fileprivate var hue: Hue = .random fileprivate var luminosity: Luminosity = .light //MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. refresh() } //MARK: Segue Transition override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showSetting" { let settingVC = (segue.destination as! UINavigationController).topViewController as! SettingViewController settingVC.delegate = self settingVC.count = count settingVC.hue = hue settingVC.luminosity = luminosity } else if segue.identifier == "showDetail" { if let indexPath = collectionView?.indexPath(for: sender as! UICollectionViewCell) { let detailVC = segue.destination as! DetailViewController detailVC.color = colors[indexPath.row] } } } func refresh() { colors = randomColors(count: count, hue: hue, luminosity: luminosity) collectionView?.reloadData() } } //MARK: Collection View DataSource extension ViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return colors.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) cell.contentView.backgroundColor = colors[indexPath.row] return cell } } extension ViewController: SettingViewControllerDelegate { func settingViewController(_ viewController: SettingViewController, didSetCount count: Int, hue: Hue, luminosity: Luminosity) { dismiss(animated: true, completion: nil) self.count = count self.hue = hue self.luminosity = luminosity refresh() } }
17ceb9e2321f2036b6d58ea5c11593e4
37.288889
131
0.691817
false
false
false
false
okkhoury/SafeNights_iOS
refs/heads/master
Pods/JSONHelper/JSONHelper/Extensions/Float.swift
mit
1
// // Copyright © 2016 Baris Sencan. All rights reserved. // import Foundation extension Float: Convertible { public static func convert<T>(fromValue value: T?) throws -> Float? { guard let value = value else { return nil } if let floatValue = value as? Float { return floatValue } else if let stringValue = value as? String { return Float(stringValue) } else if let doubleValue = value as? Double { return Float(doubleValue) } else if let intValue = value as? Int { return Float(intValue) } throw ConversionError.unsupportedType } }
91a24790afa6769f2a9cc277f711e095
23.833333
71
0.666107
false
false
false
false
realm/SwiftLint
refs/heads/main
Source/SwiftLintFramework/Rules/Style/ClosingBraceRule.swift
mit
1
import SwiftSyntax struct ClosingBraceRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "closing_brace", name: "Closing Brace Spacing", description: "Closing brace with closing parenthesis should not have any whitespaces in the middle.", kind: .style, nonTriggeringExamples: [ Example("[].map({ })"), Example("[].map(\n { }\n)") ], triggeringExamples: [ Example("[].map({ ↓} )"), Example("[].map({ ↓}\t)") ], corrections: [ Example("[].map({ ↓} )\n"): Example("[].map({ })\n") ] ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? { Rewriter( locationConverter: file.locationConverter, disabledRegions: disabledRegions(file: file) ) } } private extension ClosingBraceRule { private final class Visitor: ViolationsSyntaxVisitor { override func visitPost(_ node: TokenSyntax) { if node.hasClosingBraceViolation { violations.append(node.positionAfterSkippingLeadingTrivia) } } } private final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter { private(set) var correctionPositions: [AbsolutePosition] = [] let locationConverter: SourceLocationConverter let disabledRegions: [SourceRange] init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) { self.locationConverter = locationConverter self.disabledRegions = disabledRegions } override func visit(_ node: TokenSyntax) -> TokenSyntax { guard node.hasClosingBraceViolation, !node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else { return super.visit(node) } correctionPositions.append(node.positionAfterSkippingLeadingTrivia) return super.visit(node.withTrailingTrivia(.zero)) } } } private extension TokenSyntax { var hasClosingBraceViolation: Bool { guard tokenKind == .rightBrace, let nextToken = nextToken, nextToken.tokenKind == .rightParen else { return false } let isImmediatelyNext = positionAfterSkippingLeadingTrivia == nextToken.positionAfterSkippingLeadingTrivia - SourceLength(utf8Length: 1) if isImmediatelyNext || nextToken.hasLeadingNewline { return false } else { return true } } private var hasLeadingNewline: Bool { leadingTrivia.contains { piece in if case .newlines = piece { return true } else { return false } } } }
8ce0a98f1e61e8c65b1b978c8149366b
30.877551
109
0.605314
false
false
false
false
77u4/Timetable
refs/heads/master
Timetable/Connection.swift
gpl-3.0
1
// // Connection.swift // Timetable // // Created by Jannis on 04.01.15. // Copyright (c) 2015 Jannis Hutt. All rights reserved. // import Foundation let timetableURL = "http://jannishutt.de/downloads/timetable.json" class Connection { class func getTimetableData(success: ((data: NSData) -> Void)) { //1 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { //2 let filePath = NSBundle.mainBundle().pathForResource("Monday",ofType:"json") var readError:NSError? if let data = NSData(contentsOfFile:filePath!, options: NSDataReadingOptions.DataReadingUncached, error:&readError) { success(data: data) } }) } class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) { var session = NSURLSession.sharedSession() // Use NSURLSession to get data from an NSURL let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in if let responseError = error { completion(data: nil, error: responseError) } else if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode != 200 { var statusError = NSError(domain:"de.jannishutt", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."]) completion(data: nil, error: statusError) } else { completion(data: data, error: nil) } } }) loadDataTask.resume() } }
44da7ec7daf12d687675ca316361bd6d
35.2
180
0.587293
false
false
false
false
alecchyi/SwiftDemos
refs/heads/master
SwiftDemos/PersonalViewController.swift
mit
1
// // PersonalViewController.swift // SwiftDemos // // Created by dst-macpro1 on 15/10/22. // Copyright (c) 2015年 ibm. All rights reserved. // import UIKit class PersonalViewController: UIViewController { @IBOutlet weak var personalHeaderView: UIView! @IBOutlet weak var headImageView: UIImageView! @IBOutlet weak var lblNickname: UILabel! @IBOutlet weak var lblBU: UILabel! @IBOutlet weak var tableView: UITableView! var longTapHeadView:UILongPressGestureRecognizer? var dataList = [["组织机构","数据中心"],["帮助","版权协议"],["设置","退出"]] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell") self.longTapHeadView = UILongPressGestureRecognizer(target: self, action: "longTapHeadView:") self.headImageView.addGestureRecognizer(longTapHeadView!) fetchUserInfo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func loadView() { super.loadView() } func fetchUserInfo() { if IJReachability.isConnectedToNetwork() { // http://9.119.117.155:3000/say/demo.json //http://demos.alecchyi.bluemix.net/say/demo.json var url = NSURL(string: "http://demos.alecchyi.bluemix.net/say/demo.json") if let u = url { let request = NSURLRequest(URL: u, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30) let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let task = session.dataTaskWithRequest(request, completionHandler: {(let data, let response, let error) -> Void in if let jsonData = data { if let dic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments, error: nil) as? Dictionary<String, AnyObject> { if let nickname = dic["uNickname"] as? String { self.lblNickname.text = nickname } if let bu = dic["uBU"] as? String { self.lblBU.text = bu } if let pic = dic["uHeadUrl"] as? String { self.headImageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: pic)!)!) // if let imgUrl = NSURL(string: pic) { // session.downloadTaskWithURL(imgUrl, completionHandler: {[weak self](let fileUrl, let resp, let erro1) -> Void in // if let weakSelf = self { // println(fileUrl) // weakSelf.headImageView.image = UIImage(data: NSData(contentsOfURL: fileUrl)!) // } // }) // } } // println(dic) } } // println(response) }) task.resume() } } } func longTapHeadView(sender:UILongPressGestureRecognizer) { let alert = UIAlertController(title: "选择照片", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet) alert.addAction(UIAlertAction(title: "图片库", style: UIAlertActionStyle.Default, handler: {[weak self](let action) -> Void in if let weakSelf = self { weakSelf.pickerFromSource(0) } })) if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){ alert.addAction(UIAlertAction(title: "拍照", style: UIAlertActionStyle.Default, handler: {[weak self](let action) -> Void in if let weakSelf = self { weakSelf.pickerFromSource(1) } })) } alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } extension PersonalViewController:UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.dataList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) as! UITableViewCell let item = self.dataList[indexPath.section][indexPath.row] cell.textLabel?.text = item cell.selectionStyle = UITableViewCellSelectionStyle.None cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.imageView?.image = UIImage(named: "AppIcon") return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataList[section].count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 && indexPath.row == 0 { self.performSegueWithIdentifier("helpViewIdentifier", sender: nil) }else if indexPath.section == 1 && indexPath.row == 1 { self.performSegueWithIdentifier("protocolViewIdentifier", sender: nil) } } } extension PersonalViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate { func pickerFromSource(source:Int){ var imgPicker = UIImagePickerController() imgPicker.delegate = self imgPicker.allowsEditing = true if source == 1 { imgPicker.sourceType = UIImagePickerControllerSourceType.Camera }else { imgPicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary } self.presentViewController(imgPicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { self.headImageView.image = UIImage(CGImage:image.CGImage) UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) picker.dismissViewControllerAnimated(true, completion: {() -> Void in }) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: nil) } }
e6fa67e2be0eaaa8ffbdca3fbd2b09c1
42.047619
183
0.595962
false
false
false
false
Shivol/Swift-CS333
refs/heads/master
examples/graphics/LayersAnimations.playground/Pages/Layer Mask.xcplaygroundpage/Contents.swift
mit
3
import UIKit import PlaygroundSupport var view = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 250)) view.layer.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1).cgColor let dotCount = 6 for i in 0...dotCount { for j in 0..<dotCount { let dotSize = CGSize(width: view.bounds.width / CGFloat(dotCount), height: view.bounds.width / CGFloat(dotCount)) let originX = view.bounds.origin.x + (0.25 + CGFloat(i) - CGFloat(j % 2) / 2) * dotSize.width let originY = view.bounds.origin.y + (0.25 + CGFloat(j)) * dotSize.height let dot = CAShapeLayer() dot.path = CGPath(ellipseIn: CGRect(x: originX, y: originY, width: dotSize.width / 2, height: dotSize.height / 2), transform: nil) dot.fillColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1).cgColor dot.strokeColor = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1).cgColor view.layer.addSublayer(dot) } } let star = CAShapeLayer() let starPath = UIBezierPath(starWithNumberOfPoints: 5, centeredAt: view.center, innerRadius: view.bounds.width / 4, outerRadius: view.bounds.width / 2) star.path = starPath.cgPath view.layer.mask = star PlaygroundPage.current.liveView = view
1d69ad02508c391a793bd5fb7fea4ca4
41.34375
151
0.681919
false
false
false
false
marcosgriselli/SwipeableTabBarController
refs/heads/master
SwipeableTabBarController/SwipeInteractor.swift
mit
1
// // SwipeInteractor.swift // SwipeableTabBarController // // Created by Marcos Griselli on 1/26/17. // Copyright © 2017 Marcos Griselli. All rights reserved. // import UIKit /// Responsible of driving the interactive transtion. @objc(SwipeInteractor) class SwipeInteractor: UIPercentDrivenInteractiveTransition { // MARK: - Private private weak var transitionContext: UIViewControllerContextTransitioning? private var gestureRecognizer: UIPanGestureRecognizer private var edge: UIRectEdge private var initialLocationInContainerView: CGPoint = CGPoint() private var initialTranslationInContainerView: CGPoint = CGPoint() private let xVelocityForComplete: CGFloat = 200.0 private let xVelocityForCancel: CGFloat = 30.0 init(gestureRecognizer: UIPanGestureRecognizer, edge: UIRectEdge) { self.gestureRecognizer = gestureRecognizer self.edge = edge super.init() // Add self as an observer of the gesture recognizer so that this // object receives updates as the user moves their finger. gestureRecognizer.addTarget(self, action: #selector(gestureRecognizeDidUpdate(_:))) } deinit { gestureRecognizer.removeTarget(self, action: #selector(gestureRecognizeDidUpdate(_:))) } override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { // Save the transitionContext, initial location, and the translation within // the containing view. self.transitionContext = transitionContext initialLocationInContainerView = gestureRecognizer.location(in: transitionContext.containerView) initialTranslationInContainerView = gestureRecognizer.translation(in: transitionContext.containerView) super.startInteractiveTransition(transitionContext) } /// Returns the offset of the pan gesture recognizer from its initial location /// as a percentage of the transition container view's width. /// /// - Parameter gesture: swiping gesture /// - Returns: percent completed for the interactive transition private func percentForGesture(_ gesture: UIPanGestureRecognizer) -> CGFloat { let transitionContainerView = transitionContext?.containerView let translationInContainerView = gesture.translation(in: transitionContainerView) // If the direction of the current touch along the horizontal axis does not // match the initial direction, then the current touch position along // the horizontal axis has crossed over the initial position. if translationInContainerView.x > 0.0 && initialTranslationInContainerView.x < 0.0 || translationInContainerView.x < 0.0 && initialTranslationInContainerView.x > 0.0 { return -1.0 } // Figure out what percentage we've traveled. return abs(translationInContainerView.x) / (transitionContainerView?.bounds ?? CGRect()).width } @IBAction func gestureRecognizeDidUpdate(_ gestureRecognizer: UIScreenEdgePanGestureRecognizer) { switch gestureRecognizer.state { case .began: // The Began state is handled by AAPLSlideTransitionDelegate. In // response to the gesture recognizer transitioning to this state, // it will trigger the transition. break case .changed: // -percentForGesture returns -1.f if the current position of the // touch along the horizontal axis has crossed over the initial // position. if percentForGesture(gestureRecognizer) < 0.0 { cancel() // Need to remove our action from the gesture recognizer to // ensure it will not be called again before deallocation. gestureRecognizer.removeTarget(self, action: #selector(gestureRecognizeDidUpdate(_:))) } else { update(percentForGesture(gestureRecognizer)) } case .ended: let transitionContainerView = transitionContext?.containerView let velocityInContainerView = gestureRecognizer.velocity(in: transitionContainerView) let shouldComplete: Bool switch edge { /// TODO (marcosgriselli): - Standarize and simplify case .left: shouldComplete = (percentForGesture(gestureRecognizer) >= 0.4 && velocityInContainerView.x < xVelocityForCancel) || velocityInContainerView.x < -xVelocityForComplete case .right: shouldComplete = (percentForGesture(gestureRecognizer) >= 0.4 && velocityInContainerView.x > -xVelocityForCancel) || velocityInContainerView.x > xVelocityForComplete default: fatalError("\(edge) is unsupported.") } if shouldComplete { finish() } else { cancel() } default: cancel() } } }
3bc6c9bfb7a9309c70eb37a605180645
43.769912
181
0.671477
false
false
false
false
KaiCode2/swift-corelibs-foundation
refs/heads/master
Foundation/NSBundle.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation public class NSBundle : NSObject { private var _bundle : CFBundle! private static var _mainBundle : NSBundle = { return NSBundle(cfBundle: CFBundleGetMainBundle()) }() public class func main() -> NSBundle { return _mainBundle } internal init(cfBundle: CFBundle) { super.init() _bundle = cfBundle } public init?(path: String) { super.init() // TODO: We do not yet resolve symlinks, but we must for compatibility // let resolvedPath = path._nsObject.stringByResolvingSymlinksInPath let resolvedPath = path guard resolvedPath.length > 0 else { return nil } let url = NSURL(fileURLWithPath: resolvedPath) _bundle = CFBundleCreate(kCFAllocatorSystemDefault, unsafeBitCast(url, to: CFURL.self)) } public convenience init?(url: NSURL) { if let path = url.path { self.init(path: path) } else { return nil } } public init(for aClass: AnyClass) { NSUnimplemented() } public init?(identifier: String) { super.init() guard let result = CFBundleGetBundleWithIdentifier(identifier._cfObject) else { return nil } _bundle = result } /* Methods for loading and unloading bundles. */ public func load() -> Bool { NSUnimplemented() } public var isLoaded: Bool { NSUnimplemented() } public func unload() -> Bool { NSUnimplemented() } public func preflight() throws { NSUnimplemented() } public func loadAndReturnError() throws { NSUnimplemented() } /* Methods for locating various components of a bundle. */ public var bundleURL: NSURL { return CFBundleCopyBundleURL(_bundle)._nsObject } public var resourceURL: NSURL? { return CFBundleCopyResourcesDirectoryURL(_bundle)?._nsObject } public var executableURL: NSURL? { return CFBundleCopyExecutableURL(_bundle)?._nsObject } public func urlForAuxiliaryExecutable(_ executableName: String) -> NSURL? { return CFBundleCopyAuxiliaryExecutableURL(_bundle, executableName._cfObject)?._nsObject } public var privateFrameworksURL: NSURL? { return CFBundleCopyPrivateFrameworksURL(_bundle)?._nsObject } public var sharedFrameworksURL: NSURL? { return CFBundleCopySharedFrameworksURL(_bundle)?._nsObject } public var sharedSupportURL: NSURL? { return CFBundleCopySharedSupportURL(_bundle)?._nsObject } public var builtInPlugInsURL: NSURL? { return CFBundleCopyBuiltInPlugInsURL(_bundle)?._nsObject } public var appStoreReceiptURL: NSURL? { // Always nil on this platform return nil } public var bundlePath: String { return bundleURL.path! } public var resourcePath: String? { return resourceURL?.path } public var executablePath: String? { return executableURL?.path } public func pathForAuxiliaryExecutable(_ executableName: String) -> String? { return urlForAuxiliaryExecutable(executableName)?.path } public var privateFrameworksPath: String? { return privateFrameworksURL?.path } public var sharedFrameworksPath: String? { return sharedFrameworksURL?.path } public var sharedSupportPath: String? { return sharedSupportURL?.path } public var builtInPlugInsPath: String? { return builtInPlugInsURL?.path } // ----------------------------------------------------------------------------------- // MARK: - URL Resource Lookup - Class public class func urlForResource(_ name: String?, withExtension ext: String?, subdirectory subpath: String?, inBundleWith bundleURL: NSURL) -> NSURL? { // If both name and ext are nil/zero-length, return nil if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) { return nil } return CFBundleCopyResourceURLInDirectory(bundleURL._cfObject, name?._cfObject, ext?._cfObject, subpath?._cfObject)._nsObject } public class func urlsForResources(withExtension ext: String?, subdirectory subpath: String?, inBundleWith bundleURL: NSURL) -> [NSURL]? { return CFBundleCopyResourceURLsOfTypeInDirectory(bundleURL._cfObject, ext?._cfObject, subpath?._cfObject)?._unsafeTypedBridge() } // ----------------------------------------------------------------------------------- // MARK: - URL Resource Lookup - Instance public func URLForResource(_ name: String?, withExtension ext: String?) -> NSURL? { return self.URLForResource(name, withExtension: ext, subdirectory: nil) } public func URLForResource(_ name: String?, withExtension ext: String?, subdirectory subpath: String?) -> NSURL? { // If both name and ext are nil/zero-length, return nil if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) { return nil } return CFBundleCopyResourceURL(_bundle, name?._cfObject, ext?._cfObject, subpath?._cfObject)?._nsObject } public func URLForResource(_ name: String?, withExtension ext: String?, subdirectory subpath: String?, localization localizationName: String?) -> NSURL? { // If both name and ext are nil/zero-length, return nil if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) { return nil } return CFBundleCopyResourceURLForLocalization(_bundle, name?._cfObject, ext?._cfObject, subpath?._cfObject, localizationName?._cfObject)?._nsObject } public func urlsForResources(withExtension ext: String?, subdirectory subpath: String?) -> [NSURL]? { return CFBundleCopyResourceURLsOfType(_bundle, ext?._cfObject, subpath?._cfObject)?._unsafeTypedBridge() } public func urlsForResources(withExtension ext: String?, subdirectory subpath: String?, localization localizationName: String?) -> [NSURL]? { return CFBundleCopyResourceURLsOfTypeForLocalization(_bundle, ext?._cfObject, subpath?._cfObject, localizationName?._cfObject)?._unsafeTypedBridge() } // ----------------------------------------------------------------------------------- // MARK: - Path Resource Lookup - Class public class func pathForResource(_ name: String?, ofType ext: String?, inDirectory bundlePath: String) -> String? { return NSBundle.urlForResource(name, withExtension: ext, subdirectory: bundlePath, inBundleWith: NSURL(fileURLWithPath: bundlePath))?.path ?? nil } public class func pathsForResources(ofType ext: String?, inDirectory bundlePath: String) -> [String] { // Force-unwrap path, beacuse if the URL can't be turned into a path then something is wrong anyway return urlsForResources(withExtension: ext, subdirectory: bundlePath, inBundleWith: NSURL(fileURLWithPath: bundlePath))?.map { $0.path! } ?? [] } // ----------------------------------------------------------------------------------- // MARK: - Path Resource Lookup - Instance public func pathForResource(_ name: String?, ofType ext: String?) -> String? { return self.URLForResource(name, withExtension: ext, subdirectory: nil)?.path } public func pathForResource(_ name: String?, ofType ext: String?, inDirectory subpath: String?) -> String? { return self.URLForResource(name, withExtension: ext, subdirectory: subpath)?.path } public func pathForResource(_ name: String?, ofType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> String? { return self.URLForResource(name, withExtension: ext, subdirectory: subpath, localization: localizationName)?.path } public func pathsForResources(ofType ext: String?, inDirectory subpath: String?) -> [String] { // Force-unwrap path, beacuse if the URL can't be turned into a path then something is wrong anyway return self.urlsForResources(withExtension: ext, subdirectory: subpath)?.map { $0.path! } ?? [] } public func pathsForResources(ofType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> [String] { // Force-unwrap path, beacuse if the URL can't be turned into a path then something is wrong anyway return self.urlsForResources(withExtension: ext, subdirectory: subpath, localization: localizationName)?.map { $0.path! } ?? [] } // ----------------------------------------------------------------------------------- // MARK: - Localized Strings public func localizedString(forKey key: String, value: String?, table tableName: String?) -> String { let localizedString = CFBundleCopyLocalizedString(_bundle, key._cfObject, value?._cfObject, tableName?._cfObject)! return localizedString._swiftObject } // ----------------------------------------------------------------------------------- // MARK: - Other public var bundleIdentifier: String? { return CFBundleGetIdentifier(_bundle)?._swiftObject } /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types. public var infoDictionary: [String : Any]? { let cfDict: CFDictionary? = CFBundleGetInfoDictionary(_bundle) return cfDict.map(_expensivePropertyListConversion) as? [String: Any] } /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types. public var localizedInfoDictionary: [String : Any]? { let cfDict: CFDictionary? = CFBundleGetLocalInfoDictionary(_bundle) return cfDict.map(_expensivePropertyListConversion) as? [String: Any] } /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types. public func objectForInfoDictionaryKey(_ key: String) -> Any? { if let localizedInfoDictionary = localizedInfoDictionary { return localizedInfoDictionary[key] } else { return infoDictionary?[key] } } public func classNamed(_ className: String) -> AnyClass? { NSUnimplemented() } public var principalClass: AnyClass? { NSUnimplemented() } public var preferredLocalizations: [String] { return NSBundle.preferredLocalizations(from: localizations) } public var localizations: [String] { let cfLocalizations: CFArray? = CFBundleCopyBundleLocalizations(_bundle) let nsLocalizations = cfLocalizations.map(_expensivePropertyListConversion) as? [Any] return nsLocalizations?.map { $0 as! String } ?? [] } public var developmentLocalization: String? { let region = CFBundleGetDevelopmentRegion(_bundle)! return region._swiftObject } public class func preferredLocalizations(from localizationsArray: [String]) -> [String] { let cfLocalizations: CFArray? = CFBundleCopyPreferredLocalizationsFromArray(localizationsArray._cfObject) let nsLocalizations = cfLocalizations.map(_expensivePropertyListConversion) as? [Any] return nsLocalizations?.map { $0 as! String } ?? [] } public class func preferredLocalizations(from localizationsArray: [String], forPreferences preferencesArray: [String]?) -> [String] { let localizations = CFBundleCopyLocalizationsForPreferences(localizationsArray._cfObject, preferencesArray?._cfObject)! return localizations._swiftObject.map { return ($0 as! NSString)._swiftObject } } public var executableArchitectures: [NSNumber]? { let architectures = CFBundleCopyExecutableArchitectures(_bundle)! return architectures._swiftObject.map() { $0 as! NSNumber } } }
c9425b10771bac6f686842c107de0418
42.402027
160
0.644664
false
false
false
false
macfeteria/swift-line-echobot-demo
refs/heads/master
Sources/env.swift
mit
1
// // env.swift // demo // // Created by Ter on 3/13/17. // // import Foundation struct Envionment { let port:Int let channelAccessToken:String let secretKey:String init () { let defaultPort = 8080 let defaultChannelAccessToken = "Token" let defaultSecretKey = "Secret" if let requestedPort = ProcessInfo.processInfo.environment["PORT"] { port = Int(requestedPort) ?? defaultPort } else { port = defaultPort } if let token = ProcessInfo.processInfo.environment["CHANNEL_ACC_TOKEN"] { channelAccessToken = String(token) ?? defaultChannelAccessToken } else { channelAccessToken = defaultChannelAccessToken } if let key = ProcessInfo.processInfo.environment["CHANNEL_SECRET_KEY"] { secretKey = String(key) ?? defaultChannelAccessToken } else { secretKey = defaultSecretKey } } }
22b9fe45b13b741dd28dbeb0bc5fb331
23.463415
81
0.589232
false
false
false
false
AngryLi/Onmyouji
refs/heads/master
Carthage/Checkouts/IQKeyboardManager/Demo/Swift_Demo/ViewController/CustomViewController.swift
apache-2.0
6
// // CustomViewController.swift // Demo // // Created by Iftekhar on 19/09/15. // Copyright © 2015 Iftekhar. All rights reserved. // import UIKit import IQKeyboardManagerSwift class CustomViewController : UIViewController, UIPopoverPresentationControllerDelegate { fileprivate var returnHandler : IQKeyboardReturnKeyHandler! @IBOutlet fileprivate var settingsView : UIView! @IBOutlet fileprivate var switchDisableViewController : UISwitch! @IBOutlet fileprivate var switchEnableViewController : UISwitch! @IBOutlet fileprivate var switchDisableToolbar : UISwitch! @IBOutlet fileprivate var switchEnableToolbar : UISwitch! @IBOutlet fileprivate var switchDisableTouchResign : UISwitch! @IBOutlet fileprivate var switchEnableTouchResign : UISwitch! @IBOutlet fileprivate var switchAllowPreviousNext : UISwitch! @IBOutlet fileprivate var settingsTopConstraint : NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() settingsView.layer.shadowColor = UIColor.black.cgColor settingsView.layer.shadowOffset = CGSize.zero settingsView.layer.shadowRadius = 5.0 settingsView.layer.shadowOpacity = 0.5 returnHandler = IQKeyboardReturnKeyHandler(controller: self) returnHandler.lastTextFieldReturnKeyType = .done } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) switchDisableViewController.isOn = IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses.contains(where: { element in return element == CustomViewController.self }) switchEnableViewController.isOn = IQKeyboardManager.sharedManager().enabledDistanceHandlingClasses.contains(where: { element in return element == CustomViewController.self }) switchDisableToolbar.isOn = IQKeyboardManager.sharedManager().disabledToolbarClasses.contains(where: { element in return element == CustomViewController.self }) switchEnableToolbar.isOn = IQKeyboardManager.sharedManager().enabledToolbarClasses.contains(where: { element in return element == CustomViewController.self }) switchDisableTouchResign.isOn = IQKeyboardManager.sharedManager().disabledTouchResignedClasses.contains(where: { element in return element == CustomViewController.self }) switchEnableTouchResign.isOn = IQKeyboardManager.sharedManager().enabledTouchResignedClasses.contains(where: { element in return element == CustomViewController.self }) switchAllowPreviousNext.isOn = IQKeyboardManager.sharedManager().toolbarPreviousNextAllowedClasses.contains(where: { element in return element == IQPreviousNextView.self }); } @IBAction func tapAction(_ sender: UITapGestureRecognizer) { if sender.state == .ended { let animationCurve = UIViewAnimationOptions.init(rawValue: 7) let animationDuration : TimeInterval = 0.3; UIView.animate(withDuration: animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(animationCurve), animations: { () -> Void in if self.settingsTopConstraint.constant != 0 { self.settingsTopConstraint.constant = 0; } else { self.settingsTopConstraint.constant = -self.settingsView.frame.size.height+30; } self.view.setNeedsLayout() self.view.layoutIfNeeded() }) { (animated:Bool) -> Void in} } } @IBAction func disableInViewControllerAction(_ sender: UISwitch) { self.view.endEditing(true) if sender.isOn { IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses.append(CustomViewController.self) } else { if let index = IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses.index(where: { element in return element == CustomViewController.self }) { IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses.remove(at: index) } } } @IBAction func enableInViewControllerAction(_ sender: UISwitch) { self.view.endEditing(true) if sender.isOn { IQKeyboardManager.sharedManager().enabledDistanceHandlingClasses.append(CustomViewController.self) } else { if let index = IQKeyboardManager.sharedManager().enabledDistanceHandlingClasses.index(where: { element in return element == CustomViewController.self }) { IQKeyboardManager.sharedManager().enabledDistanceHandlingClasses.remove(at: index) } } } @IBAction func disableToolbarAction(_ sender: UISwitch) { self.view.endEditing(true) if sender.isOn { IQKeyboardManager.sharedManager().disabledToolbarClasses.append(CustomViewController.self) } else { if let index = IQKeyboardManager.sharedManager().disabledToolbarClasses.index(where: { element in return element == CustomViewController.self }) { IQKeyboardManager.sharedManager().disabledToolbarClasses.remove(at: index) } } } @IBAction func enableToolbarAction(_ sender: UISwitch) { self.view.endEditing(true) if sender.isOn { IQKeyboardManager.sharedManager().enabledToolbarClasses.append(CustomViewController.self) } else { if let index = IQKeyboardManager.sharedManager().enabledToolbarClasses.index(where: { element in return element == CustomViewController.self }) { IQKeyboardManager.sharedManager().enabledToolbarClasses.remove(at: index) } } } @IBAction func disableTouchOutsideAction(_ sender: UISwitch) { self.view.endEditing(true) if sender.isOn { IQKeyboardManager.sharedManager().disabledTouchResignedClasses.append(CustomViewController.self) } else { if let index = IQKeyboardManager.sharedManager().disabledTouchResignedClasses.index(where: { element in return element == CustomViewController.self }) { IQKeyboardManager.sharedManager().disabledTouchResignedClasses.remove(at: index) } } } @IBAction func enableTouchOutsideAction(_ sender: UISwitch) { self.view.endEditing(true) if sender.isOn { IQKeyboardManager.sharedManager().enabledTouchResignedClasses.append(CustomViewController.self) } else { if let index = IQKeyboardManager.sharedManager().enabledTouchResignedClasses.index(where: { element in return element == CustomViewController.self }) { IQKeyboardManager.sharedManager().enabledTouchResignedClasses.remove(at: index) } } } @IBAction func allowedPreviousNextAction(_ sender: UISwitch) { self.view.endEditing(true) if sender.isOn { IQKeyboardManager.sharedManager().toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self) } else { if let index = IQKeyboardManager.sharedManager().toolbarPreviousNextAllowedClasses.index(where: { element in return element == IQPreviousNextView.self }) { IQKeyboardManager.sharedManager().toolbarPreviousNextAllowedClasses.remove(at: index) } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { if identifier == "SettingsNavigationController" { let controller = segue.destination controller.modalPresentationStyle = .popover controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem let heightWidth = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height); controller.preferredContentSize = CGSize(width: heightWidth, height: heightWidth) controller.popoverPresentationController?.delegate = self } } } func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) { self.view.endEditing(true) } override var shouldAutorotate : Bool { return true } }
22edc400189169668156eb782fd60af0
39.232143
174
0.65091
false
false
false
false
powerytg/Accented
refs/heads/master
Accented/Core/API/Requests/UnfollowUserRequest.swift
mit
1
// // UnfollowUserRequest.swift // Accented // // Request to unfollow user // // Created by Tiangong You on 9/10/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class UnfollowUserRequest: APIRequest { private var userId : String init(userId : String, success : SuccessAction?, failure : FailureAction?) { self.userId = userId super.init(success: success, failure: failure) ignoreCache = true url = "\(APIRequest.baseUrl)users/\(userId)/friends" } override func handleSuccess(data: Data, response: HTTPURLResponse?) { super.handleSuccess(data: data, response: response) let userInfo : [String : Any] = [RequestParameters.userId : userId, RequestParameters.response : data] NotificationCenter.default.post(name: APIEvents.didUnfollowUser, object: nil, userInfo: userInfo) if let success = successAction { success() } } override func handleFailure(_ error: Error) { super.handleFailure(error) let userInfo : [String : String] = [RequestParameters.errorMessage : error.localizedDescription] NotificationCenter.default.post(name: APIEvents.failedUnfollowUser, object: nil, userInfo: userInfo) if let failure = failureAction { failure(error.localizedDescription) } } }
da283f74bab42cd07f1e998fe9e58c0d
30.782609
108
0.627223
false
false
false
false
DarrenKong/firefox-ios
refs/heads/master
Client/Frontend/AuthenticationManager/AuthenticationSettingsViewController.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import SwiftKeychainWrapper import LocalAuthentication private let logger = Logger.browserLogger private func presentNavAsFormSheet(_ presented: UINavigationController, presenter: UINavigationController?, settings: AuthenticationSettingsViewController?) { presented.modalPresentationStyle = .formSheet presenter?.present(presented, animated: true) { if let selectedRow = settings?.tableView.indexPathForSelectedRow { settings?.tableView.deselectRow(at: selectedRow, animated: false) } } } class TurnPasscodeOnSetting: Setting { weak var settings: AuthenticationSettingsViewController? override var accessibilityIdentifier: String? { return "TurnOnPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.settings = settings as? AuthenticationSettingsViewController super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOnPasscode, enabled: true), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: SetupPasscodeViewController()), presenter: navigationController, settings: settings) } } class TurnPasscodeOffSetting: Setting { weak var settings: AuthenticationSettingsViewController? override var accessibilityIdentifier: String? { return "TurnOffPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.settings = settings as? AuthenticationSettingsViewController super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOffPasscode, enabled: true), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: RemovePasscodeViewController()), presenter: navigationController, settings: settings) } } class ChangePasscodeSetting: Setting { weak var settings: AuthenticationSettingsViewController? override var accessibilityIdentifier: String? { return "ChangePasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool) { self.settings = settings as? AuthenticationSettingsViewController let attributedTitle: NSAttributedString = NSAttributedString.tableRowTitle(AuthenticationStrings.changePasscode, enabled: enabled) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: ChangePasscodeViewController()), presenter: navigationController, settings: settings) } } class RequirePasscodeSetting: Setting { weak var settings: AuthenticationSettingsViewController? fileprivate weak var navigationController: UINavigationController? override var accessibilityIdentifier: String? { return "PasscodeInterval" } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { // Only show the interval if we are enabled and have an interval set. let authenticationInterval = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() if let interval = authenticationInterval?.requiredPasscodeInterval, enabled { return NSAttributedString.tableRowTitle(interval.settingTitle, enabled: false) } return NSAttributedString(string: "") } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) { self.navigationController = settings.navigationController self.settings = settings as? AuthenticationSettingsViewController let title = AuthenticationStrings.requirePasscode let attributedTitle = NSAttributedString.tableRowTitle(title, enabled: enabled ?? true) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else { navigateToRequireInterval() return } if authInfo.requiresValidation() { AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.requirePasscodeTouchReason, success: { self.navigateToRequireInterval() }, cancel: nil, fallback: { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self) self.deselectRow() }) } else { self.navigateToRequireInterval() } } fileprivate func navigateToRequireInterval() { navigationController?.pushViewController(RequirePasscodeIntervalViewController(), animated: true) } } extension RequirePasscodeSetting: PasscodeEntryDelegate { @objc func passcodeValidationDidSucceed() { navigationController?.dismiss(animated: true) { self.navigateToRequireInterval() } } } class TouchIDSetting: Setting { fileprivate let authInfo: AuthenticationKeychainInfo? fileprivate weak var navigationController: UINavigationController? fileprivate weak var switchControl: UISwitch? fileprivate var touchIDSuccess: (() -> Void)? fileprivate var touchIDFallback: (() -> Void)? init( title: NSAttributedString?, navigationController: UINavigationController? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil, touchIDSuccess: (() -> Void)? = nil, touchIDFallback: (() -> Void)? = nil) { self.touchIDSuccess = touchIDSuccess self.touchIDFallback = touchIDFallback self.navigationController = navigationController self.authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() super.init(title: title, delegate: delegate, enabled: enabled) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .none // In order for us to recognize a tap gesture without toggling the switch, // the switch is wrapped in a UIView which has a tap gesture recognizer. This way // we can disable interaction of the switch and still handle tap events. let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.isOn = authInfo?.useTouchID ?? false control.isUserInteractionEnabled = false switchControl = control let accessoryContainer = UIView(frame: control.frame) accessoryContainer.addSubview(control) let gesture = UITapGestureRecognizer(target: self, action: #selector(switchTapped)) accessoryContainer.addGestureRecognizer(gesture) cell.accessoryView = accessoryContainer } @objc fileprivate func switchTapped() { guard let authInfo = authInfo else { logger.error("Authentication info should always be present when modifying Touch ID preference.") return } if authInfo.useTouchID { AppAuthenticator.presentAuthenticationUsingInfo( authInfo, touchIDReason: AuthenticationStrings.disableTouchReason, success: self.touchIDSuccess, cancel: nil, fallback: self.touchIDFallback ) } else { toggleTouchID(true) } } func toggleTouchID(_ enabled: Bool) { authInfo?.useTouchID = enabled KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authInfo) switchControl?.setOn(enabled, animated: true) } } class AuthenticationSettingsViewController: SettingsTableViewController { override func viewDidLoad() { super.viewDidLoad() updateTitleForTouchIDState() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .PasscodeDidRemove, object: nil) notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .PasscodeDidCreate, object: nil) notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .UIApplicationDidBecomeActive, object: nil) tableView.accessibilityIdentifier = "AuthenticationManager.settingsTableView" } deinit { NotificationCenter.default.removeObserver(self) } override func generateSettings() -> [SettingSection] { if let _ = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() { return passcodeEnabledSettings() } else { return passcodeDisabledSettings() } } fileprivate func updateTitleForTouchIDState() { let localAuthContext = LAContext() if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { let title: String if #available(iOS 11.0, *), localAuthContext.biometryType == .faceID { title = AuthenticationStrings.faceIDPasscodeSetting } else { title = AuthenticationStrings.touchIDPasscodeSetting } navigationItem.title = title } else { navigationItem.title = AuthenticationStrings.passcode } } fileprivate func passcodeEnabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOffSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: true) ]) var requirePasscodeSectionChildren: [Setting] = [RequirePasscodeSetting(settings: self)] let localAuthContext = LAContext() if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { let title: String if #available(iOS 11.0, *), localAuthContext.biometryType == .faceID { title = Strings.UseFaceID } else { title = Strings.UseTouchID } requirePasscodeSectionChildren.append( TouchIDSetting( title: NSAttributedString.tableRowTitle(title, enabled: true), navigationController: self.navigationController, delegate: nil, enabled: true, touchIDSuccess: { [unowned self] in self.touchIDAuthenticationSucceeded() }, touchIDFallback: { [unowned self] in self.fallbackOnTouchIDFailure() } ) ) } let requirePasscodeSection = SettingSection(title: nil, children: requirePasscodeSectionChildren) settings += [ passcodeSection, requirePasscodeSection, ] return settings } fileprivate func passcodeDisabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOnSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: false) ]) let requirePasscodeSection = SettingSection(title: nil, children: [ RequirePasscodeSetting(settings: self, delegate: nil, enabled: false), ]) settings += [ passcodeSection, requirePasscodeSection, ] return settings } } extension AuthenticationSettingsViewController { func refreshSettings(_ notification: Notification) { updateTitleForTouchIDState() settings = generateSettings() tableView.reloadData() } } extension AuthenticationSettingsViewController: PasscodeEntryDelegate { fileprivate func getTouchIDSetting() -> TouchIDSetting? { guard settings.count >= 2 && settings[1].count >= 2 else { return nil } return settings[1][1] as? TouchIDSetting } func touchIDAuthenticationSucceeded() { getTouchIDSetting()?.toggleTouchID(false) } func fallbackOnTouchIDFailure() { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self) } @objc func passcodeValidationDidSucceed() { getTouchIDSetting()?.toggleTouchID(false) navigationController?.dismiss(animated: true, completion: nil) } }
8fcd799b927e5c7cab15985d422bd6f7
37.399449
158
0.673793
false
false
false
false
mozilla/focus
refs/heads/master
Blockzilla/BrowserViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import SnapKit import Telemetry import LocalAuthentication import StoreKit import Intents class BrowserViewController: UIViewController { let appSplashController: AppSplashController private var context = LAContext() private let mainContainerView = UIView(frame: .zero) let darkView = UIView() private let webViewController = WebViewController(userAgent: UserAgent.shared) private let webViewContainer = UIView() var modalDelegate: ModalDelegate? private var keyboardState: KeyboardState? private let browserToolbar = BrowserToolbar() private var homeView: HomeView? private let overlayView = OverlayView() private let searchEngineManager = SearchEngineManager(prefs: UserDefaults.standard) private let urlBarContainer = URLBarContainer() private var urlBar: URLBar! private let requestHandler = RequestHandler() private let searchSuggestClient = SearchSuggestClient() private var findInPageBar: FindInPageBar? private var fillerView: UIView? private let alertStackView = UIStackView() // All content that appears above the footer should be added to this view. (Find In Page/SnackBars) private var toolbarBottomConstraint: Constraint! private var urlBarTopConstraint: Constraint! private var homeViewBottomConstraint: Constraint! private var browserBottomConstraint: Constraint! private var lastScrollOffset = CGPoint.zero private var lastScrollTranslation = CGPoint.zero private var scrollBarOffsetAlpha: CGFloat = 0 private var scrollBarState: URLBarScrollState = .expanded private enum URLBarScrollState { case collapsed case expanded case transitioning case animating } private var trackingProtectionStatus: TrackingProtectionStatus = .on(TPPageStats()) { didSet { urlBar.updateTrackingProtectionBadge(trackingStatus: trackingProtectionStatus) } } private var homeViewContainer = UIView() private var showsToolsetInURLBar = false { didSet { if showsToolsetInURLBar { browserBottomConstraint.deactivate() } else { browserBottomConstraint.activate() } } } private let searchSuggestionsDebouncer = Debouncer(timeInterval: 0.1) private var shouldEnsureBrowsingMode = false private var initialUrl: URL? var tipManager: TipManager? static let userDefaultsTrackersBlockedKey = "lifetimeTrackersBlocked" init(appSplashController: AppSplashController, tipManager: TipManager = TipManager.shared) { self.appSplashController = appSplashController self.tipManager = tipManager super.init(nibName: nil, bundle: nil) KeyboardHelper.defaultHelper.addDelegate(delegate: self) } required init?(coder aDecoder: NSCoder) { fatalError("BrowserViewController hasn't implemented init?(coder:)") } override func viewDidLoad() { super.viewDidLoad() setupBiometrics() view.addSubview(mainContainerView) darkView.isHidden = true darkView.backgroundColor = UIConstants.colors.background darkView.alpha = 0.4 view.addSubview(darkView) darkView.snp.makeConstraints { make in make.edges.equalToSuperview() } mainContainerView.snp.makeConstraints { make in make.top.bottom.leading.width.equalToSuperview() } webViewController.delegate = self let background = GradientBackgroundView(alpha: 0.7, startPoint: CGPoint.zero, endPoint: CGPoint(x: 1, y: 1)) mainContainerView.addSubview(background) mainContainerView.addSubview(homeViewContainer) webViewContainer.isHidden = true mainContainerView.addSubview(webViewContainer) urlBarContainer.alpha = 0 mainContainerView.addSubview(urlBarContainer) browserToolbar.isHidden = true browserToolbar.alpha = 0 browserToolbar.delegate = self browserToolbar.translatesAutoresizingMaskIntoConstraints = false mainContainerView.addSubview(browserToolbar) overlayView.isHidden = true overlayView.alpha = 0 overlayView.delegate = self overlayView.backgroundColor = UIConstants.colors.overlayBackground overlayView.setSearchSuggestionsPromptViewDelegate(delegate: self) mainContainerView.addSubview(overlayView) background.snp.makeConstraints { make in make.edges.equalTo(mainContainerView) } urlBarContainer.snp.makeConstraints { make in make.top.leading.trailing.equalTo(mainContainerView) make.height.equalTo(mainContainerView).multipliedBy(0.6).priority(500) } browserToolbar.snp.makeConstraints { make in make.leading.trailing.equalTo(mainContainerView) toolbarBottomConstraint = make.bottom.equalTo(mainContainerView).constraint } homeViewContainer.snp.makeConstraints { make in make.top.equalTo(mainContainerView.safeAreaLayoutGuide.snp.top) make.leading.trailing.equalTo(mainContainerView) homeViewBottomConstraint = make.bottom.equalTo(mainContainerView).constraint homeViewBottomConstraint.activate() } webViewContainer.snp.makeConstraints { make in make.top.equalTo(urlBarContainer.snp.bottom).priority(500) make.bottom.equalTo(mainContainerView).priority(500) browserBottomConstraint = make.bottom.equalTo(browserToolbar.snp.top).priority(1000).constraint if !showsToolsetInURLBar { browserBottomConstraint.activate() } make.leading.trailing.equalTo(mainContainerView) } overlayView.snp.makeConstraints { make in make.top.equalTo(urlBarContainer.snp.bottom) make.leading.trailing.bottom.equalTo(mainContainerView) } view.addSubview(alertStackView) alertStackView.axis = .vertical alertStackView.alignment = .center // true if device is an iPad or is an iPhone in landscape mode showsToolsetInURLBar = (UIDevice.current.userInterfaceIdiom == .pad && (UIScreen.main.bounds.width == view.frame.size.width || view.frame.size.width > view.frame.size.height)) || (UIDevice.current.userInterfaceIdiom == .phone && view.frame.size.width > view.frame.size.height) containWebView() createHomeView() createURLBar() updateViewConstraints() // Listen for request desktop site notifications NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: UIConstants.strings.requestDesktopNotification), object: nil, queue: nil) { _ in self.webViewController.requestUserAgentChange() } // Listen for request mobile site notifications NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: UIConstants.strings.requestMobileNotification), object: nil, queue: nil) { _ in self.webViewController.requestUserAgentChange() } let dropInteraction = UIDropInteraction(delegate: self) view.addInteraction(dropInteraction) // Listen for find in page actvitiy notifications NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: UIConstants.strings.findInPageNotification), object: nil, queue: nil) { _ in self.updateFindInPageVisibility(visible: true, text: "") } guard shouldEnsureBrowsingMode else { return } ensureBrowsingMode() guard let url = initialUrl else { return } submit(url: url) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: animated) if let homeViewToolset = homeView?.toolbar.toolset { homeViewToolset.setHighlightWhatsNew(shouldHighlight: homeViewToolset.shouldShowWhatsNew()) homeView?.toolbar.layoutIfNeeded() } browserToolbar.toolset.setHighlightWhatsNew(shouldHighlight: browserToolbar.toolset.shouldShowWhatsNew()) browserToolbar.layoutIfNeeded() super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { // Prevent the keyboard from showing up until after the user has viewed the Intro. let userHasSeenIntro = UserDefaults.standard.integer(forKey: AppDelegate.prefIntroDone) == AppDelegate.prefIntroVersion if userHasSeenIntro && !urlBar.inBrowsingMode { urlBar.activateTextField() } super.viewDidAppear(animated) } private func setupBiometrics() { // Register for foreground notification to check biometric authentication NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { notification in var biometricError: NSError? // Check if user is already in a cleared session, or doesn't have biometrics enabled in settings if !Settings.getToggle(SettingsToggle.biometricLogin) || !AppDelegate.needsAuthenticated || self.webViewContainer.isHidden { self.appSplashController.toggleSplashView(hide: true) return } AppDelegate.needsAuthenticated = false self.context = LAContext() self.context.localizedReason = String(format: UIConstants.strings.authenticationReason, AppInfo.productName) self.context.localizedCancelTitle = UIConstants.strings.newSessionFromBiometricFailure if self.context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthentication, error: &biometricError) { self.context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: self.context.localizedReason) { [unowned self] (success, _) in DispatchQueue.main.async { if success { self.showToolbars() self.appSplashController.toggleSplashView(hide: true) } else { // Clear the browser session, as the user failed to authenticate self.resetBrowser(hidePreviousSession: true) self.appSplashController.toggleSplashView(hide: true) } } } } else { // Ran into an error with biometrics, so disable them and clear the browser: Settings.set(false, forToggle: SettingsToggle.biometricLogin) self.resetBrowser() self.appSplashController.toggleSplashView(hide: true) } } } // These functions are used to handle displaying and hiding the keyboard after the splash view is animated public func activateUrlBarOnHomeView() { // If the home view is not displayed, nor the overlayView hidden do not activate the text field: guard homeView != nil || !overlayView.isHidden else { return } urlBar.activateTextField() } public func deactivateUrlBarOnHomeView() { urlBar.dismissTextField() } private func containWebView() { addChild(webViewController) webViewContainer.addSubview(webViewController.view) webViewController.didMove(toParent: self) webViewController.view.snp.makeConstraints { make in make.edges.equalTo(webViewContainer.snp.edges) } } public func exitFullScreenVideo() { let js = "document.getElementsByTagName('video')[0].webkitExitFullScreen()" webViewController.evaluate(js, completion: nil) } private func createHomeView() { let homeView: HomeView if TipManager.shared.shouldShowTips() { homeView = HomeView(tipManager: tipManager) } else { homeView = HomeView() } homeView.delegate = self homeView.toolbar.toolset.delegate = self homeViewContainer.addSubview(homeView) homeView.snp.makeConstraints { make in make.edges.equalTo(homeViewContainer) } if let homeView = self.homeView { homeView.removeFromSuperview() } self.homeView = homeView } private func createURLBar() { urlBar = URLBar() urlBar.delegate = self urlBar.toolsetDelegate = self urlBar.shrinkFromView = urlBarContainer urlBar.shouldShowToolset = showsToolsetInURLBar mainContainerView.insertSubview(urlBar, aboveSubview: urlBarContainer) urlBar.snp.makeConstraints { make in urlBarTopConstraint = make.top.equalTo(mainContainerView.safeAreaLayoutGuide.snp.top).constraint make.leading.trailing.bottom.equalTo(urlBarContainer) } } private func buildTrackingProtectionMenu(info: TPPageStats?) -> PhotonActionSheet { var actions = [[PhotonActionSheetItem]]() if info != nil { let titleItem = PhotonActionSheetItem(title: UIConstants.strings.trackingProtectionLabel, text: UIConstants.strings.trackingProtectionLabelDescription, textStyle: .subtitle, iconString: "tracking_protection", isEnabled: true, accessory: .Switch) actions.append([titleItem]) } else { let titleItem = PhotonActionSheetItem(title: UIConstants.strings.trackingProtectionLabel, iconString: "tracking_protection_off", isEnabled: false, accessory: .Switch) actions.append([titleItem]) } let totalCount = PhotonActionSheetItem(title: UIConstants.strings.trackersBlocked, accessory: .Text, accessoryText: String(info?.total ?? 0), bold: true) let adCount = PhotonActionSheetItem(title: UIConstants.strings.adTrackerLabel, accessory: .Text, accessoryText: String(info?.adCount ?? 0)) let analyticCount = PhotonActionSheetItem(title: UIConstants.strings.analyticTrackerLabel, accessory: .Text, accessoryText: String(info?.analyticCount ?? 0)) let socialCount = PhotonActionSheetItem(title: UIConstants.strings.socialTrackerLabel, accessory: .Text, accessoryText: String(info?.socialCount ?? 0)) let contentCount = PhotonActionSheetItem(title: UIConstants.strings.contentTrackerLabel, accessory: .Text, accessoryText: String(info?.contentCount ?? 0)) actions.append([totalCount, adCount, analyticCount, socialCount, contentCount]) return PhotonActionSheet(actions: actions, style: .overCurrentContext) } override func updateViewConstraints() { super.updateViewConstraints() alertStackView.snp.remakeConstraints { make in make.centerX.equalTo(self.view) make.width.equalTo(self.view.snp.width) if let keyboardHeight = keyboardState?.intersectionHeightForView(view: self.view), keyboardHeight > 0 { make.bottom.equalTo(self.view).offset(-keyboardHeight) } else if !browserToolbar.isHidden { // is an iPhone make.bottom.equalTo(self.browserToolbar.snp.top).priority(.low) make.bottom.lessThanOrEqualTo(self.view.safeAreaLayoutGuide.snp.bottom).priority(.required) } else { // is an iPad make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom) } } } func updateFindInPageVisibility(visible: Bool, text: String = "") { if visible { if findInPageBar == nil { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.open, object: TelemetryEventObject.findInPageBar) urlBar.dismiss { // Start our animation after urlBar dismisses let findInPageBar = FindInPageBar() self.findInPageBar = findInPageBar let fillerView = UIView() self.fillerView = fillerView fillerView.backgroundColor = UIConstants.Photon.Grey70 findInPageBar.text = text findInPageBar.delegate = self self.alertStackView.addArrangedSubview(findInPageBar) self.mainContainerView.insertSubview(fillerView, belowSubview: self.browserToolbar) findInPageBar.snp.makeConstraints { make in make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.alertStackView) make.bottom.equalTo(self.alertStackView.snp.bottom) } fillerView.snp.makeConstraints { make in make.top.equalTo(self.alertStackView.snp.bottom) make.bottom.equalTo(self.view) make.leading.trailing.equalTo(self.alertStackView) } self.view.layoutIfNeeded() self.findInPageBar?.becomeFirstResponder() } } } else if let findInPageBar = self.findInPageBar { findInPageBar.endEditing(true) webViewController.evaluate("__firefox__.findDone()", completion: nil) findInPageBar.removeFromSuperview() fillerView?.removeFromSuperview() self.findInPageBar = nil self.fillerView = nil updateViewConstraints() } } func resetBrowser(hidePreviousSession: Bool = false) { // Used when biometrics fail and the previous session should be obscured if hidePreviousSession { clearBrowser() urlBar.activateTextField() return } // Screenshot the browser, showing the screenshot on top. let screenshotView = view.snapshotView(afterScreenUpdates: true) ?? UIView() mainContainerView.addSubview(screenshotView) screenshotView.snp.makeConstraints { make in make.edges.equalTo(mainContainerView) } clearBrowser() UIView.animate(withDuration: UIConstants.layout.deleteAnimationDuration, animations: { screenshotView.snp.remakeConstraints { make in make.centerX.equalTo(self.mainContainerView) make.top.equalTo(self.mainContainerView.snp.bottom) make.size.equalTo(self.mainContainerView).multipliedBy(0.9) } screenshotView.alpha = 0 self.mainContainerView.layoutIfNeeded() }, completion: { _ in self.urlBar.activateTextField() Toast(text: UIConstants.strings.eraseMessage).show() screenshotView.removeFromSuperview() }) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.click, object: TelemetryEventObject.eraseButton) if #available(iOS 12.0, *) { userActivity = SiriShortcuts().getActivity(for: .eraseAndOpen) let interaction = INInteraction(intent: eraseIntent, response: nil) interaction.donate { (error) in if let error = error { print(error.localizedDescription) } } } } private func clearBrowser() { // Helper function for resetBrowser that handles all the logic of actually clearing user data and the browsing session overlayView.currentURL = "" webViewController.reset() webViewContainer.isHidden = true browserToolbar.isHidden = true browserToolbar.canGoBack = false browserToolbar.canGoForward = false urlBar.removeFromSuperview() urlBarContainer.alpha = 0 createHomeView() createURLBar() // Clear the cache and cookies, starting a new session. WebCacheUtils.reset() requestReviewIfNecessary() mainContainerView.layoutIfNeeded() } func requestReviewIfNecessary() { if AppInfo.isTesting() { return } let currentLaunchCount = UserDefaults.standard.integer(forKey: UIConstants.strings.userDefaultsLaunchCountKey) let threshold = UserDefaults.standard.integer(forKey: UIConstants.strings.userDefaultsLaunchThresholdKey) if threshold == 0 { UserDefaults.standard.set(14, forKey: UIConstants.strings.userDefaultsLaunchThresholdKey) return } // Make sure the request isn't within 90 days of last request let minimumDaysBetweenReviewRequest = 90 let daysSinceLastRequest: Int if let previousRequest = UserDefaults.standard.object(forKey: UIConstants.strings.userDefaultsLastReviewRequestDate) as? Date { daysSinceLastRequest = Calendar.current.dateComponents([.day], from: previousRequest, to: Date()).day ?? 0 } else { // No previous request date found, meaning we've never asked for a review daysSinceLastRequest = minimumDaysBetweenReviewRequest } if currentLaunchCount <= threshold || daysSinceLastRequest < minimumDaysBetweenReviewRequest { return } UserDefaults.standard.set(Date(), forKey: UIConstants.strings.userDefaultsLastReviewRequestDate) // Increment the threshold by 50 so the user is not constantly pestered with review requests switch threshold { case 14: UserDefaults.standard.set(64, forKey: UIConstants.strings.userDefaultsLaunchThresholdKey) case 64: UserDefaults.standard.set(114, forKey: UIConstants.strings.userDefaultsLaunchThresholdKey) default: break } SKStoreReviewController.requestReview() } private func showSettings(shouldScrollToSiri: Bool = false) { guard let modalDelegate = modalDelegate else { return } let settingsViewController = SettingsViewController(searchEngineManager: searchEngineManager, whatsNew: browserToolbar.toolset, shouldScrollToSiri: shouldScrollToSiri) let settingsNavController = UINavigationController(rootViewController: settingsViewController) settingsNavController.modalPresentationStyle = .formSheet modalDelegate.presentModal(viewController: settingsNavController, animated: true) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.click, object: TelemetryEventObject.settingsButton) } @available(iOS 12.0, *) private func showSiriFavoriteSettings() { guard let modalDelegate = modalDelegate else { return } urlBar.shouldPresent = false let siriFavoriteViewController = SiriFavoriteViewController() let siriFavoriteNavController = UINavigationController(rootViewController: siriFavoriteViewController) siriFavoriteNavController.modalPresentationStyle = .formSheet modalDelegate.presentModal(viewController: siriFavoriteNavController, animated: true) } func ensureBrowsingMode() { guard urlBar != nil else { shouldEnsureBrowsingMode = true; return } guard !urlBar.inBrowsingMode else { return } urlBarContainer.alpha = 1 urlBar.ensureBrowsingMode() shouldEnsureBrowsingMode = false } func submit(url: URL) { // If this is the first navigation, show the browser and the toolbar. guard isViewLoaded else { initialUrl = url; return } if webViewContainer.isHidden { webViewContainer.isHidden = false homeView?.removeFromSuperview() homeView = nil urlBar.inBrowsingMode = true if !showsToolsetInURLBar { browserToolbar.animateHidden(false, duration: UIConstants.layout.toolbarFadeAnimationDuration) } } webViewController.load(URLRequest(url: url)) if urlBar.url == nil { urlBar.url = url } guard #available(iOS 12.0, *), let savedUrl = UserDefaults.standard.value(forKey: "favoriteUrl") as? String else { return } if let currentDomain = url.baseDomain, let savedDomain = URL(string: savedUrl)?.baseDomain, currentDomain == savedDomain { userActivity = SiriShortcuts().getActivity(for: .openURL) } } func openOverylay(text: String) { urlBar.activateTextField() urlBar.fillUrlBar(text: text) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // Fixes the issue of a user fresh-opening Focus via Split View guard isViewLoaded else { return } // UIDevice.current.orientation isn't reliable. See https://bugzilla.mozilla.org/show_bug.cgi?id=1315370#c5 // As a workaround, consider the phone to be in landscape if the new width is greater than the height. showsToolsetInURLBar = (UIDevice.current.userInterfaceIdiom == .pad && (UIScreen.main.bounds.width == size.width || size.width > size.height)) || (UIDevice.current.userInterfaceIdiom == .phone && size.width > size.height) urlBar.updateConstraints() browserToolbar.updateConstraints() coordinator.animate(alongsideTransition: { _ in self.urlBar.shouldShowToolset = self.showsToolsetInURLBar if self.homeView == nil && self.scrollBarState != .expanded { self.hideToolbars() } self.browserToolbar.animateHidden(self.homeView != nil || self.showsToolsetInURLBar, duration: coordinator.transitionDuration, completion: { self.updateViewConstraints() }) }) } private func presentImageActionSheet(title: String, link: String?, saveAction: @escaping () -> Void, copyAction: @escaping () -> Void) { var normalizedTitle = title if title.count > UIConstants.layout.truncateCharactersLimit { normalizedTitle = String("\(title.prefix(UIConstants.layout.truncateHeadCharactersCount))\(UIConstants.strings.truncateLeader)\(title.suffix(UIConstants.layout.truncateTailCharactersCount))") } let alertController = UIAlertController(title: normalizedTitle, message: nil, preferredStyle: .actionSheet) if let link = link { alertController.addAction(UIAlertAction(title: UIConstants.strings.copyLink, style: .default) { _ in UIPasteboard.general.string = link }) alertController.addAction(UIAlertAction(title: UIConstants.strings.shareLink, style: .default) { _ in let activityViewController = UIActivityViewController(activityItems: [link], applicationActivities: nil) self.present(activityViewController, animated: true, completion: nil) }) } alertController.addAction(UIAlertAction(title: UIConstants.strings.saveImage, style: .default) { _ in saveAction() }) alertController.addAction(UIAlertAction(title: UIConstants.strings.copyImage, style: .default) { _ in copyAction() }) alertController.addAction(UIAlertAction(title: UIConstants.strings.cancel, style: .cancel)) alertController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0) alertController.popoverPresentationController?.sourceView = self.view alertController.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.size.width / 2.0, y: self.view.bounds.size.height / 2.0, width: 1.0, height: 1.0) present(alertController, animated: true, completion: nil) } @objc private func selectLocationBar() { showToolbars() urlBar.activateTextField() } @objc private func reload() { webViewController.reload() } @objc private func goBack() { webViewController.goBack() } @objc private func goForward() { webViewController.goForward() } private func toggleURLBarBackground(isBright: Bool) { if urlBar.isEditing { urlBarContainer.barState = .editing } else if case .on = trackingProtectionStatus { urlBarContainer.barState = .bright } else { urlBarContainer.barState = .dark } } private func toggleToolbarBackground() { switch trackingProtectionStatus { case .off: browserToolbar.color = .dark case .on: browserToolbar.color = .bright } } override var keyCommands: [UIKeyCommand]? { return [ UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(BrowserViewController.selectLocationBar), discoverabilityTitle: UIConstants.strings.selectLocationBarTitle), UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(BrowserViewController.reload), discoverabilityTitle: UIConstants.strings.browserReload), UIKeyCommand(input: "[", modifierFlags: .command, action: #selector(BrowserViewController.goBack), discoverabilityTitle: UIConstants.strings.browserBack), UIKeyCommand(input: "]", modifierFlags: .command, action: #selector(BrowserViewController.goForward), discoverabilityTitle: UIConstants.strings.browserForward) ] } func refreshTipsDisplay() { createHomeView() } private func getNumberOfLifetimeTrackersBlocked(userDefaults: UserDefaults = UserDefaults.standard) -> Int { return userDefaults.integer(forKey: BrowserViewController.userDefaultsTrackersBlockedKey) } private func setNumberOfLifetimeTrackersBlocked(numberOfTrackers: Int) { UserDefaults.standard.set(numberOfTrackers, forKey: BrowserViewController.userDefaultsTrackersBlockedKey) } func updateURLBar() { if webViewController.url?.absoluteString != "about:blank" { urlBar.url = webViewController.url overlayView.currentURL = urlBar.url?.absoluteString ?? "" } } } extension BrowserViewController: UIDropInteractionDelegate { func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool { return session.canLoadObjects(ofClass: URL.self) } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal { return UIDropProposal(operation: .copy) } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { _ = session.loadObjects(ofClass: URL.self) { urls in guard let url = urls.first else { return } self.ensureBrowsingMode() self.urlBar.fillUrlBar(text: url.absoluteString) self.submit(url: url) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.drop, object: TelemetryEventObject.searchBar) } } } extension BrowserViewController: FindInPageBarDelegate { func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) { find(text, function: "find") } func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.click, object: TelemetryEventObject.findNext) findInPageBar?.endEditing(true) find(text, function: "findNext") } func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.click, object: TelemetryEventObject.findPrev) findInPageBar?.endEditing(true) find(text, function: "findPrevious") } func findInPageDidPressClose(_ findInPage: FindInPageBar) { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.close, object: TelemetryEventObject.findInPageBar) updateFindInPageVisibility(visible: false) } private func find(_ text: String, function: String) { let escaped = text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") webViewController.evaluate("__firefox__.\(function)(\"\(escaped)\")", completion: nil) } } extension BrowserViewController: URLBarDelegate { func urlBar(_ urlBar: URLBar, didAddCustomURL url: URL) { // Add the URL to the autocomplete list: let autocompleteSource = CustomCompletionSource() switch autocompleteSource.add(suggestion: url.absoluteString) { case .error(.duplicateDomain): break case .error(let error): guard !error.message.isEmpty else { return } Toast(text: error.message).show() case .success: Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.change, object: TelemetryEventObject.customDomain) Toast(text: UIConstants.strings.autocompleteCustomURLAdded).show() } } func urlBar(_ urlBar: URLBar, didEnterText text: String) { let trimmedText = text.trimmingCharacters(in: .whitespaces) let isOnHomeView = homeView != nil if Settings.getToggle(.enableSearchSuggestions) && !trimmedText.isEmpty { searchSuggestionsDebouncer.renewInterval() searchSuggestionsDebouncer.completion = { self.searchSuggestClient.getSuggestions(trimmedText, callback: { suggestions, error in let userInputText = urlBar.userInputText?.trimmingCharacters(in: .whitespaces) ?? "" // Check if this callback is stale (new user input has been requested) if userInputText.isEmpty || userInputText != trimmedText { return } if userInputText == trimmedText { let suggestions = suggestions ?? [trimmedText] DispatchQueue.main.async { self.overlayView.setSearchQuery(suggestions: suggestions, hideFindInPage: isOnHomeView || text.isEmpty, hideAddToComplete: true) } } }) } } else { overlayView.setSearchQuery(suggestions: [trimmedText], hideFindInPage: isOnHomeView || text.isEmpty, hideAddToComplete: true) } } func urlBarDidPressScrollTop(_: URLBar, tap: UITapGestureRecognizer) { guard !urlBar.isEditing else { return } switch scrollBarState { case .expanded: let y = tap.location(in: urlBar).y // If the tap is greater than this threshold, the user wants to type in the URL bar if y >= 10 { urlBar.activateTextField() return } // Just scroll the vertical position so the page doesn't appear under // the notch on the iPhone X var point = webViewController.scrollView.contentOffset point.y = 0 webViewController.scrollView.setContentOffset(point, animated: true) case .collapsed: showToolbars() default: break } } func urlBar(_ urlBar: URLBar, didSubmitText text: String) { let text = text.trimmingCharacters(in: .whitespaces) guard !text.isEmpty else { urlBar.url = webViewController.url return } SearchHistoryUtils.pushSearchToStack(with: text) SearchHistoryUtils.isFromURLBar = true var url = URIFixup.getURL(entry: text) if url == nil { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.typeQuery, object: TelemetryEventObject.searchBar) Telemetry.default.recordSearch(location: .actionBar, searchEngine: searchEngineManager.activeEngine.getNameOrCustom()) url = searchEngineManager.activeEngine.urlForQuery(text) } else { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.typeURL, object: TelemetryEventObject.searchBar) } if let urlBarURL = url { submit(url: urlBarURL) urlBar.url = urlBarURL } if let urlText = urlBar.url?.absoluteString { overlayView.currentURL = urlText } urlBar.dismiss() } func urlBarDidDismiss(_ urlBar: URLBar) { overlayView.dismiss() toggleURLBarBackground(isBright: !webViewController.isLoading) } func urlBarDidPressDelete(_ urlBar: URLBar) { updateFindInPageVisibility(visible: false) self.resetBrowser() } func urlBarDidFocus(_ urlBar: URLBar) { let isOnHomeView = homeView != nil overlayView.present(isOnHomeView: isOnHomeView) toggleURLBarBackground(isBright: false) } func urlBarDidActivate(_ urlBar: URLBar) { UIView.animate(withDuration: UIConstants.layout.urlBarTransitionAnimationDuration, animations: { self.urlBarContainer.alpha = 1 self.updateFindInPageVisibility(visible: false) self.view.layoutIfNeeded() }) } func urlBarDidDeactivate(_ urlBar: URLBar) { UIView.animate(withDuration: UIConstants.layout.urlBarTransitionAnimationDuration) { self.urlBarContainer.alpha = 0 self.view.layoutIfNeeded() } } func urlBarDidTapShield(_ urlBar: URLBar) { Telemetry.default.recordEvent(TelemetryEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.open, object: TelemetryEventObject.trackingProtectionDrawer)) switch trackingProtectionStatus { case .on(let info): let menuOn = buildTrackingProtectionMenu(info: info) presentPhotonActionSheet(menuOn, from: urlBar.shieldIcon) case .off: let menuOff = buildTrackingProtectionMenu(info: nil) presentPhotonActionSheet(menuOff, from: urlBar.shieldIcon) } } func urlBarDidLongPress(_ urlBar: URLBar) { let customURLItem = PhotonActionSheetItem(title: UIConstants.strings.customURLMenuButton, iconString: "icon_link") { action in urlBar.addCustomURL() UserDefaults.standard.set(false, forKey: TipManager.TipKey.autocompleteTip) } var actions = [PhotonActionSheetItem]() if let clipboardString = UIPasteboard.general.string { let pasteAndGoItem = PhotonActionSheetItem(title: UIConstants.strings.urlPasteAndGo, iconString: "icon_paste_and_go") { action in urlBar.pasteAndGo(clipboardString: clipboardString) } actions.append(pasteAndGoItem) let pasteItem = PhotonActionSheetItem(title: UIConstants.strings.urlPaste, iconString: "icon_paste") { action in urlBar.paste(clipboardString: clipboardString) } actions.append(pasteItem) } let copyItem = PhotonActionSheetItem(title: UIConstants.strings.copyAddressButton, iconString: "icon_link") { action in urlBar.copyToClipboard() Toast(text: UIConstants.strings.copyURLToast).show() } actions.append(copyItem) let urlContextMenu = PhotonActionSheet(actions: [[customURLItem], actions], style: .overCurrentContext) presentPhotonActionSheet(urlContextMenu, from: urlBar) } func urlBarDidPressPageActions(_ urlBar: URLBar) { guard let url = urlBar.url else { return } let utils = OpenUtils(url: url, webViewController: webViewController) let items = PageActionSheetItems(url: url) let sharePageItem = PhotonActionSheetItem(title: UIConstants.strings.sharePage, iconString: "icon_openwith_active") { action in let shareVC = utils.buildShareViewController() // Exact frame dimensions taken from presentPhotonActionSheet shareVC.popoverPresentationController?.sourceView = urlBar.pageActionsButton shareVC.popoverPresentationController?.sourceRect = CGRect(x: urlBar.pageActionsButton.frame.width/2, y: urlBar.pageActionsButton.frame.size.height * 0.75, width: 1, height: 1) shareVC.becomeFirstResponder() self.present(shareVC, animated: true, completion: nil) } var shareItems = [sharePageItem] if items.canOpenInFirefox { shareItems.append(items.openInFireFoxItem) } if items.canOpenInChrome { shareItems.append(items.openInChromeItem) } shareItems.append(items.openInSafariItem) let copyItem = PhotonActionSheetItem(title: UIConstants.strings.copyAddress, iconString: "icon_link") { action in urlBar.copyToClipboard() Toast(text: UIConstants.strings.copyURLToast).show() } shareItems.append(copyItem) var actionItems = [items.findInPageItem] webViewController.userAgentString == UserAgent.getDesktopUserAgent() ? actionItems.append(items.requestMobileItem) : actionItems.append(items.requestDesktopItem) let pageActionsMenu = PhotonActionSheet(title: UIConstants.strings.pageActionsTitle, actions: [shareItems, actionItems], style: .overCurrentContext) presentPhotonActionSheet(pageActionsMenu, from: urlBar.pageActionsButton) } } extension BrowserViewController: PhotonActionSheetDelegate { func presentPhotonActionSheet(_ actionSheet: PhotonActionSheet, from sender: UIView) { actionSheet.modalPresentationStyle = UIDevice.current.userInterfaceIdiom == .pad ? .popover : .overCurrentContext actionSheet.delegate = self darkView.isHidden = false if let popoverVC = actionSheet.popoverPresentationController, actionSheet.modalPresentationStyle == .popover { popoverVC.delegate = self popoverVC.sourceView = sender popoverVC.sourceRect = CGRect(x: sender.frame.width/2, y: sender.frame.size.height * 0.75, width: 1, height: 1) popoverVC.permittedArrowDirections = .up popoverVC.backgroundColor = UIConstants.colors.background } present(actionSheet, animated: true, completion: nil) } func photonActionSheetDidDismiss() { darkView.isHidden = true } func photonActionSheetDidToggleProtection(enabled: Bool) { enabled ? webViewController.enableTrackingProtection() : webViewController.disableTrackingProtection() let telemetryEvent = TelemetryEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.change, object: TelemetryEventObject.trackingProtectionToggle) telemetryEvent.addExtra(key: "to", value: enabled) Telemetry.default.recordEvent(telemetryEvent) UserDefaults.standard.set(false, forKey: TipManager.TipKey.sitesNotWorkingTip) webViewController.reload() } } extension BrowserViewController: BrowserToolsetDelegate { func browserToolsetDidLongPressReload(_ browserToolbar: BrowserToolset) { // Request desktop site urlBar.dismiss() let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let title = webViewController.userAgentString == UserAgent.getDesktopUserAgent() ? "Request Mobile Site" : "Request Desktop Site" let object = webViewController.userAgentString == UserAgent.getDesktopUserAgent() ? TelemetryEventObject.requestMobile : TelemetryEventObject.requestDesktop alert.addAction(UIAlertAction(title: title, style: .default, handler: { (action) in Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.click, object: object) self.webViewController.requestUserAgentChange() })) alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) // Must handle iPad interface separately, as it does not implement action sheets let iPadAlert = alert.popoverPresentationController iPadAlert?.sourceView = browserToolbar.stopReloadButton iPadAlert?.sourceRect = browserToolbar.stopReloadButton.bounds present(alert, animated: true) } func browserToolsetDidPressBack(_ browserToolset: BrowserToolset) { webViewController.goBack() } private func handleNavigationBack() { // Check if the previous site we were on was AMP guard let navigatingFromAmpSite = SearchHistoryUtils.pullSearchFromStack()?.hasPrefix(UIConstants.strings.googleAmpURLPrefix) else { return } // Make sure our navigation is not pushed to the SearchHistoryUtils stack (since it already exists there) SearchHistoryUtils.isFromURLBar = true // This function is now getting called after our new url is set!! if !navigatingFromAmpSite { SearchHistoryUtils.goBack() } } func browserToolsetDidPressForward(_ browserToolset: BrowserToolset) { webViewController.goForward() } private func handleNavigationForward() { // Make sure our navigation is not pushed to the SearchHistoryUtils stack (since it already exists there) SearchHistoryUtils.isFromURLBar = true // Check if we're navigating to an AMP site *after* the URL bar is updated. This is intentionally grabbing the NEW url guard let navigatingToAmpSite = urlBar.url?.absoluteString.hasPrefix(UIConstants.strings.googleAmpURLPrefix) else { return } if !navigatingToAmpSite { SearchHistoryUtils.goForward() } } func browserToolsetDidPressReload(_ browserToolset: BrowserToolset) { webViewController.reload() } func browserToolsetDidPressStop(_ browserToolset: BrowserToolset) { webViewController.stop() } func browserToolsetDidPressSettings(_ browserToolbar: BrowserToolset) { updateFindInPageVisibility(visible: false) showSettings() } } extension BrowserViewController: HomeViewDelegate { func shareTrackerStatsButtonTapped() { guard let trackerStatsShareButton = homeView?.trackerStatsShareButton else { return } Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.share, object: TelemetryEventObject.trackerStatsShareButton) let numberOfTrackersBlocked = getNumberOfLifetimeTrackersBlocked() let appStoreUrl = URL(string: String(format: "https://mzl.la/2GZBav0")) // Add space after shareTrackerStatsText to add URL in sentence let shareTrackerStatsText = "%@, the privacy browser from Mozilla, has already blocked %@ trackers for me. Fewer ads and trackers following me around means faster browsing! Get Focus for yourself here" let text = String(format: shareTrackerStatsText + " ", AppInfo.productName, String(numberOfTrackersBlocked)) let shareController = UIActivityViewController(activityItems: [text, appStoreUrl as Any], applicationActivities: nil) // Exact frame dimensions taken from presentPhotonActionSheet shareController.popoverPresentationController?.sourceView = trackerStatsShareButton shareController.popoverPresentationController?.sourceRect = CGRect(x: trackerStatsShareButton.frame.width/2, y: 0, width: 1, height: 1) present(shareController, animated: true) } func tipTapped() { guard let tip = tipManager?.currentTip, tip.showVc else { return } switch tip.identifier { case TipManager.TipKey.biometricTip: Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.click, object: TelemetryEventObject.biometricTip) showSettings() case TipManager.TipKey.siriEraseTip: Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.click, object: TelemetryEventObject.siriEraseTip) showSettings(shouldScrollToSiri: true) case TipManager.TipKey.siriFavoriteTip: if #available(iOS 12.0, *) { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.show, object: TelemetryEventObject.siriFavoriteTip) showSiriFavoriteSettings() } default: break } } } extension BrowserViewController: OverlayViewDelegate { func overlayViewDidPressSettings(_ overlayView: OverlayView) { showSettings() } func overlayViewDidTouchEmptyArea(_ overlayView: OverlayView) { urlBar.dismiss() } func overlayView(_ overlayView: OverlayView, didSearchForQuery query: String) { if searchEngineManager.activeEngine.urlForQuery(query) != nil { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.selectQuery, object: TelemetryEventObject.searchBar) Telemetry.default.recordSearch(location: .actionBar, searchEngine: searchEngineManager.activeEngine.getNameOrCustom()) urlBar(urlBar, didSubmitText: query) } urlBar.dismiss() } func overlayView(_ overlayView: OverlayView, didSearchOnPage query: String) { updateFindInPageVisibility(visible: true, text: query) self.find(query, function: "find") } func overlayView(_ overlayView: OverlayView, didAddToAutocomplete query: String) { urlBar.dismiss() let autocompleteSource = CustomCompletionSource() switch autocompleteSource.add(suggestion: query) { case .error(.duplicateDomain): Toast(text: UIConstants.strings.autocompleteCustomURLDuplicate).show() case .error(let error): guard !error.message.isEmpty else { return } Toast(text: error.message).show() case .success: Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.change, object: TelemetryEventObject.customDomain) Toast(text: UIConstants.strings.autocompleteCustomURLAdded).show() } } func overlayView(_ overlayView: OverlayView, didSubmitText text: String) { let text = text.trimmingCharacters(in: .whitespaces) guard !text.isEmpty else { urlBar.url = webViewController.url return } var url = URIFixup.getURL(entry: text) if url == nil { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.typeQuery, object: TelemetryEventObject.searchBar) Telemetry.default.recordSearch(location: .actionBar, searchEngine: searchEngineManager.activeEngine.getNameOrCustom()) url = searchEngineManager.activeEngine.urlForQuery(text) } else { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.typeURL, object: TelemetryEventObject.searchBar) } if let overlayURL = url { submit(url: overlayURL) urlBar.url = overlayURL } urlBar.dismiss() } } extension BrowserViewController: SearchSuggestionsPromptViewDelegate { func searchSuggestionsPromptView(_ searchSuggestionsPromptView: SearchSuggestionsPromptView, didEnable: Bool) { UserDefaults.standard.set(true, forKey: SearchSuggestionsPromptView.respondedToSearchSuggestionsPrompt) Settings.set(didEnable, forToggle: SettingsToggle.enableSearchSuggestions) overlayView.updateSearchSuggestionsPrompt(hidden: true) if didEnable, let urlbar = self.urlBar, let value = self.urlBar?.userInputText { urlBar(urlbar, didEnterText: value) } } } extension BrowserViewController: WebControllerDelegate { func webControllerDidStartProvisionalNavigation(_ controller: WebController) { urlBar.dismiss() updateFindInPageVisibility(visible: false) } func webController(_ controller: WebController, didUpdateFindInPageResults currentResult: Int?, totalResults: Int?) { if let total = totalResults { findInPageBar?.totalResults = total } if let current = currentResult { findInPageBar?.currentResult = current } } func webControllerDidReload(_ controller: WebController) { SearchHistoryUtils.isReload = true } func webControllerDidStartNavigation(_ controller: WebController) { if !SearchHistoryUtils.isFromURLBar && !SearchHistoryUtils.isNavigating && !SearchHistoryUtils.isReload { SearchHistoryUtils.pushSearchToStack(with: (urlBar.url?.absoluteString)!) } SearchHistoryUtils.isReload = false SearchHistoryUtils.isNavigating = false SearchHistoryUtils.isFromURLBar = false urlBar.isLoading = true browserToolbar.color = .loading toggleURLBarBackground(isBright: false) updateURLBar() } func webControllerDidFinishNavigation(_ controller: WebController) { updateURLBar() urlBar.isLoading = false toggleToolbarBackground() toggleURLBarBackground(isBright: !urlBar.isEditing) urlBar.progressBar.hideProgressBar() } func webControllerURLDidChange(_ controller: WebController, url: URL) { showToolbars() } func webController(_ controller: WebController, didFailNavigationWithError error: Error) { urlBar.url = webViewController.url urlBar.isLoading = false toggleURLBarBackground(isBright: true) toggleToolbarBackground() urlBar.progressBar.hideProgressBar() } func webController(_ controller: WebController, didUpdateCanGoBack canGoBack: Bool) { urlBar.canGoBack = canGoBack browserToolbar.canGoBack = canGoBack } func webController(_ controller: WebController, didUpdateCanGoForward canGoForward: Bool) { urlBar.canGoForward = canGoForward browserToolbar.canGoForward = canGoForward } func webController(_ controller: WebController, didUpdateEstimatedProgress estimatedProgress: Double) { // Don't update progress if the home view is visible. This prevents the centered URL bar // from catching the global progress events. guard homeView == nil else { return } urlBar.progressBar.alpha = 1 urlBar.progressBar.isHidden = false urlBar.progressBar.setProgress(Float(estimatedProgress), animated: true) } func webController(_ controller: WebController, scrollViewWillBeginDragging scrollView: UIScrollView) { lastScrollOffset = scrollView.contentOffset lastScrollTranslation = scrollView.panGestureRecognizer.translation(in: scrollView) } func webController(_ controller: WebController, scrollViewDidEndDragging scrollView: UIScrollView) { snapToolbars(scrollView: scrollView) } func webController(_ controller: WebController, scrollViewDidScroll scrollView: UIScrollView) { let translation = scrollView.panGestureRecognizer.translation(in: scrollView) let isDragging = scrollView.panGestureRecognizer.state != .possible // This will be 0 if we're moving but not dragging (i.e., gliding after dragging). let dragDelta = translation.y - lastScrollTranslation.y // This will match dragDelta unless the URL bar is transitioning. let offsetDelta = scrollView.contentOffset.y - lastScrollOffset.y lastScrollOffset = scrollView.contentOffset lastScrollTranslation = translation guard scrollBarState != .animating, !scrollView.isZooming else { return } guard scrollView.contentOffset.y + scrollView.frame.height < scrollView.contentSize.height && (scrollView.contentOffset.y > 0 || scrollBarOffsetAlpha > 0) else { // We're overscrolling, so don't do anything. return } if !isDragging && offsetDelta < 0 { // We're gliding up after dragging, so fully show the toolbars. showToolbars() return } let pageExtendsBeyondScrollView = scrollView.frame.height + (UIConstants.layout.browserToolbarHeight + view.safeAreaInsets.bottom) + UIConstants.layout.urlBarHeight < scrollView.contentSize.height let toolbarsHiddenAtTopOfPage = scrollView.contentOffset.y <= 0 && scrollBarOffsetAlpha > 0 guard isDragging, (dragDelta < 0 && pageExtendsBeyondScrollView) || toolbarsHiddenAtTopOfPage || scrollBarState == .transitioning else { return } let lastOffsetAlpha = scrollBarOffsetAlpha scrollBarOffsetAlpha = (0 ... 1).clamp(scrollBarOffsetAlpha - dragDelta / UIConstants.layout.urlBarHeight) switch scrollBarOffsetAlpha { case 0: scrollBarState = .expanded case 1: scrollBarState = .collapsed default: scrollBarState = .transitioning } self.urlBar.collapseUrlBar(expandAlpha: max(0, (1 - scrollBarOffsetAlpha * 2)), collapseAlpha: max(0, -(1 - scrollBarOffsetAlpha * 2))) self.urlBarTopConstraint.update(offset: -scrollBarOffsetAlpha * (UIConstants.layout.urlBarHeight - UIConstants.layout.collapsedUrlBarHeight)) self.toolbarBottomConstraint.update(offset: scrollBarOffsetAlpha * (UIConstants.layout.browserToolbarHeight + view.safeAreaInsets.bottom)) updateViewConstraints() scrollView.bounds.origin.y += (lastOffsetAlpha - scrollBarOffsetAlpha) * UIConstants.layout.urlBarHeight lastScrollOffset = scrollView.contentOffset } func webControllerShouldScrollToTop(_ controller: WebController) -> Bool { guard scrollBarOffsetAlpha == 0 else { showToolbars() return false } return true } func webControllerDidNavigateBack(_ controller: WebController) { handleNavigationBack() } func webControllerDidNavigateForward(_ controller: WebController) { handleNavigationForward() } func webController(_ controller: WebController, stateDidChange state: BrowserState) {} func webController(_ controller: WebController, didUpdateTrackingProtectionStatus trackingStatus: TrackingProtectionStatus) { // Calculate the number of trackers blocked and add that to lifetime total if case .on(let info) = trackingStatus, case .on(let oldInfo) = trackingProtectionStatus { let differenceSinceLastUpdate = max(0, info.total - oldInfo.total) let numberOfTrackersBlocked = getNumberOfLifetimeTrackersBlocked() setNumberOfLifetimeTrackersBlocked(numberOfTrackers: numberOfTrackersBlocked + differenceSinceLastUpdate) } trackingProtectionStatus = trackingStatus } private func showToolbars() { let scrollView = webViewController.scrollView scrollBarState = .animating UIView.animate(withDuration: UIConstants.layout.urlBarTransitionAnimationDuration, delay: 0, options: .allowUserInteraction, animations: { self.urlBar.collapseUrlBar(expandAlpha: 1, collapseAlpha: 0) self.urlBarTopConstraint.update(offset: 0) self.toolbarBottomConstraint.update(inset: 0) scrollView.bounds.origin.y += self.scrollBarOffsetAlpha * UIConstants.layout.urlBarHeight self.scrollBarOffsetAlpha = 0 self.view.layoutIfNeeded() }, completion: { _ in self.scrollBarState = .expanded }) } private func hideToolbars() { let scrollView = webViewController.scrollView scrollBarState = .animating UIView.animate(withDuration: UIConstants.layout.urlBarTransitionAnimationDuration, delay: 0, options: .allowUserInteraction, animations: { self.urlBar.collapseUrlBar(expandAlpha: 0, collapseAlpha: 1) self.urlBarTopConstraint.update(offset: -UIConstants.layout.urlBarHeight + UIConstants.layout.collapsedUrlBarHeight) self.toolbarBottomConstraint.update(offset: UIConstants.layout.browserToolbarHeight + self.view.safeAreaInsets.bottom) scrollView.bounds.origin.y += (self.scrollBarOffsetAlpha - 1) * UIConstants.layout.urlBarHeight self.scrollBarOffsetAlpha = 1 self.view.layoutIfNeeded() }, completion: { _ in self.scrollBarState = .collapsed }) } private func snapToolbars(scrollView: UIScrollView) { guard scrollBarState == .transitioning else { return } if scrollBarOffsetAlpha < 0.05 || scrollView.contentOffset.y < UIConstants.layout.urlBarHeight { showToolbars() } else { hideToolbars() } } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state self.updateViewConstraints() UIView.animate(withDuration: state.animationDuration) { self.homeViewBottomConstraint.update(offset: -state.intersectionHeightForView(view: self.view)) self.view.layoutIfNeeded() } } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = state self.updateViewConstraints() UIView.animate(withDuration: state.animationDuration) { self.homeViewBottomConstraint.update(offset: 0) self.view.layoutIfNeeded() } } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidHideWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } } extension BrowserViewController: UIPopoverPresentationControllerDelegate { func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { darkView.isHidden = true } } @available(iOS 12.0, *) extension BrowserViewController { public var eraseIntent: EraseIntent { let intent = EraseIntent() intent.suggestedInvocationPhrase = "Erase" return intent } } protocol WhatsNewDelegate { func shouldShowWhatsNew() -> Bool func didShowWhatsNew() }
36091a5a5797bf1fbfcd62c5895bb7a5
43.121064
284
0.685943
false
false
false
false
solinor/paymenthighway-ios-framework
refs/heads/master
PaymentHighway/UI/Theme/DefaultTheme.swift
mit
1
// // DefaultTheme.swift // PaymentHighway // // Copyright © 2018 Payment Highway Oy. All rights reserved. // private let defaultBarTintColor = UIColor(hexInt: 0xf6f6f6) private let defaultBackgroundColor = UIColor.white private let defaultPrimaryForegroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 153) private let defaultPrimaryActiveForegroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 222) private let defaultSecondaryForegroundColor = UIColor(hexInt: 0x9d00ba) private let defaultSecondaryActiveForegroundColor = defaultSecondaryForegroundColor private let defaultErrorForegroundColor = UIColor.red private let defaultErrorActiveForegroundColor = UIColor.red private let defaultHighlightColor = defaultSecondaryForegroundColor private let defaultHighlightDisableColor = UIColor(red: 124, green: 124, blue: 124, alpha: 153) private let defaultRoundedBorderRadius: CGFloat = 28 private let defaultPlaceholderFontScale: CGFloat = 0.8 private let defaultBorderWidth: CGFloat = 1.5 private let defaultPlaceholderAnimationDuration = 0.25 private let defaultFontSize: CGFloat = 13 private let defaultTextImageHeight: CGFloat = 24 private let defaultTextPaddingX: CGFloat = 24.0 private let defaultShowKeyboard = false private let defaultExpiryDatePicker = false /// Default implementation of the Theme /// /// - seealso: `Theme` open class DefaultTheme : Theme { /// Singleton instance of the default theme /// public static let instance: DefaultTheme = DefaultTheme() /// Animation duration for the placeholder label /// public var placeholderAnimationDuration: Double /// Border Radius to make Text Field rounded /// public var borderRadius: CGFloat /// Placeholder label font scale. /// /// Text field when focused or not empty show the placeholder label above the text with a smaller font public var placeholderFontScale: CGFloat /// Border width /// public var borderWidth: CGFloat /// returns height of the Text Field image /// public var textImageHeight: CGFloat /// X padding for Text Field /// public var textPaddingX: CGFloat /// Bar tin color /// public var barTintColor: UIColor /// View background color /// public var primaryBackgroundColor: UIColor /// Background color for all subviews like TextFields /// public var secondaryBackgroundColor: UIColor /// Text color for any text field in a view /// public var primaryForegroundColor: UIColor /// Text color for any text field in a view when is active/focused /// public var primaryActiveForegroundColor: UIColor /// Border color for any text field in a view /// public var secondaryForegroundColor: UIColor /// Border color for any text field in a view when is active/focused /// public var secondaryActiveForegroundColor: UIColor /// Text and Border color for any text field in case of error /// public var errorForegroundColor: UIColor /// Text and Border color for any text field in case of error when is active/focused /// public var errorActiveForegroundColor: UIColor /// Color used in all the important ui elements like buttons /// public var highlightColor: UIColor /// Color used in all the important ui elements like buttons when disabled /// public var highlightDisableColor: UIColor /// If true show automatically the keyboard with focus in the first text field /// public var showKeyboard: Bool /// Font used for all the bold text in the views /// public var emphasisFont: UIFont /// Font used in the views /// public var font: UIFont /// Expiry date picker enabled /// public var expiryDatePicker: Bool public init() { placeholderAnimationDuration = defaultPlaceholderAnimationDuration borderRadius = defaultRoundedBorderRadius placeholderFontScale = defaultPlaceholderFontScale borderWidth = defaultBorderWidth textImageHeight = defaultTextImageHeight textPaddingX = defaultTextPaddingX barTintColor = defaultBarTintColor primaryBackgroundColor = defaultBackgroundColor secondaryBackgroundColor = defaultBackgroundColor primaryForegroundColor = defaultPrimaryForegroundColor primaryActiveForegroundColor = defaultPrimaryActiveForegroundColor secondaryForegroundColor = defaultSecondaryForegroundColor secondaryActiveForegroundColor = defaultSecondaryActiveForegroundColor errorForegroundColor = defaultErrorForegroundColor errorActiveForegroundColor = defaultErrorActiveForegroundColor highlightColor = defaultHighlightColor highlightDisableColor = defaultHighlightDisableColor showKeyboard = defaultShowKeyboard emphasisFont = UIFont.systemFont(ofSize: defaultFontSize+1, weight: .bold) font = UIFont.systemFont(ofSize: defaultFontSize, weight: .regular) expiryDatePicker = defaultExpiryDatePicker } open func textImageView(textFieldType: TextFieldType, cardBrand: CardBrand? = nil) -> UIView? { let iconImageView = UIImageView(frame: CGRect.zero) iconImageView.image = UIImage(named: textFieldType.iconId(cardBrand: cardBrand), in: Bundle(for: type(of: self)), compatibleWith: nil) iconImageView.frame = CGRect(x: 0, y: 0, width: textImageHeight, height: textImageHeight) iconImageView.contentMode = .scaleAspectFit return iconImageView } }
e3ab27f18c8d2fdf120ce1605d372f6b
35.647436
106
0.714361
false
false
false
false
Novkirishki/JustNinja
refs/heads/master
Just Ninja/Just Ninja/Ninja.swift
mit
1
// // Ninja.swift // Just Ninja // // Created by Nikolai Novkirishki on 1/31/16. // Copyright © 2016 Nikolai Novkirishki. All rights reserved. // import Foundation import SpriteKit class Ninja: SKSpriteNode { var body: SKSpriteNode! var arm: SKSpriteNode! var leftFoot: SKSpriteNode! var rightFoot: SKSpriteNode! var face: SKSpriteNode! var isFlippedDown = false init() { let ninjaSize = CGSizeMake(NINJA_WIDTH, NINJA_HEIGHT) super.init(texture: nil, color: UIColor.clearColor(), size: ninjaSize) drawNinjaAppearance() loadPhysicsBodyWithSize(ninjaSize) } func drawNinjaAppearance() { body = SKSpriteNode(color: UIColor.blackColor(), size: CGSizeMake(self.frame.size.width, 40)) body.position = CGPointMake(0, 2) addChild(body) let skinColor = UIColor(red: 207.0/255.0, green: 193.0/255.0, blue: 168.0/255.0, alpha: 1.0) face = SKSpriteNode(color: skinColor, size: CGSizeMake(self.frame.size.width, 12)) face.position = CGPointMake(0, 6) body.addChild(face) let eyeColor = UIColor.whiteColor() let leftEye = SKSpriteNode(color: eyeColor, size: CGSizeMake(6, 6)) let rightEye = leftEye.copy() as! SKSpriteNode let pupil = SKSpriteNode(color: UIColor.blackColor(), size: CGSizeMake(3, 3)) pupil.position = CGPointMake(2, 0) leftEye.addChild(pupil) rightEye.addChild(pupil.copy() as! SKSpriteNode) leftEye.position = CGPointMake(-4, 0) face.addChild(leftEye) rightEye.position = CGPointMake(14, 0) face.addChild(rightEye) let eyebrow = SKSpriteNode(color: UIColor.blackColor(), size: CGSizeMake(11, 1)) eyebrow.position = CGPointMake(-1, leftEye.size.height/2) leftEye.addChild(eyebrow) rightEye.addChild(eyebrow.copy()as! SKSpriteNode) let armColor = UIColor(red: 46/255, green: 46/255, blue: 46/255, alpha: 1.0) arm = SKSpriteNode(color: armColor, size: CGSizeMake(8, 14)) arm.anchorPoint = CGPointMake(0.5, 0.9) arm.position = CGPointMake(-10, -7) body.addChild(arm) let hand = SKSpriteNode(color: skinColor, size: CGSizeMake(arm.size.width, 5)) hand.position = CGPointMake(0, -arm.size.height*0.9 + hand.size.height/2) arm.addChild(hand) leftFoot = SKSpriteNode(color: UIColor.blackColor(), size: CGSizeMake(9, 4)) leftFoot.position = CGPointMake(-6, -size.height/2 + leftFoot.size.height/2) addChild(leftFoot) rightFoot = leftFoot.copy() as! SKSpriteNode rightFoot.position.x = 8 addChild(rightFoot) } func loadPhysicsBodyWithSize(size: CGSize) { physicsBody = SKPhysicsBody(rectangleOfSize: size) physicsBody?.categoryBitMask = NINJA_CATEGORY physicsBody?.contactTestBitMask = WALL_CATEGORY physicsBody?.affectedByGravity = false } func flip() { isFlippedDown = !isFlippedDown var scale: CGFloat! if isFlippedDown { scale = -1.0 } else { scale = 1.0 } let translate = SKAction.moveByX(0, y: scale*(size.height + GROUND_HEIGHT), duration: 0.1) let flip = SKAction.scaleYTo(scale, duration: 0.1) runAction(translate) runAction(flip) } func fall() { physicsBody?.affectedByGravity = true physicsBody?.applyImpulse(CGVectorMake(-5, 30)) let rotateBack = SKAction.rotateByAngle(CGFloat(M_PI) / 2, duration: 0.4) runAction(rotateBack) } func startRunning() { let rotateBack = SKAction.rotateByAngle(-CGFloat(M_PI)/2.0, duration: 0.1) arm.runAction(rotateBack) run() } func run() { let up = SKAction.moveByX(0, y: 2, duration: 0.05) let down = SKAction.moveByX(0, y: -2, duration: 0.05) leftFoot.runAction(up, completion: { () -> Void in self.leftFoot.runAction(down) self.rightFoot.runAction(up, completion: { () -> Void in self.rightFoot.runAction(down, completion: { () -> Void in self.run() }) }) }) } func breathe() { let breatheOut = SKAction.moveByX(0, y: -2, duration: 1) let breatheIn = SKAction.moveByX(0, y: 2, duration: 1) let breath = SKAction.sequence([breatheOut, breatheIn]) body.runAction(SKAction.repeatActionForever(breath)) } func stop() { body.removeAllActions() leftFoot.removeAllActions() rightFoot.removeAllActions() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
e7cf4102ab8342d7c1bd12777aa915fc
32.598639
101
0.600446
false
false
false
false
VArbiter/Rainville_iOS-Swift
refs/heads/master
Rainville-Swift/Rainville-Swift/Classes/Category/CCViewExtension.swift
gpl-3.0
1
// // CCViewExtension.swift // Rainville-Swift // // Created by 冯明庆 on 01/06/2017. // Copyright © 2017 冯明庆. All rights reserved. // import Foundation import UIKit extension UIView { var x : Double { set { var frame : CGRect = self.frame; frame.origin.x = CGFloat(x); self.frame = frame; } get { return Double(self.frame.origin.x) ; } } var y : Double { set { var frame : CGRect = self.frame; frame.origin.y = CGFloat(y); self.frame = frame; } get { return Double(self.frame.origin.y); } } var width : Double { set { var frame : CGRect = self.frame; frame.size.width = CGFloat(width); self.frame = frame; } get { return Double(self.frame.size.width); } } var height : Double { set { var frame : CGRect = self.frame; frame.size.height = CGFloat(height); self.frame = frame; } get { return Double(self.frame.size.height); } } var origin : CGPoint { set { var frame : CGRect = self.frame; frame.origin = origin; self.frame = frame; } get { return self.frame.origin; } } var size : CGSize { set { var frame : CGRect = self.frame; frame.size = size; self.frame = frame; } get { return self.frame.size; } } var left : Double { set { var frame : CGRect = self.frame; frame.origin.x = CGFloat(left); self.frame = frame; } get { return Double(self.frame.origin.x); } } var right : Double { set { var frame : CGRect = self.frame; frame.origin.x = CGFloat(right) - frame.size.width; self.frame = frame; } get { return Double(self.frame.origin.x + self.frame.size.width); } } var top : Double { set { var frame : CGRect = self.frame; frame.origin.y = CGFloat(top); self.frame = frame; } get { return Double(self.frame.origin.y); } } var bottom : Double { set { var frame : CGRect = self.frame; frame.origin.y = CGFloat(bottom) - frame.size.height; self.frame = frame; } get { return Double(self.frame.origin.y + self.frame.size.height); } } }
11802baa87e172ca656c9f2a395d4be5
21.346774
72
0.449657
false
false
false
false
ilhanadiyaman/firefox-ios
refs/heads/master
Client/Frontend/Browser/ReaderModeBarView.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import SnapKit enum ReaderModeBarButtonType { case MarkAsRead, MarkAsUnread, Settings, AddToReadingList, RemoveFromReadingList private var localizedDescription: String { switch self { case .MarkAsRead: return NSLocalizedString("Mark as Read", comment: "Name for Mark as read button in reader mode") case .MarkAsUnread: return NSLocalizedString("Mark as Unread", comment: "Name for Mark as unread button in reader mode") case .Settings: return NSLocalizedString("Display Settings", comment: "Name for display settings button in reader mode. Display in the meaning of presentation, not monitor.") case .AddToReadingList: return NSLocalizedString("Add to Reading List", comment: "Name for button adding current article to reading list in reader mode") case .RemoveFromReadingList: return NSLocalizedString("Remove from Reading List", comment: "Name for button removing current article from reading list in reader mode") } } private var imageName: String { switch self { case .MarkAsRead: return "MarkAsRead" case .MarkAsUnread: return "MarkAsUnread" case .Settings: return "SettingsSerif" case .AddToReadingList: return "addToReadingList" case .RemoveFromReadingList: return "removeFromReadingList" } } private var image: UIImage? { let image = UIImage(named: imageName) image?.accessibilityLabel = localizedDescription return image } } protocol ReaderModeBarViewDelegate { func readerModeBar(readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) } class ReaderModeBarView: UIView { var delegate: ReaderModeBarViewDelegate? var readStatusButton: UIButton! var settingsButton: UIButton! var listStatusButton: UIButton! dynamic var buttonTintColor: UIColor = UIColor.clearColor() { didSet { readStatusButton.tintColor = self.buttonTintColor settingsButton.tintColor = self.buttonTintColor listStatusButton.tintColor = self.buttonTintColor } } override init(frame: CGRect) { super.init(frame: frame) readStatusButton = createButton(type: .MarkAsRead, action: "SELtappedReadStatusButton:") readStatusButton.snp_makeConstraints { (make) -> () in make.left.equalTo(self) make.height.centerY.equalTo(self) make.width.equalTo(80) } settingsButton = createButton(type: .Settings, action: "SELtappedSettingsButton:") settingsButton.snp_makeConstraints { (make) -> () in make.height.centerX.centerY.equalTo(self) make.width.equalTo(80) } listStatusButton = createButton(type: .AddToReadingList, action: "SELtappedListStatusButton:") listStatusButton.snp_makeConstraints { (make) -> () in make.right.equalTo(self) make.height.centerY.equalTo(self) make.width.equalTo(80) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { super.drawRect(rect) let context = UIGraphicsGetCurrentContext() CGContextSetLineWidth(context, 0.5) CGContextSetRGBStrokeColor(context, 0.1, 0.1, 0.1, 1.0) CGContextSetStrokeColorWithColor(context, UIColor.grayColor().CGColor) CGContextBeginPath(context) CGContextMoveToPoint(context, 0, frame.height) CGContextAddLineToPoint(context, frame.width, frame.height) CGContextStrokePath(context) } private func createButton(type type: ReaderModeBarButtonType, action: Selector) -> UIButton { let button = UIButton() addSubview(button) button.setImage(type.image, forState: .Normal) button.addTarget(self, action: action, forControlEvents: .TouchUpInside) return button } func SELtappedReadStatusButton(sender: UIButton!) { delegate?.readerModeBar(self, didSelectButton: unread ? .MarkAsRead : .MarkAsUnread) } func SELtappedSettingsButton(sender: UIButton!) { delegate?.readerModeBar(self, didSelectButton: .Settings) } func SELtappedListStatusButton(sender: UIButton!) { delegate?.readerModeBar(self, didSelectButton: added ? .RemoveFromReadingList : .AddToReadingList) } private func updateUnread(unread: Bool) { var buttonType: ReaderModeBarButtonType = unread ? .MarkAsRead : .MarkAsUnread if !added { buttonType = .MarkAsUnread } readStatusButton.setImage(buttonType.image, forState: UIControlState.Normal) readStatusButton.enabled = added readStatusButton.alpha = added ? 1.0 : 0.6 } var unread: Bool = true { didSet { updateUnread(unread) } } private func updateAdded(added: Bool) { let buttonType: ReaderModeBarButtonType = added ? .RemoveFromReadingList : .AddToReadingList listStatusButton.setImage(buttonType.image, forState: UIControlState.Normal) } var added: Bool = false { didSet { updateAdded(added) updateUnread(unread) } } } extension ReaderModeBarView: Themeable { func forceApplyTheme() { backgroundColor = ReaderModeBarView.appearance().backgroundColor buttonTintColor = ReaderModeBarView.appearance().buttonTintColor } }
89699e1eae0c923fff1c5e37d04dd82e
36.568627
182
0.683661
false
false
false
false
stefanilie/swift-playground
refs/heads/master
Swift3 and iOS10/Playgrounds/Strings.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit var str: String = "Hello, playground" var firstName = "Jack" var secondName = "Bauer" var age = 45 var fullName = firstName + " " + secondName var fullName2 = "\(firstName) \(secondName) is \(age)" fullName.append(" III") var bookTitle = "revenge of the crab cakes" bookTitle = bookTitle.capitalized var chatroomAnnoyingGuy = "PLEASE HELP ME NOW" var lowercasedChat = chatroomAnnoyingGuy.lowercased() var sentence = "What the Fuck!!? Shit this is crazy!" if sentence.contains("Fuck") || sentence.contains("Shit") { sentence.replacingOccurrences(of: "Fuck", with: "f***") sentence.replacingOccurrences(of: "Shit", with: "S***") }
bec745e1f484d114963e6dc5ecf740e6
26.346154
59
0.708451
false
false
false
false
coderMONSTER/iosstar
refs/heads/master
iOSStar/AppAPI/SocketAPI/SocketReqeust/SocketResponse.swift
gpl-3.0
1
// // SocketResponse.swift // viossvc // // Created by yaowang on 2016/11/25. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit class SocketResponse { fileprivate var body:SocketDataPacket? var statusCode:Int { get { return Int(body!.operate_code) } } func responseData() -> Data? { return body?.data as Data? } init(packet:SocketDataPacket) { body = packet; } } class SocketJsonResponse: SocketResponse { private var _jsonOjbect:AnyObject?; override var statusCode: Int { get{ let dict:NSDictionary? = responseJsonObject() as? NSDictionary var errorCode: Int = 0; if ( dict == nil ) { errorCode = -11012; //json解析失败 } else if( dict != nil && dict?["result"] != nil ) { errorCode = dict?["result"] as! Int; } else { errorCode = 0; } return errorCode; } } func responseJsonObject() -> AnyObject? { if body?.data?.count == 0 { return nil } if _jsonOjbect == nil { do{ #if false var json = String(data: body!.data!, encoding: .utf8) json = json == nil ? "" : json; // debugPrint("\(body!.operate_code) \(body!.data_length) json\(json!)") #endif _jsonOjbect = try JSONSerialization.jsonObject(with: body!.data!, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject? }catch let error as Error! { var json = String(data: body!.data!, encoding: .utf8) json = json == nil ? "" : json; debugPrint("解析json\(json!) \(error) ") } } return _jsonOjbect } func responseJson<T:NSObject>() ->T? { var object = responseJsonObject() if object != nil && !(T.isKind(of: NSDictionary.self)) && T.isKind(of: NSObject.self) { object = responseModel(T.classForCoder()) } return object as? T } func responseModel(_ modelClass: AnyClass) ->AnyObject?{ let object = responseJsonObject() if object != nil { return try! OEZJsonModelAdapter.model(of: modelClass, fromJSONDictionary: object as! [AnyHashable: Any]) as AnyObject? } return nil } func responseModels(_ modelClass: AnyClass) ->[AnyObject]? { let array:[AnyObject]? = responseJsonObject() as? [AnyObject] if array != nil { return try! OEZJsonModelAdapter.models(of: modelClass, fromJSONArray: nil) as [AnyObject]? } return nil; } func responseResult() -> Int? { let dict = responseJsonObject() as? [String:AnyObject] if dict != nil && dict!["result_"] != nil { return dict!["result_"] as? Int; } return nil; } }
f641acd926125dd0c41cab4b23c5ee39
28.428571
156
0.519094
false
false
false
false
genadyo/WWDC
refs/heads/master
WWDC/PartyTableViewController.swift
mit
2
// // PartyTableViewController.swift // SFParties // // Created by Genady Okrain on 4/28/16. // Copyright © 2016 Okrain. All rights reserved. // import UIKit import MapKit import SafariServices import Contacts import EventKitUI import Crashlytics import StoreKit protocol PartyTableViewControllerDelegate { func reloadData() } class PartyTableViewController: UITableViewController, SFSafariViewControllerDelegate, EKEventEditViewDelegate { var party: Party! var delegate: PartyTableViewControllerDelegate? @IBOutlet weak var goingButton: UIButton! @IBOutlet weak var logoImageView: UIImageView! { didSet { logoImageView.pin_setImage(from: party.logo) } } @IBOutlet weak var titleLabel: UILabel! { didSet { titleLabel.text = party.title } } @IBOutlet weak var detailsLabel: UILabel! { didSet { let font = UIFont.systemFont(ofSize: 15.0, weight: .light) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = 20.0 paragraphStyle.maximumLineHeight = 20.0 paragraphStyle.minimumLineHeight = 20.0 let color = UIColor(red: 146.0/255.0, green: 146.0/255.0, blue: 146.0/255.0, alpha: 1.0) let attributedDetails = NSMutableAttributedString(string: party.details, attributes: [NSAttributedStringKey.font: font, NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.foregroundColor: color]) detailsLabel.attributedText = attributedDetails; } } @IBOutlet weak var dateLabel: UILabel! { didSet { dateLabel.text = party.date } } @IBOutlet weak var hoursLabel: UILabel! { didSet { hoursLabel.text = party.hours } } @IBOutlet weak var mapView: MKMapView! { didSet { var region = MKCoordinateRegion() region.center.latitude = party.latitude region.center.longitude = party.longitude region.span.latitudeDelta = 0.0075 region.span.longitudeDelta = 0.0075 mapView.setRegion(region, animated: false) let annotation = MKPointAnnotation() annotation.coordinate = CLLocationCoordinate2DMake(party.latitude, party.longitude) mapView.addAnnotation(annotation) } } @IBOutlet weak var address1Label: UILabel! { didSet { address1Label.text = party.address1 } } @IBOutlet weak var address2Label: UILabel! { didSet { address2Label.text = party.address2 } } @IBOutlet weak var address3Label: UILabel! { didSet { address3Label.text = party.address3 } } override func viewDidLoad() { super.viewDidLoad() // Going/Old goingButton.isSelected = party.isGoing party.isOld = true delegate?.reloadData() // Self sizing cells tableView.estimatedRowHeight = 100.0 tableView.rowHeight = UITableViewAutomaticDimension if let buildString = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String, let build = Int(buildString), build > UserDefaults.standard.integer(forKey: "lastReviewBuild") { UserDefaults.standard.set(build, forKey: "lastReviewBuild") SKStoreReviewController.requestReview() } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) if indexPath.row == 6 { // Xcode Bug #2 cell.backgroundColor = UIColor(red: 106.0/255.0, green: 118.0/255.0, blue: 220.0/255.0, alpha: 1.0) } return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } @IBAction func updateGoing(_ sender: UIButton) { party.isGoing = !party.isGoing goingButton.isSelected = party.isGoing delegate?.reloadData() } @IBAction func openMaps(_ sender: AnyObject) { let coordinate = CLLocationCoordinate2DMake(party.latitude, party.longitude) var addressDictionary = [String: AnyObject]() addressDictionary[CNPostalAddressCountryKey] = "United States" as AnyObject addressDictionary[CNPostalAddressStreetKey] = party.address2 as AnyObject let address3Split = party.address3.components(separatedBy: ", ") if address3Split.count == 2 { addressDictionary[CNPostalAddressCityKey] = address3Split[0] as AnyObject let address3SplitSplit = address3Split[1].components(separatedBy: " ") if address3SplitSplit.count == 2 { addressDictionary[CNPostalAddressStateKey] = address3SplitSplit[0] as AnyObject addressDictionary[CNPostalAddressPostalCodeKey] = address3SplitSplit[1] as AnyObject } } let item = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary: addressDictionary)) item.name = party.title item.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeWalking, MKLaunchOptionsMapTypeKey: MKMapType.standard.rawValue]) } @IBAction func openWeb(_ sender: AnyObject) { let safariViewController = SFSafariViewController(url: party.url) safariViewController.delegate = self present(safariViewController, animated: true, completion: nil) } @IBAction func openCal(_ sender: UITapGestureRecognizer) { let eventStore = EKEventStore() let authorizationStatus = EKEventStore.authorizationStatus(for: .event) let needsToRequestAccessToEventStore = authorizationStatus == .notDetermined if needsToRequestAccessToEventStore == true { eventStore.requestAccess(to: .event) { [weak self] granted, error in if granted == true { self?.addEvent() } else if let url = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } } else { let granted = authorizationStatus == .authorized if granted == true { addEvent() } else if let url = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } } func addEvent() { let eventStore = EKEventStore() let event = EKEvent(eventStore: eventStore) // Event event.title = party.title event.startDate = party.startDate event.endDate = party.endDate event.location = "\(party.address1) \(party.address2) \(party.address3)" event.url = party.url event.notes = party.details // addController let addController = EKEventEditViewController() addController.eventStore = eventStore addController.event = event addController.editViewDelegate = self present(addController, animated: true, completion: nil) } // MARK: SFSafariViewControllerDelegate func safariViewControllerDidFinish(_ controller: SFSafariViewController) { controller.dismiss(animated: true, completion: nil) } // MARK: EKEventEditViewDelegate func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) { switch action { case .saved: do { if let event = controller.event { try controller.eventStore.save(event, span: .thisEvent) } } catch { } break; default: break; } controller.dismiss(animated: true, completion: nil) } }
aaaba077081ef136800fe53466123524
35.071429
232
0.64604
false
false
false
false
HarveyHu/TicTacToe-in-Swift
refs/heads/master
TicTacToe/Chessboard.swift
mit
1
// // Chessboard.swift // TicTacToe // // Created by HarveyHu on 7/30/15. // Copyright (c) 2015 HarveyHu. All rights reserved. // import Foundation protocol ChessboardDelegate { func show(chessboard: Array<Chessboard.Status>) func onGameOver(winner: Chessboard.Status) } class Chessboard: NSCopying { static let sharedInstance = Chessboard() enum Status: Int { case Empty = 0 case Nought = 1 case Cross = 2 } var chessboardDelegate: ChessboardDelegate? var firstHand: Status = Status.Nought private var _currentBoard = Array<Status>(count: 9, repeatedValue: Status.Empty) private let _lineSets: Set<Set<Int>> = [[0, 4, 8], [2, 4, 6], [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8]] func copy() -> AnyObject! { if let asCopying = ((self as AnyObject) as? NSCopying) { return asCopying.copyWithZone(nil) } else { assert(false, "This class doesn't implement NSCopying") return nil } } @objc func copyWithZone(zone: NSZone) -> AnyObject { let newValue = Chessboard() newValue._currentBoard = _currentBoard newValue.firstHand = firstHand return newValue } func chess(position: Int, status: Status, isShow: Bool = false) -> Bool { if position < 9 && _currentBoard[position] == Status.Empty { _currentBoard[position] = status if isShow { dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in if let strongSelf = self { strongSelf.chessboardDelegate?.show(strongSelf._currentBoard) if strongSelf.checkGameOver() { strongSelf.chessboardDelegate?.onGameOver(strongSelf.checkWin()) } } } } return true } return false } func chessShow(position: Int, status: Status) -> Bool { return chess(position, status: status, isShow: true) } func generateLegalMoves() -> [Int]? { var legalMoves = Array<Int>() for position in 0 ..< 9 { if _currentBoard[position] == Status.Empty { legalMoves.append(position) } } if legalMoves.count > 0 { return legalMoves } return nil } func newGame() { _currentBoard.removeAll() _currentBoard = Array<Status>(count: 9, repeatedValue: Status.Empty) chessboardDelegate?.show(_currentBoard) } func checkWin() -> Status { var noughtSet = Set<Int>() var crossSet = Set<Int>() for index in 0 ..< _currentBoard.count { switch _currentBoard[index] { case Status.Nought: noughtSet.insert(index) break case Status.Cross: crossSet.insert(index) break default: break } } for lineSet in _lineSets { if lineSet.isSubsetOf(noughtSet) { return Status.Nought } else if lineSet.isSubsetOf(crossSet) { return Status.Cross } } //not end yet return Status.Empty } func checkGameOver() -> Bool { var isFull = true for index in 0 ..< _currentBoard.count { if _currentBoard[index] == Status.Empty { isFull = false break } } if checkWin() == Status.Empty && !isFull { return false } return true } }
3a914bcc7de498c47ea6a8d623e181dc
28.492188
131
0.520933
false
false
false
false
petrone/PetroneAPI_swift
refs/heads/master
PetroneAPI/Petrone.swift
mit
1
// // Petrone.swift // Petrone // // Created by Byrobot on 2017. 7. 20.. // Copyright © 2017년 Byrobot. All rights reserved. // import Foundation public class Petrone { public static let instance:Petrone = Petrone() weak open var delegate: PetroneProtocol? public var petroneList : [String:PetroneScanData] = [:] private var prevControlTime: Int64 = 0 private var controller:PetroneController? private var petroneBLE: PetroneBLE? private var petroneWIFI: PetroneWIFI? private var sendInterval:TimeInterval = 1.0 / 20 // send packet max 20fps private var timer: Timer? = nil private var packetList : Array<PetronePacket> = Array<PetronePacket>() private struct PetroneControlValue { public var throttle: Int8 = 0 public var throttleTimer: Int = 0 public var yaw: Int8 = 0 public var yawTimer: Int = 0 public var roll: Int8 = 0 public var rollTimer: Int = 0 public var pitch: Int8 = 0 public var pitchTimer: Int = 0 } private var controlValue : PetroneControlValue = PetroneControlValue() public var status:PetroneStatus? = nil public var trim:PetroneTrim? = nil public var attitude:PetroneAttitude? = nil public var gyro:PetroneGyroBias? = nil public var countOfFlight:PetroneCountFlight? = nil public var countOfDrive:PetroneCountDrive? = nil public var imuRawAndAngle:PetroneImuRawAndAngle? = nil public var pressure:PetronePressure? = nil public var imageFlow:PetroneImageFlow? = nil public var motor:PetroneMotor? = nil public var range:PetroneRange? = nil public var isPairing: Bool = false func pairing(status:Bool, reason:String = "" ) { isPairing = status; if isPairing { if (petroneBLE?.connected)! { controller = petroneBLE self.sendInterval = 1.0 / 20 } else if (petroneWIFI?.connected)! { controller = petroneWIFI self.sendInterval = 1.0 / 40 } if timer == nil { prevControlTime = getCurrentMillis() timer = Timer.scheduledTimer(timeInterval: self.sendInterval, target: self, selector:(#selector(onSend)), userInfo: nil, repeats: true) } if (petroneBLE?.connected)! { self.delegate?.petrone(controller!, didConnect: (petroneBLE?.discoveredPeripheral?.name)!) } else if (petroneWIFI?.connected)! { self.delegate?.petrone(controller!, didConnect: "PETRONE FPV") } } else { controller = nil if timer != nil { timer?.invalidate() } self.delegate?.petrone(reason) } } public func isReadyForStart() -> Bool { if (status?.mode.rawValue)! < PetroneMode.Drive.rawValue { if( status?.modeFlight == PetroneModeFlight.Ready ) { return true } else { return false } } else { if( status?.modeDrive == PetroneModeDrive.Ready ) { return true } else { return false } } } public func onScan() { if petroneBLE == nil { petroneBLE = PetroneBLE() } if !(petroneBLE?.isScanning())! { petroneBLE?.onScan() } if petroneWIFI == nil { petroneWIFI = PetroneWIFI() } petroneWIFI?.onScan() } public func onStopScan() { if petroneBLE != nil { petroneBLE?.onStopScan() petroneList.removeAll() } if petroneBLE != nil { petroneWIFI?.onStopScan() petroneList.removeAll() } } public func onConnect(_ target:String) { if target.contains("FPV") { petroneWIFI?.onConnect("FPV") petroneBLE?.onStopScan() } else { petroneBLE?.onConnect(target) petroneWIFI?.onStopScan() } petroneList.removeAll() } public func onDisconnect() { petroneBLE?.onDisConnect() petroneWIFI?.onDisConnect() } public func takeOff() { let packet:PetronePacketTakeOff = PetronePacketTakeOff() self.sendPacket(packet) } public func landing() { let packet:PetronePacketLanding = PetronePacketLanding() self.sendPacket(packet) } public func emergencyStop() { let packet:PetronePacketEmergencyStop = PetronePacketEmergencyStop() self.sendPacket(packet) } public func onSqure() { let packet:PetronePacketSquare = PetronePacketSquare() self.sendPacket(packet) } public func onRotate180() { let packet:PetronePacketRotate180 = PetronePacketRotate180() self.sendPacket(packet) } public func onRotate90Left() { let packet:PetronePacketRotate90 = PetronePacketRotate90() self.sendPacket(packet) } public func onRotate90Right() { let packet:PetronePacketRotate90 = PetronePacketRotate90() self.sendPacket(packet) } public func throttle(value:Int8, millisecond:Int = 100) { controlValue.throttle = value controlValue.throttleTimer = millisecond } public func yaw(value:Int8, millisecond:Int = 100) { controlValue.yaw = value controlValue.yawTimer = millisecond } public func roll(value:Int8, millisecond:Int = 100) { controlValue.roll = value controlValue.rollTimer = millisecond } public func pitch(value:Int8, millisecond:Int = 100) { controlValue.pitch = value controlValue.pitchTimer = millisecond } public func control(forward:Int8, leftRight:Int8, millisecond:Int = 100) { controlValue.throttle = forward controlValue.throttleTimer = millisecond controlValue.yaw = 0 controlValue.yawTimer = 0 controlValue.roll = leftRight controlValue.rollTimer = millisecond controlValue.pitch = 0 controlValue.pitchTimer = 0 } public func control(throttle:Int8, yaw:Int8, roll:Int8, pitch:Int8, millisecond:Int = 100) { controlValue.throttle = throttle controlValue.throttleTimer = millisecond controlValue.yaw = yaw controlValue.yawTimer = millisecond controlValue.roll = roll controlValue.rollTimer = millisecond controlValue.pitch = pitch controlValue.pitchTimer = millisecond } public func changeMode(mode:PetroneMode) { let packet:PetronePacketModeChange = PetronePacketModeChange() packet.mode = mode self.sendPacket(packet) } public func changeTrim(throttle:Int16, yaw:Int16, roll:Int16, pitch:Int16, wheel:Int16) { let packet:PetronePacketChangeTrim = PetronePacketChangeTrim() packet.flight.throttle = throttle packet.flight.yaw = yaw packet.flight.roll = roll packet.flight.pitch = pitch packet.drive.wheel = wheel self.sendPacket(packet) } public func changeTrim(throttle:Int16, yaw:Int16, roll:Int16, pitch:Int16) { let packet:PetronePacketChangeTrim = PetronePacketChangeTrim() packet.flight.throttle = throttle packet.flight.yaw = yaw packet.flight.roll = roll packet.flight.pitch = pitch packet.drive.wheel = (self.trim?.drive.wheel)! self.sendPacket(packet) } public func changeTrim(wheel:Int16) { let packet:PetronePacketChangeTrim = PetronePacketChangeTrim() packet.drive.wheel = wheel packet.flight.throttle = (self.trim?.flight.throttle)! packet.flight.yaw = (self.trim?.flight.yaw)! packet.flight.roll = (self.trim?.flight.roll)! packet.flight.pitch = (self.trim?.flight.pitch)! self.sendPacket(packet) } public func color(red:UInt8, green:UInt8, blue:UInt8) { let packet:PetronePacketLedColor2 = PetronePacketLedColor2() packet.led1.mode = PetroneLigthMode.EyeHold.rawValue packet.led1.red = red packet.led1.green = green packet.led1.blue = blue packet.led1.interval = 255 packet.led2.mode = PetroneLigthMode.ArmHold.rawValue packet.led2.red = red packet.led2.green = green packet.led2.blue = blue packet.led2.interval = 255 self.sendPacket(packet) } public func color(eyeRed:UInt8, eyeGreen:UInt8, eyeBlue:UInt8, armRed:UInt8, armGreen:UInt8, armBlue:UInt8) { let packet:PetronePacketLedColor2 = PetronePacketLedColor2() packet.led1.mode = PetroneLigthMode.EyeHold.rawValue packet.led1.red = eyeRed packet.led1.green = eyeGreen packet.led1.blue = eyeBlue packet.led1.interval = 255 packet.led2.mode = PetroneLigthMode.ArmHold.rawValue packet.led2.red = armRed packet.led2.green = armGreen packet.led2.blue = armBlue packet.led2.interval = 255 self.sendPacket(packet) } public func colorForEye(red:UInt8, green:UInt8, blue:UInt8) { let packet:PetronePacketLedColor = PetronePacketLedColor() packet.led.mode = PetroneLigthMode.EyeHold.rawValue packet.led.red = red packet.led.green = green packet.led.blue = blue packet.led.interval = 255 self.sendPacket(packet) } public func colorForArm(red:UInt8, green:UInt8, blue:UInt8) { let packet:PetronePacketLedColor = PetronePacketLedColor() packet.led.mode = PetroneLigthMode.ArmHold.rawValue packet.led.red = red packet.led.green = green packet.led.blue = blue packet.led.interval = 255 self.sendPacket(packet) } // Flight mode only public func turn() { } // Drive mode only public func turnLeft() { } // Drive mode only public func turnRight() { } public func requestState() { let packet:PetronePacketStatus = PetronePacketStatus() self.sendPacket(packet) } public func requestAttitude() { let packet:PetronePacketAttitude = PetronePacketAttitude() self.sendPacket(packet) } public func requestGyroBias() { let packet:PetronePacketGyroBias = PetronePacketGyroBias() self.sendPacket(packet) } public func requestTrimAll() { let packet:PetronePacketRequestTrimAll = PetronePacketRequestTrimAll() self.sendPacket(packet) } public func requestTrimFlight() { let packet:PetronePacketRequestTrimFlight = PetronePacketRequestTrimFlight() self.sendPacket(packet) } public func requestTrimDrive() { let packet:PetronePacketRequestTrimDrive = PetronePacketRequestTrimDrive() self.sendPacket(packet) } public func requestCountFlight() { let packet:PetronePacketCountFlight = PetronePacketCountFlight() self.sendPacket(packet) } public func requestCountDrive() { let packet:PetronePacketCountDrive = PetronePacketCountDrive() self.sendPacket(packet) } public func requestImuRawAndAngle() { let packet:PetronePacketImuRawAndAngle = PetronePacketImuRawAndAngle() self.sendPacket(packet) } public func requestPressure() { let packet:PetronePacketPressure = PetronePacketPressure() self.sendPacket(packet) } public func requestImageFlow() { let packet:PetronePacketImageFlow = PetronePacketImageFlow() self.sendPacket(packet) } public func requestBattery() { let packet:PetronePacketBattery = PetronePacketBattery() self.sendPacket(packet) } public func requestMotor() { let packet:PetronePacketMotor = PetronePacketMotor() self.sendPacket(packet) } public func requestTemperature() { let packet:PetronePacketTemperature = PetronePacketTemperature() self.sendPacket(packet) } public func requestRange() { let packet:PetronePacketRange = PetronePacketRange() self.sendPacket(packet) } public func appearPetrone(name:String, uuid:String, rssi RSSI: NSNumber, isFPV:Bool = false) { if petroneList[uuid] != nil { var prev = petroneList[uuid] prev?.rssi = RSSI petroneList.updateValue(prev!, forKey: uuid) } else { let data: PetroneScanData = PetroneScanData(name:name, uuid:uuid, rssi:RSSI) petroneList[uuid] = data } } public func updatePetrone(uuid:String, rssi RSSI: NSNumber, isFPV:Bool = false) { if petroneList[uuid] != nil { var prev = petroneList[uuid] prev?.rssi = RSSI petroneList.updateValue(prev!, forKey: uuid) } } public func sendPacket(_ packet:PetronePacket) { packetList.insert(packet, at: packetList.count) } /*! * @method recvPacket: * * @param data recved data ( [UInt8] ) */ public func recvPacket(data:Data) { switch ( data[0] as UInt8 ){ case PetroneDataType.Ack.rawValue: self.delegate?.petrone(controller!, recvFromPetrone: data[5]) case PetroneDataType.State.rawValue: if self.status == nil { self.status = PetroneStatus() } self.status?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.status!) case PetroneDataType.Attitude.rawValue: if self.attitude == nil { self.attitude = PetroneAttitude() } self.attitude?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.attitude!) case PetroneDataType.GyroBias.rawValue: if self.gyro == nil { self.gyro = PetroneGyroBias() } self.gyro?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.gyro!) case PetroneDataType.TrimAll.rawValue: if self.trim == nil { self.trim = PetroneTrim() } self.trim?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.trim!) case PetroneDataType.TrimFlight.rawValue: if self.trim == nil { self.trim = PetroneTrim() } self.trim?.flight.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: (self.trim?.flight)!) case PetroneDataType.TrimDrive.rawValue: if self.trim == nil { self.trim = PetroneTrim() } self.trim?.drive.parse(data) self.delegate?.petrone(controller!, recvFromPetrone: (self.trim?.drive)!) case PetroneDataType.CountFlight.rawValue: if self.countOfFlight == nil { self.countOfFlight = PetroneCountFlight() } self.countOfFlight?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.countOfFlight!) case PetroneDataType.CountDrive.rawValue: if self.countOfDrive == nil { self.countOfDrive = PetroneCountDrive() } self.countOfDrive?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.countOfDrive!) case PetroneDataType.ImuRawAndAngle.rawValue: if self.imuRawAndAngle == nil { self.imuRawAndAngle = PetroneImuRawAndAngle() } self.imuRawAndAngle?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.imuRawAndAngle!) case PetroneDataType.Pressure.rawValue: if self.pressure == nil { self.pressure = PetronePressure() } self.pressure?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.pressure!) case PetroneDataType.ImageFlow.rawValue: if self.imageFlow == nil { self.imageFlow = PetroneImageFlow() } self.imageFlow?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.imageFlow!) case PetroneDataType.Motor.rawValue: if self.motor == nil { self.motor = PetroneMotor() } self.motor?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.motor!) case PetroneDataType.Range.rawValue: if self.range == nil { self.range = PetroneRange() } self.range?.parse(data); self.delegate?.petrone(controller!, recvFromPetrone: self.range!) default: NSLog("Uknown Packet recv.") } } @objc private func onSend() { if controller != nil && controller!.connected { if status != nil { if (status?.modeFlight.rawValue)! > PetroneModeFlight.Ready.rawValue || (status?.mode == PetroneMode.Drive) { let current = getCurrentMillis() if( current - prevControlTime > 99 ) { // send control packet 10 frame per sec. if self.controlValue.throttleTimer > 0 || self.controlValue.yawTimer > 0 || self.controlValue.pitchTimer > 0 || self.controlValue.rollTimer > 0 { let packet = PetronePacketControl() packet.throttle = self.controlValue.throttle packet.yaw = self.controlValue.yaw packet.pitch = self.controlValue.pitch packet.roll = self.controlValue.roll self.consumeControlTime(UInt16( current - prevControlTime )) self.sendPacket(packet) } prevControlTime = current } } } if packetList.count > 0 { let packet:PetronePacket = packetList.removeFirst() controller?.sendPacket(packet) //petroneBLE?.sendPacket(packet) } } } private func consumeControlTime( _ diffTime:UInt16 ) { self.controlValue.throttleTimer -= Int(diffTime) self.controlValue.yawTimer -= Int(diffTime) self.controlValue.pitchTimer -= Int(diffTime) self.controlValue.rollTimer -= Int(diffTime) if self.controlValue.throttleTimer <= 0 { self.controlValue.throttle = 0 self.controlValue.throttleTimer = 0 } if self.controlValue.yawTimer <= 0 { self.controlValue.yaw = 0 self.controlValue.yawTimer = 0 } if self.controlValue.pitchTimer <= 0 { self.controlValue.roll = 0 self.controlValue.pitchTimer = 0 } if self.controlValue.rollTimer <= 0 { self.controlValue.roll = 0 self.controlValue.rollTimer = 0 } } public class func getUInt64(_ data:Data, start:inout Int) -> UInt64 { var ret:UInt64 = 0; ret = UInt64(data[start+7]); ret = ret << 8 + UInt64(data[start+6]); ret = ret << 8 + UInt64(data[start+5]); ret = ret << 8 + UInt64(data[start+4]); ret = ret << 8 + UInt64(data[start+3]); ret = ret << 8 + UInt64(data[start+2]); ret = ret << 8 + UInt64(data[start+1]); ret = ret << 8 + UInt64(data[start]); start += 8 return ret } public class func getInt32(_ data:Data, start:inout Int) -> Int32 { var ret:Int32 = Int32(data[start+3]) ret = ret << 8 + Int32(data[start+2]); ret = ret << 8 + Int32(data[start+1]); ret = ret << 8 + Int32(data[start]) start += 4 return ret } public class func getUInt16(_ data:Data, start:inout Int) -> UInt16 { var ret:UInt16 = UInt16(data[start+1]) ret = ret << 8 + UInt16(data[start]) start += 2 return ret } public class func getInt16(_ data:Data, start:inout Int) -> Int16 { var ret:Int16 = Int16(data[start+1]) ret = ret << 8 + Int16(data[start]) start += 2 return ret } public class func setInt16(_ data:inout Data, value:Int16) { data.append(contentsOf: [UInt8(value & 0x00ff), UInt8(value >> 8)]) } func getCurrentMillis()->Int64 { return Int64(Date().timeIntervalSince1970 * 1000) } } public protocol PetroneNetworkDelegate : NSObjectProtocol { func onScanned() func onConnected() func onRecv(data:Data) }
f11ec941cf5de312a044b12243d40a3f
32.589783
169
0.578275
false
false
false
false
moldedbits/firebase-chat-example
refs/heads/master
Firebase-Chat-Research/Chat.swift
mit
1
// // Chat.swift // Firebase-Chat-Research // // Created by Amit kumar Swami on 18/03/16. // Copyright © 2016 moldedbits. All rights reserved. // import UIKit class Chat: NSObject { var user: String = "" var from: String = "" var channelName: String = "" var to: String = "" var timeStamp: NSDate = NSDate() struct FireBasePropertyKey { static let from = "from" static let channelName = "name" static let to = "to" static let timeStamp = "timestamp" } init(user: String, from: String, to: String, channelName: String, timeStamp: NSDate) { self.user = user self.from = from self.to = to self.channelName = channelName self.timeStamp = timeStamp } }
01286ce1ba4633fc1a8474bcb43f09a7
21.028571
90
0.595331
false
false
false
false
danielmartin/swift
refs/heads/master
stdlib/public/core/UnicodeScalarProperties.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Exposes advanced properties of Unicode.Scalar defined by the Unicode // Standard. //===----------------------------------------------------------------------===// import SwiftShims extension Unicode.Scalar { /// A value that provides access to properties of a Unicode scalar that are /// defined by the Unicode standard. public struct Properties { @usableFromInline internal var _scalar: Unicode.Scalar internal init(_ scalar: Unicode.Scalar) { self._scalar = scalar } // Provide the value as UChar32 to make calling the ICU APIs cleaner internal var icuValue: __swift_stdlib_UChar32 { return __swift_stdlib_UChar32(bitPattern: self._scalar._value) } } /// A value that provides access to properties of the Unicode scalar that are /// defined by the Unicode standard. public var properties: Properties { return Properties(self) } } /// Boolean properties that are defined by the Unicode Standard (i.e., not /// ICU-specific). extension Unicode.Scalar.Properties { internal func _hasBinaryProperty( _ property: __swift_stdlib_UProperty ) -> Bool { return __swift_stdlib_u_hasBinaryProperty(icuValue, property) != 0 } /// A Boolean property indicating whether the scalar is alphabetic. /// /// Alphabetic scalars are the primary units of alphabets and/or syllabaries. /// /// This property corresponds to the `Alphabetic` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isAlphabetic: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ALPHABETIC) } /// A Boolean property indicating whether the scalar is an ASCII character /// commonly used for the representation of hexadecimal numbers. /// /// The only scalars for which this property is true are: /// /// * U+0030...U+0039: DIGIT ZERO...DIGIT NINE /// * U+0041...U+0046: LATIN CAPITAL LETTER A...LATIN CAPITAL LETTER F /// * U+0061...U+0066: LATIN SMALL LETTER A...LATIN SMALL LETTER F /// /// This property corresponds to the `ASCII_Hex_Digit` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isASCIIHexDigit: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ASCII_HEX_DIGIT) } /// A Boolean property indicating whether the scalar is a format control /// character that has a specific function in the Unicode Bidrectional /// Algorithm. /// /// This property corresponds to the `Bidi_Control` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isBidiControl: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_BIDI_CONTROL) } /// A Boolean property indicating whether the scalar is mirrored in /// bidirectional text. /// /// This property corresponds to the `Bidi_Mirrored` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isBidiMirrored: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_BIDI_MIRRORED) } /// A Boolean property indicating whether the scalar is a punctuation /// symbol explicitly called out as a dash in the Unicode Standard or a /// compatibility equivalent. /// /// This property corresponds to the `Dash` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDash: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DASH) } /// A Boolean property indicating whether the scalar is a default-ignorable /// code point. /// /// Default-ignorable code points are those that should be ignored by default /// in rendering (unless explicitly supported). They have no visible glyph or /// advance width in and of themselves, although they may affect the display, /// positioning, or adornment of adjacent or surrounding characters. /// /// This property corresponds to the `Default_Ignorable_Code_Point` property /// in the [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDefaultIgnorableCodePoint: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DEFAULT_IGNORABLE_CODE_POINT) } /// A Boolean property indicating whether the scalar is deprecated. /// /// Scalars are never removed from the Unicode Standard, but the usage of /// deprecated scalars is strongly discouraged. /// /// This property corresponds to the `Deprecated` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDeprecated: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DEPRECATED) } /// A Boolean property indicating whether the scalar is a diacritic. /// /// Diacritics are scalars that linguistically modify the meaning of another /// scalar to which they apply. Scalars for which this property is true are /// frequently, but not always, combining marks or modifiers. /// /// This property corresponds to the `Diacritic` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDiacritic: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DIACRITIC) } /// A Boolean property indicating whether the scalar's principal function is /// to extend the value or shape of a preceding alphabetic scalar. /// /// Typical extenders are length and iteration marks. /// /// This property corresponds to the `Extender` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isExtender: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EXTENDER) } /// A Boolean property indicating whether the scalar is excluded from /// composition when performing Unicode normalization. /// /// This property corresponds to the `Full_Composition_Exclusion` property in /// the [Unicode Standard](http://www.unicode.org/versions/latest/). public var isFullCompositionExclusion: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_FULL_COMPOSITION_EXCLUSION) } /// A Boolean property indicating whether the scalar is a grapheme base. /// /// A grapheme base can be thought of as a space-occupying glyph above or /// below which other non-spacing modifying glyphs can be applied. For /// example, when the character `é` is represented in NFD form, the grapheme /// base is "e" (U+0065 LATIN SMALL LETTER E) and it is followed by a single /// grapheme extender, U+0301 COMBINING ACUTE ACCENT. /// /// The set of scalars for which `isGraphemeBase` is true is disjoint by /// definition from the set for which `isGraphemeExtend` is true. /// /// This property corresponds to the `Grapheme_Base` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isGraphemeBase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_GRAPHEME_BASE) } /// A Boolean property indicating whether the scalar is a grapheme extender. /// /// A grapheme extender can be thought of primarily as a non-spacing glyph /// that is applied above or below another glyph. /// /// The set of scalars for which `isGraphemeExtend` is true is disjoint by /// definition from the set for which `isGraphemeBase` is true. /// /// This property corresponds to the `Grapheme_Extend` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isGraphemeExtend: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_GRAPHEME_EXTEND) } /// A Boolean property indicating whether the scalar is one that is commonly /// used for the representation of hexadecimal numbers or a compatibility /// equivalent. /// /// This property is true for all scalars for which `isASCIIHexDigit` is true /// as well as for their CJK halfwidth and fullwidth variants. /// /// This property corresponds to the `Hex_Digit` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isHexDigit: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_HEX_DIGIT) } /// A Boolean property indicating whether the scalar is one which is /// recommended to be allowed to appear in a non-starting position in a /// programming language identifier. /// /// Applications that store identifiers in NFKC normalized form should instead /// use `isXIDContinue` to check whether a scalar is a valid identifier /// character. /// /// This property corresponds to the `ID_Continue` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDContinue: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ID_CONTINUE) } /// A Boolean property indicating whether the scalar is one which is /// recommended to be allowed to appear in a starting position in a /// programming language identifier. /// /// Applications that store identifiers in NFKC normalized form should instead /// use `isXIDStart` to check whether a scalar is a valid identifier /// character. /// /// This property corresponds to the `ID_Start` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDStart: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ID_START) } /// A Boolean property indicating whether the scalar is considered to be a /// CJKV (Chinese, Japanese, Korean, and Vietnamese) or other siniform /// (Chinese writing-related) ideograph. /// /// This property roughly defines the class of "Chinese characters" and does /// not include characters of other logographic scripts such as Cuneiform or /// Egyptian Hieroglyphs. /// /// This property corresponds to the `Ideographic` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIdeographic: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_IDEOGRAPHIC) } /// A Boolean property indicating whether the scalar is an ideographic /// description character that determines how the two ideographic characters /// or ideographic description sequences that follow it are to be combined to /// form a single character. /// /// Ideographic description characters are technically printable characters, /// but advanced rendering engines may use them to approximate ideographs that /// are otherwise unrepresentable. /// /// This property corresponds to the `IDS_Binary_Operator` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDSBinaryOperator: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_IDS_BINARY_OPERATOR) } /// A Boolean property indicating whether the scalar is an ideographic /// description character that determines how the three ideographic characters /// or ideographic description sequences that follow it are to be combined to /// form a single character. /// /// Ideographic description characters are technically printable characters, /// but advanced rendering engines may use them to approximate ideographs that /// are otherwise unrepresentable. /// /// This property corresponds to the `IDS_Trinary_Operator` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDSTrinaryOperator: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_IDS_TRINARY_OPERATOR) } /// A Boolean property indicating whether the scalar is a format control /// character that has a specific function in controlling cursive joining and /// ligation. /// /// There are two scalars for which this property is true: /// /// * When U+200C ZERO WIDTH NON-JOINER is inserted between two characters, it /// directs the rendering engine to render them separately/disconnected when /// it might otherwise render them as a ligature. For example, a rendering /// engine might display "fl" in English as a connected glyph; inserting the /// zero width non-joiner would force them to be rendered as disconnected /// glyphs. /// /// * When U+200D ZERO WIDTH JOINER is inserted between two characters, it /// directs the rendering engine to render them as a connected glyph when it /// would otherwise render them independently. The zero width joiner is also /// used to construct complex emoji from sequences of base emoji characters. /// For example, the various "family" emoji are encoded as sequences of man, /// woman, or child emoji that are interleaved with zero width joiners. /// /// This property corresponds to the `Join_Control` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isJoinControl: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_JOIN_CONTROL) } /// A Boolean property indicating whether the scalar requires special handling /// for operations involving ordering, such as sorting and searching. /// /// This property applies to a small number of spacing vowel letters occurring /// in some Southeast Asian scripts like Thai and Lao, which use a visual /// order display model. Such letters are stored in text ahead of /// syllable-initial consonants. /// /// This property corresponds to the `Logical_Order_Exception` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isLogicalOrderException: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_LOGICAL_ORDER_EXCEPTION) } /// A Boolean property indicating whether the scalar's letterform is /// considered lowercase. /// /// This property corresponds to the `Lowercase` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isLowercase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_LOWERCASE) } /// A Boolean property indicating whether the scalar is one that naturally /// appears in mathematical contexts. /// /// The set of scalars for which this property is true includes mathematical /// operators and symbols as well as specific Greek and Hebrew letter /// variants that are categorized as symbols. Notably, it does _not_ contain /// the standard digits or Latin/Greek letter blocks; instead, it contains the /// mathematical Latin, Greek, and Arabic letters and numbers defined in the /// Supplemental Multilingual Plane. /// /// This property corresponds to the `Math` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isMath: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_MATH) } /// A Boolean property indicating whether the scalar is permanently reserved /// for internal use. /// /// This property corresponds to the `Noncharacter_Code_Point` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isNoncharacterCodePoint: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_NONCHARACTER_CODE_POINT) } /// A Boolean property indicating whether the scalar is one that is used in /// writing to surround quoted text. /// /// This property corresponds to the `Quotation_Mark` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isQuotationMark: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_QUOTATION_MARK) } /// A Boolean property indicating whether the scalar is a radical component of /// CJK characters, Tangut characters, or Yi syllables. /// /// These scalars are often the components of ideographic description /// sequences, as defined by the `isIDSBinaryOperator` and /// `isIDSTrinaryOperator` properties. /// /// This property corresponds to the `Radical` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isRadical: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_RADICAL) } /// A Boolean property indicating whether the scalar has a "soft dot" that /// disappears when a diacritic is placed over the scalar. /// /// For example, "i" is soft dotted because the dot disappears when adding an /// accent mark, as in "í". /// /// This property corresponds to the `Soft_Dotted` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isSoftDotted: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_SOFT_DOTTED) } /// A Boolean property indicating whether the scalar is a punctuation symbol /// that typically marks the end of a textual unit. /// /// This property corresponds to the `Terminal_Punctuation` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isTerminalPunctuation: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_TERMINAL_PUNCTUATION) } /// A Boolean property indicating whether the scalar is one of the unified /// CJK ideographs in the Unicode Standard. /// /// This property is false for CJK punctuation and symbols, as well as for /// compatibility ideographs (which canonically decompose to unified /// ideographs). /// /// This property corresponds to the `Unified_Ideograph` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isUnifiedIdeograph: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_UNIFIED_IDEOGRAPH) } /// A Boolean property indicating whether the scalar's letterform is /// considered uppercase. /// /// This property corresponds to the `Uppercase` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isUppercase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_UPPERCASE) } /// A Boolean property indicating whether the scalar is a whitespace /// character. /// /// This property is true for scalars that are spaces, separator characters, /// and other control characters that should be treated as whitespace for the /// purposes of parsing text elements. /// /// This property corresponds to the `White_Space` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isWhitespace: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_WHITE_SPACE) } /// A Boolean property indicating whether the scalar is one which is /// recommended to be allowed to appear in a non-starting position in a /// programming language identifier, with adjustments made for NFKC normalized /// form. /// /// The set of scalars `[:XID_Continue:]` closes the set `[:ID_Continue:]` /// under NFKC normalization by removing any scalars whose normalized form is /// not of the form `[:ID_Continue:]*`. /// /// This property corresponds to the `XID_Continue` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isXIDContinue: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_XID_CONTINUE) } /// A Boolean property indicating whether the scalar is one which is /// recommended to be allowed to appear in a starting position in a /// programming language identifier, with adjustments made for NFKC normalized /// form. /// /// The set of scalars `[:XID_Start:]` closes the set `[:ID_Start:]` under /// NFKC normalization by removing any scalars whose normalized form is not of /// the form `[:ID_Start:] [:ID_Continue:]*`. /// /// This property corresponds to the `XID_Start` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isXIDStart: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_XID_START) } /// A Boolean property indicating whether the scalar is a punctuation mark /// that generally marks the end of a sentence. /// /// This property corresponds to the `Sentence_Terminal` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isSentenceTerminal: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_S_TERM) } /// A Boolean property indicating whether the scalar is a variation selector. /// /// Variation selectors allow rendering engines that support them to choose /// different glyphs to display for a particular code point. /// /// This property corresponds to the `Variation_Selector` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isVariationSelector: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_VARIATION_SELECTOR) } /// A Boolean property indicating whether the scalar is recommended to have /// syntactic usage in patterns represented in source code. /// /// This property corresponds to the `Pattern_Syntax` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isPatternSyntax: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_PATTERN_SYNTAX) } /// A Boolean property indicating whether the scalar is recommended to be /// treated as whitespace when parsing patterns represented in source code. /// /// This property corresponds to the `Pattern_White_Space` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isPatternWhitespace: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_PATTERN_WHITE_SPACE) } /// A Boolean property indicating whether the scalar is considered to be /// either lowercase, uppercase, or titlecase. /// /// Though similar in name, this property is _not_ equivalent to /// `changesWhenCaseMapped`. The set of scalars for which `isCased` is true is /// a superset of those for which `changesWhenCaseMapped` is true. An example /// of scalars that only have `isCased` as true are the Latin small capitals /// that are used by the International Phonetic Alphabet. These letters have a /// case but do not change when they are mapped to any of the other cases. /// /// This property corresponds to the `Cased` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isCased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CASED) } /// A Boolean property indicating whether the scalar is ignored for casing /// purposes. /// /// This property corresponds to the `Case_Ignorable` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isCaseIgnorable: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CASE_IGNORABLE) } /// A Boolean property indicating whether the scalar's normalized form differs /// from the `lowercaseMapping` of each constituent scalar. /// /// This property corresponds to the `Changes_When_Lowercased` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenLowercased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_LOWERCASED) } /// A Boolean property indicating whether the scalar's normalized form differs /// from the `uppercaseMapping` of each constituent scalar. /// /// This property corresponds to the `Changes_When_Uppercased` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenUppercased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_UPPERCASED) } /// A Boolean property indicating whether the scalar's normalized form differs /// from the `titlecaseMapping` of each constituent scalar. /// /// This property corresponds to the `Changes_When_Titlecased` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenTitlecased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_TITLECASED) } /// A Boolean property indicating whether the scalar's normalized form differs /// from the case-fold mapping of each constituent scalar. /// /// This property corresponds to the `Changes_When_Casefolded` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenCaseFolded: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_CASEFOLDED) } /// A Boolean property indicating whether the scalar may change when it /// undergoes case mapping. /// /// For any scalar `s`, it holds by definition that /// /// ``` /// s.changesWhenCaseMapped = s.changesWhenLowercased || /// s.changesWhenUppercased || /// s.changesWhenTitlecased /// ``` /// /// This property corresponds to the `Changes_When_Casemapped` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenCaseMapped: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_CASEMAPPED) } /// A Boolean property indicating whether the scalar is one that is not /// identical to its NFKC case-fold mapping. /// /// This property corresponds to the `Changes_When_NFKC_Casefolded` property /// in the [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenNFKCCaseFolded: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // FIXME: These properties were introduced in ICU 57, but Ubuntu 16.04 comes // with ICU 55 so the values won't be correct there. Exclude them on // non-Darwin platforms for now; bundling ICU with the toolchain would resolve // this and other inconsistencies (https://bugs.swift.org/browse/SR-6076). /// A Boolean property indicating whether the scalar has an emoji /// presentation, whether or not it is the default. /// /// This property is true for scalars that are rendered as emoji by default /// and also for scalars that have a non-default emoji rendering when followed /// by U+FE0F VARIATION SELECTOR-16. This includes some scalars that are not /// typically considered to be emoji: /// /// ``` /// let sunglasses: Unicode.Scalar = "😎" /// let dollar: Unicode.Scalar = "$" /// let zero: Unicode.Scalar = "0" /// /// print(sunglasses.isEmoji) /// // Prints "true" /// print(dollar.isEmoji) /// // Prints "false" /// print(zero.isEmoji) /// // Prints "true" /// ``` /// /// The final result is true because the ASCII digits have non-default emoji /// presentations; some platforms render these with an alternate appearance. /// /// Because of this behavior, testing `isEmoji` alone on a single scalar is /// insufficient to determine if a unit of text is rendered as an emoji; a /// correct test requires inspecting multiple scalars in a `Character`. In /// addition to checking whether the base scalar has `isEmoji == true`, you /// must also check its default presentation (see `isEmojiPresentation`) and /// determine whether it is followed by a variation selector that would modify /// the presentation. /// /// This property corresponds to the `Emoji` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmoji: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI) } /// A Boolean property indicating whether the scalar is one that should be /// rendered with an emoji presentation, rather than a text presentation, by /// default. /// /// Scalars that have emoji presentation by default can be followed by /// U+FE0E VARIATION SELECTOR-15 to request the text presentation of the /// scalar instead. Likewise, scalars that default to text presentation can /// be followed by U+FE0F VARIATION SELECTOR-16 to request the emoji /// presentation. /// /// This property corresponds to the `Emoji_Presentation` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmojiPresentation: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_PRESENTATION) } /// A Boolean property indicating whether the scalar is one that can modify /// a base emoji that precedes it. /// /// The Fitzpatrick skin types are examples of emoji modifiers; they change /// the appearance of the preceding emoji base (that is, a scalar for which /// `isEmojiModifierBase` is true) by rendering it with a different skin tone. /// /// This property corresponds to the `Emoji_Modifier` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmojiModifier: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_MODIFIER) } /// A Boolean property indicating whether the scalar is one whose appearance /// can be changed by an emoji modifier that follows it. /// /// This property corresponds to the `Emoji_Modifier_Base` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmojiModifierBase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_MODIFIER_BASE) } #endif } /// Case mapping properties. extension Unicode.Scalar.Properties { // The type of ICU case conversion functions. internal typealias _U_StrToX = ( /* dest */ UnsafeMutablePointer<__swift_stdlib_UChar>, /* destCapacity */ Int32, /* src */ UnsafePointer<__swift_stdlib_UChar>, /* srcLength */ Int32, /* locale */ UnsafePointer<Int8>, /* pErrorCode */ UnsafeMutablePointer<__swift_stdlib_UErrorCode> ) -> Int32 /// Applies the given ICU string mapping to the scalar. /// /// This function attempts first to write the mapping into a stack-based /// UTF-16 buffer capable of holding 16 code units, which should be enough for /// all current case mappings. In the event more space is needed, it will be /// allocated on the heap. internal func _applyMapping(_ u_strTo: _U_StrToX) -> String { // TODO(String performance): Stack buffer first and then detect real count let count = 64 var array = Array<UInt16>(repeating: 0, count: count) let len: Int = array.withUnsafeMutableBufferPointer { bufPtr in return _scalar.withUTF16CodeUnits { utf16 in var err = __swift_stdlib_U_ZERO_ERROR let correctSize = u_strTo( bufPtr.baseAddress._unsafelyUnwrappedUnchecked, Int32(bufPtr.count), utf16.baseAddress._unsafelyUnwrappedUnchecked, Int32(utf16.count), "", &err) guard err.isSuccess else { fatalError("Unexpected error case-converting Unicode scalar.") } // TODO: _internalInvariant(count == correctSize, "inconsistent ICU behavior") return Int(correctSize) } } // TODO: replace `len` with `count` return array[..<len].withUnsafeBufferPointer { return String._uncheckedFromUTF16($0) } } /// The lowercase mapping of the scalar. /// /// This property is a `String`, not a `Unicode.Scalar` or `Character`, /// because some mappings may transform a scalar into multiple scalars or /// graphemes. For example, the character "İ" (U+0130 LATIN CAPITAL LETTER I /// WITH DOT ABOVE) becomes two scalars (U+0069 LATIN SMALL LETTER I, U+0307 /// COMBINING DOT ABOVE) when converted to lowercase. /// /// This property corresponds to the `Lowercase_Mapping` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var lowercaseMapping: String { return _applyMapping(__swift_stdlib_u_strToLower) } /// The titlecase mapping of the scalar. /// /// This property is a `String`, not a `Unicode.Scalar` or `Character`, /// because some mappings may transform a scalar into multiple scalars or /// graphemes. For example, the ligature "fi" (U+FB01 LATIN SMALL LIGATURE FI) /// becomes "Fi" (U+0046 LATIN CAPITAL LETTER F, U+0069 LATIN SMALL LETTER I) /// when converted to titlecase. /// /// This property corresponds to the `Titlecase_Mapping` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var titlecaseMapping: String { return _applyMapping { ptr, cap, src, len, locale, err in return __swift_stdlib_u_strToTitle(ptr, cap, src, len, nil, locale, err) } } /// The uppercase mapping of the scalar. /// /// This property is a `String`, not a `Unicode.Scalar` or `Character`, /// because some mappings may transform a scalar into multiple scalars or /// graphemes. For example, the German letter "ß" (U+00DF LATIN SMALL LETTER /// SHARP S) becomes "SS" (U+0053 LATIN CAPITAL LETTER S, U+0053 LATIN CAPITAL /// LETTER S) when converted to uppercase. /// /// This property corresponds to the `Uppercase_Mapping` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var uppercaseMapping: String { return _applyMapping(__swift_stdlib_u_strToUpper) } } extension Unicode { /// A version of the Unicode Standard represented by its `major.minor` /// components. public typealias Version = (major: Int, minor: Int) } extension Unicode.Scalar.Properties { /// The earliest version of the Unicode Standard in which the scalar was /// assigned. /// /// This value will be nil for code points that have not yet been assigned. /// /// This property corresponds to the `Age` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var age: Unicode.Version? { var versionInfo: __swift_stdlib_UVersionInfo = (0, 0, 0, 0) withUnsafeMutablePointer(to: &versionInfo) { tuplePtr in tuplePtr.withMemoryRebound(to: UInt8.self, capacity: 4) { versionInfoPtr in __swift_stdlib_u_charAge(icuValue, versionInfoPtr) } } guard versionInfo.0 != 0 else { return nil } return (major: Int(versionInfo.0), minor: Int(versionInfo.1)) } } extension Unicode { /// The most general classification of a Unicode scalar. /// /// The general category of a scalar is its "first-order, most usual /// categorization". It does not attempt to cover multiple uses of some /// scalars, such as the use of letters to represent Roman numerals. public enum GeneralCategory { /// An uppercase letter. /// /// This value corresponds to the category `Uppercase_Letter` (abbreviated /// `Lu`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case uppercaseLetter /// A lowercase letter. /// /// This value corresponds to the category `Lowercase_Letter` (abbreviated /// `Ll`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case lowercaseLetter /// A digraph character whose first part is uppercase. /// /// This value corresponds to the category `Titlecase_Letter` (abbreviated /// `Lt`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case titlecaseLetter /// A modifier letter. /// /// This value corresponds to the category `Modifier_Letter` (abbreviated /// `Lm`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case modifierLetter /// Other letters, including syllables and ideographs. /// /// This value corresponds to the category `Other_Letter` (abbreviated /// `Lo`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherLetter /// A non-spacing combining mark with zero advance width (abbreviated Mn). /// /// This value corresponds to the category `Nonspacing_Mark` (abbreviated /// `Mn`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case nonspacingMark /// A spacing combining mark with positive advance width. /// /// This value corresponds to the category `Spacing_Mark` (abbreviated `Mc`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case spacingMark /// An enclosing combining mark. /// /// This value corresponds to the category `Enclosing_Mark` (abbreviated /// `Me`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case enclosingMark /// A decimal digit. /// /// This value corresponds to the category `Decimal_Number` (abbreviated /// `Nd`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case decimalNumber /// A letter-like numeric character. /// /// This value corresponds to the category `Letter_Number` (abbreviated /// `Nl`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case letterNumber /// A numeric character of another type. /// /// This value corresponds to the category `Other_Number` (abbreviated `No`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherNumber /// A connecting punctuation mark, like a tie. /// /// This value corresponds to the category `Connector_Punctuation` /// (abbreviated `Pc`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case connectorPunctuation /// A dash or hyphen punctuation mark. /// /// This value corresponds to the category `Dash_Punctuation` (abbreviated /// `Pd`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case dashPunctuation /// An opening punctuation mark of a pair. /// /// This value corresponds to the category `Open_Punctuation` (abbreviated /// `Ps`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case openPunctuation /// A closing punctuation mark of a pair. /// /// This value corresponds to the category `Close_Punctuation` (abbreviated /// `Pe`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case closePunctuation /// An initial quotation mark. /// /// This value corresponds to the category `Initial_Punctuation` /// (abbreviated `Pi`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case initialPunctuation /// A final quotation mark. /// /// This value corresponds to the category `Final_Punctuation` (abbreviated /// `Pf`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case finalPunctuation /// A punctuation mark of another type. /// /// This value corresponds to the category `Other_Punctuation` (abbreviated /// `Po`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherPunctuation /// A symbol of mathematical use. /// /// This value corresponds to the category `Math_Symbol` (abbreviated `Sm`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case mathSymbol /// A currency sign. /// /// This value corresponds to the category `Currency_Symbol` (abbreviated /// `Sc`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case currencySymbol /// A non-letterlike modifier symbol. /// /// This value corresponds to the category `Modifier_Symbol` (abbreviated /// `Sk`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case modifierSymbol /// A symbol of another type. /// /// This value corresponds to the category `Other_Symbol` (abbreviated /// `So`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherSymbol /// A space character of non-zero width. /// /// This value corresponds to the category `Space_Separator` (abbreviated /// `Zs`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case spaceSeparator /// A line separator, which is specifically (and only) U+2028 LINE /// SEPARATOR. /// /// This value corresponds to the category `Line_Separator` (abbreviated /// `Zl`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case lineSeparator /// A paragraph separator, which is specifically (and only) U+2029 PARAGRAPH /// SEPARATOR. /// /// This value corresponds to the category `Paragraph_Separator` /// (abbreviated `Zp`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case paragraphSeparator /// A C0 or C1 control code. /// /// This value corresponds to the category `Control` (abbreviated `Cc`) in /// the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case control /// A format control character. /// /// This value corresponds to the category `Format` (abbreviated `Cf`) in /// the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case format /// A surrogate code point. /// /// This value corresponds to the category `Surrogate` (abbreviated `Cs`) in /// the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case surrogate /// A private-use character. /// /// This value corresponds to the category `Private_Use` (abbreviated `Co`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case privateUse /// A reserved unassigned code point or a non-character. /// /// This value corresponds to the category `Unassigned` (abbreviated `Cn`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case unassigned internal init(rawValue: __swift_stdlib_UCharCategory) { switch rawValue { case __swift_stdlib_U_UNASSIGNED: self = .unassigned case __swift_stdlib_U_UPPERCASE_LETTER: self = .uppercaseLetter case __swift_stdlib_U_LOWERCASE_LETTER: self = .lowercaseLetter case __swift_stdlib_U_TITLECASE_LETTER: self = .titlecaseLetter case __swift_stdlib_U_MODIFIER_LETTER: self = .modifierLetter case __swift_stdlib_U_OTHER_LETTER: self = .otherLetter case __swift_stdlib_U_NON_SPACING_MARK: self = .nonspacingMark case __swift_stdlib_U_ENCLOSING_MARK: self = .enclosingMark case __swift_stdlib_U_COMBINING_SPACING_MARK: self = .spacingMark case __swift_stdlib_U_DECIMAL_DIGIT_NUMBER: self = .decimalNumber case __swift_stdlib_U_LETTER_NUMBER: self = .letterNumber case __swift_stdlib_U_OTHER_NUMBER: self = .otherNumber case __swift_stdlib_U_SPACE_SEPARATOR: self = .spaceSeparator case __swift_stdlib_U_LINE_SEPARATOR: self = .lineSeparator case __swift_stdlib_U_PARAGRAPH_SEPARATOR: self = .paragraphSeparator case __swift_stdlib_U_CONTROL_CHAR: self = .control case __swift_stdlib_U_FORMAT_CHAR: self = .format case __swift_stdlib_U_PRIVATE_USE_CHAR: self = .privateUse case __swift_stdlib_U_SURROGATE: self = .surrogate case __swift_stdlib_U_DASH_PUNCTUATION: self = .dashPunctuation case __swift_stdlib_U_START_PUNCTUATION: self = .openPunctuation case __swift_stdlib_U_END_PUNCTUATION: self = .closePunctuation case __swift_stdlib_U_CONNECTOR_PUNCTUATION: self = .connectorPunctuation case __swift_stdlib_U_OTHER_PUNCTUATION: self = .otherPunctuation case __swift_stdlib_U_MATH_SYMBOL: self = .mathSymbol case __swift_stdlib_U_CURRENCY_SYMBOL: self = .currencySymbol case __swift_stdlib_U_MODIFIER_SYMBOL: self = .modifierSymbol case __swift_stdlib_U_OTHER_SYMBOL: self = .otherSymbol case __swift_stdlib_U_INITIAL_PUNCTUATION: self = .initialPunctuation case __swift_stdlib_U_FINAL_PUNCTUATION: self = .finalPunctuation default: fatalError("Unknown general category \(rawValue)") } } } } // Internal helpers extension Unicode.GeneralCategory { internal var _isSymbol: Bool { switch self { case .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol: return true default: return false } } internal var _isPunctuation: Bool { switch self { case .connectorPunctuation, .dashPunctuation, .openPunctuation, .closePunctuation, .initialPunctuation, .finalPunctuation, .otherPunctuation: return true default: return false } } } extension Unicode.Scalar.Properties { /// The general category (most usual classification) of the scalar. /// /// This property corresponds to the `General_Category` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var generalCategory: Unicode.GeneralCategory { let rawValue = __swift_stdlib_UCharCategory( __swift_stdlib_UCharCategory.RawValue( __swift_stdlib_u_getIntPropertyValue( icuValue, __swift_stdlib_UCHAR_GENERAL_CATEGORY))) return Unicode.GeneralCategory(rawValue: rawValue) } } extension Unicode.Scalar.Properties { internal func _scalarName( _ choice: __swift_stdlib_UCharNameChoice ) -> String? { var err = __swift_stdlib_U_ZERO_ERROR let count = Int(__swift_stdlib_u_charName(icuValue, choice, nil, 0, &err)) guard count > 0 else { return nil } // ICU writes a trailing null, so we have to save room for it as well. var array = Array<UInt8>(repeating: 0, count: count + 1) return array.withUnsafeMutableBufferPointer { bufPtr in var err = __swift_stdlib_U_ZERO_ERROR let correctSize = __swift_stdlib_u_charName( icuValue, choice, UnsafeMutableRawPointer(bufPtr.baseAddress._unsafelyUnwrappedUnchecked) .assumingMemoryBound(to: Int8.self), Int32(bufPtr.count), &err) guard err.isSuccess else { fatalError("Unexpected error case-converting Unicode scalar.") } _internalInvariant(count == correctSize, "inconsistent ICU behavior") return String._fromASCII( UnsafeBufferPointer(rebasing: bufPtr[..<count])) } } /// The published name of the scalar. /// /// Some scalars, such as control characters, do not have a value for this /// property in the UCD. For such scalars, this property will be nil. /// /// This property corresponds to the `Name` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var name: String? { return _scalarName(__swift_stdlib_U_UNICODE_CHAR_NAME) } /// The normative formal alias of the scalar, or nil if it has no alias. /// /// The name of a scalar is immutable and never changed in future versions of /// the Unicode Standard. The `nameAlias` property is provided to issue /// corrections if a name was issued erroneously. For example, the `name` of /// U+FE18 is "PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRAKCET" /// (note that "BRACKET" is misspelled). The `nameAlias` property then /// contains the corrected name. /// /// This property corresponds to the `Name_Alias` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var nameAlias: String? { return _scalarName(__swift_stdlib_U_CHAR_NAME_ALIAS) } } extension Unicode { /// The classification of a scalar used in the Canonical Ordering Algorithm /// defined by the Unicode Standard. /// /// Canonical combining classes are used by the ordering algorithm to /// determine if two sequences of combining marks should be considered /// canonically equivalent (that is, identical in interpretation). Two /// sequences are canonically equivalent if they are equal when sorting the /// scalars in ascending order by their combining class. /// /// For example, consider the sequence `"\u{0041}\u{0301}\u{0316}"` (LATIN /// CAPITAL LETTER A, COMBINING ACUTE ACCENT, COMBINING GRAVE ACCENT BELOW). /// The combining classes of these scalars have the numeric values 0, 230, and /// 220, respectively. Sorting these scalars by their combining classes yields /// `"\u{0041}\u{0316}\u{0301}"`, so two strings that differ only by the /// ordering of those scalars would compare as equal: /// /// ``` /// print("\u{0041}\u{0316}\u{0301}" == "\u{0041}\u{0301}\u{0316}") /// // Prints "true" /// ``` /// /// Named and Unnamed Combining Classes /// =================================== /// /// Canonical combining classes are defined in the Unicode Standard as /// integers in the range `0...254`. For convenience, the standard assigns /// symbolic names to a subset of these combining classes. /// /// The `CanonicalCombiningClass` type conforms to `RawRepresentable` with a /// raw value of type `UInt8`. Instances of the type can be created from the /// actual numeric value using the `init(rawValue:)` initializer, and /// combining classes with symbolic names can also be referenced using the /// static members that share those names. /// /// ``` /// print(Unicode.CanonicalCombiningClass(rawValue: 1) == .overlay) /// // Prints "true" /// ``` public struct CanonicalCombiningClass: Comparable, Hashable, RawRepresentable { /// Base glyphs that occupy their own space and do not combine with others. public static let notReordered = CanonicalCombiningClass(rawValue: 0) /// Marks that overlay a base letter or symbol. public static let overlay = CanonicalCombiningClass(rawValue: 1) /// Diacritic nukta marks in Brahmi-derived scripts. public static let nukta = CanonicalCombiningClass(rawValue: 7) /// Combining marks that are attached to hiragana and katakana to indicate /// voicing changes. public static let kanaVoicing = CanonicalCombiningClass(rawValue: 8) /// Diacritic virama marks in Brahmi-derived scripts. public static let virama = CanonicalCombiningClass(rawValue: 9) /// Marks attached at the bottom left. public static let attachedBelowLeft = CanonicalCombiningClass(rawValue: 200) /// Marks attached directly below. public static let attachedBelow = CanonicalCombiningClass(rawValue: 202) /// Marks attached directly above. public static let attachedAbove = CanonicalCombiningClass(rawValue: 214) /// Marks attached at the top right. public static let attachedAboveRight = CanonicalCombiningClass(rawValue: 216) /// Distinct marks at the bottom left. public static let belowLeft = CanonicalCombiningClass(rawValue: 218) /// Distinct marks directly below. public static let below = CanonicalCombiningClass(rawValue: 220) /// Distinct marks at the bottom right. public static let belowRight = CanonicalCombiningClass(rawValue: 222) /// Distinct marks to the left. public static let left = CanonicalCombiningClass(rawValue: 224) /// Distinct marks to the right. public static let right = CanonicalCombiningClass(rawValue: 226) /// Distinct marks at the top left. public static let aboveLeft = CanonicalCombiningClass(rawValue: 228) /// Distinct marks directly above. public static let above = CanonicalCombiningClass(rawValue: 230) /// Distinct marks at the top right. public static let aboveRight = CanonicalCombiningClass(rawValue: 232) /// Distinct marks subtending two bases. public static let doubleBelow = CanonicalCombiningClass(rawValue: 233) /// Distinct marks extending above two bases. public static let doubleAbove = CanonicalCombiningClass(rawValue: 234) /// Greek iota subscript only (U+0345 COMBINING GREEK YPOGEGRAMMENI). public static let iotaSubscript = CanonicalCombiningClass(rawValue: 240) /// The raw integer value of the canonical combining class. public let rawValue: UInt8 /// Creates a new canonical combining class with the given raw integer /// value. /// /// - Parameter rawValue: The raw integer value of the canonical combining /// class. public init(rawValue: UInt8) { self.rawValue = rawValue } public static func == ( lhs: CanonicalCombiningClass, rhs: CanonicalCombiningClass ) -> Bool { return lhs.rawValue == rhs.rawValue } public static func < ( lhs: CanonicalCombiningClass, rhs: CanonicalCombiningClass ) -> Bool { return lhs.rawValue < rhs.rawValue } public var hashValue: Int { return rawValue.hashValue } public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } } } extension Unicode.Scalar.Properties { /// The canonical combining class of the scalar. /// /// This property corresponds to the `Canonical_Combining_Class` property in /// the [Unicode Standard](http://www.unicode.org/versions/latest/). public var canonicalCombiningClass: Unicode.CanonicalCombiningClass { let rawValue = UInt8(__swift_stdlib_u_getIntPropertyValue( icuValue, __swift_stdlib_UCHAR_CANONICAL_COMBINING_CLASS)) return Unicode.CanonicalCombiningClass(rawValue: rawValue) } } extension Unicode { /// The numeric type of a scalar. /// /// Scalars with a non-nil numeric type include numbers, fractions, numeric /// superscripts and subscripts, and circled or otherwise decorated number /// glyphs. /// /// Some letterlike scalars used in numeric systems, such as Greek or Latin /// letters, do not have a non-nil numeric type, in order to prevent programs /// from incorrectly interpreting them as numbers in non-numeric contexts. public enum NumericType { /// Digits that are commonly understood to form base-10 numbers. /// /// Specifically, scalars have this numeric type if they occupy a contiguous /// range of code points representing numeric values `0...9`. case decimal /// Decimal digits that otherwise do not meet the requirements of numeric /// type `decimal`. /// /// Scalars with this numeric type are often those that represent a decimal /// digit but would not typically be used to write a base-10 number, such as /// "④" (U+2463 CIRCLED DIGIT FOUR). /// /// In practice, the distinction between `digit` and `numeric` has not /// proven to be valuable. As of Unicode 6.3, any new scalars that represent /// numbers but do not meet the requirements of `decimal` will have numeric /// type `numeric`, and programs can treat `digit` and `numeric` /// equivalently. case digit /// Numbers that are not decimal digits. /// /// This numeric type includes fractions such as "⅕" (U+2155 VULGAR FRACITON /// ONE FIFTH), numerical CJK ideographs like "兆" (U+5146 CJK UNIFIED /// IDEOGRAPH-5146), and other scalars that are not decimal digits used /// positionally in the writing of base-10 numbers. case numeric internal init?(rawValue: __swift_stdlib_UNumericType) { switch rawValue { case __swift_stdlib_U_NT_NONE: return nil case __swift_stdlib_U_NT_DECIMAL: self = .decimal case __swift_stdlib_U_NT_DIGIT: self = .digit case __swift_stdlib_U_NT_NUMERIC: self = .numeric default: fatalError("Unknown numeric type \(rawValue)") } } } } /// Numeric properties of scalars. extension Unicode.Scalar.Properties { /// The numeric type of the scalar. /// /// The value of this property is nil for scalars that do not represent a /// number. /// /// ``` /// print("X", ("X" as Unicode.Scalar).properties.numericType ?? "nil") /// // Prints "X nil" /// print("4", ("4" as Unicode.Scalar).properties.numericType ?? "nil") /// // Prints "4 decimal" /// print("\u{2463}", ("\u{2463}" as Unicode.Scalar).properties.numericType ?? "nil") /// // Prints "④ digit" /// print("\u{2155}", ("\u{2155}" as Unicode.Scalar).properties.numericType ?? "nil") /// // Prints "⅕ numeric" /// ``` /// /// This property corresponds to the `Numeric_Type` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var numericType: Unicode.NumericType? { let rawValue = __swift_stdlib_UNumericType( __swift_stdlib_UNumericType.RawValue( __swift_stdlib_u_getIntPropertyValue( icuValue, __swift_stdlib_UCHAR_NUMERIC_TYPE))) return Unicode.NumericType(rawValue: rawValue) } /// The numeric value of the scalar. /// /// The value of this property is nil for scalars that do not represent a /// number. /// /// The numeric value of a scalar is represented as a `Double` because some /// scalars represent fractions: /// /// ``` /// print("X", ("X" as Unicode.Scalar).properties.numericValue ?? "nil") /// // Prints "X nil" /// print("4", ("4" as Unicode.Scalar).properties.numericValue ?? "nil") /// // Prints "4 4.0" /// print("\u{2463}", ("\u{2463}" as Unicode.Scalar).properties.numericValue ?? "nil") /// // Prints "④ 4.0" /// print("\u{2155}", ("\u{2155}" as Unicode.Scalar).properties.numericValue ?? "nil") /// // Prints "⅕ 0.2" /// ``` /// /// This property corresponds to the `Numeric_Value` property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var numericValue: Double? { let icuNoNumericValue: Double = -123456789 let result = __swift_stdlib_u_getNumericValue(icuValue) return result != icuNoNumericValue ? result : nil } }
1023fecb74a479dbf3c0a2e1f3300172
40.47724
88
0.694566
false
false
false
false
kfarst/alarm
refs/heads/master
alarm/SleepQualityMonitor.swift
mit
1
// // SleepQualityMonitor.swift // alarm // // Created by Michael Lewis on 3/21/15. // Copyright (c) 2015 Kevin Farst. All rights reserved. // import Foundation /** * The SleepQualityMonitor is responsible for running the sensor * helpers, running calculations on their data, and determining * the quality of the user's sleep based upon them. * * In the most practical sense, this class is responsible for * notifying it's delegate if it thinks that the user should be * woken up. The AlarmHelper will integrate that into the alarm * logic to determine if we want to act on that information. * ie, is it during the 30-minute pre-alarm phase? */ protocol SleepQualityMonitorDelegate { func userShouldWakeUp() } class SleepQualityMonitor: SoundMonitorDelegate, MotionMonitorDelegate { var delegate: SleepQualityMonitorDelegate! /* Sound config */ let soundMonitor: SoundMonitor // Keep track of time and intensity of sound var soundTimeData: [NSTimeInterval] = [] var soundIntensityData: [Double] = [] let soundDataMutex = NSObject() // Time-stamps where we think we heard motion var soundEvents: [NSTimeInterval] = [] let SOUND_CALCULATION_TIME_WINDOW: NSTimeInterval = 10.0 * 60.0 // 10 minutes (in seconds) let SOUND_CALCULATION_PERIOD: NSTimeInterval = 1.0 // seconds let SOUND_CALCULATION_INDEX_WINDOW: Int /* Motion config */ let motionMonitor: MotionMonitor // Keep track of time and intensity of movement var motionTimeData: [NSTimeInterval] = [] var motionIntensityData: [Double] = [] let motionDataMutex = NSObject() // Time-stamps where we think we saw motion var motionEvents: [NSTimeInterval] = [] let MOTION_CALCULATION_TIME_WINDOW: NSTimeInterval = 10.0 * 60.0 // 10 minutes (in seconds) let MOTION_SPIKE_SCALAR_THRESHOLD = 5.0 // 5x mean acceleration /* Data pruning job */ var dataPruningTimer: NSTimer? let DATA_PRUNING_PERIOD = 60.0 // seconds init() { // The number of items in the sound data to look at when calculating SOUND_CALCULATION_INDEX_WINDOW = Int(SOUND_CALCULATION_TIME_WINDOW / SOUND_CALCULATION_PERIOD) // Set up our sound monitor soundMonitor = SoundMonitor() soundMonitor.timerPeriod = SOUND_CALCULATION_PERIOD // Set up our motion monitor motionMonitor = MotionMonitor() // Set up the delegates soundMonitor.delegate = self motionMonitor.delegate = self } /* Public interface */ func startMonitoring() { NSLog("Starting sleep quality monitoring") // Make sure we're stopped stopMonitoring() // Clear out the data with_mutex(soundDataMutex) { self.soundTimeData = [] self.soundIntensityData = [] self.soundEvents = [] } with_mutex(motionDataMutex) { self.motionTimeData = [] self.motionIntensityData = [] self.motionEvents = [] } // Start up the monitoring soundMonitor.startRecording() motionMonitor.startMonitoring() } func stopMonitoring() { soundMonitor.stopRecording() motionMonitor.stopMonitoring() } /* Delegate handling */ // Handle receiving sound monitor data func receiveSoundMonitorData(intensity: Double) { // Perform this under a mutex to avoid data corruption with_mutex(soundDataMutex) { // Stash the timestamp and data self.soundTimeData.append(NSDate().timeIntervalSince1970) self.soundIntensityData.append(intensity) } // We have new data, so check to see if we should wake up checkAndNotify() } // Handle receiving motion monitor data func receiveMotionMonitorData(intensity: Double) { // Perform this under a mutex to avoid data corruption with_mutex(motionDataMutex) { // Stash the timestamp and data self.motionTimeData.append(NSDate().timeIntervalSince1970) self.motionIntensityData.append(intensity) } // See if this latest data point is considered a motion "event" self.checkLatestMotionDataPoint() // We have new data, so check to see if we should wake up checkAndNotify() } /* Event handling */ // Prune old data in a safe way // This should be called periodically to make sure we don't blow up memory. func pruneData(timer: NSTimer) { // Perform this under a mutex to avoid data corruption with_mutex(soundDataMutex) { let thresholdTime = NSDate().timeIntervalSince1970 - self.SOUND_CALCULATION_TIME_WINDOW let numElementsToKeep = self.soundTimeData.filter({ $0 >= thresholdTime }).count let firstElement = self.soundTimeData.count - numElementsToKeep let lastElement = self.soundTimeData.count - 1 self.soundTimeData = Array(self.soundTimeData[firstElement...lastElement]) self.soundIntensityData = Array(self.soundIntensityData[firstElement...lastElement]) } // Perform this under a mutex to avoid data corruption with_mutex(motionDataMutex) { let thresholdTime = NSDate().timeIntervalSince1970 - self.MOTION_CALCULATION_TIME_WINDOW let numElementsToKeep = self.motionTimeData.filter({ $0 >= thresholdTime }).count let firstElement = self.motionTimeData.count - numElementsToKeep let lastElement = self.motionTimeData.count - 1 self.motionTimeData = Array(self.motionTimeData[firstElement...lastElement]) self.motionIntensityData = Array(self.motionIntensityData[firstElement...lastElement]) } } /* Private functions */ // Basic locking functionality for the arrays func with_mutex(mutex: AnyObject, closure: () -> ()) { objc_sync_enter(mutex) closure() objc_sync_exit(mutex) } // Check if the microphone data thinks we should wake up // We're actually going to be checking to see if the user is falling // back asleep. This is working on the assumption that if the user is // naturally waking up, we should let them. We only want to activate // the alarm early if the user is in danger of falling back into deep // sleep before their alarm goes off. private func checkAndNotify() { if isUserFallingBackAsleep() { delegate.userShouldWakeUp() } } // Determine if the user is waking up right now private func isUserFallingBackAsleep() -> Bool { //let soundSlope = soundMonitorSlope() //NSLog("Sound monitor slope: \(soundSlope)") let tenMinutesAgo: NSTimeInterval = NSDate().timeIntervalSince1970 - 10.0 * 60.0 let twentyMinutesAgo: NSTimeInterval = tenMinutesAgo - 10.0 * 60.0 var isMovingLess = false // Perform this under a mutex to avoid bad reads with_mutex(motionDataMutex) { // Are there fewer motion events in the past 10 minutes than // in the 10 minutes prior? let numEventsInLastTenMinutes = self.motionEvents.filter({ tenMinutesAgo < $0 }).count let numEventsInLastTwentyMinutes = self.motionEvents.filter({ twentyMinutesAgo < $0 && $0 < tenMinutesAgo }).count isMovingLess = numEventsInLastTenMinutes < numEventsInLastTwentyMinutes } return isMovingLess } // Calculate a slope for the sound data private func soundMonitorSlope() -> Double { // Don't even bother if soundIntensityData.count > SOUND_CALCULATION_INDEX_WINDOW { // Get a slice of the `SOUND_CALCULATION_INDEX_WINDOW` most recent rows let recentSoundIntensityData = Array(soundIntensityData[ soundIntensityData.count-SOUND_CALCULATION_INDEX_WINDOW..<soundIntensityData.count ]) return LinearRegression.slope(recentSoundIntensityData, y: soundTimeData) } else { // Not enough data points. No slope. return 0.0 } } // Did the last event exceed our mean by a scalar threshold? private func checkLatestMotionDataPoint() { // Perform this under a mutex to avoid bad reads with_mutex(motionDataMutex) { // This is inefficient to do every time. The summation should be cached. let count = Double(self.motionIntensityData.count) // Need to have at least 2 data points if count >= 2 { let mean = self.motionIntensityData.reduce(0.0, combine: +) / count let latestIntensity = self.motionIntensityData[self.motionIntensityData.count-1] let previousIntensity = self.motionIntensityData[self.motionIntensityData.count-2] // If the latest reading is much higer than the mean and // is very different from the previous, save it as an event. if latestIntensity > (mean * self.MOTION_SPIKE_SCALAR_THRESHOLD) && (latestIntensity - previousIntensity) > mean { NSLog("Motion event: intensity=\(latestIntensity), mean=\(mean)") self.motionEvents.append(self.motionTimeData.last!) } } } } // Kicks off a periodic timer to prune data that's outside of our window private func startDataPruningTimer() { invalidateDataPruningTimer() dataPruningTimer = NSTimer.scheduledTimerWithTimeInterval( DATA_PRUNING_PERIOD, target: self, selector: "pruneData:", userInfo: nil, repeats: true ) } // Kill existing timer if it exists private func invalidateDataPruningTimer() { if let timer = dataPruningTimer { timer.invalidate() dataPruningTimer = nil } } }
7c0af6fa15cd91977f04d22ce6972589
33.125461
94
0.702206
false
false
false
false
ObjectAlchemist/OOUIKit
refs/heads/master
Sources/_UIKitDelegate/UIScrollViewDelegate/ManagingZooming/UIScrollViewDelegateZoom.swift
mit
1
// // UIScrollViewDelegateZoom.swift // OOUIKit // // Created by Karsten Litsche on 03.11.17. // import UIKit import OOBase public final class UIScrollViewDelegateZoom: NSObject, UIScrollViewDelegate { // MARK: - init fileprivate init( viewForZooming: @escaping (UIScrollView) -> OOView? = { _ in nil }, willBeginZooming: @escaping (UIScrollView, UIView?) -> OOExecutable = { _,_ in DoNothing() }, didEndZooming: @escaping (UIScrollView, UIView?, CGFloat) -> OOExecutable = { _,_,_ in DoNothing() }, didZoom: @escaping (UIScrollView) -> OOExecutable = { _ in DoNothing() } ) { self.viewForZooming = viewForZooming self.willBeginZooming = willBeginZooming self.didEndZooming = didEndZooming self.didZoom = didZoom super.init() } // MARK: - protocol: UIScrollViewDelegate public final func viewForZooming(in scrollView: UIScrollView) -> UIView? { return viewForZooming(scrollView)?.ui } public final func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { willBeginZooming(scrollView, view).execute() } public final func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { didEndZooming(scrollView, view, scale).execute() } public final func scrollViewDidZoom(_ scrollView: UIScrollView) { didZoom(scrollView).execute() } // MARK: - private private let viewForZooming: (UIScrollView) -> OOView? private let willBeginZooming: (UIScrollView, UIView?) -> OOExecutable private let didEndZooming: (UIScrollView, UIView?, CGFloat) -> OOExecutable private let didZoom: (UIScrollView) -> OOExecutable } public extension UIScrollViewDelegateZoom { convenience init( viewForZooming: @escaping (UIScrollView) -> OOView, willBeginZooming: @escaping (UIScrollView, UIView?) -> OOExecutable = { _,_ in DoNothing() }, didEndZooming: @escaping (UIScrollView, UIView?, CGFloat) -> OOExecutable = { _,_,_ in DoNothing() }, didZoom: @escaping (UIScrollView) -> OOExecutable = { _ in DoNothing() } ) { let viewForZooming: (UIScrollView) -> OOView? = viewForZooming self.init(viewForZooming: viewForZooming, willBeginZooming: willBeginZooming, didEndZooming: didEndZooming, didZoom: didZoom) } convenience init( willBeginZooming: @escaping (UIScrollView, UIView?) -> OOExecutable = { _,_ in DoNothing() }, didEndZooming: @escaping (UIScrollView, UIView?, CGFloat) -> OOExecutable = { _,_,_ in DoNothing() }, didZoom: @escaping (UIScrollView) -> OOExecutable = { _ in DoNothing() } ) { self.init(viewForZooming: { _ in nil }, willBeginZooming: willBeginZooming, didEndZooming: didEndZooming, didZoom: didZoom) } }
60665249b5de813755561506bd6fc5b4
37.893333
133
0.659925
false
false
false
false
finngaida/wwdc
refs/heads/master
2015/Finn Gaida/FGCategoryButton.swift
gpl-2.0
1
// // CategoryButton.swift // Finn Gaida // // Created by Finn Gaida on 18.04.15. // Copyright (c) 2015 Finn Gaida. All rights reserved. // import UIKit enum FGApp { case SunUp case Brightness case FabTap case PlateCollect case YouthEast case Kolumbus case apprupt } class FGCategoryButton: UIControl { var container = UIView() var containerRect = CGRectZero var delegate = FGViewController() var appDelegate = FGStoryController() var isApp:Bool = false var app:FGApp = FGApp.SunUp var icon = UIImageView() override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(rect: CGRect, title: NSString?, delegate: FGViewController) { super.init(frame: rect) self.frame = rect let shrinkFactor:CGFloat = 1.0 self.delegate = delegate containerRect = CGRectMake(self.frame.width * ((1 - shrinkFactor)/2), self.frame.width * ((1 - shrinkFactor)/2), self.frame.width * shrinkFactor, self.frame.width * shrinkFactor) let darkmode = NSUserDefaults.standardUserDefaults().boolForKey("darkmode") container.frame = containerRect container.backgroundColor = UIColor(white: 0.3, alpha: 0.5) container.layer.masksToBounds = true container.layer.cornerRadius = rect.width/6 container.autoresizesSubviews = true let blurView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark)) blurView.frame = CGRectMake(0, 0, container.frame.width, container.frame.height) container.addSubview(blurView) self.addSubview(container) let iconView = UIImageView(image: UIImage(named: "w\(title!.lowercaseString)")) iconView.frame = CGRectMake(container.frame.width * 0.2, container.frame.width * 0.2, container.frame.width * 0.6, container.frame.width * 0.6) container.addSubview(iconView) let titleLabel = UILabel(frame: CGRectMake(10, rect.height, rect.width - 20, rect.height*0.2)) titleLabel.backgroundColor = UIColor.clearColor() titleLabel.textColor = (darkmode) ? UIColor.whiteColor() : UIColor.blackColor() titleLabel.font = UIFont(name: "HelveticaNeue", size: rect.width/8) titleLabel.text = title as? String titleLabel.textAlignment = NSTextAlignment.Center self.addSubview(titleLabel) } init(app: FGApp, frame: CGRect) { super.init(frame: frame) self.isApp = true self.app = app icon = UIImageView(frame: CGRectMake(0, 0, self.frame.width, self.frame.height)) switch (app) { case .SunUp: icon.image = UIImage(named: "SunUp") case .Brightness: icon.image = UIImage(named: "Brightness") case .FabTap: icon.image = UIImage(named: "FabTap") case .PlateCollect: icon.image = UIImage(named: "PlateCollect") case .Kolumbus: icon.image = UIImage(named: "Kolumbus") case .YouthEast: icon.image = UIImage(named: "YouthEast") case .apprupt: icon.image = UIImage(named: "apprupt") } self.addSubview(icon) icon.layer.masksToBounds = true icon.layer.cornerRadius = self.frame.width/7 } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { touchDown(self) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { touchUp(self) } func touchDown(sender: FGCategoryButton) { let shrinkFactor:CGFloat = 0.95 // animate button to smaller state UIView.animateWithDuration(0.25, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in let newFrame = CGRectMake(self.containerRect.width * ((1 - shrinkFactor) / 2), self.containerRect.height * ((1 - shrinkFactor) / 2), self.frame.width * shrinkFactor, self.frame.height * shrinkFactor) sender.container.frame = newFrame if (self.isApp) { let ico = sender.subviews[0] ico.frame = CGRectMake(ico.frame.origin.x * shrinkFactor, ico.frame.origin.y * shrinkFactor, ico.frame.width * shrinkFactor, ico.frame.width * shrinkFactor) self.icon.frame = CGRectMake(self.icon.frame.origin.x + self.icon.frame.width * (1 - shrinkFactor), self.icon.frame.origin.y + self.icon.frame.height * (1 - shrinkFactor), self.icon.frame.width * shrinkFactor, self.icon.frame.width * shrinkFactor) } else { let ico = sender.subviews[0].subviews[1] ico.frame = CGRectMake(ico.frame.origin.x * shrinkFactor, ico.frame.origin.y * shrinkFactor, ico.frame.width * shrinkFactor, ico.frame.width * shrinkFactor) self.icon.frame = CGRectMake(self.icon.frame.origin.x + self.icon.frame.width * (1 - shrinkFactor), self.icon.frame.origin.y + self.icon.frame.height * (1 - shrinkFactor), self.icon.frame.width * shrinkFactor, self.icon.frame.width * shrinkFactor) } }, completion: nil) } func touchUp(sender: FGCategoryButton) { /*let point = (touches.first as! UITouch).locationInView(self as UIView) if (CGRectContainsPoint(self.frame, point)) { */ // add action if (self.isApp) { self.appDelegate.showApp(self.app) } else { self.delegate.showStory(self.tag) } //} // animate button to smaller state UIView.animateWithDuration(0.25, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in let newFrame = CGRectMake(0, 0, self.containerRect.width, self.containerRect.height) sender.container.frame = newFrame if (self.isApp) { let shrinkFactor:CGFloat = 0.95 let ico = sender.subviews[0] ico.frame = CGRectMake(ico.frame.origin.x / shrinkFactor, ico.frame.origin.y / shrinkFactor, ico.frame.width / shrinkFactor, ico.frame.width / shrinkFactor) self.icon.frame = CGRectMake(0, 0, self.frame.width, self.frame.height) } else { let shrinkFactor:CGFloat = 0.95 let ico = sender.subviews[0].subviews[1] ico.frame = CGRectMake(ico.frame.origin.x / shrinkFactor, ico.frame.origin.y / shrinkFactor, ico.frame.width / shrinkFactor, ico.frame.width / shrinkFactor) self.icon.frame = CGRectMake(0, 0, self.frame.width, self.frame.height) } }, completion: nil) } }
c2e8f9b33f2d3ada016b22057857c860
39.926136
263
0.610995
false
false
false
false
ITzTravelInTime/TINU
refs/heads/development
TINU/SharedVariables.swift
gpl-2.0
1
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Cocoa //here there are all the variables that are accessible in all the app to determinate the status of the app and what it is doing let toggleRecoveryModeShadows = true public var look: UIManager.AppLook{ /* struct MEM{ static var result: UIManager.AppLook! = nil } if let r = MEM.result{ return r } var ret: UIManager.AppLook! = nil if let lk = simulateLook, ret == nil{ print("Forcing a simulated Theme \(lk.rawValue)") ret = lk } if (Recovery.status && !toggleRecoveryModeShadows && (ret == nil)){ print("Recovery theme will be used") ret = .recovery } if #available(macOS 11.0, *), ret == nil { print("Shadows SF Symbols theme will be used") ret = .shadowsSFSymbolsFill }else{ print("Shadows Old Icons theme will be used") } MEM.result = ret ?? .shadowsOldIcons return MEM.result! */ return .status }
e9aa513bc4612788a6a68a612b0e7846
26.783333
127
0.736053
false
false
false
false
material-components/material-components-ios
refs/heads/develop
components/ButtonBar/tests/unit/ButtonBarObservationTests.swift
apache-2.0
2
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import MaterialComponents.MaterialButtonBar import MaterialComponents.MaterialButtons class ButtonBarObservationTests: XCTestCase { var buttonBar: MDCButtonBar! override func setUp() { buttonBar = MDCButtonBar() } // Create a solid color image for testing purposes. private func createImage(colored color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSize(width: 64, height: 64), true, 1) color.setFill() UIRectFill(CGRect(x: 0, y: 0, width: 64, height: 64)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } // MARK: Initial state func testInitialTextButtonStateMatchesItemState() { // Given let item = UIBarButtonItem(title: "LEFT", style: .plain, target: nil, action: nil) // When buttonBar.items = [item] buttonBar.layoutSubviews() // Then let titles = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.title(for: .normal) } XCTAssertEqual(titles, [item.title!]) } func testInitialImageButtonStateMatchesItemState() { // Given let image1 = createImage(colored: .red) let item = UIBarButtonItem(image: image1, style: .plain, target: nil, action: nil) // When buttonBar.items = [item] buttonBar.layoutSubviews() // Then let images = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.image(for: .normal) } XCTAssertEqual(images, [item.image!]) } func testInitialGeneralStateMatchesItemState() { // Given let item = UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil) // When item.accessibilityHint = "Hint" item.accessibilityIdentifier = "Identifier" item.accessibilityLabel = "Label" item.accessibilityValue = "Value" item.isEnabled = true item.tag = 100 item.tintColor = .blue buttonBar.items = [item] buttonBar.layoutSubviews() // Then let accessibilityHints = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.accessibilityHint } XCTAssertEqual(accessibilityHints, [item.accessibilityHint!]) let accessibilityIdentifiers = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.accessibilityIdentifier } XCTAssertEqual(accessibilityIdentifiers, [item.accessibilityIdentifier!]) let accessibilityLabels = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.accessibilityLabel } XCTAssertEqual(accessibilityLabels, [item.accessibilityLabel!]) let accessibilityValues = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.accessibilityValue } XCTAssertEqual(accessibilityValues, [item.accessibilityValue!]) let enabled = buttonBar.subviews.compactMap { $0 as? MDCButton }.map { $0.isEnabled } XCTAssertEqual(enabled, [item.isEnabled]) let tags = buttonBar.subviews.compactMap { $0 as? MDCButton }.map { $0.tag } XCTAssertEqual(tags, [item.tag]) let tintColors = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.tintColor } XCTAssertEqual(tintColors, [item.tintColor!]) } // MARK: KVO observation func testAccessibilityHintChangesAreObserved() { // Given let item = UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil) item.accessibilityHint = "Hint" buttonBar.items = [item] buttonBar.layoutSubviews() // When item.accessibilityHint = "Other hint" // Then let accessibilityLabels = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.accessibilityHint } XCTAssertEqual(accessibilityLabels, [item.accessibilityHint!]) } func testAccessibilityIdentifierChangesAreObserved() { // Given let item = UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil) item.accessibilityIdentifier = "Identifier" buttonBar.items = [item] buttonBar.layoutSubviews() // When item.accessibilityIdentifier = "Other identifier" // Then let accessibilityIdentifiers = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.accessibilityIdentifier } XCTAssertEqual(accessibilityIdentifiers, [item.accessibilityIdentifier!]) } func testAccessibilityLabelChangesAreObserved() { // Given let item = UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil) item.accessibilityLabel = "Label" buttonBar.items = [item] buttonBar.layoutSubviews() // When item.accessibilityLabel = "Other label" // Then let accessibilityLabels = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.accessibilityLabel } XCTAssertEqual(accessibilityLabels, [item.accessibilityLabel!]) } func testAccessibilityValueChangesAreObserved() { // Given let item = UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil) item.accessibilityValue = "Value" buttonBar.items = [item] buttonBar.layoutSubviews() // When item.accessibilityValue = "Other value" // Then let accessibilityValues = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.accessibilityValue } XCTAssertEqual(accessibilityValues, [item.accessibilityValue!]) } func testEnabledChangesAreObserved() { // Given let item = UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil) item.isEnabled = true buttonBar.items = [item] buttonBar.layoutSubviews() // When item.isEnabled = false // Then let enabled = buttonBar.subviews.compactMap { $0 as? MDCButton }.map { $0.isEnabled } XCTAssertEqual(enabled, [item.isEnabled]) } func testImageChangesAreObserved() { // Given let image1 = createImage(colored: .red) let item = UIBarButtonItem(image: image1, style: .plain, target: nil, action: nil) buttonBar.items = [item] buttonBar.layoutSubviews() // When item.image = createImage(colored: .blue) // Then let images = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.image(for: .normal) } XCTAssertEqual(images, [item.image!]) } func testTagChangesAreObserved() { // Given let item = UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil) item.tag = 100 buttonBar.items = [item] buttonBar.layoutSubviews() // When item.tag = 50 // Then let tags = buttonBar.subviews.compactMap { $0 as? MDCButton }.map { $0.tag } XCTAssertEqual(tags, [item.tag]) } func testTintColorChangesAreObserved() { // Given let item = UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil) item.tintColor = .blue buttonBar.items = [item] buttonBar.layoutSubviews() // When item.tintColor = .red // Then let tintColors = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.tintColor } XCTAssertEqual(tintColors, [item.tintColor!]) // Verify that the tint color reverts to the default item.tintColor = nil do { let tintColors = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.tintColor } XCTAssertEqual(tintColors, [buttonBar.tintColor]) } } func testTintColorChangeToNilIsObservedAndReset() { // Given let item = UIBarButtonItem(title: "Title", style: .plain, target: nil, action: nil) item.tintColor = .blue buttonBar.items = [item] buttonBar.layoutSubviews() // When item.tintColor = nil // Then let tintColors = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.tintColor } XCTAssertEqual(tintColors, [buttonBar.tintColor]) } func testTitleChangesAreObserved() { // Given let item = UIBarButtonItem(title: "LEFT", style: .plain, target: nil, action: nil) buttonBar.items = [item] buttonBar.layoutSubviews() // When item.title = "NEW TITLE" // Then let titles = buttonBar.subviews.compactMap { $0 as? MDCButton }.compactMap { $0.title(for: .normal) } XCTAssertEqual(titles, [item.title!]) } }
b337ea503a8ad6978bd1152afbee273a
31.278388
99
0.691897
false
true
false
false
ReactiveX/RxSwift
refs/heads/main
RxExample/RxExample/Examples/SimpleValidation/SimpleValidationViewController.swift
mit
1
// // SimpleValidationViewController.swift // RxExample // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit import RxSwift import RxCocoa private let minimalUsernameLength = 5 private let minimalPasswordLength = 5 class SimpleValidationViewController : ViewController { @IBOutlet weak var usernameOutlet: UITextField! @IBOutlet weak var usernameValidOutlet: UILabel! @IBOutlet weak var passwordOutlet: UITextField! @IBOutlet weak var passwordValidOutlet: UILabel! @IBOutlet weak var doSomethingOutlet: UIButton! override func viewDidLoad() { super.viewDidLoad() usernameValidOutlet.text = "Username has to be at least \(minimalUsernameLength) characters" passwordValidOutlet.text = "Password has to be at least \(minimalPasswordLength) characters" let usernameValid = usernameOutlet.rx.text.orEmpty .map { $0.count >= minimalUsernameLength } .share(replay: 1) // without this map would be executed once for each binding, rx is stateless by default let passwordValid = passwordOutlet.rx.text.orEmpty .map { $0.count >= minimalPasswordLength } .share(replay: 1) let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 } .share(replay: 1) usernameValid .bind(to: passwordOutlet.rx.isEnabled) .disposed(by: disposeBag) usernameValid .bind(to: usernameValidOutlet.rx.isHidden) .disposed(by: disposeBag) passwordValid .bind(to: passwordValidOutlet.rx.isHidden) .disposed(by: disposeBag) everythingValid .bind(to: doSomethingOutlet.rx.isEnabled) .disposed(by: disposeBag) doSomethingOutlet.rx.tap .subscribe(onNext: { [weak self] _ in self?.showAlert() }) .disposed(by: disposeBag) } func showAlert() { let alert = UIAlertController( title: "RxExample", message: "This is wonderful", preferredStyle: .alert ) let defaultAction = UIAlertAction(title: "Ok", style: .default, handler: nil) alert.addAction(defaultAction) present(alert, animated: true, completion: nil) } }
63423eb4b0c288be67e8cf125bbd3333
31.197368
117
0.631385
false
false
false
false
material-motion/material-motion-swift
refs/heads/develop
Pods/MaterialMotion/src/interactions/SlopRegion.swift
apache-2.0
2
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit /** Changes the direction of a transition when the provided pan gesture recognizer moves out of or back into a slop region. **Constraints** Either the x or y axis can be selected. The default axis is y. */ public final class SlopRegion: Interaction { /** The gesture recognizer that will be observed by this interaction. */ public let gesture: UIPanGestureRecognizer? /** The size of the slop region. */ public let size: CGFloat public init(withTranslationOf gesture: UIPanGestureRecognizer?, size: CGFloat) { self.gesture = gesture self.size = size } /** The axis to observe. */ public enum Axis { /** Observes the x axis. */ case x /** Observes the y axis. */ case y } public func add(to direction: ReactiveProperty<TransitionDirection>, withRuntime runtime: MotionRuntime, constraints axis: Axis?) { guard let gesture = gesture else { return } let axis = axis ?? .y let chooseAxis: (MotionObservable<CGPoint>) -> MotionObservable<CGFloat> switch axis { case .x: chooseAxis = { $0.x() } case .y: chooseAxis = { $0.y() } } runtime.connect(chooseAxis(runtime.get(gesture).translation(in: runtime.containerView)) .slop(size: size).rewrite([.onExit: .backward, .onReturn: .forward]), to: direction) } }
da71e254f9ae3765a64a1b534831f6f7
25.605263
133
0.687438
false
false
false
false
muhlenXi/SwiftEx
refs/heads/master
projects/FindLover/FindLover/ViewController.swift
mit
1
// // ViewController.swift // FindLover // // Created by 席银军 on 2017/8/16. // Copyright © 2017年 muhlenXi. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - IBOutlet @IBOutlet weak var name: UITextField! @IBOutlet weak var sex: UISegmentedControl! @IBOutlet weak var birthday: UIDatePicker! @IBOutlet weak var height: UILabel! @IBOutlet weak var hasProperty: UISwitch! @IBOutlet weak var info: UITextView! // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Event responnse @IBAction func sliderValueChanged(_ sender: UISlider) { let value = Int(sender.value) sender.value = Float(value) height.text = "\(value)cm" } @IBAction func okAction(_ sender: Any) { if let nameText = name.text, let heightText = height.text { let sexText = sex.selectedSegmentIndex == 0 ? "高富帅" : "白富美" let gregorian = Calendar(identifier: .gregorian) let components = gregorian.dateComponents([Calendar.Component.year], from: birthday.date, to: Date()) var ageText = "" if let age = components.year { ageText = "\(age)" } let hasPropertyText = hasProperty.isOn ? "有房" : "无房" info.text = "我是\(nameText),\(sexText),\(ageText)岁,身高\(heightText),目前\(hasPropertyText),求交往!" } } } // MARK: - UITextFieldDelegate extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
fed24fe7d7db8866de87740bff45fb32
26.324324
113
0.592483
false
false
false
false
externl/ice
refs/heads/3.7
swift/src/Ice/Incoming.swift
gpl-2.0
4
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import IceImpl import PromiseKit public final class Incoming { private let current: Current private var format: FormatType private let istr: InputStream private let responseCallback: ICEBlobjectResponse private let exceptionCallback: ICEBlobjectException private var servant: Disp? private var locator: ServantLocator? private var cookie: AnyObject? private var ostr: OutputStream! // must be set before calling responseCallback private var ok: Bool // false if response contains a UserException init(istr: InputStream, response: @escaping ICEBlobjectResponse, exception: @escaping ICEBlobjectException, current: Current) { self.istr = istr format = .DefaultFormat ok = true responseCallback = response exceptionCallback = exception self.current = current } public func readEmptyParams() throws { // // Remember the encoding used by the input parameters, we'll // encode the response parameters with the same encoding. // current.encoding = try istr.skipEmptyEncapsulation() } public func readParamEncaps() throws -> Data { let params = try istr.readEncapsulation() current.encoding = params.encoding return params.bytes } public func read<T>(_ cb: (InputStream) throws -> T) throws -> T { // // Remember the encoding used by the input parameters, we'll // encode the response parameters with the same encoding. // current.encoding = try istr.startEncapsulation() let l = try cb(istr) try istr.endEncapsulation() return l } public func startOver() { istr.startOver() ostr = nil } public func writeParamEncaps(ok: Bool, outParams: Data) -> OutputStream { let ostr = OutputStream(communicator: istr.communicator, encoding: current.encoding) if outParams.isEmpty { ostr.writeEmptyEncapsulation(current.encoding) } else { ostr.writeEncapsulation(outParams) } self.ok = ok return ostr } public func response() { guard locator == nil || servantLocatorFinished() else { return } precondition(ostr != nil, "OutputStream was not set before calling response()") ostr.finished().withUnsafeBytes { responseCallback(ok, $0.baseAddress!, $0.count) } } public func exception(_ ex: Error) { guard locator == nil || servantLocatorFinished() else { return } handleException(ex) } public func setFormat(_ format: FormatType) { self.format = format } @discardableResult public func setResult(_ os: OutputStream) -> Promise<OutputStream>? { ostr = os return nil // Response is cached in the Incoming to not have to create unnecessary promise } public func setResult() -> Promise<OutputStream>? { let ostr = OutputStream(communicator: istr.communicator) ostr.writeEmptyEncapsulation(current.encoding) self.ostr = ostr return nil // Response is cached in the Incoming to not have to create unnecessary future } public func setResult(_ cb: (OutputStream) -> Void) -> Promise<OutputStream>? { let ostr = OutputStream(communicator: istr.communicator) ostr.startEncapsulation(encoding: current.encoding, format: format) cb(ostr) ostr.endEncapsulation() self.ostr = ostr return nil // Response is cached in the Incoming to not have to create unnecessary future } public func setResultPromise(_ p: Promise<Void>) -> Promise<OutputStream> { // Use the thread which fulfilled the promise (on: nil) return p.map(on: nil) { let ostr = OutputStream(communicator: self.istr.communicator) ostr.writeEmptyEncapsulation(self.current.encoding) return ostr } } public func setResultPromise<T>(_ p: Promise<T>, _ cb: @escaping (OutputStream, T) -> Void) -> Promise<OutputStream> { // Use the thread which fulfilled the promise (on: nil) return p.map(on: nil) { t in let ostr = OutputStream(communicator: self.istr.communicator) ostr.startEncapsulation(encoding: self.current.encoding, format: self.format) cb(ostr, t) ostr.endEncapsulation() return ostr } } func servantLocatorFinished() -> Bool { guard let locator = locator, let servant = servant else { preconditionFailure() } do { try locator.finished(curr: current, servant: servant, cookie: cookie) return true } catch { handleException(error) } return false } func invoke(_ servantManager: ServantManager) { servant = servantManager.findServant(id: current.id, facet: current.facet) if servant == nil { locator = servantManager.findServantLocator(category: current.id.category) if locator == nil, !current.id.category.isEmpty { locator = servantManager.findServantLocator(category: "") } if let locator = locator { do { let locatorReturn = try locator.locate(current) (servant, cookie) = (locatorReturn.returnValue, locatorReturn.cookie) } catch { handleException(error) return } } } guard let s = servant else { do { if servantManager.hasServant(id: current.id) || servantManager.isAdminId(current.id) { throw FacetNotExistException(id: current.id, facet: current.facet, operation: current.operation) } else { throw ObjectNotExistException(id: current.id, facet: current.facet, operation: current.operation) } } catch { exceptionCallback(convertException(error)) return } } // // Dispatch in the incoming call // do { // Request was dispatched asynchronously if promise is non-nil if let promise = try s.dispatch(request: self, current: current) { // Use the thread which fulfilled the promise (on: nil) promise.done(on: nil) { ostr in self.ostr = ostr self.response() }.catch(on: nil) { error in self.exception(error) } } else { response() } } catch { exception(error) } } func handleException(_ exception: Error) { guard let e = exception as? UserException else { exceptionCallback(convertException(exception)) return } ok = false // response will contain a UserException let ostr = OutputStream(communicator: istr.communicator) ostr.startEncapsulation(encoding: current.encoding, format: format) ostr.write(e) ostr.endEncapsulation() ostr.finished().withUnsafeBytes { responseCallback(ok, $0.baseAddress!, $0.count) } } func convertException(_ exception: Error) -> ICERuntimeException { // // 1. run-time exceptions that travel over the wire // 2. other LocalExceptions and UserExceptions // 3. all other exceptions are LocalException // switch exception { // 1. Known run-time exceptions case let exception as ObjectNotExistException: let e = ICEObjectNotExistException() e.file = exception.file e.line = Int32(exception.line) e.name = exception.id.name e.category = exception.id.category e.facet = exception.facet e.operation = exception.operation return e case let exception as FacetNotExistException: let e = ICEFacetNotExistException() e.file = exception.file e.line = Int32(exception.line) e.name = exception.id.name e.category = exception.id.category e.facet = exception.facet e.operation = exception.operation return e case let exception as OperationNotExistException: let e = ICEOperationNotExistException() e.file = exception.file e.line = Int32(exception.line) e.name = exception.id.name e.category = exception.id.category e.facet = exception.facet e.operation = exception.operation return e case let exception as UnknownUserException: let e = ICEUnknownUserException() e.file = exception.file e.line = Int32(exception.line) e.unknown = exception.unknown return e case let exception as UnknownLocalException: let e = ICEUnknownLocalException() e.file = exception.file e.line = Int32(exception.line) e.unknown = exception.unknown return e case let exception as UnknownException: let e = ICEUnknownException() e.file = exception.file e.line = Int32(exception.line) e.unknown = exception.unknown return e // 2. Other LocalExceptions and UserExceptions case let exception as LocalException: let e = ICEUnknownLocalException() e.file = exception.file e.line = Int32(exception.line) e.unknown = "\(exception)" return e case let exception as UserException: let e = ICEUnknownUserException() e.unknown = "\(exception.ice_id())" return e // 3. Unknown exceptions default: let e = ICEUnknownException() e.file = #file e.line = Int32(#line) e.unknown = "\(exception)" return e } } }
d8efa9dfed424242b33ac75cb99c8acb
33.949495
117
0.584682
false
false
false
false
Ivacker/swift
refs/heads/master
stdlib/public/core/ArrayBuffer.swift
apache-2.0
9
//===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// // // This is the class that implements the storage and object management for // Swift Array. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims internal typealias _ArrayBridgeStorage = _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCoreType> public struct _ArrayBuffer<Element> : _ArrayBufferType { /// Create an empty buffer. public init() { _storage = _ArrayBridgeStorage(native: _emptyArrayStorage) } public init(nsArray: _NSArrayCoreType) { _sanityCheck(_isClassOrObjCExistential(Element.self)) _storage = _ArrayBridgeStorage(objC: nsArray) } /// Returns an `_ArrayBuffer<U>` containing the same elements. /// /// - Requires: The elements actually have dynamic type `U`, and `U` /// is a class or `@objc` existential. @warn_unused_result func castToBufferOf<U>(_: U.Type) -> _ArrayBuffer<U> { _sanityCheck(_isClassOrObjCExistential(Element.self)) _sanityCheck(_isClassOrObjCExistential(U.self)) return _ArrayBuffer<U>(storage: _storage) } /// The spare bits that are set when a native array needs deferred /// element type checking. var deferredTypeCheckMask : Int { return 1 } /// Returns an `_ArrayBuffer<U>` containing the same elements, /// deffering checking each element's `U`-ness until it is accessed. /// /// - Requires: `U` is a class or `@objc` existential derived from `Element`. @warn_unused_result func downcastToBufferWithDeferredTypeCheckOf<U>( _: U.Type ) -> _ArrayBuffer<U> { _sanityCheck(_isClassOrObjCExistential(Element.self)) _sanityCheck(_isClassOrObjCExistential(U.self)) // FIXME: can't check that U is derived from Element pending // <rdar://problem/19915280> generic metatype casting doesn't work // _sanityCheck(U.self is Element.Type) return _ArrayBuffer<U>( storage: _ArrayBridgeStorage( native: _native._storage, bits: deferredTypeCheckMask)) } var needsElementTypeCheck: Bool { // NSArray's need an element typecheck when the element type isn't AnyObject return !_isNativeTypeChecked && !(AnyObject.self is Element.Type) } //===--- private --------------------------------------------------------===// internal init(storage: _ArrayBridgeStorage) { _storage = storage } internal var _storage: _ArrayBridgeStorage } extension _ArrayBuffer { /// Adopt the storage of `source`. public init(_ source: NativeBuffer, shiftedToStartIndex: Int) { _sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") _storage = _ArrayBridgeStorage(native: source._storage) } var arrayPropertyIsNative : Bool { return _isNative } /// `true`, if the array is native and does not need a deferred type check. var arrayPropertyIsNativeTypeChecked : Bool { return _isNativeTypeChecked } /// Returns `true` iff this buffer's storage is uniquely-referenced. @warn_unused_result mutating func isUniquelyReferenced() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferenced_native_noSpareBits() } return _storage.isUniquelyReferencedNative() && _isNative } /// Returns `true` iff this buffer's storage is either /// uniquely-referenced or pinned. @warn_unused_result mutating func isUniquelyReferencedOrPinned() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferencedOrPinned_native_noSpareBits() } return _storage.isUniquelyReferencedOrPinnedNative() && _isNative } /// Convert to an NSArray. /// /// - Precondition: `_isBridgedToObjectiveC(Element.self)`. /// O(1) if the element type is bridged verbatim, O(N) otherwise. @warn_unused_result public func _asCocoaArray() -> _NSArrayCoreType { _sanityCheck( _isBridgedToObjectiveC(Element.self), "Array element type is not bridged to Objective-C") return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative } /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the self /// buffer store minimumCapacity elements, returns that buffer. /// Otherwise, returns `nil`. @warn_unused_result public mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> NativeBuffer? { if _fastPath(isUniquelyReferenced()) { let b = _native if _fastPath(b.capacity >= minimumCapacity) { return b } } return nil } @warn_unused_result public mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } @warn_unused_result public mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @warn_unused_result public func requestNativeBuffer() -> NativeBuffer? { if !_isClassOrObjCExistential(Element.self) { return _native } return _fastPath(_storage.isNative) ? _native : nil } // We have two versions of type check: one that takes a range and the other // checks one element. The reason for this is that the ARC optimizer does not // handle loops atm. and so can get blocked by the presence of a loop (over // the range). This loop is not necessary for a single element access. @inline(never) internal func _typeCheckSlowPath(index: Int) { if _fastPath(_isNative) { let element: AnyObject = castToBufferOf(AnyObject.self)._native[index] _precondition( element is Element, "Down-casted Array element failed to match the target type") } else { let ns = _nonNative _precondition( ns.objectAtIndex(index) is Element, "NSArray element failed to match the Swift Array Element type") } } func _typeCheck(subRange: Range<Int>) { if !_isClassOrObjCExistential(Element.self) { return } if _slowPath(needsElementTypeCheck) { // Could be sped up, e.g. by using // enumerateObjectsAtIndexes:options:usingBlock: in the // non-native case. for i in subRange { _typeCheckSlowPath(i) } } } /// Copy the given subRange of this buffer into uninitialized memory /// starting at target. Return a pointer past-the-end of the /// just-initialized memory. @inline(never) // The copy loop blocks retain release matching. public func _uninitializedCopy( subRange: Range<Int>, target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _typeCheck(subRange) if _fastPath(_isNative) { return _native._uninitializedCopy(subRange, target: target) } let nonNative = _nonNative let nsSubRange = SwiftShims._SwiftNSRange( location:subRange.startIndex, length: subRange.endIndex - subRange.startIndex) let buffer = UnsafeMutablePointer<AnyObject>(target) // Copies the references out of the NSArray without retaining them nonNative.getObjects(buffer, range: nsSubRange) // Make another pass to retain the copied objects var result = target for _ in subRange { result.initialize(result.memory) ++result } return result } /// Return a `_SliceBuffer` containing the given `subRange` of values /// from this buffer. public subscript(subRange: Range<Int>) -> _SliceBuffer<Element> { get { _typeCheck(subRange) if _fastPath(_isNative) { return _native[subRange] } // Look for contiguous storage in the NSArray let nonNative = self._nonNative let cocoa = _CocoaArrayWrapper(nonNative) let cocoaStorageBaseAddress = cocoa.contiguousStorage(self.indices) if cocoaStorageBaseAddress != nil { return _SliceBuffer( owner: nonNative, subscriptBaseAddress: UnsafeMutablePointer(cocoaStorageBaseAddress), indices: subRange, hasNativeBuffer: false) } // No contiguous storage found; we must allocate let subRangeCount = subRange.count let result = _ContiguousArrayBuffer<Element>( count: subRangeCount, minimumCapacity: 0) // Tell Cocoa to copy the objects into our storage cocoa.buffer.getObjects( UnsafeMutablePointer(result.firstElementAddress), range: _SwiftNSRange( location: subRange.startIndex, length: subRangeCount)) return _SliceBuffer(result, shiftedToStartIndex: subRange.startIndex) } set { fatalError("not implemented") } } public var _unconditionalMutableSubscriptBaseAddress: UnsafeMutablePointer<Element> { _sanityCheck(_isNative, "must be a native buffer") return _native.firstElementAddress } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. public var firstElementAddress: UnsafeMutablePointer<Element> { if (_fastPath(_isNative)) { return _native.firstElementAddress } return nil } /// The number of elements the buffer stores. public var count: Int { @inline(__always) get { return _fastPath(_isNative) ? _native.count : _nonNative.count } set { _sanityCheck(_isNative, "attempting to update count of Cocoa array") _native.count = newValue } } /// Traps if an inout violation is detected or if the buffer is /// native and the subscript is out of range. /// /// wasNative == _isNative in the absence of inout violations. /// Because the optimizer can hoist the original check it might have /// been invalidated by illegal user code. internal func _checkInoutAndNativeBounds(index: Int, wasNative: Bool) { _precondition( _isNative == wasNative, "inout rules were violated: the array was overwritten") if _fastPath(wasNative) { _native._checkValidSubscript(index) } } // TODO: gyb this /// Traps if an inout violation is detected or if the buffer is /// native and typechecked and the subscript is out of range. /// /// wasNativeTypeChecked == _isNativeTypeChecked in the absence of /// inout violations. Because the optimizer can hoist the original /// check it might have been invalidated by illegal user code. internal func _checkInoutAndNativeTypeCheckedBounds( index: Int, wasNativeTypeChecked: Bool ) { _precondition( _isNativeTypeChecked == wasNativeTypeChecked, "inout rules were violated: the array was overwritten") if _fastPath(wasNativeTypeChecked) { _native._checkValidSubscript(index) } } /// The number of elements the buffer can store without reallocation. public var capacity: Int { return _fastPath(_isNative) ? _native.capacity : _nonNative.count } @inline(__always) @warn_unused_result func getElement(i: Int, wasNativeTypeChecked: Bool) -> Element { if _fastPath(wasNativeTypeChecked) { return _nativeTypeChecked[i] } return unsafeBitCast(_getElementSlowPath(i), Element.self) } @inline(never) @warn_unused_result func _getElementSlowPath(i: Int) -> AnyObject { _sanityCheck( _isClassOrObjCExistential(Element.self), "Only single reference elements can be indexed here.") let element: AnyObject if _isNative { // _checkInoutAndNativeTypeCheckedBounds does no subscript // checking for the native un-typechecked case. Therefore we // have to do it here. _native._checkValidSubscript(i) element = castToBufferOf(AnyObject.self)._native[i] _precondition( element is Element, "Down-casted Array element failed to match the target type") } else { // ObjC arrays do their own subscript checking. element = _nonNative.objectAtIndex(i) _precondition( element is Element, "NSArray element failed to match the Swift Array Element type") } return element } /// Get or set the value of the ith element. public subscript(i: Int) -> Element { get { return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked) } nonmutating set { if _fastPath(_isNative) { _native[i] = newValue } else { var refCopy = self refCopy.replace( subRange: i...i, with: 1, elementsOf: CollectionOfOne(newValue)) } } } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. public func withUnsafeBufferPointer<R>( @noescape body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { if _fastPath(_isNative) { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } return try ContiguousArray(self).withUnsafeBufferPointer(body) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Requires: Such contiguous storage exists or the buffer is empty. public mutating func withUnsafeMutableBufferPointer<R>( @noescape body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _sanityCheck( firstElementAddress != nil || count == 0, "Array is bridging an opaque NSArray; can't get a pointer to the elements" ) defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } /// An object that keeps the elements stored in this buffer alive. public var owner: AnyObject { return _fastPath(_isNative) ? _native._storage : _nonNative } /// An object that keeps the elements stored in this buffer alive. /// /// - Requires: This buffer is backed by a `_ContiguousArrayBuffer`. public var nativeOwner: AnyObject { _sanityCheck(_isNative, "Expect a native array") return _native._storage } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. public var identity: UnsafePointer<Void> { if _isNative { return _native.identity } else { return unsafeAddressOf(_nonNative) } } //===--- CollectionType conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Int { return count } //===--- private --------------------------------------------------------===// typealias Storage = _ContiguousArrayStorage<Element> public typealias NativeBuffer = _ContiguousArrayBuffer<Element> var _isNative: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNative } } /// `true`, if the array is native and does not need a deferred type check. var _isNativeTypeChecked: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask) } } /// Our native representation. /// /// - Requires: `_isNative`. var _native: NativeBuffer { return NativeBuffer( _isClassOrObjCExistential(Element.self) ? _storage.nativeInstance : _storage.nativeInstance_noSpareBits) } /// Fast access to the native representation. /// /// - Requires: `_isNativeTypeChecked`. var _nativeTypeChecked: NativeBuffer { return NativeBuffer(_storage.nativeInstance_noSpareBits) } var _nonNative: _NSArrayCoreType { @inline(__always) get { _sanityCheck(_isClassOrObjCExistential(Element.self)) return _storage.objCInstance } } } #endif
7c595ecff59db6fe3e27ad257d054bdb
31.309615
80
0.666746
false
false
false
false
18775134221/SwiftBase
refs/heads/develop
04-observables-in-practice/starter/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift
apache-2.0
38
// // Bag+Rx.swift // RxSwift // // Created by Krunoslav Zaher on 10/19/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation // MARK: forEach extension Bag where T: ObserverType { /// Dispatches `event` to app observers contained inside bag. /// /// - parameter action: Enumeration closure. func on(_ event: Event<T.E>) { if _onlyFastPath { _value0?.on(event) return } let value0 = _value0 let dictionary = _dictionary if let value0 = value0 { value0.on(event) } if let dictionary = dictionary { for element in dictionary.values { element.on(event) } } } } /// Dispatches `dispose` to all disposables contained inside bag. func disposeAll(in bag: Bag<Disposable>) { if bag._onlyFastPath { bag._value0?.dispose() return } let value0 = bag._value0 let dictionary = bag._dictionary if let value0 = value0 { value0.dispose() } if let dictionary = dictionary { for element in dictionary.values { element.dispose() } } }
98aabdb32135346de40f7d806c35443d
19.758621
65
0.563123
false
false
false
false
sschiau/swift-package-manager
refs/heads/master
Sources/PackageDescription4/Target.swift
apache-2.0
1
/* This source file is part of the Swift.org open source project Copyright (c) 2018 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 Swift project authors */ /// The description for an individual target. public final class Target { /// The type of this target. public enum TargetType: String, Encodable { case regular case test case system } /// Represents a target's dependency on another entity. public enum Dependency { #if PACKAGE_DESCRIPTION_4 case targetItem(name: String) case productItem(name: String, package: String?) case byNameItem(name: String) #else case _targetItem(name: String) case _productItem(name: String, package: String?) case _byNameItem(name: String) #endif } /// The name of the target. public var name: String /// The path of the target, relative to the package root. /// /// If nil, package manager will search the predefined paths to look /// for this target. public var path: String? /// The source files in this target. /// /// If nil, all valid source files found in the target's path will be included. /// /// This can contain directories and individual source files. Directories /// will be searched recursively for valid source files. /// /// Paths specified are relative to the target path. public var sources: [String]? /// List of paths to be excluded from source inference. /// /// Exclude paths are relative to the target path. /// This property has more precedence than sources property. public var exclude: [String] /// If this is a test target. public var isTest: Bool { return type == .test } /// Dependencies on other entities inside or outside the package. public var dependencies: [Dependency] /// The path to the directory containing public headers of a C language target. /// /// If a value is not provided, the directory will be set to "include". public var publicHeadersPath: String? /// The type of target. public let type: TargetType /// `pkgconfig` name to use for system library target. If present, swiftpm will try to /// search for <name>.pc file to get the additional flags needed for the /// system target. public let pkgConfig: String? /// Providers array for the System library target. public let providers: [SystemPackageProvider]? /// C build settings. var cSettings: [CSetting]? /// C++ build settings. var cxxSettings: [CXXSetting]? /// Swift build settings. var swiftSettings: [SwiftSetting]? /// Linker build settings. var linkerSettings: [LinkerSetting]? /// Construct a target. private init( name: String, dependencies: [Dependency], path: String?, exclude: [String], sources: [String]?, publicHeadersPath: String?, type: TargetType, pkgConfig: String? = nil, providers: [SystemPackageProvider]? = nil, cSettings: [CSetting]? = nil, cxxSettings: [CXXSetting]? = nil, swiftSettings: [SwiftSetting]? = nil, linkerSettings: [LinkerSetting]? = nil ) { self.name = name self.dependencies = dependencies self.path = path self.publicHeadersPath = publicHeadersPath self.sources = sources self.exclude = exclude self.type = type self.pkgConfig = pkgConfig self.providers = providers self.cSettings = cSettings self.cxxSettings = cxxSettings self.swiftSettings = swiftSettings self.linkerSettings = linkerSettings switch type { case .regular, .test: precondition(pkgConfig == nil && providers == nil) case .system: break } } public static func target( name: String, dependencies: [Dependency] = [], path: String? = nil, exclude: [String] = [], sources: [String]? = nil, publicHeadersPath: String? = nil, _cSettings: [CSetting]? = nil, _cxxSettings: [CXXSetting]? = nil, _swiftSettings: [SwiftSetting]? = nil, _linkerSettings: [LinkerSetting]? = nil ) -> Target { return Target( name: name, dependencies: dependencies, path: path, exclude: exclude, sources: sources, publicHeadersPath: publicHeadersPath, type: .regular, cSettings: _cSettings, cxxSettings: _cxxSettings, swiftSettings: _swiftSettings, linkerSettings: _linkerSettings ) } public static func testTarget( name: String, dependencies: [Dependency] = [], path: String? = nil, exclude: [String] = [], sources: [String]? = nil, _cSettings: [CSetting]? = nil, _cxxSettings: [CXXSetting]? = nil, _swiftSettings: [SwiftSetting]? = nil, _linkerSettings: [LinkerSetting]? = nil ) -> Target { return Target( name: name, dependencies: dependencies, path: path, exclude: exclude, sources: sources, publicHeadersPath: nil, type: .test, cSettings: _cSettings, cxxSettings: _cxxSettings, swiftSettings: _swiftSettings, linkerSettings: _linkerSettings ) } #if !PACKAGE_DESCRIPTION_4 public static func systemLibrary( name: String, path: String? = nil, pkgConfig: String? = nil, providers: [SystemPackageProvider]? = nil ) -> Target { return Target( name: name, dependencies: [], path: path, exclude: [], sources: nil, publicHeadersPath: nil, type: .system, pkgConfig: pkgConfig, providers: providers) } #endif } extension Target: Encodable { private enum CodingKeys: CodingKey { case name case path case sources case exclude case dependencies case publicHeadersPath case type case pkgConfig case providers case cSettings case cxxSettings case swiftSettings case linkerSettings } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(path, forKey: .path) try container.encode(sources, forKey: .sources) try container.encode(exclude, forKey: .exclude) try container.encode(dependencies, forKey: .dependencies) try container.encode(publicHeadersPath, forKey: .publicHeadersPath) try container.encode(type, forKey: .type) try container.encode(pkgConfig, forKey: .pkgConfig) try container.encode(providers, forKey: .providers) if let cSettings = self.cSettings { let cSettings = VersionedValue(cSettings, api: "cSettings", versions: [.v5]) try container.encode(cSettings, forKey: .cSettings) } if let cxxSettings = self.cxxSettings { let cxxSettings = VersionedValue(cxxSettings, api: "cxxSettings", versions: [.v5]) try container.encode(cxxSettings, forKey: .cxxSettings) } if let swiftSettings = self.swiftSettings { let swiftSettings = VersionedValue(swiftSettings, api: "swiftSettings", versions: [.v5]) try container.encode(swiftSettings, forKey: .swiftSettings) } if let linkerSettings = self.linkerSettings { let linkerSettings = VersionedValue(linkerSettings, api: "linkerSettings", versions: [.v5]) try container.encode(linkerSettings, forKey: .linkerSettings) } } } extension Target.Dependency { /// A dependency on a target in the same package. public static func target(name: String) -> Target.Dependency { #if PACKAGE_DESCRIPTION_4 return .targetItem(name: name) #else return ._targetItem(name: name) #endif } /// A dependency on a product from a package dependency. public static func product(name: String, package: String? = nil) -> Target.Dependency { #if PACKAGE_DESCRIPTION_4 return .productItem(name: name, package: package) #else return ._productItem(name: name, package: package) #endif } // A by-name dependency that resolves to either a target or a product, // as above, after the package graph has been loaded. public static func byName(name: String) -> Target.Dependency { #if PACKAGE_DESCRIPTION_4 return .byNameItem(name: name) #else return ._byNameItem(name: name) #endif } } // MARK: ExpressibleByStringLiteral extension Target.Dependency: ExpressibleByStringLiteral { public init(stringLiteral value: String) { #if PACKAGE_DESCRIPTION_4 self = .byNameItem(name: value) #else self = ._byNameItem(name: value) #endif } }
8edcd88d2522154ab2762cefa1fbaaa3
30.610738
103
0.613482
false
false
false
false
5lucky2xiaobin0/PandaTV
refs/heads/master
PandaTV/PandaTV/Classes/Game/Controller/GameVC.swift
mit
1
// // GameVC.swift // PandaTV // // Created by 钟斌 on 2017/3/24. // Copyright © 2017年 xiaobin. All rights reserved. // import UIKit class GameVC: UIViewController { let gamevm : GameVM = GameVM() var titles : [TitleItem] = [TitleItem]() var titleView : TitleView? lazy var ContentGameVC : ContentView = { let typeVC = GameListVC() var childVCs = [UIViewController]() childVCs.append(typeVC) var index = 0 for titles in self.titles { if index > 0 { let vc = GameTypeVC() vc.searchPath = titles.ename childVCs.append(vc) } index += 1 } let contentChildVC = ContentView(frame: CGRect(x: 0, y: titleViewH, width: screenW, height: screenH - titleViewH - tabBarH), views: childVCs) contentChildVC.delegate = self return contentChildVC }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white automaticallyAdjustsScrollViewInsets = false //先设置2组固定数据 let categoryDict: [String : Any] = ["cname" : "分类", "ename" : ""] let hotDict: [String : Any] = ["cname" : "热门", "ename" : "game_hot"] titles.append(TitleItem(dict: categoryDict)) titles.append(TitleItem(dict: hotDict)) //加载数据 loadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: false) } } extension GameVC { func setUI() { //添加顶部选择界面 titleView = TitleView(frame: CGRect(x: 0, y: 0, width: screenW, height: titleViewH), titleArr: self.titles) titleView?.delegate = self view.addSubview(titleView!) //添加内容界面 view.addSubview(ContentGameVC) } } extension GameVC { func loadData() { gamevm.requestTitleData { self.titles += self.gamevm.titles self.setUI() } } } extension GameVC : ContentViewDelegate { func contentViewScrollTo(index: Int) { titleView?.scrollToTitle(index: index) } } extension GameVC : TitleViewDelegate { func titleViewScrollTo(index: Int) { ContentGameVC.scrollToView(index: index) } }
60727515b9b5a8a41a7469486b76125c
25.397959
149
0.589872
false
false
false
false
liuxuan30/ios-charts
refs/heads/master
Pods/Charts/Source/Charts/Components/AxisBase.swift
apache-2.0
2
// // AxisBase.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics /// Base class for all axes @objc(ChartAxisBase) open class AxisBase: ComponentBase { public override init() { super.init() } /// Custom formatter that is used instead of the auto-formatter if set private var _axisValueFormatter: IAxisValueFormatter? @objc open var labelFont = NSUIFont.systemFont(ofSize: 10.0) @objc open var labelTextColor = NSUIColor.labelOrBlack @objc open var axisLineColor = NSUIColor.gray @objc open var axisLineWidth = CGFloat(0.5) @objc open var axisLineDashPhase = CGFloat(0.0) @objc open var axisLineDashLengths: [CGFloat]! @objc open var gridColor = NSUIColor.gray.withAlphaComponent(0.9) @objc open var gridLineWidth = CGFloat(0.5) @objc open var gridLineDashPhase = CGFloat(0.0) @objc open var gridLineDashLengths: [CGFloat]! @objc open var gridLineCap = CGLineCap.butt @objc open var drawGridLinesEnabled = true @objc open var drawAxisLineEnabled = true /// flag that indicates of the labels of this axis should be drawn or not @objc open var drawLabelsEnabled = true private var _centerAxisLabelsEnabled = false /// Centers the axis labels instead of drawing them at their original position. /// This is useful especially for grouped BarChart. @objc open var centerAxisLabelsEnabled: Bool { get { return _centerAxisLabelsEnabled && entryCount > 0 } set { _centerAxisLabelsEnabled = newValue } } @objc open var isCenterAxisLabelsEnabled: Bool { get { return centerAxisLabelsEnabled } } /// array of limitlines that can be set for the axis private var _limitLines = [ChartLimitLine]() /// Are the LimitLines drawn behind the data or in front of the data? /// /// **default**: false @objc open var drawLimitLinesBehindDataEnabled = false /// Are the grid lines drawn behind the data or in front of the data? /// /// **default**: true @objc open var drawGridLinesBehindDataEnabled = true /// the flag can be used to turn off the antialias for grid lines @objc open var gridAntialiasEnabled = true /// the actual array of entries @objc open var entries = [Double]() /// axis label entries only used for centered labels @objc open var centeredEntries = [Double]() /// the number of entries the legend contains @objc open var entryCount: Int { return entries.count } /// the number of label entries the axis should have /// /// **default**: 6 private var _labelCount = Int(6) /// the number of decimal digits to use (for the default formatter @objc open var decimals: Int = 0 /// When true, axis labels are controlled by the `granularity` property. /// When false, axis values could possibly be repeated. /// This could happen if two adjacent axis values are rounded to same value. /// If using granularity this could be avoided by having fewer axis values visible. @objc open var granularityEnabled = false private var _granularity = Double(1.0) /// The minimum interval between axis values. /// This can be used to avoid label duplicating when zooming in. /// /// **default**: 1.0 @objc open var granularity: Double { get { return _granularity } set { _granularity = newValue // set this to `true` if it was disabled, as it makes no sense to set this property with granularity disabled granularityEnabled = true } } /// The minimum interval between axis values. @objc open var isGranularityEnabled: Bool { get { return granularityEnabled } } /// if true, the set number of y-labels will be forced @objc open var forceLabelsEnabled = false @objc open func getLongestLabel() -> String { var longest = "" for i in 0 ..< entries.count { let text = getFormattedLabel(i) if longest.count < text.count { longest = text } } return longest } /// - Returns: The formatted label at the specified index. This will either use the auto-formatter or the custom formatter (if one is set). @objc open func getFormattedLabel(_ index: Int) -> String { if index < 0 || index >= entries.count { return "" } return valueFormatter?.stringForValue(entries[index], axis: self) ?? "" } /// Sets the formatter to be used for formatting the axis labels. /// If no formatter is set, the chart will automatically determine a reasonable formatting (concerning decimals) for all the values that are drawn inside the chart. /// Use `nil` to use the formatter calculated by the chart. @objc open var valueFormatter: IAxisValueFormatter? { get { if _axisValueFormatter == nil || (_axisValueFormatter is DefaultAxisValueFormatter && (_axisValueFormatter as! DefaultAxisValueFormatter).hasAutoDecimals && (_axisValueFormatter as! DefaultAxisValueFormatter).decimals != decimals) { _axisValueFormatter = DefaultAxisValueFormatter(decimals: decimals) } return _axisValueFormatter } set { _axisValueFormatter = newValue ?? DefaultAxisValueFormatter(decimals: decimals) } } @objc open var isDrawGridLinesEnabled: Bool { return drawGridLinesEnabled } @objc open var isDrawAxisLineEnabled: Bool { return drawAxisLineEnabled } @objc open var isDrawLabelsEnabled: Bool { return drawLabelsEnabled } /// Are the LimitLines drawn behind the data or in front of the data? /// /// **default**: false @objc open var isDrawLimitLinesBehindDataEnabled: Bool { return drawLimitLinesBehindDataEnabled } /// Are the grid lines drawn behind the data or in front of the data? /// /// **default**: true @objc open var isDrawGridLinesBehindDataEnabled: Bool { return drawGridLinesBehindDataEnabled } /// Extra spacing for `axisMinimum` to be added to automatically calculated `axisMinimum` @objc open var spaceMin: Double = 0.0 /// Extra spacing for `axisMaximum` to be added to automatically calculated `axisMaximum` @objc open var spaceMax: Double = 0.0 /// Flag indicating that the axis-min value has been customized internal var _customAxisMin: Bool = false /// Flag indicating that the axis-max value has been customized internal var _customAxisMax: Bool = false /// Do not touch this directly, instead, use axisMinimum. /// This is automatically calculated to represent the real min value, /// and is used when calculating the effective minimum. internal var _axisMinimum = Double(0) /// Do not touch this directly, instead, use axisMaximum. /// This is automatically calculated to represent the real max value, /// and is used when calculating the effective maximum. internal var _axisMaximum = Double(0) /// the total range of values this axis covers @objc open var axisRange = Double(0) /// The minumum number of labels on the axis @objc open var axisMinLabels = Int(2) { didSet { axisMinLabels = axisMinLabels > 0 ? axisMinLabels : oldValue } } /// The maximum number of labels on the axis @objc open var axisMaxLabels = Int(25) { didSet { axisMaxLabels = axisMaxLabels > 0 ? axisMaxLabels : oldValue } } /// the number of label entries the axis should have /// max = 25, /// min = 2, /// default = 6, /// be aware that this number is not fixed and can only be approximated @objc open var labelCount: Int { get { return _labelCount } set { let range = axisMinLabels...axisMaxLabels as ClosedRange _labelCount = newValue.clamped(to: range) forceLabelsEnabled = false } } @objc open func setLabelCount(_ count: Int, force: Bool) { self.labelCount = count forceLabelsEnabled = force } /// `true` if focing the y-label count is enabled. Default: false @objc open var isForceLabelsEnabled: Bool { return forceLabelsEnabled } /// Adds a new ChartLimitLine to this axis. @objc open func addLimitLine(_ line: ChartLimitLine) { _limitLines.append(line) } /// Removes the specified ChartLimitLine from the axis. @objc open func removeLimitLine(_ line: ChartLimitLine) { guard let i = _limitLines.firstIndex(of: line) else { return } _limitLines.remove(at: i) } /// Removes all LimitLines from the axis. @objc open func removeAllLimitLines() { _limitLines.removeAll(keepingCapacity: false) } /// The LimitLines of this axis. @objc open var limitLines : [ChartLimitLine] { return _limitLines } // MARK: Custom axis ranges /// By calling this method, any custom minimum value that has been previously set is reseted, and the calculation is done automatically. @objc open func resetCustomAxisMin() { _customAxisMin = false } @objc open var isAxisMinCustom: Bool { return _customAxisMin } /// By calling this method, any custom maximum value that has been previously set is reseted, and the calculation is done automatically. @objc open func resetCustomAxisMax() { _customAxisMax = false } @objc open var isAxisMaxCustom: Bool { return _customAxisMax } /// The minimum value for this axis. /// If set, this value will not be calculated automatically depending on the provided data. /// Use `resetCustomAxisMin()` to undo this. @objc open var axisMinimum: Double { get { return _axisMinimum } set { _customAxisMin = true _axisMinimum = newValue axisRange = abs(_axisMaximum - newValue) } } /// The maximum value for this axis. /// If set, this value will not be calculated automatically depending on the provided data. /// Use `resetCustomAxisMax()` to undo this. @objc open var axisMaximum: Double { get { return _axisMaximum } set { _customAxisMax = true _axisMaximum = newValue axisRange = abs(newValue - _axisMinimum) } } /// Calculates the minimum, maximum and range values of the YAxis with the given minimum and maximum values from the chart data. /// /// - Parameters: /// - dataMin: the y-min value according to chart data /// - dataMax: the y-max value according to chart @objc open func calculate(min dataMin: Double, max dataMax: Double) { // if custom, use value as is, else use data value var min = _customAxisMin ? _axisMinimum : (dataMin - spaceMin) var max = _customAxisMax ? _axisMaximum : (dataMax + spaceMax) // temporary range (before calculations) let range = abs(max - min) // in case all values are equal if range == 0.0 { max = max + 1.0 min = min - 1.0 } _axisMinimum = min _axisMaximum = max // actual range axisRange = abs(max - min) } }
7d58661ce979970b07a6f39d279dda7b
31.783198
168
0.620319
false
false
false
false
Tony0822/DouYuZB
refs/heads/master
DYZB/DYZB/Classes/Home/Controller/RecommentdViewController.swift
mit
1
// // RecommentdViewController.swift // DYZB // // Created by TonyYang on 2017/6/27. // Copyright © 2017年 TonyYang. All rights reserved. // import UIKit fileprivate let KItemMargin : CGFloat = 10; fileprivate let KItemW = (KScreenW - 3 * 10) / 2 fileprivate let KItemH = KItemW * 3 / 4 fileprivate let KHeaderViewH : CGFloat = 50 fileprivate let KNormalCellID = "KNormalCellID" fileprivate let KHeaderViewID = "KHeaderViewID" class RecommentdViewController: UIViewController { // MARK: 懒加载属性 fileprivate lazy var collectionView : UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: KItemW, height: KItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = KItemMargin layout.headerReferenceSize = CGSize(width: KScreenW, height: KHeaderViewH); layout.sectionInset = UIEdgeInsets(top: 0, left: KItemMargin, bottom: 0, right: KItemMargin) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.autoresizingMask = [.flexibleWidth , .flexibleHeight] // collectionView.delegate = self collectionView.dataSource = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: KNormalCellID) collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KHeaderViewID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil) , forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KHeaderViewID) return collectionView }() // 系统函数 override func viewDidLoad() { super.viewDidLoad() // 1.设置UI界面 setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: 设置UI extension RecommentdViewController { fileprivate func setupUI() { // 1.将UIcollectionView添加到控制器view view.addSubview(collectionView) } } // MARK:协议 extension RecommentdViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 12 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return 8 } return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KNormalCellID, for: indexPath) cell.backgroundColor = UIColor.yellow return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出section的headerView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: KHeaderViewID, for: indexPath) return headerView } }
9dee47b144c87d0af02767be1548a5d3
34.902174
164
0.712685
false
false
false
false
mitochrome/complex-gestures-demo
refs/heads/master
apps/GestureInput/Carthage/Checkouts/RxDataSources/RxSwift/Tests/RxCocoaTests/DelegateProxyTest.swift
mit
4
// // DelegateProxyTest.swift // Tests // // Created by Krunoslav Zaher on 7/5/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import XCTest import RxSwift import RxCocoa #if os(iOS) import UIKit #endif // MARK: Protocols @objc protocol TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } @objc class MockTestDelegateProtocol : NSObject , TestDelegateProtocol { var numbers = [Int]() func testEventHappened(_ value: Int) { numbers.append(value) } } protocol TestDelegateControl: NSObjectProtocol { associatedtype ParentObject: AnyObject associatedtype Delegate: NSObjectProtocol func doThatTest(_ value: Int) var delegateProxy: DelegateProxy<ParentObject, Delegate> { get } func setMineForwardDelegate(_ testDelegate: Delegate) -> Disposable } extension TestDelegateControl { var testSentMessage: Observable<Int> { return delegateProxy .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return delegateProxy .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } } // MARK: Tests final class DelegateProxyTest : RxTest { func test_OnInstallDelegateIsRetained() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock let _ = view.rx.proxy XCTAssertEqual(mock.messages, []) XCTAssertTrue(view.rx.proxy.forwardToDelegate() === mock) } func test_forwardsUnobservedMethods() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock let _ = view.rx.proxy var invoked = false mock.invoked = { invoked = true } XCTAssertFalse(invoked) view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertTrue(invoked) XCTAssertEqual(mock.messages, ["didLearnSomething"]) } func test_forwardsObservedMethods() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock var observedFeedRequestSentMessage = false var observedMessageInvoked = false var events: [MessageProcessingStage] = [] var delegates: [NSObject?] = [] var responds: [Bool] = [] _ = view.rx.observeWeakly(NSObject.self, "delegate").skip(1).subscribe(onNext: { delegate in delegates.append(delegate) if let delegate = delegate { responds.append(delegate.responds(to: #selector(ThreeDSectionedViewProtocol.threeDView(_:didLearnSomething:)))) } }) let sentMessage = view.rx.proxy.sentMessage(#selector(ThreeDSectionedViewProtocol.threeDView(_:didLearnSomething:))) let methodInvoked = view.rx.proxy.methodInvoked(#selector(ThreeDSectionedViewProtocol.threeDView(_:didLearnSomething:))) XCTAssertArraysEqual(delegates, [view.rx.proxy]) { $0 === $1 } XCTAssertEqual(responds, [true]) _ = methodInvoked .subscribe(onNext: { n in observedMessageInvoked = true events.append(.methodInvoked) }) XCTAssertArraysEqual(delegates, [view.rx.proxy, nil, view.rx.proxy]) { $0 === $1 } XCTAssertEqual(responds, [true, true]) mock.invoked = { events.append(.invoking) } _ = sentMessage .subscribe(onNext: { n in observedFeedRequestSentMessage = true events.append(.sentMessage) }) XCTAssertArraysEqual(delegates, [view.rx.proxy, nil, view.rx.proxy, nil, view.rx.proxy]) { $0 === $1 } XCTAssertEqual(responds, [true, true, true]) XCTAssertTrue(!observedFeedRequestSentMessage) XCTAssertTrue(!observedMessageInvoked) view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertTrue(observedFeedRequestSentMessage) XCTAssertTrue(observedMessageInvoked) XCTAssertEqual(mock.messages, ["didLearnSomething"]) XCTAssertEqual(events, [.sentMessage, .invoking, .methodInvoked]) } func test_forwardsObserverDispose() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock var nMessages = 0 var invoked = false let d = view.rx.proxy.sentMessage(#selector(ThreeDSectionedViewProtocol.threeDView(_:didLearnSomething:))) .subscribe(onNext: { n in nMessages += 1 }) let d2 = view.rx.proxy.methodInvoked(#selector(ThreeDSectionedViewProtocol.threeDView(_:didLearnSomething:))) .subscribe(onNext: { n in nMessages += 1 }) mock.invoked = { invoked = true } XCTAssertTrue(nMessages == 0) XCTAssertFalse(invoked) view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertTrue(invoked) XCTAssertTrue(nMessages == 2) d.dispose() d2.dispose() view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertTrue(nMessages == 2) } func test_forwardsUnobservableMethods() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock var invoked = false mock.invoked = { invoked = true } XCTAssertFalse(invoked) view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertTrue(invoked) XCTAssertEqual(mock.messages, ["didLearnSomething"]) } func test_observesUnimplementedOptionalMethods() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock XCTAssertTrue(!mock.responds(to: NSSelectorFromString("threeDView(threeDView:didGetXXX:"))) let sentArgument = IndexPath(index: 0) var receivedArgumentSentMessage: IndexPath? = nil var receivedArgumentMethodInvoked: IndexPath? = nil var events: [MessageProcessingStage] = [] var delegates: [NSObject?] = [] var responds: [Bool] = [] _ = view.rx.observeWeakly(NSObject.self, "delegate").skip(1).subscribe(onNext: { delegate in delegates.append(delegate) if let delegate = delegate { responds.append(delegate.responds(to: #selector(ThreeDSectionedViewProtocol.threeDView(_:didGetXXX:)))) } }) let sentMessage = view.rx.proxy.sentMessage(#selector(ThreeDSectionedViewProtocol.threeDView(_:didGetXXX:))) let methodInvoked = view.rx.proxy.methodInvoked(#selector(ThreeDSectionedViewProtocol.threeDView(_:didGetXXX:))) XCTAssertArraysEqual(delegates, [view.rx.proxy]) { $0 == $1 } XCTAssertEqual(responds, [false]) let d1 = sentMessage .subscribe(onNext: { n in let ip = n[1] as! IndexPath receivedArgumentSentMessage = ip events.append(.sentMessage) }) XCTAssertArraysEqual(delegates, [view.rx.proxy, nil, view.rx.proxy]) { $0 == $1 } XCTAssertEqual(responds, [false, true]) let d2 = methodInvoked .subscribe(onNext: { n in let ip = n[1] as! IndexPath receivedArgumentMethodInvoked = ip events.append(.methodInvoked) }) XCTAssertArraysEqual(delegates, [view.rx.proxy, nil, view.rx.proxy, nil, view.rx.proxy]) { $0 === $1 } XCTAssertEqual(responds, [false, true, true]) mock.invoked = { events.append(.invoking) } view.delegate?.threeDView?(view, didGetXXX: sentArgument) XCTAssertTrue(receivedArgumentSentMessage == sentArgument) XCTAssertTrue(receivedArgumentMethodInvoked == sentArgument) XCTAssertEqual(mock.messages, []) XCTAssertEqual(events, [.sentMessage, .methodInvoked]) d1.dispose() XCTAssertArraysEqual(delegates, [view.rx.proxy, nil, view.rx.proxy, nil, view.rx.proxy, nil, view.rx.proxy]) { $0 === $1 } XCTAssertEqual(responds, [false, true, true, true]) d2.dispose() XCTAssertArraysEqual(delegates, [view.rx.proxy, nil, view.rx.proxy, nil, view.rx.proxy, nil, view.rx.proxy, nil, view.rx.proxy]) { $0 === $1 } XCTAssertEqual(responds, [false, true, true, true, false]) } func test_delegateProxyCompletesOnDealloc() { var view: ThreeDSectionedView! = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock var completedSentMessage = false var completedMethodInvoked = false autoreleasepool { XCTAssertTrue(!mock.responds(to: NSSelectorFromString("threeDView:threeDView:didGetXXX:"))) let sentArgument = IndexPath(index: 0) _ = view .rx.proxy .sentMessage(#selector(ThreeDSectionedViewProtocol.threeDView(_:didGetXXX:))) .subscribe(onCompleted: { completedSentMessage = true }) _ = view .rx.proxy .methodInvoked(#selector(ThreeDSectionedViewProtocol.threeDView(_:didGetXXX:))) .subscribe(onCompleted: { completedMethodInvoked = true }) mock.invoked = {} view.delegate?.threeDView?(view, didGetXXX: sentArgument) } XCTAssertTrue(!completedSentMessage) XCTAssertTrue(!completedMethodInvoked) view = nil XCTAssertTrue(completedSentMessage) XCTAssertTrue(completedMethodInvoked) } } extension DelegateProxyTest { func test_delegateProxyType() { let view = InitialClassView() let subclassView = InitialClassViewSubclass() _ = InitialClassViewDelegateProxy.createProxy(for: view) let proxy2 = InitialClassViewDelegateProxy.createProxy(for: subclassView) XCTAssert(proxy2 is InitialClassViewDelegateProxySubclass) } func test_delegateProxyTypeExtend_a() { let extendView1 = InitialClassViewSometimeExtended1_a() let extendView2 = InitialClassViewSometimeExtended2_a() _ = InitialClassViewDelegateProxy.createProxy(for: extendView1) _ = InitialClassViewDelegateProxy.createProxy(for: extendView2) ExtendClassViewDelegateProxy_a.register { ExtendClassViewDelegateProxy_a(parentObject1: $0) } let extendedProxy1 = InitialClassViewDelegateProxy.createProxy(for: extendView1) let extendedProxy2 = InitialClassViewDelegateProxy.createProxy(for: extendView2) XCTAssert(extendedProxy1 is ExtendClassViewDelegateProxy_a) XCTAssert(extendedProxy2 is ExtendClassViewDelegateProxy_a) } func test_delegateProxyTypeExtend_b() { let extendView1 = InitialClassViewSometimeExtended1_b() let extendView2 = InitialClassViewSometimeExtended2_b() _ = InitialClassViewDelegateProxy.createProxy(for: extendView1) _ = InitialClassViewDelegateProxy.createProxy(for: extendView2) ExtendClassViewDelegateProxy_b.register { ExtendClassViewDelegateProxy_b(parentObject2: $0) } _ = InitialClassViewDelegateProxy.createProxy(for: extendView1) let extendedProxy2 = InitialClassViewDelegateProxy.createProxy(for: extendView2) XCTAssert(extendedProxy2 is ExtendClassViewDelegateProxy_b) } } #if os(iOS) extension DelegateProxyTest { func test_DelegateProxyHierarchyWorks() { let tableView = UITableView() _ = tableView.rx.delegate.sentMessage(#selector(UIScrollViewDelegate.scrollViewWillBeginDragging(_:))) _ = tableView.rx.delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDragging(_:))) } } #endif // MARK: Testing extensions extension DelegateProxyTest { func performDelegateTest<Control: TestDelegateControl, ExtendedProxy: DelegateProxyType>( _ createControl: @autoclosure() -> Control, make: @escaping (Control) -> ExtendedProxy) { ExtendedProxy.register(make: make) var control: Control! autoreleasepool { control = createControl() } var receivedValueSentMessage: Int! var receivedValueMethodInvoked: Int! var completedSentMessage = false var completedMethodInvoked = false var deallocated = false var stages: [MessageProcessingStage] = [] autoreleasepool { _ = control.testSentMessage.subscribe(onNext: { value in receivedValueSentMessage = value stages.append(.sentMessage) }, onCompleted: { completedSentMessage = true }) _ = control.testMethodInvoked.subscribe(onNext: { value in receivedValueMethodInvoked = value stages.append(.methodInvoked) }, onCompleted: { completedMethodInvoked = true }) _ = (control as! NSObject).rx.deallocated.subscribe(onNext: { _ in deallocated = true }) } XCTAssertTrue(receivedValueSentMessage == nil) XCTAssertTrue(receivedValueMethodInvoked == nil) XCTAssertEqual(stages, []) autoreleasepool { control.doThatTest(382763) } XCTAssertEqual(stages, [.sentMessage, .methodInvoked]) XCTAssertEqual(receivedValueSentMessage, 382763) XCTAssertEqual(receivedValueMethodInvoked, 382763) autoreleasepool { let mine = MockTestDelegateProtocol() let disposable = control.setMineForwardDelegate(mine as! Control.Delegate) XCTAssertEqual(mine.numbers, []) control.doThatTest(2) XCTAssertEqual(mine.numbers, [2]) disposable.dispose() control.doThatTest(3) XCTAssertEqual(mine.numbers, [2]) } XCTAssertFalse(deallocated) XCTAssertFalse(completedSentMessage) XCTAssertFalse(completedMethodInvoked) autoreleasepool { control = nil } XCTAssertTrue(deallocated) XCTAssertTrue(completedSentMessage) XCTAssertTrue(completedMethodInvoked) } } // MARK: Mocks // test case { final class Food: NSObject { } @objc protocol ThreeDSectionedViewProtocol: NSObjectProtocol { func threeDView(_ threeDView: ThreeDSectionedView, listenToMeee: IndexPath) func threeDView(_ threeDView: ThreeDSectionedView, feedMe: IndexPath) func threeDView(_ threeDView: ThreeDSectionedView, howTallAmI: IndexPath) -> CGFloat @objc optional func threeDView(_ threeDView: ThreeDSectionedView, didGetXXX: IndexPath) @objc optional func threeDView(_ threeDView: ThreeDSectionedView, didLearnSomething: String) @objc optional func threeDView(_ threeDView: ThreeDSectionedView, didFallAsleep: IndexPath) @objc optional func threeDView(_ threeDView: ThreeDSectionedView, getMeSomeFood: IndexPath) -> Food } final class ThreeDSectionedView: NSObject { @objc dynamic var delegate: ThreeDSectionedViewProtocol? } // } // integration { final class ThreeDSectionedViewDelegateProxy: DelegateProxy<ThreeDSectionedView, ThreeDSectionedViewProtocol> , ThreeDSectionedViewProtocol , DelegateProxyType { // Register known implementations public static func registerKnownImplementations() { self.register { ThreeDSectionedViewDelegateProxy(parentObject: $0) } } init(parentObject: ThreeDSectionedView) { super.init(parentObject: parentObject, delegateProxy: ThreeDSectionedViewDelegateProxy.self) } // delegate func threeDView(_ threeDView: ThreeDSectionedView, listenToMeee: IndexPath) { } func threeDView(_ threeDView: ThreeDSectionedView, feedMe: IndexPath) { } func threeDView(_ threeDView: ThreeDSectionedView, howTallAmI: IndexPath) -> CGFloat { return 1.1 } // integration class func currentDelegate(for object: ThreeDSectionedView) -> ThreeDSectionedViewProtocol? { return object.delegate } class func setCurrentDelegate(_ delegate: ThreeDSectionedViewProtocol?, to object: ThreeDSectionedView) { object.delegate = delegate } } extension Reactive where Base: ThreeDSectionedView { var proxy: DelegateProxy<ThreeDSectionedView, ThreeDSectionedViewProtocol> { return ThreeDSectionedViewDelegateProxy.proxy(for: base) } } // } final class MockThreeDSectionedViewProtocol : NSObject, ThreeDSectionedViewProtocol { var messages: [String] = [] var invoked: (() -> ())! func threeDView(_ threeDView: ThreeDSectionedView, listenToMeee: IndexPath) { messages.append("listenToMeee") invoked() } func threeDView(_ threeDView: ThreeDSectionedView, feedMe: IndexPath) { messages.append("feedMe") invoked() } func threeDView(_ threeDView: ThreeDSectionedView, howTallAmI: IndexPath) -> CGFloat { messages.append("howTallAmI") invoked() return 3 } /*func threeDView(threeDView: ThreeDSectionedView, didGetXXX: IndexPath) { messages.append("didGetXXX") }*/ func threeDView(_ threeDView: ThreeDSectionedView, didLearnSomething: String) { messages.append("didLearnSomething") invoked() } //optional func threeDView(threeDView: ThreeDSectionedView, didFallAsleep: IndexPath) func threeDView(_ threeDView: ThreeDSectionedView, getMeSomeFood: IndexPath) -> Food { messages.append("getMeSomeFood") invoked() return Food() } } // test case { @objc protocol InitialClassViewDelegate: NSObjectProtocol { } class InitialClassView: NSObject { weak var delegate: InitialClassViewDelegate? } class InitialClassViewSubclass: InitialClassView { } class InitialClassViewDelegateProxy : DelegateProxy<InitialClassView, InitialClassViewDelegate> , DelegateProxyType , InitialClassViewDelegate { init(parentObject: InitialClassView) { super.init(parentObject: parentObject, delegateProxy: InitialClassViewDelegateProxy.self) } // Register known implementations public static func registerKnownImplementations() { self.register { InitialClassViewDelegateProxy(parentObject: $0) } self.register { InitialClassViewDelegateProxySubclass(parentObject: $0) } } static func currentDelegate(for object: ParentObject) -> InitialClassViewDelegate? { return object.delegate } static func setCurrentDelegate(_ delegate: InitialClassViewDelegate?, to object: ParentObject) { return object.delegate = delegate } } class InitialClassViewDelegateProxySubclass: InitialClassViewDelegateProxy { init(parentObject: InitialClassViewSubclass) { super.init(parentObject: parentObject) } } class InitialClassViewSometimeExtended1_a: InitialClassView { } class InitialClassViewSometimeExtended2_a: InitialClassViewSometimeExtended1_a { } class InitialClassViewSometimeExtended1_b: InitialClassView { } class InitialClassViewSometimeExtended2_b: InitialClassViewSometimeExtended1_b { } class ExtendClassViewDelegateProxy_a: InitialClassViewDelegateProxy { init(parentObject1: InitialClassViewSometimeExtended1_a) { super.init(parentObject: parentObject1) } init(parentObject2: InitialClassViewSometimeExtended2_a) { super.init(parentObject: parentObject2) } } class ExtendClassViewDelegateProxy_b: InitialClassViewDelegateProxy { init(parentObject1: InitialClassViewSometimeExtended1_b) { super.init(parentObject: parentObject1) } init(parentObject2: InitialClassViewSometimeExtended2_b) { super.init(parentObject: parentObject2) } } // } #if os(macOS) extension MockTestDelegateProtocol : NSTextFieldDelegate { } #endif #if os(iOS) extension MockTestDelegateProtocol: UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { fatalError() } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { fatalError() } } #endif #if os(iOS) || os(tvOS) extension MockTestDelegateProtocol : UICollectionViewDataSource , UIScrollViewDelegate , UITableViewDataSource , UITableViewDelegate , UISearchBarDelegate , UISearchControllerDelegate , UINavigationControllerDelegate , UITabBarControllerDelegate , UITabBarDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { fatalError() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { fatalError() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { fatalError() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { fatalError() } } #endif #if os(iOS) extension MockTestDelegateProtocol : UIPickerViewDelegate , UIWebViewDelegate { } #endif
b7169c8a12ad58c04edaf1070e1b830d
31.331865
183
0.658688
false
true
false
false
cottonBuddha/Qsic
refs/heads/master
Qsic/QSLoginWidget.swift
mit
1
// // QSLoginWidget.swift // Qsic // // Created by cottonBuddha on 2017/8/2. // Copyright © 2017年 cottonBuddha. All rights reserved. // import Foundation class QSLoginWidget: QSWidget { var accountInput: QSInputWidget? var passwordInput: QSInputWidget? var accountLength: Int = 0 var passwordLength: Int = 0 convenience init(startX:Int, startY:Int) { self.init(startX: startX, startY: startY, width: Int(COLS - Int32(startX + 1)), height: 3) } override func drawWidget() { super.drawWidget() self.drawLoginWidget() wrefresh(self.window) } private func drawLoginWidget() { mvwaddstr(self.window, 0, 0, "需要登录~") mvwaddstr(self.window, 1, 0, "账号:") mvwaddstr(self.window, 2, 0, "密码:") } public func getInputContent(completionHandler:(String,String)->()) { accountInput = QSInputWidget.init(startX: 6, startY: 1, width: 40, height: 1) self.addSubWidget(widget: accountInput!) let account = accountInput?.input() accountLength = account!.lengthInCurses() passwordInput = QSInputWidget.init(startX: 6, startY: 2, width: 40, height: 1) self.addSubWidget(widget: passwordInput!) let password = passwordInput?.input() passwordLength = password!.lengthInCurses() completionHandler(account!,password!) } public func hide() { eraseSelf() } }
fb2b9fadb55da786f224f08da6179706
28.019608
98
0.621622
false
false
false
false
tidwall/Safe
refs/heads/master
Tests/atomic-test.swift
mit
1
// // atomic-test.swift // Safe // // Created by Josh Baker on 7/1/15. // Copyright © 2015 ONcast. All rights reserved. // import XCTest extension Tests { func testAtomicInt() { do { var (n, a) = (Int(47), IntA(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = +n a = +a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = -n a = -a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n = ~n a = ~a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int(47), IntA(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicInt64() { do { var (n, a) = (Int64(47), Int64A(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = +n a = +a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = -n a = -a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n = ~n a = ~a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int64(47), Int64A(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicInt32() { do { var (n, a) = (Int32(47), Int32A(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = +n a = +a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = -n a = -a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n = ~n a = ~a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int32(47), Int32A(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicInt16() { do { var (n, a) = (Int16(47), Int16A(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = +n a = +a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = -n a = -a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n = ~n a = ~a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int16(47), Int16A(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicInt8() { do { var (n, a) = (Int8(47), Int8A(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = +n a = +a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = -n a = -a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n = ~n a = ~a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Int8(47), Int8A(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicUInt() { do { var (n, a) = (UInt(47), UIntA(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt(47), UIntA(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicUInt64() { do { var (n, a) = (UInt64(47), UInt64A(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt64(47), UInt64A(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicUInt32() { do { var (n, a) = (UInt32(47), UInt32A(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt32(47), UInt32A(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicUInt16() { do { var (n, a) = (UInt16(47), UInt16A(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt16(47), UInt16A(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicUInt8() { do { var (n, a) = (UInt8(47), UInt8A(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n << 2 a = a << 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n >> 2 a = a >> 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n ^ 2 a = a ^ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n & 2 a = a & 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n &+ 2 a = a &+ 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n &- 2 a = a &- 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n = n &* 2 a = a &* 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n <<= 2 a <<= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n >>= 2 a >>= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n ^= 2 a ^= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (UInt8(47), UInt8A(47)) n &= 2 a &= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicDouble() { do { var (n, a) = (Double(47), DoubleA(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n = +n a = +a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n = -n a = -a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Double(47), DoubleA(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicFloat() { do { var (n, a) = (Float(47), FloatA(47)) n = n + 2 a = a + 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n = n - 2 a = a - 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n = n * 2 a = a * 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n = n / 2 a = a / 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n = n % 2 a = a % 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n = +n a = +a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n = -n a = -a XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n += 2 a += 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n -= 2 a -= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n *= 2 a *= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n /= 2 a /= 2 XCTAssert(n == a, "Mismatch") } do { var (n, a) = (Float(47), FloatA(47)) n %= 2 a %= 2 XCTAssert(n == a, "Mismatch") } } } extension Tests { func testAtomicBool() { } } extension Tests { func testAtomicString() { do { var (n, a) = (String("47"), StringA("47")) n = n + "2" a = a + "2" XCTAssert(n == a, "Mismatch") } do { var (n, a) = (String("47"), StringA("47")) n += "2" a += "2" XCTAssert(n == a, "Mismatch") } } }
05590ca1c8a3f8533470faf08d2ee9e3
23.797677
146
0.297715
false
false
false
false
benjaminhorner/finalweather
refs/heads/master
FinalWeather/AppDelegate.swift
mit
1
// // AppDelegate.swift // FinalWeather // // Created by Benjamin Horner on 31/01/2017. // Copyright © 2017 Benjamin Horner. All rights reserved. // import UIKit import SwiftyBeaver import SwiftyUserDefaults import Fabric import Crashlytics // SwiftyBeaver let log = SwiftyBeaver.self // SwiftyUserDefaults extension DefaultsKeys { static let latestWeather = DefaultsKey<Any?>("latestWeather") } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // Better logging var enableLogs = false let logLevel = SwiftyBeaver.Level.debug var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // START LOGGING // -------------------------------------- // Better logs // add log destinations. at least one is needed! if self.enableLogs { let console = ConsoleDestination() console.minLevel = self.logLevel log.addDestination(console) } // Add Fabric Fabric.with([Crashlytics.self]) // Set the main view controller for the app // This will be the MainViewController let window = UIWindow(frame: UIScreen.main.bounds) self.window = window window.rootViewController = MainViewController() 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
2f1895fa508d1b8a5ecad6e9fcd28f29
34.369565
285
0.684081
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/Views/Rank/RankView.swift
mit
1
// // RankView.swift // Yep // // Created by NIX on 15/3/18. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit @IBDesignable final class RankView: UIView { @IBInspectable var barNumber: Int = 4 @IBInspectable var barColor: UIColor = UIColor.yepTintColor() @IBInspectable var barBackgroundColor: UIColor = UIColor(white: 0.0, alpha: 0.15) @IBInspectable var rank: Int = 2 @IBInspectable var gap: CGFloat = 1 override func didMoveToSuperview() { super.didMoveToSuperview() backgroundColor = UIColor.clearColor() } override func drawRect(rect: CGRect) { let barWidth = (rect.width - gap * (CGFloat(barNumber) - 1)) / CGFloat(barNumber) let barStepHeight = rect.height / CGFloat(barNumber) for i in 0..<barNumber { let bar = UIBezierPath() let barIndex = CGFloat(i) let x = barWidth * 0.5 + barWidth * barIndex + gap * barIndex bar.moveToPoint(CGPoint(x: x, y: rect.height)) bar.addLineToPoint(CGPoint(x: x, y: barStepHeight * (CGFloat(barNumber) - (barIndex + 1)))) bar.lineWidth = barWidth if i < rank { barColor.setStroke() } else { barBackgroundColor.setStroke() } bar.stroke() } } }
bf922812b2c4a889729415581dbb7c84
28.413043
103
0.594974
false
false
false
false
codedswitch/CSFramework
refs/heads/master
Example/Pods/Socket.IO-Client-Swift/Source/SocketIO/Engine/SocketEngine.swift
mit
1
// // SocketEngine.swift // Socket.IO-Client-Swift // // Created by Erik Little on 3/3/15. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Dispatch import Foundation import Starscream /// The class that handles the engine.io protocol and transports. /// See `SocketEnginePollable` and `SocketEngineWebsocket` for transport specific methods. public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, SocketEngineWebsocket, ConfigSettable { // MARK: Properties private static let logType = "SocketEngine" /// The queue that all engine actions take place on. public let engineQueue = DispatchQueue(label: "com.socketio.engineHandleQueue") /// The connect parameters sent during a connect. public var connectParams: [String: Any]? { didSet { (urlPolling, urlWebSocket) = createURLs() } } /// A dictionary of extra http headers that will be set during connection. public var extraHeaders: [String: String]? /// A queue of engine.io messages waiting for POSTing /// /// **You should not touch this directly** public var postWait = [String]() /// `true` if there is an outstanding poll. Trying to poll before the first is done will cause socket.io to /// disconnect us. /// /// **Do not touch this directly** public var waitingForPoll = false /// `true` if there is an outstanding post. Trying to post before the first is done will cause socket.io to /// disconnect us. /// /// **Do not touch this directly** public var waitingForPost = false /// `true` if this engine is closed. public private(set) var closed = false /// If `true` the engine will attempt to use WebSocket compression. public private(set) var compress = false /// `true` if this engine is connected. Connected means that the initial poll connect has succeeded. public private(set) var connected = false /// An array of HTTPCookies that are sent during the connection. public private(set) var cookies: [HTTPCookie]? /// When `true`, the engine is in the process of switching to WebSockets. /// /// **Do not touch this directly** public private(set) var fastUpgrade = false /// When `true`, the engine will only use HTTP long-polling as a transport. public private(set) var forcePolling = false /// When `true`, the engine will only use WebSockets as a transport. public private(set) var forceWebsockets = false /// `true` If engine's session has been invalidated. public private(set) var invalidated = false /// If `true`, the engine is currently in HTTP long-polling mode. public private(set) var polling = true /// If `true`, the engine is currently seeing whether it can upgrade to WebSockets. public private(set) var probing = false /// The URLSession that will be used for polling. public private(set) var session: URLSession? /// The session id for this engine. public private(set) var sid = "" /// The path to engine.io. public private(set) var socketPath = "/engine.io/" /// The url for polling. public private(set) var urlPolling = URL(string: "http://localhost/")! /// The url for WebSockets. public private(set) var urlWebSocket = URL(string: "http://localhost/")! /// If `true`, then the engine is currently in WebSockets mode. @available(*, deprecated, message: "No longer needed, if we're not polling, then we must be doing websockets") public private(set) var websocket = false /// The WebSocket for this engine. public private(set) var ws: WebSocket? /// The client for this engine. public weak var client: SocketEngineClient? private weak var sessionDelegate: URLSessionDelegate? private let url: URL private var pingInterval: Int? private var pingTimeout = 0 { didSet { pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25000)) } } private var pongsMissed = 0 private var pongsMissedMax = 0 private var probeWait = ProbeWaitQueue() private var secure = false private var security: SocketIO.SSLSecurity? private var selfSigned = false // MARK: Initializers /// Creates a new engine. /// /// - parameter client: The client for this engine. /// - parameter url: The url for this engine. /// - parameter config: An array of configuration options for this engine. public init(client: SocketEngineClient, url: URL, config: SocketIOClientConfiguration) { self.client = client self.url = url super.init() setConfigs(config) sessionDelegate = sessionDelegate ?? self (urlPolling, urlWebSocket) = createURLs() } /// Creates a new engine. /// /// - parameter client: The client for this engine. /// - parameter url: The url for this engine. /// - parameter options: The options for this engine. public convenience init(client: SocketEngineClient, url: URL, options: [String: Any]?) { self.init(client: client, url: url, config: options?.toSocketConfiguration() ?? []) } deinit { DefaultSocketLogger.Logger.log("Engine is being released", type: SocketEngine.logType) closed = true stopPolling() } // MARK: Methods private func checkAndHandleEngineError(_ msg: String) { do { let dict = try msg.toDictionary() guard let error = dict["message"] as? String else { return } /* 0: Unknown transport 1: Unknown sid 2: Bad handshake request 3: Bad request */ didError(reason: error) } catch { client?.engineDidError(reason: "Got unknown error from server \(msg)") } } private func handleBase64(message: String) { // binary in base64 string let noPrefix = String(message[message.index(message.startIndex, offsetBy: 2)..<message.endIndex]) if let data = Data(base64Encoded: noPrefix, options: .ignoreUnknownCharacters) { client?.parseEngineBinaryData(data) } } private func closeOutEngine(reason: String) { sid = "" closed = true invalidated = true connected = false ws?.disconnect() stopPolling() client?.engineDidClose(reason: reason) } /// Starts the connection to the server. public func connect() { engineQueue.async { self._connect() } } private func _connect() { if connected { DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: SocketEngine.logType) disconnect(reason: "reconnect") } DefaultSocketLogger.Logger.log("Starting engine. Server: \(url)", type: SocketEngine.logType) DefaultSocketLogger.Logger.log("Handshaking", type: SocketEngine.logType) resetEngine() if forceWebsockets { polling = false createWebSocketAndConnect() return } var reqPolling = URLRequest(url: urlPolling, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60.0) addHeaders(to: &reqPolling) doLongPoll(for: reqPolling) } private func createURLs() -> (URL, URL) { if client == nil { return (URL(string: "http://localhost/")!, URL(string: "http://localhost/")!) } var urlPolling = URLComponents(string: url.absoluteString)! var urlWebSocket = URLComponents(string: url.absoluteString)! var queryString = "" urlWebSocket.path = socketPath urlPolling.path = socketPath if secure { urlPolling.scheme = "https" urlWebSocket.scheme = "wss" } else { urlPolling.scheme = "http" urlWebSocket.scheme = "ws" } if let connectParams = self.connectParams { for (key, value) in connectParams { let keyEsc = key.urlEncode()! let valueEsc = "\(value)".urlEncode()! queryString += "&\(keyEsc)=\(valueEsc)" } } urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString return (urlPolling.url!, urlWebSocket.url!) } private func createWebSocketAndConnect() { ws?.delegate = nil // TODO this seems a bit defensive, is this really needed? var req = URLRequest(url: urlWebSocketWithSid) addHeaders(to: &req) ws = WebSocket(request: req) ws?.callbackQueue = engineQueue ws?.enableCompression = compress ws?.delegate = self ws?.disableSSLCertValidation = selfSigned ws?.security = security?.security ws?.connect() } /// Called when an error happens during execution. Causes a disconnection. public func didError(reason: String) { DefaultSocketLogger.Logger.error("\(reason)", type: SocketEngine.logType) client?.engineDidError(reason: reason) disconnect(reason: reason) } /// Disconnects from the server. /// /// - parameter reason: The reason for the disconnection. This is communicated up to the client. public func disconnect(reason: String) { engineQueue.async { self._disconnect(reason: reason) } } private func _disconnect(reason: String) { guard connected && !closed else { return closeOutEngine(reason: reason) } DefaultSocketLogger.Logger.log("Engine is being closed.", type: SocketEngine.logType) if polling { disconnectPolling(reason: reason) } else { sendWebSocketMessage("", withType: .close, withData: []) closeOutEngine(reason: reason) } } // We need to take special care when we're polling that we send it ASAP // Also make sure we're on the emitQueue since we're touching postWait private func disconnectPolling(reason: String) { postWait.append(String(SocketEnginePacketType.close.rawValue)) doRequest(for: createRequestForPostWithPostWait()) {_, _, _ in } closeOutEngine(reason: reason) } /// Called to switch from HTTP long-polling to WebSockets. After calling this method the engine will be in /// WebSocket mode. /// /// **You shouldn't call this directly** public func doFastUpgrade() { if waitingForPoll { DefaultSocketLogger.Logger.error("Outstanding poll when switched to WebSockets," + "we'll probably disconnect soon. You should report this.", type: SocketEngine.logType) } DefaultSocketLogger.Logger.log("Switching to WebSockets", type: SocketEngine.logType) sendWebSocketMessage("", withType: .upgrade, withData: []) polling = false fastUpgrade = false probing = false flushProbeWait() } private func flushProbeWait() { DefaultSocketLogger.Logger.log("Flushing probe wait", type: SocketEngine.logType) for waiter in probeWait { write(waiter.msg, withType: waiter.type, withData: waiter.data) } probeWait.removeAll(keepingCapacity: false) if postWait.count != 0 { flushWaitingForPostToWebSocket() } } /// Causes any packets that were waiting for POSTing to be sent through the WebSocket. This happens because when /// the engine is attempting to upgrade to WebSocket it does not do any POSTing. /// /// **You shouldn't call this directly** public func flushWaitingForPostToWebSocket() { guard let ws = self.ws else { return } for msg in postWait { ws.write(string: msg) } postWait.removeAll(keepingCapacity: false) } private func handleClose(_ reason: String) { client?.engineDidClose(reason: reason) } private func handleMessage(_ message: String) { client?.parseEngineMessage(message) } private func handleNOOP() { doPoll() } private func handleOpen(openData: String) { guard let json = try? openData.toDictionary() else { didError(reason: "Error parsing open packet") return } guard let sid = json["sid"] as? String else { didError(reason: "Open packet contained no sid") return } let upgradeWs: Bool self.sid = sid connected = true pongsMissed = 0 if let upgrades = json["upgrades"] as? [String] { upgradeWs = upgrades.contains("websocket") } else { upgradeWs = false } if let pingInterval = json["pingInterval"] as? Int, let pingTimeout = json["pingTimeout"] as? Int { self.pingInterval = pingInterval self.pingTimeout = pingTimeout } if !forcePolling && !forceWebsockets && upgradeWs { createWebSocketAndConnect() } sendPing() if !forceWebsockets { doPoll() } client?.engineDidOpen(reason: "Connect") } private func handlePong(with message: String) { pongsMissed = 0 // We should upgrade if message == "3probe" { DefaultSocketLogger.Logger.log("Received probe response, should upgrade to WebSockets", type: SocketEngine.logType) upgradeTransport() } client?.engineDidReceivePong() } /// Parses raw binary received from engine.io. /// /// - parameter data: The data to parse. public func parseEngineData(_ data: Data) { DefaultSocketLogger.Logger.log("Got binary data: \(data)", type: SocketEngine.logType) client?.parseEngineBinaryData(data.subdata(in: 1..<data.endIndex)) } /// Parses a raw engine.io packet. /// /// - parameter message: The message to parse. /// - parameter fromPolling: Whether this message is from long-polling. /// If `true` we might have to fix utf8 encoding. public func parseEngineMessage(_ message: String) { DefaultSocketLogger.Logger.log("Got message: \(message)", type: SocketEngine.logType) let reader = SocketStringReader(message: message) if message.hasPrefix("b4") { return handleBase64(message: message) } guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else { checkAndHandleEngineError(message) return } switch type { case .message: handleMessage(String(message.dropFirst())) case .noop: handleNOOP() case .pong: handlePong(with: message) case .open: handleOpen(openData: String(message.dropFirst())) case .close: handleClose(message) default: DefaultSocketLogger.Logger.log("Got unknown packet type", type: SocketEngine.logType) } } // Puts the engine back in its default state private func resetEngine() { let queue = OperationQueue() queue.underlyingQueue = engineQueue closed = false connected = false fastUpgrade = false polling = true probing = false invalidated = false session = Foundation.URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: queue) sid = "" waitingForPoll = false waitingForPost = false } private func sendPing() { guard connected, let pingInterval = pingInterval else { return } // Server is not responding if pongsMissed > pongsMissedMax { client?.engineDidClose(reason: "Ping timeout") return } pongsMissed += 1 write("", withType: .ping, withData: []) engineQueue.asyncAfter(deadline: DispatchTime.now() + .milliseconds(pingInterval)) {[weak self, id = self.sid] in // Make sure not to ping old connections guard let this = self, this.sid == id else { return } this.sendPing() } client?.engineDidSendPing() } /// Called when the engine should set/update its configs from a given configuration. /// /// parameter config: The `SocketIOClientConfiguration` that should be used to set/update configs. open func setConfigs(_ config: SocketIOClientConfiguration) { for option in config { switch option { case let .connectParams(params): connectParams = params case let .cookies(cookies): self.cookies = cookies case let .extraHeaders(headers): extraHeaders = headers case let .sessionDelegate(delegate): sessionDelegate = delegate case let .forcePolling(force): forcePolling = force case let .forceWebsockets(force): forceWebsockets = force case let .path(path): socketPath = path if !socketPath.hasSuffix("/") { socketPath += "/" } case let .secure(secure): self.secure = secure case let .selfSigned(selfSigned): self.selfSigned = selfSigned case let .security(security): self.security = security case .compress: self.compress = true default: continue } } } // Moves from long-polling to websockets private func upgradeTransport() { if ws?.isConnected ?? false { DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: SocketEngine.logType) fastUpgrade = true sendPollMessage("", withType: .noop, withData: []) // After this point, we should not send anymore polling messages } } /// Writes a message to engine.io, independent of transport. /// /// - parameter msg: The message to send. /// - parameter withType: The type of this message. /// - parameter withData: Any data that this message has. public func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data]) { engineQueue.async { guard self.connected else { return } guard !self.probing else { self.probeWait.append((msg, type, data)) return } if self.polling { DefaultSocketLogger.Logger.log("Writing poll: \(msg) has data: \(data.count != 0)", type: SocketEngine.logType) self.sendPollMessage(msg, withType: type, withData: data) } else { DefaultSocketLogger.Logger.log("Writing ws: \(msg) has data: \(data.count != 0)", type: SocketEngine.logType) self.sendWebSocketMessage(msg, withType: type, withData: data) } } } // MARK: Starscream delegate conformance /// Delegate method for connection. public func websocketDidConnect(socket: WebSocketClient) { if !forceWebsockets { probing = true probeWebSocket() } else { connected = true probing = false polling = false } } /// Delegate method for disconnection. public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { probing = false if closed { client?.engineDidClose(reason: "Disconnect") return } guard !polling else { flushProbeWait() return } connected = false polling = true if let reason = error?.localizedDescription { didError(reason: reason) } else { client?.engineDidClose(reason: "Socket Disconnected") } } // Test Properties func setConnected(_ value: Bool) { connected = value } } extension SocketEngine { // MARK: URLSessionDelegate methods /// Delegate called when the session becomes invalid. public func URLSession(session: URLSession, didBecomeInvalidWithError error: NSError?) { DefaultSocketLogger.Logger.error("Engine URLSession became invalid", type: "SocketEngine") didError(reason: "Engine URLSession became invalid") } }
23460f1d671342288b08290b708b28ff
31.899701
121
0.614461
false
false
false
false
JGiola/swift
refs/heads/main
test/Concurrency/reasync.swift
apache-2.0
13
// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency -disable-availability-checking // REQUIRES: concurrency //// Basic definitions and parsing func reasyncFunction(_: () async -> ()) reasync {} func reasyncRethrowsFunction(_: () async throws -> ()) reasync rethrows {} func rethrowsReasyncFunction(_: () async throws -> ()) rethrows reasync {} // expected-error@-1 {{'reasync' must precede 'rethrows'}}{{65-73=}}{{56-56=reasync }} func asyncReasyncFunction(_: () async throws -> ()) async reasync {} // expected-error@-1 {{'reasync' has already been specified}}{{59-67=}} func reasyncParam(_: () reasync -> ()) {} // expected-error@-1 {{only function declarations may be marked 'reasync'; did you mean 'async'?}}{{25-32=async}} //// Invalid cases func noReasyncParams() reasync {} // expected-error@-1 {{'reasync' function must take an 'async' function argument}} //// Method override attribute checking class Base { func reasyncMethod(_: () async -> ()) reasync {} // expected-note@-1 {{overridden declaration is here}} } class Derived : Base { override func reasyncMethod(_: () async -> ()) async {} // expected-error@-1 {{override of 'reasync' method should also be 'reasync'}} } //// Reasync call site checking func asyncFunction() async {} func callReasyncFunction() async { reasyncFunction { } await reasyncFunction { } // expected-warning {{no 'async' operations occur within 'await' expression}} reasyncFunction { await asyncFunction() } // expected-error@-1:3 {{expression is 'async' but is not marked with 'await'}}{{3-3=await }} // expected-note@-2:3 {{call is 'async'}} await reasyncFunction { await asyncFunction() } } enum HorseError : Error { case colic } func callReasyncRethrowsFunction() async throws { reasyncRethrowsFunction { } await reasyncRethrowsFunction { } // expected-warning@-1 {{no 'async' operations occur within 'await' expression}} try reasyncRethrowsFunction { } // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} try await reasyncRethrowsFunction { } // expected-warning@-1 {{no 'async' operations occur within 'await' expression}} // expected-warning@-2 {{no calls to throwing functions occur within 'try' expression}} reasyncRethrowsFunction { await asyncFunction() } // expected-error@-1:3 {{expression is 'async' but is not marked with 'await'}}{{3-3=await }} // expected-note@-2:3 {{call is 'async'}} await reasyncRethrowsFunction { await asyncFunction() } try reasyncRethrowsFunction { await asyncFunction() } // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error@-2:3 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-3:7 {{call is 'async'}} try await reasyncRethrowsFunction { await asyncFunction() } // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} reasyncRethrowsFunction { throw HorseError.colic } // expected-error@-1 {{call can throw but is not marked with 'try'}} // expected-note@-2 {{call is to 'rethrows' function, but argument function can throw}} await reasyncRethrowsFunction { throw HorseError.colic } // expected-error@-1 {{call can throw but is not marked with 'try'}} // expected-note@-2 {{call is to 'rethrows' function, but argument function can throw}} // expected-warning@-3 {{no 'async' operations occur within 'await' expression}} try reasyncRethrowsFunction { throw HorseError.colic } try await reasyncRethrowsFunction { throw HorseError.colic } // expected-warning@-1 {{no 'async' operations occur within 'await' expression}} reasyncRethrowsFunction { await asyncFunction(); throw HorseError.colic } // expected-error@-1 {{call can throw but is not marked with 'try'}} // expected-note@-2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@-3:3 {{expression is 'async' but is not marked with 'await'}}{{3-3=await }} // expected-note@-4:3 {{call is 'async'}} await reasyncRethrowsFunction { await asyncFunction(); throw HorseError.colic } // expected-error@-1 {{call can throw but is not marked with 'try'}} // expected-note@-2 {{call is to 'rethrows' function, but argument function can throw}} try reasyncRethrowsFunction { await asyncFunction(); throw HorseError.colic } // expected-error@-1:3 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-2:7 {{call is 'async'}} try await reasyncRethrowsFunction { await asyncFunction(); throw HorseError.colic } } func computeValue() -> Int {} func computeValueAsync() async -> Int {} func reasyncWithAutoclosure(_: @autoclosure () async -> Int) reasync {} func callReasyncWithAutoclosure1() { // expected-note@-1 2{{add 'async' to function 'callReasyncWithAutoclosure1()' to make it asynchronous}} reasyncWithAutoclosure(computeValue()) await reasyncWithAutoclosure(await computeValueAsync()) // expected-error@-1 {{'async' call in a function that does not support concurrency}} await reasyncWithAutoclosure(computeValueAsync()) // expected-error@-1:32 {{expression is 'async' but is not marked with 'await'}}{{32-32=await }} // expected-note@-2:32 {{call is 'async' in an autoclosure argument}} // expected-error@-3 {{'async' call in a function that does not support concurrency}} } func callReasyncWithAutoclosure2() async { reasyncWithAutoclosure(computeValue()) await reasyncWithAutoclosure(await computeValueAsync()) await reasyncWithAutoclosure(15 + computeValueAsync()) // expected-error@-1:32 {{expression is 'async' but is not marked with 'await'}}{{32-32=await }} // expected-note@-2:37 {{call is 'async' in an autoclosure argument}} } //// Reasync body checking // FIXME: Need tailored diagnostics to handle 'reasync' vs 'sync'. func invalidReasyncBody(_: () async -> ()) reasync { // expected-note@-1 {{add 'async' to function 'invalidReasyncBody' to make it asynchronous}} _ = await computeValueAsync() // expected-error@-1 {{'async' call in a function that does not support concurrency}} } func validReasyncBody(_ fn: () async -> ()) reasync { await fn() } //// String interpolation func reasyncWithAutoclosure2(_: @autoclosure () async -> String) reasync {} func callReasyncWithAutoclosure3() { let world = 123 reasyncWithAutoclosure2("Hello \(world)") } //// async let func callReasyncWithAutoclosure4(_: () async -> ()) reasync { await reasyncFunction { async let x = 123 _ = await x } }
c5e0041d2a69fbf6b0a1b550c7de61ee
40.0125
113
0.708321
false
false
false
false
EaglesoftZJ/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Contacts List/Cells/AAContactActionCell.swift
agpl-3.0
1
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation open class AAContactActionCell: AATableViewCell { public let titleView = YYLabel() public let iconView = UIImageView() public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) titleView.font = UIFont.systemFont(ofSize: 18) titleView.textColor = ActorSDK.sharedActor().style.cellTintColor titleView.displaysAsynchronously = true iconView.contentMode = UIViewContentMode.center self.contentView.addSubview(titleView) self.contentView.addSubview(iconView) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func bind(_ icon: String, actionTitle: String) { titleView.text = actionTitle iconView.image = UIImage.bundled(icon)?.tintImage(ActorSDK.sharedActor().style.cellTintColor) } open override func layoutSubviews() { super.layoutSubviews() let width = self.contentView.frame.width; iconView.frame = CGRect(x: 30, y: 8, width: 40, height: 40); titleView.frame = CGRect(x: 80, y: 8, width: width - 80 - 14, height: 40); } }
8610ef7fc46810c53e8b83a614207ccc
33.868421
101
0.667925
false
false
false
false
daltonclaybrook/swift-promises
refs/heads/master
Promises/Promise.swift
mit
1
// // Promise.swift // Promises // // Created by Dalton Claybrook on 7/1/15. // Copyright © 2015 Claybrook Software, LLC. All rights reserved. // typealias PromiseBlock = AnyObject? throws -> AnyObject? typealias DoneBlock = Void -> Void typealias CatchBlock = ErrorType -> Void func ==(lhs: Promise, rhs: Promise) -> Bool { return (ObjectIdentifier(lhs) == ObjectIdentifier(rhs)) } enum PromiseError: ErrorType { case Error } class Promise : Hashable, Equatable { var hashValue: Int { get { return ObjectIdentifier(self).hashValue } } init(block: PromiseBlock) { then(block) } func then(block: PromiseBlock) -> Self { PromiseManager.sharedManager.chainBlock(block, forPromise: self) return self } func catchError(block: CatchBlock) -> Self { PromiseManager.sharedManager.attachErrorBlock(block, forPromise: self) return self } func done(block: DoneBlock?) { PromiseManager.sharedManager.executeChainForPromise(self, withDoneBlock: block) } }
d3fdf0f89e85052d3e9f7b25807535b9
22.913043
87
0.649091
false
false
false
false
PJayRushton/TeacherTools
refs/heads/master
TeacherTools/GroupSettingsViewController.swift
mit
1
// // GroupSettingsViewController.swift // TeacherTools // // Created by Parker Rushton on 12/27/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit class GroupSettingsViewController: UITableViewController, AutoStoryboardInitializable { @IBOutlet weak var groupNameLabel: UILabel! @IBOutlet weak var groupNameTextField: UITextField! @IBOutlet weak var lastNameLabel: UILabel! @IBOutlet weak var lastNameSwitch: UISwitch! @IBOutlet weak var exportImageView: UIImageView! @IBOutlet weak var exportLabel: UILabel! @IBOutlet weak var deleteLabel: UILabel! @IBOutlet weak var themeLabel: UILabel! @IBOutlet weak var themeNameLabel: UILabel! @IBOutlet weak var rateLabel: UILabel! @IBOutlet weak var shareLabel: UILabel! @IBOutlet weak var upgradeLabel: UILabel! var core = App.core var group: Group? { return core.state.selectedGroup } fileprivate var saveBarButton = UIBarButtonItem() fileprivate var doneBarButton = UIBarButtonItem() fileprivate var flexy = UIBarButtonItem() fileprivate var toolbarTapRecognizer = UITapGestureRecognizer() fileprivate let appStoreURL = URL(string: "itms-apps://itunes.apple.com/app/id977797579") fileprivate let versionLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() setUp() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) core.add(subscriber: self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) core.remove(subscriber: self) } @IBAction func groupNameTextFieldChanged(_ sender: UITextField) { updateToolbar() } @IBAction func lastNameSwitchChanged(_ sender: UISwitch) { updateLastFirstPreference() } var isNewGroupName: Bool { guard groupNameTextField.isFirstResponder else { return false } guard let text = groupNameTextField.text else { return false } return text != group?.name } var toolbar: UIToolbar = { let toolbar = UIToolbar() toolbar.sizeToFit() toolbar.tintColor = .white toolbar.barTintColor = App.core.state.theme.tintColor return toolbar }() } // MARK: - Subscriber extension GroupSettingsViewController: Subscriber { func update(with state: AppState) { groupNameTextField.text = group?.name lastNameSwitch.isOn = state.currentUser?.lastFirst ?? false themeNameLabel.text = state.theme.name let proText = state.currentUser!.isPro ? "Thanks for upgrading to pro!" : "Upgrade to PRO!" upgradeLabel.text = proText updateUI(with: state.theme) tableView.reloadData() } func updateUI(with theme: Theme) { tableView.backgroundView = theme.mainImage.imageView let borderImage = theme.borderImage.image.stretchableImage(withLeftCapWidth: 0, topCapHeight: 0) navigationController?.navigationBar.setBackgroundImage(borderImage, for: .default) lastNameSwitch.onTintColor = theme.tintColor groupNameTextField.textColor = theme.textColor groupNameTextField.font = theme.font(withSize: 19) exportBarButton.tintColor = theme.tintColor exportImageView.tintColor = theme.textColor for label in [groupNameLabel, lastNameLabel, exportLabel, deleteLabel, themeLabel, themeNameLabel, rateLabel, shareLabel, upgradeLabel] { label?.font = theme.font(withSize: 17) label?.textColor = theme.textColor } upgradeLabel.textColor = core.state.currentUser!.isPro ? theme.textColor : .appleBlue deleteLabel.textColor = .red versionLabel.font = theme.font(withSize: 12) versionLabel.textColor = theme.textColor } } // MARK: Fileprivate extension GroupSettingsViewController { func setUp() { groupNameTextField.inputAccessoryView = toolbar setupToolbar() setUpVersionFooter() } func showThemeSelectionVC() { let themeVC = ThemeSelectionViewController.initializeFromStoryboard() navigationController?.pushViewController(themeVC, animated: true) } func launchAppStore() { guard let appStoreURL = appStoreURL, UIApplication.shared.canOpenURL(appStoreURL) else { core.fire(event: ErrorEvent(error: nil, message: "Error launching app store")) return } UIApplication.shared.open(appStoreURL, options: [:], completionHandler: nil) } func launchShareSheet() { let textToShare = "Check out this great app for teachers called Teacher Tools. You can find it in the app store!" var objectsToShare: [Any] = [textToShare] if let appStoreURL = URL(string: "https://itunes.apple.com/us/app/teacher-tools-tool-for-teachers/id977797579?mt=8") { objectsToShare.append(appStoreURL) } let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, .addToReadingList, .assignToContact, .openInIBooks, .postToTencentWeibo, .postToVimeo, .print, .saveToCameraRoll, .postToWeibo, .postToFlickr] activityVC.modalPresentationStyle = .popover let shareIndexPath = IndexPath(row: TableSection.app.rows.index(of: .share)!, section: TableSection.app.rawValue) activityVC.popoverPresentationController?.sourceRect = tableView.cellForRow(at: shareIndexPath)!.contentView.frame activityVC.popoverPresentationController?.sourceView = tableView.cellForRow(at: shareIndexPath)?.contentView present(activityVC, animated: true, completion: nil) } func showProVC() { let proVC = ProViewController.initializeFromStoryboard().embededInNavigationController proVC.modalPresentationStyle = .popover let proIndexPath = IndexPath(row: TableSection.app.rows.index(of: .pro)!, section: TableSection.app.rawValue) proVC.popoverPresentationController?.sourceRect = tableView.cellForRow(at: proIndexPath)!.contentView.frame proVC.popoverPresentationController?.sourceView = tableView.cellForRow(at: proIndexPath)?.contentView present(proVC, animated: true, completion: nil) } func showAlreadyProAlert() { let alert = UIAlertController(title: "Thanks for purchasing the PRO version", message: "If you haven't already, consider sharing this app with someone who would enjoy it, or rating it on the app store!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Rate", style: .default, handler: { _ in self.launchAppStore() })) alert.addAction(UIAlertAction(title: "Share", style: .default, handler: { _ in self.launchShareSheet() })) alert.addAction(UIAlertAction(title: "Later", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func presentNoDeleteAlert() { let alert = UIAlertController(title: "You won't have any classes left!", message: "You'll have to add a new class first", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func presentDeleteConfirmation() { var message = "This cannot be undone" guard let group = group else { return } if group.studentIds.count > 0 { let studentKey = group.studentIds.count == 1 ? "student" : "students" message = "This class's \(group.studentIds.count) \(studentKey) will also be deleted." } let alert = UIAlertController(title: "Are you sure?", message: message, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { _ in self.core.fire(command: DeleteObject(object: group)) guard let tabBarController = self.tabBarController as? MainTabBarController else { return } tabBarController.selectedIndex = 0 })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } @objc func saveClassName() { guard var group = group, let name = groupNameTextField.text else { core.fire(event: ErrorEvent(error: nil, message: "Error saving class")) return } let shouldSave = name.isEmpty == false && name != group.name if shouldSave { group.name = name core.fire(command: UpdateObject(object: group)) core.fire(event: DisplaySuccessMessage(message: "Saved!")) } else { groupNameTextField.text = group.name } groupNameTextField.resignFirstResponder() } @objc func toolbarTapped() { if isNewGroupName { saveClassName() } else { doneButtonPressed() } } @objc func doneButtonPressed() { view.endEditing(true) } func setupToolbar() { flexy = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: #selector(toolbarTapped)) saveBarButton = UIBarButtonItem(title: NSLocalizedString("Save", comment: ""), style: .plain, target: self, action: #selector(saveClassName)) doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneButtonPressed)) saveBarButton.setTitleTextAttributes([NSAttributedString.Key.font: core.state.theme.font(withSize: 20)], for: .normal) toolbarTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(toolbarTapped)) toolbar.addGestureRecognizer(toolbarTapRecognizer) toolbar.setItems([flexy, saveBarButton, flexy], animated: false) updateToolbar() } func updateToolbar() { let items = isNewGroupName ? [flexy, saveBarButton, flexy] : [flexy, doneBarButton] toolbar.setItems(items, animated: false) } func updateLastFirstPreference() { guard let user = core.state.currentUser else { core.fire(event: NoOp()) return } user.lastFirst = lastNameSwitch.isOn core.fire(command: UpdateUser(user: user)) } fileprivate func showExportShareSheet() { let textToShare = Exporter.exportStudentList(state: core.state) let objectsToShare: [Any] = [textToShare] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, .addToReadingList, .assignToContact, .openInIBooks, .postToTencentWeibo, .postToVimeo, .print, .saveToCameraRoll, .postToWeibo, .postToFlickr] activityVC.modalPresentationStyle = .popover activityVC.popoverPresentationController?.barButtonItem = exportBarButton present(activityVC, animated: true, completion: nil) } fileprivate func setUpVersionFooter() { versionLabel.frame = CGRect(x: 0, y: -2, width: view.frame.size.width * 0.95, height: 20) versionLabel.font = core.state.theme.font(withSize: 12) versionLabel.textColor = core.state.theme.textColor versionLabel.textAlignment = .right versionLabel.text = versionDescription let footerView = UIView() footerView.addSubview(versionLabel) tableView.tableFooterView = footerView } fileprivate var versionDescription: String { let versionDescription = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String var version = "3.1" if let versionString = versionDescription { version = versionString } return "version: \(version)" } } // MARK: - UITextFieldDelegate extension GroupSettingsViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { updateToolbar() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { saveClassName() return true } } // MARK: - UITableViewDelegate extension GroupSettingsViewController { enum TableSection: Int { case group case app var rows: [TableRow] { switch self { case .group: return [.className, .lastFirst, .export, .delete] case .app: return [.theme, .rate, .share, .pro] } } } enum TableRow { case className case lastFirst case export case delete case theme case rate case share case pro } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return Platform.isPad || UIDevice.current.type.isPlusSize ? 60 : 44 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = core.state.theme.tintColor let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = core.state.theme.font(withSize: 17) label.textColor = core.state.theme.isDefault ? .white : core.state.theme.textColor label.textAlignment = .center headerView.addSubview(label) headerView.addConstraint(headerView.centerYAnchor.constraint(equalTo: label.centerYAnchor)) headerView.addConstraint(headerView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: label.leadingAnchor)) headerView.addConstraint(headerView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: label.trailingAnchor)) switch TableSection(rawValue: section)! { case .group: label.text = "Class Settings" case .app: label.text = "App Settings" } return headerView } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let section = TableSection(rawValue: indexPath.section)! let row = section.rows[indexPath.row] switch row { case .className: groupNameTextField.becomeFirstResponder() case .lastFirst: lastNameSwitch.isOn = !lastNameSwitch.isOn lastNameSwitchChanged(lastNameSwitch) case .export: showExportShareSheet() case .delete: presentDeleteConfirmation() case .theme: showThemeSelectionVC() case .rate: launchAppStore() case .share: launchShareSheet() case .pro: guard let currentUser = core.state.currentUser, currentUser.isPro else { showProVC() return } showAlreadyProAlert() } } }
e3709266040ef622943172ef61d4545d
38.437018
235
0.663516
false
false
false
false
chrisbudro/GrowlerHour
refs/heads/master
growlers/MainBrowseViewController.swift
mit
1
// // MainBrowseViewController.swift // growlers // // Created by Chris Budro on 9/7/15. // Copyright (c) 2015 chrisbudro. All rights reserved. // import UIKit enum BrowseBySelector: Int { case Brewery = 0 case Style = 1 case Retailer = 2 case PoweredBy = 3 } final class MainBrowseViewController: UITableViewController { //MARK: Constants let numberOfCells: CGFloat = 3 let kPoweredByCellHeight: CGFloat = 60 //MARK: Properties var filter = Filter() //MARK: Life Cycle Methods override func viewDidLoad() { // filter.retrieveLocationDetails { (locationDetails, error) -> Void in // self.filter.locationDetails = locationDetails // } navigationItem.titleView = UIImageView(image: UIImage(named: "GrowlerHour")) let filterButton = UIBarButtonItem(image: UIImage(named: "sliders"), style: .Plain, target: self, action: "showFiltersWasPressed") navigationItem.rightBarButtonItem = filterButton } //MARK: Helper Methods func showFiltersWasPressed() { let filterViewNavController = storyboard?.instantiateViewControllerWithIdentifier("FilterViewNavController") as! UINavigationController let filterViewController = filterViewNavController.viewControllers.first as! FilterViewController filterViewController.filter = filter filterViewController.delegate = self presentViewController(filterViewNavController, animated: true, completion: nil) } } //MARK: Table View Delegate extension MainBrowseViewController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var viewController: BaseTableViewController? switch indexPath.row { case BrowseBySelector.Brewery.rawValue: viewController = BreweryBrowseTableViewController(style: .Plain) let queryManager = QueryManager(type: .Brewery, filter: filter) viewController?.queryManager = queryManager case BrowseBySelector.Style.rawValue: viewController = StyleBrowseTableViewController(style: .Plain) let queryManager = QueryManager(type: .BeerStyle, filter: filter) viewController?.queryManager = queryManager case BrowseBySelector.Retailer.rawValue: viewController = RetailerBrowseTableViewController(style: .Plain) let queryManager = QueryManager(type: .Retailer, filter: filter) viewController?.queryManager = queryManager default: break } if let viewController = viewController { navigationController?.pushViewController(viewController, animated: true) } } override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { if indexPath.row == BrowseBySelector.PoweredBy.rawValue { return false } return true } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == BrowseBySelector.PoweredBy.rawValue { return kPoweredByCellHeight } return view.bounds.height / numberOfCells } } //MARK: Filter Delegate extension MainBrowseViewController: FilterDelegate { func filterWasUpdated(filter: Filter) { self.filter = filter } }
2f464b6151a5d56ac05651cb0efb9177
32.684211
139
0.745858
false
false
false
false
thewisecity/declarehome-ios
refs/heads/master
CookedApp/ViewControllers/InviteMembersViewController.swift
gpl-3.0
1
// // InviteMembersViewController.swift // CookedApp // // Created by Dexter Lohnes on 12/4/15. // Copyright © 2015 The Wise City. All rights reserved. // import UIKit class InviteMembersViewController: UIViewController { @IBOutlet weak var groupName : UILabel? @IBOutlet weak var inviteeEmailAddress : UITextField? @IBOutlet weak var sendButton : UIButton? @IBOutlet weak var loadingView : UIView! var group : Group? { didSet { refreshInfo() } } override func viewDidLoad() { super.viewDidLoad() loadingView.hidden = true self.navigationController?.navigationBar.translucent = false // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func refreshInfo() { groupName?.text = group?.name } @IBAction func sendInvite(sender: UIButton) { loadingView.hidden = false PFCloud.callFunctionInBackground("inviteToGroup", withParameters: ["groupId" : (group?.objectId)!, "inviteeEmail" : (inviteeEmailAddress?.text)!]) { (result: AnyObject?, e : NSError?) -> Void in self.loadingView.hidden = true if (e != nil) { // Error print("Error while sending invite") //TODO: Alert popup? } else { self.inviteeEmailAddress?.text = nil //SUCCESS! //TODO: Alert popup? } } } /* // 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. } */ }
16549b333f510a39a6741a661b8e2064
27.410959
202
0.591128
false
false
false
false
SeptAi/Cooperate
refs/heads/master
Cooperate/Cooperate/Class/Tools/Extension/UIImage+extension.swift
mit
1
// // UIImage+extension.swift // Cooperate // // Created by J on 2017/1/4. // Copyright © 2017年 J. All rights reserved. // import UIKit extension UIImage{ // 图形性能优化 func cz_avatarImage(size:CGSize?, backColor:UIColor = UIColor.white, lineColor:UIColor = UIColor.lightGray) -> UIImage?{ var size = size if size == nil { size = self.size } let rect = CGRect(origin: CGPoint(), size: size!) UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) backColor.setFill() UIRectFill(rect) let path = UIBezierPath(ovalIn: rect) path.addClip() draw(in: rect) let ovalPath = UIBezierPath(ovalIn: rect) ovalPath.lineWidth = 2 lineColor.setStroke() ovalPath.stroke() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } }
e293e047f028b2591d16981823cd957c
23.95
124
0.57515
false
false
false
false
EZ-NET/CodePiece
refs/heads/Rev2
CodePiece/SNS/API/APIKeys.swift
gpl-3.0
1
// // APIKeys.swift // CodePiece // // Created by Tomohiro Kumagai on 2020/01/12. // Copyright © 2020 Tomohiro Kumagai. All rights reserved. // import Foundation import Ocean import CodePieceSupport /// API Keys. /// /// This class load APIKeys file each time referencing a static property for key or secret. struct APIKeys { /** A key and a initial vector for decryption. **/ /// APIKey data for GitHub. struct Gist { static var clientId: String? { return value(of: "GitHubClientID") } static var clientSecret: String? { return value(of: "GitHubClientSecret") } } /// APIKey data for Twitter. struct Twitter { static var consumerKey: String? { return value(of: "TwitterConsumerKey") } static var consumerSecret: String? { return value(of: "TwitterConsumerSecret") } } } private extension APIKeys { /// URL of APIKeys file. static var plistUrl = Bundle.main.url(forResource: "APIKeys", withExtension: "plist") /// API Keys data. static var plist: Dictionary<String, Any>? { guard let url = plistUrl else { return nil } return NSDictionary(contentsOf: url) as? Dictionary<String, Any> } static func stringValueFromPlistDirectly(_ name: String) -> String? { return plist?[name] as? String } static func dataValueFromPlistDirectly(_ name: String) -> Data? { return plist?[name] as? Data } static func value(of name: String) -> String? { #if DEBUG if let value = dataValueFromPlistDirectly("\(name)-Beta-Crypted") { return try! cipher.decrypto(value, initialVector: nil) } if let value = stringValueFromPlistDirectly("\(name)-Beta") { return value } #endif if let value = dataValueFromPlistDirectly("\(name)-Crypted") { return try! cipher.decrypto(value, initialVector: nil) } return stringValueFromPlistDirectly(name) } }
25af265c1a032c083cd05625edb984b8
18.306122
91
0.672304
false
false
false
false
jcantosm/coursera.ios
refs/heads/master
pizzas/pizzas/PizzaTipoMasaViewController.swift
apache-2.0
1
// // PizzaTipoMasaViewController.swift // pizzas // // Created by Javier Cantos on 05/01/16. // Copyright © 2016 Javier Cantos. All rights reserved. // import UIKit // lista de tipos de masas de pizza let masas = ["Delgada", "Crujiente", "Gruesa"] class PizzaTipoMasaViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { // índice del tamaño de pizza seleccionado var tamanyo = 0 // índice del tipo de masa seleccionado var masa = 0 // índice del tipo de queso seleccionado var queso = 0 // lista de ingredientes seleccionados de la pizza var pizza = Array<String>() // índice del tipo de masa seleccionado @IBOutlet weak var uiPickerTipoMasa: UIPickerView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { self.uiPickerTipoMasa.selectRow(self.masa, inComponent: 0, animated: true) } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return masas.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return masas[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.masa = row } // 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. if (segue.identifier == "pizzaTamanyoSegue") { let vc = segue.destinationViewController as! PizzaTamanyoViewController vc.masa = self.masa vc.queso = self.queso vc.tamanyo = self.tamanyo vc.pizza = self.pizza } if (segue.identifier == "pizzaTipoQuesoSegue") { let vc = segue.destinationViewController as! PizzaTipoQuesoViewController vc.masa = self.masa vc.queso = self.queso vc.tamanyo = self.tamanyo vc.pizza = self.pizza } } }
6c43837d484b342e0b4b5ae635647819
30.547619
109
0.655472
false
false
false
false
MosheBerman/Precalc
refs/heads/master
Precalc/Precalc/Graph.swift
mit
1
// // Graph.swift // Precalc // // Created by Moshe Berman on 12/25/16. // Copyright © 2016 Moshe Berman. All rights reserved. // import CoreGraphics /*: # The Graph When we draw graphs on paper, we usually draw an x axis and a y axis. Then, we calculate and plot points using a given interval. The graph view works in a similar way. By defining our positive and negative x limits, we can easily draw a square graph that scales to fit the frame of the view, and fits the defined number of calculations in our range. */ class GraphView : UIView { fileprivate(set) var equations : [GraphableEquation] = [] var x1: CGFloat = -15.0 var x2: CGFloat = 15.0 var interval : CGFloat = 1.0 fileprivate let graphBackgroundColor = UIColor(red: 0.95, green: 0.95, blue: 1.0, alpha: 1.0) fileprivate let graphLineColor = UIColor(red: 0.8, green: 0.9, blue: 1.0, alpha: 1.0) fileprivate lazy var scale : CGFloat = self.frame.width / (max(self.x1, self.x2) - min(self.x1, self.x2)) fileprivate var numberOfLines : Int { return Int(self.frame.width) / Int(scale) } // MARK: - Initializer convenience init(withSmallerXBound x1: CGFloat, largerXBound x2: CGFloat, andInterval interval: CGFloat) { // If this isn't square, weird things will happen. Sorry! self.init(frame: CGRect(x: 0, y: 0, width: 600, height: 600)) self.x1 = x1 self.x2 = x2 self.interval = interval } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } // MARK: - Adding Equations func clear() { self.equations = [] self.setNeedsDisplay() } func addEquation(_ equation: GraphableEquation) { _ = equation.compute(withInterval: self.interval, between: self.x1, and: self.x2) self.equations.append(equation) self.setNeedsDisplay() } // MARK: - Drawing override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } self.fillBackground(withContext: context, andRect: rect) self.drawHorizontalLines(withContext: context) self.drawVerticalLines(withContext: context) for equation in self.equations { self.drawEquation(equation, withContext: context, inRect: rect) } } // MARK: - Draw Equation func drawEquation(_ equation: GraphableEquation, withContext context: CGContext, inRect rect: CGRect) { let coordinates = equation.compute(withInterval: self.interval, between: x1, and: x2) self.drawLines(betweenCoordinates: coordinates, withContext: context, inRect: rect , usingColor: equation.drawingColor.cgColor) self.drawPoints(atCoordinates: coordinates, withContext: context, inRect: rect, usingColor: equation.drawingColor.cgColor) } // MARK: - Fill With Background Color func fillBackground(withContext context: CGContext, andRect rect: CGRect) { context.setFillColor(self.graphBackgroundColor.cgColor) context.fill(rect) } // MARK: - Draw Grid func drawHorizontalLines(withContext context: CGContext) { var y : CGFloat = 0.0 context.setStrokeColor(self.graphLineColor.cgColor) context.setLineWidth(0.5) while y < self.frame.height { if context.isPathEmpty == false { context.strokePath() // Stroke Axis if y == self.frame.width/2.0 { context.setLineWidth(2.0) } else { context.setLineWidth(1.0) } } context.move(to: CGPoint(x: 0.0, y: y)) context.addLine(to: CGPoint(x: self.frame.height, y: y)) y = y + self.scale } context.strokePath() } func drawVerticalLines(withContext context: CGContext) { var x : CGFloat = 0.0 context.setStrokeColor(self.graphLineColor.cgColor) context.setLineWidth(0.5) while x < self.frame.height { if context.isPathEmpty == false { context.strokePath() } // Stroke Axis if x == self.frame.height/2.0 { context.setLineWidth(2.0) } else { context.setLineWidth(1.0) } context.move(to: CGPoint(x: x, y: 0.0)) context.addLine(to: CGPoint(x: x, y: self.frame.width)) x = x + self.scale } context.strokePath() } // MARK: - Draw the Graph func drawPoints(atCoordinates coordinates: [Coordinate], withContext context: CGContext, inRect rect: CGRect, usingColor color: CGColor) { context.setStrokeColor(color) context.setLineWidth(2.0) for coordinate in coordinates { let translated = self.translated(coordinate: coordinate, toRect: rect) context.move(to: translated) self.drawCircle(inContext: context, atCoordinate: translated) } context.strokePath() } func drawLines(betweenCoordinates coordinates: [Coordinate], withContext context: CGContext, inRect rect: CGRect, usingColor color: CGColor) { context.setStrokeColor(color) context.setLineWidth(1.0) let translated = self.translated(coordinate: coordinates[0], toRect: rect) context.move(to: translated) for coordinate in coordinates { let translated = self.translated(coordinate: coordinate, toRect: rect) context.addLine(to: translated) context.move(to: translated) } context.strokePath() } // MARK: - Convert Coordinates to the CGContext func translated(coordinate coord: Coordinate, toRect rect: CGRect) -> Coordinate { var coordinate : Coordinate = coord let scale = self.scale coordinate.x = (rect.width / 2.0) + (coordinate.x * scale) coordinate.y = (rect.height / 2.0) + (-coordinate.y * scale) return coordinate } // MARK: - Draw a Circle func drawCircle(inContext context: CGContext, atCoordinate coordinate: Coordinate) { context.addArc(center: coordinate, radius: 1.0, startAngle: 0.0, endAngle: CGFloat(M_PI) * 2.0, clockwise: false) } }
ec06f0f221390aca77bc3297e4d9918a
28.918455
350
0.573662
false
false
false
false