repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
aschwaighofer/swift
test/DebugInfo/enum.swift
1
3421
// RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | %FileCheck %s // RUN: %target-swift-frontend -primary-file %s -emit-ir -gdwarf-types -o - | %FileCheck %s --check-prefix=DWARF // UNSUPPORTED: OS=watchos protocol P {} enum Either { case First(Int64), Second(P), Neither // CHECK: !DICompositeType({{.*}}name: "Either", // CHECK-SAME: line: [[@LINE-3]], // CHECK-SAME: size: {{328|168}}, } // CHECK: ![[EMPTY:.*]] = !{} // DWARF: ![[INT:.*]] = !DICompositeType({{.*}}identifier: "$sSiD" let E : Either = .Neither; // CHECK: !DICompositeType({{.*}}name: "Color", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: size: 8, // CHECK-SAME: identifier: "$s4enum5ColorOD" enum Color : UInt64 { // This is effectively a 2-bit bitfield: // DWARF: !DIDerivedType(tag: DW_TAG_member, name: "Red" // DWARF-SAME: baseType: ![[UINT64:[0-9]+]] // DWARF-SAME: size: 8{{[,)]}} // DWARF: ![[UINT64]] = !DICompositeType({{.*}}identifier: "$ss6UInt64VD" case Red, Green, Blue } // CHECK: !DICompositeType({{.*}}name: "MaybeIntPair", // CHECK-SAME: line: [[@LINE+3]], // CHECK-SAME: size: 136{{[,)]}} // CHECK-SAME: identifier: "$s4enum12MaybeIntPairOD" enum MaybeIntPair { // DWARF: !DIDerivedType(tag: DW_TAG_member, name: "none" // DWARF-SAME: baseType: ![[INT]]{{[,)]}} case none // DWARF: !DIDerivedType(tag: DW_TAG_member, name: "just" // DWARF-SAME: baseType: ![[INTTUP:[0-9]+]] // DWARF-SAME: size: 128{{[,)]}} // DWARF: ![[INTTUP]] = !DICompositeType({{.*}}identifier: "$ss5Int64V_ABtD" case just(Int64, Int64) } enum Maybe<T> { case none case just(T) } let r = Color.Red let c = MaybeIntPair.just(74, 75) // CHECK: !DICompositeType({{.*}}name: "Maybe", // CHECK-SAME: line: [[@LINE-8]], // CHECK-SAME: identifier: "$s4enum5MaybeOyAA5ColorOGD" let movie : Maybe<Color> = .none public enum Nothing { } public func foo(_ empty : Nothing) { } // CHECK: !DICompositeType({{.*}}name: "Nothing", {{.*}}elements: ![[EMPTY]] // CHECK: !DICompositeType({{.*}}name: "Rose", // CHECK-SAME: {{.*}}identifier: "$s4enum4RoseOyxG{{z?}}D") enum Rose<A> { case MkRose(() -> A, () -> [Rose<A>]) // DWARF: !DICompositeType({{.*}}name: "Rose",{{.*}}identifier: "$s4enum4RoseOyxGD") case IORose(() -> Rose<A>) } func foo<T>(_ x : Rose<T>) -> Rose<T> { return x } // CHECK: !DICompositeType({{.*}}name: "Tuple", {{.*}}identifier: "$s4enum5TupleOyxGD") // DWARF: !DICompositeType({{.*}}name: "Tuple", // DWARF-SAME: {{.*}}identifier: "$s4enum5TupleOyxG{{z?}}D") public enum Tuple<P> { case C(P, () -> Tuple) } func bar<T>(_ x : Tuple<T>) -> Tuple<T> { return x } // CHECK-DAG: ![[LIST:.*]] = !DICompositeType({{.*}}identifier: "$s4enum4ListOyxGD" // CHECK-DAG: ![[LIST_MEMBER:.*]] = !DIDerivedType(tag: DW_TAG_member, {{.*}} baseType: ![[LIST]] // CHECK-DAG: ![[LIST_ELTS:.*]] = !{![[LIST_MEMBER]]} // CHECK-DAG: ![[LIST_CONTAINER:.*]] = !DICompositeType({{.*}}elements: ![[LIST_ELTS]] // CHECK-DAG: ![[LET_LIST:.*]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[LIST_CONTAINER]]) // CHECK-DAG: !DILocalVariable(name: "self", arg: 1, {{.*}} line: [[@LINE+4]], type: ![[LET_LIST]], flags: DIFlagArtificial) public enum List<T> { indirect case Tail(List, T) case End func fooMyList() {} }
apache-2.0
1890a811125f1a99f8efb9914717a06d
36.184783
124
0.572932
3.224317
false
false
false
false
zhfish/XMMediator
Sources/XMMediator+Router.swift
1
3271
// // XMMediator+Router.swift // XMMediator // // Created by 王晨 on 2017/3/5. // Copyright © 2017年 天星宿命. All rights reserved. // import Foundation // MARK: - 路由支持扩展 extension XMMediator { /// 远程调用入口(有规则检查) /// /// - Parameters: /// - url: 规则:scheme://[token]@[target]/[action]?[params] /// URL例子: myapp://token@targetA/actionB?id=1234 /// - Returns: 如果没有返回值,则返回nil public func openURL(with urlString:String) -> Any? { return openURL(with: urlString, isVerify: true) } /// 远程调用入口(可选规则检查) /// /// - Parameters: /// - url: 规则:scheme://[token]@[target]/[action]?[params] /// URL例子: myapp://token@targetA/actionB?id=1234 /// - isVerify: 使用规则检查 /// - Returns: 如果没有返回值,则返回nil public func openURL(with urlString:String, isVerify:Bool) -> Any? { guard let url = URL(string: urlString) else { return false } guard isVerify && validationRule(URL: url) else { return false } return performWith(targetName: url.xm_target!, actionName: url.xm_action!, params: url.xm_params, shouldCacheTarget: false) } /// 远程调用规则检查 /// /// - Parameter urlString: url字符串 /// - Returns: 返回布尔值,表示是否可以远程调用 public func canOpenURL(with urlString:String) -> Bool { guard let url = URL(string: urlString) else { return false } return validationRule(URL: url) } /// 验证规则 /// /// - Parameter url: url类 /// - Returns: 返回布尔值 private func validationRule(URL url:URL) -> Bool { //判断token guard config.isURLTokenVerifySkip == true , url.xm_token == config.URLToken else { return false } guard config.isURLRuleVerifySkip == false else { return true } guard let rule = config.URLRouteRule else { return false } guard let scheme = url.scheme else { return false } guard rule.schemes.contains(scheme) else { return false } guard let target = url.xm_target else { return false } guard let action = url.xm_action else { return false } let target_array = rule.targets[target] var action_find = false if target_array != nil { if target_array!.count == 0 { action_find = true } else { action_find = target_array!.contains(action) } } switch rule.defaultRule { case "allow": guard action_find == false else { return false } break case "deny": guard action_find == true else { return false } break default: return false } return true } }
mit
2537c69fb202267cf03c869b93317d7a
24.366667
131
0.505913
4.233658
false
false
false
false
ljshj/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Contacts List/Cells/AAContactCell.swift
1
2377
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import UIKit public class AAContactCell : AATableViewCell, AABindedCell, AABindedSearchCell { public typealias BindData = ACContact public static func bindedCellHeight(table: AAManagedTable, item: BindData) -> CGFloat { return 56 } public static func bindedCellHeight(item: BindData) -> CGFloat { return 56 } public let avatarView = AAAvatarView() public let shortNameView = YYLabel() public let titleView = YYLabel() public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) titleView.font = UIFont.systemFontOfSize(18) titleView.textColor = appStyle.contactTitleColor titleView.displaysAsynchronously = true shortNameView.font = UIFont.boldSystemFontOfSize(18) shortNameView.textAlignment = NSTextAlignment.Center shortNameView.textColor = appStyle.contactTitleColor shortNameView.displaysAsynchronously = true self.contentView.addSubview(avatarView) self.contentView.addSubview(shortNameView) self.contentView.addSubview(titleView) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func bind(item: ACContact, search: String?) { bind(item) } public func bind(item: ACContact, table: AAManagedTable, index: Int, totalCount: Int) { bind(item) } func bind(item: ACContact) { avatarView.bind(item.name, id: Int(item.uid), avatar: item.avatar); titleView.text = item.name; shortNameView.hidden = true } func bindDisabled(disabled: Bool) { if disabled { titleView.alpha = 0.5 avatarView.alpha = 0.5 } else { titleView.alpha = 1 avatarView.alpha = 1 } } public override func layoutSubviews() { super.layoutSubviews() let width = self.contentView.frame.width; shortNameView.frame = CGRectMake(0, 8, 30, 40); avatarView.frame = CGRectMake(30, 8, 44, 44); titleView.frame = CGRectMake(80, 8, width - 80 - 14, 40); } }
mit
8d781952971a2de902bd8a39bd8a5ac9
29.487179
91
0.635255
4.811741
false
false
false
false
dander521/ShareTest
Uhome/Classes/Module/Login/Controller/LoginViewController.swift
1
11947
// // LoginViewController.swift // Uhome // // Created by 程荣刚 on 2017/6/2. // Copyright © 2017年 menhao. All rights reserved. // import Foundation import UIKit import KRProgressHUD import Then import Alamofire import HandyJSON class LoginViewController: BaseViewController { var backgroundView: UIImageView! var headImageView: UIImageView! var headLabel: UILabel! var phoneTF: UITextField! var codeViewTF: UITextField! var codeView: WSAuthCode! var pincodeTF: UITextField! var pincodeButton: UIButton! var loginButton: UIButton! var phoneLabel: UILabel! var codeViewLabel: UILabel! var pincodeLabel: UILabel! var phoneCode: String? override func viewDidLoad() { super.viewDidLoad() self.clearNavigationBarColor() self.setUpUI() self.customizeTF() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// 导航栏透明 func clearNavigationBarColor() { var textAttrs: [String : AnyObject] = Dictionary() textAttrs[NSForegroundColorAttributeName] = UIColor.white textAttrs[NSFontAttributeName] = UIFont.systemFont(ofSize: 16) self.navigationController?.navigationBar.titleTextAttributes = textAttrs navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationController?.navigationBar.shadowImage = UIImage() UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent navigationController?.navigationBar.isTranslucent = true } /// 登录 func touchLoginBtn() { requestLogin() } func requestLogin() { // if self.phoneTF.text == nil || Validate.phoneNum(self.phoneTF.text!).isRight == false { // MBProgressHUD.showMessage("请输入正确手机号码") // return // } // // if self.phoneCode == nil { // MBProgressHUD.showMessage("请输入正确验证码") // return // } MBProgressHUD.showMessage("请求中...") UhomeNetManager.sharedInstance.postRequest(urlString: loginByCode, params: ["mobile" : self.phoneTF.text!, "code" : self.phoneCode!], success: { (successJson) in MBProgressHUD.hide() if let model = JSONDeserializer<LoginModel>.deserializeFrom(json: successJson) { print(model.msg ?? "msg") TXModelAchivar.updateUserModel(withKey: "userId", value: model.data["id"] as! String) TXModelAchivar.updateUserModel(withKey: "mobile", value: model.data["mobile"] as! String) TXModelAchivar.updateUserModel(withKey: "point", value: model.data["point"] as! String) TXModelAchivar.updateUserModel(withKey: "user_name", value: model.data["user_name"] as! String) } UIApplication.shared.keyWindow?.rootViewController = MainNavigationController.init(rootViewController: BMPViewController()) TXModelAchivar.updateUserModel(withKey: "isLogin", value: "1") }, failure: { (errorMsg) in MBProgressHUD.hide() }) } /// 获取手机验证码 func touchPincodeBtn() { TXCountDownTime.shared().start(withTime: 60, title: "获取验证码", countDownTitle: "重新获取", mainColor: UIColor.yellow, count: UIColor.lightGray, atBtn: self.pincodeButton) // if self.phoneTF.text != nil && Validate.phoneNum(self.phoneTF.text!).isRight { MBProgressHUD.showMessage("请求中...") UhomeNetManager.sharedInstance.postRequest(urlString: loginGetCode, params: ["mobile" : self.phoneTF.text!], success: { (successJson) in MBProgressHUD.hide() // FIXME: 处理手机验证码返回 // self.phoneCode = ? if let model = JSONDeserializer<LoginCodeModel>.deserializeFrom(json: successJson) { print(model.msg ?? "msg") self.phoneCode = model.data["code"] as? String } }, failure: { (errorMsg) in MBProgressHUD.hide() }) // } else { // MBProgressHUD.showMessage("请输入正确的手机号码") // } } /// 刷新图形验证码 func touchRefreshPincodeBtn() { codeView.reloadView() } /// 配置UI func setUpUI() { view.backgroundColor = UIColor.white backgroundView = UIImageView().then { $0.backgroundColor = UIColor.clear } codeView = WSAuthCode.init(frame: CGRect(x:0,y:0,width:100,height:44), allWordArraytype: OnlyNumbers) headImageView = UIImageView().then { $0.backgroundColor = UIColor.clear $0.image = UIImage.init(named: "background") $0.layer.cornerRadius = 50 $0.layer.masksToBounds = true } headLabel = UILabel().then { $0.backgroundColor = UIColor.clear $0.text = "TKC光轴链" $0.textAlignment = NSTextAlignment.center $0.textColor = UIColor.black $0.font = UIFont.systemFont(ofSize: 14) } phoneLabel = UILabel().then { $0.backgroundColor = UIColor.black } codeViewLabel = UILabel().then { $0.backgroundColor = UIColor.black } pincodeLabel = UILabel().then { $0.backgroundColor = UIColor.black } phoneTF = UITextField().then { $0.backgroundColor = UIColor.white $0.font = UIFont.systemFont(ofSize: 14) $0.borderStyle = UITextBorderStyle.none $0.textAlignment = NSTextAlignment.left } pincodeTF = UITextField().then { $0.isSecureTextEntry = false $0.borderStyle = UITextBorderStyle.none $0.backgroundColor = UIColor.white $0.font = UIFont.systemFont(ofSize: 14) $0.textAlignment = NSTextAlignment.left } codeViewTF = UITextField().then { $0.isSecureTextEntry = false $0.borderStyle = UITextBorderStyle.none $0.backgroundColor = UIColor.white $0.font = UIFont.systemFont(ofSize: 14) $0.textAlignment = NSTextAlignment.left } pincodeButton = UIButton().then { $0.layer.cornerRadius = 5 $0.layer.masksToBounds = true $0.backgroundColor = UIColor.yellow $0.titleLabel?.font = UIFont.systemFont(ofSize: 16) $0.setTitle("获取验证码", for: UIControlState.normal) $0.setTitleColor(UIColor.black, for: UIControlState.normal) $0.addTarget(self, action: #selector(LoginViewController.touchPincodeBtn), for: UIControlEvents.touchUpInside) } loginButton = UIButton().then { $0.layer.cornerRadius = 5 $0.layer.masksToBounds = true $0.backgroundColor = UIColor.yellow $0.titleLabel?.font = UIFont.systemFont(ofSize: 20) $0.setTitle("登 录", for: UIControlState.normal) $0.setTitleColor(UIColor.black, for: UIControlState.normal) $0.addTarget(self, action: #selector(LoginViewController.touchLoginBtn), for: UIControlEvents.touchUpInside) } view.addSubview(backgroundView) view.addSubview(headImageView) view.addSubview(headLabel) view.addSubview(phoneTF) view.addSubview(pincodeTF) view.addSubview(codeViewTF) view.addSubview(pincodeButton) view.addSubview(loginButton) view.addSubview(codeView) view.addSubview(phoneLabel) view.addSubview(codeViewLabel) view.addSubview(pincodeLabel) backgroundView.mas_makeConstraints {make in make?.edges.mas_equalTo()(self.view) } headImageView.mas_makeConstraints { make in make?.top.equalTo()(self.view)?.setOffset(100) make?.centerX.equalTo()(self.view) make?.height.equalTo()(100) make?.width.equalTo()(100) } headLabel.mas_makeConstraints { make in make?.top.equalTo()(self.headImageView.mas_bottom)?.setOffset(15) make?.centerX.equalTo()(self.view) make?.height.equalTo()(20) make?.width.equalTo()(150) } phoneTF.mas_makeConstraints { make in make?.top.equalTo()(self.headLabel.mas_bottom)?.setOffset(40) make?.left.equalTo()(self.view)?.setOffset(20) make?.right.equalTo()(self.view)?.setOffset(-20) make?.height.equalTo()(44) } codeViewTF.mas_makeConstraints { make in make?.top.equalTo()(self.phoneTF.mas_bottom)?.setOffset(20) make?.left.equalTo()(self.view)?.setOffset(20) make?.right.equalTo()(self.codeView.mas_left)?.setOffset(-10) make?.height.equalTo()(44) } codeView.mas_makeConstraints { make in make?.top.equalTo()(self.phoneTF.mas_bottom)?.setOffset(20) make?.left.equalTo()(self.codeViewTF.mas_right)?.setOffset(10) make?.height.equalTo()(44) make?.right.equalTo()(self.view)?.setOffset(-20) make?.width.equalTo()(100) } pincodeTF.mas_makeConstraints { make in make?.top.equalTo()(self.codeView.mas_bottom)?.setOffset(20) make?.left.equalTo()(self.view)?.setOffset(20) make?.height.equalTo()(44) } pincodeButton.mas_makeConstraints { make in make?.top.equalTo()(self.codeView.mas_bottom)?.setOffset(20) make?.left.equalTo()(self.pincodeTF.mas_right)?.setOffset(10) make?.right.equalTo()(self.view)?.setOffset(-20) make?.height.equalTo()(44) make?.width.equalTo()(100) } loginButton.mas_makeConstraints { make in make?.top.equalTo()(self.pincodeTF.mas_bottom)?.setOffset(60) make?.left.equalTo()(self.view)?.setOffset(20) make?.right.equalTo()(self.view)?.setOffset(-20) make?.height.equalTo()(50) } phoneLabel.mas_makeConstraints { make in make?.top.equalTo()(self.phoneTF.mas_bottom) make?.left.equalTo()(self.phoneTF.mas_left) make?.right.equalTo()(self.phoneTF.mas_right) make?.height.equalTo()(0.5) } codeViewLabel.mas_makeConstraints { make in make?.top.equalTo()(self.codeViewTF.mas_bottom) make?.left.equalTo()(self.codeViewTF.mas_left) make?.right.equalTo()(self.codeViewTF.mas_right) make?.height.equalTo()(0.5) } pincodeLabel.mas_makeConstraints { make in make?.top.equalTo()(self.pincodeTF.mas_bottom) make?.left.equalTo()(self.pincodeTF.mas_left) make?.right.equalTo()(self.pincodeTF.mas_right) make?.height.equalTo()(0.5) } } } extension LoginViewController { func customizeTF() { phoneTF.attributedPlaceholder = NSAttributedString(string: "输入手机号", attributes: [NSForegroundColorAttributeName: UIColor.lightGray]) codeViewTF.attributedPlaceholder = NSAttributedString(string: "图形验证码", attributes: [NSForegroundColorAttributeName: UIColor.lightGray]) pincodeTF.attributedPlaceholder = NSAttributedString(string: "输入验证码", attributes: [NSForegroundColorAttributeName: UIColor.lightGray]) } }
mit
bdea0033f68e304d0dfc510bd76da0f2
37.491803
172
0.598126
4.631164
false
false
false
false
wangyaqing/LeetCode-swift
Solutions/34. Find First and Last Position of Element in Sorted Array.playground/Contents.swift
1
1153
import UIKit class Solution { func searchRange(_ nums: [Int], _ target: Int) -> [Int] { let result = searchRange(nums, 0, nums.count - 1, target) if result.count == 0 { return [-1, -1] } else if result.count == 1 { return [result.first!, result.first!] } else { return [result.first!, result.last!] } } func searchRange(_ nums: [Int], _ start: Int, _ end: Int, _ target: Int) -> [Int] { guard end >= start else { return [] } if end == start { if nums[start] == target { return [start] } else { return [] } } let left = start let right = end if nums[left] > target || nums[right] < target { return [] } let mid = (start + end) / 2 var leftResult = searchRange(nums, left, mid, target) let rightResult = searchRange(nums, mid + 1, right, target) leftResult.append(contentsOf: rightResult) return leftResult } } print(Solution().searchRange([5,7,7,8,8,10], 7))
mit
538f9624af6c9d89988742c914006785
28.564103
87
0.487424
4.031469
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeUIMagic/AwesomeUIMagic/Classes/Old/UIViewExtensions.swift
1
3300
// // UIView+Layers.swift // MV UI Hacks // // Created by Evandro Harrison Hoffmann on 07/07/2016. // Copyright © 2016 It's Day Off. All rights reserved. // import UIKit extension UIView { // MARK: - Triangle public func addTringleView(_ rect: CGRect, fillColor: UIColor) { guard let context = UIGraphicsGetCurrentContext() else { return } context.beginPath() context.move(to: CGPoint(x: rect.minX, y: rect.maxY)) context.addLine(to: CGPoint(x: rect.midX, y: rect.minY)) context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) context.closePath() context.setFillColor(fillColor.cgColor) context.fillPath() } // MARK: - Single corner radius public func addCornerRadius(byRoundingCorners corners: UIRectCorner, radius: CGFloat) { let rectShape = CAShapeLayer() rectShape.bounds = self.frame rectShape.position = self.center rectShape.path = UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath self.layer.mask = rectShape self.layer.masksToBounds = true self.layoutIfNeeded() } // MARK: - Blur effect public func addBluredBackground(style: UIBlurEffectStyle = .dark) { for view in subviews { if view is UIVisualEffectView { view.removeFromSuperview() } } let blurEffect = UIBlurEffect(style: style) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.addSubview(blurEffectView) } // // MARK: - MagicID Associations // // private static let magicID = ObjectAssociation<NSObject>() // // // MARK: - MagicID // // @IBInspectable // public var magicID: String { // get { // return UIView.magicID[self] as? String ?? "" // } // set (newValue) { // UIView.magicID[self] = newValue as NSObject // } // } // // // MARK: - Snapshots // // public func snapshotsFrom() -> [(UIView, CGPoint, CGRect)] { // return processSnapshots(snapshotsArray: []) // } // // fileprivate func processSnapshots(_ subviews: [UIView]? = nil, snapshotsArray: [(UIView, CGPoint, CGRect)]) -> [(UIView, CGPoint, CGRect)] { // var snapshots = snapshotsArray // for view in (subviews ?? self.subviews) { // if !view.magicID.isEmpty { // view.subviews.forEach({ $0.isHidden = true }) // if let snapshot = view.snapshotView(afterScreenUpdates: true) { // view.subviews.forEach({ $0.isHidden = false }) // snapshot.magicID = view.magicID // snapshots.append((snapshot, self.convert(view.center, from: view.superview), self.convert(view.frame, from: view.superview))) // } // } // // if !view.subviews.isEmpty { // snapshots = processSnapshots(view.subviews, snapshotsArray: snapshots) // } // } // return snapshots // } }
mit
87a2528dd89fde5bdc0012365362a843
32.323232
149
0.586541
4.318063
false
false
false
false
bay2/LetToDo
LetToDo/Home/View/HomeGroupCollectionViewCell.swift
1
3198
// // HomeGroupCollectionViewCell.swift // LetToDo // // Created by xuemincai on 2016/10/4. // Copyright © 2016年 xuemincai. All rights reserved. // import UIKit import IBAnimatable import RandomColor import RxSwift import RxCocoa import EZSwiftExtensions class HomeGroupCollectionViewCell: UICollectionViewCell { @IBOutlet weak var editBtn: UIButton! @IBOutlet weak var editView: UIView! @IBOutlet weak var displayView: UIView! @IBOutlet weak var moreBtn: UIButton! @IBOutlet weak var mainView: AnimatableView! @IBOutlet weak var groupTitle: UILabel! @IBOutlet weak var itemLab: UILabel! var groupID: String! fileprivate var doubleTap = UITapGestureRecognizer() fileprivate var disposebag = DisposeBag() var transformAinmate: ZoomTransitioning! override func awakeFromNib() { super.awakeFromNib() transformAinmate = ZoomTransitioning(zoomView: mainView); groupTitle.textColor = randomColor(hue: .random, luminosity: .bright) editView.addGestureRecognizer(doubleTap) doubleTap.numberOfTapsRequired = 2 // MARK: 模式切换 do { let switchAnimate = { [unowned self] in self.editView.isHidden = !self.editView.isHidden self.displayView.isHidden = !self.displayView.isHidden self.mainView.animate() } doubleTap.rx .event .map{ _ -> Void in return } .bindNext(switchAnimate) .addDisposableTo(disposebag) moreBtn.rx.tap .bindNext(switchAnimate) .addDisposableTo(disposebag) } // MARK: 点击编辑 do { editBtn.rx .tap .bindNext { let nav = StoryboardScene.Home.instantiateEditGroupViewNavController() nav.transitioningDelegate = self guard let vc = nav.topViewController as? EditGroupViewController else { return } vc.groupTitle = self.groupTitle.text vc.groupID = self.groupID ez.topMostVC?.presentVC(nav) } .addDisposableTo(disposebag) } } } extension HomeGroupCollectionViewCell: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transformAinmate.transitionType = .Present return transformAinmate } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transformAinmate.transitionType = .Dismiss return transformAinmate } }
mit
1f2851bc311da8b2ffdfca0a7b550273
28.165138
177
0.571249
6.066794
false
false
false
false
austinzheng/swift
stdlib/public/core/CTypes.swift
2
8637
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // C Primitive Types //===----------------------------------------------------------------------===// /// The C 'char' type. /// /// This will be the same as either `CSignedChar` (in the common /// case) or `CUnsignedChar`, depending on the platform. public typealias CChar = Int8 /// The C 'unsigned char' type. public typealias CUnsignedChar = UInt8 /// The C 'unsigned short' type. public typealias CUnsignedShort = UInt16 /// The C 'unsigned int' type. public typealias CUnsignedInt = UInt32 /// The C 'unsigned long' type. #if os(Windows) && arch(x86_64) public typealias CUnsignedLong = UInt32 #else public typealias CUnsignedLong = UInt #endif /// The C 'unsigned long long' type. public typealias CUnsignedLongLong = UInt64 /// The C 'signed char' type. public typealias CSignedChar = Int8 /// The C 'short' type. public typealias CShort = Int16 /// The C 'int' type. public typealias CInt = Int32 /// The C 'long' type. #if os(Windows) && arch(x86_64) public typealias CLong = Int32 #else public typealias CLong = Int #endif /// The C 'long long' type. public typealias CLongLong = Int64 /// The C 'float' type. public typealias CFloat = Float /// The C 'double' type. public typealias CDouble = Double /// The C 'long double' type. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // On Darwin, long double is Float80 on x86, and Double otherwise. #if arch(x86_64) || arch(i386) public typealias CLongDouble = Float80 #else public typealias CLongDouble = Double #endif #elseif os(Windows) // On Windows, long double is always Double. public typealias CLongDouble = Double #elseif os(Linux) // On Linux/x86, long double is Float80. // TODO: Fill in definitions for additional architectures as needed. IIRC // armv7 should map to Double, but arm64 and ppc64le should map to Float128, // which we don't yet have in Swift. #if arch(x86_64) || arch(i386) public typealias CLongDouble = Float80 #endif // TODO: Fill in definitions for other OSes. #if arch(s390x) // On s390x '-mlong-double-64' option with size of 64-bits makes the // Long Double type equivalent to Double type. public typealias CLongDouble = Double #endif #endif // FIXME: Is it actually UTF-32 on Darwin? // /// The C++ 'wchar_t' type. public typealias CWideChar = Unicode.Scalar // FIXME: Swift should probably have a UTF-16 type other than UInt16. // /// The C++11 'char16_t' type, which has UTF-16 encoding. public typealias CChar16 = UInt16 /// The C++11 'char32_t' type, which has UTF-32 encoding. public typealias CChar32 = Unicode.Scalar /// The C '_Bool' and C++ 'bool' type. public typealias CBool = Bool /// A wrapper around an opaque C pointer. /// /// Opaque pointers are used to represent C pointers to types that /// cannot be represented in Swift, such as incomplete struct types. @_fixed_layout public struct OpaquePointer { @usableFromInline internal var _rawValue: Builtin.RawPointer @usableFromInline @_transparent internal init(_ v: Builtin.RawPointer) { self._rawValue = v } /// Creates an `OpaquePointer` from a given address in memory. @_transparent public init?(bitPattern: Int) { if bitPattern == 0 { return nil } self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Creates an `OpaquePointer` from a given address in memory. @_transparent public init?(bitPattern: UInt) { if bitPattern == 0 { return nil } self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Converts a typed `UnsafePointer` to an opaque C pointer. @_transparent public init<T>(_ from: UnsafePointer<T>) { self._rawValue = from._rawValue } /// Converts a typed `UnsafePointer` to an opaque C pointer. /// /// The result is `nil` if `from` is `nil`. @_transparent public init?<T>(_ from: UnsafePointer<T>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } /// Converts a typed `UnsafeMutablePointer` to an opaque C pointer. @_transparent public init<T>(_ from: UnsafeMutablePointer<T>) { self._rawValue = from._rawValue } /// Converts a typed `UnsafeMutablePointer` to an opaque C pointer. /// /// The result is `nil` if `from` is `nil`. @_transparent public init?<T>(_ from: UnsafeMutablePointer<T>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } } extension OpaquePointer: Equatable { @inlinable // unsafe-performance public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue)) } } extension OpaquePointer: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(Int(Builtin.ptrtoint_Word(_rawValue))) } } extension OpaquePointer : CustomDebugStringConvertible { /// A textual representation of the pointer, suitable for debugging. public var debugDescription: String { return _rawPointerToString(_rawValue) } } extension Int { /// Creates a new value with the bit pattern of the given pointer. /// /// The new value represents the address of the pointer passed as `pointer`. /// If `pointer` is `nil`, the result is `0`. /// /// - Parameter pointer: The pointer to use as the source for the new /// integer. @inlinable // unsafe-performance public init(bitPattern pointer: OpaquePointer?) { self.init(bitPattern: UnsafeRawPointer(pointer)) } } extension UInt { /// Creates a new value with the bit pattern of the given pointer. /// /// The new value represents the address of the pointer passed as `pointer`. /// If `pointer` is `nil`, the result is `0`. /// /// - Parameter pointer: The pointer to use as the source for the new /// integer. @inlinable // unsafe-performance public init(bitPattern pointer: OpaquePointer?) { self.init(bitPattern: UnsafeRawPointer(pointer)) } } /// A wrapper around a C `va_list` pointer. #if arch(arm64) && os(Linux) @_fixed_layout public struct CVaListPointer { @usableFromInline // unsafe-performance internal var value: (__stack: UnsafeMutablePointer<Int>?, __gr_top: UnsafeMutablePointer<Int>?, __vr_top: UnsafeMutablePointer<Int>?, __gr_off: Int32, __vr_off: Int32) @inlinable // unsafe-performance public // @testable init(__stack: UnsafeMutablePointer<Int>?, __gr_top: UnsafeMutablePointer<Int>?, __vr_top: UnsafeMutablePointer<Int>?, __gr_off: Int32, __vr_off: Int32) { value = (__stack, __gr_top, __vr_top, __gr_off, __vr_off) } } #else @_fixed_layout public struct CVaListPointer { @usableFromInline // unsafe-performance internal var _value: UnsafeMutableRawPointer @inlinable // unsafe-performance public // @testable init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) { _value = from } } extension CVaListPointer : CustomDebugStringConvertible { /// A textual representation of the pointer, suitable for debugging. public var debugDescription: String { return _value.debugDescription } } #endif @inlinable internal func _memcpy( dest destination: UnsafeMutableRawPointer, src: UnsafeRawPointer, size: UInt ) { let dest = destination._rawValue let src = src._rawValue let size = UInt64(size)._value Builtin.int_memcpy_RawPointer_RawPointer_Int64( dest, src, size, /*volatile:*/ false._value) } /// Copy `count` bytes of memory from `src` into `dest`. /// /// The memory regions `source..<source + count` and /// `dest..<dest + count` may overlap. @inlinable internal func _memmove( dest destination: UnsafeMutableRawPointer, src: UnsafeRawPointer, size: UInt ) { let dest = destination._rawValue let src = src._rawValue let size = UInt64(size)._value Builtin.int_memmove_RawPointer_RawPointer_Int64( dest, src, size, /*volatile:*/ false._value) }
apache-2.0
5db19cc2efb588fba54b4c8208a6f9e2
28.179054
80
0.674308
4.056834
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureForm/Sources/FeatureFormDomain/Models/FormQuestion.swift
1
2495
// Copyright © Blockchain Luxembourg S.A. All rights reserved. public struct Form: Codable, Equatable { public struct Header: Codable, Equatable { public let title: String public let description: String public init(title: String, description: String) { self.title = title self.description = description } } public let header: Header? public let context: String? public var nodes: [FormQuestion] public let blocking: Bool public var isEmpty: Bool { nodes.isEmpty } public var isNotEmpty: Bool { !isEmpty } public init(header: Form.Header? = nil, context: String? = nil, nodes: [FormQuestion], blocking: Bool = true) { self.header = header self.context = context self.nodes = nodes self.blocking = blocking } } public struct FormQuestion: Codable, Identifiable, Equatable { public enum QuestionType: String, Codable { case singleSelection = "SINGLE_SELECTION" case multipleSelection = "MULTIPLE_SELECTION" case openEnded = "OPEN_ENDED" var answer: FormAnswer.AnswerType { FormAnswer.AnswerType(rawValue) } } public let id: String public let type: QuestionType public let isDropdown: Bool? public let text: String public let instructions: String? @Default<Empty> public var children: [FormAnswer] public var input: String? public let hint: String? public let regex: String? public init( id: String, type: QuestionType, isDropdown: Bool?, text: String, instructions: String?, regex: String? = nil, input: String? = nil, hint: String? = nil, children: [FormAnswer] ) { self.id = id self.type = type self.isDropdown = isDropdown self.text = text self.instructions = instructions self.regex = regex self.input = input self.hint = hint self.children = children } public var own: FormAnswer { get { FormAnswer( id: id, type: type.answer, text: text, children: children, input: input, hint: hint, regex: regex, instructions: instructions, checked: nil ) } set { input = newValue.input } } }
lgpl-3.0
260b50cd407f0adf86f5fcd40c92f6b6
25.531915
115
0.570168
4.661682
false
false
false
false
mbrandonw/naturally-swift
naturally-swift/naturally-swift/Monad.swift
1
383
public protocol Monad : Functor { class func unit (x: _A) -> _FA class func bind (x: _FA, f: _A -> _FB) -> _FB func >>= (x: _FA, f: _A -> _FB) -> _FB } func flatM < M: Monad, MM: Monad where MM._A == M._FA, MM._A == MM._B, M._A == M._B> (xss: MM._FA) -> M._FA { func id (x: MM._A) -> MM._A { return x } let r = MM.bind(xss, id) return r }
mit
f43d2659bf82fc2984862aa17fee8849
16.409091
47
0.451697
2.408805
false
false
false
false
Reality-Virtually-Hackathon/Team-2
WorkspaceAR/Focus Square/FocusSquare.swift
1
16764
/* See LICENSE folder for this sample’s licensing information. Abstract: SceneKit node giving the user hints about the status of ARKit world tracking. */ import Foundation import ARKit /** An `SCNNode` which is used to provide uses with visual cues about the status of ARKit world tracking. - Tag: FocusSquare */ class FocusSquare: SCNNode { // MARK: - Types enum State { case initializing case featuresDetected(anchorPosition: float3, camera: ARCamera?) case planeDetected(anchorPosition: float3, planeAnchor: ARPlaneAnchor, camera: ARCamera?) } // MARK: - Configuration Properties // Original size of the focus square in meters. static let size: Float = 0.17 // Thickness of the focus square lines in meters. static let thickness: Float = 0.018 // Scale factor for the focus square when it is closed, w.r.t. the original size. static let scaleForClosedSquare: Float = 0.97 // Side length of the focus square segments when it is open (w.r.t. to a 1x1 square). static let sideLengthForOpenSegments: CGFloat = 0.2 // Duration of the open/close animation static let animationDuration = 0.7 static let primaryColor = #colorLiteral(red: 1, green: 0.8, blue: 0, alpha: 1) // Color of the focus square fill. static let fillColor = #colorLiteral(red: 1, green: 0.9254901961, blue: 0.4117647059, alpha: 1) // MARK: - Properties /// The most recent position of the focus square based on the current state. var lastPosition: float3? { switch state { case .initializing: return nil case .featuresDetected(let anchorPosition, _): return anchorPosition case .planeDetected(let anchorPosition, _, _): return anchorPosition } } var state: State = .initializing { didSet { guard state != oldValue else { return } switch state { case .initializing: displayAsBillboard() case .featuresDetected(let anchorPosition, let camera): displayAsOpen(at: anchorPosition, camera: camera) case .planeDetected(let anchorPosition, let planeAnchor, let camera): displayAsClosed(at: anchorPosition, planeAnchor: planeAnchor, camera: camera) } } } /// Indicates whether the segments of the focus square are disconnected. private var isOpen = false /// Indicates if the square is currently being animated. private var isAnimating = false /// The focus square's most recent positions. private var recentFocusSquarePositions: [float3] = [] /// Previously visited plane anchors. private var anchorsOfVisitedPlanes: Set<ARAnchor> = [] /// List of the segments in the focus square. private var segments: [FocusSquare.Segment] = [] /// The primary node that controls the position of other `FocusSquare` nodes. private let positioningNode = SCNNode() // MARK: - Initialization override init() { super.init() opacity = 0.0 /* The focus square consists of eight segments as follows, which can be individually animated. s1 s2 _ _ s3 | | s4 s5 | | s6 - - s7 s8 */ let s1 = Segment(name: "s1", corner: .topLeft, alignment: .horizontal) let s2 = Segment(name: "s2", corner: .topRight, alignment: .horizontal) let s3 = Segment(name: "s3", corner: .topLeft, alignment: .vertical) let s4 = Segment(name: "s4", corner: .topRight, alignment: .vertical) let s5 = Segment(name: "s5", corner: .bottomLeft, alignment: .vertical) let s6 = Segment(name: "s6", corner: .bottomRight, alignment: .vertical) let s7 = Segment(name: "s7", corner: .bottomLeft, alignment: .horizontal) let s8 = Segment(name: "s8", corner: .bottomRight, alignment: .horizontal) segments = [s1, s2, s3, s4, s5, s6, s7, s8] let sl: Float = 0.5 // segment length let c: Float = FocusSquare.thickness / 2 // correction to align lines perfectly s1.simdPosition += float3(-(sl / 2 - c), -(sl - c), 0) s2.simdPosition += float3(sl / 2 - c, -(sl - c), 0) s3.simdPosition += float3(-sl, -sl / 2, 0) s4.simdPosition += float3(sl, -sl / 2, 0) s5.simdPosition += float3(-sl, sl / 2, 0) s6.simdPosition += float3(sl, sl / 2, 0) s7.simdPosition += float3(-(sl / 2 - c), sl - c, 0) s8.simdPosition += float3(sl / 2 - c, sl - c, 0) positioningNode.eulerAngles.x = .pi / 2 // Horizontal positioningNode.simdScale = float3(FocusSquare.size * FocusSquare.scaleForClosedSquare) for segment in segments { positioningNode.addChildNode(segment) } positioningNode.addChildNode(fillPlane) // Always render focus square on top of other content. displayNodeHierarchyOnTop(true) addChildNode(positioningNode) // Start the focus square as a billboard. displayAsBillboard() } required init?(coder aDecoder: NSCoder) { fatalError("\(#function) has not been implemented") } // MARK: - Appearance /// Hides the focus square. func hide() { guard action(forKey: "hide") == nil else { return } displayNodeHierarchyOnTop(false) runAction(.fadeOut(duration: 0.5), forKey: "hide") } /// Unhides the focus square. func unhide() { guard action(forKey: "unhide") == nil else { return } displayNodeHierarchyOnTop(true) runAction(.fadeIn(duration: 0.5), forKey: "unhide") } /// Displays the focus square parallel to the camera plane. private func displayAsBillboard() { eulerAngles.x = -.pi / 2 simdPosition = float3(0, 0, -0.8) unhide() performOpenAnimation() } /// Called when a surface has been detected. private func displayAsOpen(at position: float3, camera: ARCamera?) { performOpenAnimation() recentFocusSquarePositions.append(position) updateTransform(for: position, camera: camera) } /// Called when a plane has been detected. private func displayAsClosed(at position: float3, planeAnchor: ARPlaneAnchor, camera: ARCamera?) { performCloseAnimation(flash: !anchorsOfVisitedPlanes.contains(planeAnchor)) anchorsOfVisitedPlanes.insert(planeAnchor) recentFocusSquarePositions.append(position) updateTransform(for: position, camera: camera) } // MARK: Helper Methods /// Update the transform of the focus square to be aligned with the camera. private func updateTransform(for position: float3, camera: ARCamera?) { simdTransform = matrix_identity_float4x4 // Average using several most recent positions. recentFocusSquarePositions = Array(recentFocusSquarePositions.suffix(10)) // Move to average of recent positions to avoid jitter. let average = recentFocusSquarePositions.reduce(float3(0), { $0 + $1 }) / Float(recentFocusSquarePositions.count) self.simdPosition = average self.simdScale = float3(scaleBasedOnDistance(camera: camera)) // Correct y rotation of camera square. guard let camera = camera else { return } let tilt = abs(camera.eulerAngles.x) let threshold1: Float = .pi / 2 * 0.65 let threshold2: Float = .pi / 2 * 0.75 let yaw = atan2f(camera.transform.columns.0.x, camera.transform.columns.1.x) var angle: Float = 0 switch tilt { case 0..<threshold1: angle = camera.eulerAngles.y case threshold1..<threshold2: let relativeInRange = abs((tilt - threshold1) / (threshold2 - threshold1)) let normalizedY = normalize(camera.eulerAngles.y, forMinimalRotationTo: yaw) angle = normalizedY * (1 - relativeInRange) + yaw * relativeInRange default: angle = yaw } eulerAngles.y = angle } private func normalize(_ angle: Float, forMinimalRotationTo ref: Float) -> Float { // Normalize angle in steps of 90 degrees such that the rotation to the other angle is minimal var normalized = angle while abs(normalized - ref) > .pi / 4 { if angle > ref { normalized -= .pi / 2 } else { normalized += .pi / 2 } } return normalized } /** Reduce visual size change with distance by scaling up when close and down when far away. These adjustments result in a scale of 1.0x for a distance of 0.7 m or less (estimated distance when looking at a table), and a scale of 1.2x for a distance 1.5 m distance (estimated distance when looking at the floor). */ private func scaleBasedOnDistance(camera: ARCamera?) -> Float { guard let camera = camera else { return 1.0 } let distanceFromCamera = simd_length(simdWorldPosition - camera.transform.translation) if distanceFromCamera < 0.7 { return distanceFromCamera / 0.7 } else { return 0.25 * distanceFromCamera + 0.825 } } // MARK: Animations private func performOpenAnimation() { guard !isOpen, !isAnimating else { return } isOpen = true isAnimating = true // Open animation SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) SCNTransaction.animationDuration = FocusSquare.animationDuration / 4 positioningNode.opacity = 1.0 for segment in segments { segment.open() } SCNTransaction.completionBlock = { self.positioningNode.runAction(pulseAction(), forKey: "pulse") // This is a safe operation because `SCNTransaction`'s completion block is called back on the main thread. self.isAnimating = false } SCNTransaction.commit() // Add a scale/bounce animation. SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) SCNTransaction.animationDuration = FocusSquare.animationDuration / 4 positioningNode.simdScale = float3(FocusSquare.size) SCNTransaction.commit() } private func performCloseAnimation(flash: Bool = false) { guard isOpen, !isAnimating else { return } isOpen = false isAnimating = true positioningNode.removeAction(forKey: "pulse") positioningNode.opacity = 1.0 // Close animation SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) SCNTransaction.animationDuration = FocusSquare.animationDuration / 2 positioningNode.opacity = 0.99 SCNTransaction.completionBlock = { SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) SCNTransaction.animationDuration = FocusSquare.animationDuration / 4 for segment in self.segments { segment.close() } SCNTransaction.completionBlock = { self.isAnimating = false } SCNTransaction.commit() } SCNTransaction.commit() // Scale/bounce animation positioningNode.addAnimation(scaleAnimation(for: "transform.scale.x"), forKey: "transform.scale.x") positioningNode.addAnimation(scaleAnimation(for: "transform.scale.y"), forKey: "transform.scale.y") positioningNode.addAnimation(scaleAnimation(for: "transform.scale.z"), forKey: "transform.scale.z") if flash { let waitAction = SCNAction.wait(duration: FocusSquare.animationDuration * 0.75) let fadeInAction = SCNAction.fadeOpacity(to: 0.25, duration: FocusSquare.animationDuration * 0.125) let fadeOutAction = SCNAction.fadeOpacity(to: 0.0, duration: FocusSquare.animationDuration * 0.125) fillPlane.runAction(SCNAction.sequence([waitAction, fadeInAction, fadeOutAction])) let flashSquareAction = flashAnimation(duration: FocusSquare.animationDuration * 0.25) for segment in segments { segment.runAction(.sequence([waitAction, flashSquareAction])) } } } // MARK: Convenience Methods private func scaleAnimation(for keyPath: String) -> CAKeyframeAnimation { let scaleAnimation = CAKeyframeAnimation(keyPath: keyPath) let easeOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) let easeInOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let linear = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) let size = FocusSquare.size let ts = FocusSquare.size * FocusSquare.scaleForClosedSquare let values = [size, size * 1.15, size * 1.15, ts * 0.97, ts] let keyTimes: [NSNumber] = [0.00, 0.25, 0.50, 0.75, 1.00] let timingFunctions = [easeOut, linear, easeOut, easeInOut] scaleAnimation.values = values scaleAnimation.keyTimes = keyTimes scaleAnimation.timingFunctions = timingFunctions scaleAnimation.duration = FocusSquare.animationDuration return scaleAnimation } /// Sets the rendering order of the `positioningNode` to show on top or under other scene content. func displayNodeHierarchyOnTop(_ isOnTop: Bool) { // Recursivley traverses the node's children to update the rendering order depending on the `isOnTop` parameter. func updateRenderOrder(for node: SCNNode) { node.renderingOrder = isOnTop ? 2 : 0 for material in node.geometry?.materials ?? [] { material.readsFromDepthBuffer = !isOnTop } for child in node.childNodes { updateRenderOrder(for: child) } } updateRenderOrder(for: positioningNode) } private lazy var fillPlane: SCNNode = { let correctionFactor = FocusSquare.thickness / 2 // correction to align lines perfectly let length = CGFloat(1.0 - FocusSquare.thickness * 2 + correctionFactor) let plane = SCNPlane(width: length, height: length) let node = SCNNode(geometry: plane) node.name = "fillPlane" node.opacity = 0.0 let material = plane.firstMaterial! material.diffuse.contents = FocusSquare.fillColor material.isDoubleSided = true material.ambient.contents = UIColor.black material.lightingModel = .constant material.emission.contents = FocusSquare.fillColor return node }() } // MARK: - Animations and Actions private func pulseAction() -> SCNAction { let pulseOutAction = SCNAction.fadeOpacity(to: 0.4, duration: 0.5) let pulseInAction = SCNAction.fadeOpacity(to: 1.0, duration: 0.5) pulseOutAction.timingMode = .easeInEaseOut pulseInAction.timingMode = .easeInEaseOut return SCNAction.repeatForever(SCNAction.sequence([pulseOutAction, pulseInAction])) } private func flashAnimation(duration: TimeInterval) -> SCNAction { let action = SCNAction.customAction(duration: duration) { (node, elapsedTime) -> Void in // animate color from HSB 48/100/100 to 48/30/100 and back let elapsedTimePercentage = elapsedTime / CGFloat(duration) let saturation = 2.8 * (elapsedTimePercentage - 0.5) * (elapsedTimePercentage - 0.5) + 0.3 if let material = node.geometry?.firstMaterial { material.diffuse.contents = UIColor(hue: 0.1333, saturation: saturation, brightness: 1.0, alpha: 1.0) } } return action } extension FocusSquare.State: Equatable { static func ==(lhs: FocusSquare.State, rhs: FocusSquare.State) -> Bool { switch (lhs, rhs) { case (.initializing, .initializing): return true case (.featuresDetected(let lhsPosition, let lhsCamera), .featuresDetected(let rhsPosition, let rhsCamera)): return lhsPosition == rhsPosition && lhsCamera == rhsCamera case (.planeDetected(let lhsPosition, let lhsPlaneAnchor, let lhsCamera), .planeDetected(let rhsPosition, let rhsPlaneAnchor, let rhsCamera)): return lhsPosition == rhsPosition && lhsPlaneAnchor == rhsPlaneAnchor && lhsCamera == rhsCamera default: return false } } }
mit
7ba4d97ba1cf741c9079d73f403e6d5a
37.269406
121
0.646224
4.675593
false
false
false
false
apple/swift-nio-http2
Sources/NIOHPACK/DynamicHeaderTable.swift
1
5173
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore /// Implements the dynamic part of the HPACK header table, as defined in /// [RFC 7541 § 2.3](https://httpwg.org/specs/rfc7541.html#dynamic.table). @usableFromInline struct DynamicHeaderTable: Sendable { public static let defaultSize = 4096 /// The actual table, with items looked up by index. private var storage: HeaderTableStorage /// The length of the contents of the table. var length: Int { return self.storage.length } /// The size to which the dynamic table may currently grow. Represents /// the current maximum length signaled by the peer via a table-resize /// value at the start of an encoded header block. /// /// - note: This value cannot exceed `self.maximumTableLength`. var allowedLength: Int { get { return self.storage.maxSize } set { self.storage.setTableSize(to: newValue) } } /// The maximum permitted size of the dynamic header table as set /// through a SETTINGS_HEADER_TABLE_SIZE value in a SETTINGS frame. var maximumTableLength: Int { didSet { if self.allowedLength > maximumTableLength { self.allowedLength = maximumTableLength } } } /// The number of items in the table. var count: Int { return self.storage.count } init(maximumLength: Int = DynamicHeaderTable.defaultSize) { self.storage = HeaderTableStorage(maxSize: maximumLength) self.maximumTableLength = maximumLength self.allowedLength = maximumLength // until we're told otherwise, this is what we assume the other side expects. } /// Subscripts into the dynamic table alone, using a zero-based index. subscript(i: Int) -> HeaderTableEntry { return self.storage[i] } // internal for testing func dumpHeaders() -> String { return self.storage.dumpHeaders(offsetBy: StaticHeaderTable.count) } // internal for testing -- clears the dynamic table mutating func clear() { self.storage.purge(toRelease: self.storage.length) } /// Searches the table for a matching header, optionally with a particular value. If /// a match is found, returns the index of the item and an indication whether it contained /// the matching value as well. /// /// Invariants: If `value` is `nil`, result `containsValue` is `false`. /// /// - Parameters: /// - name: The name of the header for which to search. /// - value: Optional value for the header to find. Default is `nil`. /// - Returns: A tuple containing the matching index and, if a value was specified as a /// parameter, an indication whether that value was also found. Returns `nil` /// if no matching header name could be located. func findExistingHeader(named name: String, value: String?) -> (index: Int, containsValue: Bool)? { // looking for both name and value, but can settle for just name if no value // has been provided. Return the first matching name (lowest index) in that case. guard let value = value else { // no `first` on AnySequence, just `first(where:)` return self.storage.firstIndex(matching: name).map { ($0, false) } } // If we have a value, locate the index of the lowest header which contains that // value, but if no value matches, return the index of the lowest header with a // matching name alone. switch self.storage.closestMatch(name: name, value: value) { case .full(let index): return (index, true) case .partial(let index): return (index, false) case .none: return nil } } /// Appends a header to the table. Note that if this succeeds, the new item's index /// is always zero. /// /// This call may result in an empty table, as per RFC 7541 § 4.4: /// > "It is not an error to attempt to add an entry that is larger than the maximum size; /// > an attempt to add an entry larger than the maximum size causes the table to be /// > emptied of all existing entries and results in an empty table." /// /// - Parameters: /// - name: A String representing the name of the header field. /// - value: A String representing the value of the header field. /// - Returns: `true` if the header was added to the table, `false` if not. mutating func addHeader(named name: String, value: String) { self.storage.add(name: name, value: value) } }
apache-2.0
875de32b75856b7ac0300198277d9fee
39.085271
121
0.619416
4.559965
false
false
false
false
nik3212/AnimateRecordButton
AnimateRecordButtonView/AnimateButtonRecordView.swift
1
1539
// // AnimateButtonRecordView.swift // AnimateRecordButton // // Created by Никита Васильев on 04.09.17. // Copyright © 2017 ReGen Software. All rights reserved. // import UIKit class ANView: UIView { override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override func draw(_ rect: CGRect) { let context: CGContext = UIGraphicsGetCurrentContext()! context.saveGState() let circlePath: UIBezierPath = UIBezierPath(ovalIn: getBounds()) UIColor.white.setStroke() circlePath.lineWidth = CGFloat(PropertyAnimateButtonView.LineHeight) circlePath.stroke() UIColor.black.setFill() circlePath.fill() context.restoreGState() } private func setup() { self.layer.masksToBounds = true self.layer.cornerRadius = self.frame.height / 2 } private func getBounds() -> CGRect { return CGRect(x: CGFloat(PropertyAnimateButtonView.LineHeight) / 2, y: CGFloat(PropertyAnimateButtonView.LineHeight) / 2, width: self.bounds.size.width - CGFloat(PropertyAnimateButtonView.LineHeight), height: self.bounds.size.height - CGFloat(PropertyAnimateButtonView.LineHeight)) } }
gpl-3.0
f7803ad84d28de4f27c35286c25697cb
24.4
102
0.581365
4.980392
false
false
false
false
apple/swift
test/Frontend/module-alias-invalid-input.swift
1
2384
// Tests for invalid module alias format and values. // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias foo=bar 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS %s // INVALID_MODULE_ALIAS: error: invalid module alias "foo"; make sure the alias differs from the module name, module ABI name, module link name, and a standard library name // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias Swift=Bar 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS1 %s // INVALID_MODULE_ALIAS1: error: invalid module alias "Swift"; make sure the alias differs from the module name, module ABI name, module link name, and a standard library name // RUN: %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias Bar=Swift -verify // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias bar=bar 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS2 %s // INVALID_MODULE_ALIAS2: error: duplicate module alias; the name "bar" is already used for a module alias or an underlying name // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias bar=baz -module-alias baz=cat 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS3 %s // INVALID_MODULE_ALIAS3: error: duplicate module alias; the name "baz" is already used for a module alias or an underlying name // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias bar 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS4 %s // INVALID_MODULE_ALIAS4: error: invalid module alias format "bar"; make sure to use the format '-module-alias alias_name=underlying_name' // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias bar=c-a.t 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_NAME %s // INVALID_MODULE_NAME: error: module name "c-a.t" is not a valid identifier // These should succeed. // RUN: %target-swift-frontend -emit-silgen %s > /dev/null // RUN: %target-swift-frontend -emit-silgen -parse-as-library -module-name foo %s -module-alias bar=cat > /dev/null // RUN: %target-swift-frontend -typecheck -parse-as-library -module-name foo %s -module-alias bar=cat public class Logger { public init() {} public func startLogging() {} }
apache-2.0
9608fa5423c49e61ad91618aede84994
78.466667
186
0.743289
3.386364
false
false
false
false
dnevera/IMProcessing
IMProcessing/Classes/FrontEnd/IMPImageView.swift
1
18901
// // IMPScrollView.swift // IMProcessing // // Created by denis svinarchuk on 25.12.15. // Copyright © 2015 Dehancer.photo. All rights reserved. // #if os(iOS) import UIKit import QuartzCore #else import AppKit #endif extension IMPImageView { func updateFrameSize(texture:MTLTexture) { let w = (texture.width.float/self.imageView.scaleFactor).cgfloat let h = (texture.height.float/self.imageView.scaleFactor).cgfloat if w != self.imageView.frame.size.width || h != self.imageView.frame.size.height { dispatch_async(dispatch_get_main_queue(), { CATransaction.begin() CATransaction.setDisableActions(true) self.imageView.frame = CGRect(x: 0, y: 0, width: w, height: h) CATransaction.commit() }) } } } #if os(iOS) public class IMPScrollView: UIScrollView { override init(frame: CGRect) { super.init(frame: frame) let doubleTap = UITapGestureRecognizer(target: self, action: #selector(IMPScrollView.zoom(_:))) doubleTap.numberOfTapsRequired = 2 self.addGestureRecognizer(doubleTap) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func zoomRectForScale(scale:CGFloat, center:CGPoint) -> CGRect { var zoomRect = frame zoomRect.size.height = frame.size.height / scale zoomRect.size.width = frame.size.width / scale // choose an origin so as to get the right center. zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0) zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0) return zoomRect; } var originalPoint:CGPoint? func zoom(gestureRecognizer:UIGestureRecognizer) { let duration = UIApplication.sharedApplication().statusBarOrientationAnimationDuration if zoomScale <= minimumZoomScale { if subviews.count > 0 { let view = subviews[0] originalPoint = view.layer.frame.origin let zoomRect = zoomRectForScale(maximumZoomScale, center:gestureRecognizer.locationInView(view)) UIView.animateWithDuration(duration, animations: { () -> Void in view.layer.frame.origin = CGPointZero self.zoomToRect(zoomRect, animated:false) }) } } else{ UIView.animateWithDuration(duration, animations: { () -> Void in if self.subviews.count > 0 && self.originalPoint != nil { let view = self.subviews[0] view.layer.frame.origin = self.originalPoint! } self.setZoomScale(self.minimumZoomScale, animated: false) }) } } } public class IMPImageView: IMPViewBase, IMPContextProvider, UIScrollViewDelegate { public var metalTransform: CATransform3D { return self.imageView.metalLayer.transform } public var metalLayer: CAMetalLayer { return self.imageView.metalLayer } public var context:IMPContext! public var filter:IMPFilter?{ didSet{ imageView?.filter = filter } } public var orientation:UIDeviceOrientation{ get{ return imageView.orientation } set{ imageView.orientation = orientation } } public func setOrientation(orientation:UIDeviceOrientation, animate:Bool) { imageView.setOrientation(orientation, animate: animate) } // internal func updateLayer(){ // imageView.updateLayer() // } private func configure(){ scrollView = IMPScrollView(frame: bounds) scrollView?.backgroundColor = IMPColor.clearColor() scrollView?.showsVerticalScrollIndicator = false scrollView?.showsHorizontalScrollIndicator = false scrollView?.scrollEnabled=true scrollView?.userInteractionEnabled=true scrollView?.maximumZoomScale = 4.0 scrollView?.minimumZoomScale = 1 scrollView?.zoomScale = 1 scrollView?.delegate = self self.addSubview(scrollView) imageView = IMPView(context: self.context, frame: self.bounds) //imageView.updateLayerHandler = updateLayer imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] imageView.backgroundColor = IMPColor.clearColor() scrollView.addSubview(imageView) } public init(context contextIn:IMPContext, frame: NSRect){ super.init(frame: frame) context = contextIn defer{ self.configure() } } public convenience override init(frame frameRect: NSRect) { self.init(context: IMPContext(), frame:frameRect) } required public init?(coder: NSCoder) { super.init(coder: coder) self.context = IMPContext() defer{ self.configure() } } public func sizeFit(){ } /// Present image in oroginal size public func sizeOriginal(){ } public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } private var minimumScale:Float{ get { let scrollViewSize = self.bounds.size let zoomViewSize = scrollView.contentSize var scaleToFit = fminf(scrollViewSize.width.float / zoomViewSize.width.float, scrollViewSize.height.float / zoomViewSize.height.float); if scaleToFit > 1.0 { scaleToFit = 1.0 } return scaleToFit } } private var imageView:IMPView! public var scrollView:IMPScrollView! } #else /// Image preview window public class IMPImageView: IMPViewBase, IMPContextProvider{ public var dragOperation:IMPDragOperationHandler? { didSet{ imageView.dragOperation = dragOperation } } /// GPU device context public var context:IMPContext! /// View backgound public var backgroundColor:IMPColor{ set{ imageView.backgroundColor = newValue scrollView.backgroundColor = newValue } get{ return imageView.backgroundColor } } /// View filter public var filter:IMPFilter?{ didSet{ imageView?.filter = filter filter?.addDestinationObserver(destination: { (destination) in if let texture = destination.texture{ self.updateFrameSize(texture) } }) } } public var isPaused:Bool { set{ imageView.isPaused = newValue } get { return imageView.isPaused } } /// Magnify image to fit rectangle /// /// - parameter rect: rectangle which is used to magnify the image to fit size an position public func magnifyToFitRect(rect:CGRect){ isSizeFit = false scrollView.magnifyToFitRect(rect) imageView.layerNeedUpdate = true } private var isSizeFit = true /// Fite image to current view size public func sizeFit(){ isSizeFit = true imageView.updateLayer() scrollView.magnifyToFitRect(imageView.bounds) imageView.layerNeedUpdate = true } /// Present image in oroginal size public func sizeOriginal(){ isSizeFit = false imageView.updateLayer() scrollView.magnifyToFitRect(bounds) imageView.layerNeedUpdate = true } @objc func magnifyChanged(event:NSNotification){ isSizeFit = false imageView.layerNeedUpdate = true } /// Create image view object with th context within properly frame /// /// - parameter contextIn: GPU device context /// - parameter frame: view frame rectangle /// public init(context contextIn:IMPContext, frame: NSRect = CGRect(x: 0, y: 0, width: 100, height: 100)){ super.init(frame: frame) context = contextIn defer{ self.configure() } } /// Create image with default context. /// /// - parameter frameRect: view frame rectangle /// public convenience override init(frame frameRect: NSRect) { self.init(context: IMPContext(), frame:frameRect) } /// Create image with a filter /// /// - parameter filter: image filter /// - parameter frame: view frame rectangle /// public convenience init(filter:IMPFilter, frame:NSRect = CGRect(x: 0, y: 0, width: 100, height: 100)){ self.init(context:filter.context,frame:frame) defer{ self.filter = filter } } required public init?(coder: NSCoder) { super.init(coder: coder) self.context = IMPContext() defer{ self.configure() } } override public func setFrameSize(newSize: NSSize) { super.setFrameSize(newSize) if isSizeFit { sizeFit() } } public func addMouseEventObserver(observer:IMPView.MouseEventHandler){ imageView.addMouseEventObserver(observer) } public var imageArea:NSRect { var frame = imageView.frame frame.origin.x += scrollView.contentInsets.left frame.origin.y += scrollView.contentInsets.top frame.size.width -= scrollView.contentInsets.right frame.size.height -= scrollView.contentInsets.bottom return frame } private var imageView:IMPView! private var scrollView:IMPScrollView! private func configure(){ NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(IMPImageView.magnifyChanged(_:)), name: NSScrollViewWillStartLiveMagnifyNotification, object: nil) scrollView = IMPScrollView(frame: bounds) scrollView.drawsBackground = false scrollView.wantsLayer = true scrollView.allowsMagnification = true scrollView.acceptsTouchEvents = true scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = true scrollView.autoresizingMask = [.ViewHeightSizable, .ViewWidthSizable] imageView = IMPView(context: self.context, frame: self.bounds) imageView.backgroundColor = IMPColor.clearColor() imageView.animationDuration = 0 scrollView.documentView = imageView addSubview(scrollView) } } class IMPScrollView:NSScrollView { private var cv:IMPClipView! private func configure(){ cv = IMPClipView(frame: self.bounds) contentView = cv verticalScroller = IMPScroller() verticalScroller?.controlSize = NSControlSize(rawValue: 5)! horizontalScroller = IMPScroller() horizontalScroller?.controlSize = NSControlSize(rawValue: 5)! } required init?(coder: NSCoder) { super.init(coder: coder) self.configure() } override init(frame frameRect: NSRect) { super.init(frame: frameRect) self.configure() } override func magnifyToFitRect(rect: NSRect) { super.magnifyToFitRect(rect) self.cv.moveToCenter(true) } override func drawRect(dirtyRect: NSRect) { backgroundColor.set() NSRectFill(dirtyRect) } } class IMPScroller: NSScroller { var backgroundColor = IMPColor.clearColor() // func drawBackground(rect:NSRect){ // let path = NSBezierPath(roundedRect: rect, xRadius: 0, yRadius: 0) // IMPColor.clearColor().set() // path.fill() // } // // static var width = 5 // // override func drawKnob() { // for i in 0...6{ // drawBackground(rectForPart(NSScrollerPart(rawValue: UInt(i))!)) // } // // let knobRect = rectForPart(.Knob) // let newRect = NSMakeRect((knobRect.size.width - IMPScroller.width.cgloat) / 2, knobRect.origin.y, IMPScroller.width.cgloat, knobRect.size.height) // let path = NSBezierPath(roundedRect: newRect, xRadius:5, yRadius:5) // IMPColor.lightGrayColor().set() // path.fill() // } override func drawRect(dirtyRect: NSRect) { backgroundColor.set() NSRectFill(dirtyRect) drawKnob() } override func drawKnobSlotInRect(slotRect: NSRect, highlight flag: Bool) { super.drawKnobSlotInRect(slotRect, highlight: true) } override func mouseExited(theEvent:NSEvent){ super.mouseExited(theEvent) self.fadeOut() } override func mouseEntered(theEvent:NSEvent) { super.mouseEntered(theEvent) NSAnimationContext.runAnimationGroup({ (context) -> Void in context.duration = 0.1 self.animator().alphaValue = 1.0 }, completionHandler: nil) NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: #selector(IMPScroller.fadeOut), object: nil) } override func mouseMoved(theEvent:NSEvent){ super.mouseMoved(theEvent) self.alphaValue = 1.0 } func fadeOut() { NSAnimationContext.runAnimationGroup({ (context) -> Void in context.duration = 0.3 self.animator().alphaValue = 1.0 }, completionHandler: nil) } } class IMPClipView:NSClipView { private var viewPoint = NSPoint() override func constrainBoundsRect(proposedBounds: NSRect) -> NSRect { if let documentView = self.documentView{ let documentFrame:NSRect = documentView.frame var clipFrame = self.bounds let x = documentFrame.size.width - clipFrame.size.width let y = documentFrame.size.height - clipFrame.size.height clipFrame.origin = proposedBounds.origin if clipFrame.size.width>documentFrame.size.width{ clipFrame.origin.x = CGFloat(roundf(Float(x) / 2.0)) } else{ let m = Float(max(0, min(clipFrame.origin.x, x))) clipFrame.origin.x = CGFloat(roundf(m)) } if clipFrame.size.height>documentFrame.size.height{ clipFrame.origin.y = CGFloat(roundf(Float(y) / 2.0)) } else{ let m = Float(max(0, min(clipFrame.origin.y, y))) clipFrame.origin.y = CGFloat(roundf(m)) } viewPoint.x = NSMidX(clipFrame) / documentFrame.size.width; viewPoint.y = NSMidY(clipFrame) / documentFrame.size.height; return clipFrame } else{ return super.constrainBoundsRect(proposedBounds) } } func moveToCenter(always:Bool = false){ if let documentView = self.documentView{ let documentFrame:NSRect = documentView.frame var clipFrame = self.bounds if documentFrame.size.width < clipFrame.size.width || always { clipFrame.origin.x = CGFloat(roundf(Float(documentFrame.size.width - clipFrame.size.width) / 2.0)); } else { clipFrame.origin.x = CGFloat(roundf(Float(viewPoint.x * documentFrame.size.width - (clipFrame.size.width) / 2.0))); } if documentFrame.size.height < clipFrame.size.height || always { clipFrame.origin.y = CGFloat(roundf(Float(documentFrame.size.height - clipFrame.size.height) / 2.0)); } else { clipFrame.origin.y = CGFloat(roundf(Float(viewPoint.x * documentFrame.size.height - (clipFrame.size.height) / 2.0))); } let scrollView = self.superview self.scrollToPoint(self.constrainBoundsRect(clipFrame).origin) scrollView?.reflectScrolledClipView(self) } } override func viewFrameChanged(notification: NSNotification) { super.viewBoundsChanged(notification) self.moveToCenter() } override var documentView:AnyObject?{ didSet{ self.moveToCenter() } } } #endif
mit
435e97e514a2842da8ac6f7973b1b231
33.489051
168
0.52582
5.498982
false
false
false
false
olivier38070/OAuthSwift
OAuthSwiftTests/TestOAuthSwiftURLHandler.swift
3
2900
// // TestOAuthSwiftURLHandler.swift // OAuthSwift // // Created by phimage on 17/11/15. // Copyright © 2015 Dongri Jin. All rights reserved. // import Foundation import OAuthSwift enum AccessTokenResponse { case AccessToken(String), Code(String), Error(String,String), None var responseType: String { switch self { case .AccessToken: return "token" case .Code: return "code" case .Error: return "code" case .None: return "code" } } } class TestOAuthSwiftURLHandler: NSObject, OAuthSwiftURLHandlerType { let callbackURL: String let authorizeURL: String let version: OAuthSwiftCredential.Version var accessTokenResponse: AccessTokenResponse? var authorizeURLComponents: NSURLComponents? { return NSURLComponents(URL: NSURL(string: self.authorizeURL)!, resolvingAgainstBaseURL: false) } init(callbackURL: String, authorizeURL: String, version: OAuthSwiftCredential.Version) { self.callbackURL = callbackURL self.authorizeURL = authorizeURL self.version = version } @objc func handle(url: NSURL) { switch version { case .OAuth1: handleV1(url) case .OAuth2: handleV2(url) } } func handleV1(url: NSURL) { let urlComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) if let queryItems = urlComponents?.queryItems { for queryItem in queryItems { if let value = queryItem.value where queryItem.name == "oauth_token" { let url = "\(self.callbackURL)?oauth_token=\(value)" OAuth1Swift.handleOpenURL(NSURL(string: url)!) } } } urlComponents?.query = nil if urlComponents != authorizeURLComponents { print("bad authorizeURL \(url), must be \(authorizeURL)") return } // else do nothing } func handleV2(url: NSURL) { var url = "\(self.callbackURL)/" if let response = accessTokenResponse { switch response { case .AccessToken(let token): url += "?access_token=\(token)" case .Code(let code): url += "?code='\(code)'" case .Error(let error,let errorDescription): let e = error.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! let ed = errorDescription.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! url += "?error='\(e)'&errorDescription='\(ed)'" case .None: break // nothing } } OAuth2Swift.handleOpenURL(NSURL(string: url)!) } }
mit
70a5fb2a08a5b572dd216455599ac5d2
29.208333
124
0.583305
5.28051
false
false
false
false
cohena100/Shimi
Carthage/Checkouts/SwiftyBeaver/Tests/SwiftyBeaverTests/BaseDestinationTests.swift
1
32353
// // BaseDestinationTests.swift // SwiftyBeaver // // Created by Sebastian Kreutzberger on 05.12.15. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation import XCTest @testable import SwiftyBeaver class BaseDestinationTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testInit() { let obj = BaseDestination() XCTAssertNotNil(obj.queue) } //////////////////////////////// // MARK: Format //////////////////////////////// func testFormatMessage() { let obj = BaseDestination() var str = "" var format = "" // empty format str = obj.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50) XCTAssertEqual(str, "") // format without variables format = "Hello" str = obj.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50) XCTAssertEqual(str, "Hello") // weird format format = "$" str = obj.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50) XCTAssertEqual(str, "") // basic format with ignored color and thread format = "|$T| $C$L$c: $M" str = obj.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50) XCTAssertEqual(str, "|main| VERBOSE: Hello") // format with date and color let obj2 = BaseDestination() let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let dateStr = formatter.string(from: Date()) obj2.levelColor.verbose = "?" obj2.escape = ">" obj2.reset = "<" format = "[$Dyyyy-MM-dd HH:mm:ss$d] |$T| $N.$F:$l $C$L$c: $M" str = obj2.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50) XCTAssertEqual(str, "[\(dateStr)] |main| ViewController.testFunction():50 >?VERBOSE<: Hello") // UTC datetime let obj3 = BaseDestination() let utcFormatter = DateFormatter() utcFormatter.timeZone = TimeZone(abbreviation: "UTC") utcFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let utcDateStr = utcFormatter.string(from: Date()) str = BaseDestination().formatDate(utcFormatter.dateFormat, timeZone: "UTC") format = "$Zyyyy-MM-dd HH:mm:ss$z" str = obj3.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50) XCTAssertEqual(str, "\(utcDateStr)") // context in different formats let obj4 = BaseDestination() format = "$L: $M $X" str = obj4.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50, context: "Context!") XCTAssertEqual(str, "VERBOSE: Hello Context!") str = obj4.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50, context: 123) XCTAssertEqual(str, "VERBOSE: Hello 123") str = obj4.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50, context: [1, "a", 2]) XCTAssertEqual(str, "VERBOSE: Hello [1, \"a\", 2]") str = obj4.formatMessage(format, level: .verbose, msg: "Hello", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50, context: nil) XCTAssertEqual(str, "VERBOSE: Hello ") } func testMessageToJSON() { let obj = BaseDestination() guard let str = obj.messageToJSON(.info, msg: "hello world", thread: "main", file: "/path/to/ViewController.swift", function: "testFunction()", line: 50, context: ["foo": "bar", "hello": 2]) else { XCTFail("str should not be nil"); return } print(str) // decode JSON string into dict and compare if it is the the same guard let data = str.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data, options: []), let dict = json as? [String:Any], let timestamp = dict["timestamp"] as? Double, let level = dict["level"] as? Int, let message = dict["message"] as? String, let thread = dict["thread"] as? String, let file = dict["file"] as? String, let function = dict["function"] as? String, let line = dict["line"] as? Int, let context = dict["context"] as? [String: Any] else { XCTFail("dict and its properties should not be nil"); return } XCTAssertGreaterThanOrEqual(timestamp, Date().timeIntervalSince1970 - 10) XCTAssertEqual(level, SwiftyBeaver.Level.info.rawValue) XCTAssertEqual(message, "hello world") XCTAssertEqual(thread, "main") XCTAssertEqual(file, "/path/to/ViewController.swift") XCTAssertEqual(function, "testFunction()") XCTAssertEqual(line, 50) XCTAssertEqual(context["foo"] as? String, "bar") XCTAssertEqual(context["hello"] as? Int, 2) } func testLevelWord() { let obj = BaseDestination() var str = "" str = obj.levelWord(SwiftyBeaver.Level.verbose) XCTAssertNotNil(str, "VERBOSE") str = obj.levelWord(SwiftyBeaver.Level.debug) XCTAssertNotNil(str, "DEBUG") str = obj.levelWord(SwiftyBeaver.Level.info) XCTAssertNotNil(str, "INFO") str = obj.levelWord(SwiftyBeaver.Level.warning) XCTAssertNotNil(str, "WARNING") str = obj.levelWord(SwiftyBeaver.Level.error) XCTAssertNotNil(str, "ERROR") // custom level strings obj.levelString.verbose = "Who cares" obj.levelString.debug = "Look" obj.levelString.info = "Interesting" obj.levelString.warning = "Oh oh" obj.levelString.error = "OMG!!!" str = obj.levelWord(SwiftyBeaver.Level.verbose) XCTAssertNotNil(str, "Who cares") str = obj.levelWord(SwiftyBeaver.Level.debug) XCTAssertNotNil(str, "Look") str = obj.levelWord(SwiftyBeaver.Level.info) XCTAssertNotNil(str, "Interesting") str = obj.levelWord(SwiftyBeaver.Level.warning) XCTAssertNotNil(str, "Oh oh") str = obj.levelWord(SwiftyBeaver.Level.error) XCTAssertNotNil(str, "OMG!!!") } func testColorForLevel() { let obj = BaseDestination() var str = "" // empty on default str = obj.colorForLevel(SwiftyBeaver.Level.verbose) XCTAssertNotNil(str, "") str = obj.colorForLevel(SwiftyBeaver.Level.debug) XCTAssertNotNil(str, "") str = obj.colorForLevel(SwiftyBeaver.Level.info) XCTAssertNotNil(str, "") str = obj.colorForLevel(SwiftyBeaver.Level.warning) XCTAssertNotNil(str, "") str = obj.colorForLevel(SwiftyBeaver.Level.error) XCTAssertNotNil(str, "") // custom level color strings obj.levelString.verbose = "silver" obj.levelString.debug = "green" obj.levelString.info = "blue" obj.levelString.warning = "yellow" obj.levelString.error = "red" str = obj.colorForLevel(SwiftyBeaver.Level.verbose) XCTAssertNotNil(str, "silver") str = obj.colorForLevel(SwiftyBeaver.Level.debug) XCTAssertNotNil(str, "green") str = obj.colorForLevel(SwiftyBeaver.Level.info) XCTAssertNotNil(str, "blue") str = obj.colorForLevel(SwiftyBeaver.Level.warning) XCTAssertNotNil(str, "yellow") str = obj.colorForLevel(SwiftyBeaver.Level.error) XCTAssertNotNil(str, "red") } func testFileNameOfFile() { let obj = BaseDestination() var str = "" str = obj.fileNameOfFile("") XCTAssertEqual(str, "") str = obj.fileNameOfFile("foo.bar") XCTAssertEqual(str, "foo.bar") str = obj.fileNameOfFile("path/to/ViewController.swift") XCTAssertEqual(str, "ViewController.swift") } func testFileNameOfFileWithoutSuffix() { let obj = BaseDestination() var str = "" str = obj.fileNameWithoutSuffix("") XCTAssertEqual(str, "") str = obj.fileNameWithoutSuffix("/") XCTAssertEqual(str, "") str = obj.fileNameWithoutSuffix("foo") XCTAssertEqual(str, "foo") str = obj.fileNameWithoutSuffix("foo.bar") XCTAssertEqual(str, "foo") str = obj.fileNameWithoutSuffix("path/to/ViewController.swift") XCTAssertEqual(str, "ViewController") } func testFormatDate() { // empty format var str = BaseDestination().formatDate("") XCTAssertEqual(str, "") // no time format str = BaseDestination().formatDate("--") XCTAssertGreaterThanOrEqual(str, "--") // HH:mm:ss let formatter = DateFormatter() formatter.dateFormat = "HH:mm:ss" let dateStr = formatter.string(from: Date()) str = BaseDestination().formatDate(formatter.dateFormat) XCTAssertEqual(str, dateStr) // test UTC let utcFormatter = DateFormatter() utcFormatter.timeZone = TimeZone(abbreviation: "UTC") utcFormatter.dateFormat = "HH:mm:ss" let utcDateStr = utcFormatter.string(from: Date()) str = BaseDestination().formatDate(utcFormatter.dateFormat, timeZone: "UTC") XCTAssertEqual(str, utcDateStr) } //////////////////////////////// // MARK: Filters //////////////////////////////// func test_init_noMinLevelSet() { let destination = BaseDestination() XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.verbose, path: "", function: "")) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.debug, path: "", function: "")) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.info, path: "", function: "")) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.warning, path: "", function: "")) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.error, path: "", function: "")) } func test_init_minLevelSet() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info XCTAssertFalse(destination.shouldLevelBeLogged(SwiftyBeaver.Level.verbose, path: "", function: "")) XCTAssertFalse(destination.shouldLevelBeLogged(SwiftyBeaver.Level.debug, path: "", function: "")) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.info, path: "", function: "")) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.warning, path: "", function: "")) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.error, path: "", function: "")) } func test_shouldLevelBeLogged_hasMinLevel_True() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.verbose destination.addFilter(Filters.Path.equals("/world/beaver.swift", caseSensitive: true, required: true)) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.warning, path: "/world/beaver.swift", function: "initialize")) } func test_shouldLevelBeLogged_hasMinLevel_False() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.equals("/world/beaver.swift", caseSensitive: true, required: true)) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.warning, path: "/world/beaver.swift", function: "initialize")) } func test_shouldLevelBeLogged_hasMinLevelAndMatchingLevelAndEqualPath_True() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.verbose let filter = Filters.Path.equals("/world/beaver.swift", caseSensitive: true, required: true, minLevel: .debug) destination.addFilter(filter) XCTAssertTrue(destination.shouldLevelBeLogged(.debug, path: "/world/beaver.swift", function: "initialize")) } func test_shouldLevelBeLogged_hasMinLevelAndNoMatchingLevelButEqualPath_False() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info let filter = Filters.Path.equals("/world/beaver.swift", caseSensitive: true, required: true, minLevel: .debug) destination.addFilter(filter) XCTAssertTrue(destination.shouldLevelBeLogged(.debug, path: "/world/beaver.swift", function: "initialize")) } func test_shouldLevelBeLogged_hasMinLevelAndOneEqualsPathFilterAndDoesNotPass_False() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.equals("/world/beaver.swift", caseSensitive: true, required: true)) XCTAssertFalse(destination.shouldLevelBeLogged(.debug, path: "/hello/foo.swift", function: "initialize")) } func test_shouldLevelBeLogged_hasLevelFilterAndTwoRequiredPathFiltersAndPasses_True() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.startsWith("/world", caseSensitive: true, required: true)) destination.addFilter(Filters.Path.endsWith("beaver.swift", caseSensitive: true, required: true)) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.warning, path: "/world/beaver.swift", function: "initialize")) } func test_shouldLevelBeLogged_hasLevelFilterAndTwoRequiredPathFiltersAndDoesNotPass_False() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.startsWith("/world", caseSensitive: true, required: true)) destination.addFilter(Filters.Path.endsWith("foo.swift", caseSensitive: true, required: true)) XCTAssertFalse(destination.shouldLevelBeLogged(.debug, path: "/hello/foo.swift", function: "initialize")) } func test_shouldLevelBeLogged_hasLevelFilterARequiredPathFilterAndTwoRequiredMessageFiltersAndPasses_True() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.startsWith("/world", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.startsWith("SQL:", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.contains("insert", caseSensitive: false, required: true)) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.warning, path: "/world/beaver.swift", function: "executeSQLStatement", message: "SQL: INSERT INTO table (c1, c2) VALUES (1, 2)")) } func test_shouldLevelBeLogged_hasLevelFilterARequiredPathFilterAndTwoRequiredMessageFiltersAndDoesNotPass_False() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.startsWith("/world", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.startsWith("SQL:", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.contains("insert", caseSensitive: false, required: true)) XCTAssertFalse(destination.shouldLevelBeLogged(.debug, path: "/world/beaver.swift", function: "executeSQLStatement", message: "SQL: DELETE FROM table WHERE c1 = 1")) } func test_shouldLevelBeLogged_hasLevelFilterCombinationOfAllOtherFiltersAndPasses_True() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.startsWith("/world", caseSensitive: true, required: true)) destination.addFilter(Filters.Path.endsWith("/beaver.swift", caseSensitive: true, required: true)) destination.addFilter(Filters.Function.equals("executeSQLStatement", required: true)) destination.addFilter(Filters.Message.startsWith("SQL:", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.contains("insert", "update", "delete", required: true)) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.warning, path: "/world/beaver.swift", function: "executeSQLStatement", message: "SQL: INSERT INTO table (c1, c2) VALUES (1, 2)")) } func test_shouldLevelBeLogged_hasLevelFilterCombinationOfAllOtherFiltersAndDoesNotPass_False() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.startsWith("/world", caseSensitive: true, required: true)) destination.addFilter(Filters.Path.endsWith("/beaver.swift", caseSensitive: true, required: true)) destination.addFilter(Filters.Function.equals("executeSQLStatement", required: true)) destination.addFilter(Filters.Message.startsWith("SQL:", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.contains("insert", "update", "delete", required: true)) XCTAssertFalse(destination.shouldLevelBeLogged(.debug, path: "/world/beaver.swift", function: "executeSQLStatement", message: "SQL: CREATE TABLE sample (c1 INTEGER, c2 VARCHAR)")) } func test_shouldLevelBeLogged_hasLevelFilterCombinationOfOtherFiltersIncludingNonRequiredAndPasses_True() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.startsWith("/world", caseSensitive: true, required: true)) destination.addFilter(Filters.Path.endsWith("/beaver.swift", caseSensitive: true, required: true)) destination.addFilter(Filters.Function.equals("executeSQLStatement", required: true)) destination.addFilter(Filters.Message.startsWith("SQL:", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.contains("insert")) destination.addFilter(Filters.Message.contains("update")) destination.addFilter(Filters.Message.contains("delete")) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.warning, path: "/world/beaver.swift", function: "executeSQLStatement", message: "SQL: INSERT INTO table (c1, c2) VALUES (1, 2)")) } func test_shouldLevelBeLogged_hasLevelFilterCombinationOfOtherFiltersIncludingNonRequired_True() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.startsWith("/world", caseSensitive: true, required: true)) destination.addFilter(Filters.Path.endsWith("/beaver.swift", caseSensitive: true, required: true)) destination.addFilter(Filters.Function.equals("executeSQLStatement", required: true)) destination.addFilter(Filters.Message.startsWith("SQL:", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.contains("insert", caseSensitive: true)) destination.addFilter(Filters.Message.contains("update")) destination.addFilter(Filters.Message.contains("delete")) XCTAssertTrue(destination.shouldLevelBeLogged(SwiftyBeaver.Level.warning, path: "/world/beaver.swift", function: "executeSQLStatement", message: "SQL: INSERT INTO table (c1, c2) VALUES (1, 2)")) } func test_shouldLevelBeLogged_hasLevelFilterCombinationOfOtherFiltersIncludingNonRequired_False() { let destination = BaseDestination() destination.minLevel = SwiftyBeaver.Level.info destination.addFilter(Filters.Path.startsWith("/world", caseSensitive: true, required: true)) destination.addFilter(Filters.Path.endsWith("/beaver.swift", caseSensitive: true, required: true)) destination.addFilter(Filters.Function.equals("executeSQLStatement", required: true)) destination.addFilter(Filters.Message.startsWith("SQL:", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.contains("rename", caseSensitive: true, required: true)) destination.addFilter(Filters.Message.contains("update")) destination.addFilter(Filters.Message.contains("delete")) XCTAssertFalse(destination.shouldLevelBeLogged(.debug, path: "/world/beaver.swift", function: "executeSQLStatement", message: "SQL: INSERT INTO table (c1, c2) VALUES (1, 2)")) } func test_shouldLevelBeLogged_hasMatchingNonRequiredFilter_True() { let destination = BaseDestination() destination.minLevel = .info destination.addFilter(Filters.Path.contains("/ViewController")) XCTAssertTrue(destination.shouldLevelBeLogged(.debug, path: "/world/ViewController.swift", function: "myFunc", message: "Hello World")) } func test_shouldLevelBeLogged_hasNoMatchingNonRequiredFilter_False() { let destination = BaseDestination() destination.minLevel = .info destination.addFilter(Filters.Path.contains("/ViewController")) XCTAssertFalse(destination.shouldLevelBeLogged(.debug, path: "/world/beaver.swift", function: "myFunc", message: "Hello World")) } func test_shouldLevelBeLogged_hasNoMatchingNonRequiredFilterAndMinLevel_False() { let destination = BaseDestination() destination.minLevel = .info destination.addFilter(Filters.Path.contains("/ViewController", minLevel: .debug)) XCTAssertFalse(destination.shouldLevelBeLogged(.verbose, path: "/world/ViewController.swift", function: "myFunc", message: "Hello World")) } func test_shouldLevelBeLogged_noFilters_True() { // everything is logged on default let destination = BaseDestination() XCTAssertTrue(destination.shouldLevelBeLogged(.debug, path: "/world/ViewController.swift", function: "myFunc", message: "Hello World")) } func test_shouldLevelBeLogged_multipleNonRequiredFiltersAndGlobal_True() { // everything is logged on default let destination = BaseDestination() destination.minLevel = .info destination.addFilter(Filters.Path.contains("/ViewController", minLevel: .debug)) destination.addFilter(Filters.Function.contains("Func", minLevel: .debug)) destination.addFilter(Filters.Message.contains("World", minLevel: .debug)) //destination.debugPrint = true // covered by filters XCTAssertTrue(destination.shouldLevelBeLogged(.debug, path: "/world/ViewController.swift", function: "myFunc", message: "Hello World")) // not in filter and below global minLevel XCTAssertFalse(destination.shouldLevelBeLogged(.debug, path: "hello.swift", function: "foo", message: "bar")) } func test_shouldLevelBeLogged_excludeFilter_True() { // everything is logged on default let destination = BaseDestination() destination.minLevel = .error destination.addFilter(Filters.Path.contains("/ViewController", minLevel: .debug)) destination.addFilter(Filters.Function.excludes("myFunc", minLevel: .debug)) //destination.debugPrint = true // excluded XCTAssertFalse(destination.shouldLevelBeLogged(.debug, path: "/world/ViewController.swift", function: "myFunc", message: "Hello World")) // excluded XCTAssertFalse(destination.shouldLevelBeLogged(.error, path: "/world/ViewController.swift", function: "myFunc", message: "Hello World")) // not excluded, but below minLevel XCTAssertFalse(destination.shouldLevelBeLogged(.debug, path: "/world/OtherViewController.swift", function: "otherFunc", message: "Hello World")) // not excluded, but above minLevel XCTAssertTrue(destination.shouldLevelBeLogged(.error, path: "/world/OtherViewController.swift", function: "otherFunc", message: "Hello World")) } /// turns dict into JSON-encoded string func jsonStringFromDict(_ dict: [String: Any]) -> String? { var jsonString: String? // try to create JSON string do { let jsonData = try JSONSerialization.data(withJSONObject: dict, options: []) jsonString = String(data: jsonData, encoding: .utf8) } catch { print("SwiftyBeaver could not create JSON from dict.") } return jsonString } // MARK: Linux allTests static let allTests = [ ("testFormatMessage", testFormatMessage), ("testLevelWord", testLevelWord), ("testColorForLevel", testColorForLevel), ("testFileNameOfFile", testFileNameOfFile), ("testFileNameOfFileWithoutSuffix", testFileNameOfFileWithoutSuffix), ("testFormatDate", testFormatDate), ("test_init_noMinLevelSet", test_init_noMinLevelSet), ("test_init_minLevelSet", test_init_minLevelSet), ("test_shouldLevelBeLogged_hasMinLevel_True", test_shouldLevelBeLogged_hasMinLevel_True), ("test_shouldLevelBeLogged_hasMinLevel_False", test_shouldLevelBeLogged_hasMinLevel_False), ("test_shouldLevelBeLogged_hasMinLevelAndMatchingLevelAndEqualPath_True", test_shouldLevelBeLogged_hasMinLevelAndMatchingLevelAndEqualPath_True), ("test_shouldLevelBeLogged_hasMinLevelAndNoMatchingLevelButEqualPath_False", test_shouldLevelBeLogged_hasMinLevelAndNoMatchingLevelButEqualPath_False), ("test_shouldLevelBeLogged_hasMinLevelAndOneEqualsPathFilterAndDoesNotPass_False", test_shouldLevelBeLogged_hasMinLevelAndOneEqualsPathFilterAndDoesNotPass_False), ("test_shouldLevelBeLogged_hasLevelFilterAndTwoRequiredPathFiltersAndPasses_True", test_shouldLevelBeLogged_hasLevelFilterAndTwoRequiredPathFiltersAndPasses_True), ("test_shouldLevelBeLogged_hasLevelFilterAndTwoRequiredPathFiltersAndDoesNotPass_False", test_shouldLevelBeLogged_hasLevelFilterAndTwoRequiredPathFiltersAndDoesNotPass_False), ("test_shouldLevelBeLogged_hasLevelFilterARequiredPathFilterAndTwoRequiredMessageFiltersAndPasses_True", test_shouldLevelBeLogged_hasLevelFilterARequiredPathFilterAndTwoRequiredMessageFiltersAndPasses_True), ("test_shouldLevelBeLogged_hasLevelFilterARequiredPathFilterAndTwoRequiredMessageFiltersAndDoesNotPass_False", test_shouldLevelBeLogged_hasLevelFilterARequiredPathFilterAndTwoRequiredMessageFiltersAndDoesNotPass_False), ("test_shouldLevelBeLogged_hasLevelFilterCombinationOfAllOtherFiltersAndPasses_True", test_shouldLevelBeLogged_hasLevelFilterCombinationOfAllOtherFiltersAndPasses_True), ("test_shouldLevelBeLogged_hasLevelFilterCombinationOfAllOtherFiltersAndDoesNotPass_False", test_shouldLevelBeLogged_hasLevelFilterCombinationOfAllOtherFiltersAndDoesNotPass_False), ("test_shouldLevelBeLogged_hasLevelFilterCombinationOfOtherFiltersIncludingNonRequiredAndPasses_True", test_shouldLevelBeLogged_hasLevelFilterCombinationOfOtherFiltersIncludingNonRequiredAndPasses_True), ("test_shouldLevelBeLogged_hasLevelFilterCombinationOfOtherFiltersIncludingNonRequired_True", test_shouldLevelBeLogged_hasLevelFilterCombinationOfOtherFiltersIncludingNonRequired_True), ("test_shouldLevelBeLogged_hasLevelFilterCombinationOfOtherFiltersIncludingNonRequired_False", test_shouldLevelBeLogged_hasLevelFilterCombinationOfOtherFiltersIncludingNonRequired_False), ("test_shouldLevelBeLogged_hasMatchingNonRequiredFilter_True", test_shouldLevelBeLogged_hasMatchingNonRequiredFilter_True), ("test_shouldLevelBeLogged_hasNoMatchingNonRequiredFilter_False", test_shouldLevelBeLogged_hasNoMatchingNonRequiredFilter_False), ("test_shouldLevelBeLogged_hasNoMatchingNonRequiredFilterAndMinLevel_False", test_shouldLevelBeLogged_hasNoMatchingNonRequiredFilterAndMinLevel_False), ("test_shouldLevelBeLogged_noFilters_True", test_shouldLevelBeLogged_noFilters_True), ("test_shouldLevelBeLogged_multipleNonRequiredFiltersAndGlobal_True", test_shouldLevelBeLogged_multipleNonRequiredFiltersAndGlobal_True), ("test_shouldLevelBeLogged_excludeFilter_True", test_shouldLevelBeLogged_excludeFilter_True) ] }
mit
26c20004fa7cf2596e09945da5006b16
52.651741
162
0.621105
4.896625
false
true
false
false
gurenupet/hah-auth-ios-swift
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/UIFontToNSDictionary.swift
5
1638
// // UIFontToNSDictionary.swift // Mixpanel // // Created by Yarden Eitan on 9/6/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation import UIKit @objc(UIFontToNSDictionary) class UIFontToNSDictionary: ValueTransformer { override class func transformedValueClass() -> AnyClass { return NSDictionary.self } override class func allowsReverseTransformation() -> Bool { return true } override func transformedValue(_ value: Any?) -> Any? { guard let font = value as? UIFont else { return nil } return ["familyName": font.familyName, "fontName": font.fontName, "pointSize": font.pointSize] } override func reverseTransformedValue(_ value: Any?) -> Any? { guard let dict = value as? NSDictionary else { return nil } if let fontSize = dict["pointSize"] as? CGFloat, fontSize > 0.0, let fontName = dict["fontName"] as? String { let systemFont = UIFont.systemFont(ofSize: fontSize) let boldSystemFont = UIFont.boldSystemFont(ofSize: fontSize) let italicSystemFont = UIFont.italicSystemFont(ofSize: fontSize) if systemFont.fontName == fontName { return systemFont } else if boldSystemFont.fontName == fontName { return boldSystemFont } else if italicSystemFont.fontName == fontName { return italicSystemFont } else { return UIFont(name: fontName, size: fontSize) } } return nil } }
mit
573fa78613c47bc41347b21e758c3eac
29.886792
117
0.603543
5.147799
false
false
false
false
innocarpe/TabNavigable
Sources/TabNavigable/TabNavigable.swift
1
2072
// // TabNavigable // TabNavigable // // Created by Wooseong Kim on 2017. 6. 26. // Copyright © 2017 Wooseong Kim. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit // MARK: Protocol public protocol TabNavigable: class, AssociatedObjectStore { var containerView: UIView! { get set } var viewControllers: [UIViewController]! { get set } } // MARK: - Protocol extension private var activeViewControllerKey = "activeViewController" extension TabNavigable where Self: UIViewController { public func changeActiveViewController(index: Int) { if index < viewControllers.count { activeViewController = viewControllers[index] } else { fatalError("Index must be less than viewControllers.count") } } var activeViewController: UIViewController? { get { return associatedObject(forKey: &activeViewControllerKey) } set { let oldValue = activeViewController if newValue != nil { setAssociatedObject(newValue, forKey: &activeViewControllerKey) removeInactiveViewController(inactiveViewController: oldValue) updateActiveViewController() } } } private func removeInactiveViewController(inactiveViewController: UIViewController?) { if let inActiveVC = inactiveViewController { // call before removing child view controller's view from hierarchy inActiveVC.willMove(toParentViewController: nil) inActiveVC.view.removeFromSuperview() // call after removing child view controller's view from hierarchy inActiveVC.removeFromParentViewController() } } private func updateActiveViewController() { if let activeVC = activeViewController { // call before adding child view controller's view as subview addChildViewController(activeVC) activeVC.view.frame = containerView.bounds containerView.addSubview(activeVC.view) // call before adding child view controller's view as subview activeVC.didMove(toParentViewController: self) } } } #endif
mit
bd43df4031ef08995ecf80370c75b621
27.763889
88
0.708836
5.038929
false
false
false
false
KenanAtmaca/Design-Patterns-Swift
Structural/Proxy.swift
1
831
// // Created by Kenan Atmaca // kenanatmaca.com // protocol proxyProtocol { func download(_ site:String) } class Api: proxyProtocol { func download(_ site:String) { print("Download file %100 ... \(site)") } } class ApiProxy : proxyProtocol { private var api:Api! func auth(_ token: String) -> Bool { guard token == "XXX" else { return false } api = Api() return true } func download(_ site:String) { if api != nil { api.download(site) } else { print("@ Error Access Api Token") } } } let obj = ApiProxy() obj.download("http://img.com/pwqr3") // Error obj.auth("XXX") obj.download("http://img.com/pwqr3") // Download
gpl-3.0
4e1bfb822cb1a6687524b519e9fe0978
15.959184
48
0.499398
3.847222
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Components/Timetable/Main/TimetableLessonDetails/TimetableDetailsFooters.swift
1
3433
// // TimetableDetailsFooters.swift // HTWDD // // Created by Chris Herlemann on 21.07.21. // Copyright © 2021 HTW Dresden. All rights reserved. // class RequiredFooter: UITableViewHeaderFooterView { let title = UILabel() let background = UIView() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) configureContents() } func configureContents() { background.backgroundColor = UIColor.htw.cellBackground if #available(iOS 11.0, *) { background.layer.cornerRadius = 6 background.layer.masksToBounds = true background.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] } contentView.backgroundColor = UIColor.htw.veryLightGrey background.translatesAutoresizingMaskIntoConstraints = false title.translatesAutoresizingMaskIntoConstraints = false title.font = .systemFont(ofSize: 14) contentView.addSubview(background) contentView.addSubview(title) NSLayoutConstraint.activate([ background.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8), background.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8), background.topAnchor.constraint(equalTo: contentView.topAnchor), background.bottomAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), title.heightAnchor.constraint(equalToConstant: 30), title.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16), title.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), title.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -14), title.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -16) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class EmptyFooter: UITableViewHeaderFooterView { let background = UIView() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) configureContents() } func configureContents() { background.backgroundColor = UIColor.htw.cellBackground if #available(iOS 11.0, *) { background.layer.cornerRadius = 6 background.layer.masksToBounds = true background.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] } contentView.backgroundColor = UIColor.htw.veryLightGrey background.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(background) NSLayoutConstraint.activate([ background.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8), background.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8), background.topAnchor.constraint(equalTo: contentView.topAnchor), background.bottomAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
76729087be9adb8169b60badd40a5100
35.126316
100
0.659091
5.682119
false
false
false
false
morphizus/XCUI-PO-model
Support/UITestCase.swift
1
1706
import Foundation import XCTest class UITestCase: XCTestCase { let app = XCUIApplication() private var uiTestCaseGherkinSteps = UITestCaseGherkinSteps() private static var firstUse: Bool = true private var screens: ScreenMap! static func isFirstUse() -> Bool { let fu = UITestCase.firstUse UITestCase.firstUse = false return fu } func set(screens: ScreenMap, with steps: [UIStepDefiner]) { self.screens = screens merge(steps: steps) } func Given(_ step: String) { executeStep(whithName: step, screens: screens) } func When(_ step: String) { executeStep(whithName: step, screens: screens) } func Then(_ step: String) { executeStep(whithName: step, screens: screens) } override func setUp() { super.setUp() app.launch() } override func tearDown() { super.tearDown() screens = nil } //MARK: private private func merge(steps: [UIStepDefiner]) { for composer in steps { //merge the steps for step in composer.uiTestCaseGherkinSteps { assert(uiTestCaseGherkinSteps[step.key] == nil, "Already have a test with name \'\(step.key)\'") self.uiTestCaseGherkinSteps[step.key] = step.value } } } private func executeStep(whithName name: String, screens: ScreenMap) { guard let gherkinStep = uiTestCaseGherkinSteps[name] else { assertionFailure("Step \'\(name)\' not found") return } //execute Gherkin step gherkinStep(screens) } }
apache-2.0
32757b0203e4c2140b03ce048c499bb9
25.65625
112
0.583822
4.385604
false
true
false
false
itechline/bonodom_new
SlideMenuControllerSwift/PickerDialog.swift
1
11800
// // PickerDialog.swift // // Created by Loren Burton on 02/08/2016. // import Foundation import UIKit import QuartzCore class PickerDialog: UIView, UIPickerViewDataSource, UIPickerViewDelegate { typealias PickerCallback = (value: String, display: String) -> Void /* Constants */ private let kPickerDialogDefaultButtonHeight: CGFloat = 50 private let kPickerDialogDefaultButtonSpacerHeight: CGFloat = 1 private let kPickerDialogCornerRadius: CGFloat = 3 private let kPickerDialogDoneButtonTag: Int = 1 /* Views */ private var dialogView: UIView! private var titleLabel: UILabel! private var picker: UIPickerView! private var cancelButton: UIButton! private var doneButton: UIButton! /* Variables */ private var pickerData = [[String: String]]() private var selectedPickerValue: String? private var callback: PickerCallback? /* Overrides */ init() { super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) setupView() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupView() { self.dialogView = createContainerView() self.dialogView!.layer.shouldRasterize = true self.dialogView!.layer.rasterizationScale = UIScreen.mainScreen().scale self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.mainScreen().scale self.dialogView!.layer.opacity = 0.5 self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1) self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) picker.delegate = self self.addSubview(self.dialogView!) } /* Handle device orientation changes */ func deviceOrientationDidChange(notification: NSNotification) { close() // For now just close it } /* Required UIPickerView functions */ func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerData[row]["display"] } /* Helper to find row of selected value */ func findIndexForValue(value: String, array: [[String: String]]) -> Int? { for (index, dictionary) in array.enumerate() { if dictionary["value"] == value { return index } } return nil } /* Create the dialog view, and animate opening the dialog */ func show(title: String, doneButtonTitle: String = "OK", cancelButtonTitle: String = "Mégse", options: [[String: String]], selected: String? = nil, callback: PickerCallback) { self.titleLabel.text = title self.pickerData = options self.doneButton.setTitle(doneButtonTitle, forState: .Normal) self.cancelButton.setTitle(cancelButtonTitle, forState: .Normal) self.callback = callback if selected != nil { self.selectedPickerValue = selected let selectedIndex = findIndexForValue(selected!, array: options) ?? 0 self.picker.selectRow(selectedIndex, inComponent: 0, animated: false) } /* */ //UIApplication.sharedApplication().windows.first!.addSubview(self) //UIApplication.sharedApplication().windows.first!.endEditing(true) UIApplication.sharedApplication().keyWindow?.addSubview(self) /*let screenSize = UIScreen.mainScreen().bounds.size UIView.animateWithDuration(0.2) { self.frame = CGRectMake(0, screenSize.height - 260.0, screenSize.width, 260.0) }*/ /* Anim */ UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) self.dialogView!.layer.opacity = 1 self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1) }, completion: nil ) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PickerDialog.deviceOrientationDidChange(_:)), name: UIDeviceOrientationDidChangeNotification, object: nil) } /* Dialog close animation then cleaning and removing the view from the parent */ private func close() { NSNotificationCenter.defaultCenter().removeObserver(self) let currentTransform = self.dialogView.layer.transform let startRotation = (self.valueForKeyPath("layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0 let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + M_PI * 270 / 180), 0, 0, 0) self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1)) self.dialogView.layer.opacity = 1 UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1)) self.dialogView.layer.opacity = 0 }) { (finished: Bool) -> Void in for v in self.subviews { v.removeFromSuperview() } self.removeFromSuperview() } } /* Creates the container view here: create the dialog, then add the custom content and buttons */ private func createContainerView() -> UIView { let screenSize = countScreenSize() let dialogSize = CGSizeMake( 300, 230 + kPickerDialogDefaultButtonHeight + kPickerDialogDefaultButtonSpacerHeight) // For the black background self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height) // This is the dialog's container; we attach the custom content and the buttons to this one let dialogContainer = UIView(frame: CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height)) // First, we style the dialog to match the iOS8 UIAlertView >>> let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer) gradient.frame = dialogContainer.bounds gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor, UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).CGColor, UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor] let cornerRadius = kPickerDialogCornerRadius gradient.cornerRadius = cornerRadius dialogContainer.layer.insertSublayer(gradient, atIndex: 0) dialogContainer.layer.cornerRadius = cornerRadius dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).CGColor dialogContainer.layer.borderWidth = 1 dialogContainer.layer.shadowRadius = cornerRadius + 5 dialogContainer.layer.shadowOpacity = 0.1 dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius + 5) / 2, 0 - (cornerRadius + 5) / 2) dialogContainer.layer.shadowColor = UIColor.blackColor().CGColor dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).CGPath // There is a line above the button let lineView = UIView(frame: CGRectMake(0, dialogContainer.bounds.size.height - kPickerDialogDefaultButtonHeight - kPickerDialogDefaultButtonSpacerHeight, dialogContainer.bounds.size.width, kPickerDialogDefaultButtonSpacerHeight)) lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1) dialogContainer.addSubview(lineView) // ˆˆˆ //Title self.titleLabel = UILabel(frame: CGRectMake(10, 10, 280, 30)) self.titleLabel.textAlignment = NSTextAlignment.Center self.titleLabel.textColor = UIColor(hex: "333333") self.titleLabel.font = UIFont(name: "AvenirNext-Medium", size: 16) dialogContainer.addSubview(self.titleLabel) self.picker = UIPickerView(frame: CGRectMake(0, 30, 0, 0)) self.picker.setValue(UIColor(hex: "333333"), forKeyPath: "textColor") self.picker.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin self.picker.frame.size.width = 300 dialogContainer.addSubview(self.picker) // Add the buttons addButtonsToView(dialogContainer) return dialogContainer } /* Add buttons to container */ private func addButtonsToView(container: UIView) { let buttonWidth = container.bounds.size.width / 2 self.cancelButton = UIButton(type: UIButtonType.Custom) as UIButton self.cancelButton.frame = CGRectMake( 0, container.bounds.size.height - kPickerDialogDefaultButtonHeight, buttonWidth, kPickerDialogDefaultButtonHeight ) self.cancelButton.setTitleColor(UIColor(hex: "555555"), forState: UIControlState.Normal) self.cancelButton.setTitleColor(UIColor(hex: "555555"), forState: UIControlState.Highlighted) self.cancelButton.titleLabel!.font = UIFont(name: "AvenirNext-Medium", size: 15) self.cancelButton.layer.cornerRadius = kPickerDialogCornerRadius self.cancelButton.addTarget(self, action: #selector(PickerDialog.buttonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.cancelButton) self.doneButton = UIButton(type: UIButtonType.Custom) as UIButton self.doneButton.frame = CGRectMake( buttonWidth, container.bounds.size.height - kPickerDialogDefaultButtonHeight, buttonWidth, kPickerDialogDefaultButtonHeight ) self.doneButton.tag = kPickerDialogDoneButtonTag self.doneButton.setTitleColor(UIColor(hex: "555555"), forState: UIControlState.Normal) self.doneButton.setTitleColor(UIColor(hex: "555555"), forState: UIControlState.Highlighted) self.doneButton.titleLabel!.font = UIFont(name: "AvenirNext-Medium", size: 15) self.doneButton.layer.cornerRadius = kPickerDialogCornerRadius self.doneButton.addTarget(self, action: #selector(PickerDialog.buttonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.doneButton) } func buttonTapped(sender: UIButton!) { if sender.tag == kPickerDialogDoneButtonTag { let selectedIndex = self.picker.selectedRowInComponent(0) let selectedValue = self.pickerData[selectedIndex]["value"] let selectedText = self.pickerData[selectedIndex]["display"] self.callback?(value: selectedValue!, display: selectedText!) } close() } /* Helper function: count and return the screen's size */ func countScreenSize() -> CGSize { let screenWidth = UIScreen.mainScreen().applicationFrame.size.width let screenHeight = UIScreen.mainScreen().bounds.size.height return CGSizeMake(screenWidth, screenHeight) } }
mit
c07de15445789462f6e394c3be997924
41.584838
238
0.66531
4.945912
false
false
false
false
PlutoMa/EmployeeCard
EmployeeCard/EmployeeCard/NetUtil/NetConstant.swift
1
760
// // NetConstant.swift // EmployeeCard // // Created by PlutoMa on 2017/4/1. // Copyright © 2017年 PlutoMa. All rights reserved. // import Foundation let baseUrl = "http://60.208.20.231:10000/" let helloUrl = "dwCard/hello.do" let loginUrl = "dwCard/servlet/LoginServlet" let adlsVersionUrl = "dwCard/addresslist.do?method=getAddresslistVersion" let adlsInfoUrl = "dwCard/addresslist.do?method=getAddressList" let qrCodeUrl = "dwCard/servlet/GetQrCodeKey" let busInfoUrl = "dwCard/busservice.do?method=getBusInfo" let mapInfoUrl = "dwCard/images/oos_images/" let weddingInfoUrl = "dwCard/weddingInfo.do" let weddingPhotoUrl = "dwCard/images/marry/" let recordInfoUrl = "dwCard/queryDiningHis.do" let servicePagesUrl = "dwCard/servicePages.do"
mit
e3960f34e320a29bc755f351f6a3166e
24.233333
73
0.760898
2.835206
false
false
false
false
mipstian/vapor-apns
Sources/VaporAPNS/CurlVersionHelper.swift
3
3581
// // CurlVersionHelper.swift // VaporAPNS // // Created by Matthijs Logemann on 01/01/2017. // // import Foundation import CCurl import Console open class CurlVersionHelper { public enum Result { case ok case old case noHTTP2 case unknown } public func checkVersion(autoInstall: Bool = false) { let result = checkVersionNum() if result == .old { let console: ConsoleProtocol = Terminal(arguments: CommandLine.arguments) var response = "" if !autoInstall { console.output("Your current version of curl is out of date!\nVaporAPNS will not work with this version of curl.", style: .error) console.output("You can update curl yourself or we can try to update curl and it's nescessary dependencies.", style: .info) response = console.ask("Continue installing curl? [y/n]", style: .info) } if response == "y" || autoInstall { let curlupdater = CurlUpdater() curlupdater.updateCurl() }else { exit(1) } }else if result == .noHTTP2 { let console: ConsoleProtocol = Terminal(arguments: CommandLine.arguments) var response = "" if !autoInstall { console.output("Your current version of curl lacks HTTP2!\nVaporAPNS will not work with this version of curl.", style: .error) console.output("You can either let VaporAPNS rebuild and install curl for you or you can rebuild curl with HTTP2 support yourself.", style: .info) response = console.ask("Continue rebuilding curl? [y/n]", style: .info) } if response == "y" || autoInstall { let curlupdater = CurlUpdater() curlupdater.updateCurl() }else { exit(1) } } } private func checkVersionNum() -> Result { let version = curl_version_info(CURLVERSION_FOURTH) let verBytes = version?.pointee.version let versionString = String.init(cString: verBytes!) // return .old guard checkVersionNumber(versionString, "7.51.0") >= 0 else { return .old } let features = version?.pointee.features if ((features! & CURL_VERSION_HTTP2) == CURL_VERSION_HTTP2) { return .ok }else { return .noHTTP2 } } private func checkVersionNumber(_ strVersionA: String, _ strVersionB: String) -> Int{ var arrVersionA = strVersionA.split(".").map({ Int($0) }) guard arrVersionA.count == 3 else { fatalError("Wrong curl version scheme! \(strVersionA)") } var arrVersionB = strVersionB.split(".").map({ Int($0) }) guard arrVersionB.count == 3 else { fatalError("Wrong curl version scheme! \(strVersionB)") } let intVersionA = (100000000 * arrVersionA[0]!) + (1000000 * arrVersionA[1]!) + (10000 * arrVersionA[2]!) let intVersionB = (100000000 * arrVersionB[0]!) + (1000000 * arrVersionB[1]!) + (10000 * arrVersionB[2]!) // let intVersionA = 0 // let intVersionB = 0 if (intVersionA > intVersionB) { return 1 }else if(intVersionA < intVersionB){ return -1 }else{ return 0 } } }
mit
1f5fb5d2fdf56feca497deb98e2c1ca2
33.104762
162
0.545937
4.498744
false
false
false
false
FotiosTragopoulos/Core-Geometry
Core Geometry/Ana1ViewLine.swift
1
1621
// // Ana1ViewLine.swift // Core Geometry // // Created by Fotios Tragopoulos on 22/01/2017. // Copyright © 2017 Fotios Tragopoulos. All rights reserved. // import UIKit class Ana1ViewLine: UIView { override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let myShadowOffset = CGSize (width: 10, height: 10) context?.setShadow (offset: myShadowOffset, blur: 8) context?.saveGState() context?.setLineWidth(5.0) context?.setStrokeColor(UIColor.blue.cgColor) let xView = viewWithTag(48)?.alignmentRect(forFrame: rect).midX let yView = viewWithTag(48)?.alignmentRect(forFrame: rect).midY let width = self.viewWithTag(48)?.frame.size.width let height = self.viewWithTag(48)?.frame.size.height let size = CGSize(width: width! * 0.7, height: height! * 0.7) let linePlacementX = CGFloat(size.width/1.7) let linePlacementY = CGFloat(size.height/2) context?.move(to: CGPoint(x: (xView! - linePlacementX * 0.92), y: (yView! + linePlacementY * 1.2))) context?.addLine(to: CGPoint(x: (xView! + linePlacementX * 0.94), y: (yView! - linePlacementY))) context?.strokePath() context?.restoreGState() self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil) } }
apache-2.0
a596d1f4baea0b3dad2169a04f32750c
36.674419
219
0.637037
3.884892
false
false
false
false
chunkyguy/MobileReddit
MobileReddit/FirstViewController.swift
1
9647
// // FrontPageViewController.swift // MobileReddit // // Created by Sid on 14/09/14. // Copyright (c) 2014 whackylabs. All rights reserved. // import UIKit class RedditPacket { struct Meta { let kind:String let modhash:String let after:String let before:String? init(dict:NSDictionary) { kind = dict["kind"] as String let data = dict["data"] as NSDictionary modhash = data["modhash"] as String after = data["after"] as String before = data["before"] as? String } } struct Item { let kind:String let domain:String? let banned_by:String? let media_embed:String? let subreddit:String? let selftext_html:String? let selftext:String? let likes:String? let secure_media:String? let link_flair_text:String? let id:String? let gilded:String? let secure_media_embed:String? let clicked:String? let report_reasons:String? let author:String? let media:String? let score:String? let approved_by:String? let over_18:String? let hidden:String? let thumbnail:String? let subreddit_id:String? let edited:String? let link_flair_css_class:String? let author_flair_css_class:String? let downs:String? let saved:String? let is_self:String? let name:String? let permalink:String? let stickied:String? let created:String? let url:String? let author_flair_text:String? let title:String? let created_utc:String? let ups:String? let num_comments:String? let visited:String? let num_reports:String? let distinguished:String? init(dict:NSDictionary) { kind = dict["kind"] as String let data = dict["data"] as NSDictionary domain = data["domain"] as? String banned_by = data["banned_by"] as? String media_embed = data["media_embed"] as? String subreddit = data["subreddit"] as? String selftext_html = data["selftext_html"] as? String selftext = data["selftext"] as? String likes = data["likes"] as? String secure_media = data["secure_media"] as? String link_flair_text = data["link_flair_text"] as? String id = data["d"] as? String gilded = data["gilded"] as? String secure_media_embed = data["secure_media_embed"] as? String clicked = data["clicked"] as? String report_reasons = data["report_reasons"] as? String author = data["author"] as? String media = data["media"] as? String score = data["score"] as? String approved_by = data["approved_by"] as? String over_18 = data["over_18"] as? String hidden = data["hidden"] as? String thumbnail = data["thumbnail"] as? String subreddit_id = data["subreddit_id"] as? String edited = data["edited"] as? String link_flair_css_class = data["link_flair_css_class"] as? String author_flair_css_class = data["author_flair_css_class"] as? String downs = data["downs"] as? String saved = data["saved"] as? String is_self = data["is_self"] as? String name = data["name"] as? String permalink = data["permalink"] as? String stickied = data["stickied"] as? String created = data["created"] as? String url = data["url"] as? String author_flair_text = data["author_flair_text"] as? String title = data["title"] as? String created_utc = data["domain"] as? String ups = data["ups"] as? String num_comments = data["num_comments"] as? String visited = data["visited"] as? String num_reports = data["num_reports"] as? String distinguished = data["distinguished"] as? String } } let meta:Meta; let items:[Item] = [] init(dict:NSDictionary) { meta = Meta(dict: dict) let data = dict["data"] as NSDictionary let children = data["children"] as NSArray for child in children as [NSDictionary] { items.append(Item(dict: child)) } } } func parseJSONFromData(data:NSData)->RedditPacket? { var jsonError : NSError? let jsonResult : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &jsonError) if let error = jsonError { println("JSON Error \(jsonError)") return nil } else if let jsonArray = jsonResult as? NSArray { println("JSON Array \(jsonArray)") return nil } else if let jsonDict = jsonResult as? NSDictionary { println("JSON Dict \(jsonDict)") return RedditPacket(dict: jsonDict) } return nil } func parseJSONFromString(str:String)->RedditPacket? { if let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) { return parseJSONFromData(data) } return nil } func readFileContents(filepath:NSURL) -> String? { var fileError:NSError? let fileContent = String.stringWithContentsOfURL(filepath, encoding: NSUTF8StringEncoding, error: &fileError) if let readError = fileError { println("Error \(readError) while reading contents of file \(filepath)") return nil } return fileContent } func fetchLocalData(filepath:NSURL, completionHandler:(RedditPacket?)->()) { if let fileContent = readFileContents(filepath) { return completionHandler(parseJSONFromString(fileContent)) } return completionHandler(nil) } func fetchRemoteData(completionHandler:(RedditPacket?)->()) { let scheme = "http" let baseURL = "http://www.reddit.com/" let method = "GET" let path = "r/all/top.json" /* create session */ let sessionConfig:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) /* start a request */ let finalURL:NSURL = NSURL(string: "http://www.reddit.com/r/all/top.json") let request:NSMutableURLRequest = NSMutableURLRequest(URL: finalURL, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60) request.addValue("MobileReddit/1.0 by u/whackylabs", forHTTPHeaderField: "User-Agent") let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in var jsonError : NSError? let jsonResult : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &jsonError) if let error = jsonError { println("JSON Error \(jsonError)") completionHandler(nil) } else if let jsonDict = jsonResult as? NSDictionary { println("JSON Dict \(jsonDict)") completionHandler(RedditPacket(dict: jsonDict)) } else if let jsonArray = jsonResult as? NSArray { println("JSON Array \(jsonArray)") completionHandler(nil) } }) task.resume() } func bundlePathForFilename(filename:String, extn:String?) -> NSURL? { return NSBundle.mainBundle() .URLForResource(filename, withExtension: extn) } class FrontPageViewController: UITableViewController { let cellId = "frontDefaultCell" var currentPacket:RedditPacket? override func viewDidLoad() { super.viewDidLoad() if let filepath = bundlePathForFilename("top", "json") { fetchLocalData(filepath, { (packet:RedditPacket?) -> () in self.currentPacket = packet }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: UITableViewDataSource methods override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let packet = currentPacket { println("rows:\(section): \(packet.items.count)") return packet.items.count } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as UITableViewCell if let packet = currentPacket { let item:RedditPacket.Item = packet.items[indexPath.row] if let itemTitle = item.title { cell.textLabel?.text = itemTitle cell.textLabel?.numberOfLines = 0 cell.textLabel?.sizeToFit() } if let itemSubreddit = item.subreddit { cell.detailTextLabel?.text = itemSubreddit } } return cell } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } //MARK: UITableViewDelegate methods }
mit
aeba6c833c8e7e564999f99491206789
32.61324
116
0.596766
4.747539
false
false
false
false
hshssingh4/Tips-iOS-Project
Tips/ViewController.swift
1
6424
// // ViewController.swift // Tips // // Created by Harpreet on 12/6/15. // Copyright © 2015 Harpreet. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var billField: UITextField! @IBOutlet weak var plusLabel: UILabel! @IBOutlet weak var equalsLabel: UILabel! @IBOutlet weak var customTipSlider: UISlider! @IBOutlet weak var customTipLabel: UILabel! let defaults = NSUserDefaults.standardUserDefaults() let originalTintColor: UIColor = UIColor(red: 0, green: 0.478431, blue: 1, alpha: 1) var numberFormatter = NSNumberFormatter() var tipAmount = 0.0; var totalAmount = 0.0; var billAmount = 0.0; let percentages = [0.18, 0.20, 0.25]; var percentage = 0.0; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. billField.becomeFirstResponder() tipControl.selectedSegmentIndex = defaults.integerForKey("indexDefaultTip") numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle numberFormatter.numberStyle = .CurrencyStyle billField.placeholder = numberFormatter.currencySymbol billField.attributedPlaceholder = NSAttributedString(string: billField.placeholder!, attributes:[NSForegroundColorAttributeName : UIColor.lightGrayColor()]) setDefaultTheme() checkTimeElapsed() tipLabel.adjustsFontSizeToFitWidth = true totalLabel.adjustsFontSizeToFitWidth = true } override func viewWillAppear(animated: Bool) { billField.becomeFirstResponder() setDefaultTheme() tipControl.selectedSegmentIndex = defaults.integerForKey("indexDefaultTip") if defaults.boolForKey("customTipSlider") { customTipSlider.value = Float(defaults.integerForKey("customTipValue")) customTipLabel.text = String(Int(customTipSlider.value)) + " %" tipControl.hidden = true customTipSlider.hidden = false customTipLabel.hidden = false } else { tipControl.hidden = false customTipSlider.hidden = true customTipLabel.hidden = true } calculateTip("") } @IBAction func calculateTip(sender: AnyObject) { numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle numberFormatter.numberStyle = .CurrencyStyle billField.placeholder = numberFormatter.currencySymbol if billField.text?.isEmpty == true { moveDownAnimation() } else { moveUpAnimation() } billAmount = NSString(string: billField.text!).doubleValue let previousTime = NSDate() defaults.setObject(previousTime, forKey: "previousTime") defaults.setObject(billField.text, forKey: "textThen") if defaults.boolForKey("customTipSlider") { percentage = Double(Int(customTipSlider.value)) / 100.0 } else { percentage = percentages[tipControl.selectedSegmentIndex] } tipAmount = billAmount * percentage totalAmount = billAmount + tipAmount tipLabel.text = numberFormatter.stringFromNumber(tipAmount) totalLabel.text = numberFormatter.stringFromNumber(totalAmount) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func moveDownAnimation() { UIView.animateWithDuration(0.5, animations: { self.billField.center.y = 400 self.tipControl.alpha = 0 self.customTipSlider.alpha = 0 self.customTipLabel.alpha = 0 self.tipLabel.alpha = 0 self.totalLabel.alpha = 0 self.plusLabel.alpha = 0 self.equalsLabel.alpha = 0 }) } func moveUpAnimation() { UIView.animateWithDuration(0.5, animations: { self.billField.center.y = 187.0 self.tipControl.alpha = 1 self.tipLabel.alpha = 1 self.customTipSlider.alpha = 1 self.customTipLabel.alpha = 1 self.totalLabel.alpha = 1 self.plusLabel.alpha = 1 self.equalsLabel.alpha = 1 }) } @IBAction func sliderValueChanged(sender: AnyObject) { customTipLabel.text = String(Int(customTipSlider.value)) + " %" } func setDefaultTheme() { if defaults.integerForKey("indexThemeColor") == 0 { self.view.backgroundColor = UIColor.whiteColor() billField.textColor = UIColor.blackColor() tipControl.tintColor = originalTintColor plusLabel.textColor = UIColor.blackColor() equalsLabel.textColor = UIColor.blackColor() tipLabel.textColor = UIColor.blackColor() totalLabel.textColor = UIColor.blackColor() customTipLabel.textColor = UIColor.blackColor() customTipSlider.tintColor = originalTintColor } else { self.view.backgroundColor = UIColor.blackColor() billField.textColor = UIColor.whiteColor() tipControl.tintColor = UIColor.whiteColor() plusLabel.textColor = UIColor.whiteColor() equalsLabel.textColor = UIColor.whiteColor() tipLabel.textColor = UIColor.whiteColor() totalLabel.textColor = UIColor.whiteColor() customTipLabel.textColor = UIColor.whiteColor() customTipSlider.tintColor = UIColor.lightGrayColor() } } func checkTimeElapsed() { if defaults.objectForKey("previousTime") != nil { let previousTime = defaults.objectForKey("previousTime") as! NSDate let timeNow = NSDate() let textThen = defaults.stringForKey("textThen") if timeNow.timeIntervalSinceDate(previousTime) < 10000 { billField.text = textThen } } calculateTip("") } }
apache-2.0
45c9ae6916b356558a210245f943198d
33.532258
164
0.622606
5.282072
false
false
false
false
agrippa1994/Step-Counter
Step Counter/HealthKit.swift
1
2879
// // HealthKit.swift // Step Counter // // Created by Mani on 09.02.15. // Copyright (c) 2015 Mani. All rights reserved. // import Foundation import HealthKit class Health { // MARK: - Private vars private let hkStore = HKHealthStore() private var sampleTypes = NSSet(array: [ HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount), HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning), HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierFlightsClimbed) ]) // MARK: - Private functions private func isHealthKitAvailable(completion: Bool -> Void) { if !HKHealthStore.isHealthDataAvailable() { return completion(false) } hkStore.requestAuthorizationToShareTypes(NSSet(), readTypes: sampleTypes) { success, error in return completion((success == false || error != nil) ? false : true) } } private func query(sampleTypeIdentifier: String, startDate: NSDate, endDate: NSDate, unit: HKUnit, completion: Double? -> Void) { isHealthKitAvailable { if !$0 { return completion(nil) } let sampleType = HKSampleType.quantityTypeForIdentifier(sampleTypeIdentifier) let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: nil) let query = HKStatisticsQuery(quantityType: sampleType, quantitySamplePredicate: predicate, options: .CumulativeSum) { query, statistics, error in if error != nil { return completion(nil) } if let quantity = statistics.sumQuantity() { return completion(quantity.doubleValueForUnit(unit)) } return completion(0.0) } self.hkStore.executeQuery(query) } } // MARK: - Public functions func querySteps(#fromDateTime: NSDate, toDateTime: NSDate, callback: (Double?) -> Void) { query(HKQuantityTypeIdentifierStepCount, startDate: fromDateTime, endDate: toDateTime, unit: HKUnit.countUnit()) { callback($0) } } func queryTrack(#fromDateTime: NSDate, toDateTime: NSDate, callback: (Double?) -> Void) { query(HKQuantityTypeIdentifierDistanceWalkingRunning, startDate: fromDateTime, endDate: toDateTime, unit: HKUnit(fromString: "km")) { callback($0) } } func queryFlightsClimbed(#fromDateTime: NSDate, toDateTime: NSDate, callback: (Double?) -> Void) { query(HKQuantityTypeIdentifierFlightsClimbed, startDate: fromDateTime, endDate: toDateTime, unit: HKUnit.countUnit()) { callback($0) } } }
gpl-2.0
f2c290048eaa020227fd13480e4b31ec
36.894737
158
0.627648
5.178058
false
false
false
false
sharath-cliqz/browser-ios
Storage/ThirdParty/SwiftData.swift
2
40527
/* 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/. */ /* * This is a heavily modified version of SwiftData.swift by Ryan Fowler * This has been enhanced to support custom files, correct binding, versioning, * and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and * to force callers to request a connection before executing commands. Database creation helpers, savepoint * helpers, image support, and other features have been removed. */ // SwiftData.swift // // Copyright (c) 2014 Ryan Fowler // // 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 import Shared import XCGLogger private let DatabaseBusyTimeout: Int32 = 3 * 1000 private let log = Logger.syncLogger /** * Handle to a SQLite database. * Each instance holds a single connection that is shared across all queries. */ open class SwiftData { let filename: String static var EnableWAL = true static var EnableForeignKeys = true /// Used to keep track of the corrupted databases we've logged. static var corruptionLogsWritten = Set<String>() /// Used for testing. static var ReuseConnections = true /// For thread-safe access to the shared connection. fileprivate let sharedConnectionQueue: DispatchQueue /// Shared connection to this database. fileprivate var sharedConnection: ConcreteSQLiteDBConnection? fileprivate var key: String? = nil fileprivate var prevKey: String? = nil /// A simple state flag to track whether we should accept new connection requests. /// If a connection request is made while the database is closed, a /// FailedSQLiteDBConnection will be returned. fileprivate(set) var closed = false init(filename: String, key: String? = nil, prevKey: String? = nil) { self.filename = filename self.sharedConnectionQueue = DispatchQueue(label: "SwiftData queue: \(filename)", attributes: []) // Ensure that multi-thread mode is enabled by default. // See https://www.sqlite.org/threadsafe.html assert(sqlite3_threadsafe() == 2) self.key = key self.prevKey = prevKey } fileprivate func getSharedConnection() -> ConcreteSQLiteDBConnection? { var connection: ConcreteSQLiteDBConnection? sharedConnectionQueue.sync { if self.closed { log.warning(">>> Database is closed for \(self.filename)") return } if self.sharedConnection == nil { log.debug(">>> Creating shared SQLiteDBConnection for \(self.filename) on thread \(Thread.current).") self.sharedConnection = ConcreteSQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.readWriteCreate.toSQL(), key: self.key, prevKey: self.prevKey) } connection = self.sharedConnection } return connection } /** * The real meat of all the execute methods. This is used internally to open and * close a database connection and run a block of code inside it. */ func withConnection(_ flags: SwiftData.Flags, synchronous: Bool=true, cb: @escaping (_ db: SQLiteDBConnection) -> NSError?) -> NSError? { let conn: ConcreteSQLiteDBConnection? if SwiftData.ReuseConnections { conn = getSharedConnection() } else { log.debug(">>> Creating non-shared SQLiteDBConnection for \(self.filename) on thread \(Thread.current).") conn = ConcreteSQLiteDBConnection(filename: filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey) } guard let connection = conn else { // Run the callback with a fake failed connection. // Yeah, that means we have an error return value but we still run the callback. let failed = FailedSQLiteDBConnection() let queue = self.sharedConnectionQueue let noConnection = NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not create a connection"]) if synchronous { var error: NSError? = nil queue.sync { error = cb(failed) } return error ?? noConnection } queue.async { cb(failed) } return noConnection } if synchronous { var error: NSError? = nil connection.queue.sync { error = cb(connection) } return error } connection.queue.async { cb(connection) } return nil } func transaction(_ transactionClosure: @escaping (_ db: SQLiteDBConnection) -> Bool) -> NSError? { return self.transaction(synchronous: true, transactionClosure: transactionClosure) } /** * Helper for opening a connection, starting a transaction, and then running a block of code inside it. * The code block can return true if the transaction should be committed. False if we should roll back. */ func transaction(synchronous: Bool=true, transactionClosure: @escaping (_ db: SQLiteDBConnection) -> Bool) -> NSError? { return withConnection(SwiftData.Flags.readWriteCreate, synchronous: synchronous) { db in if let err = db.executeChange("BEGIN EXCLUSIVE") { log.warning("BEGIN EXCLUSIVE failed.") return err } if transactionClosure(db) { log.verbose("Op in transaction succeeded. Committing.") if let err = db.executeChange("COMMIT") { log.error("COMMIT failed. Rolling back.") db.executeChange("ROLLBACK") return err } } else { log.debug("Op in transaction failed. Rolling back.") if let err = db.executeChange("ROLLBACK") { return err } } return nil } } /// Don't use this unless you know what you're doing. The deinitializer /// should be used to achieve refcounting semantics. func forceClose() { sharedConnectionQueue.sync { self.closed = true self.sharedConnection = nil } } /// Reopens a database that had previously been force-closed. /// Does nothing if this database is already open. func reopenIfClosed() { sharedConnectionQueue.sync { self.closed = false } } public enum Flags { case readOnly case readWrite case readWriteCreate fileprivate func toSQL() -> Int32 { switch self { case .readOnly: return SQLITE_OPEN_READONLY case .readWrite: return SQLITE_OPEN_READWRITE case .readWriteCreate: return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE } } } } /** * Wrapper class for a SQLite statement. * This class helps manage the statement lifecycle. By holding a reference to the SQL connection, we ensure * the connection is never deinitialized while the statement is active. This class is responsible for * finalizing the SQL statement once it goes out of scope. */ private class SQLiteDBStatement { var pointer: OpaquePointer? = nil fileprivate let connection: ConcreteSQLiteDBConnection init(connection: ConcreteSQLiteDBConnection, query: String, args: Args?) throws { self.connection = connection let status = sqlite3_prepare_v2(connection.sqliteDB, query, -1, &pointer, nil) if status != SQLITE_OK { throw connection.createErr("During: SQL Prepare \(query)", status: Int(status)) } if let args = args, let bindError = bind(args) { throw bindError } } /// Binds arguments to the statement. fileprivate func bind(_ objects: [Any?]) -> NSError? { let count = Int(sqlite3_bind_parameter_count(pointer)) if (count < objects.count) { return connection.createErr("During: Bind", status: 202) } if (count > objects.count) { return connection.createErr("During: Bind", status: 201) } for (index, obj) in objects.enumerated() { var status: Int32 = SQLITE_OK // Doubles also pass obj as Int, so order is important here. if obj is Double { status = sqlite3_bind_double(pointer, Int32(index+1), obj as! Double) } else if obj is Int { status = sqlite3_bind_int(pointer, Int32(index+1), Int32(obj as! Int)) } else if obj is Bool { status = sqlite3_bind_int(pointer, Int32(index+1), (obj as! Bool) ? 1 : 0) } else if obj is String { typealias CFunction = @convention(c) (UnsafeMutableRawPointer?) -> Void let transient = unsafeBitCast(-1, to: CFunction.self) status = sqlite3_bind_text(pointer, Int32(index+1), (obj as! String).cString(using: String.Encoding.utf8)!, -1, transient) } else if obj is NSData { status = sqlite3_bind_blob(pointer, Int32(index+1), ((obj as! Data) as NSData).bytes, -1, nil) } else if obj is Date { let timestamp = (obj as! Date).timeIntervalSince1970 status = sqlite3_bind_double(pointer, Int32(index+1), timestamp) } else if obj == nil { status = sqlite3_bind_null(pointer, Int32(index+1)) } if status != SQLITE_OK { return connection.createErr("During: Bind", status: Int(status)) } } return nil } func close() { if nil != self.pointer { sqlite3_finalize(self.pointer) self.pointer = nil } } deinit { if nil != self.pointer { sqlite3_finalize(self.pointer) } } } protocol SQLiteDBConnection { var lastInsertedRowID: Int { get } var numberOfRowsModified: Int { get } func executeChange(_ sqlStr: String) -> NSError? func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? func executeQuery<T>(_ sqlStr: String, factory: ((SDRow) -> T)) -> Cursor<T> func executeQuery<T>(_ sqlStr: String, factory: ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func interrupt() func checkpoint() func checkpoint(_ mode: Int32) func vacuum() -> NSError? } // Represents a failure to open. class FailedSQLiteDBConnection: SQLiteDBConnection { fileprivate func fail(_ str: String) -> NSError { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: str]) } var lastInsertedRowID: Int { return 0 } var numberOfRowsModified: Int { return 0 } func executeChange(_ sqlStr: String) -> NSError? { return self.fail("Non-open connection; can't execute change.") } func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? { return self.fail("Non-open connection; can't execute change.") } func executeQuery<T>(_ sqlStr: String, factory: ((SDRow) -> T)) -> Cursor<T> { return self.executeQuery(sqlStr, factory: factory, withArgs: nil) } func executeQuery<T>(_ sqlStr: String, factory: ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } internal func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func interrupt() {} func checkpoint() {} func checkpoint(_ mode: Int32) {} func vacuum() -> NSError? { return self.fail("Non-open connection; can't vacuum.") } } open class ConcreteSQLiteDBConnection: SQLiteDBConnection { fileprivate var sqliteDB: OpaquePointer? = nil fileprivate let filename: String fileprivate let debug_enabled = false fileprivate let queue: DispatchQueue open var version: Int { get { return pragma("user_version", factory: IntFactory) ?? 0 } set { executeChange("PRAGMA user_version = \(newValue)") } } fileprivate func setKey(_ key: String?) -> NSError? { sqlite3_key(sqliteDB, key ?? "", Int32((key ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil) if cursor.status != .Success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid key"]) } return nil } fileprivate func reKey(_ oldKey: String?, newKey: String?) -> NSError? { sqlite3_key(sqliteDB, oldKey ?? "", Int32((oldKey ?? "").characters.count)) sqlite3_rekey(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) // Check that the new key actually works sqlite3_key(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil) if cursor.status != .Success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Rekey failed"]) } return nil } func interrupt() { log.debug("Interrupt") sqlite3_interrupt(sqliteDB) } fileprivate func pragma<T: Equatable>(_ pragma: String, expected: T?, factory: @escaping (SDRow) -> T, message: String) throws { let cursorResult = self.pragma(pragma, factory: factory) if cursorResult != expected { log.error("\(message): \(cursorResult), \(expected)") throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "PRAGMA didn't return expected output: \(message)."]) } } fileprivate func pragma<T>(_ pragma: String, factory: @escaping (SDRow) -> T) -> T? { let cursor = executeQueryUnsafe("PRAGMA \(pragma)", factory: factory, withArgs: nil) defer { cursor.close() } return cursor[0] } fileprivate func prepareShared() { if SwiftData.EnableForeignKeys { pragma("foreign_keys=ON", factory: IntFactory) } // Retry queries before returning locked errors. sqlite3_busy_timeout(self.sqliteDB, DatabaseBusyTimeout) } fileprivate func prepareEncrypted(_ flags: Int32, key: String?, prevKey: String? = nil) throws { // Setting the key needs to be the first thing done with the database. if let _ = setKey(key) { if let err = closeCustomConnection(immediately: true) { log.error("Couldn't close connection: \(err). Failing to open.") throw err } if let err = openWithFlags(flags) { throw err } if let err = reKey(prevKey, newKey: key) { log.error("Unable to encrypt database") throw err } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") try pragma("journal_mode=WAL", expected: "wal", factory: StringFactory, message: "WAL journal mode set") } self.prepareShared() } fileprivate func prepareCleartext() throws { // If we just created the DB -- i.e., no tables have been created yet -- then // we can set the page size right now and save a vacuum. // // For where these values come from, see Bug 1213623. // // Note that sqlcipher uses cipher_page_size instead, but we don't set that // because it needs to be set from day one. let desiredPageSize = 32 * 1024 pragma("page_size=\(desiredPageSize)", factory: IntFactory) let currentPageSize = pragma("page_size", factory: IntFactory) // This has to be done without WAL, so we always hop into rollback/delete journal mode. if currentPageSize != desiredPageSize { try pragma("journal_mode=DELETE", expected: "delete", factory: StringFactory, message: "delete journal mode set") try pragma("page_size=\(desiredPageSize)", expected: nil, factory: IntFactory, message: "Page size set") log.info("Vacuuming to alter database page size from \(currentPageSize) to \(desiredPageSize).") if let err = self.vacuum() { log.error("Vacuuming failed: \(err).") } else { log.debug("Vacuuming succeeded.") } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") let desiredPagesPerJournal = 16 let desiredCheckpointSize = desiredPagesPerJournal * desiredPageSize let desiredJournalSizeLimit = 3 * desiredCheckpointSize /* * With whole-module-optimization enabled in Xcode 7.2 and 7.2.1, the * compiler seems to eagerly discard these queries if they're simply * inlined, causing a crash in `pragma`. * * Hackily hold on to them. */ let journalModeQuery = "journal_mode=WAL" let autoCheckpointQuery = "wal_autocheckpoint=\(desiredPagesPerJournal)" let journalSizeQuery = "journal_size_limit=\(desiredJournalSizeLimit)" try withExtendedLifetime(journalModeQuery, { try pragma(journalModeQuery, expected: "wal", factory: StringFactory, message: "WAL journal mode set") }) try withExtendedLifetime(autoCheckpointQuery, { try pragma(autoCheckpointQuery, expected: desiredPagesPerJournal, factory: IntFactory, message: "WAL autocheckpoint set") }) try withExtendedLifetime(journalSizeQuery, { try pragma(journalSizeQuery, expected: desiredJournalSizeLimit, factory: IntFactory, message: "WAL journal size limit set") }) } self.prepareShared() } init?(filename: String, flags: Int32, key: String? = nil, prevKey: String? = nil) { log.debug("Opening connection to \(filename).") self.filename = filename self.queue = DispatchQueue(label: "SQLite connection: \(filename)", attributes: []) if let failure = openWithFlags(flags) { log.warning("Opening connection to \(filename) failed: \(failure).") return nil } if key == nil && prevKey == nil { do { try self.prepareCleartext() } catch { return nil } } else { do { try self.prepareEncrypted(flags, key: key, prevKey: prevKey) } catch { return nil } } } deinit { log.debug("deinit: closing connection on thread \(Thread.current).") self.queue.sync { self.closeCustomConnection() } } open var lastInsertedRowID: Int { return Int(sqlite3_last_insert_rowid(sqliteDB)) } open var numberOfRowsModified: Int { return Int(sqlite3_changes(sqliteDB)) } func checkpoint() { self.checkpoint(SQLITE_CHECKPOINT_FULL) } /** * Blindly attempts a WAL checkpoint on all attached databases. */ func checkpoint(_ mode: Int32) { guard sqliteDB != nil else { log.warning("Trying to checkpoint a nil DB!") return } log.debug("Running WAL checkpoint on \(self.filename) on thread \(Thread.current).") sqlite3_wal_checkpoint_v2(sqliteDB, nil, mode, nil, nil) log.debug("WAL checkpoint done on \(self.filename).") } func vacuum() -> NSError? { return self.executeChange("VACUUM") } /// Creates an error from a sqlite status. Will print to the console if debug_enabled is set. /// Do not call this unless you're going to return this error. fileprivate func createErr(_ description: String, status: Int) -> NSError { var msg = SDError.errorMessageFromCode(status) if (debug_enabled) { log.debug("SwiftData Error -> \(description)") log.debug(" -> Code: \(status) - \(msg)") } if let errMsg = String(validatingUTF8: sqlite3_errmsg(sqliteDB)) { msg += " " + errMsg if (debug_enabled) { log.debug(" -> Details: \(errMsg)") } } return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg]) } /// Open the connection. This is called when the db is created. You should not call it yourself. fileprivate func openWithFlags(_ flags: Int32) -> NSError? { let status = sqlite3_open_v2(filename.cString(using: String.Encoding.utf8)!, &sqliteDB, flags, nil) if status != SQLITE_OK { return createErr("During: Opening Database with Flags", status: Int(status)) } return nil } /// Closes a connection. This is called via deinit. Do not call this yourself. fileprivate func closeCustomConnection(immediately: Bool=false) -> NSError? { log.debug("Closing custom connection for \(self.filename) on \(Thread.current).") // TODO: add a lock here? let db = self.sqliteDB self.sqliteDB = nil // Don't bother trying to call sqlite3_close multiple times. guard db != nil else { log.warning("Connection was nil.") return nil } let status = immediately ? sqlite3_close(db) : sqlite3_close_v2(db) // Note that if we use sqlite3_close_v2, this will still return SQLITE_OK even if // there are outstanding prepared statements if status != SQLITE_OK { log.error("Got status \(status) while attempting to close.") return createErr("During: closing database with flags", status: Int(status)) } log.debug("Closed \(self.filename).") return nil } open func executeChange(_ sqlStr: String) -> NSError? { return self.executeChange(sqlStr, withArgs: nil) } /// Executes a change on the database. open func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil log.error("SQL error: \(error1.localizedDescription) for SQL \(sqlStr).") } // Close, not reset -- this isn't going to be reused. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) } log.error("SQL error: \(error.localizedDescription) for SQL \(sqlStr).") return error } let status = sqlite3_step(statement!.pointer) if status != SQLITE_DONE && status != SQLITE_OK { error = createErr("During: SQL Step \(sqlStr)", status: Int(status)) } return error } func executeQuery<T>(_ sqlStr: String, factory: ((SDRow) -> T)) -> Cursor<T> { return self.executeQuery(sqlStr, factory: factory, withArgs: nil) } /// Queries the database. /// Returns a cursor pre-filled with the complete result set. func executeQuery<T>(_ sqlStr: String, factory: ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } // Close, not reset -- this isn't going to be reused, and the FilledSQLiteCursor // consumes everything. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) } log.error("SQL error: \(error.localizedDescription).") return Cursor<T>(err: error) } return FilledSQLiteCursor<T>(statement: statement!, factory: factory) } func writeCorruptionInfoForDBNamed(_ dbFilename: String, toLogger logger: XCGLogger) { DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).sync { guard !SwiftData.corruptionLogsWritten.contains(dbFilename) else { return } logger.error("Corrupt DB detected! DB filename: \(dbFilename)") let dbFileSize = ("file://\(dbFilename)".asURL)?.allocatedFileSize() ?? 0 logger.error("DB file size: \(dbFileSize) bytes") logger.error("Integrity check:") let messages = self.executeQueryUnsafe("PRAGMA integrity_check", factory: StringFactory, withArgs: nil) defer { messages.close() } if messages.status == CursorStatus.Success { for message in messages { logger.error(message) } logger.error("----") } else { logger.error("Couldn't run integrity check: \(messages.statusMessage).") } // Write call stack. logger.error("Call stack: ") for message in Thread.callStackSymbols { logger.error(" >> \(message)") } logger.error("----") // Write open file handles. let openDescriptors = FSUtils.openFileDescriptors() logger.error("Open file descriptors: ") for (k, v) in openDescriptors { logger.error(" \(k): \(v)") } logger.error("----") SwiftData.corruptionLogsWritten.insert(dbFilename) } } /** * Queries the database. * Returns a live cursor that holds the query statement and database connection. * Instances of this class *must not* leak outside of the connection queue! */ internal func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } if let error = error { return Cursor(err: error) } return LiveSQLiteCursor(statement: statement!, factory: factory) } } /// Helper for queries that return a single integer result. func IntFactory(_ row: SDRow) -> Int { return row[0] as! Int } /// Helper for queries that return a single String result. func StringFactory(_ row: SDRow) -> String { return row[0] as! String } /// Wrapper around a statement for getting data from a row. This provides accessors for subscript indexing /// and a generator for iterating over columns. class SDRow: Sequence { // The sqlite statement this row came from. fileprivate let statement: SQLiteDBStatement // The columns of this database. The indices of these are assumed to match the indices // of the statement. fileprivate let columnNames: [String] fileprivate init(statement: SQLiteDBStatement, columns: [String]) { self.statement = statement self.columnNames = columns } // Return the value at this index in the row fileprivate func getValue(_ index: Int) -> Any? { let i = Int32(index) let type = sqlite3_column_type(statement.pointer, i) var ret: Any? = nil switch type { case SQLITE_NULL, SQLITE_INTEGER: ret = NSNumber(value: sqlite3_column_int64(statement.pointer, i) as Int64) case SQLITE_TEXT: if let text = sqlite3_column_text(statement.pointer, i) { ret = String(cString: text) } case SQLITE_BLOB: let blob = sqlite3_column_blob(statement.pointer, i) if blob != nil { let size = sqlite3_column_bytes(statement.pointer, i) ret = Data(bytes: blob!, count: Int(size)) } case SQLITE_FLOAT: ret = Double(sqlite3_column_double(statement.pointer, i)) default: log.warning("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil") } return ret } // Accessor getting column 'key' in the row subscript(key: Int) -> Any? { return getValue(key) } // Accessor getting a named column in the row. This (currently) depends on // the columns array passed into this Row to find the correct index. subscript(key: String) -> Any? { get { if let index = columnNames.index(of: key) { return getValue(index) } return nil } } // Allow iterating through the row. This is currently broken. func makeIterator() -> AnyIterator<Any> { let nextIndex = 0 return AnyIterator() { // This crashes the compiler. Yay! if (nextIndex < self.columnNames.count) { return nil // self.getValue(nextIndex) } return nil } } } /// Helper for pretty printing SQL (and other custom) error codes. private struct SDError { fileprivate static func errorMessageFromCode(_ errorCode: Int) -> String { switch errorCode { case -1: return "No error" // SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html case 0: return "Successful result" case 1: return "SQL error or missing database" case 2: return "Internal logic error in SQLite" case 3: return "Access permission denied" case 4: return "Callback routine requested an abort" case 5: return "The database file is busy" case 6: return "A table in the database is locked" case 7: return "A malloc() failed" case 8: return "Attempt to write a readonly database" case 9: return "Operation terminated by sqlite3_interrupt()" case 10: return "Some kind of disk I/O error occurred" case 11: return "The database disk image is malformed" case 12: return "Unknown opcode in sqlite3_file_control()" case 13: return "Insertion failed because database is full" case 14: return "Unable to open the database file" case 15: return "Database lock protocol error" case 16: return "Database is empty" case 17: return "The database schema changed" case 18: return "String or BLOB exceeds size limit" case 19: return "Abort due to constraint violation" case 20: return "Data type mismatch" case 21: return "Library used incorrectly" case 22: return "Uses OS features not supported on host" case 23: return "Authorization denied" case 24: return "Auxiliary database format error" case 25: return "2nd parameter to sqlite3_bind out of range" case 26: return "File opened that is not a database file" case 27: return "Notifications from sqlite3_log()" case 28: return "Warnings from sqlite3_log()" case 100: return "sqlite3_step() has another row ready" case 101: return "sqlite3_step() has finished executing" // Custom SwiftData errors // Binding errors case 201: return "Not enough objects to bind provided" case 202: return "Too many objects to bind provided" // Custom connection errors case 301: return "A custom connection is already open" case 302: return "Cannot open a custom connection inside a transaction" case 303: return "Cannot open a custom connection inside a savepoint" case 304: return "A custom connection is not currently open" case 305: return "Cannot close a custom connection inside a transaction" case 306: return "Cannot close a custom connection inside a savepoint" // Index and table errors case 401: return "At least one column name must be provided" case 402: return "Error extracting index names from sqlite_master" case 403: return "Error extracting table names from sqlite_master" // Transaction and savepoint errors case 501: return "Cannot begin a transaction within a savepoint" case 502: return "Cannot begin a transaction within another transaction" // Unknown error default: return "Unknown error" } } } /// Provides access to the result set returned by a database query. /// The entire result set is cached, so this does not retain a reference /// to the statement or the database connection. private class FilledSQLiteCursor<T>: ArrayCursor<T> { fileprivate init(statement: SQLiteDBStatement, factory: (SDRow) -> T) { var status = CursorStatus.Success var statusMessage = "" let data = FilledSQLiteCursor.getValues(statement, factory: factory, status: &status, statusMessage: &statusMessage) super.init(data: data, status: status, statusMessage: statusMessage) } /// Return an array with the set of results and release the statement. fileprivate class func getValues(_ statement: SQLiteDBStatement, factory: (SDRow) -> T, status: inout CursorStatus, statusMessage: inout String) -> [T] { var rows = [T]() var count = 0 status = CursorStatus.Success statusMessage = "Success" var columns = [String]() let columnCount = sqlite3_column_count(statement.pointer) for i in 0..<columnCount { let columnName = String(cString: sqlite3_column_name(statement.pointer, i)) columns.append(columnName) } while true { let sqlStatus = sqlite3_step(statement.pointer) if sqlStatus != SQLITE_ROW { if sqlStatus != SQLITE_DONE { // NOTE: By setting our status to failure here, we'll report our count as zero, // regardless of how far we've read at this point. status = CursorStatus.Failure statusMessage = SDError.errorMessageFromCode(Int(sqlStatus)) } break } count += 1 let row = SDRow(statement: statement, columns: columns) let result = factory(row) rows.append(result) } return rows } } /// Wrapper around a statement to help with iterating through the results. private class LiveSQLiteCursor<T>: Cursor<T> { fileprivate var statement: SQLiteDBStatement! // Function for generating objects of type T from a row. fileprivate let factory: (SDRow) -> T // Status of the previous fetch request. fileprivate var sqlStatus: Int32 = 0 // Number of rows in the database // XXX - When Cursor becomes an interface, this should be a normal property, but right now // we can't override the Cursor getter for count with a stored property. fileprivate var _count: Int = 0 override var count: Int { get { if status != .Success { return 0 } return _count } } fileprivate var position: Int = -1 { didSet { // If we're already there, shortcut out. if (oldValue == position) { return } var stepStart = oldValue // If we're currently somewhere in the list after this position // we'll have to jump back to the start. if (position < oldValue) { sqlite3_reset(self.statement.pointer) stepStart = -1 } // Now step up through the list to the requested position for _ in stepStart..<position { sqlStatus = sqlite3_step(self.statement.pointer) } } } init(statement: SQLiteDBStatement, factory: @escaping (SDRow) -> T) { self.factory = factory self.statement = statement // The only way I know to get a count. Walk through the entire statement to see how many rows there are. var count = 0 self.sqlStatus = sqlite3_step(statement.pointer) while self.sqlStatus != SQLITE_DONE { count += 1 self.sqlStatus = sqlite3_step(statement.pointer) } sqlite3_reset(statement.pointer) self._count = count super.init(status: .Success, msg: "success") } // Helper for finding all the column names in this statement. fileprivate lazy var columns: [String] = { // This untangles all of the columns and values for this row when its created let columnCount = sqlite3_column_count(self.statement.pointer) var columns = [String]() for i: Int32 in 0 ..< columnCount { let columnName = String(cString: sqlite3_column_name(self.statement.pointer, i)) columns.append(columnName) } return columns }() override subscript(index: Int) -> T? { get { if status != .Success { return nil } self.position = index if self.sqlStatus != SQLITE_ROW { return nil } let row = SDRow(statement: statement, columns: self.columns) return self.factory(row) } } override func close() { statement = nil super.close() } }
mpl-2.0
4692648845f81e56b5fd07e796052edb
36.078683
177
0.598885
4.789293
false
false
false
false
exponent/exponent
ios/vendored/sdk43/@stripe/stripe-react-native/ios/CardFormManager.swift
2
1015
import Foundation @objc(ABI43_0_0CardFormManager) class CardFormManager: ABI43_0_0RCTViewManager { override func view() -> UIView! { let cardForm = CardFormView() let stripeSdk = bridge.module(forName: "StripeSdk") as? StripeSdk stripeSdk?.cardFormView = cardForm; return cardForm } override class func requiresMainQueueSetup() -> Bool { return false } @objc func focus(_ abi43_0_0ReactTag: NSNumber) { self.bridge!.uiManager.addUIBlock { (_: ABI43_0_0RCTUIManager?, viewRegistry: [NSNumber: UIView]?) in let view: CardFormView = (viewRegistry![abi43_0_0ReactTag] as? CardFormView)! view.focus() } } @objc func blur(_ abi43_0_0ReactTag: NSNumber) { self.bridge!.uiManager.addUIBlock { (_: ABI43_0_0RCTUIManager?, viewRegistry: [NSNumber: UIView]?) in let view: CardFormView = (viewRegistry![abi43_0_0ReactTag] as? CardFormView)! view.blur() } } }
bsd-3-clause
3e85b935d335d4b5206a134ff457ef92
34
109
0.626601
3.918919
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-399/examples/W4Example_W17/W4Example/Source/Service/FruitService.swift
1
3107
// // FruitService.swift // W4Example // // Created by Charles Augustine on 2/3/17. // Copyright © 2017 Charles. All rights reserved. // import Foundation class FruitService { // MARK: Data Access func fruitNames() -> Array<String> { // Use a map operation to convert the array of dictionaries containing values into an array only containing the // fruit names. return fruitData.map { $0["FruitName"] as? String ?? "Unknown Fruit" } // // This is equivalent code using more conventional procedural style: // var fruitNames = Array<String>() // for fruitValues in fruitData { // if let fruitName = fruitValues["FruitName"] as? String { // fruitNames.append("Fruit Name") // } // else { // fruitNames.append("Unknown Fruit") // } // } // // return fruitNames } func taxonomyValues(forFruitName fruitName: String) -> Array<String> { // Use the filter function to filter the array of fruit values down to the ones with the same name as the // parameter and then use the first function to retrieve the first object in the filtered results. Use the ? // operator to pull the fruit taxonomy values from that first object if it isn't nil and attempt to cast that to // an array of strings. Use the ?? operator to provide an empty array if the first object was nil or the cast // failed (i.e., if anything anythin made the expression turn out as nil). return fruitData.filter({ ($0["FruitName"] as? String) == fruitName }).first?["FruitTaxonomy"] as? Array<String> ?? [] // // This is equivalent code using more conventional procedural style: // var filteredFruitData: Array<Dictionary<String, Any>> // for fruitValues in fruitData { // if fruitValues["FruitName"] == fruitName { // filteredFruitData.append(fruitValues) // } // } // // let result: Array<String> // if filteredFruitData.count > 0 { // let fruitValues = filteredFruitData[0] // if let taxonomyValues = fruitValues["FruitTaxonomy"] as? Array<String> { // result = taxonomyValues // } // else { // result = [] // } // } // else { // result = [] // } // // return result } // MARK: Initialization // This init method is marked as private so that nothing can instantiate FruitService directly. Instead using the // shared static property to access a shared "singleton" instance. private init() { // Retrieve the path to the fruits.plist from the main bundle. This is possible because the file is part of the // application resources. If it was not we would have to retrieve the path to the file in another manner. let path = Bundle.main.path(forResource: "fruits", ofType: "plist")! // Use the contentsOfFile: initializer of NSArray to read the plist. The same initializer exists on the // NSDictionary type. You have to use the type that corresponds to the root element of the plist being read. fruitData = NSArray(contentsOfFile: path) as! Array<Dictionary<String, Any>> } // MARK: Properties (Private) private let fruitData: Array<Dictionary<String, Any>> // MARK: Propertis (Static Constant) static let shared = FruitService() }
gpl-3.0
63f00a0327f6ec2e5f479854c40f4b29
35.541176
120
0.699936
3.549714
false
false
false
false
seaburg/PHDiff
PHDiff/PHDiff/Sources/PaulHeckelDifference.swift
1
6097
// // PaulHeckelDifference.swift // PaulHeckelDifference // // Created by Andre Alves on 10/13/16. // Copyright © 2016 Andre Alves. All rights reserved. // import Foundation internal final class PaulHeckelDifference<T: Diffable> { private var newArray: [T] = [] private var oldArray: [T] = [] // OA private var oldReferencesTable: [Reference] = [] // NA private var newReferencesTable: [Reference] = [] func difference(from fromArray: [T], to toArray: [T]) -> [DiffStep<T>] { newArray = toArray oldArray = fromArray calculateReferencesTables() let differenceSteps = calculateDifferenceSteps() cleanUp() return differenceSteps } private func calculateReferencesTables() { // First and second pass fillSymbolsToReferenceTables() // Third pass bindAnchorReferences() // Fourth pass bindSameReferencesAfterAnchors() // Fifth pass bindSameReferencesBeforeAnchors() } private func fillSymbolsToReferenceTables() { var table: [T.HashType: Reference.Symbol] = [:] for newObject in newArray { let identifier = newObject.diffIdentifier let symbol = table[identifier] ?? Reference.Symbol() symbol.newCounter += 1 table[identifier] = symbol newReferencesTable.append(.Pointer(symbol)) } for (oldIndex, oldObject) in oldArray.enumerated() { let identifier = oldObject.diffIdentifier let symbol = table[identifier] ?? Reference.Symbol() symbol.oldCounter += 1 symbol.oldIndex = oldIndex table[identifier] = symbol oldReferencesTable.append(.Pointer(symbol)) } } private func bindAnchorReferences() { for (index, reference) in newReferencesTable.enumerated() { if let symbol = reference.symbol, symbol.isAnchor { bindReferences(oldIndex: symbol.oldIndex, newIndex: index) } } } private func bindSameReferencesAfterAnchors() { for newIndex in stride(from: 0, to: newReferencesTable.count - 1, by: 1) { if let oldIndex = newReferencesTable[newIndex].index { if hasSameSymbolReferencesAt(newIndex: newIndex + 1, oldIndex: oldIndex + 1) { bindReferences(oldIndex: oldIndex + 1, newIndex: newIndex + 1) } } } } private func bindSameReferencesBeforeAnchors() { for newIndex in stride(from: newReferencesTable.count - 1, to: 0, by: -1) { if let oldIndex = newReferencesTable[newIndex].index { if hasSameSymbolReferencesAt(newIndex: newIndex - 1, oldIndex: oldIndex - 1) { bindReferences(oldIndex: oldIndex - 1, newIndex: newIndex - 1) } } } } private func hasSameSymbolReferencesAt(newIndex: Int, oldIndex: Int) -> Bool { guard let newSymbol = referenceSymbol(at: newIndex, from: newReferencesTable) else { return false } guard let oldSymbol = referenceSymbol(at: oldIndex, from: oldReferencesTable) else { return false } return newSymbol === oldSymbol } private func bindReferences(oldIndex: Int, newIndex: Int) { newReferencesTable[newIndex] = .Index(oldIndex) oldReferencesTable[oldIndex] = .Index(newIndex) } private func referenceSymbol(at index: Int, from references: [Reference]) -> Reference.Symbol? { if index < 0 || index >= references.count { return nil } return references[index].symbol } private func calculateDifferenceSteps() -> [DiffStep<T>] { var steps: [DiffStep<T>] = [] var deleteOffsets = Array(repeating: 0, count: oldReferencesTable.count) var runningOffset = 0 // Find deletions and incremement offset for each delete for (index, reference) in oldReferencesTable.enumerated() { deleteOffsets[index] = runningOffset if reference.symbol != nil { steps.append(.delete(value: oldArray[index], index: index)) runningOffset -= 1 } } runningOffset = 0 // Find inserts, moves and updates for (newIndex, reference) in newReferencesTable.enumerated() { if let oldIndex = reference.index { // Checks for the current offset, if matches means that this move is not needed let expectedOldIndex = oldIndex + runningOffset + deleteOffsets[oldIndex] if expectedOldIndex != newIndex { steps.append(.move(value: newArray[newIndex], fromIndex: oldIndex, toIndex: newIndex)) } // Check if this object has changed if newArray[newIndex] != oldArray[oldIndex] { steps.append(.update(value: newArray[newIndex], index: oldIndex)) } } else { steps.append(.insert(value: newArray[newIndex], index: newIndex)) runningOffset += 1 } } return steps } func cleanUp() { newArray = [] oldArray = [] newReferencesTable = [] oldReferencesTable = [] } } /// The `Reference` is used during diff info setup. It can points to the symbol table or array index. private enum Reference { fileprivate final class Symbol { var oldCounter = 0 // OC var newCounter = 0 // NC var oldIndex = 0 // OLNO var isAnchor: Bool { return (newCounter == 1 && oldCounter == 1) } } case Pointer(Symbol) case Index(Int) var symbol: Symbol? { switch self { case let .Pointer(symbol): return symbol default: return nil } } var index: Int? { switch self { case let .Index(index): return index default: return nil } } }
mit
967d53a74b94ca8db23c15a9ca8ecb84
31.425532
106
0.588911
4.743969
false
false
false
false
weby/Stencil
Tests/Nodes/NodeSpec.swift
1
1493
import Spectre import Stencil class ErrorNode : NodeType { func render(context: Context) throws -> String { throw TemplateSyntaxError("Custom Error") } } func testNode() { describe("Node") { let context = Context(dictionary: [ "name": "Kyle", "age": 27, "items": [1, 2, 3], ]) $0.describe("TextNode") { $0.it("renders the given text") { let node = TextNode(text: "Hello World") try expect(try node.render(context)) == "Hello World" } } $0.describe("VariableNode") { $0.it("resolves and renders the variable") { let node = VariableNode(variable: Variable("name")) try expect(try node.render(context)) == "Kyle" } $0.it("resolves and renders a non string variable") { let node = VariableNode(variable: Variable("age")) try expect(try node.render(context)) == "27" } } $0.describe("rendering nodes") { $0.it("renders the nodes") { let nodes: [NodeType] = [ TextNode(text:"Hello "), VariableNode(variable: "name"), ] try expect(try renderNodes(nodes, context)) == "Hello Kyle" } $0.it("correctly throws a nodes failure") { let nodes: [NodeType] = [ TextNode(text:"Hello "), VariableNode(variable: "name"), ErrorNode(), ] try expect(try renderNodes(nodes, context)).toThrow(TemplateSyntaxError("Custom Error")) } } } }
bsd-2-clause
265b8289e3100814c334db15bf1cbc7f
23.883333
96
0.563965
3.928947
false
false
false
false
UIKonf/uikonf-app
UIKonfApp/UIKonfApp/SimpleLookup.swift
1
1808
// // GenericIndex.swift // UIKonfApp // // Created by Maxim Zaks on 14.03.15. // Copyright (c) 2015 Maxim Zaks. All rights reserved. // import Foundation import Entitas class SimpleLookup<T : Hashable> : GroupObserver { var index : [T:[Entity]] let indexKeyBuilder : (entity : Entity, removedComponent : Component?) -> T weak var group : Group? init(group : Group, indexKeyBuilder : (entity : Entity, removedComponent : Component?) -> T) { index = [:] self.indexKeyBuilder = indexKeyBuilder group.addObserver(self) for e in group { entityAdded(e) } self.group = group } subscript(key: T) -> [Entity] { if let result = index[key]{ return result } return [] } func entityAdded(entity : Entity) { let key = indexKeyBuilder(entity: entity, removedComponent: nil) if var entities = index[key] { // we could theoreticly have duplicate entries // this will be solved when switching to Set in 8.3 entities.append(entity) index[key] = entities } else { index[key] = [entity] } } func entityRemoved(entity : Entity, withRemovedComponent removedComponent : Component) { let key = indexKeyBuilder(entity: entity, removedComponent: removedComponent) if var entities = index[key] { // TODO should be more efficient e.g. switch to Set in 8.3 index[key] = entities.filter({$0 != entity}) } } func disconnec(){ group?.removeObserver(self) } } extension SimpleLookup : SequenceType { func generate() -> DictionaryGenerator<T, [Entity]> { return index.generate() } }
mit
5a764d9d10d8e34bf8c7b759805e3767
26.815385
98
0.582965
4.214452
false
false
false
false
xGoPox/vapor-authentification
Sources/App/Models/UserCredentials.swift
1
949
// // UserCredentials.swift // vapor-authentification // // Created by Clement Yerochewski on 1/13/17. // // import Auth import BCrypt import Node import Vapor typealias HashedPassword = (secret: User.Secret, salt: User.Salt) struct UserCredentials: Credentials { var password: String var email: String private let hash: HashProtocol init(email: String, password: String, hash: HashProtocol) { self.email = email self.hash = hash self.password = password } func hashPassword(using salt: User.Salt = BCryptSalt().string) throws -> HashedPassword { return (try hash.make((password) + salt), salt) } } struct AuthenticatedUserCredentials: Credentials { let id: String /* init(node: Node) throws { guard let id: String = try node.extract(User.Keys.id) else { throw VaporAuthError.couldNotLogIn } self.id = id }*/ }
mit
adf0083d255da06d2a71c16c1dcd5e79
19.630435
93
0.641728
3.937759
false
false
false
false
lucasleelz/LemoniOS
LemoniOS/Classes/Sessions/Views/SessionsCell.swift
2
1066
// // SessionsCell.swift // LemoniOS // // Created by lucas on 16/7/3. // Copyright © 2016年 三只小猪. All rights reserved. // import UIKit class SessionsCell: UITableViewCell { static let identifier = "SessionsCell" @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! private var session: Session? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func configure(withSession session: Session) { self.session = session if let avatarURLString = session.avatarURLString { self.avatarImageView.image = UIImage(named: avatarURLString) } self.nameLabel.text = session.name self.contentLabel.text = session.content self.timeLabel.text = "\(session.createdTime)" } }
mit
0838a3b10460ade436ce9380446af310
24.119048
72
0.653081
4.547414
false
false
false
false
fakerabbit/memoria
Memoria/RoundTextView.swift
1
1505
// // RoundTextView.swift // Memoria // // Created by Mirko Justiniano on 3/2/17. // Copyright © 2017 MM. All rights reserved. // import Foundation import UIKit let kRoundTextInset: CGFloat = 5 class RoundTextView: UITextView { override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) } convenience init(frame: CGRect) { self.init(frame: frame, textContainer: nil) self.backgroundColor = UIColor.clear self.textColor = Utils.textColor() self.font = Utils.mainFont() self.isScrollEnabled = false self.textAlignment = .center self.isUserInteractionEnabled = false self.textContainerInset = UIEdgeInsets(top: kRoundTextInset, left: kRoundTextInset, bottom: kRoundTextInset, right: kRoundTextInset) self.layer.masksToBounds = false; self.layer.borderWidth = 1 self.layer.borderColor = Utils.textColor().cgColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.frame.size.width/2; var inset = round(self.contentSize.height/(self.font?.lineHeight)!) //debugPrint("inset: \(inset)") inset /= 2 self.textContainerInset = UIEdgeInsets(top: self.frame.size.height/inset, left: 0, bottom: 0, right: 0) } }
mit
b5dc1e14b0a36176ee6b798c0f338c19
31.695652
140
0.663564
4.297143
false
false
false
false
JLCdeSwift/DangTangDemo
DanTangdemo/Classes/Main/Controller/LCNavigationController.swift
1
2486
// // LCNavigationController.swift // DanTangdemo // // Created by 冀柳冲 on 2017/7/5. // Copyright © 2017年 sunny冲哥. All rights reserved. // import UIKit import SVProgressHUD class LCNavigationController: UINavigationController { override class func initialize(){ super.initialize() let navBar = UINavigationBar.appearance() navBar.barTintColor = LCGlobalRedColor() navBar.tintColor = UIColor.white navBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 20)] } /// 统一定制左上角返回按钮 /// /// - Parameters: /// - viewController: 即将入栈的控制器 /// - animated: 是否显示动画 override func pushViewController(_ viewController: UIViewController, animated: Bool) { /// 这时push进来的控制器viewController,不是第一个子控制器(不是根控制器) if viewControllers.count > 0 { // push 后隐藏 tabbar viewController.hidesBottomBarWhenPushed = true viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "checkUserType_backward_9x15_"), style: .plain, target: self, action: #selector(navigationBackClick)) } super.pushViewController(viewController, animated: animated) } /// 返回按钮 func navigationBackClick() { if SVProgressHUD.isVisible() { SVProgressHUD.dismiss() } //isNetworkActivityIndicatorVisible 指示器的联网动画(状态栏左侧转动的) if UIApplication.shared.isNetworkActivityIndicatorVisible { UIApplication.shared.isNetworkActivityIndicatorVisible = false } popViewController(animated: true) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
bb61588de0edc4aa5572394a176ab0d3
31.746479
201
0.674839
5.043384
false
false
false
false
raymondCaptain/RefinedViewControllerDemo
ArrayDataSource.swift
1
1275
// // ArrayDataSource.swift // RefinedViewControllerDemo // // Created by zhiweimiao on 2017/8/25. // Copyright © 2017年 zhiweimiao. All rights reserved. // import Foundation import UIKit class ArrayDataSource<Element, Cell: UITableViewCell>: NSObject, UITableViewDataSource where Cell: ConfigureCell, Cell.E == Element { typealias E = Element var items: [E]! var cellIdentifier = "default" override init() { super.init() } // MARK: - UITableViewDataSource // 泛型类延展里的方法不会暴露给OC,所以这些协议方法只能写在这里,而不能单独写在 extension 里 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let aCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? Cell let cell = aCell ?? Cell(style: .default, reuseIdentifier: cellIdentifier) cell.configure(for: item(atIndexPath: indexPath)) return cell } } extension ArrayDataSource { func item(atIndexPath indexPath: IndexPath) -> E { return items[indexPath.row] } }
mit
55f771fc259c40b96342ef56e1b52601
26.813953
133
0.682274
4.397059
false
false
false
false
ianthetechie/SwiftCGI-Demo
SwiftCGI Demo/AppDelegate.swift
1
3371
// // AppDelegate.swift // // Copyright (c) 2014, Ian Wagner // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that thefollowing conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // import Cocoa import SwiftCGI @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { // UI junk. Because Cocoa app... let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength) var server: FCGIServer! func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application // TODO: Clean up this kludge // NOTE: You should change the root path to match your server configuration let rootRouter = Router(path: "cgi", handleWildcardChildren: false, withHandler: rootHandler) let blogRouter = Router(path: "blog", handleWildcardChildren: true, withHandler: blogRootHandler) rootRouter.attachRouter(blogRouter) #if EMBED_SERVER server = FCGIServer(port: 9000, requestRouter: rootRouter, useEmbeddedHTTPServer: true) #else server = FCGIServer(port: 9000, requestRouter: rootRouter, useEmbeddedHTTPServer: false) #endif // Set up middleware server.registerMiddlewareHandler(sessionMiddlewareHandler) do { try server.start() print("Started SwiftCGI server on port \(server.port)") } catch { print("Failed to start SwiftCGI server") exit(1) } // Set ourselves up in the status bar (top of the screen) statusItem.title = "SwiftCGI" // TODO: Use a logo let menu = NSMenu() menu.addItemWithTitle("Kill Server", action: Selector("killServer:"), keyEquivalent: "") statusItem.menu = menu } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func killServer(sender: AnyObject!) { NSApplication.sharedApplication().terminate(sender) } }
bsd-2-clause
48dd52dff06cff9588bac9889569ef50
38.197674
105
0.690596
4.906841
false
false
false
false
mibaldi/ChildBeaconApp
ChildBeaconProject/Models/Beacon.swift
1
2266
// // KidBeacon // Creado por Mikel Balduciel Diaz, Eduardo González de la Huebra Sánchez y David Jiménez Guinaldo en 2016 // para el Club Universitario de Innovación de la Universidad Pontificia de Salamanca. // Copyright © 2016. Todos los derecho reservados. // import Foundation import CoreLocation class Beacon : NSObject{ var beaconId = Int64() var beaconGroupId = Int64() var name = String () var minor = String() var major = String() var distance = Float() var beaconGroupUUID = String() dynamic var lastSeenBeacon: CLBeacon? override var hashValue: Int { get { return beaconId.hashValue << 15 + name.hashValue } } static func addBeacon(name: String,minor: String,major: String,group: Int64,groupUUID:String) throws -> Void{ let beacon = Beacon() beacon.name = name beacon.beaconGroupId = group beacon.minor = minor beacon.major = major beacon.beaconGroupUUID = groupUUID do{ try BeaconDataHelper.insert(beacon) } catch{ throw DataAccessError.Insert_Error } } static func updateBeacon(id : Int64, name: String,minor: String,major: String) throws -> Void{ let beacon = Beacon() beacon.beaconId = id beacon.name = name beacon.minor = minor beacon.major = major do{ try BeaconDataHelper.updateBeacon(beacon) } catch{ throw DataAccessError.Insert_Error } } static func deleteBeacon(id : Int64) throws -> Void{ let beacon = Beacon() beacon.beaconId = id do{ try BeaconDataHelper.delete(beacon) } catch{ throw DataAccessError.Delete_Error } } } func ==(item: Beacon, beacon: CLBeacon) -> Bool { return ((beacon.proximityUUID.UUIDString == item.beaconGroupUUID) && (Int(beacon.major) == Int(item.major)) && (Int(beacon.minor) == Int(item.minor))) } func ==(lhs: Beacon, rhs: Beacon) -> Bool { return (lhs.beaconId == rhs.beaconId) && (lhs.name == rhs.name) && (Int(lhs.minor) == Int(rhs.minor)) && (Int(lhs.major) == Int(rhs.major)) }
apache-2.0
66e9779d91de615f66b9b7510762bdb6
28.75
113
0.598408
4.008865
false
false
false
false
yuanhoujun/firefox-ios
Client/Frontend/Browser/SwipeAnimator.swift
10
5588
/* 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 struct SwipeAnimationParameters { let totalRotationInDegrees: Double let deleteThreshold: CGFloat let totalScale: CGFloat let totalAlpha: CGFloat let minExitVelocity: CGFloat let recenterAnimationDuration: NSTimeInterval } private let DefaultParameters = SwipeAnimationParameters( totalRotationInDegrees: 10, deleteThreshold: 60, totalScale: 0.9, totalAlpha: 0, minExitVelocity: 800, recenterAnimationDuration: 0.15) protocol SwipeAnimatorDelegate: class { func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) } class SwipeAnimator: NSObject { weak var delegate: SwipeAnimatorDelegate? weak var container: UIView! weak var animatingView: UIView! private var prevOffset: CGPoint! private let params: SwipeAnimationParameters var containerCenter: CGPoint { return CGPoint(x: CGRectGetWidth(container.frame) / 2, y: CGRectGetHeight(container.frame) / 2) } init(animatingView: UIView, container: UIView, params: SwipeAnimationParameters = DefaultParameters) { self.animatingView = animatingView self.container = container self.params = params super.init() let panGesture = UIPanGestureRecognizer(target: self, action: Selector("SELdidPan:")) container.addGestureRecognizer(panGesture) panGesture.delegate = self } } //MARK: Private Helpers extension SwipeAnimator { private func animateBackToCenter() { UIView.animateWithDuration(params.recenterAnimationDuration, animations: { self.animatingView.transform = CGAffineTransformIdentity self.animatingView.alpha = 1 }) } private func animateAwayWithVelocity(velocity: CGPoint, speed: CGFloat) { // Calculate the edge to calculate distance from let translation = velocity.x >= 0 ? CGRectGetWidth(container.frame) : -CGRectGetWidth(container.frame) let timeStep = NSTimeInterval(abs(translation) / speed) UIView.animateWithDuration(timeStep, animations: { self.animatingView.transform = self.transformForTranslation(translation) self.animatingView.alpha = self.alphaForDistanceFromCenter(abs(translation)) }, completion: { finished in if finished { self.animatingView.alpha = 0 self.delegate?.swipeAnimator(self, viewDidExitContainerBounds: self.animatingView) } }) } private func transformForTranslation(translation: CGFloat) -> CGAffineTransform { let halfWidth = container.frame.size.width / 2 let totalRotationInRadians = CGFloat(params.totalRotationInDegrees / 180.0 * M_PI) // Determine rotation / scaling amounts by the distance to the edge var rotation = (translation / halfWidth) * totalRotationInRadians var scale = 1 - (abs(translation) / halfWidth) * (1 - params.totalScale) let rotationTransform = CGAffineTransformMakeRotation(rotation) let scaleTransform = CGAffineTransformMakeScale(scale, scale) let translateTransform = CGAffineTransformMakeTranslation(translation, 0) return CGAffineTransformConcat(CGAffineTransformConcat(rotationTransform, scaleTransform), translateTransform) } private func alphaForDistanceFromCenter(distance: CGFloat) -> CGFloat { let halfWidth = container.frame.size.width / 2 return 1 - (distance / halfWidth) * (1 - params.totalAlpha) } } //MARK: Selectors extension SwipeAnimator { @objc func SELdidPan(recognizer: UIPanGestureRecognizer!) { let translation = recognizer.translationInView(container) switch (recognizer.state) { case .Began: prevOffset = containerCenter case .Changed: animatingView.transform = transformForTranslation(translation.x) animatingView.alpha = alphaForDistanceFromCenter(abs(translation.x)) prevOffset = CGPoint(x: translation.x, y: 0) case .Cancelled: animateBackToCenter() case .Ended: let velocity = recognizer.velocityInView(container) // Bounce back if the velocity is too low or if we have not reached the treshold yet let speed = max(abs(velocity.x), params.minExitVelocity) if (speed < params.minExitVelocity || abs(prevOffset.x) < params.deleteThreshold) { animateBackToCenter() } else { animateAwayWithVelocity(velocity, speed: speed) } default: break } } func close(#right: Bool) { let direction = CGFloat(right ? -1 : 1) animateAwayWithVelocity(CGPoint(x: -direction * params.minExitVelocity, y: 0), speed: direction * params.minExitVelocity) } @objc func SELcloseWithoutGesture() -> Bool { close(right: false) return true } } extension SwipeAnimator: UIGestureRecognizerDelegate { @objc func gestureRecognizerShouldBegin(recognizer: UIGestureRecognizer) -> Bool { let cellView = recognizer.view as UIView! let panGesture = recognizer as! UIPanGestureRecognizer let translation = panGesture.translationInView(cellView.superview!) return fabs(translation.x) > fabs(translation.y) } }
mpl-2.0
05fed8af397b6acb5eb630d771166268
37.8125
129
0.685934
5.281664
false
false
false
false
KlubJagiellonski/pola-ios
BuyPolish/Pola/UI/ProductSearch/ScanCode/ProductCard/MainProggressView.swift
1
2040
import UIKit final class MainProggressView: UIView { private let filledProgressView = UIView() private let percentLabel = UILabel() private let titleMargin = CGFloat(10) private let barHeight = CGFloat(20) var progress = CGFloat(0) { didSet { let points = Int(progress * 100) let text = R.string.localizable.progressPoints(points) percentLabel.text = text percentLabel.sizeToFit() accessibilityValue = R.string.localizable.accessibilityMainProgressValue(text) invalidateIntrinsicContentSize() setNeedsLayout() } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = Theme.lightBackgroundColor filledProgressView.backgroundColor = Theme.actionColor addSubview(filledProgressView) percentLabel.font = Theme.captionFont percentLabel.textColor = Theme.clearColor addSubview(percentLabel) isAccessibilityElement = true accessibilityTraits = .staticText } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { var rect = CGRect.zero rect.size.width = bounds.width * progress rect.size.height = bounds.height filledProgressView.frame = rect rect = percentLabel.frame rect.origin.x = bounds.width - titleMargin - percentLabel.frame.width rect.origin.y = (bounds.height - percentLabel.bounds.height) / 2 percentLabel.frame = rect } override var intrinsicContentSize: CGSize { return CGSize( width: percentLabel.intrinsicContentSize.width + titleMargin, height: barHeight ) } override func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize( width: percentLabel.sizeThatFits(size).width + titleMargin, height: barHeight ) } }
gpl-2.0
7c0364ae00f4278e747e276af0ed590d
29.909091
90
0.640686
5.138539
false
false
false
false
VadimPavlov/Swifty
Sources/Swifty/ios/Notifications/Application.swift
1
921
// // Application.swift // Swifty // // Created by Vadim Pavlov on 10/31/17. // Copyright © 2017 Vadym Pavlov. All rights reserved. // import UIKit public enum Application { // State public static let WillEnterForeground = NotificationDescriptor(name: UIApplication.willEnterForegroundNotification, convert: NoUserInfo.init) public static let DidEnterBackground = NotificationDescriptor(name: UIApplication.didEnterBackgroundNotification, convert: NoUserInfo.init) public static let WillTerminate = NotificationDescriptor(name: UIApplication.willTerminateNotification, convert: NoUserInfo.init) // Focus public static let WillResignActive = NotificationDescriptor(name: UIApplication.willResignActiveNotification, convert: NoUserInfo.init) public static let DidBecomeActive = NotificationDescriptor(name: UIApplication.didBecomeActiveNotification, convert: NoUserInfo.init) }
mit
7a0616d58923eb9fb44b5c3783a6841f
42.809524
145
0.793478
5.082873
false
false
false
false
iDevelopper/PBRevealViewController
ExampleWithSwiftLibrary/ExampleWithSwiftLibrary/AnimationControllerForPush.swift
1
1418
// // AnimationControllerForPush.swift // ExampleWithSwiftLibrary // // Created by Patrick BODET on 19/08/2017. // Copyright © 2016 iDevelopper. All rights reserved. // import UIKit class AnimationControllerForPush: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.8 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) let fromView = fromViewController?.view /* UIView.transition(with: fromView!, duration: transitionDuration(using: transitionContext), options: [.transitionCurlUp, .showHideTransitionViews] , animations: { fromView?.isHidden = true }) { (finished) in fromView?.isHidden = false transitionContext.completeTransition(finished) } */ UIView.transition(with: transitionContext.containerView, duration: transitionDuration(using: transitionContext), options: [.transitionCurlUp, .showHideTransitionViews] , animations: { fromView?.isHidden = true }) { (finished) in fromView?.isHidden = false transitionContext.completeTransition(finished) } } }
mit
5727f923a827c353f11063b6b162b1d0
38.361111
191
0.703599
5.760163
false
false
false
false
samodom/CoreDataSwagger
CoreDataSwagger/NSManagedObjectExtensions.swift
1
2576
// // NSManagedObjectExtensions.swift // CoreDataSwagger // // Created by Sam Odom on 11/18/14. // Copyright (c) 2014 Swagger Soft. All rights reserved. // import CoreData public extension NSManagedObject { /** Class method for retrieving the associated entity description from a stack's managed object model. @param inStack `CoreDataStack` with the model to search @return Entity description associated with the custom managed object subclass, if found. Nil is returned if an entity is not found or if the base class is used. */ public class func entity(inStack stack: CoreDataStack) -> NSEntityDescription? { if self.isMemberOfClass(NSManagedObject) { return nil } for entity in stack.model.entities as [NSEntityDescription] { if entity.managedObjectClassName == NSStringFromClass(self) { return entity } } return nil } /** Class method for retrieving the associated entity's property descriptions from a stack's managed object model. @param inStack `CoreDataStack` with the model to search @return Property descriptions for the entity associated with the custom managed object subclass, if found. Nil is returned if an entity is not found or if the base class is used. */ public class func properties(inStack stack: CoreDataStack) -> [NSPropertyDescription]? { if self.isMemberOfClass(NSManagedObject) { return nil } let entity = self.entity(inStack: stack) if entity == nil { return nil } let properties = entity!.properties return properties as? [NSPropertyDescription] } /** Class method for retrieving the associated entity's property descriptions by name from a stack's managed object model. @param inStack `CoreDataStack` with the model to search @return Property descriptions for the entity associated with the custom managed object subclass, if found. Nil is returned if an entity is not found or if the base class is used. */ public class func propertiesByName(inStack stack: CoreDataStack) -> [String:NSPropertyDescription]? { if self.isMemberOfClass(NSManagedObject) { return nil } let entity = self.entity(inStack: stack) if entity == nil { return nil } let properties = entity!.propertiesByName return properties as? [String:NSPropertyDescription] } }
mit
4e0dc7fdf6bce23768f056c125536bbf
35.8
191
0.663043
5.10099
false
false
false
false
khizkhiz/swift
test/SILGen/writeback_conflict_diagnostics.swift
2
4944
// RUN: %target-swift-frontend %s -o /dev/null -emit-silgen -verify struct MutatorStruct { mutating func f(x : inout MutatorStruct) {} } var global_property : MutatorStruct { get {} set {} } var global_int_property : Int { get { return 42 } set {} } struct StructWithProperty { var computed_int : Int { get { return 42 } set {} } var stored_int = 0 var computed_struct : MutatorStruct { get {} set {} } } var global_struct_property : StructWithProperty var c_global_struct_property : StructWithProperty { get {} set {} } func testInOutAlias() { var x = 42 swap(&x, // expected-note {{previous aliasing argument}} &x) // expected-error {{inout arguments are not allowed to alias each other}} swap(&global_struct_property, // expected-note {{previous aliasing argument}} &global_struct_property) // expected-error {{inout arguments are not allowed to alias each other}} } func testWriteback() { var a = StructWithProperty() a.computed_struct . // expected-note {{concurrent writeback occurred here}} f(&a.computed_struct) // expected-error {{inout writeback to computed property 'computed_struct' occurs in multiple arguments to call, introducing invalid aliasing}} swap(&global_struct_property.stored_int, &global_struct_property.stored_int) // ok swap(&global_struct_property.computed_int, // expected-note {{concurrent writeback occurred here}} &global_struct_property.computed_int) // expected-error {{inout writeback to computed property 'computed_int' occurs in multiple arguments to call, introducing invalid aliasing}} swap(&a.computed_int, // expected-note {{concurrent writeback occurred here}} &a.computed_int) // expected-error {{inout writeback to computed property 'computed_int' occurs in multiple arguments to call, introducing invalid aliasing}} global_property.f(&global_property) // expected-error {{inout writeback to computed property 'global_property' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}} a.computed_struct.f(&a.computed_struct) // expected-error {{inout writeback to computed property 'computed_struct' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}} } func testComputedStructWithProperty() { swap(&c_global_struct_property.stored_int, &c_global_struct_property.stored_int) // expected-error {{inout writeback to computed property 'c_global_struct_property' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}} var c_local_struct_property : StructWithProperty { get {} set {} } swap(&c_local_struct_property.stored_int, &c_local_struct_property.stored_int) // expected-error {{inout writeback to computed property 'c_local_struct_property' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}} swap(&c_local_struct_property.stored_int, &c_global_struct_property.stored_int) // ok } var global_array : [[Int]] func testMultiArray(i : Int, j : Int, array : [[Int]]) { var array = array swap(&array[i][j], &array[i][i]) swap(&array[0][j], &array[0][i]) swap(&global_array[0][j], &global_array[0][i]) // TODO: This is obviously the same writeback problem, but isn't detectable // with the current level of sophistication in SILGen. swap(&array[1+0][j], &array[1+0][i]) swap(&global_array[0][j], &array[j][i]) // ok } struct ArrayWithoutAddressors<T> { subscript(i: Int) -> T { get { return value } set {} } var value: T } var global_array_without_addressors: ArrayWithoutAddressors<ArrayWithoutAddressors<Int>> func testMultiArrayWithoutAddressors( i: Int, j: Int, array: ArrayWithoutAddressors<ArrayWithoutAddressors<Int>> ) { var array = array swap(&array[i][j], // expected-note {{concurrent writeback occurred here}} &array[i][i]) // expected-error {{inout writeback through subscript occurs in multiple arguments to call, introducing invalid aliasing}} swap(&array[0][j], // expected-note {{concurrent writeback occurred here}} &array[0][i]) // expected-error {{inout writeback through subscript occurs in multiple arguments to call, introducing invalid aliasing}} swap(&global_array_without_addressors[0][j], // expected-note {{concurrent writeback occurred here}} &global_array_without_addressors[0][i]) // expected-error {{inout writeback through subscript occurs in multiple arguments to call, introducing invalid aliasing}} // TODO: This is obviously the same writeback problem, but isn't detectable // with the current level of sophistication in SILGen. swap(&array[1+0][j], &array[1+0][i]) swap(&global_array_without_addressors[0][j], &array[j][i]) // ok }
apache-2.0
7c891ebe30f98e4e7584fd280feab519
42.752212
290
0.713794
3.902131
false
false
false
false
material-foundation/material-automation
Sources/Analytics.swift
1
1535
/* Copyright 2018 the Material Automation 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import PerfectCURL import PerfectLogger class Analytics { static let googleAnalyticsAPI = "http://www.google-analytics.com/collect" class func trackEvent(category: String, action: String, label: String = "0", value: String = "0") { guard let GATrackingID = ProcessInfo.processInfo.environment["GA_TRACKING_ID"] else { return } let data: [String: String] = ["v": "1", "tid": GATrackingID, "cid": "1", "t": "event", "ec": category, "ea": action, "el": label, "ev": value] let body = "\(data.map { return "\($0.0.stringByEncodingURL)=\($0.1.stringByEncodingURL)" }.joined(separator: "&"))" do { let response = try CURLRequest(googleAnalyticsAPI, .postString(body)).perform() LogFile.debug(response.bodyString) } catch { LogFile.error("error: \(error) desc: \(error.localizedDescription)") } } }
apache-2.0
2139c97515a4c659fbd83f5d6535a2a4
32.369565
120
0.684691
4.104278
false
false
false
false
jorjuela33/OperationKit
OperationKit/Operations/URLRequestOperation.swift
1
7865
// // URLRequestOperation.swift // // Copyright © 2016. 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 open class URLRequestOperation: Operation { public typealias ValidationBlock = (URLRequest?, HTTPURLResponse) -> Error? /// the allowed states for the Request public enum State { case initialized case completed case running case suspended } private let acceptableStatusCodes = Array(200..<300) fileprivate var aggregatedErrors: [Error] = [] fileprivate var finishingOperation: BlockOperation! fileprivate let operationQueue = Foundation.OperationQueue() fileprivate let lock = NSLock() fileprivate var _state: State = .initialized fileprivate var validations: [() -> Error?] = [] internal fileprivate(set) var session: URLSession! internal var sessionTask: URLSessionTask! /// the state for the current request public var state: State { get { lock.lock() defer { lock.unlock() } return _state } set { lock.lock() _state = newValue lock.unlock() } } /// the request for this operation open var request: URLRequest? { return sessionTask.originalRequest } /// the response from the host open var response: HTTPURLResponse? { return sessionTask.response as? HTTPURLResponse } // MARK: Initialization internal init(request: URLRequest, configuration: URLSessionConfiguration) { super.init() name = request.url?.absoluteString operationQueue.maxConcurrentOperationCount = 1 operationQueue.isSuspended = true session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) addCondition(ReachabilityCondition(host: request.url!)) finishingOperation = BlockOperation(block: { [unowned self] in self.finish(self.aggregatedErrors) }) operationQueue.addOperation(finishingOperation) } // MARK: Instance methods /// adds a new operation to be executed when /// the current operation is finishing func addSubOperation(_ blockOperation: BlockOperation) { assert(isFinished == false && isCancelled == false) finishingOperation.addDependency(blockOperation) operationQueue.addOperation(blockOperation) } /// agregate a new error in the array of errors func aggregate(_ error: Error) { aggregatedErrors.append(error) } /// Resume the operation. @discardableResult public func resume() -> Self { assert(state == .suspended) state = .running if sessionTask.state == .completed { operationQueue.isSuspended = false } else { sessionTask.resume() } for observer in observers { guard let ob = observer as? OperationStateObserver else { continue } ob.operationDidResume(self) } return self } /// Suspend the operation. /// /// Suspending a task preventing from continuing to /// load data. @discardableResult public func suspend() -> Self { assert(state != .completed) state = .suspended operationQueue.isSuspended = true if sessionTask.state == .running { sessionTask.suspend() } for observer in observers { guard let ob = observer as? OperationStateObserver else { continue } ob.operationDidSuspend(self) } return self } /// Validates the request, using the specified closure. /// /// validationBlock - A closure to validate the request. @discardableResult open func validate(_ validationBlock: @escaping ValidationBlock) -> Self { let _validationBlock: (() -> Error?) = { [unowned self] in guard let response = self.response else { return nil } return validationBlock(self.sessionTask?.originalRequest, response) } validations.append(_validationBlock) return self } /// Validates that the response has a status code in the specified sequence. /// /// acceptableStatusCodes - The range of acceptable status codes. @discardableResult open func validate() -> Self { return validate(acceptableStatusCodes: acceptableStatusCodes) } /// Validates that the response has a status code in the specified sequence. /// /// acceptableStatusCodes - The range of acceptable status codes. @discardableResult open func validate<S: Sequence>(acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate {[unowned self] _, response in return self.validate(acceptableStatusCodes: acceptableStatusCodes, response: response) } } // MARK: Overrided methods override open func execute() { guard state == .initialized else { return } state = .running sessionTask?.resume() } override open func finished(_ errors: [Error]) { state = .completed operationQueue.cancelAllOperations() session.invalidateAndCancel() } // MARK: Private methods fileprivate final func executeValidations() { for validation in validations { guard let error = validation() else { continue } aggregatedErrors.append(error) } } private final func validate<S: Sequence>(acceptableStatusCodes: S, response: HTTPURLResponse) -> Error? where S.Iterator.Element == Int { var error: Error? if !acceptableStatusCodes.contains(response.statusCode) { error = OperationKitError.unacceptableStatusCode(code: response.statusCode) } return error } } extension URLRequestOperation: URLSessionTaskDelegate { // MARK: URLSessionTaskDelegate public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard isCancelled == false else { return } if let error = error { aggregatedErrors.append(error) } for validation in validations { guard let error = validation() else { continue } aggregatedErrors.append(error) } executeValidations() if state == .running { operationQueue.isSuspended = false } } }
mit
62fcf6853a8ba59458b65b3f5da0f835
31.495868
141
0.62767
5.461111
false
false
false
false
ajijoyo/EasyTipView
Example/EasyTipView/ViewController.swift
2
5676
// // ViewController.swift // // Copyright (c) 2015 Teodor Patraş // // 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 EasyTipView class ViewController: UIViewController, EasyTipViewDelegate { @IBOutlet weak var toolbarItem: UIBarButtonItem! @IBOutlet weak var smallContainerView: UIView! @IBOutlet weak var navBarItem: UIBarButtonItem! @IBOutlet weak var buttonA: UIButton! @IBOutlet weak var buttonB: UIButton! @IBOutlet weak var buttonC: UIButton! @IBOutlet weak var buttonD: UIButton! override func viewDidLoad() { super.viewDidLoad() self.configureUI() var preferences = EasyTipView.Preferences() preferences.font = UIFont(name: "Futura-Medium", size: 13) preferences.textColor = UIColor.whiteColor() preferences.bubbleColor = UIColor(hue:0.46, saturation:0.99, brightness:0.6, alpha:1) preferences.arrowPosition = EasyTipView.ArrowPosition.Top EasyTipView.setGlobalPreferences(preferences) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.toolbarItemAction() } func easyTipViewDidDismiss(tipView: EasyTipView) { println("\(tipView) did dismiss!") } @IBAction func barButtonAction(sender: UIBarButtonItem) { EasyTipView.showAnimated(true, forItem: self.navBarItem, withinSuperview: self.navigationController?.view, text: "Tip view for bar button item displayed within the navigation controller's view. Tap to dismiss.", preferences: nil, delegate: self) } @IBAction func toolbarItemAction() { EasyTipView.showAnimated(true, forItem: self.toolbarItem, withinSuperview: nil, text: "EasyTipView is an easy to use tooltip view. Tap the buttons to see other tooltips.", preferences: nil, delegate: nil) } @IBAction func buttonAction(sender : UIButton) { switch sender { case buttonA: var preferences = EasyTipView.Preferences() preferences.bubbleColor = UIColor(hue:0.58, saturation:0.1, brightness:1, alpha:1) preferences.textColor = UIColor.darkGrayColor() preferences.font = UIFont(name: "HelveticaNeue-Regular", size: 10) preferences.textAlignment = NSTextAlignment.Center let view = EasyTipView(text: "Tip view within the green superview. Tap to dismiss.", preferences: preferences, delegate: nil) view.showForView(buttonA, withinSuperview: self.smallContainerView, animated: true) case buttonB: var preferences = EasyTipView.globalPreferences() preferences.textColor = UIColor.whiteColor() preferences.font = UIFont(name: "HelveticaNeue-Light", size: 14) preferences.textAlignment = NSTextAlignment.Justified EasyTipView.showAnimated(true, forView: self.buttonB, withinSuperview: self.navigationController?.view, text: "Tip view inside the navigation controller's view. Tap to dismiss!", preferences: preferences, delegate: nil) case buttonC: var preferences = EasyTipView.globalPreferences() preferences.bubbleColor = buttonC.backgroundColor! EasyTipView.showAnimated(true, forView: buttonC, withinSuperview: self.navigationController?.view, text: "This tip view cannot be presented with the arrow on the top position, so position bottom has been chosen instead. Tap to dismiss.", preferences: preferences, delegate: nil) default: var preferences = EasyTipView.globalPreferences() preferences.arrowPosition = EasyTipView.ArrowPosition.Bottom preferences.font = UIFont.systemFontOfSize(14) preferences.bubbleColor = buttonD.backgroundColor! EasyTipView.showAnimated(true, forView: buttonD, withinSuperview: nil, text: "Tip view within the topmost window. Tap to dismiss.", preferences: preferences, delegate: nil) } } func configureUI () { var color = UIColor(hue:0.46, saturation:0.99, brightness:0.6, alpha:1) buttonA.backgroundColor = UIColor(hue:0.58, saturation:0.1, brightness:1, alpha:1) self.navigationController?.view.tintColor = color self.buttonB.backgroundColor = color self.smallContainerView.backgroundColor = color } }
mit
c22d5954ad035444c9a6b0108481073b
43.685039
290
0.675242
5.145059
false
false
false
false
cihm/swift-2048-master
swift-2048/Models/AuxiliaryModels.swift
3
3005
// // AuxiliaryModels.swift // swift-2048 // // Created by Austin Zheng on 6/5/14. // Copyright (c) 2014 Austin Zheng. All rights reserved. // import Foundation /// An enum representing directions supported by the game model. enum MoveDirection { case Up case Down case Left case Right } /// An enum representing a movement command issued by the view controller as the result of the user swiping. struct MoveCommand { var direction: MoveDirection var completion: (Bool) -> () init(d: MoveDirection, c: (Bool) -> ()) { direction = d completion = c } } /// An enum representing a 'move order'. This is a data structure the game model uses to inform the view controller /// which tiles on the gameboard should be moved and/or combined. enum MoveOrder { case SingleMoveOrder(source: Int, destination: Int, value: Int, wasMerge: Bool) case DoubleMoveOrder(firstSource: Int, secondSource: Int, destination: Int, value: Int) } /// An enum representing either an empty space or a tile upon the board. enum TileObject { case Empty case Tile(value: Int) } /// An enum representing an intermediate result used by the game logic when figuring out how the board should change as /// the result of a move. ActionTokens are transformed into MoveOrders before being sent to the delegate. enum ActionToken { case NoAction(source: Int, value: Int) case Move(source: Int, value: Int) case SingleCombine(source: Int, value: Int) case DoubleCombine(source: Int, second: Int, value: Int) // Get the 'value', regardless of the specific type func getValue() -> Int { switch self { case let .NoAction(_, v): return v case let .Move(_, v): return v case let .SingleCombine(_, v): return v case let .DoubleCombine(_, _, v): return v } } // Get the 'source', regardless of the specific type func getSource() -> Int { switch self { case let .NoAction(s, _): return s case let .Move(s, _): return s case let .SingleCombine(s, _): return s case let .DoubleCombine(s, _, _): return s } } } /// A struct representing a square gameboard. Because this struct uses generics, it could conceivably be used to /// represent state for many other games without modification. struct SquareGameboard<T> { let dimension: Int var boardArray: Array<T> init(dimension d: Int, initialValue: T) { dimension = d boardArray = T[](count:d*d, repeatedValue:initialValue) } subscript(row: Int, col: Int) -> T { get { assert(row >= 0 && row < dimension) assert(col >= 0 && col < dimension) return boardArray[row*dimension + col] } set { assert(row >= 0 && row < dimension) assert(col >= 0 && col < dimension) boardArray[row*dimension + col] = newValue } } // We mark this function as 'mutating' since it changes its 'parent' struct. mutating func setAll(item: T) { for i in 0..dimension { for j in 0..dimension { self[i, j] = item } } } }
mit
41d17357a011af459fa01bd2d187c9c6
28.460784
119
0.668885
3.902597
false
false
false
false
eelcokoelewijn/StepUp
StepUp/Modules/Reminder/ReminderViewModel.swift
1
5522
import Foundation import App protocol ReminderViewOutput: class { func showReminder(_ date: Date) func pop() func timePicker(enabled: Bool) func controlSwitch(on: Bool) func showNoPushMessage() } protocol ReminderViewModel { func setModel(output: ReminderViewOutput) func start() func save(theDate: Date, pushEnabled enabled: Bool) func cancel() func pushTryTo(enabled: Bool, theDate date: Date) } protocol UsesReminderViewModel { var reminderViewModel: ReminderViewModel { get } } class MixinReminderViewModel: ReminderViewModel, UsesNotificationService { let pushStateKey = "PushStateKey" let reminderHourKey = "ReminderHourKey" let reminderMinuteKey = "ReminderMinuteKey" private weak var output: ReminderViewOutput? internal let notificationService: NotificationService init() { notificationService = MixinNotificationService() } func start() { let reminderDate = getReminderDate() let pushState = getPushState() output?.controlSwitch(on: pushState) output?.timePicker(enabled: pushState) enablePushScheduling(withDate: reminderDate, pushEnabled: pushState) output?.showReminder(reminderDate) } func setModel(output: ReminderViewOutput) { self.output = output } func save(theDate date: Date, pushEnabled enabled: Bool) { if enabled { setReminder(withDate: date) } else { cleanDefaults() } } func cancel() { output?.pop() } func pushTryTo(enabled: Bool, theDate date: Date) { storePushState(enabled: enabled) if enabled { enablePushScheduling(withDate: date, pushEnabled: enabled) } else { output?.timePicker(enabled: false) cleanDefaults() } } private func setReminder(withDate date: Date) { let title = "StepUp! Tijd voor je oefeningen" let body = "Het is tijd voor je oefeningen." let todayInterval = date.timeIntervalSinceNow if todayInterval > 0 { notificationService.scheduleLocalNotification(title: title, body: body, at: todayInterval < 60 ? 60 : todayInterval, withIdentifier: "stepup-today", repeats: false) } guard let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: date) else { return } let interval: TimeInterval = tomorrow.timeIntervalSinceNow notificationService.scheduleLocalNotification(title: title, body: body, at: interval, withIdentifier: "stepup-repeating", repeats: true) storeReminder(createReminder(fromDate: date)) } private func storePushState(enabled: Bool) { UserDefaults.standard.set(enabled, forKey: pushStateKey) } private func getPushState() -> Bool { return UserDefaults.standard.bool(forKey: pushStateKey) } private func storeReminder(_ reminder: Reminder) { UserDefaults.standard.set(reminder.hour, forKey: reminderHourKey) UserDefaults.standard.set(reminder.minute, forKey: reminderMinuteKey) } private func getReminderDate() -> Date { let reminder = Reminder(hour: UserDefaults.standard.integer(forKey: reminderHourKey), minute: UserDefaults.standard.integer(forKey: reminderMinuteKey)) guard reminder != Reminder(hour: 0, minute: 0), let date = Calendar.current.date(bySettingHour: reminder.hour, minute: reminder.minute, second: 0, of: Date()) else { return Date() } return date } private func cleanDefaults() { UserDefaults.standard.removeObject(forKey: reminderHourKey) UserDefaults.standard.removeObject(forKey: reminderMinuteKey) UserDefaults.standard.removeObject(forKey: pushStateKey) } private func createReminder(fromDate date: Date) -> Reminder { let componentsSet = Set<Calendar.Component>(arrayLiteral: .hour,.minute) let intervalComponents = Calendar.current.dateComponents(componentsSet, from: date) return Reminder(hour: intervalComponents.hour!, minute: intervalComponents.minute!) } private func enablePushScheduling(withDate date: Date, pushEnabled enabled: Bool) { notificationService.checkNotificationStatus(completion: { [weak self] result in switch result { case .ok: let pushState = self?.getPushState() ?? false self?.output?.timePicker(enabled: true && pushState) self?.save(theDate: date, pushEnabled: enabled) return case .nok: self?.output?.controlSwitch(on: false) self?.output?.timePicker(enabled: false) self?.output?.showNoPushMessage() return } }) } }
mit
205eb65ec4ed97599776b4173120b198
36.060403
102
0.581492
5.194732
false
false
false
false
glock45/swifter
Sources/Swifter/HttpResponse.swift
1
6271
// // HttpResponse.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation public enum SerializationError: Error { case invalidObject case notSupported } public protocol HttpResponseBodyWriter { func write(_ file: String.File) throws func write(_ data: [UInt8]) throws func write(_ data: ArraySlice<UInt8>) throws } public enum HttpResponseBody { case json(Any?) case html(String) case text(String) case data([UInt8]) case custom(Any, (Any) throws -> String) func content() -> (Int, ((HttpResponseBodyWriter) throws -> Void)?) { do { switch self { case .json(let object): switch object { case let array as Array<Any?>: let data = [UInt8](array.asJson().utf8) return (data.count, { try $0.write(data) }) case let dict as Dictionary<String, Any?>: let data = [UInt8](dict.asJson().utf8) return (data.count, { try $0.write(data) }) default: let data = [UInt8]("Serialisation error: Can't convert \(object) to JSON.".utf8) return (data.count, { try $0.write(data) }) } case .text(let body): let data = [UInt8](body.utf8) return (data.count, { try $0.write(data) }) case .html(let body): let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>" let data = [UInt8](serialised.utf8) return (data.count, { try $0.write(data) }) case .data(let body): return (body.count, { try $0.write(body) }) case .custom(let object, let closure): let serialised = try closure(object) let data = [UInt8](serialised.utf8) return (data.count, { try $0.write(data) }) } } catch { let data = [UInt8]("Serialisation error: \(error)".utf8) return (data.count, { try $0.write(data) }) } } } public enum HttpResponse { case switchProtocols([String: String], (Socket) -> Void) case ok(HttpResponseBody), created, accepted case movedPermanently(String) case badRequest(HttpResponseBody?), unauthorized, forbidden, notFound case internalServerError case raw(Int, String, [String:String]?, ((HttpResponseBodyWriter) -> Void)? ) func statusCode() -> Int { switch self { case .switchProtocols(_, _) : return 101 case .ok(_) : return 200 case .created : return 201 case .accepted : return 202 case .movedPermanently : return 301 case .badRequest(_) : return 400 case .unauthorized : return 401 case .forbidden : return 403 case .notFound : return 404 case .internalServerError : return 500 case .raw(let code, _ , _, _) : return code } } func reasonPhrase() -> String { switch self { case .switchProtocols(_, _) : return "Switching Protocols" case .ok(_) : return "OK" case .created : return "Created" case .accepted : return "Accepted" case .movedPermanently : return "Moved Permanently" case .badRequest(_) : return "Bad Request" case .unauthorized : return "Unauthorized" case .forbidden : return "Forbidden" case .notFound : return "Not Found" case .internalServerError : return "Internal Server Error" case .raw(_, let phrase, _, _) : return phrase } } func headers() -> [String: String] { var headers = ["Server" : "Swifter \(HttpServer.VERSION)"] switch self { case .switchProtocols(let switchHeaders, _): for (key, value) in switchHeaders { headers[key] = value } case .ok(let body): switch body { case .text(_) : headers["Content-Type"] = "text/plain" case .json(_) : headers["Content-Type"] = "application/json" case .html(_) : headers["Content-Type"] = "text/html" case .data(_) : headers["Content-Type"] = "application/octet-stream" default:break } case .movedPermanently(let location): headers["Location"] = location case .raw(_, _, let rawHeaders, _): if let rawHeaders = rawHeaders { for (k, v) in rawHeaders { headers.updateValue(v, forKey: k) } } default:break } return headers } func content() -> (length: Int, write: ((HttpResponseBodyWriter) throws -> Void)?) { switch self { case .ok(let body) : return body.content() case .badRequest(let body) : return body?.content() ?? (-1, nil) case .raw(_, _, _, let writer) : return (-1, writer) default : return (-1, nil) } } func socketSession() -> ((Socket) -> Void)? { switch self { case .switchProtocols(_, let handler) : return handler default: return nil } } } /** Makes it possible to compare handler responses with '==', but ignores any associated values. This should generally be what you want. E.g.: let resp = handler(updatedRequest) if resp == .NotFound { print("Client requested not found: \(request.url)") } */ func ==(inLeft: HttpResponse, inRight: HttpResponse) -> Bool { return inLeft.statusCode() == inRight.statusCode() }
bsd-3-clause
750ff76cf3fa9269cf6d1d7a8b237a93
33.640884
100
0.497448
4.644444
false
false
false
false
nathangitter/interactive-animations
InteractiveAnimations/InteractiveAnimations/ViewController.swift
1
12756
// // ViewController.swift // InteractiveAnimations // // Created by Nathan Gitter on 9/4/17. // Copyright © 2017 Nathan Gitter. All rights reserved. // import UIKit import UIKit.UIGestureRecognizerSubclass // MARK: - State private enum State { case closed case open } extension State { var opposite: State { switch self { case .open: return .closed case .closed: return .open } } } // MARK: - View Controller class ViewController: UIViewController { // MARK: - Constants private let popupOffset: CGFloat = 440 // MARK: - Views private lazy var contentImageView: UIImageView = { let imageView = UIImageView() imageView.image = #imageLiteral(resourceName: "content") return imageView }() private lazy var overlayView: UIView = { let view = UIView() view.backgroundColor = .black view.alpha = 0 return view }() private lazy var popupView: UIView = { let view = UIView() view.backgroundColor = .white view.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner] view.layer.shadowColor = UIColor.black.cgColor view.layer.shadowOpacity = 0.1 view.layer.shadowRadius = 10 return view }() private lazy var closedTitleLabel: UILabel = { let label = UILabel() label.text = "Reviews" label.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium) label.textColor = #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 1) label.textAlignment = .center return label }() private lazy var openTitleLabel: UILabel = { let label = UILabel() label.text = "Reviews" label.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.heavy) label.textColor = .black label.textAlignment = .center label.alpha = 0 label.transform = CGAffineTransform(scaleX: 0.65, y: 0.65).concatenating(CGAffineTransform(translationX: 0, y: -15)) return label }() private lazy var reviewsImageView: UIImageView = { let imageView = UIImageView() imageView.image = #imageLiteral(resourceName: "reviews") return imageView }() // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() layout() popupView.addGestureRecognizer(panRecognizer) } override var prefersStatusBarHidden: Bool { return true } // MARK: - Layout private var bottomConstraint = NSLayoutConstraint() private func layout() { contentImageView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(contentImageView) contentImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true contentImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true contentImageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true contentImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true overlayView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(overlayView) overlayView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true overlayView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true overlayView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true overlayView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true popupView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(popupView) popupView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true popupView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomConstraint = popupView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: popupOffset) bottomConstraint.isActive = true popupView.heightAnchor.constraint(equalToConstant: 500).isActive = true closedTitleLabel.translatesAutoresizingMaskIntoConstraints = false popupView.addSubview(closedTitleLabel) closedTitleLabel.leadingAnchor.constraint(equalTo: popupView.leadingAnchor).isActive = true closedTitleLabel.trailingAnchor.constraint(equalTo: popupView.trailingAnchor).isActive = true closedTitleLabel.topAnchor.constraint(equalTo: popupView.topAnchor, constant: 20).isActive = true openTitleLabel.translatesAutoresizingMaskIntoConstraints = false popupView.addSubview(openTitleLabel) openTitleLabel.leadingAnchor.constraint(equalTo: popupView.leadingAnchor).isActive = true openTitleLabel.trailingAnchor.constraint(equalTo: popupView.trailingAnchor).isActive = true openTitleLabel.topAnchor.constraint(equalTo: popupView.topAnchor, constant: 30).isActive = true reviewsImageView.translatesAutoresizingMaskIntoConstraints = false popupView.addSubview(reviewsImageView) reviewsImageView.leadingAnchor.constraint(equalTo: popupView.leadingAnchor).isActive = true reviewsImageView.trailingAnchor.constraint(equalTo: popupView.trailingAnchor).isActive = true reviewsImageView.bottomAnchor.constraint(equalTo: popupView.bottomAnchor).isActive = true reviewsImageView.heightAnchor.constraint(equalToConstant: 428).isActive = true } // MARK: - Animation /// The current state of the animation. This variable is changed only when an animation completes. private var currentState: State = .closed /// All of the currently running animators. private var runningAnimators = [UIViewPropertyAnimator]() /// The progress of each animator. This array is parallel to the `runningAnimators` array. private var animationProgress = [CGFloat]() private lazy var panRecognizer: InstantPanGestureRecognizer = { let recognizer = InstantPanGestureRecognizer() recognizer.addTarget(self, action: #selector(popupViewPanned(recognizer:))) return recognizer }() /// Animates the transition, if the animation is not already running. private func animateTransitionIfNeeded(to state: State, duration: TimeInterval) { // ensure that the animators array is empty (which implies new animations need to be created) guard runningAnimators.isEmpty else { return } // an animator for the transition let transitionAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1, animations: { switch state { case .open: self.bottomConstraint.constant = 0 self.popupView.layer.cornerRadius = 20 self.overlayView.alpha = 0.5 self.closedTitleLabel.transform = CGAffineTransform(scaleX: 1.6, y: 1.6).concatenating(CGAffineTransform(translationX: 0, y: 15)) self.openTitleLabel.transform = .identity case .closed: self.bottomConstraint.constant = self.popupOffset self.popupView.layer.cornerRadius = 0 self.overlayView.alpha = 0 self.closedTitleLabel.transform = .identity self.openTitleLabel.transform = CGAffineTransform(scaleX: 0.65, y: 0.65).concatenating(CGAffineTransform(translationX: 0, y: -15)) } self.view.layoutIfNeeded() }) // the transition completion block transitionAnimator.addCompletion { position in // update the state switch position { case .start: self.currentState = state.opposite case .end: self.currentState = state case .current: () } // manually reset the constraint positions switch self.currentState { case .open: self.bottomConstraint.constant = 0 case .closed: self.bottomConstraint.constant = self.popupOffset } // remove all running animators self.runningAnimators.removeAll() } // an animator for the title that is transitioning into view let inTitleAnimator = UIViewPropertyAnimator(duration: duration, curve: .easeIn, animations: { switch state { case .open: self.openTitleLabel.alpha = 1 case .closed: self.closedTitleLabel.alpha = 1 } }) inTitleAnimator.scrubsLinearly = false // an animator for the title that is transitioning out of view let outTitleAnimator = UIViewPropertyAnimator(duration: duration, curve: .easeOut, animations: { switch state { case .open: self.closedTitleLabel.alpha = 0 case .closed: self.openTitleLabel.alpha = 0 } }) outTitleAnimator.scrubsLinearly = false // start all animators transitionAnimator.startAnimation() inTitleAnimator.startAnimation() outTitleAnimator.startAnimation() // keep track of all running animators runningAnimators.append(transitionAnimator) runningAnimators.append(inTitleAnimator) runningAnimators.append(outTitleAnimator) } @objc private func popupViewPanned(recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: // start the animations animateTransitionIfNeeded(to: currentState.opposite, duration: 1) // pause all animations, since the next event may be a pan changed runningAnimators.forEach { $0.pauseAnimation() } // keep track of each animator's progress animationProgress = runningAnimators.map { $0.fractionComplete } case .changed: // variable setup let translation = recognizer.translation(in: popupView) var fraction = -translation.y / popupOffset // adjust the fraction for the current state and reversed state if currentState == .open { fraction *= -1 } if runningAnimators[0].isReversed { fraction *= -1 } // apply the new fraction for (index, animator) in runningAnimators.enumerated() { animator.fractionComplete = fraction + animationProgress[index] } case .ended: // variable setup let yVelocity = recognizer.velocity(in: popupView).y let shouldClose = yVelocity > 0 // if there is no motion, continue all animations and exit early if yVelocity == 0 { runningAnimators.forEach { $0.continueAnimation(withTimingParameters: nil, durationFactor: 0) } break } // reverse the animations based on their current state and pan motion switch currentState { case .open: if !shouldClose && !runningAnimators[0].isReversed { runningAnimators.forEach { $0.isReversed = !$0.isReversed } } if shouldClose && runningAnimators[0].isReversed { runningAnimators.forEach { $0.isReversed = !$0.isReversed } } case .closed: if shouldClose && !runningAnimators[0].isReversed { runningAnimators.forEach { $0.isReversed = !$0.isReversed } } if !shouldClose && runningAnimators[0].isReversed { runningAnimators.forEach { $0.isReversed = !$0.isReversed } } } // continue all animations runningAnimators.forEach { $0.continueAnimation(withTimingParameters: nil, durationFactor: 0) } default: () } } } // MARK: - InstantPanGestureRecognizer /// A pan gesture that enters into the `began` state on touch down instead of waiting for a touches moved event. class InstantPanGestureRecognizer: UIPanGestureRecognizer { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { if (self.state == UIGestureRecognizerState.began) { return } super.touchesBegan(touches, with: event) self.state = UIGestureRecognizerState.began } }
mit
61ed06f951439dff338e42579ed20c27
38.735202
146
0.636064
5.509719
false
false
false
false
jpush/aurora-imui
iOS/IMUIInputView/Views/IMUICameraCell.swift
1
3234
// // IMUICameraCell.swift // IMUIChat // // Created by oshumini on 2017/3/9. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import Photos import AVFoundation private enum SessionSetupResult { case success case notAuthorized case configurationFailed } private enum LivePhotoMode { case on case off } // TODO: Need to Restructure @available(iOS 8.0, *) class IMUICameraCell: UICollectionViewCell, IMUIFeatureCellProtocol { @IBOutlet weak var cameraView: IMUICameraView! open var cameraVC = IMUIHidenStatusViewController() // use to present full size mode viewcontroller var isFullScreenMode = false var isActivity = true var featureDelegate: IMUIFeatureViewDelegate? override func awakeFromNib() { super.awakeFromNib() cameraView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 253) cameraView.startRecordVideoCallback = { self.featureDelegate?.startRecordVideo() } cameraView.recordVideoCallback = {(path, duration) in self.featureDelegate?.didRecordVideo(with: path, durationTime: duration) if self.isFullScreenMode { self.shrinkDownScreen() self.isFullScreenMode = false } } cameraView.shootPictureCallback = { imageData in DispatchQueue.main.async { self.featureDelegate?.didShotPicture(with: imageData) } if self.isFullScreenMode { // Switch to main thread operation UI DispatchQueue.main.async { self.shrinkDownScreen() } self.isFullScreenMode = false } } cameraView.onClickFullSizeCallback = { btn in if self.isFullScreenMode { self.shrinkDownScreen() self.isFullScreenMode = false } else { self.setFullScreenMode() self.isFullScreenMode = true } } } func setFullScreenMode() { self.featureDelegate?.cameraFullScreen() let rootVC = UIApplication.shared.delegate?.window??.rootViewController self.cameraView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) self.cameraVC.view = self.cameraView DispatchQueue.main.async { rootVC?.present(self.cameraVC, animated: true, completion: {} ) } } func shrinkDownScreen() { self.featureDelegate?.cameraRecoverScreen() DispatchQueue.main.async { self.cameraVC.dismiss(animated: false, completion: { print("\(self.contentView)") self.contentView.addSubview(self.cameraView) self.cameraView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 253) }) } } func activateMedia() { isActivity = true self.cameraView?.activateMedia() } func inactivateMedia() { self.cameraView?.inactivateMedia() } @IBAction func clickToAdjustCameraViewSize(_ sender: Any) { let rootVC = UIApplication.shared.delegate?.window??.rootViewController let cameraVC = UIViewController() cameraVC.view.backgroundColor = UIColor.white cameraVC.view = cameraView rootVC?.present(cameraVC, animated: true, completion: { }) } }
mit
40c7355e10f5aaaf8a11e311c8b58539
25.702479
118
0.669452
4.450413
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/Node.swift
1
23827
// // Node.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. 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 /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. public protocol Node { var id: GraphQL.ID { get } } extension Storefront { /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. open class NodeQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = Node /// A globally-unique identifier. @discardableResult open func id(alias: String? = nil) -> NodeQuery { addField(field: "id", aliasSuffix: alias) return self } override init() { super.init() addField(field: "__typename") } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onAppliedGiftCard(subfields: (AppliedGiftCardQuery) -> Void) -> NodeQuery { let subquery = AppliedGiftCardQuery() subfields(subquery) addInlineFragment(on: "AppliedGiftCard", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onArticle(subfields: (ArticleQuery) -> Void) -> NodeQuery { let subquery = ArticleQuery() subfields(subquery) addInlineFragment(on: "Article", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onBlog(subfields: (BlogQuery) -> Void) -> NodeQuery { let subquery = BlogQuery() subfields(subquery) addInlineFragment(on: "Blog", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onCart(subfields: (CartQuery) -> Void) -> NodeQuery { let subquery = CartQuery() subfields(subquery) addInlineFragment(on: "Cart", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onCartLine(subfields: (CartLineQuery) -> Void) -> NodeQuery { let subquery = CartLineQuery() subfields(subquery) addInlineFragment(on: "CartLine", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onCheckout(subfields: (CheckoutQuery) -> Void) -> NodeQuery { let subquery = CheckoutQuery() subfields(subquery) addInlineFragment(on: "Checkout", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onCheckoutLineItem(subfields: (CheckoutLineItemQuery) -> Void) -> NodeQuery { let subquery = CheckoutLineItemQuery() subfields(subquery) addInlineFragment(on: "CheckoutLineItem", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onCollection(subfields: (CollectionQuery) -> Void) -> NodeQuery { let subquery = CollectionQuery() subfields(subquery) addInlineFragment(on: "Collection", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onComment(subfields: (CommentQuery) -> Void) -> NodeQuery { let subquery = CommentQuery() subfields(subquery) addInlineFragment(on: "Comment", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onExternalVideo(subfields: (ExternalVideoQuery) -> Void) -> NodeQuery { let subquery = ExternalVideoQuery() subfields(subquery) addInlineFragment(on: "ExternalVideo", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onGenericFile(subfields: (GenericFileQuery) -> Void) -> NodeQuery { let subquery = GenericFileQuery() subfields(subquery) addInlineFragment(on: "GenericFile", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onLocation(subfields: (LocationQuery) -> Void) -> NodeQuery { let subquery = LocationQuery() subfields(subquery) addInlineFragment(on: "Location", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onMailingAddress(subfields: (MailingAddressQuery) -> Void) -> NodeQuery { let subquery = MailingAddressQuery() subfields(subquery) addInlineFragment(on: "MailingAddress", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onMediaImage(subfields: (MediaImageQuery) -> Void) -> NodeQuery { let subquery = MediaImageQuery() subfields(subquery) addInlineFragment(on: "MediaImage", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onMenu(subfields: (MenuQuery) -> Void) -> NodeQuery { let subquery = MenuQuery() subfields(subquery) addInlineFragment(on: "Menu", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onMenuItem(subfields: (MenuItemQuery) -> Void) -> NodeQuery { let subquery = MenuItemQuery() subfields(subquery) addInlineFragment(on: "MenuItem", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onMetafield(subfields: (MetafieldQuery) -> Void) -> NodeQuery { let subquery = MetafieldQuery() subfields(subquery) addInlineFragment(on: "Metafield", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onModel3d(subfields: (Model3dQuery) -> Void) -> NodeQuery { let subquery = Model3dQuery() subfields(subquery) addInlineFragment(on: "Model3d", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onOrder(subfields: (OrderQuery) -> Void) -> NodeQuery { let subquery = OrderQuery() subfields(subquery) addInlineFragment(on: "Order", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onPage(subfields: (PageQuery) -> Void) -> NodeQuery { let subquery = PageQuery() subfields(subquery) addInlineFragment(on: "Page", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onPayment(subfields: (PaymentQuery) -> Void) -> NodeQuery { let subquery = PaymentQuery() subfields(subquery) addInlineFragment(on: "Payment", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onProduct(subfields: (ProductQuery) -> Void) -> NodeQuery { let subquery = ProductQuery() subfields(subquery) addInlineFragment(on: "Product", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onProductOption(subfields: (ProductOptionQuery) -> Void) -> NodeQuery { let subquery = ProductOptionQuery() subfields(subquery) addInlineFragment(on: "ProductOption", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onProductVariant(subfields: (ProductVariantQuery) -> Void) -> NodeQuery { let subquery = ProductVariantQuery() subfields(subquery) addInlineFragment(on: "ProductVariant", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onShop(subfields: (ShopQuery) -> Void) -> NodeQuery { let subquery = ShopQuery() subfields(subquery) addInlineFragment(on: "Shop", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onShopPolicy(subfields: (ShopPolicyQuery) -> Void) -> NodeQuery { let subquery = ShopPolicyQuery() subfields(subquery) addInlineFragment(on: "ShopPolicy", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onUrlRedirect(subfields: (UrlRedirectQuery) -> Void) -> NodeQuery { let subquery = UrlRedirectQuery() subfields(subquery) addInlineFragment(on: "UrlRedirect", subfields: subquery) return self } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. @discardableResult open func onVideo(subfields: (VideoQuery) -> Void) -> NodeQuery { let subquery = VideoQuery() subfields(subquery) addInlineFragment(on: "Video", subfields: subquery) return self } } /// An object with an ID field to support global identification, in accordance /// with the [Relay /// specification](https://relay.dev/graphql/objectidentification.htm#sec-Node-Interface). /// This interface is used by the /// [node](https://shopify.dev/api/admin-graphql/unstable/queries/node) and /// [nodes](https://shopify.dev/api/admin-graphql/unstable/queries/nodes) /// queries. open class UnknownNode: GraphQL.AbstractResponse, GraphQLObject, Node { public typealias Query = NodeQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "id": guard let value = value as? String else { throw SchemaViolationError(type: UnknownNode.self, field: fieldName, value: fieldValue) } return GraphQL.ID(rawValue: value) default: throw SchemaViolationError(type: UnknownNode.self, field: fieldName, value: fieldValue) } } internal static func create(fields: [String: Any]) throws -> Node { guard let typeName = fields["__typename"] as? String else { throw SchemaViolationError(type: UnknownNode.self, field: "__typename", value: fields["__typename"] ?? NSNull()) } switch typeName { case "AppliedGiftCard": return try AppliedGiftCard.init(fields: fields) case "Article": return try Article.init(fields: fields) case "Blog": return try Blog.init(fields: fields) case "Cart": return try Cart.init(fields: fields) case "CartLine": return try CartLine.init(fields: fields) case "Checkout": return try Checkout.init(fields: fields) case "CheckoutLineItem": return try CheckoutLineItem.init(fields: fields) case "Collection": return try Collection.init(fields: fields) case "Comment": return try Comment.init(fields: fields) case "ExternalVideo": return try ExternalVideo.init(fields: fields) case "GenericFile": return try GenericFile.init(fields: fields) case "Location": return try Location.init(fields: fields) case "MailingAddress": return try MailingAddress.init(fields: fields) case "MediaImage": return try MediaImage.init(fields: fields) case "Menu": return try Menu.init(fields: fields) case "MenuItem": return try MenuItem.init(fields: fields) case "Metafield": return try Metafield.init(fields: fields) case "Model3d": return try Model3d.init(fields: fields) case "Order": return try Order.init(fields: fields) case "Page": return try Page.init(fields: fields) case "Payment": return try Payment.init(fields: fields) case "Product": return try Product.init(fields: fields) case "ProductOption": return try ProductOption.init(fields: fields) case "ProductVariant": return try ProductVariant.init(fields: fields) case "Shop": return try Shop.init(fields: fields) case "ShopPolicy": return try ShopPolicy.init(fields: fields) case "UrlRedirect": return try UrlRedirect.init(fields: fields) case "Video": return try Video.init(fields: fields) default: return try UnknownNode.init(fields: fields) } } /// A globally-unique identifier. open var id: GraphQL.ID { return internalGetId() } func internalGetId(alias: String? = nil) -> GraphQL.ID { return field(field: "id", aliasSuffix: alias) as! GraphQL.ID } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { return [] } } }
mit
d4cdbc6d88b0bc4dcb277d17842f9dd9
39.591141
116
0.712511
3.752283
false
false
false
false
tfausak/Swifty8
Swifty8/AppDelegate.swift
1
1928
// // AppDelegate.swift // Swifty8 // // Created by Taylor Fausak on 6/7/14. // Copyright (c) 2014 Taylor Fausak. All rights reserved. // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate { var game = Game() @IBOutlet var window: NSWindow @IBOutlet var leftButton : NSButton @IBOutlet var downButton : NSButton @IBOutlet var rightButton : NSButton @IBOutlet var upButton : NSButton @IBOutlet var gridView : NSCollectionView @IBOutlet var scoreCell : NSTextFieldCell @IBOutlet var winnerField : NSTextField func applicationDidFinishLaunching(aNotification: NSNotification?) { updateView() } func applicationWillTerminate(aNotification: NSNotification?) { // Insert code here to tear down your application } @IBAction func leftButtonPushed(sender : NSButton) { game.move(Direction.Left) updateView() } @IBAction func downButtonPushed(sender : NSButton) { game.move(Direction.Down) updateView() } @IBAction func rightButtonPushed(sender : NSButton) { game.move(Direction.Right) updateView() } @IBAction func upButtonPushed(sender : NSButton) { game.move(Direction.Up) updateView() } func updateView() { leftButton.enabled = game.canMove(Direction.Left) downButton.enabled = game.canMove(Direction.Down) rightButton.enabled = game.canMove(Direction.Right) upButton.enabled = game.canMove(Direction.Up) gridView.maxNumberOfRows = game.height gridView.maxNumberOfColumns = game.width // TODO: This is dumb. Why can't I just set the content to the list of // tiles? gridView.content = game.tiles.map { $0.description } scoreCell.title = "Score: \(game.score)" winnerField.hidden = !game.hasWon } }
mit
e65238dfd042b3039f08f890f1a1e0b0
25.410959
78
0.64834
4.645783
false
false
false
false
kellanburket/Passenger
Example/Passenger/Twitter/Media.swift
1
583
// // Media.swift // Passenger // // Created by Kellan Cummings on 7/11/15. // Copyright (c) 2015 CocoaPods. All rights reserved. // import Foundation import Passenger class Media: Entity { var type: String? var sizes = [ "thumb": ImageSize(), "large": ImageSize(), "medium": ImageSize(), "small": ImageSize() ] var indices = [Int]() var mediaUrl = Image() var displayUrl = Image() var expandedUrl = Image() var mediaUrlHttps = Image() var idStr: String? var entity = BelongsTo<StatusEntity>() }
mit
4b4484b98124f3426d112b2f46adba21
17.21875
54
0.591767
3.860927
false
false
false
false
pandazheng/Spiral
Spiral/KillerContactVisitor.swift
2
1006
// // KillerContactVisitor.swift // Spiral // // Created by 杨萧玉 on 14-7-14. // Copyright (c) 2014年 杨萧玉. All rights reserved. // import Foundation import SpriteKit class KillerContactVisitor:ContactVisitor{ func visitPlayer(body:SKPhysicsBody){ let thisNode = self.body.node // let otherNode = body.node thisNode?.removeFromParent() } func visitKiller(body:SKPhysicsBody){ let thisNode = self.body.node // let otherNode = body.node thisNode?.removeFromParent() } func visitScore(body:SKPhysicsBody){ // let thisNode = self.body.node // let otherNode = body.node } func visitShield(body:SKPhysicsBody){ let thisNode = self.body.node // let otherNode = body.node thisNode?.removeFromParent() } func visitReaper(body:SKPhysicsBody){ let thisNode = self.body.node // let otherNode = body.node thisNode?.removeFromParent() } }
mit
8160adcaef230d11b6515d1139ae7740
23.219512
49
0.63004
4.04898
false
false
false
false
bastiangardel/EasyPayClientSeller
TB_Client_Seller/TB_Client_Seller/AppDelegate.swift
1
8941
// // AppDelegate.swift // TB_Client_Seller // // Created by Bastian Gardel on 20.06.16. // // Copyright © 2016 Bastian Gardel // // 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 CoreData import KeychainSwift import TWMessageBarManager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let keychain = KeychainSwift() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { registerForPushNotifications(application) self.keychain.set("", forKey: "deviceToken"); return true } func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { if notificationSettings.types != .None { application.registerForRemoteNotifications() } } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) var tokenString = "" for i in 0..<deviceToken.length { tokenString += String(format: "%02.2hhx", arguments:[tokenChars[i]]) } self.keychain.set(tokenString, forKey: "deviceToken"); print("Device Token:", tokenString) } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { self.keychain.set("", forKey: "deviceToken"); print("Failed to register:", error) } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { application.applicationIconBadgeNumber = 0 TWMessageBarManager.sharedInstance().showMessageWithTitle(userInfo["aps"]!["alert"]!!["title"] as? String, description: userInfo["aps"]!["alert"]!!["body"] as? String, type: TWMessageBarMessageType.Success, duration:6.0) NSNotificationCenter.defaultCenter().postNotificationName("quitView", object: nil, userInfo: userInfo) } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } func registerForPushNotifications(application: UIApplication) { let notificationSettings = UIUserNotificationSettings( forTypes: [.Badge, .Sound, .Alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "HEIG-VD.TB_Client_Seller" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("TB_Client_Seller", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
8d02212b699429cd01d8ea377ff7a4dc
50.976744
290
0.731655
5.643939
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/views/trip overview/TKUISegmentStationaryDoubleCell.swift
1
4397
// // TKUISegmentStationaryDoubleCell.swift // TripKitUI-iOS // // Created by Adrian Schönig on 04.01.21. // Copyright © 2020 SkedGo Pty Ltd. All rights reserved. // import UIKit import RxSwift import TripKit class TKUISegmentStationaryDoubleCell: UITableViewCell { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var timeEndLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var endSubtitleLabel: UILabel! @IBOutlet weak var lineWrapper: UIView! @IBOutlet weak var topLine: UIView! @IBOutlet weak var topLineDot: UIView! @IBOutlet weak var bottomLine: UIView! @IBOutlet weak var bottomLineDot: UIView! @IBOutlet weak var lineDotWidthConstraint: NSLayoutConstraint! /// Space from the label stack across the time stack to the superview. Ideally /// we wouldn't need this and instead just have a fixed space between the label /// stack and the time stack, but Auto Layout can't seem to handle this and /// won't allow the label stack to grow vertically. So we have this, and toggle it /// between 82 and 16 depending on whether there's a time stack. @IBOutlet weak var labelStackTrailingConstraint: NSLayoutConstraint! static let nib = UINib(nibName: "TKUISegmentStationaryDoubleCell", bundle: Bundle(for: TKUISegmentStationaryDoubleCell.self)) static let reuseIdentifier = "TKUISegmentStationaryDoubleCell" private var disposeBag = DisposeBag() override func awakeFromNib() { super.awakeFromNib() backgroundColor = .clear topLineDot.backgroundColor = .tkBackground bottomLineDot.backgroundColor = .tkBackground titleLabel.font = TKStyleManager.boldCustomFont(forTextStyle: .body) titleLabel.textColor = .tkLabelPrimary subtitleLabel.textColor = .tkLabelSecondary endSubtitleLabel.textColor = .tkLabelSecondary timeLabel.textColor = .tkLabelPrimary timeLabel.numberOfLines = 0 timeEndLabel.textColor = .tkLabelPrimary timeEndLabel.numberOfLines = 0 } override func prepareForReuse() { super.prepareForReuse() disposeBag = DisposeBag() } override func setHighlighted(_ highlighted: Bool, animated: Bool) { // Not calling super to not override line colors UIView.animate(withDuration: animated ? 0.25 : 0) { self.contentView.backgroundColor = highlighted ? .tkBackgroundSelected : self.backgroundColor } } override func setSelected(_ selected: Bool, animated: Bool) { setHighlighted(selected, animated: animated); } } extension TKUISegmentStationaryDoubleCell { func configure(with item: TKUITripOverviewViewModel.StationaryItem) { let startText = item.startTime?.timeString(for: item.timeZone) let endText = item.endTime?.timeString(for: item.timeZone) if !item.timesAreFixed { timeLabel.text = nil timeEndLabel.text = nil } else if let start = startText, let end = endText, start.1 != end.1 { timeLabel.attributedText = start.0 timeLabel.accessibilityLabel = Loc.Arrives(atTime: start.1) timeEndLabel.attributedText = end.0 timeEndLabel.accessibilityLabel = Loc.Departs(atTime: end.1) } else if let time = startText ?? endText { timeLabel.attributedText = time.0 timeLabel.accessibilityLabel = Loc.At(time: time.1) timeEndLabel.text = nil } else { timeLabel.text = nil timeEndLabel.text = nil } titleLabel.text = item.title subtitleLabel.text = item.subtitle subtitleLabel.isHidden = item.subtitle == nil endSubtitleLabel.text = item.endSubtitle endSubtitleLabel.isHidden = item.endSubtitle == nil topLineDot.layer.borderColor = (item.topConnection?.color ?? .tkLabelPrimary).cgColor topLineDot.layer.borderWidth = 3 bottomLineDot.layer.borderColor = (item.bottomConnection?.color ?? .tkLabelPrimary).cgColor bottomLineDot.layer.borderWidth = 3 let width: CGFloat = item.isContinuation ? 12 : 18 lineDotWidthConstraint.constant = width topLineDot.layer.cornerRadius = width / 2 bottomLineDot.layer.cornerRadius = width / 2 topLine.backgroundColor = item.topConnection?.color topLine.isHidden = item.topConnection?.color == nil bottomLine.backgroundColor = item.bottomConnection?.color bottomLine.isHidden = item.bottomConnection?.color == nil } }
apache-2.0
8bae668c815e2bedc79e86a10ee8d997
32.807692
127
0.72992
4.516958
false
false
false
false
skedgo/tripkit-ios
Sources/TripKit/vendor/ASPolygonKit/Polygon.swift
1
16371
// // Polygon.swift // // Created by Adrian Schoenig on 18/2/17. // // import Foundation #if canImport(CoreGraphics) import CoreGraphics #endif typealias TKPolygon = Polygon enum PolygonUnionError: Error, CustomDebugStringConvertible { #if DEBUG case polygonTooComplex([Polygon.UnionStep]) #else case polygonTooComplex #endif case polygonIsSubset case invalidPolygon var debugDescription: String { switch self { case .polygonTooComplex: return "polygonTooComplex" case .polygonIsSubset: return "polygonIsSubset" case .invalidPolygon: return "invalidPolygon" } } } struct Polygon { #if DEBUG enum UnionStep { case start(Polygon, Polygon, [Intersection], start: Point) case extendMine(partial: [Point]) case extendYours(partial: [Point]) case intersect(Intersection, onMine: Bool) } #endif var points: [Point] { didSet { firstLink = Polygon.firstLink(for: points) } } var firstLink: LinkedLine init(pairs: [(Double, Double)]) { self.init(points: pairs.map { pair in Point(latitude: pair.0, longitude: pair.1) }) } init(points: [Point]) { self.points = points firstLink = Polygon.firstLink(for: points) } // MARK: Basic info var description: String? { return points.reduce("[ ") { previous, point in let start = previous.utf8.count == 2 ? previous : previous + ", " return start + point.description } + " ]" } var minY: Double { return points.reduce(Double.infinity) { acc, point in return Double.minimum(acc, point.y) } } var maxY: Double { return points.reduce(Double.infinity * -1) { acc, point in return Double.maximum(acc, point.y) } } var minX: Double { return points.reduce(Double.infinity) { acc, point in return Double.minimum(acc, point.x) } } var maxX: Double { return points.reduce(Double.infinity * -1) { acc, point in return Double.maximum(acc, point.x) } } #if canImport(CoreGraphics) var boundingRect: CGRect { return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) } #endif func isClockwise() -> Bool { var points: [Point] = self.points if let first = points.first, first != points.last { points.append(first) } let offsetPoints: [Point] = Array(points[1...] + [points[0]]) let signedArea: Double = zip(points, offsetPoints).reduce(0) { area, pair in area + pair.0.x * pair.1.y - pair.1.x * pair.0.y } // Note: Actual area is `signedArea / 2`, but we just care about sign // Negative points means clock-wise; positive means counter-clockwise return signedArea < 0 } func clockwise() -> Polygon { let result = isClockwise() ? self : Polygon(points: points.reversed()) assert(result.isClockwise()) return result } // MARK: Polygon as list of lines static func firstLink(for points: [Point]) -> LinkedLine { var first: LinkedLine? = nil var previous: LinkedLine? = nil for (index, point) in points.enumerated() { let nextIndex = (index == points.endIndex - 1) ? points.startIndex : index + 1 let next = points[nextIndex] if next != point { let line = Line(start: point, end: next) let link = LinkedLine(line: line, next: nil) if first == nil { first = link } previous?.next = link previous = link } } return first! } // MARK: Polygon to polygon intersections func intersects(_ polygon: Polygon) -> Bool { return intersections(polygon).count > 0 } func intersections(_ polygon: Polygon) -> [Intersection] { var intersections : [Intersection] = [] for link in firstLink { for other in polygon.firstLink { if let point = link.line.intersection(with: other.line) { if let index = intersections.firstIndex(where: { $0.point == point} ) { // Account for the case where the intersection is at a corner of the polygon var updated = intersections[index] if !updated.mine.contains(link) { updated.mine.append(link) } if !updated.yours.contains(other) { updated.yours.append(other) } intersections[index] = updated } else { let intersection = Intersection(point: point, mine: [link], yours: [other]) intersections.append(intersection) } } } } return intersections } // MARK: Contains point check fileprivate func numberOfIntersections(_ line: Line) -> Int { var count = 0 for link in firstLink { if let point = link.line.intersection(with: line) { if point != line.start && point != line.end { count += 1 } } } return count } /// Check if the polygon contains a point /// - Parameters: /// - point: The point to check /// - onLine: `true` if the contains check should succeed when the point is right on the edge of the polygon /// - Returns: Whether the polygon contains the point func contains(_ point: Point, onLine: Bool) -> Bool { if onLine { for link in firstLink { if link.line.contains(point) { return true } } } let ray = Line(start: point, end: Point(x: 0, y: 0)) // assuming no polygon contains the coast of africa return numberOfIntersections(ray) % 2 == 1 } /// Checks if the polygon contains the provided polygon /// - Parameter polygon: The polygon to check for containment /// - Returns: Whether `self` contains `polygon`, ignoring interior polygons of either func contains(_ polygon: Polygon) -> Bool { for point in polygon.points { if !contains(point, onLine: false) { return false } } return true } // MARK: Union @discardableResult /// Merged the provided polygon into the caller /// - Parameter polygon: Polygon to merge into `self` /// - Returns: Whether the polygon was merged; return `false` if there's no overlap mutating func union(_ polygon: Polygon) throws -> Bool { let intersections = self.intersections(polygon) if intersections.count == 0 { return false } return try union(polygon, with: intersections, allowInverting: true) } @discardableResult mutating func union(_ polygon: Polygon, with intersections: [Intersection]) throws -> Bool { try union(polygon, with: intersections, allowInverting: true) } private mutating func union(_ polygon: Polygon, with intersections: [Intersection], allowInverting: Bool) throws -> Bool { if polygon.points.count < 3 || points.count < 3 { throw PolygonUnionError.invalidPolygon } if intersections.count == 0 { return false } var startLink: LinkedLine = firstLink // We need to start with a link that starts outside the polygon // that we are trying to add. while polygon.contains(startLink.line.start, onLine: true) { if let next = startLink.next { startLink = next } else { break } } if polygon.contains(startLink.line.start, onLine: true) { // This polygon is (deemed to be) a subset of the polygon that you're // trying to merge into it. If this happens, we try it the other way // around. if allowInverting { var grower = polygon let invertedIntersections = grower.intersections(self) let merged = try grower.union(self, with: invertedIntersections, allowInverting: false) if merged { self = grower return true } else { return false } } else { throw PolygonUnionError.polygonIsSubset } } let startPoint = startLink.line.start var current = (point: startLink.line.start, link: startLink, onMine: true) var remainingIntersections = intersections var newPoints: [Point] = [] #if DEBUG var steps: [UnionStep] = [ .start(self, polygon, intersections, start: startPoint) ] #endif repeat { Polygon.append(current.point, to: &newPoints) #if DEBUG steps.append(current.onMine ? .extendMine(partial: newPoints) : .extendYours(partial: newPoints)) #endif if newPoints.count - points.count > polygon.points.count * 2 { #if DEBUG print("Could not merge\n\n\(polygon.encodeCoordinates())\n\ninto\n\n\(encodeCoordinates())\n\n") throw PolygonUnionError.polygonTooComplex(steps) #else throw PolygonUnionError.polygonTooComplex #endif } let candidates = Polygon.potentialIntersections( in: remainingIntersections, startingAt: current.point, on: current.link, polygonStart: (mine: firstLink, yours: polygon.firstLink) ) if let (index, closest, newOnMine) = closestIntersection(candidates, to: current.point), newOnMine != current.onMine { #if DEBUG steps.append(.intersect(closest, onMine: newOnMine)) #endif remainingIntersections.remove(at: index) current = (point: closest.point, link: (newOnMine ? closest.mine : closest.yours).last!, onMine: newOnMine) } else { // the linked lines do not wrap around themselves, so we do that here manually let next: LinkedLine if let nextInPoly = current.link.next { next = nextInPoly } else if current.onMine { next = firstLink } else { next = polygon.firstLink } current = (point: next.line.start, link: next, onMine: current.onMine) } } while current.point != startPoint assert(newPoints.count > 2, "Should never end up with a line (or less) after merging") points = newPoints if points.first != points.last, let first = points.first { points.append(first) } #if DEBUG // let stepsGeoJSON: [String: Any] = [ // "type": "FeatureCollection", // "features": steps.flatMap { $0.toGeoJSON(startOnly: false) } // ] // print(String(decoding: try JSONSerialization.data(withJSONObject: stepsGeoJSON, options: []), as: UTF8.self)) #endif return true } fileprivate static func potentialIntersections( in intersections: [Intersection], startingAt start: Point, on link: LinkedLine, polygonStart: (mine: LinkedLine, yours: LinkedLine) ) -> [(Int, Intersection, Bool)] { var lineIntersections: [(Int, Intersection, Bool)] = [] for (index, intersection) in intersections.enumerated() { // The intersection applies if it's for the same link AND if the intersection's point is on that link between `start` and the intersection's end, i.e., we can't go back if `start` is already further along the link than the intersections' point. guard intersection.appliesTo(link, start: start) else { continue } // The two lines intersection. For this intersection we want to continue on the one which has a smaller clock wise angle. // We compare your angle `line.start - point - other.line.end` to mine `line.start - point - line.end`. // It is possible that `point == other.line.end` in that case, we take the angle to `other.next.line.end`. Same thing with `point == line.end` in which case we compare to the angle to `line.next.end` let point = intersection.point func findAngle(for links: [LinkedLine], lastPoint: Point) -> (angle: Double, end: Point) { return links.map { link in let link = links.last! let end: Point if point == link.line.end { if let next = link.next { end = next.line.end } else { end = lastPoint } } else { end = link.line.end } let angle = calculateAngle(start: start, middle: point, end: end) return (angle, end) }.min { $0.angle < $1.angle }! } let (yourAngle, yourEnd) = findAngle(for: intersection.yours, lastPoint: polygonStart.yours.line.end) let (myAngle, myEnd) = findAngle(for: intersection.mine, lastPoint: polygonStart.mine.line.end) let continueOnMine: Bool if myAngle < yourAngle { continueOnMine = true } else if (yourAngle < myAngle) { continueOnMine = false } else { let myDistance = point.distance(from: myEnd) let yourDistance = point.distance(from: yourEnd) continueOnMine = myDistance > yourDistance } let candidate = (index, intersection, continueOnMine) lineIntersections.append(candidate) } return lineIntersections } fileprivate static func append(_ point: Point, to points: inout [Point]) { // 1) if we don't have a last point, just append it // 2) if we have a previous point and this is the same, skip it // 3) if we have two previous points and this is on the same line then remove the previous point and insert this one // 4) otherwise, append it if let last = points.last { if last == point { return // 2) } if points.count - 2 >= 0 { let lastLast = points[points.count - 2] let spanner = Line(start: lastLast, end: point) let next = Line(start: last, end: point) if (abs(spanner.m) > 1_000_000 && abs(next.m) > 1_000_000) // takes care of both being Infinity || abs(spanner.m - next.m) < 0.0001 { points.removeLast() // 3) } } } points.append(point) // 1, 3, 4) } } // To find the polygon between the two polygons, we see if there's an intersection between each pair of lines between the polygons. First we need to get the lines in a polygon. class LinkedLine: Sequence, Equatable { let line: Line var next: LinkedLine? init(line: Line, next: LinkedLine?) { self.line = line self.next = next } func makeIterator() -> AnyIterator<LinkedLine> { var this: LinkedLine? = self return AnyIterator { let ret = this this = this?.next return ret } } } func ==(lhs: LinkedLine, rhs: LinkedLine) -> Bool { return lhs.line == rhs.line } // Let's calculate the intersections and keep for each intersection information about which line this intersection is with struct Intersection { let point: Point var mine: [LinkedLine] var yours: [LinkedLine] fileprivate func appliesTo(_ link: LinkedLine, start: Point) -> Bool { guard mine.contains(link) || yours.contains(link) else { return false } let linkStart = link.line.start let toPoint = point.distance(from: linkStart) let toStart = start.distance(from: linkStart) return toStart <= toPoint } } // For this exercise we assume that one polygon is never part of another, so we only need to deal with two cases: There's an overlap or there's none. Note, that if there's an overlap, we should have at least two intersection points. // What do we do with the intersections? // For each line that intersects we need to deal with the case that it has multiple intersections. Typically we are only concerned about the closest then. private func closestIntersection(_ intersections: [(Int, Intersection, Bool)], to point: Point) -> (Int, Intersection, Bool)? { if (intersections.count <= 1) { return intersections.first } else { // the closest is the one with the least distance from the points to the intersection return intersections.reduce(nil) { prior, entry in if prior == nil || entry.1.point.distance(from: point) < prior!.1.point.distance(from: point) { return entry } else { return prior } } } } private func calculateAngle(start: Point, middle: Point, end: Point) -> Double { let v1 = Point(x: start.x - middle.x, y: start.y - middle.y) let v2 = Point(x: end.x - middle.x, y: end.y - middle.y) let arg1 = v1.x * v2.y - v1.y * v2.x let arg2 = v1.x * v2.x + v1.y * v2.y let atan = atan2(arg1, arg2) let degrees = atan * -180/Double.pi if degrees < 0 { return degrees + 360 } else { return degrees } }
apache-2.0
3b3d775c49e5a3257a8a301cd05660aa
30.482692
250
0.626351
4.044219
false
false
false
false
izotx/iTenWired-Swift
Conference App/Event.swift
1
6199
// Copyright (c) 2016, Izotx // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Izotx nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // Event.swift // Created by Felipe Neves Brito {[email protected]} on 4/5/16. import Foundation /// Event object attribuites names enum EventEnum : String{ case id case name case summary case timeStart case timeStop case date case presenters case track case location_id } /// Contains the conference events data class Event : NSObject{ /// The events unique ID var id:Int = 0 /// The events name var name:String = "" /// The events description and information var summary:String = "" /// The time the event starts var timeStart:String = "" /// The time the event ends var timeStop:String = "" /// The events date var date:String = "" /// The ID if the events Track var trackID = 0 /// A list with all the events presentors var presentorsIDs:[Int] = [] /// The Id of the location of the event var locationId = 0 init(id:Int){ self.id = id } /** Initializes an event with the provided data - Parameters: - id: The event's unique id - name: The event's name - summary: The event's summary/description - timeStart: The time the event starts - timeStop: The time the event stops - date: The event's date */ init(id:Int, name:String, summary:String, timeStart:String, timeStop:String, date:String){ self.id = id self.name = name self.summary = summary self.timeStart = timeStart self.timeStop = timeStop self.date = date } /** Initializes an event with the provided dictionary - Parameter dictionary: A dictionary with an event's data */ init(dictionary: NSDictionary){ if let IDString = dictionary.objectForKey(EventEnum.id.rawValue) as? String{ self.id = Int(IDString)! } if let name = dictionary.objectForKey(EventEnum.name.rawValue) as? String{ self.name = name } if let summary = dictionary.objectForKey(EventEnum.summary.rawValue) as? String{ self.summary = summary } if let timeStart = dictionary.objectForKey(EventEnum.timeStart.rawValue) as? String{ self.timeStart = timeStart } if let timeStop = dictionary.objectForKey(EventEnum.timeStop.rawValue) as? String{ self.timeStop = timeStop } if let date = dictionary.objectForKey(EventEnum.date.rawValue) as? String{ self.date = date } if let speakersIds = dictionary.objectForKey(EventEnum.presenters.rawValue) as? [String]{ for id in speakersIds { self.presentorsIDs.append(Int(id)!) } } if let trackIDString = dictionary.objectForKey(EventEnum.track.rawValue) as? String { self.trackID = Int(trackIDString)! } if let locationId = dictionary.objectForKey(EventEnum.location_id.rawValue) as? Int { self.locationId = locationId } } required convenience init?(coder decoder: NSCoder){ guard let id:Int32 = decoder.decodeIntForKey(EventEnum.id.rawValue), let name:String = decoder.decodeObjectForKey(EventEnum.name.rawValue) as? String, let summary = decoder.decodeObjectForKey(EventEnum.summary.rawValue) as? String, let timeStart = decoder.decodeObjectForKey(EventEnum.timeStart.rawValue) as? String, let timeStop = decoder.decodeObjectForKey(EventEnum.timeStop.rawValue) as? String, let date = decoder.decodeObjectForKey(EventEnum.date.rawValue) as? String else { return nil } self.init(id: Int(id), name: name, summary: summary, timeStart: timeStart, timeStop: timeStop, date: date) } } //MARK: - NSCoding extension Event: NSCoding{ func encodeWithCoder(coder: NSCoder) { coder.encodeInt(Int32(self.id), forKey: EventEnum.id.rawValue) coder.encodeObject(self.name, forKey: EventEnum.name.rawValue) coder.encodeObject(self.summary, forKey: EventEnum.summary.rawValue) coder.encodeObject(self.timeStart, forKey: EventEnum.timeStart.rawValue) coder.encodeObject(self.timeStop, forKey: EventEnum.timeStop.rawValue) coder.encodeObject(self.date, forKey: EventEnum.date.rawValue) } }
bsd-2-clause
bf592692bf8a980778e028c16431f158
34.028249
114
0.644297
4.571534
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-05/ImageMetalling-05/IMPHistogramAnalyzer.swift
1
5426
// // IMPHistogramAnalizer.swift // ImageMetalling-05 // // Created by denis svinarchuk on 28.11.15. // Copyright © 2015 IMetalling. All rights reserved. // import UIKit /// /// Протокол солверов статистики гистограммы. Солверами будем решать конкретные задачи обработки данных прилетевших в контейнер. /// protocol IMPHistogramSolver{ func analizerDidUpdate(analizer: IMPHistogramAnalyzer, histogram: IMPHistogram, imageSize: CGSize); } /// /// Анализатор гистограммы четырех канальной гистограммы. /// Сам анализатор представляем как некий общий класс работающий с произвольным типом гистограмм. /// Конкретную обрадотку статистики оставляем за набором решающий классов поддерживающих протокол IMPHistogramSolver. /// class IMPHistogramAnalyzer: DPFilter { /// /// Тут храним наши вычисленные распределения поканальных интенсивностей. /// var histogram = IMPHistogram() /// /// Солверы участвующие в анализе гистограммы /// var solvers:[IMPHistogramSolver] = [IMPHistogramSolver]() /// Замыкание выполняющаеся после завершения расчета значений солвера. /// Замыкание можно определить для обновления значений пользовательской цепочки фильтров. var solversDidUpdate: (() -> Void)? /// /// Конструктор анализатора с произвольным счетчиком, который /// задаем kernel-функцией. Главное условие совместимость с типом IMPHistogramBuffer /// как контейнером данных гистограммы. /// /// init(function: String, context aContext: DPContext!) { super.init(context: aContext) // инициализируем счетчик kernel_impHistogramCounter = DPFunction.newFunction(function, context: self.context) // создаем память в устройстве под контейнер счета histogramUniformBuffer = self.context.device.newBufferWithLength(sizeof(IMPHistogramBuffer), options: MTLResourceOptions.CPUCacheModeDefaultCache) // добавляем счетчик как метод фильтра self.addFunction(kernel_impHistogramCounter); } /// /// По умолчанию гистограмма инициализируется счетчиком интенсивностей в RGB-пространстве, /// с дополнительным вычислением канала яркости. /// required convenience init!(context aContext: DPContext!) { self.init(function: "kernel_impHistogramRGBYCounter", context:aContext) } // // Буфер обмена контейнера счета с GPU // private var histogramUniformBuffer:MTLBuffer! // // kernel-функция счета // private var kernel_impHistogramCounter:DPFunction! /// /// При каждом обращении к GPU для расчета гистограмы нам нужно обресетить данные посчитанные на предыдущем этапе /// если объект анализатора постоянно определен. /// override func configureBlitUniform(commandEncoder: MTLBlitCommandEncoder!) { commandEncoder.fillBuffer(histogramUniformBuffer, range: NSMakeRange(0, sizeof(IMPHistogramBuffer)), value: 0) } /// /// Устанавливаем указатель на контейнер счета в буфере команд. /// override func configureFunction(function: DPFunction!, uniform commandEncoder: MTLComputeCommandEncoder!) { commandEncoder.setBuffer(histogramUniformBuffer, offset:0, atIndex:0); } /// /// Перегружаем свойство источника: при каждом обновлении нам нужно выполнить подсчет новой статистики. /// override var source:DPImageProvider!{ didSet{ super.source = source if source.texture != nil { // выполняем фильтр self.apply() } } } override func apply() { super.apply() // обновляем структуру гистограммы с которой уже будем работать histogram.updateWithData(histogramUniformBuffer.contents()) for s in solvers { let size = CGSizeMake(CGFloat(self.source.texture.width), CGFloat(self.source.texture.height)) s.analizerDidUpdate(self, histogram: self.histogram, imageSize: size) } if let finishSolver = self.solversDidUpdate { finishSolver() } } }
mit
a9719f3eb556d6d87265009c35b18df3
34.555556
154
0.686058
3.387622
false
false
false
false
MoooveOn/Advanced-Frameworks
LiveRendering/LiveRendering/PieView.swift
1
5669
// // PieView.swift // LiveRendering // // Created by Pavel Selivanov on 14.06.17. // Copyright © 2017 Pavel Selivanov. All rights reserved. // import UIKit @IBDesignable class PieView: UIView { // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. //override func draw(_ rect: CGRect) { // Drawing code //} var bgLayer: CAShapeLayer! @IBInspectable var bgLayerColor: UIColor = UIColor.darkGray { didSet { updateLayerProperties() } } var bgImageLayer: CALayer! @IBInspectable var bgImage: UIImage? { didSet { updateLayerProperties() } } var ringLayer: CAShapeLayer! @IBInspectable var ringThickness: CGFloat = 2.0 @IBInspectable var ringColor: UIColor = UIColor.green @IBInspectable var ringProgress: CGFloat = 0.75 { didSet { updateLayerProperties() } } var percentageLayer: CATextLayer! @IBInspectable var showPercentage: Bool = true { didSet { updateLayerProperties() } } @IBInspectable var percentagePosition: CGFloat = 100 { didSet { updateLayerProperties() } } @IBInspectable var percentageColor: UIColor = .white { didSet { updateLayerProperties() } } var lineWidth: CGFloat = 2 override func layoutSubviews() { super.layoutSubviews() createChart() } func createChart() { layoutBackgroundLayer() layoutBackgroundImageLayer() createPie() updateLayerProperties() } func layoutBackgroundLayer() { if bgLayer == nil { bgLayer = CAShapeLayer() layer.addSublayer(bgLayer) let rectangle = bounds.insetBy(dx: lineWidth / 2, dy: lineWidth / 2) let path = UIBezierPath(ovalIn: rectangle) //See explanation in documentation why we use cgPath bgLayer.path = path.cgPath bgLayer.fillColor = bgLayerColor.cgColor //Our bgLayer fills the whole view bgLayerColor.accessibilityFrame = layer.bounds } } func layoutBackgroundImageLayer() { if bgImageLayer == nil { //Out image has rectangular shape, but we want to have circle shape of image. Let's create mask fot it: let imageMask = CAShapeLayer() let inset = lineWidth + 3 let insetBounds = self.bounds.insetBy(dx: inset, dy: inset) let maskPath = UIBezierPath(ovalIn: insetBounds) imageMask.path = maskPath.cgPath imageMask.fillColor = UIColor.black.cgColor imageMask.frame = self.bounds bgImageLayer = CAShapeLayer() bgImageLayer.mask = imageMask bgImageLayer.frame = self.bounds bgImageLayer.contentsGravity = kCAGravityResizeAspectFill layer.addSublayer(bgImageLayer) } } func createPie() { if ringProgress == 0 { if ringLayer != nil { ringLayer.strokeEnd = 0 } } if ringLayer == nil { ringLayer = CAShapeLayer() layer.addSublayer(ringLayer) let inset = ringThickness / 2 let rectangle = bounds.insetBy(dx: inset, dy: inset) let path = UIBezierPath(ovalIn: rectangle) ringLayer.transform = CATransform3DMakeRotation(-CGFloat.pi / 2, 0, 0, 1) ringLayer.strokeColor = ringColor.cgColor ringLayer.path = path.cgPath ringLayer.fillColor = nil ringLayer.lineWidth = ringThickness ringLayer.strokeStart = 0 } ringLayer.strokeEnd = ringProgress / 100 ringLayer.frame = layer.bounds if percentageLayer == nil { percentageLayer = CATextLayer() layer.addSublayer(percentageLayer) percentageLayer.font = UIFont(name: "HelveticaNeue-Light", size: 80) percentageLayer.frame = CGRect(x: 0, y: 0, width: bounds.size.width, height: percentageLayer.fontSize + 10) percentageLayer.position = CGPoint(x: bounds.midX, y: percentagePosition) percentageLayer.string = "\(Int(ringProgress))%" percentageLayer.alignmentMode = kCAAlignmentCenter percentageLayer.foregroundColor = percentageColor.cgColor percentageLayer.contentsScale = UIScreen.main.scale } } func updateLayerProperties() { if bgLayer != nil { bgLayer.fillColor = bgLayerColor.cgColor } if bgImageLayer != nil { if let image = bgImage { bgImageLayer.contents = image.cgImage } } if ringLayer != nil { ringLayer.strokeEnd = ringProgress / 100 ringLayer.strokeColor = ringColor.cgColor ringLayer.lineWidth = ringThickness } if percentageLayer != nil { if showPercentage == true { percentageLayer.opacity = 1 percentageLayer.string = "\(Int(ringProgress))%" percentageLayer.position = CGPoint(x: bounds.midX, y: percentagePosition) percentageLayer.foregroundColor = percentageColor.cgColor } else { percentageLayer.opacity = 0 } } } }
mit
672adfd1b9dca6394071ade4233f4b96
25.862559
119
0.575688
5.471042
false
false
false
false
Driftt/drift-sdk-ios
Drift/Models/Attachment.swift
2
1977
// // Attachment.swift // Drift // // Created by Brian McDonald on 29/07/2016. // Copyright © 2016 Drift. All rights reserved. // import Alamofire struct Attachment { let id: Int64 let fileName: String let size: Int let mimeType: String let conversationId: Int64 let publicId: String let publicPreviewURL: String? func isImage() -> Bool { return (mimeType.lowercased() == "image/jpeg") || (mimeType.lowercased() == "image/png") || (mimeType.lowercased() == "image/gif") || (mimeType.lowercased() == "image/jpg") } func getAttachmentURL(accessToken: String?) -> URLRequest? { let headers: HTTPHeaders = [ "Authorization": "bearer \(accessToken ?? "")" ] return try? URLRequest(url: URL(string: "https://conversation.api.drift.com/attachments/\(id)/data")!, method: .get, headers: headers) } } func ==(lhs: Attachment, rhs: Attachment) -> Bool { return lhs.id == rhs.id } class AttachmentDTO: Codable, DTO { typealias DataObject = Attachment var id: Int64? var fileName: String? var size: Int? var mimeType: String? var conversationId: Int64? var publicId: String? var publicPreviewURL: String? enum CodingKeys: String, CodingKey { case id = "id" case fileName = "fileName" case size = "size" case mimeType = "mimeType" case conversationId = "conversationId" case publicId = "publicId" case publicPreviewURL = "publicPreviewUrl" } func mapToObject() -> Attachment? { return Attachment(id: id ?? 0, fileName: fileName ?? "", size: size ?? 0, mimeType: mimeType ?? "", conversationId: conversationId ?? 0, publicId: publicId ?? "", publicPreviewURL: publicPreviewURL) } }
mit
c6a3bf2e163473853fa24979323441fe
27.637681
184
0.569332
4.460497
false
false
false
false
nathawes/swift
test/Constraints/fixes.swift
5
17473
// RUN: %target-typecheck-verify-swift func f1() -> Int { } func f2(_: Int = 5) -> Int { } func f3(_: Int...) -> Int { } class A { } class B : A { func iAmAB() {} func createB() -> B { return B() } } func f4() -> B { } func f5(_ a: A) { } func f6(_ a: A, _: Int) { } func createB() -> B { } func createB(_ i: Int) -> B { } func f7(_ a: A, _: @escaping () -> Int) -> B { } func f7(_ a: A, _: Int) -> Int { } // Forgot the '()' to call a function. func forgotCall() { // Simple cases var x: Int x = f1 // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}} x = f2 // expected-error{{cannot assign value of type '(Int) -> Int' to type 'Int'}} x = f3 // expected-error{{cannot assign value of type '(Int...) -> Int' to type 'Int'}} // With a supertype conversion var a = A() a = f4 // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}{{9-9=()}} // As a call f5(f4) // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}{{8-8=()}} f6(f4, f2) // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}{{8-8=()}} // expected-error@-1 {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{12-12=()}} // With overloading: only one succeeds. a = createB // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} let _: A = createB // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} {{21-21=()}} let _: B = createB // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} {{21-21=()}} // With overloading, pick the fewest number of fixes. var b = f7(f4, f1) // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} b.iAmAB() } /// Forgot the '!' to unwrap an optional. func parseInt() -> Int? { } func <(lhs: A, rhs: A) -> A? { return nil } func forgotOptionalBang(_ a: A, obj: AnyObject) { var i: Int = parseInt() // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{26-26= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{26-26=!}} var a = A(), b = B() b = a as? B // expected-error{{value of optional type 'B?' must be unwrapped to a value of type 'B'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{14-14= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{7-7=(}}{{14-14=)!}} a = a < a // expected-error{{value of optional type 'A?' must be unwrapped to a value of type 'A'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{7-7=(}}{{12-12=) ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{7-7=(}}{{12-12=)!}} // rdar://problem/20377684 -- take care that the '!' doesn't fall into an // optional evaluation context let bo: B? = b let b2: B = bo?.createB() // expected-error{{value of optional type 'B?' must be unwrapped to a value of type 'B'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } func forgotAnyObjectBang(_ obj: AnyObject) { var a = A() a = obj // expected-error{{'AnyObject' is not convertible to 'A'; did you mean to use 'as!' to force downcast?}}{{10-10= as! A}} _ = a } func increment(_ x: inout Int) { } func forgotAmpersand() { var i = 5 increment(i) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{13-13=&}} var array = [1,2,3] increment(array[1]) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{13-13=&}} } func maybeFn() -> ((Int) -> Int)? { } func extraCall() { var i = 7 i = i() // expected-error{{cannot call value of non-function type 'Int'}}{{8-10=}} maybeFn()(5) // expected-error{{value of optional type '((Int) -> Int)?' must be unwrapped to a value of type '(Int) -> Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } class U { var prop1 = 0 } class T { func m1() { // <rdar://problem/17741575> let l = self.m2!.prop1 // expected-error@-1 {{method 'm2' was used as a property; add () to call it}} {{22-22=()}} } func m2() -> U! { return U() } } // Used an optional in a conditional expression class C { var a: Int = 1 } var co: C? = nil var ciuo: C! = nil if co {} // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{4-4=(}} {{6-6= != nil)}} if ciuo {} // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{4-4=(}} {{8-8= != nil)}} co ? true : false // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{1-1=(}} {{3-3= != nil)}} !co ? false : true // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{4-4= == nil)}} ciuo ? true : false // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{1-1=(}} {{5-5= != nil)}} !ciuo ? false : true // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{6-6= == nil)}} !co // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{4-4= == nil)}} !ciuo // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{6-6= == nil)}} // Used an integer in a conditional expression var n1: Int = 1 var n2: UInt8 = 0 var n3: Int16 = 2 if n1 {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} {{4-4=(}} {{6-6= != 0)}} if !n1 {} // expected-error {{type 'Int' cannot be used as a boolean; test for '== 0' instead}} {{4-5=}} {{5-5=(}} {{7-7= == 0)}} n1 ? true : false // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} {{1-1=(}} {{3-3= != 0)}} !n1 ? false : true // expected-error {{type 'Int' cannot be used as a boolean; test for '== 0' instead}} {{1-2=}} {{2-2=(}} {{4-4= == 0)}} !n1 // expected-error {{type 'Int' cannot be used as a boolean; test for '== 0' instead}} {{1-2=}} {{2-2=(}} {{4-4= == 0)}} if n2 {} // expected-error {{type 'UInt8' cannot be used as a boolean; test for '!= 0' instead}} {{4-4=(}} {{6-6= != 0)}} !n3 // expected-error {{type 'Int16' cannot be used as a boolean; test for '== 0' instead}} {{1-2=}} {{2-2=(}} {{4-4= == 0)}} // Forgotten ! or ? var someInt = co.a // expected-error{{value of optional type 'C?' must be unwrapped to refer to member 'a' of wrapped base type 'C'}} // expected-note@-1{{chain the optional using '?' to access member 'a' only for non-'nil' base values}}{{17-17=?}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{17-17=!}} // SR-839 struct Q { let s: String? } let q = Q(s: nil) let a: Int? = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}} // expected-error@-1 {{cannot convert value of type 'String.UTF8View?' to specified type 'Int?'}} // expected-note@-2{{chain the optional using '?'}}{{18-18=?}} let b: Int = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}} // expected-error@-1 {{cannot convert value of type 'String.UTF8View' to specified type 'Int'}} // expected-note@-2{{chain the optional using '?'}}{{17-17=?}} // expected-note@-3{{force-unwrap using '!'}}{{17-17=!}} let d: Int! = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}} // expected-error@-1 {{cannot convert value of type 'String.UTF8View?' to specified type 'Int?'}} // expected-note@-2{{chain the optional using '?'}}{{18-18=?}} let c = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}} // expected-note@-1{{chain the optional using '?' to access member 'utf8' only for non-'nil' base values}}{{12-12=?}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{12-12=!}} // SR-1116 struct S1116 { var s: Int? } let a1116: [S1116] = [] var s1116 = Set(1...10).subtracting(a1116.map({ $0.s })) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{53-53= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{53-53=!}} func makeArray<T>(_ x: T) -> [T] { [x] } func sr12399(_ x: Int?) { _ = Set(0...10).subtracting(makeArray(x)) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{42-42= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{42-42=!}} } func moreComplexUnwrapFixes() { struct S { let value: Int let optValue: Int? = nil } struct T { let s: S let optS: S? } func takeNon(_ x: Int) -> Void {} func takeOpt(_ x: Int?) -> Void {} let s = S(value: 0) let t: T? = T(s: s, optS: nil) let os: S? = s takeOpt(os.value) // expected-error{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}} // expected-note@-1{{chain the optional using '?'}}{{13-13=?}} takeNon(os.value) // expected-error{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}} // expected-note@-1{{chain the optional using '?'}}{{13-13=?}} // expected-note@-2{{force-unwrap using '!'}}{{13-13=!}} // FIXME: Ideally we'd recurse evaluating chaining fixits instead of only offering just the unwrap of t takeOpt(t.s.value) // expected-error{{value of optional type 'T?' must be unwrapped to refer to member 's' of wrapped base type 'T'}} // expected-note@-1{{chain the optional using '?'}}{{12-12=?}} // expected-note@-2{{force-unwrap using '!'}}{{12-12=!}} takeOpt(t.optS.value) // expected-error{{value of optional type 'T?' must be unwrapped to refer to member 'optS' of wrapped base type 'T'}} // expected-note@-1{{chain the optional using '?'}}{{12-12=?}} // expected-error@-2{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}} // expected-note@-3{{chain the optional using '?'}}{{17-17=?}} takeNon(t.optS.value) // expected-error{{value of optional type 'T?' must be unwrapped to refer to member 'optS' of wrapped base type 'T'}} // expected-note@-1{{chain the optional using '?'}}{{12-12=?}} // expected-error@-2{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}} // expected-note@-3{{chain the optional using '?'}}{{17-17=?}} // expected-note@-4{{force-unwrap using '!'}}{{17-17=!}} takeNon(os?.value) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap using '!'}}{{13-14=!}} // expected-note@-2{{coalesce}} takeNon(os?.optValue) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap using '!'}}{{11-11=(}} {{23-23=)!}} // expected-note@-2{{coalesce}} func sample(a: Int?, b: Int!) { let aa = a // expected-note@-1{{short-circuit using 'guard'}}{{5-5=guard }} {{15-15= else \{ return \}}} // expected-note@-2{{force-unwrap}} // expected-note@-3{{coalesce}} let bb = b // expected-note{{value inferred to be type 'Int?' when initialized with an implicitly unwrapped value}} // expected-note@-1{{short-circuit using 'guard'}}{{5-5=guard }} {{15-15= else \{ return \}}} // expected-note@-2{{force-unwrap}} // expected-note@-3{{coalesce}} let cc = a takeNon(aa) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}} takeNon(bb) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}} _ = [].map { takeNon(cc) } // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}} takeOpt(cc) } func sample2(a: Int?) -> Int { let aa = a // expected-note@-1{{short-circuit using 'guard'}}{{5-5=guard }} {{15-15= else \{ return <#default value#> \}}} // expected-note@-2{{force-unwrap}} // expected-note@-3{{coalesce}} return aa // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}} } } struct FooStruct { func a() -> Int?? { return 10 } var b: Int?? { return 15 } func c() -> Int??? { return 20 } var d: Int??? { return 25 } let e: BarStruct? = BarStruct() func f() -> Optional<Optional<Int>> { return 29 } } struct BarStruct { func a() -> Int? { return 30 } var b: Int?? { return 35 } } let thing: FooStruct? = FooStruct() let _: Int? = thing?.a() // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int? = thing?.b // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int?? = thing?.c() // expected-error {{value of optional type 'Int???' must be unwrapped to a value of type 'Int??'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int?? = thing?.d // expected-error {{value of optional type 'Int???' must be unwrapped to a value of type 'Int??'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int = thing?.e?.a() // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int? = thing?.e?.b // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int? = thing?.f() // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} // SR-9851 - https://bugs.swift.org/browse/SR-9851 func coalesceWithParensRootExprFix() { let optionalBool: Bool? = false if !optionalBool { } // expected-error{{value of optional type 'Bool?' must be unwrapped to a value of type 'Bool'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{7-7=(}}{{19-19= ?? <#default value#>)}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } func test_explicit_call_with_overloads() { func foo(_: Int) {} struct S { func foo(_: Int) -> Int { return 0 } func foo(_: Int = 32, _: String = "hello") -> Int { return 42 } } foo(S().foo) // expected-error@-1 {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{14-14=()}} } // SR-11476 func testKeyPathSubscriptArgFixes(_ fn: @escaping () -> Int) { struct S { subscript(x: Int) -> Int { x } } var i: Int? _ = \S.[i] // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{12-12= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{12-12=!}} _ = \S.[nil] // expected-error {{'nil' is not compatible with expected argument type 'Int'}} _ = \S.[fn] // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{13-13=()}} } func sr12426(a: Any, _ str: String?) { a == str // expected-error {{binary operator '==' cannot be applied to operands of type 'Any' and 'String?'}} // expected-note@-1 {{overloads for '==' exist with these partially matching parameter lists: (CodingUserInfoKey, CodingUserInfoKey), (String, String)}} }
apache-2.0
2d8e2add16ec12084afceb20cfb4b965
47.267956
154
0.626109
3.406043
false
false
false
false
wess/overlook
Sources/watch/watch.swift
1
2788
// // watch.swift // overlook // // Created by Wesley Cope on 9/30/16. // // import Foundation fileprivate class FileWatch { fileprivate static let instance = FileWatch() fileprivate var excluding:[String] = [] fileprivate var context = FSEventStreamContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) fileprivate let flags = UInt32(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents) fileprivate let callback: FSEventStreamCallback = { (streamRef, userInfo, numEvents, eventPaths, eventFlags, eventIds) -> Void in guard let paths = unsafeBitCast(eventPaths, to: NSArray.self) as? [String], let path = paths.first else { return } let excludes = FileWatch.instance.excluding let filename = path.components(separatedBy: "/").last ?? "" let filtered = excludes.filter { $0.lowercased() == filename.lowercased() } guard filtered.count < 1 else { return } DispatchQueue.main.async { FileWatch.instance.stop() FileWatch.instance.handler() FileWatch.instance.start(FileWatch.instance.paths, queue: FileWatch.instance.queue, callback: FileWatch.instance.handler) } } fileprivate var handler:(() -> ()) = {} fileprivate var stream:FSEventStreamRef? fileprivate var isRunning = false fileprivate var paths:[String] = [] fileprivate var queue:DispatchQueue = DispatchQueue.global() fileprivate func start(_ paths:[String], queue:DispatchQueue, callback:@escaping () -> ()) { guard isRunning == false else { return } self.paths = paths self.queue = queue self.handler = callback self.stream = FSEventStreamCreate(kCFAllocatorDefault, FileWatch.instance.callback, &context, (paths as CFArray), FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 0, flags) if let stream = stream { FSEventStreamSetDispatchQueue(stream, queue) FSEventStreamStart(stream) isRunning = true } } fileprivate func stop() { guard let stream = stream, isRunning == true else { return } FSEventStreamStop(stream) FSEventStreamInvalidate(stream) FSEventStreamRelease(stream) self.stream = nil isRunning = false } fileprivate func cleanPath(path:String) -> String { return "" } init() {} } public func Watch(_ paths:[String], exclude:[String] = [], queue:DispatchQueue = DispatchQueue.global(), callback:@escaping (() -> ())) { FileWatch.instance.excluding = exclude FileWatch.instance.start(paths, queue: queue, callback: callback) } public func Watch(stop:Bool) { guard stop == true else { return } FileWatch.instance.stop() }
mit
30e4db3a917415f7434ee65062ad2455
31.418605
181
0.667504
4.525974
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/2 - Primitives/Input.swift
1
13191
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import SwiftUI /// Textfield Input from the Figma Component Library. /// /// # Usage: /// /// The actual final layout of this input depends on the parameters assigned on initialization. /// label, subText, prefix, and trailing are optional parameters. /// /// Input( /// text: $text, /// isFirstResponder: $isFirstResponder, /// subText: "Your password is not long enough", /// subTextStyle: .error, /// placeholder: "Password", /// state: .error, /// configuration: { textField in /// textField.isSecureTextEntry = true /// } /// ) { /// Icon.eye /// } /// /// /// # Figma /// /// [Input](https://www.figma.com/file/nlSbdUyIxB64qgypxJkm74/03---iOS-%7C-Shared?node-id=377%3A8112) public struct Input<Trailing: View>: View { #if canImport(UIKit) public typealias Configuration = (UITextField) -> Void #else public typealias Configuration = (()) -> Void #endif @Binding private var text: String @Binding private var isFirstResponder: Bool private let label: String? private let subText: String? private let subTextStyle: InputSubTextStyle private let placeholder: String? private let characterLimit: Int? private let prefix: String? private let state: InputState private let configuration: Configuration private let trailing: Trailing private let onReturnTapped: () -> Void @Environment(\.isEnabled) private var isEnabled /// TextField Input Component /// - Parameters: /// - text: The text to display and edit /// - isFirstResponder: Whether the textfield is focused /// - label: Optional text displayed above the textfield /// - subText: Optional text displayed below the textfield /// - subTextStyle: Styling of the text displayed below the textfield, See `InputSubTextStyle` /// - placeholder: Placeholder text displayed when `text` is empty. /// - prefix: Optional text displayed on the leading side of the text field /// - state: Error state overrides the border color. /// - configuration: Closure to configure specifics of `UITextField` /// - trailing: Optional trailing view, intended to contain `Icon` or `IconButton`. /// - onReturnTapped: Closure executed when the user types the return key public init( text: Binding<String>, isFirstResponder: Binding<Bool>, label: String? = nil, subText: String? = nil, subTextStyle: InputSubTextStyle = .default, placeholder: String? = nil, characterLimit: Int? = nil, prefix: String? = nil, state: InputState = .default, configuration: @escaping Configuration = { _ in }, @ViewBuilder trailing: @escaping () -> Trailing, onReturnTapped: @escaping () -> Void = {} ) { _text = text _isFirstResponder = isFirstResponder self.label = label self.subText = subText self.subTextStyle = subTextStyle self.placeholder = placeholder self.characterLimit = characterLimit self.prefix = prefix self.state = state self.configuration = configuration self.trailing = trailing() self.onReturnTapped = onReturnTapped } public var body: some View { VStack(alignment: .leading, spacing: 0) { label.map(Text.init)? .typography(.paragraph2) .foregroundColor(Color(light: .semantic.title, dark: .palette.grey100)) .padding(.bottom, 8) .padding(.top, 9) HStack(alignment: .center, spacing: 16) { prefix.map(Text.init)? .typography(.paragraph2) .foregroundColor(Color(light: .semantic.muted, dark: .palette.grey600)) #if canImport(UIKit) FocusableTextField( text: $text, isFirstResponder: $isFirstResponder, characterLimit: characterLimit, configuration: { textField in textField.font = Typography.bodyMono.uiFont textField.textColor = UIColor(textColor) textField.tintColor = UIColor(.semantic.primary) textField.attributedPlaceholder = placeholder.map { NSAttributedString( string: $0, attributes: [ .font: Typography.bodyMono.uiFont as Any, .foregroundColor: UIColor(placeholderColor) ] ) } configuration(textField) }, onReturnTapped: onReturnTapped ) .frame(minHeight: 24) #else TextField("", text: $text) .frame(minHeight: 24) #endif trailing .frame(width: 24, height: 24) .accentColor(Color(light: .palette.grey400, dark: .palette.grey400)) } .padding(.horizontal, 16) .padding(.vertical, 12) .background( ZStack { RoundedRectangle(cornerRadius: Spacing.buttonBorderRadius) .fill(backgroundColor) RoundedRectangle(cornerRadius: Spacing.buttonBorderRadius) .stroke(borderColor, lineWidth: 1) } ) subText.map(Text.init)? .typography(.caption1) .foregroundColor(subTextStyle.foregroundColor) .padding(.top, 5) .padding(.bottom, 6) } .contentShape(Rectangle()) .onTapGesture { isFirstResponder = true } } } extension Input where Trailing == EmptyView { /// Create a Textfield Input component without a trailing view /// - Parameters: /// - text: The text to display and edit /// - isFirstResponder: Whether the textfield is focused /// - label: Optional text displayed above the textfield /// - subText: Optional text displayed below the textfield /// - subTextStyle: Styling of the text displayed below the textfield, See `InputSubTextStyle` /// - placeholder: Placeholder text displayed when `text` is empty. /// - prefix: Optional text displayed on the leading side of the text field /// - state: Error state overrides the border color. /// - configuration: Closure to configure specifics of `UITextField` /// - onReturnTapped: Closure executed when the user types the return key public init( text: Binding<String>, isFirstResponder: Binding<Bool>, label: String? = nil, subText: String? = nil, subTextStyle: InputSubTextStyle = .default, placeholder: String? = nil, characterLimit: Int? = nil, prefix: String? = nil, state: InputState = .default, configuration: @escaping Configuration = { _ in }, onReturnTapped: @escaping () -> Void = {} ) { self.init( text: text, isFirstResponder: isFirstResponder, label: label, subText: subText, subTextStyle: subTextStyle, placeholder: placeholder, characterLimit: characterLimit, prefix: prefix, state: state, configuration: configuration, trailing: { EmptyView() }, onReturnTapped: onReturnTapped ) } } /// Override for the border color of `Input` public struct InputState: Equatable { let borderColor: Color? /// Default border colors, changing based on focus public static let `default` = Self(borderColor: nil) /// A red border color in all focus states public static let error = Self(borderColor: .semantic.error) /// A green border color in all focus states public static let success = Self(borderColor: .semantic.success) } /// Text style of the subtext below the text field in `Input` public struct InputSubTextStyle { let foregroundColor: Color /// Default subtext style, grey text. public static let `default` = Self(foregroundColor: Color(light: .palette.grey600, dark: .palette.grey300)) /// Primary styles the text using Color.semantic.primary public static let primary = Self(foregroundColor: .semantic.primary) /// Success subtext style, green text public static let success = Self(foregroundColor: .semantic.success) /// Error subtext style, red text public static let error = Self(foregroundColor: .semantic.error) } extension Input { // MARK: Colors private var backgroundColor: Color { if !isEnabled { return Color(light: .semantic.medium, dark: .palette.dark800) } else { return .semantic.background } } private var borderColor: Color { if let color = state.borderColor { return color } else if !isEnabled { return .semantic.medium } else if isFirstResponder { return .semantic.primary } else { return .semantic.medium } } private var textColor: Color { if !isEnabled { return placeholderColor } else { return .semantic.title } } private var placeholderColor: Color { Color(light: .semantic.muted, dark: .palette.grey600) } } struct Input_Previews: PreviewProvider { static var previews: some View { Input( text: .constant(""), isFirstResponder: .constant(false), label: "Label Title", subText: "Error text to help explain a bit more", placeholder: "Placeholder" ) { Icon.placeholder } .previewLayout(.sizeThatFits) .previewDisplayName("Field") PreviewContainer( text: .constant(""), isFirstResponder: .constant(false), state: .default ) .previewLayout(.sizeThatFits) .previewDisplayName("Placeholder") PreviewContainer( text: .constant(""), isFirstResponder: .constant(true), state: .default ) .previewLayout(.sizeThatFits) .previewDisplayName("Placeholder Focused") PreviewContainer( text: .constant("Blockchain"), isFirstResponder: .constant(false), state: .default ) .previewLayout(.sizeThatFits) .previewDisplayName("Value Added") PreviewContainer( text: .constant("Blockchain"), isFirstResponder: .constant(true), state: .default ) .previewLayout(.sizeThatFits) .previewDisplayName("Value Added Focused") PreviewContainer( text: .constant("Blockchain"), isFirstResponder: .constant(false), state: .error ) .previewLayout(.sizeThatFits) .previewDisplayName("Error") PreviewContainer( text: .constant("Blockchain"), isFirstResponder: .constant(true), state: .error ) .previewLayout(.sizeThatFits) .previewDisplayName("Error Focused") PreviewContainer( text: .constant("Blockchain"), isFirstResponder: .constant(false), state: .success ) .previewLayout(.sizeThatFits) .previewDisplayName("Success") PreviewContainer( text: .constant("Blockchain"), isFirstResponder: .constant(true), state: .success ) .previewLayout(.sizeThatFits) .previewDisplayName("Success Focused") PreviewContainer( text: .constant("Blockchain"), isFirstResponder: .constant(false), state: .default ) .disabled(true) .previewLayout(.sizeThatFits) .previewDisplayName("Disabled") } struct PreviewContainer: View { @Binding var text: String @Binding var isFirstResponder: Bool let state: InputState var body: some View { VStack { Input( text: $text, isFirstResponder: $isFirstResponder, placeholder: "Placeholder", prefix: nil, state: state ) { Icon.placeholder } Input( text: .constant(text.isEmpty ? "" : "100"), isFirstResponder: $isFirstResponder, placeholder: "0", prefix: "USD", state: state ) } } } }
lgpl-3.0
dfe30bc8e641c84b467e3e8da1de791c
32.820513
111
0.565049
5.19087
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Core/Accessibility+SimpleBuy.swift
1
1208
// Copyright © Blockchain Luxembourg S.A. All rights reserved. extension Accessibility.Identifier { public enum SimpleBuy { enum PaymentMethodsScreen { private static let prefix = "PaymentMethods." static let addCard = "\(prefix)AddCard" static let addBank = "\(prefix)AddBank" static let bankTransfer = "\(prefix)BankTransfer" static let linkedBank = "\(prefix)LinkedBank" static let useApplePay = "\(prefix)ApplePay" } public enum TransferDetails { private static let prefix = "TransferDetails." public static let lineItemPrefix = prefix public static let titleLabel = "\(prefix)titleLabel" public static let descriptionLabel = "\(prefix)descriptionLabel" public static let disclaimerLabel = "\(prefix)disclaimerLabel" public static let disclaimerImage = "\(prefix)disclaimerImage" } public enum KYCScreen { public static let titleLabel = "titleLabel" public static let subtitleLabel = "subtitleLabel" public static let goToWalletButton = "goToWalletButton" } } }
lgpl-3.0
313bf2228bb240f972c3735142a7ff34
37.935484
76
0.62966
5.536697
false
false
false
false
PeeJWeeJ/SwiftyDevice
SwiftyDevice/UIDevice+Hardware.swift
1
2182
// // UIDevice+Hardware.swift // SwiftyDevice // // Created by Paul Fechner on 9/14/16. // Copyright © 2016 PeeJWeeJ. All rights reserved. // import UIKit import SystemConfiguration extension UIDevice { public static var deviceLine: DeviceLine { return DeviceLine.make(from: machineInfoName) } public static var isPhoneIdiom: Bool { return current.userInterfaceIdiom == .phone } public static var isRetina: Bool { return UIScreen.main.scale == 2.0 } public static var isIPod: Bool { switch deviceLine { case .iPod(_): return true default: return false } } public static var machineInfoName: String { return hardwareString() } public static var cpuFrequency: Int { return systemInfo(for: HW_CPU_FREQ) } public static var busFrequency: Int { return systemInfo(for: HW_BUS_FREQ) } public static var totalMemory: Int { return systemInfo(for: HW_MEMSIZE) } public static var userMemory: Int { return systemInfo(for: HW_USERMEM) } public static var maxSocketBufferSize: Int { return systemInfo(for: KIPC_MAXSOCKBUF) } public static var totalDiskSpace: Float? { guard let attributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) else { return nil } return attributes[FileAttributeKey.systemSize] as? Float } public static var freeDiskSpace: Float? { guard let attributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) else { return nil } return attributes[FileAttributeKey.systemFreeSize] as? Float } fileprivate static func hardwareString() -> String { var name: [Int32] = [CTL_HW, HW_MACHINE] var size: Int = 2 sysctl(&name, 2, nil, &size, &name, 0) var hw_machine = [CChar](repeating: 0, count: Int(size)) sysctl(&name, 2, &hw_machine, &size, &name, 0) let hardware: String = String(validatingUTF8: hw_machine)! return hardware } fileprivate static func systemInfo(for key: Int32) -> Int { var name: [Int32] = [CTL_HW, key] var size: Int = 2 sysctl(&name, 2, nil, &size, &name, 0) var value = [Int](repeating: 0, count: Int(size)) sysctl(&name, 2, &value, &size, &name, 0) return value[0] } }
apache-2.0
9049e3c2afe3aa32258fcccc6d0275b1
21.71875
107
0.703806
3.240713
false
false
false
false
imkevinxu/Spring
Spring/SpringImageView.swift
1
2977
// // SpringImageView.swift // https://github.com/MengTo/Spring // // The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit public class SpringImageView: UIImageView, Springable { // MARK: Advanced Values @IBInspectable public var animation: String = "" @IBInspectable public var curve: String = "" @IBInspectable public var autostart: Bool = false @IBInspectable public var autohide: Bool = false @IBInspectable public var delay: CGFloat = 0 @IBInspectable public var duration: CGFloat = 0.7 @IBInspectable public var force: CGFloat = 1 @IBInspectable public var damping: CGFloat = 0.7 @IBInspectable public var velocity: CGFloat = 0.7 @IBInspectable public var rotateDegrees: CGFloat = 0 @IBInspectable public var repeatCount: Float = 1 // MARK: Basic Values @IBInspectable public var x: CGFloat = 0 @IBInspectable public var y: CGFloat = 0 @IBInspectable public var scaleX: CGFloat = 1 @IBInspectable public var scaleY: CGFloat = 1 @IBInspectable public var rotate: CGFloat = 0 public var opacity: CGFloat = 1 public var animateFrom: Bool = false lazy private var spring: Spring = Spring(self) // MARK: - View Lifecycle override public func awakeFromNib() { super.awakeFromNib() self.spring.customAwakeFromNib() } override public func didMoveToWindow() { super.didMoveToWindow() self.spring.customDidMoveToWindow() } // MARK: - Animation Methods public func animate() { self.spring.animate() } public func animateNext(completion: () -> ()) { self.spring.animateNext(completion) } public func animateTo() { self.spring.animateTo() } public func animateToNext(completion: () -> ()) { self.spring.animateToNext(completion) } }
mit
ecc548f077e60725055bab888f6af59b
33.229885
82
0.701041
4.531202
false
false
false
false
Jnosh/swift
test/Frontend/dependencies.swift
5
4174
// XFAIL: linux // RUN: rm -rf %t && mkdir -p %t // RUN: %target-swift-frontend -emit-dependencies-path - -typecheck %S/../Inputs/empty\ file.swift | %FileCheck -check-prefix=CHECK-BASIC %s // RUN: %target-swift-frontend -emit-reference-dependencies-path - -typecheck -primary-file %S/../Inputs/empty\ file.swift | %FileCheck -check-prefix=CHECK-BASIC-YAML %s // RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck -primary-file %S/../Inputs/empty\ file.swift // RUN: %FileCheck -check-prefix=CHECK-BASIC %s < %t.d // RUN: %FileCheck -check-prefix=CHECK-BASIC-YAML %s < %t.swiftdeps // CHECK-BASIC-LABEL: - : // CHECK-BASIC: Inputs/empty\ file.swift // CHECK-BASIC: Swift.swiftmodule // CHECK-BASIC-NOT: : // CHECK-BASIC-YAML-LABEL: depends-external: // CHECK-BASIC-YAML-NOT: empty\ file.swift // CHECK-BASIC-YAML: "{{.*}}/Swift.swiftmodule" // CHECK-BASIC-YAML-NOT: {{:$}} // RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck %S/../Inputs/empty\ file.swift 2>&1 | %FileCheck -check-prefix=NO-PRIMARY-FILE %s // NO-PRIMARY-FILE: warning: ignoring -emit-reference-dependencies (requires -primary-file) // RUN: %target-swift-frontend -emit-dependencies-path - -emit-module %S/../Inputs/empty\ file.swift -o %t/empty\ file.swiftmodule -emit-module-doc-path %t/empty\ file.swiftdoc -emit-objc-header-path %t/empty\ file.h | %FileCheck -check-prefix=CHECK-MULTIPLE-OUTPUTS %s // CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftmodule : // CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift // CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule // CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftdoc : // CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift // CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule // CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.h : // CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift // CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule // CHECK-MULTIPLE-OUTPUTS-NOT: : // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -typecheck %s | %FileCheck -check-prefix=CHECK-IMPORT %s // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-reference-dependencies-path - -typecheck -primary-file %s | %FileCheck -check-prefix=CHECK-IMPORT-YAML %s // CHECK-IMPORT-LABEL: - : // CHECK-IMPORT: dependencies.swift // CHECK-IMPORT-DAG: Swift.swiftmodule // CHECK-IMPORT-DAG: Inputs/dependencies/$$$$$$$$$$.h // CHECK-IMPORT-DAG: Inputs/dependencies/UserClangModule.h // CHECK-IMPORT-DAG: Inputs/dependencies/extra-header.h // CHECK-IMPORT-DAG: Inputs/dependencies/module.modulemap // CHECK-IMPORT-DAG: ObjectiveC.swift // CHECK-IMPORT-DAG: Foundation.swift // CHECK-IMPORT-DAG: CoreGraphics.swift // CHECK-IMPORT-NOT: : // CHECK-IMPORT-YAML-LABEL: depends-external: // CHECK-IMPORT-YAML-NOT: dependencies.swift // CHECK-IMPORT-YAML-DAG: "{{.*}}/Swift.swiftmodule" // CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/$$$$$.h" // CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/UserClangModule.h" // CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/extra-header.h" // CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/module.modulemap" // CHECK-IMPORT-YAML-DAG: "{{.*}}/ObjectiveC.swift" // CHECK-IMPORT-YAML-DAG: "{{.*}}/Foundation.swift" // CHECK-IMPORT-YAML-DAG: "{{.*}}/CoreGraphics.swift" // CHECK-IMPORT-YAML-NOT: {{^-}} // CHECK-IMPORT-YAML-NOT: {{:$}} // RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -typecheck %s | %FileCheck -check-prefix=CHECK-IMPORT %s // RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-reference-dependencies-path - -typecheck -primary-file %s | %FileCheck -check-prefix=CHECK-IMPORT-YAML %s import Foundation import UserClangModule class Test: NSObject {} _ = A() _ = USER_VERSION _ = EXTRA_VERSION _ = MONEY #if ERROR _ = someRandomUndefinedName #endif
apache-2.0
7f75187a22ce68f8e0ffed9bbe5a16fa
48.105882
269
0.726162
3.243201
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/TextNoteCardView.swift
1
12121
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_Palettes_Palettes import third_party_objective_c_material_components_ios_components_Typography_Typography /// A subclass of UITextView that overrides point(inside:with:) to ensure taps do one of two things, /// depending on where in the view they occur: /// /// 1. If they occur on a link, they are allowed (return true) and the data detector system will /// correctly open the URL as expected. /// 2. If they occur anywhere else, they are not allowed (return false) and the cell in which this /// view is contained will properly receive the didSelectItemAt delegate call. /// /// Without this change, and with UITextView's requirement of isSelectable being true for links to /// work, text in our TextNote cells would be selectable and tapping cells would not take you to /// the detail view as expected. class GSJNoteTextView: UITextView { override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let leftDirection = UITextDirection(rawValue: UITextLayoutDirection.left.rawValue) guard let position = closestPosition(to: point), let range = tokenizer.rangeEnclosingPosition(position, with: .character, inDirection: leftDirection) else { return false } let startIndex = offset(from: beginningOfDocument, to: range.start) return attributedText.attribute(NSAttributedString.Key.link, at: startIndex, effectiveRange: nil) != nil } } /// A view composed of a text note's data, which includes the text of the note and the values of the /// sensors when this note was taken. This view can be used inside a trial card or inside a /// snapshot card, both in Experiment detail views. Timestamp is optional. class TextNoteCardView: ExperimentCardView { // MARK: - Constants /// Font size for the text view. Used in view height calculation. static let textFontSize: CGFloat = 16.0 /// Font size for the value snapshots label. Used in view height calculation. static let valueSnapshotsFontSize: CGFloat = 12.0 // MARK: - Properties /// The text note to display. var textNote: DisplayTextNote? { didSet { updateViewForTextNote() } } private let preferredMaxLayoutWidth: CGFloat private let showTimestamp: Bool private let snapshotsLabel = UILabel() private let textView = GSJNoteTextView() // Accessibility wrapping view allowing the text to be read as well as the timestamp, without // breaking the outer view. private let accessibilityWrappingView = UIView() // MARK: - Public /// Initialize a Text Note card view with a display text note object and give it a preferred max /// layout width that informs the view's intrinsic content size. /// /// - Parameters: /// - textNote: The display text note to use in this view. /// - preferredMaxLayoutWidth: The layout width to use in this view's intrinsic content size. /// - showTimestamp: Should the relative timestamp be shown? init(textNote: DisplayTextNote, preferredMaxLayoutWidth: CGFloat, showTimestamp: Bool = false) { self.textNote = textNote self.showTimestamp = showTimestamp self.preferredMaxLayoutWidth = preferredMaxLayoutWidth super.init(frame: .zero) configureView() } override required init(frame: CGRect) { fatalError("init(frame:) is not supported") } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } /// Calculates the height required to display this view, given the data provided. /// /// - Parameters: /// - textNote: The data with which to calculate view height. /// - showingTimestamp: Should the relative timestamp be measured? /// - width: Maximum width for this view, used to constrain measurements. /// - Returns: The total height of this view. Ideally, controllers would cache this value as it /// will not change for different instances of this view type. static func heightForTextNote(_ textNote: DisplayTextNote, showingTimestamp: Bool, inWidth width: CGFloat) -> CGFloat { // Constrained width, including padding. let constrainedWidth = width - ExperimentCardView.horizontalPaddingTotal // If necessary, measure the width of the timestamp to further constrain the width of the labels // measured here. Add the spacing between the timestamp and the text as well. var timestampMeasure: CGFloat = 0 if showingTimestamp { timestampMeasure = ceil(textNote.timestamp.string.labelWidth( font: MDCTypography.fontLoader().regularFont( ofSize: TextNoteCardView.timestampFontSize))) + ExperimentCardView.innerHorizontalPadding } // Measure the height of the text, constraining it to `width`. var totalHeight = textNote.text.labelHeight(withConstrainedWidth: constrainedWidth - timestampMeasure, font: MDCTypography.fontLoader().regularFont( ofSize: TextNoteCardView.textFontSize)) if let valueSnapshots = textNote.valueSnapshots { // Add the vertical spacing between the labels. totalHeight += ExperimentCardView.innerLabelsSpacing // Measure the height of the snapshots. totalHeight += valueSnapshots.labelHeight( withConstrainedWidth: constrainedWidth - timestampMeasure, font: MDCTypography.fontLoader().regularFont( ofSize: TextNoteCardView.valueSnapshotsFontSize)) } // Add the vertical padding on top and bottom of the cell. totalHeight += (ExperimentCardView.innerVerticalPadding * 2) return totalHeight } override var intrinsicContentSize: CGSize { guard let textNote = textNote else { return .zero } return CGSize(width: UIView.noIntrinsicMetric, height: TextNoteCardView.heightForTextNote(textNote, showingTimestamp: showTimestamp, inWidth: preferredMaxLayoutWidth)) } override func sizeThatFits(_ size: CGSize) -> CGSize { guard let textNote = textNote else { return .zero } return CGSize(width: size.width, height: TextNoteCardView.heightForTextNote(textNote, showingTimestamp: showTimestamp, inWidth: size.width)) } // Performance on older devices is too poor with auto layout, so use frames to lay out this // view. override func layoutSubviews() { super.layoutSubviews() var timestampLabelFrame: CGRect = .zero if showTimestamp { timestampLabel.sizeToFit() timestampLabelFrame = timestampLabel.frame } // Calculate the offset the timestamp creates in widths for the text and value snapshots. let timestampWidthOffset = timestampLabelFrame.size.width + (ExperimentCardView.innerHorizontalPadding * (timestampLabelFrame.size.width > 0 ? 3 : 2)) // Lay out the text view. var textHeight: CGFloat = 0 if let textNote = textNote { textHeight = textNote.text.labelHeight( withConstrainedWidth: bounds.size.width - timestampWidthOffset, font: MDCTypography.fontLoader().regularFont( ofSize: TextNoteCardView.textFontSize)) } textView.frame = CGRect(x: bounds.minX + ExperimentCardView.innerHorizontalPadding, y: bounds.minY + ExperimentCardView.innerVerticalPadding, width: bounds.size.width - timestampWidthOffset, height: textHeight) // Lay out the value snapshots, if necessary. if let textNote = textNote, let valueSnapshots = textNote.valueSnapshots { let valueHeight = valueSnapshots.labelHeight( withConstrainedWidth: bounds.size.width - timestampWidthOffset, font: MDCTypography.fontLoader().regularFont( ofSize: TextNoteCardView.valueSnapshotsFontSize)) snapshotsLabel.frame = CGRect(x: bounds.minX + ExperimentCardView.innerHorizontalPadding, y: textView.frame.maxY + ExperimentCardView.innerLabelsSpacing, width: bounds.size.width - timestampWidthOffset, height: valueHeight) } // Lay out the timestamp, if necessary. if showTimestamp { timestampLabel.frame = CGRect(x: bounds.maxX - ExperimentCardView.innerHorizontalPadding - timestampLabelFrame.size.width, y: textView.frame.minY, width: timestampLabelFrame.size.width, height: timestampLabelFrame.size.height) } } override func reset() { textNote = nil textView.text = nil snapshotsLabel.text = nil timestampLabel.text = nil accessibilityWrappingView.accessibilityLabel = nil } // MARK: - Private private func configureView() { // Text view. addSubview(textView) textView.textColor = .black textView.font = MDCTypography.fontLoader().regularFont(ofSize: TextNoteCardView.textFontSize) textView.textContainerInset = .zero textView.textContainer.lineFragmentPadding = 0 textView.isScrollEnabled = false textView.isEditable = false textView.dataDetectorTypes = .link textView.isAccessibilityElement = false let linkTextAttributes: [NSAttributedString.Key : Any] = [ NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): MDCPalette.blue.tint500, NSAttributedString.Key(rawValue: NSAttributedString.Key.underlineStyle.rawValue): NSUnderlineStyle.single.rawValue, NSAttributedString.Key(rawValue: NSAttributedString.Key.underlineColor.rawValue): MDCPalette.blue.tint200 ] textView.linkTextAttributes = linkTextAttributes // Value snapshots label. snapshotsLabel.textColor = MDCPalette.grey.tint500 snapshotsLabel.font = MDCTypography.fontLoader().regularFont( ofSize: TextNoteCardView.valueSnapshotsFontSize) // Timestamp, if necessary. if showTimestamp { addSubview(timestampLabel) timestampLabel.isAccessibilityElement = true timestampLabel.accessibilityTraits = .staticText } // Accessibility wrapping view. configureAccessibilityWrappingView(accessibilityWrappingView, traits: .staticText) updateViewForTextNote() } private func updateViewForTextNote() { guard let textNote = textNote else { return } // Text view. textView.text = textNote.text // Value snapshots label. if let valueSnapshots = textNote.valueSnapshots { addSubview(snapshotsLabel) snapshotsLabel.text = valueSnapshots } else { snapshotsLabel.removeFromSuperview() } // Timestamp, if necessary. if showTimestamp { timestampLabel.text = textNote.timestamp.string } // Accessibility wrapping view. accessibilityWrappingView.accessibilityLabel = textNote.text setNeedsLayout() } }
apache-2.0
c930d72f51143e6f9422012b1729c0dc
40.368601
100
0.674614
5.088581
false
false
false
false
slepcat/mint-lisp
mint-lisp/mintlisp_util.swift
1
3665
// // mintlisp_util.swift // mint-lisp // // Created by NemuNeko on 2015/08/01. // Copyright (c) 2015年 Taizo A. All rights reserved. // import Foundation func foldl<T>(_ _func: (T, T) -> T, acc: T, operands: [T]) -> T{ if operands.count == 0 { return acc } else { var acc = acc var operands = operands let head = operands.remove(at: 0) acc = _func(acc, head) return foldl(_func, acc: acc, operands: operands) } } func map<T, U>(_ _func: (T) -> U, operands: [T]) -> [U] { return tail_map(_func, acc: [], operands: operands) } private func tail_map<T, U>(_ _func: (T) -> U, acc: [U], operands: [T]) -> [U] { if operands.count == 0 { return acc } else { var acc = acc var operands = operands let head = operands.remove(at: 0) acc.append(_func(head)) return tail_map(_func,acc: acc, operands: operands) } } func flatMap<T, U>(_ operands: [T],f: (T) -> [U]) -> [U] { let nestedList = tail_map(f, acc: [], operands: operands) return flatten(nestedList) } private func flatten<U>(_ nested:[[U]]) -> [U] { return tail_flatten(nested, acc: []) } private func tail_flatten<U>(_ nested:[[U]], acc:[U]) -> [U] { if nested.count == 0 { return acc } else { var nested = nested let head = nested.remove(at: 0) let newacc = head + acc return tail_flatten(nested, acc: newacc) } } func _and(_ a :Bool, b: Bool) -> Bool { return (a && b) } func _or(_ a :Bool, b: Bool) -> Bool { return (a || b) } ///// Utilities ///// public func delayed_list_of_args(_ _opds :SExpr) -> [SExpr] { return delayed_list_of_values(_opds) } public func delayed_list_of_values(_ _opds :SExpr) -> [SExpr] { if let atom = _opds as? Atom { return [atom] } else { return tail_delayed_list_of_values(_opds, acc: []) } } private func tail_delayed_list_of_values(_ _opds :SExpr, acc: [SExpr]) -> [SExpr] { if let pair = _opds as? Pair { return tail_delayed_list_of_values(pair.cdr, acc: acc + [pair.car]) } else { return acc } } public func list_from_array(_ array: [SExpr]) -> SExpr { return tail_list_from_array(array, acc: MNull()) } private func tail_list_from_array(_ array: [SExpr], acc: SExpr) -> SExpr { if array.count == 0 { return acc } else { var array = array var acc = acc let exp = array.removeLast() acc = Pair(car: exp, cdr: acc) return tail_list_from_array(array, acc: acc) } } public func tail(_ _seq: [SExpr]) -> [SExpr] { var seq = _seq if seq.count > 0 { seq.remove(at: 0) return seq } else { return [] } } ///// numeric ////// func cast2double(_ exp: SExpr) -> Double? { switch exp { case let num as MInt: return Double(num.value) case let num as MDouble: return num.value default: print("cast-doulbe take only number literal", terminator: "\n") return nil } } func d2farray(_ array: [Double]) -> [Float] { var acc : [Float] = [] for e in array { acc.append(Float(e)) } return acc } // unique id generator. // UID factory: we can request a unique ID through UID.get.newID // Singleton class UID { private var count:UInt = 0 private init(){} var newID: UInt { count += 1 return count } class var get: UID { struct Static{ static let idFactory = UID() } return Static.idFactory } }
apache-2.0
64d1d5ad2d91e10c4e405a1e0567c759
21.2
83
0.537265
3.305957
false
false
false
false
SECH-Tag-EEXCESS-Browser/iOSX-App
SechQueryComposer/SechQueryComposer/getPrefs.swift
1
1541
// // getPrefs.swift // SechQueryComposer // // Copyright © 2015 Peter Stoehr. All rights reserved. // import Foundation class PreferencesR { let NR_ID = "numResults" let GENDER_ID = "gender" let AGE_ID = "age" let URL_ID = "url" let defaults = NSUserDefaults.standardUserDefaults() var numResults : Int { get { let v = defaults.integerForKey(NR_ID) if (v < 10) { return 10 } return v } set (gIndex) { defaults.setInteger(gIndex, forKey: NR_ID) } } var gender : Int { get { return defaults.integerForKey(GENDER_ID) } set (gIndex) { defaults.setInteger(gIndex, forKey: GENDER_ID) } } var age : Int { get { return defaults.integerForKey(AGE_ID) } set (age) { defaults.setInteger(age, forKey: AGE_ID) } } var url : String { get { let v = defaults.valueForKey(URL_ID) if (v == nil) { return "https://eexcess-dev.joanneum.at/eexcess-privacy-proxy-issuer-1.0-SNAPSHOT/issuer" } return v as! String } set (url) { var cUrl = url if (cUrl[cUrl.endIndex.predecessor()] == "/") { cUrl.removeAtIndex(cUrl.endIndex.predecessor()) } defaults.setValue(cUrl, forKey: URL_ID) } } }
mit
dac87f51572c99aa104df6a277959073
22
105
0.485065
4.020888
false
false
false
false
oakstudios/StackedCollectionView
Source/DefaultTransitionAnimator.swift
1
2156
// // DefaultTransitionAnimator.swift // // Copyright © 2018 Oak, LLC (https://oak.is) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public class DefaultTransitionAnimator: NSObject, UICollectionViewCellAnimatedTransitioning { public func transitionDuration(transitionContext: UICollectionViewCellContextTransitioning) -> TimeInterval { return 0.15 } public func animateTransition(transitionContext: UICollectionViewCellContextTransitioning) { let toState = transitionContext.stateFor(key: .to) let cell = transitionContext.cell() let animationDuration = transitionContext.animationDuration() UIView.animate(withDuration: animationDuration) { switch toState { case .drag: cell.alpha = 0.7 cell.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) default: cell.alpha = 1.0 cell.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) } } } }
mit
9c38ed5ce4eb21c3e4c58fdc076d6bb2
38.907407
113
0.680742
4.93135
false
false
false
false
ppraveentr/MobileCore
Sources/CoreComponents/Contollers/WebViewControllerProtocol.swift
1
2580
// // FTWebViewControllerProtocol.swift // MobileCore-CoreComponents // // Created by Praveen Prabhakar on 18/08/17. // Copyright © 2017 Praveen Prabhakar. All rights reserved. // #if canImport(CoreUtility) import CoreUtility #endif import UIKit import WebKit private var kContentVC = "k.FT.AO.ContentViewController" public protocol WebViewControllerProtocol: ViewControllerProtocol { var contentView: WKWebView { get } } public extension WebViewControllerProtocol { var contentView: WKWebView { get { AssociatedObject<WKWebView>.getAssociated(self, key: &kContentVC) { self.setupContentView() }! } set { setupContentView(newValue) } } } private extension WebViewControllerProtocol { @discardableResult func setupContentView(_ local: WKWebView = WKWebView() ) -> WKWebView { if local.scrollView.delegate == nil { local.scrollView.delegate = WebViewControllerViewDelegate.shared } // Load Base view setupCoreView() if let scroll: WKWebView = AssociatedObject<WKWebView>.getAssociated(self, key: &kContentVC) { scroll.removeFromSuperview() AssociatedObject<Any>.resetAssociated(self, key: &kContentVC) } if local.superview == nil { self.mainView?.pin(view: local, edgeOffsets: .zero) } AssociatedObject<WKWebView>.setAssociated(self, value: local, key: &kContentVC) return local } } internal class WebViewControllerViewDelegate: NSObject, UIScrollViewDelegate { // MARK: - Shared delegate static var shared = WebViewControllerViewDelegate() var shouldHideNav = false var navigationController: UINavigationController? { UIWindow.topViewController?.navigationController } // MARK: - UIScrollViewDelegate func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { nil } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { UIView.animate(withDuration: 0.01, delay: 0, options: UIView.AnimationOptions()) { self.setBarStatus(hidden: velocity.y > 0) } } func setBarStatus(hidden: Bool) { self.navigationController?.setNavigationBarHidden(hidden, animated: true) guard self.navigationController?.toolbarItems?.isEmpty ?? false else { return } self.navigationController?.setToolbarHidden(hidden, animated: true) } }
mit
6aa3c78220b98195ab416ede6242b016
34.328767
110
0.685149
5.168337
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/Root/ViewModel/ZSProtocol.swift
1
3073
// // ZSProtocol.swift // zhuishushenqi // // Created by caony on 2018/6/11. // Copyright © 2018年 QS. All rights reserved. // import Foundation import RxSwift import RxCocoa import MJRefresh enum ZSRefreshStatus { case none case headerRefreshing case headerRefreshEnd case footerRefreshing case footerRefreshEnd case noMoreData } protocol ZSRefreshControl { var refreshStatus:ZSRefreshStatus { get } } extension ZSRefreshControl { func autoSetRefreshHeaderStatus(header:MJRefreshHeader?,footer:MJRefreshFooter?) { } } protocol ZSRefreshProtocol { var refreshStatus:Variable<ZSRefreshStatus>{ get } } extension ZSRefreshProtocol { func autoSetRefreshHeaderStatus(header:MJRefreshHeader?,footer:MJRefreshFooter?) -> Disposable{ return refreshStatus.asObservable().subscribe(onNext: { (status) in switch status { case .headerRefreshing: header?.beginRefreshing() case .headerRefreshEnd: header?.endRefreshing() case .footerRefreshing: footer?.beginRefreshing() case .footerRefreshEnd: footer?.endRefreshing() case .noMoreData: footer?.endRefreshingWithNoMoreData() default: break } }) } } protocol Refreshable { } extension Refreshable where Self : UIViewController{ @discardableResult func initRefreshHeader(_ scrollView: UIScrollView,_ action:@escaping () ->Void) -> MJRefreshHeader{ scrollView.mj_header = MJRefreshNormalHeader(refreshingBlock: { action() }) return scrollView.mj_header } @discardableResult func initRefreshFooter(_ scrollView: UIScrollView,_ action:@escaping () ->Void) -> MJRefreshFooter{ scrollView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { action() }) return scrollView.mj_footer } } extension Refreshable where Self : UIScrollView { @discardableResult func initRefreshHeader(_ action:@escaping () ->Void) -> MJRefreshHeader{ mj_header = MJRefreshNormalHeader(refreshingBlock: { action() }) return mj_header } @discardableResult func initRefreshFooter(_ action:@escaping () ->Void) -> MJRefreshFooter{ mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { action() }) return mj_footer } } extension Refreshable where Self : UIView{ @discardableResult func initRefreshHeader(_ scrollView: UIScrollView,_ action:@escaping () ->Void) -> MJRefreshHeader{ scrollView.mj_header = MJRefreshNormalHeader(refreshingBlock: { action() }) return scrollView.mj_header } @discardableResult func initRefreshFooter(_ scrollView: UIScrollView,_ action:@escaping () ->Void) -> MJRefreshFooter{ scrollView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { action() }) return scrollView.mj_footer } }
mit
a86ddd54080ee3c1aac641fc2ce470b4
26.410714
103
0.653746
5.185811
false
false
false
false
CatchChat/Yep
FayeClient/FayeClient.swift
1
19632
// // FayeClient.swift // Yep // // Created by NIX on 16/5/17. // Copyright © 2016年 Catch Inc. All rights reserved. // import Foundation import SocketRocket import Base64 public protocol FayeClientDelegate: class { func fayeClient(client: FayeClient, didConnectToURL URL: NSURL) func fayeClient(client: FayeClient, didDisconnectWithError error: NSError?) func fayeClient(client: FayeClient, didSubscribeToChannel channel: String) func fayeClient(client: FayeClient, didUnsubscribeFromChannel channel: String) func fayeClient(client: FayeClient, didFailWithError error: NSError?) func fayeClient(client: FayeClient, didFailDeserializeMessage message: [String: AnyObject]?, withError error: NSError?) func fayeClient(client: FayeClient, didReceiveMessage messageInfo: [String: AnyObject], fromChannel channel: String) } public typealias FayeClientSubscriptionHandler = (message: [String: AnyObject]) -> Void public typealias FayeClientPrivateHandler = (message: FayeMessage) -> Void public class FayeClient: NSObject { public private(set) var webSocket: SRWebSocket? public private(set) var serverURL: NSURL public private(set) var clientID: String? public private(set) var sentMessageCount: Int = 0 private var pendingChannelSubscriptionSet: Set<String> = [] private var openChannelSubscriptionSet: Set<String> = [] private var subscribedChannels: [String: FayeClientSubscriptionHandler] = [:] private var privateChannels: [String: FayeClientPrivateHandler] = [:] private var channelExtensions: [String: AnyObject] = [:] public var shouldRetryConnection: Bool = true public var retryInterval: NSTimeInterval = 1 public var retryAttempt: Int = 0 public var maximumRetryAttempts: Int = 5 private var reconnectTimer: NSTimer? public weak var delegate: FayeClientDelegate? private var connected: Bool = false public var isConnected: Bool { return connected } private var isWebSocketOpen: Bool { if let webSocket = webSocket { return webSocket.readyState == .OPEN } return false } private var isWebSocketClosed: Bool { if let webSocket = webSocket { return webSocket.readyState == .CLOSED } return true } deinit { subscribedChannels.removeAll() clearSubscriptions() invalidateReconnectTimer() disconnectFromWebSocket() } public init(serverURL: NSURL) { self.serverURL = serverURL super.init() } public class func clientWithURL(serverURL: NSURL) -> FayeClient { return FayeClient(serverURL: serverURL) } } // MARK: - Helpers extension FayeClient { func generateUniqueMessageID() -> String { sentMessageCount += 1 return ("\(sentMessageCount)" as NSString).base64String() } } // MARK: - Public methods extension FayeClient { public func setExtension(extension: [String: AnyObject], forChannel channel: String) { channelExtensions[channel] = `extension` } public func removeExtensionForChannel(channel: String) { channelExtensions.removeValueForKey(channel) } public func sendMessage(message: [String: AnyObject], toChannel channel: String) { let messageID = generateUniqueMessageID() sendBayeuxPublishMessage(message, withMessageUniqueID: messageID, toChannel: channel, usingExtension: nil) } public func sendMessage(message: [String: AnyObject], toChannel channel: String, usingExtension extension: [String: AnyObject]?) { let messageID = generateUniqueMessageID() sendBayeuxPublishMessage(message, withMessageUniqueID: messageID, toChannel: channel, usingExtension: `extension`) } public func sendMessage(message: [String: AnyObject], toChannel channel: String, usingExtension extension: [String: AnyObject]?, usingBlock subscriptionHandler: FayeClientPrivateHandler) { let messageID = generateUniqueMessageID() privateChannels[messageID] = subscriptionHandler sendBayeuxPublishMessage(message, withMessageUniqueID: messageID, toChannel: channel, usingExtension: `extension`) } public func connectToURL(serverURL: NSURL) -> Bool { if isConnected || isWebSocketOpen { return false } self.serverURL = serverURL return connect() } public func connect() -> Bool { if isConnected || isWebSocketOpen { return false } connectToWebSocket() return true } public func disconnect() { sendBayeuxDisconnectMessage() } public func subscribeToChannel(channel: String) { subscribeToChannel(channel, usingBlock: nil) } public func subscribeToChannel(channel: String, usingBlock subscriptionHandler: FayeClientSubscriptionHandler?) { if let subscriptionHandler = subscriptionHandler { subscribedChannels[channel] = subscriptionHandler } else { subscribedChannels.removeValueForKey(channel) } if isConnected { sendBayeuxSubscribeMessageWithChannel(channel) } } public func unsubscribeFromChannel(channel: String) { subscribedChannels.removeValueForKey(channel) pendingChannelSubscriptionSet.remove(channel) if isConnected { sendBayeuxUnsubscribeMessageWithChannel(channel) } } } private let FayeClientBayeuxConnectionTypeLongPolling = "long-polling" private let FayeClientBayeuxConnectionTypeCallbackPolling = "callback-polling" private let FayeClientBayeuxConnectionTypeIFrame = "iframe"; private let FayeClientBayeuxConnectionTypeWebSocket = "websocket" private let FayeClientBayeuxChannelHandshake = "/meta/handshake" private let FayeClientBayeuxChannelConnect = "/meta/connect" private let FayeClientBayeuxChannelDisconnect = "/meta/disconnect" private let FayeClientBayeuxChannelSubscribe = "/meta/subscribe" private let FayeClientBayeuxChannelUnsubscribe = "/meta/unsubscribe" private let FayeClientBayeuxVersion = "1.0" private let FayeClientBayeuxMinimumVersion = "1.0beta" private let FayeClientBayeuxMessageChannelKey = "channel" private let FayeClientBayeuxMessageClientIdKey = "clientId" private let FayeClientBayeuxMessageIdKey = "id" private let FayeClientBayeuxMessageDataKey = "data" private let FayeClientBayeuxMessageSubscriptionKey = "subscription" private let FayeClientBayeuxMessageExtensionKey = "ext" private let FayeClientBayeuxMessageVersionKey = "version" private let FayeClientBayeuxMessageMinimuVersionKey = "minimumVersion" private let FayeClientBayeuxMessageSupportedConnectionTypesKey = "supportedConnectionTypes" private let FayeClientBayeuxMessageConnectionTypeKey = "connectionType" private let FayeClientWebSocketErrorDomain = "com.nixWork.FayeClient.Error" // MARK: - Bayeux procotol messages extension FayeClient { func sendBayeuxHandshakeMessage() { let supportedConnectionTypes: [String] = [ FayeClientBayeuxConnectionTypeLongPolling, FayeClientBayeuxConnectionTypeCallbackPolling, FayeClientBayeuxConnectionTypeIFrame, FayeClientBayeuxConnectionTypeWebSocket, ] var message: [String: AnyObject] = [ FayeClientBayeuxMessageChannelKey: FayeClientBayeuxChannelHandshake, FayeClientBayeuxMessageVersionKey: FayeClientBayeuxVersion, FayeClientBayeuxMessageMinimuVersionKey: FayeClientBayeuxMinimumVersion, FayeClientBayeuxMessageSupportedConnectionTypesKey: supportedConnectionTypes, ] if let `extension` = channelExtensions["handshake"] { message[FayeClientBayeuxMessageExtensionKey] = `extension` } writeMessage(message) } func sendBayeuxConnectMessage() { guard let clientID = clientID else { didFailWithMessage("FayeClient no clientID.") return } var message: [String: AnyObject] = [ FayeClientBayeuxMessageChannelKey: FayeClientBayeuxChannelConnect, FayeClientBayeuxMessageClientIdKey: clientID, FayeClientBayeuxMessageConnectionTypeKey: FayeClientBayeuxConnectionTypeWebSocket, ] if let `extension` = channelExtensions["connect"] { message[FayeClientBayeuxMessageExtensionKey] = `extension` } writeMessage(message) } func sendBayeuxDisconnectMessage() { guard let clientID = clientID else { didFailWithMessage("FayeClient no clientID.") return } let message: [String: AnyObject] = [ FayeClientBayeuxMessageChannelKey: FayeClientBayeuxChannelDisconnect, FayeClientBayeuxMessageClientIdKey: clientID, ] writeMessage(message) } func sendBayeuxSubscribeMessageWithChannel(channel: String) { guard let clientID = clientID else { didFailWithMessage("FayeClient no clientID.") return } var message: [String: AnyObject] = [ FayeClientBayeuxMessageChannelKey: FayeClientBayeuxChannelSubscribe, FayeClientBayeuxMessageClientIdKey: clientID, FayeClientBayeuxMessageSubscriptionKey: channel, ] if let `extension` = channelExtensions[channel] { message[FayeClientBayeuxMessageExtensionKey] = `extension` } writeMessage(message) { [weak self] finish in if finish { self?.pendingChannelSubscriptionSet.insert(channel) } } } func sendBayeuxUnsubscribeMessageWithChannel(channel: String) { guard let clientID = clientID else { didFailWithMessage("FayeClient no clientID.") return } let message: [String: AnyObject] = [ FayeClientBayeuxMessageChannelKey: FayeClientBayeuxChannelUnsubscribe, FayeClientBayeuxMessageClientIdKey: clientID, FayeClientBayeuxMessageSubscriptionKey: channel, ] writeMessage(message) } func sendBayeuxPublishMessage(messageInfo: [String: AnyObject], withMessageUniqueID messageID: String, toChannel channel: String, usingExtension extension: [String: AnyObject]?) { guard isConnected && isWebSocketOpen else { didFailWithMessage("FayeClient not connected to server.") return } guard let clientID = clientID else { didFailWithMessage("FayeClient no clientID.") return } var message: [String: AnyObject] = [ FayeClientBayeuxMessageChannelKey: channel, FayeClientBayeuxMessageClientIdKey: clientID, FayeClientBayeuxMessageDataKey: messageInfo, FayeClientBayeuxMessageIdKey: messageID, ] if let `extension` = `extension` { message[FayeClientBayeuxMessageExtensionKey] = `extension` } else { if let `extension` = channelExtensions[channel] { message[FayeClientBayeuxMessageExtensionKey] = `extension` } } writeMessage(message) } func clearSubscriptions() { pendingChannelSubscriptionSet.removeAll() openChannelSubscriptionSet.removeAll() } } // MARK: - Private methods extension FayeClient { private func subscribePendingSubscriptions() { for channel in subscribedChannels.keys { if !pendingChannelSubscriptionSet.contains(channel) && !openChannelSubscriptionSet.contains(channel) { sendBayeuxSubscribeMessageWithChannel(channel) } } } @objc private func reconnectTimer(timer: NSTimer) { if isConnected { invalidateReconnectTimer() } else { if shouldRetryConnection && retryAttempt < maximumRetryAttempts { retryAttempt += 1 connect() } else { invalidateReconnectTimer() } } } private func invalidateReconnectTimer() { reconnectTimer?.invalidate() reconnectTimer = nil } private func reconnect() { guard shouldRetryConnection && retryAttempt < maximumRetryAttempts else { return } reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(retryInterval, target: self, selector: #selector(FayeClient.reconnectTimer(_:)), userInfo: nil, repeats: false) } } // MARK: - SRWebSocket extension FayeClient { func writeMessage(message: [String: AnyObject], completion: ((finish: Bool) -> Void)? = nil) { do { let jsonData = try NSJSONSerialization.dataWithJSONObject(message, options: NSJSONWritingOptions(rawValue: 0)) let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) webSocket?.send(jsonString) completion?(finish: true) } catch let error as NSError { delegate?.fayeClient(self, didFailDeserializeMessage: message, withError: error) completion?(finish: false) } } func connectToWebSocket() { disconnectFromWebSocket() let request = NSURLRequest(URL: serverURL) webSocket = SRWebSocket(URLRequest: request) webSocket?.delegate = self webSocket?.open() } func disconnectFromWebSocket() { webSocket?.delegate = nil webSocket?.close() webSocket = nil } func didFailWithMessage(message: String) { let error = NSError(domain: FayeClientWebSocketErrorDomain, code: -100, userInfo: [NSLocalizedDescriptionKey: message]) delegate?.fayeClient(self, didFailWithError: error) } func handleFayeMessages(messages: [[String: AnyObject]]) { //println("handleFayeMessages: \(messages)") let fayeMessages = messages.map({ FayeMessage.messageFromDictionary($0) }).flatMap({ $0 }) fayeMessages.forEach({ fayeMessage in switch fayeMessage.channel { case FayeClientBayeuxChannelHandshake: if fayeMessage.successful { retryAttempt = 0 clientID = fayeMessage.clientID connected = true delegate?.fayeClient(self, didConnectToURL: serverURL) sendBayeuxConnectMessage() subscribePendingSubscriptions() } else { let message = String(format: "Faye client couldn't handshake with server. %@", fayeMessage.error ?? "") didFailWithMessage(message) } case FayeClientBayeuxChannelConnect: if fayeMessage.successful { connected = true sendBayeuxConnectMessage() } else { let message = String(format: "Faye client couldn't connect to server. %@", fayeMessage.error ?? "") didFailWithMessage(message) } case FayeClientBayeuxChannelDisconnect: if fayeMessage.successful { disconnectFromWebSocket() connected = false clearSubscriptions() delegate?.fayeClient(self, didDisconnectWithError: nil) } else { let message = String(format: "Faye client couldn't disconnect from server. %@", fayeMessage.error ?? "") didFailWithMessage(message) } case FayeClientBayeuxChannelSubscribe: guard let subscription = fayeMessage.subscription else { break } pendingChannelSubscriptionSet.remove(subscription) if fayeMessage.successful { openChannelSubscriptionSet.insert(subscription) delegate?.fayeClient(self, didSubscribeToChannel: subscription) } else { let message = String(format: "Faye client couldn't subscribe channel %@ with server. %@", subscription, fayeMessage.error ?? "") didFailWithMessage(message) } case FayeClientBayeuxChannelUnsubscribe: guard let subscription = fayeMessage.subscription else { break } if fayeMessage.successful { subscribedChannels.removeValueForKey(subscription) pendingChannelSubscriptionSet.remove(subscription) openChannelSubscriptionSet.remove(subscription) delegate?.fayeClient(self, didUnsubscribeFromChannel: subscription) } else { let message = String(format: "Faye client couldn't unsubscribe channel %@ with server. %@", subscription, fayeMessage.error ?? "") didFailWithMessage(message) } default: if openChannelSubscriptionSet.contains(fayeMessage.channel) { if let handler = subscribedChannels[fayeMessage.channel] { handler(message: fayeMessage.data) } else { delegate?.fayeClient(self, didReceiveMessage: fayeMessage.data, fromChannel: fayeMessage.channel) } } else { // No match for channel #if DEBUG print("fayeMessage: \(fayeMessage)") #endif if let messageID = fayeMessage.ID, handler = privateChannels[messageID] { handler(message: fayeMessage) } } } }) } } // MARK: - SRWebSocketDelegate extension FayeClient: SRWebSocketDelegate { public func webSocketDidOpen(webSocket: SRWebSocket!) { sendBayeuxHandshakeMessage() } public func webSocket(webSocket: SRWebSocket!, didReceiveMessage message: AnyObject!) { guard let message = message else { return } var _messageData: NSData? if let messageString = message as? String { _messageData = messageString.dataUsingEncoding(NSUTF8StringEncoding) } else { _messageData = message as? NSData } guard let messageData = _messageData else { return } do { if let messages = try NSJSONSerialization.JSONObjectWithData(messageData, options: []) as? [[String: AnyObject]] { handleFayeMessages(messages) } } catch let error as NSError { delegate?.fayeClient(self, didFailDeserializeMessage: nil, withError: error) } } public func webSocket(webSocket: SRWebSocket!, didFailWithError error: NSError!) { connected = false clearSubscriptions() delegate?.fayeClient(self, didFailWithError: error) reconnect() } public func webSocket(webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) { connected = false clearSubscriptions() let reason: String = reason ?? "Unknown Reason" let error = NSError(domain: FayeClientWebSocketErrorDomain, code: code, userInfo: [NSLocalizedDescriptionKey: reason]) delegate?.fayeClient(self, didDisconnectWithError: error) reconnect() } }
mit
f0f70b2680e1b88986bbcf82749a93cd
30.256369
192
0.649243
5.12239
false
false
false
false
BrisyIOS/CustomAlbum
CustomAlbum/CustomAlbum/Album/Controller/AlbumController.swift
1
6071
// // AlbumController.swift // CustomAlbum // // Created by zhangxu on 2016/12/14. // Copyright © 2016年 zhangxu. All rights reserved. // import UIKit import Photos class AlbumController: UIViewController, UITableViewDataSource, UITableViewDelegate { // cell标识 private let albumCellIdentifier = "albumCellIdentifier"; // tableView private lazy var tableView: UITableView = { let tableView = UITableView.init(frame: .zero, style: .plain); tableView.dataSource = self; tableView.delegate = self; tableView.rowHeight = realValue(value: 80); tableView.tableFooterView = UIView(); return tableView; }(); // 相册数据 private lazy var albums: [AlbumModel] = [AlbumModel](); override func viewDidLoad() { super.viewDidLoad() // 设置导航栏不透明 navigationController?.navigationBar.isTranslucent = false; // 添加tableView view.addSubview(tableView); // 注册cell tableView.register(AlbumCell.self, forCellReuseIdentifier: albumCellIdentifier); //申请权限 PHPhotoLibrary.requestAuthorization({ (status) in if status != .authorized { return } // 列出所有系统的智能相册 let smartOptions = PHFetchOptions() let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: smartOptions) self.convertCollection(collection: smartAlbums) //列出所有用户创建的相册 let userCollections = PHCollectionList.fetchTopLevelUserCollections(with: nil) self.convertCollection(collection: userCollections as! PHFetchResult<PHAssetCollection>) //相册按包含的照片数量排序(降序) self.albums.sort { (album1, album2) -> Bool in return (album1.fetchResult?.count)! > (album2.fetchResult?.count)! } //异步加载表格数据,需要在主线程中调用reloadData() 方法 DispatchQueue.main.async{ self.tableView.reloadData() } }) // Do any additional setup after loading the view. } //转化处理获取到的相簿 private func convertCollection(collection:PHFetchResult<PHAssetCollection>){ for i in 0..<collection.count{ //获取出但前相簿内的图片 let resultsOptions = PHFetchOptions() resultsOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] resultsOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) let c = collection[i] let assetsFetchResult = PHAsset.fetchAssets(in: c , options: resultsOptions) var assets = [PHAsset](); for i in 0..<assetsFetchResult.count { let asset = assetsFetchResult[i]; assets.append(asset); } //没有图片的空相簿不显示 if assetsFetchResult.count > 0{ albums.append(AlbumModel(title: c.localizedTitle, fetchResult: assets)); } } // 将相册名转为中文 let _ = albums.map({ (album) in if album.title == "Recently Added" { album.title = "最近添加"; } else if album.title == "Favorites" { album.title = "个人收藏"; } else if album.title == "Recently Deleted" { album.title = "最近删除"; } else if album.title == "Videos" { album.title = "视频"; } else if album.title == "All Photos" { album.title = "所有照片"; } else if album.title == "Selfies" { album.title = "自拍"; } else if album.title == "Screenshots" { album.title = "屏幕快照"; } else if album.title == "Camera Roll" { album.title = "相机胶卷"; } }); } // 返回表尾高度 func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.1; } // 返回行数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return albums.count; } // 返回cell func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: albumCellIdentifier, for: indexPath) as? AlbumCell; if indexPath.row < albums.count { cell?.album = albums[indexPath.row]; } return cell!; } // 选中cell, 查看相册列表 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false); let photoVc = PhotoListController(); photoVc.assets = albums[indexPath.row].fetchResult; navigationController?.pushViewController(photoVc, animated: true); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 设置子控件的frame override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews(); tableView.frame = view.bounds; } }
apache-2.0
cc064ad192ab99a3a39e4876e74f7096
32.267442
116
0.539671
5.298148
false
false
false
false
FlaneurApp/FlaneurOpen
Sources/Classes/Form Tools/FlaneurFormImagePickerElementCollectionViewCell.swift
1
13144
// // FlaneurFormImagePickerElementCollectionViewCell.swift // FlaneurOpen // // Created by Mickaël Floc'hlay on 28/09/2017. // import UIKit import FlaneurImagePicker /// The delegate of a `FlaneurFormImagePickerElementCollectionViewCell` object must adopt the /// `FlaneurFormImagePickerElementCollectionViewCellDelegate` protocol. public protocol FlaneurFormImagePickerElementCollectionViewCellDelegate: FlaneurImagePickerControllerDelegate { /// The image to use on the button presenting the image picker. func buttonImage() -> UIImage // MARK: - Configuring the image picker /// The maximum number of images the user can pick. func numberOfImages() -> Int /// The initial image selection. func initialSelection() -> [FlaneurImageDescriptor] /// The available image providers for the image picker. func sourceProviders() -> [FlaneurImageProvider] /// The localized title of the picker view controller. func localizedAttributedStringForTitle() -> NSAttributedString /// The localized string for the cancel action of the picker view controller. func localizedStringForCancelAction() -> String /// The localized string for the done action of the picker view controller. func localizedStringForDoneAction() -> String } public extension FlaneurFormImagePickerElementCollectionViewCellDelegate where Self: UIViewController { func numberOfImages() -> Int { return 1 } func initialSelection() -> [FlaneurImageDescriptor] { return [] } func sourceProviders() -> [FlaneurImageProvider] { return FlaneurImagePickerConfig.defaultSources } func localizedAttributedStringForTitle() -> NSAttributedString { return NSAttributedString(string: "Pick your pictures") } func localizedStringForCancelAction() -> String { return "Cancel" } func localizedStringForDoneAction() -> String { return "Done" } } final public class FlaneurFormImagePickerElementCollectionViewCell: FlaneurFormElementCollectionViewCell { weak var imageDelegate: FlaneurFormImagePickerElementCollectionViewCellDelegate? let launcherButton: UIButton = UIButton() let photosCollectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 9.0 // Spacing between items let result = UICollectionView(frame: .zero, collectionViewLayout: layout) result.translatesAutoresizingMaskIntoConstraints = false result.backgroundColor = .white result.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 15.0) return result }() var currentSelection: [FlaneurImageDescriptor] = [] { didSet { photosCollectionView.reloadData() } } public override init(frame: CGRect) { super.init(frame: frame) photosCollectionView.dataSource = self photosCollectionView.delegate = self launcherButton.backgroundColor = UIColor(white: (39.0 / 255.0), alpha: 1.0) launcherButton.translatesAutoresizingMaskIntoConstraints = false launcherButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) launcherButton.tintColor = .white launcherButton.contentMode = .scaleAspectFill photosCollectionView.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: "PhotoCollectionViewCell") self.addSubview(launcherButton) self.addSubview(photosCollectionView) _ = LayoutBorderManager(item: launcherButton, toItem: self, left: 16.0, bottom: 16.0) NSLayoutConstraint(item: launcherButton, attribute: .top, relatedBy: .equal, toItem: label, attribute: .bottom, multiplier: 1.0, constant: 4.0).isActive = true NSLayoutConstraint(item: launcherButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 80.0).isActive = true NSLayoutConstraint(item: launcherButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 80.0).isActive = true _ = LayoutBorderManager(item: photosCollectionView, toItem: self, bottom: 16.0, right: 0.0) NSLayoutConstraint(item: photosCollectionView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 80.0).isActive = true NSLayoutConstraint(item: photosCollectionView, attribute: .leading, relatedBy: .equal, toItem: launcherButton, attribute: .trailing, multiplier: 1.0, constant: 8.0).isActive = true } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func configureWith(formElement: FlaneurFormElement) { super.configureWith(formElement: formElement) if case FlaneurFormElementType.imagePicker(let cellDelegate) = formElement.type { self.imageDelegate = cellDelegate self.currentSelection = imageDelegate!.initialSelection() launcherButton.setImage(imageDelegate!.buttonImage().withRenderingMode(.alwaysTemplate), for: .normal) } formElement.didLoadHandler?(launcherButton) } override public func becomeFirstResponder() -> Bool { delegate?.scrollToVisibleSection(cell: self) launcherButton.isSelected = true return true } @objc func buttonPressed(_ sender: Any? = nil) { guard let delegate = delegate else { return print("buttonPressed: please set a delegate to present the image picker") } _ = self.becomeFirstResponder() let flaneurPicker = FlaneurImagePickerController(userInfo: nil, imageProviders: imageDelegate!.sourceProviders(), selectedImages: currentSelection) // Picker Configuration flaneurPicker.view.backgroundColor = .white flaneurPicker.navigationBar.tintColor = .black flaneurPicker.navigationBar.barTintColor = .white flaneurPicker.navigationBar.isTranslucent = false flaneurPicker.navigationBar.topItem?.leftBarButtonItem?.title = imageDelegate!.localizedStringForCancelAction() flaneurPicker.navigationBar.topItem?.rightBarButtonItem?.title = imageDelegate!.localizedStringForDoneAction() let myTitleViewContainer = FullWidthNavigationItemTitle(frame: CGRect(x: 0.0, y: 0.0, width: 1000.0, height: 0.0)) myTitleViewContainer.containingView = flaneurPicker.navigationBar let myTitleText = UILabel(frame: .zero) myTitleText.numberOfLines = 1 myTitleText.attributedText = imageDelegate!.localizedAttributedStringForTitle() myTitleText.font = FlaneurOpenThemeManager.shared.theme.navigationBarTitleFont myTitleViewContainer.titleLabel = myTitleText flaneurPicker.navigationBar.topItem?.titleView = myTitleViewContainer flaneurPicker.config.backgroundColorForSection = { section in switch section { case .selectedImages: return UIColor(white: (236.0 / 255.0), alpha: 1.0) case .imageSources: return .white case .pickerView: return UIColor(white: (236.0 / 255.0), alpha: 1.0) } } flaneurPicker.config.sizeForImagesPickerView = { collectionSize in let nbOfColumns: CGFloat = 3.0 let squareDimension: CGFloat = (collectionSize.width / nbOfColumns) return CGSize(width: squareDimension, height: squareDimension) } let paddingOfImages: CGFloat = 2.0 flaneurPicker.config.paddingForImagesPickerView = UIEdgeInsets(top: paddingOfImages, left: paddingOfImages, bottom: paddingOfImages, right: paddingOfImages) let selfBundle = Bundle(for: FlaneurFormView.self) if let imageBundleURL = selfBundle.url(forResource: "FlaneurOpen", withExtension: "bundle") { if let imageBundle = Bundle(url: imageBundleURL) { flaneurPicker.config.imageForImageProvider = { imageProvider in switch imageProvider.name { case "library": return UIImage(named: "libraryImageSource", in: imageBundle, compatibleWith: nil) case "camera": return UIImage(named: "cameraImageSource", in: imageBundle, compatibleWith: nil) case "instagram": return UIImage(named: "instagramImageSource", in: imageBundle, compatibleWith: nil) default: return nil } } } else { print("Bundle for FlaneurOpen images not found.") } } else { print("URL for FlaneurOpen images bundle not found.") } flaneurPicker.delegate = self delegate.presentViewController(viewController: flaneurPicker) } } extension FlaneurFormImagePickerElementCollectionViewCell: FlaneurImagePickerControllerDelegate { public func flaneurImagePickerController(_ picker: FlaneurImagePickerController, didFinishPickingImages images: [FlaneurImageDescriptor], userInfo: Any?) { self.currentSelection = images if let imageDelegate = imageDelegate { imageDelegate.flaneurImagePickerController(picker, didFinishPickingImages: images, userInfo: userInfo) } picker.dismiss(animated: true) } public func flaneurImagePickerControllerDidCancel(_ picker: FlaneurImagePickerController) { if let imageDelegate = imageDelegate { imageDelegate.flaneurImagePickerControllerDidCancel(picker) } picker.dismiss(animated: true) } public func flaneurImagePickerControllerDidFail(_ error: FlaneurImagePickerError) { debugPrint("ERROR: \(error)") } public func flaneurImagePickerController(_ picker: FlaneurImagePickerController, withCurrentSelectionOfSize count: Int, actionForNewImageSelection newImage: FlaneurImageDescriptor) -> FlaneurImagePickerControllerAction { guard let imageDelegate = imageDelegate else { return .add } if imageDelegate.numberOfImages() == 1 { return count < 1 ? .add : .replaceLast } else { if count < imageDelegate.numberOfImages() { return .add } else { return .doNothing } } } } extension FlaneurFormImagePickerElementCollectionViewCell: UICollectionViewDelegate { } extension FlaneurFormImagePickerElementCollectionViewCell: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return currentSelection.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCollectionViewCell", for: indexPath) as! PhotoCollectionViewCell cell.configureWith(imageDescription: currentSelection[indexPath.row]) return cell } } extension FlaneurFormImagePickerElementCollectionViewCell: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 80.0, height: 80.0) } }
mit
7fec136b02d1272a173897ba9d20f91c
40.72381
224
0.61995
5.89108
false
false
false
false
apple/swift
test/Reflection/typeref_decoding_asan.swift
2
26939
// XFAIL: OS=linux-gnu && CPU=aarch64 // rdar://100805115 // UNSUPPORTED: CPU=arm64e // REQUIRES: asan_runtime // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -sanitize=address -o %t/%target-library-name(TypesToReflect) // RUN: %target-swift-reflection-dump %t/%target-library-name(TypesToReflect) | %FileCheck %s // CHECK: FIELDS: // CHECK: ======= // CHECK: TypesToReflect.Box // CHECK: ------------------ // CHECK: item: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.C // CHECK: ---------------- // CHECK: aClass: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: aStruct: TypesToReflect.S // CHECK: (struct TypesToReflect.S) // CHECK: anEnum: TypesToReflect.E // CHECK: (enum TypesToReflect.E) // CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int)) // CHECK: aTupleWithLabels: (a: TypesToReflect.C, s: TypesToReflect.S, e: TypesToReflect.E) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E)) // CHECK: aMetatype: TypesToReflect.C.Type // CHECK: (metatype // CHECK: (class TypesToReflect.C)) // CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (result // CHECK: (struct Swift.Int)) // CHECK: aFunctionWithVarArgs: (TypesToReflect.C, TypesToReflect.S...) -> () // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (variadic // CHECK: (struct TypesToReflect.S)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithInout1: (inout TypesToReflect.C) -> () // CHECK: (function // CHECK: (parameters // CHECK: (inout // CHECK: (class TypesToReflect.C)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithInout2: (TypesToReflect.C, inout Swift.Int) -> () // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (inout // CHECK: (struct Swift.Int)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithInout3: (inout TypesToReflect.C, inout Swift.Int) -> () // CHECK: (function // CHECK: (parameters // CHECK: (inout // CHECK: (class TypesToReflect.C)) // CHECK: (inout // CHECK: (struct Swift.Int)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithShared: (__shared TypesToReflect.C) -> () // CHECK: (function // CHECK: (parameters // CHECK: (shared // CHECK: (class TypesToReflect.C)) // CHECK: (result // CHECK: (tuple)) // CHECK: TypesToReflect.S // CHECK: ---------------- // CHECK: aClass: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (struct TypesToReflect.S)) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (enum TypesToReflect.E)) // CHECK: aTuple: (TypesToReflect.C, TypesToReflect.Box<TypesToReflect.S>, TypesToReflect.Box<TypesToReflect.E>, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (struct TypesToReflect.S)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (enum TypesToReflect.E)) // CHECK: (struct Swift.Int)) // CHECK: aMetatype: TypesToReflect.C.Type // CHECK: (metatype // CHECK: (class TypesToReflect.C)) // CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (result // CHECK: (struct Swift.Int)) // CHECK: aFunctionWithThinRepresentation: @convention(thin) () -> () // CHECK: (function convention=thin // CHECK: (tuple)) // CHECK: aFunctionWithCRepresentation: @convention(c) () -> () // CHECK: (function convention=c // CHECK: (tuple)) // CHECK: TypesToReflect.S.NestedS // CHECK: ------------------------ // CHECK: aField: Swift.Int // CHECK: (struct Swift.Int) // CHECK: TypesToReflect.E // CHECK: ---------------- // CHECK: Class: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: Struct: TypesToReflect.S // CHECK: (struct TypesToReflect.S) // CHECK: Enum: TypesToReflect.E // CHECK: (enum TypesToReflect.E) // CHECK: Function: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> () // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (result // CHECK: (tuple)) // CHECK: Tuple: (TypesToReflect.C, TypesToReflect.S, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (struct Swift.Int)) // CHECK: IndirectTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int)) // CHECK: NestedStruct: TypesToReflect.S.NestedS // CHECK: (struct TypesToReflect.S.NestedS // CHECK: (struct TypesToReflect.S)) // CHECK: Metatype // CHECK: EmptyCase // CHECK: TypesToReflect.References // CHECK: ------------------------- // CHECK: strongRef: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: weakRef: weak Swift.Optional<TypesToReflect.C> // CHECK: (weak_storage // CHECK: (bound_generic_enum Swift.Optional // CHECK: (class TypesToReflect.C))) // CHECK: unownedRef: unowned TypesToReflect.C // CHECK: (unowned_storage // CHECK: (class TypesToReflect.C)) // CHECK: unownedUnsafeRef: unowned(unsafe) TypesToReflect.C // CHECK: (unmanaged_storage // CHECK: (class TypesToReflect.C)) // CHECK: TypesToReflect.C1 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, TypesToReflect.E1<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: dependentMember: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.C2 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, TypesToReflect.E2<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: TypesToReflect.C3 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S3<A> // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E3<A> // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, TypesToReflect.E3<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P2.Outer // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.C4 // CHECK: ----------------- // CHECK: TypesToReflect.S1 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S1<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E1<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.Box<TypesToReflect.S1<A>>, TypesToReflect.Box<TypesToReflect.E1<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.S2 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C2<A> // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S2<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E2<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C2<A>) -> (TypesToReflect.S2<A>) -> (TypesToReflect.E2<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.Box<TypesToReflect.S2<A>>, TypesToReflect.Box<TypesToReflect.E2<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: TypesToReflect.S3 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S3<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E3<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.Box<TypesToReflect.S3<A>>, TypesToReflect.Box<TypesToReflect.E3<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P2.Outer // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.S4 // CHECK: ----------------- // CHECK: TypesToReflect.E1 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Int: Swift.Int // CHECK: (struct Swift.Int) // CHECK: Function: (A) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (parameters // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (result // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: Metatype: A.Type // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: TypesToReflect.E2 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C2<A> // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S2<A> // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E2<A> // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Function: (A.Type) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (parameters // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: DependentMemberInner: A.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: ExistentialMetatype: A.Type // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: TypesToReflect.E3 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S3<A> // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E3<A> // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Function: (A.Type.Type) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (parameters // CHECK: (metatype // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (result // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: DependentMemberOuter: A.TypesToReflect.P2.Outer // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: DependentMemberInner: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.E4 // CHECK: ----------------- // CHECK: TypesToReflect.P1 // CHECK: ----------------- // CHECK: TypesToReflect.P2 // CHECK: ----------------- // CHECK: TypesToReflect.P3 // CHECK: ----------------- // CHECK: TypesToReflect.P4 // CHECK: ----------------- // CHECK: TypesToReflect.ClassBoundP // CHECK: -------------------------- // CHECK: TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}}) // CHECK: ------------------------------------------------------------------------- // CHECK: TypesToReflect.HasFileprivateProtocol // CHECK: ------------------------------------- // CHECK: x: TypesToReflect.(FileprivateProtocol in ${{[0-9a-fA-F]+}}) // CHECK: (protocol_composition // CHECK-NEXT: (protocol TypesToReflect.(FileprivateProtocol in ${{[0-9a-fA-F]+}}))) // CHECK: ASSOCIATED TYPES: // CHECK: ================= // CHECK: - TypesToReflect.C1 : TypesToReflect.ClassBoundP // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.C4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.C4 : TypesToReflect.P2 // CHECK: typealias Outer = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.S4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.S4 : TypesToReflect.P2 // CHECK: typealias Outer = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.E4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.E4 : TypesToReflect.P2 // CHECK: typealias Outer = B // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: - TypesToReflect.E4 : TypesToReflect.P3 // CHECK: typealias First = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: typealias Second = B // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: - TypesToReflect.S : TypesToReflect.P4 // CHECK: typealias Result = Swift.Int // CHECK: (struct Swift.Int) // CHECK: BUILTIN TYPES: // CHECK: ============== // CHECK: CAPTURE DESCRIPTORS: // CHECK: ==================== // CHECK: - Capture types: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - Metadata sources: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (closure_binding index=0) // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: (closure_binding index=1) // CHECK: - Capture types: // CHECK: (struct Swift.Int) // CHECK: - Metadata sources: // CHECK: - Capture types: // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=1)) // CHECK: - Metadata sources: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (closure_binding index=0) // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: (generic_argument index=0 // CHECK: (reference_capture index=0))
apache-2.0
8caa8384ec9e33852ea825d4e7fd6d1f
35.601902
298
0.667285
3.377931
false
false
false
false
bustoutsolutions/siesta
Examples/GithubBrowser/Source/UI/RepositoryListViewController.swift
1
4218
import UIKit import Siesta import SiestaUI class RepositoryListViewController: UITableViewController, ResourceObserver { // MARK: Interesting Siesta stuff var repositoriesResource: Resource? { didSet { oldValue?.removeObservers(ownedBy: self) repositoriesResource? .addObserver(self) .addObserver(statusOverlay, owner: self) .loadIfNeeded() } } var repositories: [Repository] = [] { didSet { tableView.reloadData() } } var statusOverlay = ResourceStatusOverlay() func resourceChanged(_ resource: Resource, event: ResourceEvent) { // Siesta’s typedContent() infers from the type of the repositories property that // repositoriesResource should hold content of type [Repository]. repositories = repositoriesResource?.typedContent() ?? [] } // MARK: Standard table view stuff override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = SiestaTheme.darkColor statusOverlay.embed(in: self) } override func viewDidLayoutSubviews() { statusOverlay.positionToCoverParent() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repositories.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "repo", for: indexPath) if let cell = cell as? RepositoryTableViewCell { cell.repository = repositories[(indexPath as IndexPath).row] } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "repoDetail" { if let repositoryVC = segue.destination as? RepositoryViewController, let cell = sender as? RepositoryTableViewCell { repositoryVC.repositoryResource = repositoriesResource?.optionalRelative( cell.repository?.url) } } } } class RepositoryTableViewCell: UITableViewCell { @IBOutlet weak var icon: RemoteImageView! @IBOutlet weak var userLabel: UILabel! @IBOutlet weak var repoLabel: UILabel! @IBOutlet weak var starCountLabel: UILabel! var repository: Repository? { didSet { userLabel.text = repository?.owner.login repoLabel.text = repository?.name starCountLabel.text = repository?.starCount?.description // Note how powerful this next line is: // // • RemoteImageView calls loadIfNeeded() when we set imageURL, so this automatically triggers a network // request for the image. However... // // • loadIfNeeded() won’t make redundant requests, so no need to worry about whether this avatar is used in // other table cells, or whether we’ve already requested it! Many cells sharing one image spawn one // request. One response updates _all_ the cells that image. // // • If imageURL was already set, RemoteImageView calls cancelLoadIfUnobserved() on the old image resource. // This means that if the user is scrolling fast and table cells are being reused: // // - a request in progress gets cancelled // - unless other cells are also waiting on the same image, in which case the request continues, and // - an image that we’ve already fetch stay available in memory, fully parsed & ready for instant resuse. // // Finally, note that all of this nice behavior is not special magic that’s specific to images. These are // basic Siesta behaviors you can use for resources of any kind. Look at the RemoteImageView source code // and study how it uses the core Siesta API. icon.imageURL = repository?.owner.avatarURL } } }
mit
3f4a86f01d51c4bf867d94a2deed0643
36.508929
119
0.636753
5.392811
false
false
false
false
kripple/bti-watson
ios-app/Carthage/Checkouts/ObjectMapper/ObjectMapper/Core/FromJSON.swift
15
5482
// // FromJSON.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // // The MIT License (MIT) // // Copyright (c) 2014-2015 Hearst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. internal final class FromJSON { /// Basic type class func basicType<FieldType>(inout field: FieldType, object: FieldType?) { if let value = object { field = value } } /// optional basic type class func optionalBasicType<FieldType>(inout field: FieldType?, object: FieldType?) { if let value = object { field = value } } /// Implicitly unwrapped optional basic type class func optionalBasicType<FieldType>(inout field: FieldType!, object: FieldType?) { if let value = object { field = value } } /// Mappable object class func object<N: Mappable>(inout field: N, object: AnyObject?) { if let value: N = Mapper().map(object) { field = value } } /// Optional Mappable Object class func optionalObject<N: Mappable>(inout field: N?, object: AnyObject?) { field = Mapper().map(object) } /// Implicitly unwrapped Optional Mappable Object class func optionalObject<N: Mappable>(inout field: N!, object: AnyObject?) { field = Mapper().map(object) } /// mappable object array class func objectArray<N: Mappable>(inout field: Array<N>, object: AnyObject?) { if let objects = Mapper<N>().mapArray(object) { field = objects } } /// optional mappable object array class func optionalObjectArray<N: Mappable>(inout field: Array<N>?, object: AnyObject?) { field = Mapper().mapArray(object) } /// Implicitly unwrapped optional mappable object array class func optionalObjectArray<N: Mappable>(inout field: Array<N>!, object: AnyObject?) { field = Mapper().mapArray(object) } /// mappable object array class func twoDimensionalObjectArray<N: Mappable>(inout field: Array<Array<N>>, object: AnyObject?) { if let objects = Mapper<N>().mapArrayOfArrays(object) { field = objects } } /// optional mappable 2 dimentional object array class func optionalTwoDimensionalObjectArray<N: Mappable>(inout field: Array<Array<N>>?, object: AnyObject?) { field = Mapper().mapArrayOfArrays(object) } /// Implicitly unwrapped optional 2 dimentional mappable object array class func optionalTwoDimensionalObjectArray<N: Mappable>(inout field: Array<Array<N>>!, object: AnyObject?) { field = Mapper().mapArrayOfArrays(object) } /// Dctionary containing Mappable objects class func objectDictionary<N: Mappable>(inout field: Dictionary<String, N>, object: AnyObject?) { let parsedObjects = Mapper<N>().mapDictionary(object) if let objects = parsedObjects { field = objects } } /// Optional dictionary containing Mappable objects class func optionalObjectDictionary<N: Mappable>(inout field: Dictionary<String, N>?, object: AnyObject?) { field = Mapper().mapDictionary(object) } /// Implicitly unwrapped Dictionary containing Mappable objects class func optionalObjectDictionary<N: Mappable>(inout field: Dictionary<String, N>!, object: AnyObject?) { field = Mapper().mapDictionary(object) } /// Dictionary containing Array of Mappable objects class func objectDictionaryOfArrays<N: Mappable>(inout field: Dictionary<String, [N]>, object: AnyObject?) { let parsedObjects = Mapper<N>().mapDictionaryOfArrays(object) if let objects = parsedObjects { field = objects } } /// Optional Dictionary containing Array of Mappable objects class func optionalObjectDictionaryOfArrays<N: Mappable>(inout field: Dictionary<String, [N]>?, object: AnyObject?) { field = Mapper<N>().mapDictionaryOfArrays(object) } /// Implicitly unwrapped Dictionary containing Array of Mappable objects class func optionalObjectDictionaryOfArrays<N: Mappable>(inout field: Dictionary<String, [N]>!, object: AnyObject?) { field = Mapper<N>().mapDictionaryOfArrays(object) } /// mappable object Set class func objectSet<N: Mappable>(inout field: Set<N>, object: AnyObject?) { let parsedObjects = Mapper<N>().mapSet(object) if let objects = parsedObjects { field = objects } } /// optional mappable object array class func optionalObjectSet<N: Mappable>(inout field: Set<N>?, object: AnyObject?) { field = Mapper().mapSet(object) } /// Implicitly unwrapped optional mappable object array class func optionalObjectSet<N: Mappable>(inout field: Set<N>!, object: AnyObject?) { field = Mapper().mapSet(object) } }
mit
b1c17965d3097f851c31b4dda461f39d
33.049689
118
0.724735
3.960983
false
false
false
false
markcdb/RealmManager
RealmManager/RealmThread.swift
1
5662
// // RealmThread.swift // RealmManagerExample // // Created by Mark Christian Buot on 04/09/2019. // Copyright © 2019 Morph. All rights reserved. // import Foundation /// FIFO. First-In-First-Out guaranteed on exactly same thread. class RealmThread: Thread { typealias Block = () -> () private let condition = NSCondition() private(set) var queue = [Block]() private(set) var paused: Bool = false /** Designated initializer. - parameters: - start: Boolean whether thread should start immediately. Defaults to true. - queue: Initial array of blocks to add to enqueue. Executed in order of objects in array. */ init(start: Bool = true, queue: [Block]? = nil) { super.init() // Add blocks initially to queue if let queue = queue { for block in queue { enqueue(block: block) } } // Start thread if start { self.start() } } /** The main entry point routine for the thread. You should never invoke this method directly. You should always start your thread by invoking the start method. Shouldn't invoke `super`. */ final override func main() { // Infinite loops until thread is cancelled while true { // Use NSCondition. Comments are from Apple documentation on NSCondition // 1. Lock the condition object. condition.lock() // 2. Test a boolean predicate. (This predicate is a boolean flag or other variable in your code that indicates whether it is safe to perform the task protected by the condition.) // If no blocks (or paused) and not cancelled while (queue.count == 0 || paused) && !isCancelled { // 3. If the boolean predicate is false, call the condition object’s wait or waitUntilDate: method to block the thread. Upon returning from these methods, go to step 2 to retest your boolean predicate. (Continue waiting and retesting the predicate until it is true.) condition.wait() } // 4. If the boolean predicate is true, perform the task. // If your thread supports cancellation, it should check this property periodically and exit if it ever returns true. if (isCancelled) { condition.unlock() return } // As per http://stackoverflow.com/a/22091859 by Marc Haisenko: // Execute block outside the condition, since it's also a lock! // We want to give other threads the possibility to enqueue // a new block while we're executing a block. let block = queue.removeFirst() condition.unlock() // Run block block() } } /** Add a block to be run on the thread. FIFO. - parameters: - block: The code to run. */ final func enqueue(block: @escaping Block) { // Lock to ensure first-in gets added to array first condition.lock() // Add to queue queue.append(block) // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Start the thread. - Warning: Don't start thread again after it has been cancelled/stopped. - SeeAlso: .start() - SeeAlso: .pause() */ final override func start() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // Unpause. Might be in pause state // Start super.start() // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Cancels the thread. - Warning: Don't start thread again after it has been cancelled/stopped. Use .pause() instead. - SeeAlso: .start() - SeeAlso: .pause() */ final override func cancel() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // Cancel NSThread super.cancel() // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Pause the thread. To completely stop it (i.e. remove it from the run-time), use `.cancel()` - Warning: Thread is still runnin, - SeeAlso: .start() - SeeAlso: .cancel() */ final func pause() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // paused = true // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Resume the execution of blocks from the queue on the thread. - Warning: Can't resume if thread was cancelled/stopped. - SeeAlso: .start() - SeeAlso: .cancel() */ final func resume() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // paused = false // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Empty the queue for any blocks that hasn't been run yet - SeeAlso: - .enqueue(block: Block) - .cancel() */ final func emptyQueue() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // Remove any blocks from the queue queue.removeAll() // Release from .wait() condition.signal() // Release lock condition.unlock() } }
mit
8b5d014c360afd7f7369d9ff96d5f976
30.792135
282
0.571302
4.791702
false
false
false
false
fiveagency/ios-five-utils
Example/Classes/ViewControllers/HomeViewController.swift
1
2018
// // HomeViewController.swift // FiveUtils // // Created by Miran Brajsa on 09/17/2016. // Copyright © 2016 Five Agency. All rights reserved. // import UIKit class HomeViewController: UIViewController { fileprivate let viewModel: HomeViewModel @IBOutlet private weak var tableView: UITableView! init(viewModel: HomeViewModel) { self.viewModel = viewModel super.init(nibName: String(describing: HomeViewController.self), bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("Should not be implemented.") } override func viewDidLoad() { super.viewDidLoad() setupContent() setupLayout() } private func setupContent() { let cellReuseIdentifier = String(describing: ContentCell.self) tableView.register( UINib(nibName: cellReuseIdentifier, bundle: nil), forCellReuseIdentifier: cellReuseIdentifier ) tableView.estimatedRowHeight = 100 } private func setupLayout() { guard let titleFont = UIFont.screenTitleText else { return } title = "Five Utils" navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.highlightRed, NSFontAttributeName: titleFont ] } } extension HomeViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.cellCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ContentCell.self), for: indexPath) as? ContentCell else { return UITableViewCell() } let cellViewModel = viewModel.cellViewModel(atIndex: indexPath.row) cell.setup(withViewModel: cellViewModel) return cell } }
mit
a182d536c22c94f2dad676cfbad39ff8
27.408451
140
0.663361
5.571823
false
false
false
false
songxing10000/CodeLibrary
Extensions/Swift/UIImage+Extension.swift
1
2587
// // UIImage+Extension.swift // SmallVillage // // Created by 李 on 16/7/27. // Copyright © 2016年 chenglv. All rights reserved. // import UIKit extension UIImage { /// 创建一个`点`的图像 /// /// - parameter color: 图像颜色 /// /// - returns: 当前分辨率对应的单点图像 class func yl_singleDotImage(_ color: UIColor) -> UIImage { // 1. 开启上下文,需要注意 scale UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, UIScreen.main.scale) // 2. 画图,填个颜色 color.setFill() UIRectFill(CGRect(x: 0, y: 0, width: 1, height: 1)) // 3. 从上下文获取图像 let result = UIGraphicsGetImageFromCurrentImageContext() // 4. 关闭上下文 UIGraphicsEndImageContext() // 5. 返回图像 return result! } /// 异步绘制图像 open func yl_asyncDrawImage(_ size: CGSize, isCorner: Bool = false, backColor: UIColor? = UIColor.white, finished: @escaping (_ image: UIImage)->()) { // 异步绘制图像,可以在子线程进行,因为没有更新 UI DispatchQueue.global().async { // let start = CACurrentMediaTime() // 如果指定了背景颜色,就不透明 UIGraphicsBeginImageContextWithOptions(size, backColor != nil, UIScreen.main.scale) let rect = CGRect(origin: CGPoint.zero, size: size) // 设置填充颜色 backColor?.setFill() UIRectFill(rect) // 设置圆角 - 使用路径裁切,注意:写设置裁切路径,再绘制图像 if isCorner { let path = UIBezierPath(ovalIn: rect) // 添加裁切路径 - 后续的绘制,都会被此路径裁切掉 path.addClip() } // 绘制图像 self.draw(in: rect) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // print("执行时间 \(CACurrentMediaTime() - start)") // 主线程更新 UI,提示:有的时候异步也能更新 UI,但是会非常慢! DispatchQueue.main.async { finished(result!) } } } }
mit
d1a4c59ed56985624c49c65b41a34c99
26.209877
103
0.490926
4.601253
false
false
false
false
HongliYu/firefox-ios
Client/Helpers/UserActivityHandler.swift
1
2441
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import CoreSpotlight import MobileCoreServices import WebKit private let browsingActivityType: String = "org.mozilla.ios.firefox.browsing" private let searchableIndex = CSSearchableIndex(name: "firefox") class UserActivityHandler { private var tabObservers: TabObservers! init() { self.tabObservers = registerFor( .didLoseFocus, .didGainFocus, .didChangeURL, .didLoadPageMetadata, // .didLoadFavicon, // TODO: Bug 1390294 .didClose, queue: .main) } deinit { unregister(tabObservers) } class func clearSearchIndex(completionHandler: ((Error?) -> Void)? = nil) { searchableIndex.deleteAllSearchableItems(completionHandler: completionHandler) } fileprivate func setUserActivityForTab(_ tab: Tab, url: URL) { guard !tab.isPrivate, url.isWebPage(includeDataURIs: false), !InternalURL.isValid(url: url) else { tab.userActivity?.resignCurrent() tab.userActivity = nil return } tab.userActivity?.invalidate() let userActivity = NSUserActivity(activityType: browsingActivityType) userActivity.webpageURL = url userActivity.becomeCurrent() tab.userActivity = userActivity } } extension UserActivityHandler: TabEventHandler { func tabDidGainFocus(_ tab: Tab) { tab.userActivity?.becomeCurrent() } func tabDidLoseFocus(_ tab: Tab) { tab.userActivity?.resignCurrent() } func tab(_ tab: Tab, didChangeURL url: URL) { setUserActivityForTab(tab, url: url) } func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) { guard let url = URL(string: metadata.siteURL) else { return } setUserActivityForTab(tab, url: url) } func tabDidClose(_ tab: Tab) { guard let userActivity = tab.userActivity else { return } tab.userActivity = nil userActivity.invalidate() } }
mpl-2.0
a2c10003ac1e193de1ce86f7054e2c17
28.409639
106
0.608357
5.03299
false
false
false
false
openHPI/xikolo-ios
iOS/Extensions/CALayer+roundedCorners.swift
1
698
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import UIKit extension CALayer { struct CornerStyle: Hashable, Equatable, RawRepresentable { static let searchField = CALayer.CornerStyle(rawValue: 10) static let `default` = CALayer.CornerStyle(rawValue: 6) static let inner = CALayer.CornerStyle(rawValue: 4) let rawValue: CGFloat } func roundCorners(for style: CALayer.CornerStyle, masksToBounds: Bool = true) { self.masksToBounds = masksToBounds self.cornerRadius = style.rawValue if #available(iOS 13, *) { self.cornerCurve = .continuous } } }
gpl-3.0
6831f6e8eb483658e33c2132d1bd31e7
23.034483
83
0.652798
4.35625
false
false
false
false
BlueBiteLLC/Eddystone
Pod/Classes/Beacon.swift
2
6264
import CoreBluetooth open class Beacon { //MARK: Enumerations public enum SignalStrength: Int { case excellent case veryGood case good case low case veryLow case noSignal case unknown } //MARK: Frames var frames: ( url: UrlFrame?, uid: UidFrame?, tlm: TlmFrame? ) = (nil,nil,nil) //MARK: Properties var txPower: Int var identifier: String var rssi: Double { get { var totalRssi: Double = 0 for rssi in self.rssiBuffer { totalRssi += rssi } let average: Double = totalRssi / Double(self.rssiBuffer.count) return average } } var signalStrength: SignalStrength = .unknown var rssiBuffer = [Double]() var distance: Double { get { return Beacon.calculateAccuracy(txPower: self.txPower, rssi: self.rssi) } } //MARK: Initializations init(rssi: Double, txPower: Int, identifier: String) { self.txPower = txPower self.identifier = identifier self.updateRssi(rssi) } //MARK: Delegate var delegate: BeaconDelegate? func notifyChange() { self.delegate?.beaconDidChange() } //MARK: Functions func updateRssi(_ newRssi: Double) -> Bool { self.rssiBuffer.insert(newRssi, at: 0) if self.rssiBuffer.count >= 20 { self.rssiBuffer.removeLast() } let signalStrength = Beacon.calculateSignalStrength(self.distance) if signalStrength != self.signalStrength { self.signalStrength = signalStrength self.notifyChange() } return false } //MARK: Calculations class func calculateAccuracy(txPower: Int, rssi: Double) -> Double { if rssi == 0 { return 0 } let ratio: Double = rssi / Double(txPower) if ratio < 1 { return pow(ratio, 10) } else { return 0.89976 * pow(ratio, 7.7095) + 0.111 } } class func calculateSignalStrength(_ distance: Double) -> SignalStrength { switch distance { case 0...24999: return .excellent case 25000...49999: return .veryGood case 50000...74999: return .good case 75000...99999: return .low default: return .veryLow } } //MARK: Advertisement Data func parseAdvertisementData(_ advertisementData: [AnyHashable: Any], rssi: Double) { self.updateRssi(rssi) if let bytes = Beacon.bytesFromAdvertisementData(advertisementData) { if let type = Beacon.frameTypeFromBytes(bytes) { switch type { case .url: if let frame = UrlFrame.frameWithBytes(bytes) { if frame.url != self.frames.url?.url { self.frames.url = frame log("Parsed URL Frame with url: \(frame.url)") self.notifyChange() } } case .uid: if let frame = UidFrame.frameWithBytes(bytes) { if frame.uid != self.frames.uid?.uid { self.frames.uid = frame log("Parsed UID Frame with uid: \(frame.uid)") self.notifyChange() } } case .tlm: if let frame = TlmFrame.frameWithBytes(bytes) { self.frames.tlm = frame log("Parsed TLM Frame with battery: \(frame.batteryVolts) temperature: \(frame.temperature) advertisement count: \(frame.advertisementCount) on time: \(frame.onTime)") self.notifyChange() } } } } } //MARK: Bytes class func beaconWithAdvertisementData(_ advertisementData: [AnyHashable: Any], rssi: Double, identifier: String) -> Beacon? { var txPower: Int? var type: FrameType? if let bytes = Beacon.bytesFromAdvertisementData(advertisementData) { type = Beacon.frameTypeFromBytes(bytes) txPower = Beacon.txPowerFromBytes(bytes) if let txPower = txPower, type != nil { let beacon = Beacon(rssi: rssi, txPower: txPower, identifier: identifier) beacon.parseAdvertisementData(advertisementData, rssi: rssi) return beacon } } return nil } class func bytesFromAdvertisementData(_ advertisementData: [AnyHashable: Any]) -> [Byte]? { if let serviceData = advertisementData[CBAdvertisementDataServiceDataKey] as? [AnyHashable: Any] { if let urlData = serviceData[Scanner.eddystoneServiceUUID] as? Data { let count = urlData.count / MemoryLayout<UInt8>.size var bytes = [UInt8](repeating: 0, count: count) (urlData as NSData).getBytes(&bytes, length:count * MemoryLayout<UInt8>.size) return bytes.map { byte in return Byte(byte) } } } return nil } class func frameTypeFromBytes(_ bytes: [Byte]) -> FrameType? { if bytes.count >= 1 { switch bytes[0] { case 0: return .uid case 16: return .url case 32: return .tlm default: break } } return nil } class func txPowerFromBytes(_ bytes: [Byte]) -> Int? { if bytes.count >= 2 { if let type = Beacon.frameTypeFromBytes(bytes) { if type == .uid || type == .url { return Int(bytes[1]) } } } return nil } } protocol BeaconDelegate { func beaconDidChange() }
mit
34ce161ea4907bf3205460a7e03e0a8f
29.407767
191
0.505268
5.059774
false
false
false
false
vermont42/Conjugar
Conjugar/VerbType.swift
1
282
// // VerbType.swift // Conjugar // // Created by Joshua Adams on 5/6/17. // Copyright © 2017 Josh Adams. All rights reserved. // enum VerbType: String { case irregular = "ir" case regularAr = "ra" case regularEr = "re" case regularIr = "ri" static let key = "vt" }
agpl-3.0
9a75831c2cdbbfea7a2f1dc59e5b42ee
17.733333
53
0.633452
3.122222
false
false
false
false
fredfoc/OpenWit
Example/OpenWit/Examples/Models/CustomModels.swift
1
1470
// // CustomModels.swift // OpenWit // // Created by fauquette fred on 7/01/17. // Copyright © 2017 Fred Fauquette. All rights reserved. // import Foundation import OpenWit import ObjectMapper /// a custom entity defined in Wit struct ShopItemEntity: Mappable, OpenWitGenericEntityModelProtocol { static var entityId = "shopItem" var suggested: Bool = false var confidence: Float? var type: String? var value: String? public init?(map: Map) {} } /// a custom entity defined in Wit struct ShopListEntity: Mappable, OpenWitGenericEntityModelProtocol { static var entityId = "shopList" var suggested: Bool = false var confidence: Float? var type: String? var value: String? public init?(map: Map) {} } /// A context that can be set for any type of message or conversation. /// See Wit documentation to interact with Context in Message/Conversation struct OpenWitContext: Mappable { var timeZone: String? var referenceTime: String? static let localTimeZoneName = { return (NSTimeZone.local as NSTimeZone).name }() public init?(map: Map) {} mutating public func mapping(map: Map) { referenceTime <- map["reference_time"] timeZone <- map["timezone"] } init(referenceTime: String?) { self.timeZone = OpenWitContext.localTimeZoneName self.referenceTime = referenceTime } }
mit
128aa7b9d88c90286b7422b9c5d53eb9
23.081967
74
0.656229
4.346154
false
false
false
false
mozilla-mobile/firefox-ios
WidgetKit/TopSites/TopSitesWidget.swift
2
3714
// 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 SwiftUI import WidgetKit import Combine struct TopSitesWidget: Widget { private let kind: String = "Top Sites" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: TopSitesProvider()) { entry in TopSitesView(entry: entry) } .supportedFamilies([.systemMedium]) .configurationDisplayName(String.TopSitesGalleryTitleV2) .description(String.TopSitesGalleryDescription) } } struct TopSitesView: View { let entry: TopSitesEntry @ViewBuilder func topSitesItem(_ site: WidgetKitTopSiteModel) -> some View { let url = site.url Link(destination: linkToContainingApp("?url=\(url)", query: "widget-medium-topsites-open-url")) { if entry.favicons[site.imageKey] != nil { (entry.favicons[site.imageKey])!.resizable().frame(width: 60, height: 60).mask(maskShape) } else { Rectangle() .fill(Color(UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 0.3))) .frame(width: 60, height: 60) } } } var maskShape: RoundedRectangle { RoundedRectangle(cornerRadius: 5) } var emptySquare: some View { maskShape .fill(Color(UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 0.3))) .frame(width: 60, height: 60) .background(Color.clear).frame(maxWidth: .infinity) } var body: some View { VStack { HStack { if entry.sites.isEmpty { ForEach(0..<4, id: \.self) { _ in emptySquare } } else if entry.sites.count > 3 { ForEach(entry.sites.prefix(4), id: \.url) { tab in topSitesItem(tab) .background(Color.clear).frame(maxWidth: .infinity) } } else { ForEach(entry.sites[0...entry.sites.count - 1], id: \.url) { tab in topSitesItem(tab).frame(maxWidth: .infinity) } ForEach(0..<(4 - entry.sites.count), id: \.self) { _ in emptySquare } } }.padding([.top, .horizontal]) Spacer() HStack { if entry.sites.count > 7 { ForEach(entry.sites[4...7], id: \.url) { tab in topSitesItem(tab).frame(maxWidth: .infinity) } } else { // Ensure there is at least a single site in the second row if entry.sites.count > 4 { ForEach(entry.sites[4...entry.sites.count - 1], id: \.url) { tab in topSitesItem(tab).frame(maxWidth: .infinity) } } ForEach(0..<(min(4, 8 - entry.sites.count)), id: \.self) { _ in emptySquare } } }.padding([.bottom, .horizontal]) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background((Color(UIColor(red: 0.11, green: 0.11, blue: 0.13, alpha: 1.00)))) } private func linkToContainingApp(_ urlSuffix: String = "", query: String) -> URL { let urlString = "\(scheme)://\(query)\(urlSuffix)" return URL(string: urlString)! } }
mpl-2.0
d83e68bd21ce2d415b146a3b41572ac7
35.772277
105
0.505654
4.431981
false
false
false
false
SmallPlanetSwift/Saturn
Source/TypeExtensions/NSParagraphStyle+String.swift
1
1104
// // NSParagraphStyle+String.swift // Saturn // // Created by Quinn McHenry on 11/15/15. // Copyright © 2015 Small Planet. All rights reserved. // extension NSLineBreakMode: StringLiteralConvertible { public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = Character public init(stringLiteral value: String) { switch value.lowercaseString { case "ByWordWrapping": self = ByWordWrapping case "ByCharWrapping": self = ByCharWrapping case "ByClipping": self = ByClipping case "ByTruncatingHead": self = ByTruncatingHead case "ByTruncatingMiddle": self = ByTruncatingMiddle default: self = ByTruncatingTail } } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(stringLiteral: "\(value)") } }
mit
aaab3214a3eabe21f8476ad4a2a6c550
28.052632
91
0.658205
5.65641
false
false
false
false
segabor/OSCCore
Source/OSCCore/conversion/Data+OSCMessageArgument.swift
1
1349
// // Data+OSCMessageArgument.swift // OSCCore // // Created by Sebestyén Gábor on 2017. 12. 30.. // import Foundation extension Data: OSCMessageArgument { public init?(data: ArraySlice<Byte>) { guard let size = UInt32(data: data[data.startIndex..<data.startIndex+4]) else { return nil } let rawPointer: UnsafeRawPointer? = data.suffix(from: data.startIndex+4).withUnsafeBytes { return $0.baseAddress } if let rawPointer = rawPointer { self.init(bytes: rawPointer, count: Int(size)) } else { return nil } } public var oscType: TypeTagValues { .BLOB_TYPE_TAG } public var packetSize: Int { return MemoryLayout<Int32>.size + align(size: self.count) } public var oscValue: [Byte]? { let dataSize = self.count var payload = [Byte]() payload += self.count.oscValue! payload += self.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> [Byte] in return [Byte](pointer[0..<dataSize]) } // append zeroes to the end let alignedSize = align(size: payload.count) let padding = alignedSize - payload.count if padding > 0 { payload += [Byte](repeating: 0, count: padding) } return payload } }
mit
32885a488954be8ed378aef59974c15c
25.411765
98
0.587231
4.144615
false
false
false
false
kwkhaw/SwiftAnyPic
SwiftAnyPic/PAPEditPhotoViewController.swift
1
11612
import UIKit class PAPEditPhotoViewController: UIViewController, UITextFieldDelegate, UIScrollViewDelegate { var scrollView: UIScrollView! var image: UIImage! var commentTextField: UITextField! var photoFile: PFFile? var thumbnailFile: PFFile? var fileUploadBackgroundTaskId: UIBackgroundTaskIdentifier! var photoPostBackgroundTaskId: UIBackgroundTaskIdentifier! // MARK:- NSObject deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } init(image aImage: UIImage) { super.init(nibName: nil, bundle: nil) self.image = aImage self.fileUploadBackgroundTaskId = UIBackgroundTaskInvalid self.photoPostBackgroundTaskId = UIBackgroundTaskInvalid } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- UIViewController override func loadView() { self.scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds) self.scrollView.delegate = self self.scrollView.backgroundColor = UIColor.blackColor() self.view = self.scrollView let photoImageView = UIImageView(frame: CGRectMake(0.0, 42.0, 320.0, 320.0)) photoImageView.backgroundColor = UIColor.blackColor() photoImageView.image = self.image photoImageView.contentMode = UIViewContentMode.ScaleAspectFit self.scrollView.addSubview(photoImageView) var footerRect: CGRect = PAPPhotoDetailsFooterView.rectForView() footerRect.origin.y = photoImageView.frame.origin.y + photoImageView.frame.size.height let footerView = PAPPhotoDetailsFooterView(frame: footerRect) self.commentTextField = footerView.commentField self.commentTextField!.delegate = self self.scrollView!.addSubview(footerView) self.scrollView!.contentSize = CGSizeMake(self.scrollView.bounds.size.width, photoImageView.frame.origin.y + photoImageView.frame.size.height + footerView.frame.size.height) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.hidesBackButton = true self.navigationItem.titleView = UIImageView(image: UIImage(named: "LogoNavigationBar.png")) self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PAPEditPhotoViewController.cancelButtonAction(_:))) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Publish", style: UIBarButtonItemStyle.Done, target: self, action: #selector(PAPEditPhotoViewController.doneButtonAction(_:))) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PAPEditPhotoViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PAPEditPhotoViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) self.shouldUploadImage(self.image) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. print("Memory warning on Edit") } // MARK:- UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { self.doneButtonAction(textField) textField.resignFirstResponder() return true } // MARK:- UIScrollViewDelegate func scrollViewWillBeginDragging(scrollView: UIScrollView) { self.commentTextField.resignFirstResponder() } // MARK:- () func shouldUploadImage(anImage: UIImage) -> Bool { let resizedImage: UIImage = anImage.resizedImageWithContentMode(UIViewContentMode.ScaleAspectFit, bounds: CGSizeMake(560.0, 560.0), interpolationQuality: CGInterpolationQuality.High) let thumbnailImage: UIImage = anImage.thumbnailImage(86, transparentBorder: 0, cornerRadius: 10, interpolationQuality: CGInterpolationQuality.Default) // JPEG to decrease file size and enable faster uploads & downloads guard let imageData: NSData = UIImageJPEGRepresentation(resizedImage, 0.8) else { return false } guard let thumbnailImageData: NSData = UIImagePNGRepresentation(thumbnailImage) else { return false } self.photoFile = PFFile(data: imageData) self.thumbnailFile = PFFile(data: thumbnailImageData) // Request a background execution task to allow us to finish uploading the photo even if the app is backgrounded self.fileUploadBackgroundTaskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { UIApplication.sharedApplication().endBackgroundTask(self.fileUploadBackgroundTaskId) } print("Requested background expiration task with id \(self.fileUploadBackgroundTaskId) for Anypic photo upload") self.photoFile!.saveInBackgroundWithBlock { (succeeded, error) in if (succeeded) { print("Photo uploaded successfully") self.thumbnailFile!.saveInBackgroundWithBlock { (succeeded, error) in if (succeeded) { print("Thumbnail uploaded successfully") } UIApplication.sharedApplication().endBackgroundTask(self.fileUploadBackgroundTaskId) } } else { UIApplication.sharedApplication().endBackgroundTask(self.fileUploadBackgroundTaskId) } } return true } func keyboardWillShow(note: NSNotification) { let keyboardFrameEnd: CGRect = (note.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue() var scrollViewContentSize: CGSize = self.scrollView.bounds.size scrollViewContentSize.height += keyboardFrameEnd.size.height self.scrollView.contentSize = scrollViewContentSize var scrollViewContentOffset: CGPoint = self.scrollView.contentOffset // Align the bottom edge of the photo with the keyboard scrollViewContentOffset.y = scrollViewContentOffset.y + keyboardFrameEnd.size.height*3.0 - UIScreen.mainScreen().bounds.size.height self.scrollView.setContentOffset(scrollViewContentOffset, animated: true) } func keyboardWillHide(note: NSNotification) { let keyboardFrameEnd: CGRect = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() var scrollViewContentSize: CGSize = self.scrollView.bounds.size scrollViewContentSize.height -= keyboardFrameEnd.size.height UIView.animateWithDuration(0.200, animations: { self.scrollView.contentSize = scrollViewContentSize }) } func doneButtonAction(sender: AnyObject) { var userInfo: [String: String]? let trimmedComment: String = self.commentTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) if (trimmedComment.length != 0) { userInfo = [kPAPEditPhotoViewControllerUserInfoCommentKey: trimmedComment] } if self.photoFile == nil || self.thumbnailFile == nil { let alertController = UIAlertController(title: NSLocalizedString("Couldn't post your photo", comment: ""), message: nil, preferredStyle: UIAlertControllerStyle.Alert) let alertAction = UIAlertAction(title: NSLocalizedString("Dismiss", comment: ""), style: UIAlertActionStyle.Cancel, handler: nil) alertController.addAction(alertAction) presentViewController(alertController, animated: true, completion: nil) return } // both files have finished uploading // create a photo object let photo = PFObject(className: kPAPPhotoClassKey) photo.setObject(PFUser.currentUser()!, forKey: kPAPPhotoUserKey) photo.setObject(self.photoFile!, forKey: kPAPPhotoPictureKey) photo.setObject(self.thumbnailFile!, forKey: kPAPPhotoThumbnailKey) // photos are public, but may only be modified by the user who uploaded them let photoACL = PFACL(user: PFUser.currentUser()!) photoACL.setPublicReadAccess(true) photo.ACL = photoACL // Request a background execution task to allow us to finish uploading the photo even if the app is backgrounded self.photoPostBackgroundTaskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { UIApplication.sharedApplication().endBackgroundTask(self.photoPostBackgroundTaskId) } // save photo.saveInBackgroundWithBlock { (succeeded, error) in if succeeded { print("Photo uploaded") PAPCache.sharedCache.setAttributesForPhoto(photo, likers: [PFUser](), commenters: [PFUser](), likedByCurrentUser: false) // userInfo might contain any caption which might have been posted by the uploader if let userInfo = userInfo { let commentText = userInfo[kPAPEditPhotoViewControllerUserInfoCommentKey] if commentText != nil && commentText!.length != 0 { // create and save photo caption let comment = PFObject(className: kPAPActivityClassKey) comment.setObject(kPAPActivityTypeComment, forKey: kPAPActivityTypeKey) comment.setObject(photo, forKey:kPAPActivityPhotoKey) comment.setObject(PFUser.currentUser()!, forKey: kPAPActivityFromUserKey) comment.setObject(PFUser.currentUser()!, forKey: kPAPActivityToUserKey) comment.setObject(commentText!, forKey: kPAPActivityContentKey) let ACL = PFACL(user: PFUser.currentUser()!) ACL.setPublicReadAccess(true) comment.ACL = ACL comment.saveEventually() PAPCache.sharedCache.incrementCommentCountForPhoto(photo) } } NSNotificationCenter.defaultCenter().postNotificationName(PAPTabBarControllerDidFinishEditingPhotoNotification, object: photo) } else { print("Photo failed to save: \(error)") let alertController = UIAlertController(title: NSLocalizedString("Couldn't post your photo", comment: ""), message: nil, preferredStyle: UIAlertControllerStyle.Alert) let alertAction = UIAlertAction(title: NSLocalizedString("Dismiss", comment: ""), style: UIAlertActionStyle.Cancel, handler: nil) alertController.addAction(alertAction) self.presentViewController(alertController, animated: true, completion: nil) } UIApplication.sharedApplication().endBackgroundTask(self.photoPostBackgroundTaskId) } self.parentViewController!.dismissViewControllerAnimated(true, completion: nil) } func cancelButtonAction(sender: AnyObject) { self.parentViewController!.dismissViewControllerAnimated(true, completion: nil) } }
cc0-1.0
91986e31c4f209127afc515af3e60032
49.929825
199
0.681709
5.829317
false
false
false
false
midjuly/cordova-plugin-iosrtc
src/PluginRTCPeerConnectionConstraints.swift
1
1393
import Foundation class PluginRTCPeerConnectionConstraints { private var constraints: RTCMediaConstraints init(pcConstraints: NSDictionary?) { NSLog("PluginRTCPeerConnectionConstraints#init()") if pcConstraints == nil { self.constraints = RTCMediaConstraints() return } var offerToReceiveAudio = pcConstraints?.objectForKey("offerToReceiveAudio") as? Bool var offerToReceiveVideo = pcConstraints?.objectForKey("offerToReceiveVideo") as? Bool if offerToReceiveAudio == nil && offerToReceiveVideo == nil { self.constraints = RTCMediaConstraints() return } if offerToReceiveAudio == nil { offerToReceiveAudio = false } if offerToReceiveVideo == nil { offerToReceiveVideo = false } NSLog("PluginRTCPeerConnectionConstraints#init() | [offerToReceiveAudio:\(offerToReceiveAudio!) | offerToReceiveVideo:\(offerToReceiveVideo!)]") self.constraints = RTCMediaConstraints( mandatoryConstraints: [ RTCPair(key: "OfferToReceiveAudio", value: offerToReceiveAudio == true ? "true" : "false"), RTCPair(key: "OfferToReceiveVideo", value: offerToReceiveVideo == true ? "true" : "false") ], optionalConstraints: [] ) } deinit { NSLog("PluginRTCPeerConnectionConstraints#deinit()") } func getConstraints() -> RTCMediaConstraints { NSLog("PluginRTCPeerConnectionConstraints#getConstraints()") return self.constraints } }
mit
1a66a83a776079c319df5e09363349c1
24.796296
146
0.744436
3.869444
false
false
false
false
kstaring/swift
test/type/array.swift
7
1138
// RUN: %target-parse-verify-swift // Array types. class Base1 { func f0(_ x: [Int]) { } func f0a(_ x: [Int]?) { } func f1(_ x: [[Int]]) { } func f1a(_ x: [[Int]]?) { } func f2(_ x: [([Int]) -> [Int]]) { } func f2a(_ x: [([Int]?) -> [Int]?]?) { } } class Derived1 : Base1 { override func f0(_ x: Array<Int>) { } override func f0a(_ x: Optional<Array<Int>>) { } override func f1(_ x: Array<Array<Int>>) { } override func f1a(_ x: Optional<Array<Array<Int>>>) { } override func f2(_ x: Array<(Array<Int>) -> Array<Int>>) { } override func f2a(_ x: Optional<Array<(Optional<Array<Int>>) -> Optional<Array<Int>>>>) { } } // Array types in generic specializations. struct X<T> { } func testGenericSpec() { _ = X<[Int]>() } // Array types for construction. func constructArray(_ n: Int) { var ones = [Int](repeating: 1, count: n) ones[5] = 0 var matrix = [[Float]]() matrix[1][2] = 3.14159 var _: [Int?] = [Int?]() } // Fix-Its from the old syntax to the new. typealias FixIt0 = Int[] // expected-error{{array types are now written with the brackets around the element type}}{{20-20=[}}{{23-24=}}
apache-2.0
b5cd2bd9ddd4b4b4feead6db105ba968
24.863636
136
0.577329
2.917949
false
false
false
false